# Copyright 2013-2020 Lawrence Livermore National Security, LLC and otherNEWLINE# Spack Project Developers. See the top-level COPYRIGHT file for details.NEWLINE#NEWLINE# SPDX-License-Identifier: (Apache-2.0 OR MIT)NEWLINENEWLINEfrom spack import *NEWLINENEWLINENEWLINEclass RCdcfluview(RPackage):NEWLINE """The 'U.S.' Centers for Disease Control ('CDC') maintains a portalNEWLINE for accessingNEWLINE state, regional and national influenza statistics as well as MortalityNEWLINE Surveillance Data. The web interface makes it difficult and time-consumingNEWLINE to select and retrieve influenza data. Tools are provided to access theNEWLINE data provided by the portal's underlying 'API'."""NEWLINENEWLINE homepage = "https://cloud.r-project.org/package=cdcfluview"NEWLINE url = "https://cloud.r-project.org/src/contrib/cdcfluview_0.7.0.tar.gz"NEWLINE list_url = "https://cloud.r-project.org/src/contrib/Archive/cdcfluview"NEWLINENEWLINE version('0.9.0', sha256='1b2064886858cbb1790ef808d88fbab75d3a9cf55e720638221a3377ff8dd244')NEWLINE version('0.7.0', sha256='8c8978d081f8472a6ed5ec54c4e6dd906f97ee28d0f88eef1514088f041ecc03')NEWLINENEWLINE depends_on('r@3.2.0:', type=('build', 'run'))NEWLINE depends_on('r-httr', type=('build', 'run'))NEWLINE depends_on('r-dplyr', type=('build', 'run'))NEWLINE depends_on('r-jsonlite', type=('build', 'run'))NEWLINE depends_on('r-sf', type=('build', 'run'))NEWLINE depends_on('r-xml2', type=('build', 'run'))NEWLINE depends_on('r-purrr', type=('build', 'run'))NEWLINE depends_on('r-readr', type=('build', 'run'))NEWLINE depends_on('r-mmwrweek', type=('build', 'run'))NEWLINE depends_on('r-units@0.4-6:', type=('build', 'run'))NEWLINE import importlibNEWLINEimport pkgutilNEWLINENEWLINEfrom pkg_resources import get_distribution, DistributionNotFoundNEWLINENEWLINENEWLINEdef get_package_version():NEWLINE """Get package versionNEWLINENEWLINE Returns:NEWLINE str: Installed package version, or 0.0.0.dev if not fully installedNEWLINE """NEWLINE try:NEWLINE return get_distribution(__name__.split('.')[0]).versionNEWLINE except DistributionNotFound:NEWLINE return '0.0.0.dev'NEWLINENEWLINENEWLINEdef get_file_extension(filepath):NEWLINE """Return full file extension from filepath"""NEWLINE filename = filepath.split('/')[-1]NEWLINENEWLINE return filename[filename.index('.'):]NEWLINENEWLINENEWLINEdef get_full_qualname(cls):NEWLINE """Return fully qualified class name"""NEWLINE return cls.__module__ + '.' + cls.__name__NEWLINENEWLINENEWLINEdef get_recursive_subclasses(cls):NEWLINE """Return list of all subclasses for a class, including subclasses of direct subclasses"""NEWLINE return cls.__subclasses__() + [g for s in cls.__subclasses__() for g in get_recursive_subclasses(s)]NEWLINENEWLINENEWLINEdef import_submodules(package):NEWLINE """Return list of imported module instances from beneath root_package"""NEWLINENEWLINE if isinstance(package, str):NEWLINE package = importlib.import_module(package)NEWLINENEWLINE results = {}NEWLINENEWLINE if hasattr(package, '__path__'):NEWLINE for _, name, is_pkg in pkgutil.walk_packages(package.__path__):NEWLINE full_name = package.__name__ + '.' + nameNEWLINE try:NEWLINE results[full_name] = importlib.import_module(full_name)NEWLINENEWLINE if is_pkg:NEWLINE results.update(import_submodules(full_name))NEWLINE except ImportError:NEWLINE # Ignore import failures for now; Quickest fix to support contrib serializers as extras with just depsNEWLINE continueNEWLINENEWLINE return resultsNEWLINE import osNEWLINEimport clickNEWLINENEWLINEdef register(app):NEWLINE @app.cli.group()NEWLINE def translate():NEWLINE """translation and localization"""NEWLINE passNEWLINENEWLINE @translate.command()NEWLINE def update():NEWLINE """Update all languages."""NEWLINE if os.system('pybabel extract -F babel.cfg -k _l -o messages.pot .'):NEWLINE raise RuntimeError('extract command failed')NEWLINE if os.system('pybabel update -i messages.pot -d app/translations'):NEWLINE raise RuntimeError('update command failed')NEWLINE os.remove('messages.pot')NEWLINENEWLINENEWLINE @translate.command()NEWLINE def compile():NEWLINE """Compile all languages."""NEWLINE if os.system('pybabel compile -d app/translations'):NEWLINE raise RuntimeError('compile command failed')NEWLINENEWLINENEWLINENEWLINE @translate.command()NEWLINE @click.argument('lang')NEWLINE def init(lang):NEWLINE """Initialize a new language."""NEWLINE if os.system('pybabel extract -F babel.cfg -k _l -o messages.pot .'):NEWLINE raise RuntimeError('extract command failed')NEWLINE if os.system(NEWLINE 'pybabel init -i messages.pot -d app/translations -l ' + lang):NEWLINE raise RuntimeError('init command failed')NEWLINE os.remove('messages.pot')NEWLINE ##############################################################################NEWLINE#NEWLINE# Copyright (c) 2001, 2002, 2009 Zope Foundation and Contributors.NEWLINE# All Rights Reserved.NEWLINE#NEWLINE# This software is subject to the provisions of the Zope Public License,NEWLINE# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.NEWLINE# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIEDNEWLINE# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDNEWLINE# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESSNEWLINE# FOR A PARTICULAR PURPOSE.NEWLINE#NEWLINE##############################################################################NEWLINE"""Examples supporting Sphinx doctest snippets.NEWLINE"""NEWLINEimport sysNEWLINENEWLINEfrom zope.interface import InterfaceNEWLINEfrom zope.interface import implementerNEWLINEfrom zope.interface.interfaces import IInterfaceNEWLINENEWLINEfrom zope.component._declaration import adapterNEWLINEfrom zope.component.testfiles.views import ICNEWLINENEWLINEdef write(x):NEWLINE sys.stdout.write('%s\n' % x)NEWLINENEWLINEclass ITestType(IInterface):NEWLINE passNEWLINENEWLINENEWLINEclass I1(Interface):NEWLINE passNEWLINENEWLINEclass I2(Interface):NEWLINE passNEWLINENEWLINEclass I3(Interface):NEWLINE passNEWLINENEWLINEclass I4(Interface):NEWLINE passNEWLINENEWLINEclass IGI(Interface):NEWLINE passNEWLINENEWLINEclass IQI(Interface):NEWLINE passNEWLINENEWLINEclass ISI(Interface):NEWLINE passNEWLINENEWLINEclass ISII(Interface):NEWLINE passNEWLINENEWLINEclass U(object):NEWLINENEWLINE def __init__(self, name):NEWLINE self.__name__ = nameNEWLINENEWLINE def __repr__(self):NEWLINE return "%s(%s)" % (self.__class__.__name__, self.__name__)NEWLINENEWLINE@implementer(I1)NEWLINEclass U1(U):NEWLINE passNEWLINENEWLINE@implementer(I1, I2)NEWLINEclass U12(U):NEWLINE passNEWLINENEWLINE@adapter(I1)NEWLINEdef handle1(x):NEWLINE write('handle1 %s' % x)NEWLINENEWLINEdef handle2(*objects):NEWLINE write( 'handle2 ' + repr(objects))NEWLINENEWLINE@adapter(I1)NEWLINEdef handle3(x):NEWLINE write( 'handle3 %s' % x)NEWLINENEWLINE@adapter(I1)NEWLINEdef handle4(x):NEWLINE write( 'handle4 %s' % x)NEWLINENEWLINEclass GlobalRegistry:NEWLINE passNEWLINENEWLINEfrom zope.component.globalregistry import GlobalAdapterRegistryNEWLINEbase = GlobalAdapterRegistry(GlobalRegistry, 'adapters')NEWLINEGlobalRegistry.adapters = baseNEWLINEdef clear_base():NEWLINE base.__init__(GlobalRegistry, 'adapters')NEWLINENEWLINENEWLINE@implementer(I1)NEWLINEclass Ob(object):NEWLINE def __repr__(self):NEWLINE return ''NEWLINENEWLINENEWLINEob = Ob()NEWLINENEWLINE@implementer(I2)NEWLINEclass Ob2(object):NEWLINE def __repr__(self):NEWLINE return ''NEWLINENEWLINE@implementer(IC)NEWLINEclass Ob3(object):NEWLINE passNEWLINENEWLINE@implementer(I2)NEWLINEclass Comp(object):NEWLINE def __init__(self, context):NEWLINE self.context = contextNEWLINENEWLINEcomp = Comp(1)NEWLINENEWLINENEWLINEclass ConformsToIComponentLookup(object):NEWLINE """Allow a dummy sitemanager to conform/adapt to `IComponentLookup`."""NEWLINENEWLINE def __init__(self, sitemanager):NEWLINE self.sitemanager = sitemanagerNEWLINENEWLINE def __conform__(self, interface):NEWLINE """This method is specified by the adapter PEP to do the adaptation."""NEWLINE from zope.interface.interfaces import IComponentLookupNEWLINE if interface is IComponentLookup:NEWLINE return self.sitemanagerNEWLINENEWLINENEWLINEdef clearZCML(test=None):NEWLINE from zope.configuration.xmlconfig import XMLConfigNEWLINE import zope.componentNEWLINE from zope.component.testing import setUpNEWLINE from zope.component.testing import tearDownNEWLINE tearDown()NEWLINE setUp()NEWLINE XMLConfig('meta.zcml', zope.component)()NEWLINE """NEWLINE OpenVINO DL WorkbenchNEWLINE Dataset annotator moduleNEWLINENEWLINE Copyright (c) 2021 Intel CorporationNEWLINENEWLINE Licensed under the Apache License, Version 2.0 (the "License");NEWLINE you may not use this file except in compliance with the License.NEWLINE You may obtain a copy of the License atNEWLINE http://www.apache.org/licenses/LICENSE-2.0NEWLINE Unless required by applicable law or agreed to in writing, softwareNEWLINE distributed under the License is distributed on an "AS IS" BASIS,NEWLINE WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE See the License for the specific language governing permissions andNEWLINE limitations under the License.NEWLINE"""NEWLINEfrom wb.main.scripts.dataset_annotator.dataset_annotator import DatasetAnnotatorNEWLINEfrom wb.main.scripts.dataset_annotator.task_to_auto_annotated_dataset_type_mapper import \NEWLINE TaskToAutoAnnotatedDatasetTypeMapperNEWLINE # Copyright 2020 The TensorFlow Authors. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE# ==============================================================================NEWLINE"""Tests for Keras text category_encoding preprocessing layer."""NEWLINENEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import print_functionNEWLINENEWLINENEWLINEfrom absl.testing import parameterizedNEWLINEimport numpy as npNEWLINENEWLINEfrom tensorflow.python import kerasNEWLINENEWLINEfrom tensorflow.python.data.ops import dataset_opsNEWLINEfrom tensorflow.python.eager import contextNEWLINEfrom tensorflow.python.framework import constant_opNEWLINEfrom tensorflow.python.framework import dtypesNEWLINEfrom tensorflow.python.framework import errorsNEWLINEfrom tensorflow.python.framework import sparse_tensorNEWLINEfrom tensorflow.python.keras import backendNEWLINEfrom tensorflow.python.keras import keras_parameterizedNEWLINEfrom tensorflow.python.keras.layers import coreNEWLINEfrom tensorflow.python.keras.layers.preprocessing import category_encodingNEWLINEfrom tensorflow.python.keras.layers.preprocessing import category_encoding_v1NEWLINEfrom tensorflow.python.keras.layers.preprocessing import preprocessing_test_utilsNEWLINEfrom tensorflow.python.ops import sparse_opsNEWLINEfrom tensorflow.python.ops.ragged import ragged_factory_opsNEWLINEfrom tensorflow.python.platform import testNEWLINENEWLINENEWLINEdef get_layer_class():NEWLINE if context.executing_eagerly():NEWLINE return category_encoding.CategoryEncodingNEWLINE else:NEWLINE return category_encoding_v1.CategoryEncodingNEWLINENEWLINENEWLINE@keras_parameterized.run_all_keras_modes(always_skip_v1=True)NEWLINEclass CategoryEncodingInputTest(keras_parameterized.TestCase,NEWLINE preprocessing_test_utils.PreprocessingLayerTestNEWLINE ):NEWLINENEWLINE def test_dense_input_sparse_output(self):NEWLINE input_array = constant_op.constant([[1, 2, 3], [3, 3, 0]])NEWLINENEWLINE # The expected output should be (X for missing value):NEWLINE # [[X, 1, 1, 1]NEWLINE # [1, X, X, X]NEWLINE # [X, X, X, 2]]NEWLINE expected_indices = [[0, 1], [0, 2], [0, 3], [1, 0], [1, 3]]NEWLINE expected_values = [1, 1, 1, 1, 2]NEWLINE max_tokens = 6NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32)NEWLINE layer = get_layer_class()(NEWLINE max_tokens=max_tokens, output_mode=category_encoding.COUNT, sparse=True)NEWLINE int_data = layer(input_data)NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE sp_output_dataset = model.predict(input_array, steps=1)NEWLINE self.assertAllEqual(expected_values, sp_output_dataset.values)NEWLINE self.assertAllEqual(expected_indices, sp_output_dataset.indices)NEWLINENEWLINE # Assert sparse output is same as dense output.NEWLINE layer = get_layer_class()(NEWLINE max_tokens=max_tokens,NEWLINE output_mode=category_encoding.COUNT,NEWLINE sparse=False)NEWLINE int_data = layer(input_data)NEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(input_array, steps=1)NEWLINE self.assertAllEqual(NEWLINE sparse_ops.sparse_tensor_to_dense(sp_output_dataset, default_value=0),NEWLINE output_dataset)NEWLINENEWLINE def test_sparse_input(self):NEWLINE input_array = np.array([[1, 2, 3, 0], [0, 3, 1, 0]], dtype=np.int64)NEWLINE sparse_tensor_data = sparse_ops.from_dense(input_array)NEWLINENEWLINE # pyformat: disableNEWLINE expected_output = [[0, 1, 1, 1, 0, 0],NEWLINE [0, 1, 0, 1, 0, 0]]NEWLINE # pyformat: enableNEWLINE max_tokens = 6NEWLINE expected_output_shape = [None, max_tokens]NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)NEWLINENEWLINE layer = get_layer_class()(NEWLINE max_tokens=max_tokens, output_mode=category_encoding.BINARY)NEWLINE int_data = layer(input_data)NEWLINE self.assertAllEqual(expected_output_shape, int_data.shape.as_list())NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(sparse_tensor_data, steps=1)NEWLINE self.assertAllEqual(expected_output, output_dataset)NEWLINENEWLINE def test_sparse_input_with_weights(self):NEWLINE input_array = np.array([[1, 2, 3, 4], [4, 3, 1, 4]], dtype=np.int64)NEWLINE weights_array = np.array([[.1, .2, .3, .4], [.2, .1, .4, .3]])NEWLINE sparse_tensor_data = sparse_ops.from_dense(input_array)NEWLINE sparse_weight_data = sparse_ops.from_dense(weights_array)NEWLINENEWLINE # pyformat: disableNEWLINE expected_output = [[0, .1, .2, .3, .4, 0],NEWLINE [0, .4, 0, .1, .5, 0]]NEWLINE # pyformat: enableNEWLINE max_tokens = 6NEWLINE expected_output_shape = [None, max_tokens]NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)NEWLINE weight_data = keras.Input(shape=(None,), dtype=dtypes.float32, sparse=True)NEWLINENEWLINE layer = get_layer_class()(NEWLINE max_tokens=max_tokens, output_mode=category_encoding.COUNT)NEWLINE int_data = layer(input_data, count_weights=weight_data)NEWLINE self.assertAllEqual(expected_output_shape, int_data.shape.as_list())NEWLINENEWLINE model = keras.Model(inputs=[input_data, weight_data], outputs=int_data)NEWLINE output_dataset = model.predict([sparse_tensor_data, sparse_weight_data],NEWLINE steps=1)NEWLINE self.assertAllClose(expected_output, output_dataset)NEWLINENEWLINE def test_sparse_input_sparse_output(self):NEWLINE sp_inp = sparse_tensor.SparseTensor(NEWLINE indices=[[0, 0], [1, 1], [2, 0], [2, 1], [3, 1]],NEWLINE values=[0, 2, 1, 1, 0],NEWLINE dense_shape=[4, 2])NEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)NEWLINENEWLINE # The expected output should be (X for missing value):NEWLINE # [[1, X, X, X]NEWLINE # [X, X, 1, X]NEWLINE # [X, 2, X, X]NEWLINE # [1, X, X, X]]NEWLINE expected_indices = [[0, 0], [1, 2], [2, 1], [3, 0]]NEWLINE expected_values = [1, 1, 2, 1]NEWLINE max_tokens = 6NEWLINENEWLINE layer = get_layer_class()(NEWLINE max_tokens=max_tokens, output_mode=category_encoding.COUNT, sparse=True)NEWLINE int_data = layer(input_data)NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE sp_output_dataset = model.predict(sp_inp, steps=1)NEWLINE self.assertAllEqual(expected_values, sp_output_dataset.values)NEWLINE self.assertAllEqual(expected_indices, sp_output_dataset.indices)NEWLINENEWLINE # Assert sparse output is same as dense output.NEWLINE layer = get_layer_class()(NEWLINE max_tokens=max_tokens,NEWLINE output_mode=category_encoding.COUNT,NEWLINE sparse=False)NEWLINE int_data = layer(input_data)NEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(sp_inp, steps=1)NEWLINE self.assertAllEqual(NEWLINE sparse_ops.sparse_tensor_to_dense(sp_output_dataset, default_value=0),NEWLINE output_dataset)NEWLINENEWLINE def test_sparse_input_sparse_output_with_weights(self):NEWLINE indices = [[0, 0], [1, 1], [2, 0], [2, 1], [3, 1]]NEWLINE sp_inp = sparse_tensor.SparseTensor(NEWLINE indices=indices, values=[0, 2, 1, 1, 0], dense_shape=[4, 2])NEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)NEWLINE sp_weight = sparse_tensor.SparseTensor(NEWLINE indices=indices, values=[.1, .2, .4, .3, .2], dense_shape=[4, 2])NEWLINE weight_data = keras.Input(shape=(None,), dtype=dtypes.float32, sparse=True)NEWLINENEWLINE # The expected output should be (X for missing value):NEWLINE # [[1, X, X, X]NEWLINE # [X, X, 1, X]NEWLINE # [X, 2, X, X]NEWLINE # [1, X, X, X]]NEWLINE expected_indices = [[0, 0], [1, 2], [2, 1], [3, 0]]NEWLINE expected_values = [.1, .2, .7, .2]NEWLINE max_tokens = 6NEWLINENEWLINE layer = get_layer_class()(NEWLINE max_tokens=max_tokens, output_mode=category_encoding.COUNT, sparse=True)NEWLINE int_data = layer(input_data, count_weights=weight_data)NEWLINENEWLINE model = keras.Model(inputs=[input_data, weight_data], outputs=int_data)NEWLINE sp_output_dataset = model.predict([sp_inp, sp_weight], steps=1)NEWLINE self.assertAllClose(expected_values, sp_output_dataset.values)NEWLINE self.assertAllEqual(expected_indices, sp_output_dataset.indices)NEWLINENEWLINE def test_ragged_input(self):NEWLINE input_array = ragged_factory_ops.constant([[1, 2, 3], [3, 1]])NEWLINENEWLINE # pyformat: disableNEWLINE expected_output = [[0, 1, 1, 1, 0, 0],NEWLINE [0, 1, 0, 1, 0, 0]]NEWLINE # pyformat: enableNEWLINE max_tokens = 6NEWLINE expected_output_shape = [None, max_tokens]NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32, ragged=True)NEWLINENEWLINE layer = get_layer_class()(NEWLINE max_tokens=max_tokens, output_mode=category_encoding.BINARY)NEWLINE int_data = layer(input_data)NEWLINENEWLINE self.assertAllEqual(expected_output_shape, int_data.shape.as_list())NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(input_array, steps=1)NEWLINE self.assertAllEqual(expected_output, output_dataset)NEWLINENEWLINE def test_ragged_input_sparse_output(self):NEWLINE input_array = ragged_factory_ops.constant([[1, 2, 3], [3, 3]])NEWLINENEWLINE # The expected output should be (X for missing value):NEWLINE # [[X, 1, 1, 1]NEWLINE # [X, X, X, 2]]NEWLINE expected_indices = [[0, 1], [0, 2], [0, 3], [1, 3]]NEWLINE expected_values = [1, 1, 1, 2]NEWLINE max_tokens = 6NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32, ragged=True)NEWLINE layer = get_layer_class()(NEWLINE max_tokens=max_tokens, output_mode=category_encoding.COUNT, sparse=True)NEWLINE int_data = layer(input_data)NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE sp_output_dataset = model.predict(input_array, steps=1)NEWLINE self.assertAllEqual(expected_values, sp_output_dataset.values)NEWLINE self.assertAllEqual(expected_indices, sp_output_dataset.indices)NEWLINENEWLINE # Assert sparse output is same as dense output.NEWLINE layer = get_layer_class()(NEWLINE max_tokens=max_tokens,NEWLINE output_mode=category_encoding.COUNT,NEWLINE sparse=False)NEWLINE int_data = layer(input_data)NEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(input_array, steps=1)NEWLINE self.assertAllEqual(NEWLINE sparse_ops.sparse_tensor_to_dense(sp_output_dataset, default_value=0),NEWLINE output_dataset)NEWLINENEWLINE def test_sparse_output_and_dense_layer(self):NEWLINE input_array = constant_op.constant([[1, 2, 3], [3, 3, 0]])NEWLINENEWLINE max_tokens = 4NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32)NEWLINE encoding_layer = get_layer_class()(NEWLINE max_tokens=max_tokens, output_mode=category_encoding.COUNT,NEWLINE sparse=True)NEWLINE int_data = encoding_layer(input_data)NEWLINE dense_layer = keras.layers.Dense(units=1)NEWLINE output_data = dense_layer(int_data)NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=output_data)NEWLINE _ = model.predict(input_array, steps=1)NEWLINENEWLINE def test_dense_oov_input(self):NEWLINE input_array = constant_op.constant([[1, 2, 3], [4, 3, 4]])NEWLINE max_tokens = 3NEWLINE expected_output_shape = [None, max_tokens]NEWLINE encoder_layer = get_layer_class()(max_tokens)NEWLINE input_data = keras.Input(shape=(3,), dtype=dtypes.int32)NEWLINE int_data = encoder_layer(input_data)NEWLINE self.assertAllEqual(expected_output_shape, int_data.shape.as_list())NEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE with self.assertRaisesRegex(errors.InvalidArgumentError,NEWLINE ".*must be less than max_token 3"):NEWLINE _ = model.predict(input_array, steps=1)NEWLINENEWLINENEWLINE@keras_parameterized.run_all_keras_modesNEWLINEclass CategoryEncodingAdaptTest(keras_parameterized.TestCase,NEWLINE preprocessing_test_utils.PreprocessingLayerTestNEWLINE ):NEWLINENEWLINE def test_sparse_adapt(self):NEWLINE vocab_data = sparse_ops.from_dense(NEWLINE np.array([[1, 1, 0, 1, 1, 2, 2, 0, 2, 3, 3, 0, 4]], dtype=np.int64))NEWLINE vocab_dataset = dataset_ops.Dataset.from_tensors(vocab_data)NEWLINE input_array = sparse_ops.from_dense(NEWLINE np.array([[1, 2, 3, 0], [0, 3, 1, 0]], dtype=np.int64))NEWLINENEWLINE # pyformat: disableNEWLINE expected_output = [[0, 1, 1, 1, 0],NEWLINE [0, 1, 0, 1, 0]]NEWLINE # pyformat: enableNEWLINE max_tokens = 5NEWLINE expected_output_shape = [None, max_tokens]NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)NEWLINE layer = get_layer_class()(NEWLINE max_tokens=None, output_mode=category_encoding.BINARY)NEWLINE layer.adapt(vocab_dataset)NEWLINE int_data = layer(input_data)NEWLINE self.assertAllEqual(expected_output_shape, int_data.shape.as_list())NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(input_array, steps=1)NEWLINE self.assertAllEqual(expected_output, output_dataset)NEWLINENEWLINE def test_ragged_adapt(self):NEWLINE vocab_data = ragged_factory_ops.constant(NEWLINE np.array([[1, 1, 0, 1, 1], [2, 2], [0, 2, 3], [0, 4]]))NEWLINE vocab_dataset = dataset_ops.Dataset.from_tensors(vocab_data)NEWLINE input_array = ragged_factory_ops.constant([[1, 2, 3], [3, 1]])NEWLINENEWLINE # pyformat: disableNEWLINE expected_output = [[0, 1, 1, 1, 0],NEWLINE [0, 1, 0, 1, 0]]NEWLINE # pyformat: enableNEWLINE max_tokens = 5NEWLINE expected_output_shape = [None, max_tokens]NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32, ragged=True)NEWLINENEWLINE layer = get_layer_class()(NEWLINE max_tokens=None, output_mode=category_encoding.BINARY)NEWLINE layer.adapt(vocab_dataset)NEWLINE int_data = layer(input_data)NEWLINENEWLINE self.assertAllEqual(expected_output_shape, int_data.shape.as_list())NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(input_array, steps=1)NEWLINE self.assertAllEqual(expected_output, output_dataset)NEWLINENEWLINE def test_hard_maximum_set_state_variables_after_build(self):NEWLINE state_variables = {category_encoding._NUM_ELEMENTS_NAME: 5}NEWLINE input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])NEWLINENEWLINE # pyformat: disableNEWLINE expected_output = [[0, 1, 1, 1, 0],NEWLINE [1, 1, 0, 1, 0]]NEWLINE # pyformat: enableNEWLINE max_tokens = 5NEWLINE expected_output_shape = [None, max_tokens]NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32)NEWLINE layer = get_layer_class()(NEWLINE max_tokens=max_tokens, output_mode=category_encoding.BINARY)NEWLINE int_data = layer(input_data)NEWLINE layer._set_state_variables(state_variables)NEWLINE self.assertAllEqual(expected_output_shape, int_data.shape.as_list())NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(input_array)NEWLINE self.assertAllEqual(expected_output, output_dataset)NEWLINENEWLINE def test_soft_maximum_set_state_after_build(self):NEWLINE input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])NEWLINENEWLINE # pyformat: disableNEWLINE expected_output = [[0, 1, 1, 1, 0],NEWLINE [1, 1, 0, 1, 0]]NEWLINE # pyformat: enableNEWLINE max_tokens = 5NEWLINE expected_output_shape = [None, max_tokens]NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32)NEWLINE layer = get_layer_class()(NEWLINE max_tokens=None, output_mode=category_encoding.BINARY)NEWLINE layer.build(input_data.shape)NEWLINE layer.set_num_elements(max_tokens)NEWLINE int_data = layer(input_data)NEWLINE self.assertAllEqual(expected_output_shape, int_data.shape.as_list())NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(input_array)NEWLINE self.assertAllEqual(expected_output, output_dataset)NEWLINENEWLINE def test_set_weights_fails_on_wrong_size_weights(self):NEWLINE tfidf_data = [.05, .5, .25, .2, .125]NEWLINE layer = get_layer_class()(max_tokens=6, output_mode=category_encoding.TFIDF)NEWLINENEWLINE with self.assertRaisesRegex(ValueError, ".*Layer weight shape.*"):NEWLINE layer.set_weights([np.array(tfidf_data)])NEWLINENEWLINE def test_set_num_elements_after_call_fails(self):NEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32)NEWLINE layer = get_layer_class()(NEWLINE max_tokens=None, output_mode=category_encoding.BINARY)NEWLINE layer.adapt([1, 2])NEWLINE _ = layer(input_data)NEWLINE with self.assertRaisesRegex(NEWLINE RuntimeError, ".*'max_tokens' arg must be set to None."):NEWLINE layer.set_num_elements(5)NEWLINENEWLINE def test_set_state_variables_after_call_fails(self):NEWLINE state_variables = {category_encoding._NUM_ELEMENTS_NAME: 5}NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32)NEWLINE layer = get_layer_class()(NEWLINE max_tokens=None, output_mode=category_encoding.BINARY)NEWLINE layer.adapt([1, 2])NEWLINE _ = layer(input_data)NEWLINE with self.assertRaisesRegex(RuntimeError, "Cannot update states.*"):NEWLINE layer._set_state_variables(state_variables)NEWLINENEWLINENEWLINE@keras_parameterized.run_all_keras_modesNEWLINE@keras_parameterized.run_all_keras_modesNEWLINEclass CategoryEncodingOutputTest(keras_parameterized.TestCase,NEWLINE preprocessing_test_utils.PreprocessingLayerTestNEWLINE ):NEWLINENEWLINE def test_binary_output_hard_maximum(self):NEWLINE input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])NEWLINENEWLINE # pyformat: disableNEWLINE expected_output = [[0, 1, 1, 1, 0, 0],NEWLINE [1, 1, 0, 1, 0, 0]]NEWLINE # pyformat: enableNEWLINE max_tokens = 6NEWLINE expected_output_shape = [None, max_tokens]NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32)NEWLINE layer = get_layer_class()(NEWLINE max_tokens=max_tokens, output_mode=category_encoding.BINARY)NEWLINE int_data = layer(input_data)NEWLINE self.assertAllEqual(expected_output_shape, int_data.shape.as_list())NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(input_array)NEWLINE self.assertAllEqual(expected_output, output_dataset)NEWLINENEWLINE def test_binary_output_soft_maximum(self):NEWLINE input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])NEWLINENEWLINE # pyformat: disableNEWLINE expected_output = [[0, 1, 1, 1, 0],NEWLINE [1, 1, 0, 1, 0]]NEWLINE # pyformat: enableNEWLINE max_tokens = 5NEWLINE expected_output_shape = [None, max_tokens]NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32)NEWLINE layer = get_layer_class()(NEWLINE max_tokens=None, output_mode=category_encoding.BINARY)NEWLINE layer.set_num_elements(max_tokens)NEWLINE int_data = layer(input_data)NEWLINE self.assertAllEqual(expected_output_shape, int_data.shape.as_list())NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(input_array)NEWLINE self.assertAllEqual(expected_output, output_dataset)NEWLINENEWLINE def test_count_output_hard_maximum(self):NEWLINE input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])NEWLINENEWLINE # pyformat: disableNEWLINE expected_output = [[0, 2, 1, 1, 0, 0],NEWLINE [2, 1, 0, 1, 0, 0]]NEWLINE # pyformat: enableNEWLINE max_tokens = 6NEWLINE expected_output_shape = [None, max_tokens]NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32)NEWLINE layer = get_layer_class()(max_tokens=6, output_mode=category_encoding.COUNT)NEWLINE int_data = layer(input_data)NEWLINE self.assertAllEqual(expected_output_shape, int_data.shape.as_list())NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(input_array)NEWLINE self.assertAllEqual(expected_output, output_dataset)NEWLINENEWLINE def test_count_output_soft_maximum(self):NEWLINE input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])NEWLINENEWLINE # pyformat: disableNEWLINE expected_output = [[0, 2, 1, 1, 0],NEWLINE [2, 1, 0, 1, 0]]NEWLINE # pyformat: enableNEWLINE max_tokens = 5NEWLINE expected_output_shape = [None, max_tokens]NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32)NEWLINE layer = get_layer_class()(NEWLINE max_tokens=None, output_mode=category_encoding.COUNT)NEWLINE layer.set_num_elements(max_tokens)NEWLINE int_data = layer(input_data)NEWLINE self.assertAllEqual(expected_output_shape, int_data.shape.as_list())NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(input_array)NEWLINE self.assertAllEqual(expected_output, output_dataset)NEWLINENEWLINE def test_tfidf_output_hard_maximum(self):NEWLINE tfidf_data = [.05, .5, .25, .2, .125]NEWLINE input_array = np.array([[1, 2, 3, 1], [0, 4, 1, 0]])NEWLINENEWLINE # pyformat: disableNEWLINE # pylint: disable=bad-whitespaceNEWLINE expected_output = [[ 0, 1, .25, .2, 0, 0],NEWLINE [.1, .5, 0, 0, .125, 0]]NEWLINE # pylint: enable=bad-whitespaceNEWLINE # pyformat: enableNEWLINE max_tokens = 6NEWLINE expected_output_shape = [None, max_tokens]NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32)NEWLINE layer = get_layer_class()(max_tokens=6, output_mode=category_encoding.TFIDF)NEWLINE layer.set_tfidf_data(tfidf_data)NEWLINE int_data = layer(input_data)NEWLINE self.assertAllEqual(expected_output_shape, int_data.shape.as_list())NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(input_array)NEWLINE self.assertAllClose(expected_output, output_dataset)NEWLINENEWLINE def test_tfidf_output_soft_maximum(self):NEWLINE tfidf_data = [.05, .5, .25, .2, .125]NEWLINE input_array = np.array([[1, 2, 3, 1], [0, 4, 1, 0]])NEWLINENEWLINE # pyformat: disableNEWLINE # pylint: disable=bad-whitespaceNEWLINE expected_output = [[ 0, 1, .25, .2, 0],NEWLINE [.1, .5, 0, 0, .125]]NEWLINE # pylint: enable=bad-whitespaceNEWLINE # pyformat: enableNEWLINE max_tokens = 5NEWLINE expected_output_shape = [None, max_tokens]NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32)NEWLINE layer = get_layer_class()(NEWLINE max_tokens=None, output_mode=category_encoding.TFIDF)NEWLINE layer.set_num_elements(max_tokens)NEWLINE layer.set_tfidf_data(tfidf_data)NEWLINE int_data = layer(input_data)NEWLINE self.assertAllEqual(expected_output_shape, int_data.shape.as_list())NEWLINENEWLINE model = keras.Model(inputs=input_data, outputs=int_data)NEWLINE output_dataset = model.predict(input_array)NEWLINE self.assertAllClose(expected_output, output_dataset)NEWLINENEWLINENEWLINEclass CategoryEncodingModelBuildingTest(NEWLINE keras_parameterized.TestCase,NEWLINE preprocessing_test_utils.PreprocessingLayerTest):NEWLINENEWLINE @parameterized.named_parameters(NEWLINE {NEWLINE "testcase_name": "count_hard_max",NEWLINE "max_tokens": 5,NEWLINE "output_mode": category_encoding.COUNTNEWLINE }, {NEWLINE "testcase_name": "count_soft_max",NEWLINE "max_tokens": None,NEWLINE "output_mode": category_encoding.COUNTNEWLINE }, {NEWLINE "testcase_name": "binary_hard_max",NEWLINE "max_tokens": 5,NEWLINE "output_mode": category_encoding.BINARYNEWLINE }, {NEWLINE "testcase_name": "binary_soft_max",NEWLINE "max_tokens": None,NEWLINE "output_mode": category_encoding.BINARYNEWLINE }, {NEWLINE "testcase_name": "tfidf_hard_max",NEWLINE "max_tokens": 5,NEWLINE "output_mode": category_encoding.TFIDFNEWLINE }, {NEWLINE "testcase_name": "tfidf_soft_max",NEWLINE "max_tokens": None,NEWLINE "output_mode": category_encoding.TFIDFNEWLINE })NEWLINE def test_end_to_end_bagged_modeling(self, output_mode, max_tokens):NEWLINE tfidf_data = np.array([.03, .5, .25, .2, .125])NEWLINE input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])NEWLINENEWLINE input_data = keras.Input(shape=(None,), dtype=dtypes.int32)NEWLINE layer = get_layer_class()(max_tokens=max_tokens, output_mode=output_mode)NEWLINENEWLINE weights = []NEWLINE if max_tokens is None:NEWLINE layer.set_num_elements(5)NEWLINE if output_mode == category_encoding.TFIDF:NEWLINE weights.append(tfidf_data)NEWLINENEWLINE layer.set_weights(weights)NEWLINENEWLINE int_data = layer(input_data)NEWLINE float_data = backend.cast(int_data, dtype="float32")NEWLINE output_data = core.Dense(64)(float_data)NEWLINE model = keras.Model(inputs=input_data, outputs=output_data)NEWLINE _ = model.predict(input_array)NEWLINENEWLINENEWLINE@keras_parameterized.run_all_keras_modesNEWLINEclass CategoryEncodingCombinerTest(NEWLINE keras_parameterized.TestCase,NEWLINE preprocessing_test_utils.PreprocessingLayerTest):NEWLINENEWLINE def compare_idf_accumulators(self, a, b, msg=None):NEWLINE if a is None or b is None:NEWLINE self.assertAllEqual(a, b, msg=msg)NEWLINENEWLINE self.assertAllEqual(a.data, b.data, msg=msg)NEWLINENEWLINE if a.per_doc_count_dict is not None:NEWLINENEWLINE def per_doc_counts(accumulator):NEWLINE count_values = [NEWLINE count_dict["count"]NEWLINE for count_dict in accumulator.per_doc_count_dict.values()NEWLINE ]NEWLINE return dict(zip(accumulator.per_doc_count_dict.keys(), count_values))NEWLINENEWLINE self.assertAllEqual(per_doc_counts(a), per_doc_counts(b), msg=msg)NEWLINENEWLINE compare_accumulators = compare_idf_accumulatorsNEWLINENEWLINE def update_accumulator(self, accumulator, data):NEWLINE accumulator.data[1] = data["num_documents"]NEWLINE accumulator.data[0] = data["max_element"]NEWLINENEWLINE if "document_counts" in data:NEWLINE create_dict = lambda x: {"count": x, "last_doc_id": -1}NEWLINE idf_dict = {}NEWLINE for i, count in enumerate(data["document_counts"]):NEWLINE if count > 0:NEWLINE idf_dict[i] = create_dict(count)NEWLINENEWLINE accumulator.per_doc_count_dict.update(idf_dict)NEWLINENEWLINE return accumulatorNEWLINENEWLINE def test_combiner_api_compatibility_int_mode(self):NEWLINE data = np.array([[1, 2, 3, 4], [1, 2, 3, 0]])NEWLINE combiner = category_encoding._CategoryEncodingCombiner(compute_idf=False)NEWLINE expected_accumulator_output = {NEWLINE "max_element": np.array(4),NEWLINE "num_documents": np.array(2),NEWLINE }NEWLINE expected_extract_output = {NEWLINE "num_elements": np.array(5),NEWLINE }NEWLINE expected_accumulator = combiner._create_accumulator()NEWLINE expected_accumulator = self.update_accumulator(expected_accumulator,NEWLINE expected_accumulator_output)NEWLINE self.validate_accumulator_serialize_and_deserialize(combiner, data,NEWLINE expected_accumulator)NEWLINE self.validate_accumulator_uniqueness(combiner, data)NEWLINE self.validate_accumulator_extract(combiner, data, expected_extract_output)NEWLINENEWLINE def test_combiner_api_compatibility_tfidf_mode(self):NEWLINE data = np.array([[1, 2, 3, 4], [1, 2, 3, 0]])NEWLINE combiner = category_encoding._CategoryEncodingCombiner(compute_idf=True)NEWLINE expected_accumulator_output = {NEWLINE "max_element": np.array(4),NEWLINE "document_counts": np.array([1, 2, 2, 2, 1]),NEWLINE "num_documents": np.array(2),NEWLINE }NEWLINE expected_extract_output = {NEWLINE "num_elements": np.array(5),NEWLINE "idf": np.array([0.693147, 0.510826, 0.510826, 0.510826, 0.693147]),NEWLINE }NEWLINENEWLINE expected_accumulator = combiner._create_accumulator()NEWLINE expected_accumulator = self.update_accumulator(expected_accumulator,NEWLINE expected_accumulator_output)NEWLINE self.validate_accumulator_serialize_and_deserialize(combiner, data,NEWLINE expected_accumulator)NEWLINE self.validate_accumulator_uniqueness(combiner, data)NEWLINE self.validate_accumulator_extract(combiner, data, expected_extract_output)NEWLINENEWLINE # TODO(askerryryan): Add tests confirming equivalence to behavior ofNEWLINE # existing tf.keras.preprocessing.text.Tokenizer.NEWLINE @parameterized.named_parameters(NEWLINE {NEWLINE "testcase_name": "no_top_k",NEWLINE "data": np.array([[1, 2], [4, 2], [3], [4, 2]]),NEWLINE "expected_accumulator_output": {NEWLINE "max_element": np.array(4),NEWLINE "document_counts": np.array([0, 1, 3, 1, 2]),NEWLINE "num_documents": np.array(4),NEWLINE },NEWLINE "expected_extract_output": {NEWLINE "num_elements":NEWLINE np.array(5),NEWLINE "idf":NEWLINE np.array([1.609438, 1.098612, 0.693147, 1.098612, 0.847298]),NEWLINE },NEWLINE }, {NEWLINE "testcase_name": "single_element_per_row",NEWLINE "data": np.array([[1], [2], [4], [2], [3]]),NEWLINE "expected_accumulator_output": {NEWLINE "max_element": np.array(4),NEWLINE "document_counts": np.array([0, 1, 2, 1, 1]),NEWLINE "num_documents": np.array(5),NEWLINE },NEWLINE "expected_extract_output": {NEWLINE "num_elements":NEWLINE np.array(5),NEWLINE "idf":NEWLINE np.array([1.791759, 1.252763, 0.980829, 1.252763, 1.252763]),NEWLINE },NEWLINE })NEWLINE def test_combiner_computation(self,NEWLINE data,NEWLINE expected_accumulator_output,NEWLINE expected_extract_output,NEWLINE compute_idf=True):NEWLINE combiner = category_encoding._CategoryEncodingCombiner(NEWLINE compute_idf=compute_idf)NEWLINE expected_accumulator = combiner._create_accumulator()NEWLINE expected_accumulator = self.update_accumulator(expected_accumulator,NEWLINE expected_accumulator_output)NEWLINE self.validate_accumulator_computation(combiner, data, expected_accumulator)NEWLINE self.validate_accumulator_extract(combiner, data, expected_extract_output)NEWLINENEWLINE def test_1d_data(self):NEWLINE data = [1, 2, 3]NEWLINE cls = get_layer_class()NEWLINE layer = cls()NEWLINE layer.adapt(data)NEWLINE output = layer(data)NEWLINE self.assertListEqual(output.shape.as_list(), [3, 4])NEWLINENEWLINE def test_no_adapt_exception(self):NEWLINE cls = get_layer_class()NEWLINE layer = cls()NEWLINE with self.assertRaisesRegex(NEWLINE RuntimeError, r".*you need to call.*"):NEWLINE _ = layer([1, 2, 3])NEWLINENEWLINE def test_saving_loading(self):NEWLINE encoder = category_encoding.CategoryEncoding()NEWLINE encoder.adapt([1, 2, 3])NEWLINE model = keras.Sequential([encoder])NEWLINE model.save("/tmp/model", save_format="tf")NEWLINE loaded_model = keras.models.load_model("/tmp/model")NEWLINE self.assertAllClose(model.predict([[1]]), loaded_model.predict([[1]]))NEWLINENEWLINE def test_serialize(self):NEWLINE encoder = category_encoding.CategoryEncoding()NEWLINE encoder.adapt([1, 2, 3])NEWLINE model = keras.Sequential([encoder])NEWLINE _ = keras.models.clone_model(model)NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE test.main()NEWLINE #!/usr/bin/env pythonNEWLINENEWLINE# Copyright (c) 2013 Intel Corporation. All rights reserved.NEWLINE# Use of this source code is governed by a BSD-style license that can beNEWLINE# found in the LICENSE file.NEWLINE# pylint: disable=F0401NEWLINENEWLINEimport osNEWLINEimport shutilNEWLINEimport sysNEWLINEfrom common_function import RemoveUnusedFilesInReleaseModeNEWLINENEWLINEdef Clean(dir_to_clean):NEWLINE if os.path.isdir(dir_to_clean):NEWLINE shutil.rmtree(dir_to_clean)NEWLINENEWLINENEWLINEdef PrepareFromChromium(target_dir):NEWLINE gyp_dir = os.path.join(target_dir, 'scripts', 'gyp')NEWLINE if not os.path.exists(gyp_dir):NEWLINE os.makedirs(gyp_dir)NEWLINE shutil.copytree('../build/android/gyp/util', os.path.join(gyp_dir, 'util'))NEWLINE shutil.copy('../build/android/gyp/ant.py', gyp_dir)NEWLINENEWLINENEWLINEdef PrepareFromXwalk(src_dir, target_dir):NEWLINE '''Prepare different files for app packaging tools. All resources are used byNEWLINE make_apk.py.NEWLINE '''NEWLINE # Get the dir of source code from src_dir: ../../.NEWLINE source_code_dir = os.path.dirname(os.path.dirname(src_dir))NEWLINENEWLINE # The directories for source and target .jar files.NEWLINE jar_src_dir = os.path.join(src_dir, 'lib.java')NEWLINE jar_target_dir = os.path.join(target_dir, 'libs')NEWLINENEWLINE # The directories for generated resources.NEWLINE gen_res_src_dir = os.path.join(src_dir, 'gen')NEWLINE gen_res_target_dir = os.path.join(target_dir, 'gen')NEWLINENEWLINE # The directory for source packaging tools.NEWLINE tools_src_dir = os.path.join(source_code_dir, 'xwalk/app/tools/android')NEWLINENEWLINE # The directories for source and target gyp.NEWLINE gyp_src_dir = os.path.join(tools_src_dir, 'gyp')NEWLINE gyp_target_dir = os.path.join(target_dir, 'scripts/gyp')NEWLINENEWLINE # The source file/directory list to be copied and the target directory list.NEWLINE source_target_list = [NEWLINE (os.path.join(source_code_dir, 'xwalk/VERSION'), target_dir),NEWLINENEWLINE # This jar is needed for 'javac' compile.NEWLINE (os.path.join(jar_src_dir, 'xwalk_app_runtime_java.jar'), jar_target_dir),NEWLINE (os.path.join(jar_src_dir, 'xwalk_core_embedded.dex.jar'), jar_target_dir),NEWLINENEWLINE # Native library, like libxwalkcore.so.NEWLINE (os.path.join(src_dir, 'xwalk_runtime_lib_apk/libs/x86'),NEWLINE os.path.join(target_dir, 'native_libs/x86/libs/x86')),NEWLINE (os.path.join(src_dir, 'xwalk_runtime_lib_apk/libs/armeabi-v7a'),NEWLINE os.path.join(target_dir, 'native_libs/armeabi-v7a/libs/armeabi-v7a')),NEWLINENEWLINE # Native source package(xwalk.pak) and related js files for extension.NEWLINE (os.path.join(src_dir, 'xwalk_runtime_lib/assets'),NEWLINE os.path.join(target_dir, 'native_libs_res')),NEWLINENEWLINE # Various Java resources.NEWLINE (os.path.join(source_code_dir, 'content/public/android/java/res'),NEWLINE os.path.join(target_dir, 'libs_res/content')),NEWLINE (os.path.join(source_code_dir, 'ui/android/java/res'),NEWLINE os.path.join(target_dir, 'libs_res/ui')),NEWLINE (os.path.join(source_code_dir, 'xwalk/runtime/android/java/res'),NEWLINE os.path.join(target_dir, 'libs_res/runtime')),NEWLINENEWLINE (os.path.join(gen_res_src_dir, 'ui_java/java_R'),NEWLINE os.path.join(gen_res_target_dir, 'ui_java/java_R')),NEWLINE (os.path.join(gen_res_src_dir, 'ui_java/res_crunched'),NEWLINE os.path.join(gen_res_target_dir, 'ui_java/res_crunched')),NEWLINE (os.path.join(gen_res_src_dir, 'ui_java/res_grit'),NEWLINE os.path.join(gen_res_target_dir, 'ui_java/res_grit')),NEWLINE (os.path.join(gen_res_src_dir, 'ui_java/res_v14_compatibility'),NEWLINE os.path.join(gen_res_target_dir, 'ui_java/res_v14_compatibility')),NEWLINENEWLINE (os.path.join(gen_res_src_dir, 'content_java/java_R'),NEWLINE os.path.join(gen_res_target_dir, 'content_java/java_R')),NEWLINE (os.path.join(gen_res_src_dir, 'content_java/res_crunched'),NEWLINE os.path.join(gen_res_target_dir, 'content_java/res_crunched')),NEWLINE (os.path.join(gen_res_src_dir, 'content_java/res_grit'),NEWLINE os.path.join(gen_res_target_dir, 'content_java/res_grit')),NEWLINE (os.path.join(gen_res_src_dir, 'content_java/res_v14_compatibility'),NEWLINE os.path.join(gen_res_target_dir, 'content_java/res_v14_compatibility')),NEWLINENEWLINE (os.path.join(gen_res_src_dir, 'xwalk_core_java/java_R'),NEWLINE os.path.join(gen_res_target_dir, 'xwalk_core_java/java_R')),NEWLINE (os.path.join(gen_res_src_dir, 'xwalk_core_java/res_crunched'),NEWLINE os.path.join(gen_res_target_dir, 'xwalk_core_java/res_crunched')),NEWLINE (os.path.join(gen_res_src_dir, 'xwalk_core_java/res_grit'),NEWLINE os.path.join(gen_res_target_dir, 'xwalk_core_java/res_grit')),NEWLINE (os.path.join(gen_res_src_dir, 'xwalk_core_java/res_v14_compatibility'),NEWLINE os.path.join(gen_res_target_dir, 'xwalk_core_java/res_v14_compatibility')),NEWLINENEWLINE # The app wrapper code. It's the template Java code.NEWLINE (os.path.join(source_code_dir, 'xwalk/app/android/app_template'),NEWLINE os.path.join(target_dir, 'app_src')),NEWLINENEWLINE # Copy below 5 files to overwrite the existing ones from Chromium.NEWLINE (os.path.join(gyp_src_dir, 'util/build_utils.py'),NEWLINE os.path.join(gyp_target_dir, 'util')),NEWLINE (os.path.join(gyp_src_dir, 'dex.py'), gyp_target_dir),NEWLINE (os.path.join(gyp_src_dir, 'finalize_apk.py'), gyp_target_dir),NEWLINE (os.path.join(gyp_src_dir, 'jar.py'), gyp_target_dir),NEWLINE (os.path.join(gyp_src_dir, 'javac.py'), gyp_target_dir),NEWLINENEWLINE # Build and python tools.NEWLINE (os.path.join(tools_src_dir, 'ant'),NEWLINE os.path.join(target_dir, 'scripts/ant')),NEWLINE (os.path.join(tools_src_dir, 'customize.py'), target_dir),NEWLINE (os.path.join(tools_src_dir, 'handle_permissions.py'), target_dir),NEWLINE (os.path.join(tools_src_dir, 'handle_xml.py'), target_dir),NEWLINE (os.path.join(tools_src_dir, 'make_apk.py'), target_dir),NEWLINE (os.path.join(tools_src_dir, 'manifest_json_parser.py'), target_dir),NEWLINE (os.path.join(tools_src_dir, 'parse_xpk.py'), target_dir)NEWLINE ]NEWLINENEWLINE for index in range(len(source_target_list)):NEWLINE source_path, target_path = source_target_list[index]NEWLINENEWLINE # Process source.NEWLINE if not os.path.exists(source_path):NEWLINE print ('The source path "%s" does not exist.' % source_path)NEWLINE continueNEWLINENEWLINE source_is_file = os.path.isfile(source_path)NEWLINENEWLINE # Process target.NEWLINE if source_is_file and not os.path.exists(target_path):NEWLINE os.makedirs(target_path)NEWLINENEWLINE # Do copy.NEWLINE if source_is_file:NEWLINE shutil.copy(source_path, target_path)NEWLINE else:NEWLINE shutil.copytree(source_path, target_path)NEWLINENEWLINE # Remove unused files.NEWLINE mode = os.path.basename(os.path.dirname(target_dir))NEWLINE RemoveUnusedFilesInReleaseMode(mode, os.path.join(target_dir, 'native_libs'))NEWLINENEWLINENEWLINEdef main(args):NEWLINE if len(args) != 1:NEWLINE print 'You must provide only one argument: folder to update'NEWLINE return 1NEWLINE target_dir = args[0]NEWLINE src_dir = os.path.dirname(target_dir)NEWLINE Clean(target_dir)NEWLINE PrepareFromChromium(target_dir)NEWLINE PrepareFromXwalk(src_dir, target_dir)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE sys.exit(main(sys.argv[1:]))NEWLINE import bpyNEWLINEfrom numpy import array, zeros, argmin, infNEWLINEfrom numpy.linalg import normNEWLINEfrom mathutils import *NEWLINENEWLINE####==========================================================================NEWLINE# DTW implementation courtesy of Pierre Rouanet:NEWLINE# http://github.com/pierre-rouanet/dtwNEWLINE# See examples that he postsNEWLINE####==========================================================================NEWLINENEWLINEdef dtw(x, y, dist=lambda x, y: norm(x - y, ord=1)):NEWLINE """ Computes the DTW of two sequences.NEWLINENEWLINE :param array x: N1*M arrayNEWLINE :param array y: N2*M arrayNEWLINE :param func dist: distance used as cost measure (default L1 norm)NEWLINENEWLINE Returns the minimum distance, the accumulated cost matrix and the wrap path.NEWLINENEWLINE """NEWLINE x = array(x)NEWLINE if len(x.shape) == 1:NEWLINE x = x.reshape(-1, 1)NEWLINE y = array(y)NEWLINE if len(y.shape) == 1:NEWLINE y = y.reshape(-1, 1)NEWLINENEWLINE r, c = len(x), len(y)NEWLINENEWLINE D = zeros((r + 1, c + 1))NEWLINE D[0, 1:] = infNEWLINE D[1:, 0] = infNEWLINENEWLINE for i in range(r):NEWLINE for j in range(c):NEWLINE D[i+1, j+1] = dist(x[i], y[j])NEWLINENEWLINE for i in range(r):NEWLINE for j in range(c):NEWLINE D[i+1, j+1] += min(D[i, j], D[i, j+1], D[i+1, j])NEWLINENEWLINE D = D[1:, 1:]NEWLINENEWLINE dist = D[-1, -1] / sum(D.shape)NEWLINENEWLINE return dist, D, _trackeback(D)NEWLINENEWLINENEWLINEdef _trackeback(D):NEWLINE i, j = array(D.shape) - 1NEWLINE p, q = [i], [j]NEWLINE while (i > 0 and j > 0):NEWLINE tb = argmin((D[i-1, j-1], D[i-1, j], D[i, j-1]))NEWLINENEWLINE if (tb == 0):NEWLINE i = i - 1NEWLINE j = j - 1NEWLINE elif (tb == 1):NEWLINE i = i - 1NEWLINE elif (tb == 2):NEWLINE j = j - 1NEWLINENEWLINE p.insert(0, i)NEWLINE q.insert(0, j)NEWLINENEWLINE p.insert(0, 0)NEWLINE q.insert(0, 0)NEWLINE return (array(p), array(q))NEWLINENEWLINE####==========================================================================NEWLINENEWLINE####==========================================================================NEWLINE# Get the rotation given mocap to search in, bonename, and frameNEWLINE# "action" is a blender Action, "bonename" is a string, "frame" is an intNEWLINE# blender Actions can be found in bpy.data.actionsNEWLINE####==========================================================================NEWLINEdef get_rotation(action, bonename, frame=1):NEWLINE rot = Euler([0,0,0])NEWLINE data_path = 'pose.bones["%s"].rotation_euler'%(bonename)NEWLINE for fc in action.fcurves:NEWLINE if fc.data_path == data_path:NEWLINE rot[fc.array_index] = fc.evaluate(frame)NEWLINE return(rot)NEWLINENEWLINE####==========================================================================NEWLINE# Creates a list containing the rotations of a boneNEWLINE# rot[i] equals the i+1th frame of animationNEWLINE# "action" is a blender Action, "bonename" is a stringNEWLINE####==========================================================================NEWLINEdef listRotation(action, bonename):NEWLINE rot = []NEWLINE for i in range(1, int(action.fcurves[0].range()[1]) + 1):NEWLINE rot.append(get_rotation(action, bonename, i))NEWLINE return rotNEWLINENEWLINE####==========================================================================NEWLINE# Replaces the existing rotation FCurves with the new computed rotationsNEWLINE# "action" is a blender Action, "bonename" is a string and NEWLINE# "rot" is a list of vectorsNEWLINE####==========================================================================NEWLINEdef replaceRotation(action, bonename, rot):NEWLINE data_path = 'pose.bones["%s"].rotation_euler'%(bonename)NEWLINE x = []NEWLINE y = []NEWLINE z = [] NEWLINE # Separate x, y, z values NEWLINE for i in range(len(rot)):NEWLINE x.append(rot[i][0])NEWLINE y.append(rot[i][1])NEWLINE z.append(rot[i][2])NEWLINENEWLINE # Obtain curves of interestNEWLINE for curve in action.fcurves:NEWLINE if curve.data_path == data_path:NEWLINE if curve.array_index == 0:NEWLINE c0 = curveNEWLINE elif curve.array_index == 1:NEWLINE c1 = curveNEWLINE elif curve.array_index == 2:NEWLINE c2 = curveNEWLINENEWLINE # Access keyframesNEWLINE c0k = c0.keyframe_pointsNEWLINE c1k = c1.keyframe_pointsNEWLINE c2k = c2.keyframe_pointsNEWLINENEWLINE # Replace existing keyframes with new onesNEWLINE for i in range(1, len(x)+1):NEWLINE c0k.insert(i, x[i-1], {'REPLACE'})NEWLINE c1k.insert(i, y[i-1], {'REPLACE'})NEWLINE c2k.insert(i, z[i-1], {'REPLACE'})NEWLINENEWLINE####==========================================================================NEWLINE# Creates the final curve based on determined pathNEWLINE# Based on current undrestanding of the functionNEWLINE# "curve" is a list of vectors and "path" is a list of intsNEWLINE####==========================================================================NEWLINEdef match(curve, path):NEWLINE t = []NEWLINE for i in path:NEWLINE t.append(curve[i])NEWLINE return tNEWLINENEWLINE####==========================================================================NEWLINE# Run DTW alg to find shortest pathNEWLINE# Primarily interested in Path for the time beingNEWLINE# Uses it to generate the new rotationsNEWLINE# "curveA", "curveB" are a list of vectorsNEWLINE####==========================================================================NEWLINEdef applyDTW(curveA, curveB):NEWLINE dist, cost, path = dtw(curveA, curveB)NEWLINE curveA = match(curveA, path[0])NEWLINE curveB = match(curveB, path[1])NEWLINE return curveA, curveBNEWLINENEWLINE####==========================================================================NEWLINE# Example UsageNEWLINE####==========================================================================NEWLINEif __name__ == "__main__":NEWLINE action1 = bpy.data.actions[0] # Mocap 1NEWLINE action2 = bpy.data.actions[1] # Mocap 2NEWLINE NEWLINE # Comparison jointsNEWLINE bodyBone = 'lHand'NEWLINE handBone = 'Hand'NEWLINENEWLINE # Get the rotation data (vectors)NEWLINE rotA = listRotation(action1, bodyBone)NEWLINE rotB = listRotation(action2, handBone)NEWLINENEWLINE # Process rotA and rotBNEWLINE rotA, rotB = applyDTW(rotA, rotB)NEWLINENEWLINE # Replace originalsNEWLINE replaceRotation(action1, bodyBone, rotA)NEWLINE replaceRotation(action2, handBone, rotB)NEWLINENEWLINENEWLINE #!/usr/bin/env pythonNEWLINE# -*- coding: utf-8 -*-NEWLINE# **************************************************************************NEWLINE# Copyright © 2016 jianglinNEWLINE# File Name: __init__.pyNEWLINE# Author: jianglinNEWLINE# Email: xiyang0807@gmail.comNEWLINE# Created: 2016-11-25 17:45:36 (CST)NEWLINE# Last Update:星期五 2016-11-25 17:45:36 (CST)NEWLINE# By:NEWLINE# Description:NEWLINE# **************************************************************************NEWLINE #!/usr/bin/env python3NEWLINE# -*- coding: utf-8 -*-NEWLINE# vim: set et sw=4 ts=4:NEWLINENEWLINEfrom PyQt5.QtWidgets import *NEWLINEfrom PyQt5.QtCore import *NEWLINEfrom PyQt5.QtGui import *NEWLINENEWLINEfrom ayat import (suar_names, suar_lengths)NEWLINENEWLINENEWLINEclass SuraAyatDialog(QDialog):NEWLINENEWLINE submit = pyqtSignal(int,int,int,bool,bool)NEWLINENEWLINE def __init__(s):NEWLINE super().__init__()NEWLINE s.setWindowTitle("تسميع آيات القرآن الكريم")NEWLINE #NEWLINE s.setLayoutDirection(Qt.RightToLeft)NEWLINE #NEWLINE s.suraEntry = QComboBox()NEWLINE s.fromEntry = QSpinBox()NEWLINE s.toEntry = QSpinBox()NEWLINE s.darkEntry = QCheckBox("الوضع الليلي")NEWLINE s.darkEntry.setStyleSheet("text-align: right")NEWLINE s.numberEntry = QCheckBox("ترقيم الآيات")NEWLINE s.numberEntry.setStyleSheet("text-align: right")NEWLINE #NEWLINE for (i,n) in enumerate(suar_names):NEWLINE s.suraEntry.addItem("%s - %d" % (n, i+1))NEWLINE #NEWLINE def suraChanged(i):NEWLINE s.fromEntry.setMaximum(suar_lengths[i])NEWLINE s.toEntry.setMaximum(suar_lengths[i])NEWLINE s.toEntry.setValue(suar_lengths[i])NEWLINE #NEWLINE s.fromEntry.setMinimum(1)NEWLINE s.toEntry.setMinimum(1)NEWLINE suraChanged(0)NEWLINE #NEWLINE s.suraEntry.setEditable(True)NEWLINE s.suraEntry.lineEdit().selectAll() # to just type the first characters of a sura's nameNEWLINE s.suraEntry.setInsertPolicy(QComboBox.NoInsert)NEWLINE s.suraEntry.currentIndexChanged.connect(suraChanged)NEWLINE #NEWLINE s.form = QFormLayout()NEWLINE for (name, entry) in (NEWLINE ("السورة:", s.suraEntry),NEWLINE ("من آية:", s.fromEntry),NEWLINE ("إلى آية:", s.toEntry),NEWLINE ):NEWLINE s.form.addRow(name, entry)NEWLINE #NEWLINE s.okbtn = QPushButton("انطلق")NEWLINE s.okbtn.setDefault(True)NEWLINE def ok():NEWLINE s.submit.emit(NEWLINE s.suraEntry.currentIndex(),NEWLINE s.fromEntry.value()-1,NEWLINE s.toEntry.value(),NEWLINE s.darkEntry.isChecked(),NEWLINE s.numberEntry.isChecked(),NEWLINE )NEWLINE s.accept()NEWLINE s.okbtn.clicked.connect(ok)NEWLINE s.box = QVBoxLayout()NEWLINE s.box.addLayout(s.form)NEWLINE s.box.addWidget(s.darkEntry, alignment=Qt.AlignCenter)NEWLINE s.box.addWidget(s.numberEntry, alignment=Qt.AlignCenter)NEWLINE s.box.addWidget(s.okbtn, alignment=Qt.AlignCenter)NEWLINE #NEWLINE s.setLayout(s.box)NEWLINENEWLINE # test importing of required modules and sit2standpy packageNEWLINENEWLINENEWLINEdef test_numpy():NEWLINE import numpyNEWLINENEWLINE returnNEWLINENEWLINENEWLINEdef test_scipy():NEWLINE import scipyNEWLINENEWLINE returnNEWLINENEWLINENEWLINEdef test_pywt():NEWLINE import pywtNEWLINENEWLINE returnNEWLINENEWLINENEWLINEdef test_pysit2stand():NEWLINE import sit2standpyNEWLINE from sit2standpy import Sit2Stand, detectors, mov_stats, Transition, TransitionQuantifier, \NEWLINE AccelerationFilter, process_timestamps, __version__NEWLINE from sit2standpy.detectors import Stillness, DisplacementNEWLINENEWLINE returnNEWLINE #!/usr/bin/env python2NEWLINE#NEWLINE# Distributed under the MIT/X11 software license, see the accompanyingNEWLINE# file COPYING or http://www.opensource.org/licenses/mit-license.php.NEWLINE#NEWLINENEWLINEfrom test_framework.mininode import *NEWLINEfrom test_framework.test_framework import BitcoinTestFrameworkNEWLINEfrom test_framework.util import *NEWLINEimport loggingNEWLINENEWLINE'''NEWLINEIn this test we connect to one node over p2p, send it numerous inv's, andNEWLINEcompare the resulting number of getdata requests to a max allowed value. WeNEWLINEtest for exceeding 128 blocks in flight, which was the limit an 0.9 client willNEWLINEreach. [0.10 clients shouldn't request more than 16 from a single peer.]NEWLINE'''NEWLINEMAX_REQUESTS = 128NEWLINENEWLINEclass TestManager(NodeConnCB):NEWLINE # set up NodeConnCB callbacks, overriding base classNEWLINE def on_getdata(self, conn, message):NEWLINE self.log.debug("got getdata %s" % repr(message))NEWLINE # Log the requestsNEWLINE for inv in message.inv:NEWLINE if inv.hash not in self.blockReqCounts:NEWLINE self.blockReqCounts[inv.hash] = 0NEWLINE self.blockReqCounts[inv.hash] += 1NEWLINENEWLINE def on_close(self, conn):NEWLINE if not self.disconnectOkay:NEWLINE raise EarlyDisconnectError(0)NEWLINENEWLINE def __init__(self):NEWLINE NodeConnCB.__init__(self)NEWLINE self.log = logging.getLogger("BlockRelayTest")NEWLINE self.create_callback_map()NEWLINENEWLINE def add_new_connection(self, connection):NEWLINE self.connection = connectionNEWLINE self.blockReqCounts = {}NEWLINE self.disconnectOkay = FalseNEWLINENEWLINE def run(self):NEWLINE try:NEWLINE fail = FalseNEWLINE self.connection.rpc.generate(1) # Leave IBDNEWLINENEWLINE numBlocksToGenerate = [ 8, 16, 128, 1024 ]NEWLINE for count in range(len(numBlocksToGenerate)):NEWLINE current_invs = []NEWLINE for i in range(numBlocksToGenerate[count]):NEWLINE current_invs.append(CInv(2, random.randrange(0, 1<<256)))NEWLINE if len(current_invs) >= 50000:NEWLINE self.connection.send_message(msg_inv(current_invs))NEWLINE current_invs = []NEWLINE if len(current_invs) > 0:NEWLINE self.connection.send_message(msg_inv(current_invs))NEWLINE NEWLINE # Wait and see how many blocks were requestedNEWLINE time.sleep(2)NEWLINENEWLINE total_requests = 0NEWLINE with mininode_lock:NEWLINE for key in self.blockReqCounts:NEWLINE total_requests += self.blockReqCounts[key]NEWLINE if self.blockReqCounts[key] > 1:NEWLINE raise AssertionError("Error, test failed: block %064x requested more than once" % key)NEWLINE if total_requests > MAX_REQUESTS:NEWLINE raise AssertionError("Error, too many blocks (%d) requested" % total_requests)NEWLINE print "Round %d: success (total requests: %d)" % (count, total_requests)NEWLINE except AssertionError as e:NEWLINE print "TEST FAILED: ", e.argsNEWLINENEWLINE self.disconnectOkay = TrueNEWLINE self.connection.disconnect_node()NEWLINENEWLINE NEWLINEclass MaxBlocksInFlightTest(BitcoinTestFramework):NEWLINE def add_options(self, parser):NEWLINE parser.add_option("--testbinary", dest="testbinary",NEWLINE default=os.getenv("LEMONCOIND", "lemoncoind"),NEWLINE help="Binary to test max block requests behavior")NEWLINENEWLINE def setup_chain(self):NEWLINE print "Initializing test directory "+self.options.tmpdirNEWLINE initialize_chain_clean(self.options.tmpdir, 1)NEWLINENEWLINE def setup_network(self):NEWLINE self.nodes = start_nodes(1, self.options.tmpdir, NEWLINE extra_args=[['-debug', '-whitelist=127.0.0.1']],NEWLINE binary=[self.options.testbinary])NEWLINENEWLINE def run_test(self):NEWLINE test = TestManager()NEWLINE test.add_new_connection(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test))NEWLINE NetworkThread().start() # Start up network handling in another threadNEWLINE test.run()NEWLINENEWLINEif __name__ == '__main__':NEWLINE MaxBlocksInFlightTest().main()NEWLINE """Application-specific settings."""NEWLINEimport osNEWLINEfrom django.conf import settings as _settingsNEWLINEfrom django.core.exceptions import ImproperlyConfiguredNEWLINENEWLINENEWLINE###############################################################################NEWLINE# Single settings.NEWLINE###############################################################################NEWLINEclass Setting(object):NEWLINE """Settings option helper class."""NEWLINE def __init__(self, **kwargs):NEWLINE """Initializer.NEWLINENEWLINE :kwarg default: Override default for getting.NEWLINE :type default: ``object``NEWLINE :kwarg from_env: Allow variable from evironment.NEWLINE :type from_env: ``bool``NEWLINE :kwarg valid_set: Set of valid values for setting.NEWLINE :type valid_set: ``set``NEWLINE """NEWLINE self.from_env = kwargs.get('from_env', False)NEWLINE self.default = kwargs.get('default', None)NEWLINE self.valid_set = kwargs.get('valid_set', None)NEWLINENEWLINE def validate(self, name, value):NEWLINE """Validate and return a value."""NEWLINENEWLINE if self.valid_set and value not in self.valid_set:NEWLINE raise ImproperlyConfigured(NEWLINE "%s: \"%s\" is not a valid setting (choose between %s)." %NEWLINE (name, value, ", ".join("\"%s\"" % x for x in self.valid_set)))NEWLINENEWLINE return valueNEWLINENEWLINE def env_clean(self, value): # pylint: disable=R0201NEWLINE """Clean / convert environment variable to proper type."""NEWLINE return valueNEWLINENEWLINE def get(self, name, default=None):NEWLINE """Get value."""NEWLINE default = default if default is not None else self.defaultNEWLINE try:NEWLINE value = getattr(_settings, name)NEWLINE except AttributeError:NEWLINE value = os.environ.get(name, default) if self.from_env else defaultNEWLINE # Convert env variable.NEWLINE if value != default:NEWLINE value = self.env_clean(value)NEWLINENEWLINE return self.validate(name, value)NEWLINENEWLINENEWLINEclass BoolSetting(Setting):NEWLINE """Boolean setting.."""NEWLINE def env_clean(self, value):NEWLINE """Clean / convert environment variable to proper type."""NEWLINE return self.parse_bool(value)NEWLINENEWLINE @classmethodNEWLINE def parse_bool(cls, value, default=None):NEWLINE """Convert ``string`` or ``bool`` to ``bool``."""NEWLINE if value is None:NEWLINE return defaultNEWLINENEWLINE elif isinstance(value, bool):NEWLINE return valueNEWLINENEWLINE elif isinstance(value, basestring):NEWLINE if value == 'True':NEWLINE return TrueNEWLINE elif value == 'False':NEWLINE return FalseNEWLINENEWLINE raise Exception("Value %s is not boolean." % value)NEWLINENEWLINENEWLINE###############################################################################NEWLINE# Settings wrapper.NEWLINE###############################################################################NEWLINEclass Settings(object):NEWLINE """Cloud Browser application settings.NEWLINENEWLINE This class wraps the "real" Django settings object, so can be used instead.NEWLINE The additional cloud browser settings are as follows:NEWLINENEWLINE .. note::NEWLINE **Environment Variables**: Certain credential settings can come from OSNEWLINE environment variables instead of from a settings file value to open upNEWLINE more options for secrets management. Values that can be set in theNEWLINE environment are designated with an "(*Env*)" notation.NEWLINENEWLINE Setting a value this way could be done, e.g.::NEWLINENEWLINE $ export CLOUD_BROWSER_AWS_ACCOUNT="my_account"NEWLINE $ export CLOUD_BROWSER_AWS_SECRET_KEY="my_secret"NEWLINE $ # ... start django application with environment variables.NEWLINENEWLINE **Datastore Settings**:NEWLINENEWLINE * ``CLOUD_BROWSER_DATASTORE``: Choice of datastore (see values below).NEWLINENEWLINE **Amazon Web Services**: Configure AWS S3 as backing datastore.NEWLINENEWLINE * ``CLOUD_BROWSER_DATASTORE = "AWS"``NEWLINE * ``CLOUD_BROWSER_AWS_ACCOUNT``: Account name. (*Env*)NEWLINE * ``CLOUD_BROWSER_AWS_SECRET_KEY``: Account API secret key. (*Env*)NEWLINENEWLINE **Google Storage for Developers**: Configure Google Storage as backingNEWLINE datastore.NEWLINENEWLINE * ``CLOUD_BROWSER_DATASTORE = "Google"``NEWLINE * ``CLOUD_BROWSER_GS_ACCOUNT``: Account name. (*Env*)NEWLINE * ``CLOUD_BROWSER_GS_SECRET_KEY``: Account API secret key. (*Env*)NEWLINENEWLINE **Rackspace**: Configure Rackspace Cloud Files as backing datastore.NEWLINENEWLINE * ``CLOUD_BROWSER_DATASTORE = "Rackspace"``NEWLINE * ``CLOUD_BROWSER_RACKSPACE_ACCOUNT``: Account name. (*Env*)NEWLINE * ``CLOUD_BROWSER_RACKSPACE_SECRET_KEY``: Account API secret key. (*Env*)NEWLINE * ``CLOUD_BROWSER_RACKSPACE_SERVICENET``: Boolean designating whether orNEWLINE not to use Rackspace's servicenet (i.e., the private interface on aNEWLINE Cloud Server). (*Env*)NEWLINE * ``CLOUD_BROWSER_RACKSPACE_AUTHURL``: Alternative authorization server,NEWLINE for use, e.g., with `OpenStack `_ instead ofNEWLINE Rackspace. (*Env*)NEWLINENEWLINE **Filesystem**: Configure simple filesystem mock datastore.NEWLINENEWLINE * ``CLOUD_BROWSER_DATASTORE = "Filesystem"``NEWLINE * ``CLOUD_BROWSER_FILESYSTEM_ROOT``: Filesystem root to serve from.NEWLINENEWLINE **View Permissions**: A standard Django view decorator object can beNEWLINE specified, which is wrapped for all browsing / viewing view -- for example,NEWLINE to limit views to logged in members, use ``login_required`` and for staffNEWLINE only, use ``staff_member_required``. Note that either a real decoratorNEWLINE function or a fully-qualifid string path are acceptable, so you can use,NEWLINE e.g., "django.contrib.admin.views.decorators.staff_member_required" insteadNEWLINE which might help with certain settings.py import-order-related issues.NEWLINENEWLINE * ``CLOUD_BROWSER_VIEW_DECORATOR``: View decorator or fully-qualifiedNEWLINE string path.NEWLINENEWLINE **Container Permissions**: Cloud browser allows a very rudimentary formNEWLINE of access control at the container level with white and black lists.NEWLINE If the white list is set, only container names in the white list areNEWLINE allowed. If the white list is unset, then any container name *not* inNEWLINE the black list is permitted. All name matching is exact (no regularNEWLINE expressions, etc.).NEWLINENEWLINE * ``CLOUD_BROWSER_CONTAINER_WHITELIST``: White list of names. (Iterable)NEWLINE * ``CLOUD_BROWSER_CONTAINER_BLACKLIST``: Black list of names. (Iterable)NEWLINENEWLINE **General**: Other settings.NEWLINENEWLINE * ``CLOUD_BROWSER_DEFAULT_LIST_LIMIT``: Default number of objects toNEWLINE diplay per browser page.NEWLINE * ``CLOUD_BROWSER_STATIC_MEDIA_DIR``: If this applications static mediaNEWLINE (found in ``app_media``) is served up under the ``settings.MEDIA_ROOT``,NEWLINE then set a relative path from the root, and the static media will be usedNEWLINE instead of a Django-based static view fallback.NEWLINE """NEWLINE #: Valid datastore types.NEWLINE DATASTORES = set((NEWLINE 'AWS',NEWLINE 'Google',NEWLINE 'Rackspace',NEWLINE 'Filesystem',NEWLINE ))NEWLINENEWLINE #: Settings dictionary of accessor callables.NEWLINE SETTINGS = {NEWLINE # Datastore choice.NEWLINE 'CLOUD_BROWSER_DATASTORE': Setting(NEWLINE default='Filesystem',NEWLINE valid_set=DATASTORESNEWLINE ),NEWLINENEWLINE # Amazon Web Services S3 datastore settings.NEWLINE 'CLOUD_BROWSER_AWS_ACCOUNT': Setting(from_env=True),NEWLINE 'CLOUD_BROWSER_AWS_SECRET_KEY': Setting(from_env=True),NEWLINENEWLINE # Google Storage for Developers datastore settings.NEWLINE 'CLOUD_BROWSER_GS_ACCOUNT': Setting(from_env=True),NEWLINE 'CLOUD_BROWSER_GS_SECRET_KEY': Setting(from_env=True),NEWLINENEWLINE # Rackspace datastore settings.NEWLINE 'CLOUD_BROWSER_RACKSPACE_ACCOUNT': Setting(from_env=True),NEWLINE 'CLOUD_BROWSER_RACKSPACE_SECRET_KEY': Setting(from_env=True),NEWLINE 'CLOUD_BROWSER_RACKSPACE_SERVICENET': BoolSetting(from_env=True),NEWLINE 'CLOUD_BROWSER_RACKSPACE_AUTHURL': BoolSetting(from_env=True),NEWLINENEWLINE # Filesystem datastore settings.NEWLINE 'CLOUD_BROWSER_FILESYSTEM_ROOT': Setting(),NEWLINENEWLINE # View permissions.NEWLINE 'CLOUD_BROWSER_VIEW_DECORATOR': Setting(),NEWLINENEWLINE # Permissions lists for containers.NEWLINE 'CLOUD_BROWSER_CONTAINER_WHITELIST': Setting(),NEWLINE 'CLOUD_BROWSER_CONTAINER_BLACKLIST': Setting(),NEWLINENEWLINE # Browser settings.NEWLINE 'CLOUD_BROWSER_DEFAULT_LIST_LIMIT': Setting(default=20),NEWLINENEWLINE # Static media root.NEWLINE 'CLOUD_BROWSER_STATIC_MEDIA_DIR': Setting(),NEWLINE }NEWLINENEWLINE def __init__(self):NEWLINE """Initializer."""NEWLINE self.__container_whitelist = NoneNEWLINE self.__container_blacklist = NoneNEWLINENEWLINE def __getattr__(self, name, default=None):NEWLINE """Get setting."""NEWLINE if name in self.SETTINGS:NEWLINE return self.SETTINGS[name].get(name, default)NEWLINENEWLINE # Use real Django settings.NEWLINE return getattr(_settings, name, default)NEWLINENEWLINE @propertyNEWLINE def _container_whitelist(self):NEWLINE """Container whitelist."""NEWLINE if self.__container_whitelist is None:NEWLINE self.__container_whitelist = \NEWLINE set(self.CLOUD_BROWSER_CONTAINER_WHITELIST or [])NEWLINE return self.__container_whitelistNEWLINENEWLINE @propertyNEWLINE def _container_blacklist(self):NEWLINE """Container blacklist."""NEWLINE if self.__container_blacklist is None:NEWLINE self.__container_blacklist = \NEWLINE set(self.CLOUD_BROWSER_CONTAINER_BLACKLIST or [])NEWLINE return self.__container_blacklistNEWLINENEWLINE def container_permitted(self, name):NEWLINE """Return whether or not a container is permitted.NEWLINENEWLINE :param name: Container name.NEWLINE :return: ``True`` if container is permitted.NEWLINE :rtype: ``bool``NEWLINE """NEWLINE white = self._container_whitelistNEWLINE black = self._container_blacklistNEWLINE return name not in black and (not white or name in white)NEWLINENEWLINE @propertyNEWLINE def app_media_url(self):NEWLINE """Get application media root from real media root URL."""NEWLINE url = NoneNEWLINE media_dir = self.CLOUD_BROWSER_STATIC_MEDIA_DIRNEWLINE if media_dir:NEWLINE url = os.path.join(self.MEDIA_URL, media_dir).rstrip('/') + '/'NEWLINENEWLINE return urlNEWLINENEWLINE @propertyNEWLINE def app_media_doc_root(self): # pylint: disable=R0201NEWLINE """Get application media document (file) root."""NEWLINE app_dir = os.path.abspath(os.path.dirname(__file__))NEWLINE media_root = os.path.join(app_dir, 'media')NEWLINENEWLINE return media_rootNEWLINENEWLINENEWLINEsettings = Settings() # pylint: disable=C0103NEWLINE import platformNEWLINEfrom setuptools import setupNEWLINEfrom setuptools import find_packagesNEWLINEfrom setuptools import ExtensionNEWLINENEWLINENEWLINEextra_compile_args = [NEWLINE '-std=c++11',NEWLINE '-O3',NEWLINE '-Wall',NEWLINE '-Wextra',NEWLINE '-Wconversion',NEWLINE '-fno-strict-aliasing',NEWLINE '-fno-rtti',NEWLINE]NEWLINENEWLINEif platform.system() == 'Darwin':NEWLINE extra_compile_args += ['-mmacosx-version-min=10.7', '-stdlib=libc++']NEWLINENEWLINENEWLINEsetup(NEWLINE name="python-rocksdb",NEWLINE version='0.6.8',NEWLINE description="Python bindings for RocksDB",NEWLINE keywords='rocksdb',NEWLINE author='Ming Hsuan Tu',NEWLINE author_email="qrnnis2623891@gmail.com",NEWLINE url="https://github.com/twmht/python-rocksdb",NEWLINE license='BSD License',NEWLINE setup_requires=['setuptools>=25', 'Cython>=0.20'],NEWLINE install_requires=['setuptools>=25'],NEWLINE package_dir={'rocksdb': 'rocksdb'},NEWLINE packages=find_packages('.'),NEWLINE ext_modules=[Extension(NEWLINE 'rocksdb._rocksdb',NEWLINE ['rocksdb/_rocksdb.pyx'],NEWLINE extra_compile_args=extra_compile_args,NEWLINE language='c++',NEWLINE libraries=['rocksdb', 'snappy', 'bz2', 'zstd', 'lz4'],NEWLINE )],NEWLINE extras_require={NEWLINE "doc": ['sphinx_rtd_theme', 'sphinx'],NEWLINE "test": ['pytest'],NEWLINE },NEWLINE include_package_data=TrueNEWLINE)NEWLINE #!/usr/bin/env python3NEWLINE# -*- coding: utf-8 -*-NEWLINEimport sysNEWLINENEWLINEif __name__ == '__main__':NEWLINE X1 = int(input('Введите x1 '))NEWLINE Y1 = int(input('Введите y1 '))NEWLINE X2 = int(input('Введите x2 '))NEWLINE Y2 = int(input('Введите y2 '))NEWLINENEWLINE if X1 == -X2 and Y1 == -Y2:NEWLINE print('Точки симметричны относительно начала координат')NEWLINE elif X1 == -X2 and Y1 == Y2:NEWLINE print('Точки симметричны относительно оси Y')NEWLINE elif X1 == X2 and Y1 == -Y2:NEWLINE print('Точки симметричны относительно оси X')NEWLINE else:NEWLINE print('Точки не симметричны', file=sys.stderr)NEWLINE exit(1)NEWLINE # -*- coding: utf-8 -*-NEWLINEimport osNEWLINEimport sysNEWLINENEWLINEcmd = 'coverage run `which djangocms-helper` aldryn_boilerplates test --cms --extra-settings=test_settings'NEWLINENEWLINEsys.exit(os.system(cmd))NEWLINE # MIT LICENSENEWLINE#NEWLINE# Copyright 1997 - 2020 by IXIA KeysightNEWLINE#NEWLINE# Permission is hereby granted, free of charge, to any person obtaining a copyNEWLINE# of this software and associated documentation files (the "Software"),NEWLINE# to deal in the Software without restriction, including without limitationNEWLINE# the rights to use, copy, modify, merge, publish, distribute, sublicense,NEWLINE# and/or sell copies of the Software, and to permit persons to whom theNEWLINE# Software is furnished to do so, subject to the following conditions:NEWLINE#NEWLINE# The above copyright notice and this permission notice shall be included inNEWLINE# all copies or substantial portions of the Software.NEWLINE#NEWLINE# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORNEWLINE# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,NEWLINE# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THENEWLINE# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERNEWLINE# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,NEWLINE# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INNEWLINE# THE SOFTWARE. NEWLINEfrom ixnetwork_restpy.base import BaseNEWLINEfrom ixnetwork_restpy.files import FilesNEWLINENEWLINENEWLINEclass SubTlv(Base):NEWLINE """Sub Tlv containerNEWLINE The SubTlv class encapsulates a list of subTlv resources that are managed by the system.NEWLINE A list of resources can be retrieved from the server using the SubTlv.find() method.NEWLINE """NEWLINENEWLINE __slots__ = ()NEWLINE _SDM_NAME = 'subTlv'NEWLINE _SDM_ATT_MAP = {NEWLINE 'Description': 'description',NEWLINE 'EnablePerSession': 'enablePerSession',NEWLINE 'IsEnabled': 'isEnabled',NEWLINE 'Name': 'name',NEWLINE }NEWLINENEWLINE def __init__(self, parent):NEWLINE super(SubTlv, self).__init__(parent)NEWLINENEWLINE @propertyNEWLINE def Value(self):NEWLINE """NEWLINE ReturnsNEWLINE -------NEWLINE - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.tlvprofile.value_ac1d7b13584a86b9cf1c28dca3390bca.Value): An instance of the Value classNEWLINENEWLINE RaisesNEWLINE ------NEWLINE - ServerError: The server has encountered an uncategorized error conditionNEWLINE """NEWLINE from ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.tlvprofile.value_ac1d7b13584a86b9cf1c28dca3390bca import ValueNEWLINE return Value(self)._select()NEWLINENEWLINE @propertyNEWLINE def Description(self):NEWLINE """NEWLINE ReturnsNEWLINE -------NEWLINE - str: Description of the tlvNEWLINE """NEWLINE return self._get_attribute(self._SDM_ATT_MAP['Description'])NEWLINE @Description.setterNEWLINE def Description(self, value):NEWLINE self._set_attribute(self._SDM_ATT_MAP['Description'], value)NEWLINENEWLINE @propertyNEWLINE def EnablePerSession(self):NEWLINE """NEWLINE ReturnsNEWLINE -------NEWLINE - obj(ixnetwork_restpy.multivalue.Multivalue): Enable TLV per sessionNEWLINE """NEWLINE from ixnetwork_restpy.multivalue import MultivalueNEWLINE return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnablePerSession']))NEWLINENEWLINE @propertyNEWLINE def IsEnabled(self):NEWLINE """NEWLINE ReturnsNEWLINE -------NEWLINE - bool: Enables/disables this tlvNEWLINE """NEWLINE return self._get_attribute(self._SDM_ATT_MAP['IsEnabled'])NEWLINE @IsEnabled.setterNEWLINE def IsEnabled(self, value):NEWLINE self._set_attribute(self._SDM_ATT_MAP['IsEnabled'], value)NEWLINENEWLINE @propertyNEWLINE def Name(self):NEWLINE """NEWLINE ReturnsNEWLINE -------NEWLINE - str: Name of the tlvNEWLINE """NEWLINE return self._get_attribute(self._SDM_ATT_MAP['Name'])NEWLINE @Name.setterNEWLINE def Name(self, value):NEWLINE self._set_attribute(self._SDM_ATT_MAP['Name'], value)NEWLINENEWLINE def update(self, Description=None, IsEnabled=None, Name=None):NEWLINE """Updates subTlv resource on the server.NEWLINENEWLINE This method has some named parameters with a type: obj (Multivalue).NEWLINE The Multivalue class has documentation that details the possible values for those named parameters.NEWLINENEWLINE ArgsNEWLINE ----NEWLINE - Description (str): Description of the tlvNEWLINE - IsEnabled (bool): Enables/disables this tlvNEWLINE - Name (str): Name of the tlvNEWLINENEWLINE RaisesNEWLINE ------NEWLINE - ServerError: The server has encountered an uncategorized error conditionNEWLINE """NEWLINE return self._update(self._map_locals(self._SDM_ATT_MAP, locals()))NEWLINENEWLINE def find(self, Description=None, IsEnabled=None, Name=None):NEWLINE """Finds and retrieves subTlv resources from the server.NEWLINENEWLINE All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve subTlv resources from the server.NEWLINE To retrieve an exact match ensure the parameter value starts with ^ and ends with $NEWLINE By default the find method takes no parameters and will retrieve all subTlv resources from the server.NEWLINENEWLINE ArgsNEWLINE ----NEWLINE - Description (str): Description of the tlvNEWLINE - IsEnabled (bool): Enables/disables this tlvNEWLINE - Name (str): Name of the tlvNEWLINENEWLINE ReturnsNEWLINE -------NEWLINE - self: This instance with matching subTlv resources retrieved from the server available through an iterator or indexNEWLINENEWLINE RaisesNEWLINE ------NEWLINE - ServerError: The server has encountered an uncategorized error conditionNEWLINE """NEWLINE return self._select(self._map_locals(self._SDM_ATT_MAP, locals()))NEWLINENEWLINE def read(self, href):NEWLINE """Retrieves a single instance of subTlv data from the server.NEWLINENEWLINE ArgsNEWLINE ----NEWLINE - href (str): An href to the instance to be retrievedNEWLINENEWLINE ReturnsNEWLINE -------NEWLINE - self: This instance with the subTlv resources from the server available through an iterator or indexNEWLINENEWLINE RaisesNEWLINE ------NEWLINE - NotFoundError: The requested resource does not exist on the serverNEWLINE - ServerError: The server has encountered an uncategorized error conditionNEWLINE """NEWLINE return self._read(href)NEWLINENEWLINE def get_device_ids(self, PortNames=None, EnablePerSession=None):NEWLINE """Base class infrastructure that gets a list of subTlv device ids encapsulated by this object.NEWLINENEWLINE Use the optional regex parameters in the method to refine the list of device ids encapsulated by this object.NEWLINENEWLINE ArgsNEWLINE ----NEWLINE - PortNames (str): optional regex of port namesNEWLINE - EnablePerSession (str): optional regex of enablePerSessionNEWLINENEWLINE ReturnsNEWLINE -------NEWLINE - list(int): A list of device ids that meets the regex criteria provided in the method parametersNEWLINENEWLINE RaisesNEWLINE ------NEWLINE - ServerError: The server has encountered an uncategorized error conditionNEWLINE """NEWLINE return self._get_ngpf_device_ids(locals())NEWLINE def to_binary(int_digit, length=4):NEWLINE """Convert a digit into binary string.NEWLINENEWLINE Arguments:NEWLINE int_digit {str} -- the digit needed to be convertNEWLINENEWLINE Keyword Arguments:NEWLINE length {int} -- length of converted string (default: {4})NEWLINENEWLINE Returns:NEWLINE str -- a string with specific length converted from intNEWLINENEWLINE """NEWLINE format_str = '{:0>%ds}' % lengthNEWLINE return format_str.format(bin(int(int_digit))[2:])NEWLINENEWLINENEWLINEdef checkio(data):NEWLINE data = ['{:0>2s}'.format(i) for i in data.split(':')]NEWLINE bin_data = [[to_binary(i[0], 3), to_binary(i[1])] for i in data]NEWLINE bin_data = list(map(lambda x: ' '.join(x), bin_data))NEWLINE bin_data = ' : '.join(bin_data)NEWLINE return bin_data.replace('0', '.').replace('1', '-')[1:]NEWLINENEWLINENEWLINE# These "asserts" using only for self-checkingNEWLINE# and not necessary for auto-testingNEWLINEif __name__ == '__main__':NEWLINE assert checkio("10:37:49") == ".- .... : .-- .--- : -.. -..-", "First Test"NEWLINE assert checkio("21:34:56") == "-. ...- : .-- .-.. : -.- .--.", "Second Test"NEWLINE assert checkio("11:10:12") == ".- ...- : ..- .... : ..- ..-.", "Third Test"NEWLINE assert checkio("23:59:59") == "-. ..-- : -.- -..- : -.- -..-", "Fourth Test"NEWLINE # import the generic views you want, and the models NEWLINE# they apply to.NEWLINEfrom django.views.generic import ListViewNEWLINENEWLINE# Import the models you want to use.NEWLINEfrom snippets.models import SnippetNEWLINENEWLINE# Create a class for your model that subclassesNEWLINE# the generic view you want. This serves as anNEWLINE# index view.NEWLINEclass SnippetListView(ListView):NEWLINE # Finally, tell the generic view what modelNEWLINE # it applies to, and which template to use.NEWLINE model = SnippetNEWLINE template_name = 'snippets/index.html'NEWLINENEWLINE# ==============================================NEWLINENEWLINE# In your urls.py, you'll need to update the NEWLINE# corresponding route. It'll look like this.NEWLINEurls(r'^index/$', views.SnippetListView.as_view())NEWLINE words =[ "aback","abaft","abandoned","abashed","aberrant","abhorrent","abiding","abject","ablaze","able","abnormal","aboard","aboriginal","abortive","abounding","abrasive","abrupt","absent","absorbed","absorbing","abstracted","absurd","abundant","abusive","accept","acceptable","accessible","accidental","account","accurate","achiever","acid","acidic","acoustic","acoustics","acrid","act","action","activity","actor","actually","ad hoc","adamant","adaptable","add","addicted","addition","adhesive","adjoining","adjustment","admire","admit","adorable","adventurous","advertisement","advice","advise","afford","afraid","aftermath","afternoon","afterthought","aggressive","agonizing","agree","agreeable","agreement","ahead","air","airplane","airport","ajar","alarm","alcoholic","alert","alike","alive","alleged","allow","alluring","aloof","amazing","ambiguous","ambitious","amount","amuck","amuse","amused","amusement","amusing","analyze","ancient","anger","angle","angry","animal","animated","announce","annoy","annoyed","annoying","answer","ants","anxious","apathetic","apologise","apparatus","apparel","appear","applaud","appliance","appreciate","approval","approve","aquatic","arch","argue","argument","arithmetic","arm","army","aromatic","arrange","arrest","arrive","arrogant","art","ashamed","ask","aspiring","assorted","astonishing","attach","attack","attempt","attend","attract","attraction","attractive","aunt","auspicious","authority","automatic","available","average","avoid","awake","aware","awesome","awful","axiomatic","babies","baby","back","bad","badge","bag","bait","bake","balance","ball","ban","bang","barbarous","bare","base","baseball","bashful","basin","basket","basketball","bat","bath","bathe","battle","bawdy","bead","beam","bear","beautiful","bed","bedroom","beds","bee","beef","befitting","beg","beginner","behave","behavior","belief","believe","bell","belligerent","bells","belong","beneficial","bent","berry","berserk","best","better","bewildered","big","bike","bikes","billowy","bird","birds","birth","birthday","bit","bite","bite-sized","bitter","bizarre","black","black-and-white","blade","bleach","bless","blind","blink","blood","bloody","blot","blow","blue","blue-eyed","blush","blushing","board","boast","boat","boil","boiling","bolt","bomb","bone","book","books","boorish","boot","border","bore","bored","boring","borrow","bottle","bounce","bouncy","boundary","boundless","bow","box","boy","brainy","brake","branch","brash","brass","brave","brawny","breakable","breath","breathe","breezy","brick","bridge","brief","bright","broad","broken","brother","brown","bruise","brush","bubble","bucket","building","bulb","bump","bumpy","burly","burn","burst","bury","bushes","business","bustling","busy","butter","button","buzz","cabbage","cable","cactus","cagey","cake","cakes","calculate","calculating","calculator","calendar","call","callous","calm","camera","camp","can","cannon","canvas","cap","capable","capricious","caption","car","card","care","careful","careless","caring","carpenter","carriage","carry","cars","cart","carve","cast","cat","cats","cattle","cause","cautious","cave","ceaseless","celery","cellar","cemetery","cent","certain","chalk","challenge","chance","change","changeable","channel","charge","charming","chase","cheap","cheat","check","cheer","cheerful","cheese","chemical","cherries","cherry","chess","chew","chicken","chickens","chief","childlike","children","chilly","chin","chivalrous","choke","chop","chubby","chunky","church","circle","claim","clam","clammy","clap","class","classy","clean","clear","clever","clip","cloistered","close","closed","cloth","cloudy","clover","club","clumsy","cluttered","coach","coal","coast","coat","cobweb","coherent","coil","cold","collar","collect","color","colorful","colossal","colour","comb","combative","comfortable","command","committee","common","communicate","company","compare","comparison","compete","competition","complain","complete","complex","concentrate","concern","concerned","condemned","condition","confess","confuse","confused","connect","connection","conscious","consider","consist","contain","continue","control","cooing","cook","cool","cooperative","coordinated","copper","copy","corn","correct","cough","count","country","courageous","cover","cow","cowardly","cows","crabby","crack","cracker","crash","crate","craven","crawl","crayon","crazy","cream","creator","creature","credit","creepy","crib","crime","crook","crooked","cross","crow","crowd","crowded","crown","cruel","crush","cry","cub","cuddly","cultured","cumbersome","cup","cure","curious","curl","curly","current","curtain","curve","curved","curvy","cushion","cut","cute","cycle","cynical","dad","daffy","daily","dam","damage","damaged","damaging","damp","dance","dangerous","dapper","dare","dark","dashing","daughter","day","dazzling","dead","deadpan","deafening","dear","death","debonair","debt","decay","deceive","decide","decision","decisive","decorate","decorous","deep","deeply","deer","defeated","defective","defiant","degree","delay","delicate","delicious","delight","delightful","delirious","deliver","demonic","depend","dependent","depressed","deranged","describe","descriptive","desert","deserted","deserve","design","desire","desk","destroy","destruction","detail","detailed","detect","determined","develop","development","devilish","didactic","different","difficult","digestion","diligent","dime","dinner","dinosaurs","direction","direful","dirt","dirty","disagree","disagreeable","disappear","disapprove","disarm","disastrous","discover","discovery","discreet","discussion","disgusted","disgusting","disillusioned","dislike","dispensable","distance","distinct","distribution","disturbed","divergent","divide","division","dizzy","dock","doctor","dog","dogs","doll","dolls","domineering","donkey","door","double","doubt","doubtful","downtown","drab","draconian","drag","drain","dramatic","drawer","dream","dreary","dress","drink","drip","driving","drop","drown","drum","drunk","dry","duck","ducks","dull","dust","dusty","dynamic","dysfunctional","eager","ear","early","earn","earsplitting","earth","earthquake","earthy","easy","eatable","economic","edge","educate","educated","education","effect","efficacious","efficient","egg","eggnog","eggs","eight","elastic","elated","elbow","elderly","electric","elegant","elfin","elite","embarrass","embarrassed","eminent","employ","empty","enchanted","enchanting","encourage","encouraging","end","endurable","energetic","engine","enjoy","enormous","enter","entertain","entertaining","enthusiastic","envious","equable","equal","erect","erratic","error","escape","ethereal","evanescent","evasive","even","event","examine","example","excellent","exchange","excite","excited","exciting","exclusive","excuse","exercise","exist","existence","exotic","expand","expansion","expect","expensive","experience","expert","explain","explode","extend","extra-large","extra-small","exuberant","exultant","eye","eyes","fabulous","face","fact","fade","faded","fail","faint","fair","fairies","faithful","fall","fallacious","false","familiar","famous","fanatical","fancy","fang","fantastic","far","far-flung","farm","fascinated","fast","fasten","fat","faulty","fax","fear","fearful","fearless","feeble","feeling","feigned","female","fence","fertile","festive","fetch","few","field","fierce","file","fill","film","filthy","fine","finger","finicky","fire","fireman","first","fish","fit","five","fix","fixed","flag","flagrant","flaky","flame","flap","flash","flashy","flat","flavor","flawless","flesh","flight","flimsy","flippant","float","flock","flood","floor","flow","flower","flowers","flowery","fluffy","fluttering","fly","foamy","fog","fold","follow","food","fool","foolish","foot","force","foregoing","forgetful","fork","form","fortunate","found","four","fowl","fragile","frail","frame","frantic","free","freezing","frequent","fresh","fretful","friction","friend","friendly","friends","frighten","frightened","frightening","frog","frogs","front","fruit","fry","fuel","full","fumbling","functional","funny","furniture","furry","furtive","future","futuristic","fuzzy","gabby","gainful","gamy","gaping","garrulous","gate","gather","gaudy","gaze","geese","general","gentle","ghost","giant","giants","giddy","gifted","gigantic","giraffe","girl","girls","glamorous","glass","gleaming","glib","glistening","glorious","glossy","glove","glow","glue","godly","gold","good","goofy","gorgeous","government","governor","grab","graceful","grade","grain","grandfather","grandiose","grandmother","grape","grass","grate","grateful","gratis","gray","grease","greasy","great","greedy","green","greet","grey","grieving","grin","grip","groan","groovy","grotesque","grouchy","ground","group","growth","grubby","gruesome","grumpy","guarantee","guard","guarded","guess","guide","guiltless","guitar","gullible","gun","gusty","guttural","habitual","hair","haircut","half","hall","hallowed","halting","hammer","hand","handle","hands","handsome","handsomely","handy","hang","hanging","hapless","happen","happy","harass","harbor","hard","hard-to-find","harm","harmonious","harmony","harsh","hat","hate","hateful","haunt","head","heady","heal","health","healthy","heap","heartbreaking","heat","heavenly","heavy","hellish","help","helpful","helpless","hesitant","hideous","high","high-pitched","highfalutin","hilarious","hill","hissing","historical","history","hobbies","hole","holiday","holistic","hollow","home","homeless","homely","honey","honorable","hook","hop","hope","horn","horrible","horse","horses","hose","hospitable","hospital","hot","hour","house","houses","hover","hug","huge","hulking","hum","humdrum","humor","humorous","hungry","hunt","hurried","hurry","hurt","hushed","husky","hydrant","hypnotic","hysterical","ice","icicle","icky","icy","idea","identify","idiotic","ignorant","ignore","ill","ill-fated","ill-informed","illegal","illustrious","imaginary","imagine","immense","imminent","impartial","imperfect","impolite","important","imported","impossible","impress","improve","impulse","incandescent","include","income","incompetent","inconclusive","increase","incredible","industrious","industry","inexpensive","infamous","influence","inform","inject","injure","ink","innate","innocent","inquisitive","insect","insidious","instinctive","instruct","instrument","insurance","intelligent","intend","interest","interesting","interfere","internal","interrupt","introduce","invent","invention","invincible","invite","irate","iron","irritate","irritating","island","itch","itchy","jaded","jagged","jail","jam","jar","jazzy","jealous","jeans","jelly","jellyfish","jewel","jittery","jobless","jog","join","joke","jolly","joyous","judge","judicious","juggle","juice","juicy","jumbled","jump","jumpy","juvenile","kaput","keen","kettle","key","kick","kill","kind","kindhearted","kindly","kiss","kittens","kitty","knee","kneel","knife","knit","knock","knot","knotty","knowing","knowledge","knowledgeable","known","label","labored","laborer","lace","lackadaisical","lacking","ladybug","lake","lame","lamentable","lamp","land","language","languid","large","last","late","laugh","laughable","launch","lavish","lazy","lean","learn","learned","leather","left","leg","legal","legs","lethal","letter","letters","lettuce","level","lewd","library","license","lick","lie","light","lighten","like","likeable","limit","limping","line","linen","lip","liquid","list","listen","literate","little","live","lively","living","load","loaf","lock","locket","lonely","long","long-term","longing","look","loose","lopsided","loss","loud","loutish","love","lovely","loving","low","lowly","lucky","ludicrous","lumber","lumpy","lunch","lunchroom","lush","luxuriant","lying","lyrical","macabre","machine","macho","maddening","madly","magenta","magic","magical","magnificent","maid","mailbox","majestic","makeshift","male","malicious","mammoth","man","manage","maniacal","many","marble","march","mark","marked","market","married","marry","marvelous","mask","mass","massive","match","mate","material","materialistic","matter","mature","meal","mean","measly","measure","meat","meaty","meddle","medical","meek","meeting","mellow","melodic","melt","melted","memorize","memory","men","mend","merciful","mere","mess up","messy","metal","mice","middle","mighty","military","milk","milky","mind","mindless","mine","miniature","minister","minor","mint","minute","miscreant","miss","mist","misty","mitten","mix","mixed","moan","moaning","modern","moldy","mom","momentous","money","monkey","month","moon","moor","morning","mother","motion","motionless","mountain","mountainous","mourn","mouth","move","muddle","muddled","mug","multiply","mundane","murder","murky","muscle","mushy","mute","mysterious","nail","naive","name","nappy","narrow","nasty","nation","natural","naughty","nauseating","near","neat","nebulous","necessary","neck","need","needle","needless","needy","neighborly","nerve","nervous","nest","new","next","nice","nifty","night","nimble","nine","nippy","nod","noise","noiseless","noisy","nonchalant","nondescript","nonstop","normal","north","nose","nostalgic","nosy","note","notebook","notice","noxious","null","number","numberless","numerous","nut","nutritious","nutty","oafish","oatmeal","obedient","obeisant","obese","obey","object","obnoxious","obscene","obsequious","observant","observation","observe","obsolete","obtain","obtainable","occur","ocean","oceanic","odd","offbeat","offend","offer","office","oil","old","old-fashioned","omniscient","one","onerous","open","opposite","optimal","orange","oranges","order","ordinary","organic","ossified","outgoing","outrageous","outstanding","oval","oven","overconfident","overflow","overjoyed","overrated","overt","overwrought","owe","own","pack","paddle","page","pail","painful","painstaking","paint","pale","paltry","pan","pancake","panicky","panoramic","paper","parallel","parcel","parched","park","parsimonious","part","partner","party","pass","passenger","past","paste","pastoral","pat","pathetic","pause","payment","peace","peaceful","pear","peck","pedal","peel","peep","pen","pencil","penitent","perfect","perform","periodic","permissible","permit","perpetual","person","pest","pet","petite","pets","phobic","phone","physical","picayune","pick","pickle","picture","pie","pies","pig","pigs","pin","pinch","pine","pink","pipe","piquant","pizzas","place","placid","plain","plan","plane","planes","plant","plantation","plants","plastic","plate","plausible","play","playground","pleasant","please","pleasure","plot","plough","plucky","plug","pocket","point","pointless","poised","poison","poke","polish","polite","political","pollution","poor","pop","popcorn","porter","position","possess","possessive","possible","post","pot","potato","pour","powder","power","powerful","practice","pray","preach","precede","precious","prefer","premium","prepare","present","preserve","press","pretend","pretty","prevent","previous","price","pricey","prick","prickly","print","private","probable","produce","productive","profit","profuse","program","promise","property","prose","protect","protective","protest","proud","provide","psychedelic","psychotic","public","puffy","pull","pump","pumped","punch","puncture","punish","punishment","puny","purple","purpose","purring","push","pushy","puzzled","puzzling","quack","quaint","quarrelsome","quarter","quartz","queen","question","questionable","queue","quick","quickest","quicksand","quiet","quill","quilt","quince","quirky","quiver","quixotic","quizzical","rabbit","rabbits","rabid","race","racial","radiate","ragged","rail","railway","rain","rainstorm","rainy","raise","rake","rambunctious","rampant","range","rapid","rare","raspy","rat","rate","ratty","ray","reach","reaction","reading","ready","real","realize","reason","rebel","receipt","receive","receptive","recess","recognise","recondite","record","red","reduce","redundant","reflect","reflective","refuse","regret","regular","reign","reject","rejoice","relation","relax","release","relieved","religion","rely","remain","remarkable","remember","remind","reminiscent","remove","repair","repeat","replace","reply","report","representative","reproduce","repulsive","request","rescue","resolute","resonant","respect","responsible","rest","retire","return","reward","rhetorical","rhyme","rhythm","rice","rich","riddle","rifle","right","righteous","rightful","rigid","ring","rings","rinse","ripe","risk","ritzy","river","road","roasted","rob","robin","robust","rock","rod","roll","romantic","roof","room","roomy","root","rose","rot","rotten","rough","round","route","royal","rub","ruddy","rude","ruin","rule","run","rural","rush","rustic","ruthless","sable","sack","sad","safe","sail","salt","salty","same","sand","sassy","satisfy","satisfying","save","savory","saw","scale","scandalous","scarce","scare","scarecrow","scared","scarf","scary","scatter","scattered","scene","scent","school","science","scientific","scintillating","scissors","scold","scorch","scrape","scratch","scrawny","scream","screeching","screw","scribble","scrub","sea","seal","search","seashore","seat","second","second-hand","secret","secretary","secretive","sedate","seed","seemly","selection","selective","self","selfish","sense","separate","serious","servant","serve","settle","shade","shaggy","shake","shaky","shallow","shame","shape","share","sharp","shave","sheep","sheet","shelf","shelter","shiny","ship","shirt","shiver","shivering","shock","shocking","shoe","shoes","shop","short","show","shrill","shrug","shut","shy","sick","side","sidewalk","sigh","sign","signal","silent","silk","silky","silly","silver","simple","simplistic","sin","sincere","sink","sip","sister","sisters","six","size","skate","ski","skillful","skin","skinny","skip","skirt","sky","slap","slave","sleep","sleepy","sleet","slim","slimy","slip","slippery","slope","sloppy","slow","small","smart","smash","smell","smelly","smile","smiling","smoggy","smoke","smooth","snail","snails","snake","snakes","snatch","sneaky","sneeze","sniff","snobbish","snore","snotty","snow","soak","soap","society","sock","soda","sofa","soft","soggy","solid","somber","son","song","songs","soothe","sophisticated","sordid","sore","sort","sound","soup","sour","space","spade","spare","spark","sparkle","sparkling","special","spectacular","spell","spicy","spiders","spiffy","spiky","spill","spiritual","spiteful","splendid","spoil","sponge","spooky","spoon","spot","spotless","spotted","spotty","spray","spring","sprout","spurious","spy","squalid","square","squash","squeak","squeal","squealing","squeamish","squeeze","squirrel","stage","stain","staking","stale","stamp","standing","star","stare","start","statement","station","statuesque","stay","steadfast","steady","steam","steel","steep","steer","stem","step","stereotyped","stew","stick","sticks","sticky","stiff","stimulating","stingy","stir","stitch","stocking","stomach","stone","stop","store","stormy","story","stove","straight","strange","stranger","strap","straw","stream","street","strengthen","stretch","string","strip","striped","stroke","strong","structure","stuff","stupendous","stupid","sturdy","subdued","subsequent","substance","substantial","subtract","succeed","successful","succinct","suck","sudden","suffer","sugar","suggest","suggestion","suit","sulky","summer","sun","super","superb","superficial","supply","support","suppose","supreme","surprise","surround","suspect","suspend","swanky","sweater","sweet","sweltering","swift","swim","swing","switch","symptomatic","synonymous","system","table","taboo","tacit","tacky","tail","talented","talk","tall","tame","tan","tangible","tangy","tank","tap","tart","taste","tasteful","tasteless","tasty","tawdry","tax","teaching","team","tearful","tease","tedious","teeny","teeny-tiny","teeth","telephone","telling","temper","temporary","tempt","ten","tendency","tender","tense","tent","tenuous","terrible","terrific","terrify","territory","test","tested","testy","texture","thank","thankful","thaw","theory","therapeutic","thick","thin","thing","things","thinkable","third","thirsty","thought","thoughtful","thoughtless","thread","threatening","three","thrill","throat","throne","thumb","thunder","thundering","tick","ticket","tickle","tidy","tie","tiger","tight","tightfisted","time","tin","tiny","tip","tire","tired","tiresome","title","toad","toe","toes","tomatoes","tongue","tooth","toothbrush","toothpaste","toothsome","top","torpid","touch","tough","tour","tow","towering","town","toy","toys","trace","trade","trail","train","trains","tramp","tranquil","transport","trap","trashy","travel","tray","treat","treatment","tree","trees","tremble","tremendous","trick","tricky","trip","trite","trot","trouble","troubled","trousers","truck","trucks","truculent","true","trust","truthful","try","tub","tug","tumble","turkey","turn","twig","twist","two","type","typical","ubiquitous","ugliest","ugly","ultra","umbrella","unable","unaccountable","unadvised","unarmed","unbecoming","unbiased","uncle","uncovered","understood","underwear","undesirable","undress","unequal","unequaled","uneven","unfasten","unhealthy","uninterested","unique","unit","unite","unkempt","unknown","unlock","unnatural","unpack","unruly","unsightly","unsuitable","untidy","unused","unusual","unwieldy","unwritten","upbeat","uppity","upset","uptight","use","used","useful","useless","utopian","utter","uttermost","vacation","vacuous","vagabond","vague","valuable","value","van","vanish","various","vase","vast","vegetable","veil","vein","vengeful","venomous","verdant","verse","versed","vessel","vest","victorious","view","vigorous","violent","violet","visit","visitor","vivacious","voice","voiceless","volatile","volcano","volleyball","voracious","voyage","vulgar","wacky","waggish","wail","wait","waiting","wakeful","walk","wall","wander","wandering","want","wanting","war","warlike","warm","warn","wary","wash","waste","wasteful","watch","water","watery","wave","waves","wax","way","weak","wealth","wealthy","weary","weather","week","weigh","weight","welcome","well-groomed","well-made","well-off","well-to-do","wet","wheel","whimsical","whine","whip","whirl","whisper","whispering","whistle","white","whole","wholesale","wicked","wide","wide-eyed","wiggly","wild","wilderness","willing","wind","window","windy","wine","wing","wink","winter","wipe","wire","wiry","wise","wish","wistful","witty","wobble","woebegone","woman","womanly","women","wonder","wonderful","wood","wooden","wool","woozy","word","work","workable","worm","worried","worry","worthless","wound","wrap","wrathful","wreck","wren","wrench","wrestle","wretched","wriggle","wrist","writer","writing","wrong","wry","x-ray","yak","yam","yard","yarn","yawn","year","yell","yellow","yielding","yoke","young","youthful","yummy","zany","zealous","zebra","zephyr","zesty","zinc","zip","zipper","zippy","zonked","zoo","zoom"]NEWLINE import osNEWLINEimport timeNEWLINEimport statNEWLINEimport jsonNEWLINEimport zlibNEWLINEimport typingNEWLINEfrom typing import List, Sequence, MutableSequence, OptionalNEWLINEfrom collections import UserDictNEWLINEfrom hashlib import sha256NEWLINEfrom operator import attrgetterNEWLINEfrom torba.client.hash import better_aes_encrypt, better_aes_decryptNEWLINENEWLINEif typing.TYPE_CHECKING:NEWLINE from torba.client import basemanager, baseaccount, baseledgerNEWLINENEWLINENEWLINEclass TimestampedPreferences(UserDict):NEWLINENEWLINE def __getitem__(self, key):NEWLINE return self.data[key]['value']NEWLINENEWLINE def __setitem__(self, key, value):NEWLINE self.data[key] = {NEWLINE 'value': value,NEWLINE 'ts': time.time()NEWLINE }NEWLINENEWLINE def __repr__(self):NEWLINE return repr(self.to_dict_without_ts())NEWLINENEWLINE def to_dict_without_ts(self):NEWLINE return {NEWLINE key: value['value'] for key, value in self.data.items()NEWLINE }NEWLINENEWLINE @propertyNEWLINE def hash(self):NEWLINE return sha256(json.dumps(self.data).encode()).digest()NEWLINENEWLINE def merge(self, other: dict):NEWLINE for key, value in other.items():NEWLINE if key in self.data and value['ts'] < self.data[key]['ts']:NEWLINE continueNEWLINE self.data[key] = valueNEWLINENEWLINENEWLINEclass Wallet:NEWLINE """ The primary role of Wallet is to encapsulate a collectionNEWLINE of accounts (seed/private keys) and the spending rules / settingsNEWLINE for the coins attached to those accounts. Wallets are representedNEWLINE by physical files on the filesystem.NEWLINE """NEWLINENEWLINE preferences: TimestampedPreferencesNEWLINENEWLINE def __init__(self, name: str = 'Wallet', accounts: MutableSequence['baseaccount.BaseAccount'] = None,NEWLINE storage: 'WalletStorage' = None, preferences: dict = None) -> None:NEWLINE self.name = nameNEWLINE self.accounts = accounts or []NEWLINE self.storage = storage or WalletStorage()NEWLINE self.preferences = TimestampedPreferences(preferences or {})NEWLINENEWLINE @propertyNEWLINE def id(self):NEWLINE if self.storage.path:NEWLINE return os.path.basename(self.storage.path)NEWLINE return self.nameNEWLINENEWLINE def add_account(self, account: 'baseaccount.BaseAccount'):NEWLINE self.accounts.append(account)NEWLINENEWLINE def generate_account(self, ledger: 'baseledger.BaseLedger') -> 'baseaccount.BaseAccount':NEWLINE return ledger.account_class.generate(ledger, self)NEWLINENEWLINE @propertyNEWLINE def default_account(self) -> Optional['baseaccount.BaseAccount']:NEWLINE for account in self.accounts:NEWLINE return accountNEWLINE return NoneNEWLINENEWLINE def get_account_or_default(self, account_id: str) -> Optional['baseaccount.BaseAccount']:NEWLINE if account_id is None:NEWLINE return self.default_accountNEWLINE return self.get_account_or_error(account_id)NEWLINENEWLINE def get_account_or_error(self, account_id: str) -> 'baseaccount.BaseAccount':NEWLINE for account in self.accounts:NEWLINE if account.id == account_id:NEWLINE return accountNEWLINE raise ValueError(f"Couldn't find account: {account_id}.")NEWLINENEWLINE def get_accounts_or_all(self, account_ids: List[str]) -> Sequence['baseaccount.BaseAccount']:NEWLINE return [NEWLINE self.get_account_or_error(account_id)NEWLINE for account_id in account_idsNEWLINE ] if account_ids else self.accountsNEWLINENEWLINE async def get_detailed_accounts(self, **kwargs):NEWLINE ledgers = {}NEWLINE for i, account in enumerate(self.accounts):NEWLINE details = await account.get_details(**kwargs)NEWLINE details['is_default'] = i == 0NEWLINE ledger_id = account.ledger.get_id()NEWLINE ledgers.setdefault(ledger_id, [])NEWLINE ledgers[ledger_id].append(details)NEWLINE return ledgersNEWLINENEWLINE @classmethodNEWLINE def from_storage(cls, storage: 'WalletStorage', manager: 'basemanager.BaseWalletManager') -> 'Wallet':NEWLINE json_dict = storage.read()NEWLINE wallet = cls(NEWLINE name=json_dict.get('name', 'Wallet'),NEWLINE preferences=json_dict.get('preferences', {}),NEWLINE storage=storageNEWLINE )NEWLINE account_dicts: Sequence[dict] = json_dict.get('accounts', [])NEWLINE for account_dict in account_dicts:NEWLINE ledger = manager.get_or_create_ledger(account_dict['ledger'])NEWLINE ledger.account_class.from_dict(ledger, wallet, account_dict)NEWLINE return walletNEWLINENEWLINE def to_dict(self):NEWLINE return {NEWLINE 'version': WalletStorage.LATEST_VERSION,NEWLINE 'name': self.name,NEWLINE 'preferences': self.preferences.data,NEWLINE 'accounts': [a.to_dict() for a in self.accounts]NEWLINE }NEWLINENEWLINE def save(self):NEWLINE self.storage.write(self.to_dict())NEWLINENEWLINE @propertyNEWLINE def hash(self) -> bytes:NEWLINE h = sha256()NEWLINE h.update(self.preferences.hash)NEWLINE for account in sorted(self.accounts, key=attrgetter('id')):NEWLINE h.update(account.hash)NEWLINE return h.digest()NEWLINENEWLINE def pack(self, password):NEWLINE new_data = json.dumps(self.to_dict())NEWLINE new_data_compressed = zlib.compress(new_data.encode())NEWLINE return better_aes_encrypt(password, new_data_compressed)NEWLINENEWLINE @classmethodNEWLINE def unpack(cls, password, encrypted):NEWLINE decrypted = better_aes_decrypt(password, encrypted)NEWLINE decompressed = zlib.decompress(decrypted)NEWLINE return json.loads(decompressed)NEWLINENEWLINE def merge(self, manager: 'basemanager.BaseWalletManager',NEWLINE password: str, data: str) -> List['baseaccount.BaseAccount']:NEWLINE added_accounts = []NEWLINE decrypted_data = self.unpack(password, data)NEWLINE self.preferences.merge(decrypted_data.get('preferences', {}))NEWLINE for account_dict in decrypted_data['accounts']:NEWLINE ledger = manager.get_or_create_ledger(account_dict['ledger'])NEWLINE _, _, pubkey = ledger.account_class.keys_from_dict(ledger, account_dict)NEWLINE account_id = pubkey.addressNEWLINE local_match = NoneNEWLINE for local_account in self.accounts:NEWLINE if account_id == local_account.id:NEWLINE local_match = local_accountNEWLINE breakNEWLINE if local_match is not None:NEWLINE local_match.merge(account_dict)NEWLINE else:NEWLINE new_account = ledger.account_class.from_dict(ledger, self, account_dict)NEWLINE added_accounts.append(new_account)NEWLINE return added_accountsNEWLINENEWLINE @propertyNEWLINE def is_locked(self) -> bool:NEWLINE for account in self.accounts:NEWLINE if account.encrypted:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINE def unlock(self, password):NEWLINE for account in self.accounts:NEWLINE if account.encrypted:NEWLINE account.decrypt(password)NEWLINE return TrueNEWLINENEWLINE def lock(self):NEWLINE for account in self.accounts:NEWLINE if not account.encrypted:NEWLINE assert account.password is not None, "account was never encrypted"NEWLINE account.encrypt(account.password)NEWLINE return TrueNEWLINENEWLINE @propertyNEWLINE def is_encrypted(self) -> bool:NEWLINE for account in self.accounts:NEWLINE if account.serialize_encrypted:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINE def decrypt(self):NEWLINE for account in self.accounts:NEWLINE account.serialize_encrypted = FalseNEWLINE self.save()NEWLINE return TrueNEWLINENEWLINE def encrypt(self, password):NEWLINE for account in self.accounts:NEWLINE if not account.encrypted:NEWLINE account.encrypt(password)NEWLINE account.serialize_encrypted = TrueNEWLINE self.save()NEWLINE self.unlock(password)NEWLINE return TrueNEWLINENEWLINENEWLINEclass WalletStorage:NEWLINENEWLINE LATEST_VERSION = 1NEWLINENEWLINE def __init__(self, path=None, default=None):NEWLINE self.path = pathNEWLINE self._default = default or {NEWLINE 'version': self.LATEST_VERSION,NEWLINE 'name': 'My Wallet',NEWLINE 'preferences': {},NEWLINE 'accounts': []NEWLINE }NEWLINENEWLINE def read(self):NEWLINE if self.path and os.path.exists(self.path):NEWLINE with open(self.path, 'r') as f:NEWLINE json_data = f.read()NEWLINE json_dict = json.loads(json_data)NEWLINE if json_dict.get('version') == self.LATEST_VERSION and \NEWLINE set(json_dict) == set(self._default):NEWLINE return json_dictNEWLINE else:NEWLINE return self.upgrade(json_dict)NEWLINE else:NEWLINE return self._default.copy()NEWLINENEWLINE def upgrade(self, json_dict):NEWLINE json_dict = json_dict.copy()NEWLINE version = json_dict.pop('version', -1)NEWLINE if version == -1:NEWLINE passNEWLINE upgraded = self._default.copy()NEWLINE upgraded.update(json_dict)NEWLINE return json_dictNEWLINENEWLINE def write(self, json_dict):NEWLINENEWLINE json_data = json.dumps(json_dict, indent=4, sort_keys=True)NEWLINE if self.path is None:NEWLINE return json_dataNEWLINENEWLINE temp_path = "%s.tmp.%s" % (self.path, os.getpid())NEWLINE with open(temp_path, "w") as f:NEWLINE f.write(json_data)NEWLINE f.flush()NEWLINE os.fsync(f.fileno())NEWLINENEWLINE if os.path.exists(self.path):NEWLINE mode = os.stat(self.path).st_modeNEWLINE else:NEWLINE mode = stat.S_IREAD | stat.S_IWRITENEWLINE try:NEWLINE os.rename(temp_path, self.path)NEWLINE except Exception: # pylint: disable=broad-exceptNEWLINE os.remove(self.path)NEWLINE os.rename(temp_path, self.path)NEWLINE os.chmod(self.path, mode)NEWLINE import sysNEWLINEfrom collections import namedtuple, OrderedDictNEWLINEfrom typing import Dict, ListNEWLINENEWLINEimport torchNEWLINEfrom torch import nn as nnNEWLINENEWLINEfrom model.decoder import DecoderNEWLINEfrom model.encoder import EncoderNEWLINEfrom utils import util, nn_utilNEWLINEfrom utils.ast import AbstractSyntaxTreeNEWLINEfrom utils.dataset import ExampleNEWLINEfrom utils.vocab import Vocab, SAME_VARIABLE_TOKEN, END_OF_VARIABLE_TOKENNEWLINENEWLINENEWLINEclass RecurrentSubtokenDecoder(Decoder):NEWLINE def __init__(self, variable_encoding_size: int, hidden_size: int, dropout: float, tie_embed: bool, input_feed: bool, vocab: Vocab):NEWLINE super(Decoder, self).__init__()NEWLINENEWLINE self.vocab = vocabNEWLINENEWLINE lstm_x_dim = variable_encoding_size + hidden_sizeNEWLINE if input_feed:NEWLINE lstm_x_dim += hidden_sizeNEWLINENEWLINE self.lstm_cell = nn.LSTMCell(lstm_x_dim, hidden_size) # v_encoding_t + e(y_tm1)NEWLINE self.state2names = nn.Linear(hidden_size, len(vocab.target), bias=True)NEWLINE if not tie_embed:NEWLINE self.var_name_embed = nn.Embedding(len(vocab.target), hidden_size)NEWLINENEWLINE self.dropout = nn.Dropout(dropout)NEWLINE self.config: Dict = NoneNEWLINENEWLINE self.Hypothesis = namedtuple('Hypothesis', ['variable_list', 'variable_ptr', 'score'])NEWLINENEWLINE @propertyNEWLINE def device(self):NEWLINE return self.state2names.weight.deviceNEWLINENEWLINE @classmethodNEWLINE def default_params(cls):NEWLINE return {NEWLINE 'vocab_file': None,NEWLINE 'variable_encoding_size': 128,NEWLINE 'hidden_size': 128,NEWLINE 'input_feed': False,NEWLINE 'tie_embedding': True,NEWLINE 'dropout': 0.2,NEWLINE 'beam_size': 5,NEWLINE 'max_prediction_time_step': 1200,NEWLINE 'independent_prediction_for_each_variable': FalseNEWLINE }NEWLINENEWLINE @propertyNEWLINE def independent_prediction_for_each_variable(self):NEWLINE return self.config['independent_prediction_for_each_variable']NEWLINENEWLINE @classmethodNEWLINE def build(cls, config):NEWLINE params = util.update(cls.default_params(), config)NEWLINENEWLINE vocab = Vocab.load(params['vocab_file'])NEWLINE model = cls(params['variable_encoding_size'],NEWLINE params['hidden_size'], params['dropout'], params['tie_embedding'], params['input_feed'], vocab)NEWLINE model.config = paramsNEWLINENEWLINE return modelNEWLINENEWLINE def get_init_state(self, src_ast_encoding):NEWLINE return self.encoder.get_decoder_init_state(src_ast_encoding, self.config)NEWLINENEWLINE def rnn_step(self, x, h_tm1, src_ast_encoding):NEWLINE h_t = self.lstm_cell(x, h_tm1)NEWLINE # TODO: implement attention?NEWLINE # att_t = torch.tanh(self.att_vec_linear(torch.cat([h_t], 1)))NEWLINE q_t = self.dropout(h_t[0])NEWLINENEWLINE return h_t, q_t, NoneNEWLINENEWLINE def forward(self, src_ast_encoding, prediction_target):NEWLINE # (batch_size, max_time_step)NEWLINE target_variable_encoding_indices = prediction_target['target_variable_encoding_indices']NEWLINE target_variable_encoding_indices_mask = prediction_target['target_variable_encoding_indices_mask']NEWLINENEWLINE batch_size = target_variable_encoding_indices.size(0)NEWLINE variable_encoding_size = src_ast_encoding['variable_encoding'].size(-1)NEWLINENEWLINE # (batch_size, max_time_step, encoding_size)NEWLINE # scatter variable encoding to sub-token time stepsNEWLINE variable_encoding = torch.gather(src_ast_encoding['variable_encoding'], 1,NEWLINE target_variable_encoding_indices.unsqueeze(-1).expand(-1, -1, variable_encoding_size))NEWLINE # (batch_size, max_time_step, encoding_size)NEWLINE variable_tgt_name_id = prediction_target['variable_tgt_name_id']NEWLINENEWLINE h_0 = self.get_init_state(src_ast_encoding)NEWLINE att_tm1 = variable_encoding.new_zeros(src_ast_encoding['batch_size'], self.lstm_cell.hidden_size)NEWLINE v_tm1_name_embed = torch.zeros(batch_size, self.lstm_cell.hidden_size, device=self.device)NEWLINENEWLINE h_tm1 = h_0NEWLINE query_vecs = []NEWLINE max_time_step = variable_encoding.size(1)NEWLINE for t, variable_encoding_t in enumerate(variable_encoding.split(split_size=1, dim=1)):NEWLINE # variable_encoding_t: (batch_size, encoding_size)NEWLINE variable_encoding_t = variable_encoding_t.squeeze(1)NEWLINENEWLINE if self.config['input_feed']:NEWLINE x = torch.cat([variable_encoding_t, v_tm1_name_embed, att_tm1], dim=-1)NEWLINE else:NEWLINE x = torch.cat([variable_encoding_t, v_tm1_name_embed], dim=-1)NEWLINENEWLINE h_t, q_t, alpha_t = self.rnn_step(x, h_tm1, src_ast_encoding)NEWLINENEWLINE att_tm1 = q_tNEWLINE h_tm1 = h_tNEWLINE query_vecs.append(q_t)NEWLINE v_tm1_name_id = variable_tgt_name_id[:, t]NEWLINE if self.config['tie_embedding']:NEWLINE v_tm1_name_embed = self.state2names.weight[v_tm1_name_id]NEWLINE else:NEWLINE v_tm1_name_embed = self.var_name_embed(v_tm1_name_id)NEWLINENEWLINE if self.independent_prediction_for_each_variable and t < max_time_step - 1:NEWLINE # (batch_size, )NEWLINE variable_ids_tp1 = target_variable_encoding_indices[:, t + 1]NEWLINE variable_ids_t = target_variable_encoding_indices[:, t]NEWLINENEWLINE is_tp1_same_variable = torch.eq(variable_ids_tp1, variable_ids_t).float().unsqueeze(-1) # TODO: check if correct!NEWLINE h_tm1 = (h_tm1[0] * is_tp1_same_variable, h_tm1[1] * is_tp1_same_variable)NEWLINE att_tm1 = att_tm1 * is_tp1_same_variableNEWLINE v_tm1_name_embed = v_tm1_name_embed * is_tp1_same_variableNEWLINENEWLINE # (batch_size, max_prediction_node_num, encoding_size)NEWLINE query_vecs = torch.stack(query_vecs).permute(1, 0, 2)NEWLINENEWLINE # (batch_size, max_prediction_node_num, vocab_size)NEWLINE logits = self.state2names(query_vecs)NEWLINE var_name_log_probs = torch.log_softmax(logits, dim=-1)NEWLINE var_name_log_probs = var_name_log_probs * target_variable_encoding_indices_mask.unsqueeze(-1)NEWLINENEWLINE return var_name_log_probsNEWLINENEWLINE def get_target_log_prob(self, var_name_log_probs, prediction_target, src_ast_encoding):NEWLINE # (batch_size, max_prediction_node_num)NEWLINE variable_tgt_name_id = prediction_target['variable_tgt_name_id']NEWLINE tgt_var_name_log_prob = torch.gather(var_name_log_probs,NEWLINE dim=-1, index=variable_tgt_name_id.unsqueeze(-1)).squeeze(-1)NEWLINENEWLINE tgt_var_name_log_prob = tgt_var_name_log_prob * prediction_target['target_variable_encoding_indices_mask']NEWLINENEWLINE result = dict(tgt_var_name_log_prob=tgt_var_name_log_prob)NEWLINENEWLINE return resultNEWLINENEWLINE def predict(self, examples: List[Example], encoder: Encoder) -> List[Dict]:NEWLINE batch_size = len(examples)NEWLINE beam_size = self.config['beam_size']NEWLINE same_variable_id = self.vocab.target[SAME_VARIABLE_TOKEN]NEWLINE end_of_variable_id = self.vocab.target[END_OF_VARIABLE_TOKEN]NEWLINENEWLINE variable_nums = []NEWLINE for ast_id, example in enumerate(examples):NEWLINE variable_nums.append(len(example.ast.variables))NEWLINENEWLINE beams = OrderedDict((ast_id, [self.Hypothesis([], 0, 0.)]) for ast_id in range(batch_size))NEWLINE hyp_scores_tm1 = torch.zeros(len(beams), device=self.device)NEWLINE completed_hyps = [[] for _ in range(batch_size)]NEWLINE tgt_vocab_size = len(self.vocab.target)NEWLINENEWLINE tensor_dict = self.batcher.to_tensor_dict(examples)NEWLINE nn_util.to(tensor_dict, self.device)NEWLINENEWLINE context_encoding = encoder(tensor_dict)NEWLINE h_tm1 = h_0 = self.get_init_state(context_encoding)NEWLINENEWLINE # Note that we are using the `restoration_indices` from `context_encoding`, which is the word-level restoration indexNEWLINE # (batch_size, variable_master_node_num, encoding_size)NEWLINE variable_encoding = context_encoding['variable_encoding']NEWLINE # (batch_size, encoding_size)NEWLINE variable_name_embed_tm1 = att_tm1 = torch.zeros(batch_size, self.lstm_cell.hidden_size, device=self.device)NEWLINENEWLINE max_prediction_time_step = self.config['max_prediction_time_step']NEWLINE for t in range(0, max_prediction_time_step):NEWLINE # (total_live_hyp_num, encoding_size)NEWLINE if t > 0:NEWLINE variable_encoding_t = variable_encoding[hyp_ast_ids_t, hyp_variable_ptrs_t]NEWLINE else:NEWLINE variable_encoding_t = variable_encoding[:, 0]NEWLINENEWLINE if self.config['input_feed']:NEWLINE x = torch.cat([variable_encoding_t, variable_name_embed_tm1, att_tm1], dim=-1)NEWLINE else:NEWLINE x = torch.cat([variable_encoding_t, variable_name_embed_tm1], dim=-1)NEWLINENEWLINE h_t, q_t, alpha_t = self.rnn_step(x, h_tm1, context_encoding)NEWLINENEWLINE # (total_live_hyp_num, vocab_size)NEWLINE hyp_var_name_scores_t = torch.log_softmax(self.state2names(q_t), dim=-1)NEWLINENEWLINE cont_cand_hyp_scores = hyp_scores_tm1.unsqueeze(-1) + hyp_var_name_scores_tNEWLINENEWLINE new_beams = OrderedDict()NEWLINE live_beam_ids = []NEWLINE new_hyp_scores = []NEWLINE live_prev_hyp_ids = []NEWLINE new_hyp_var_name_ids = []NEWLINE new_hyp_ast_ids = []NEWLINE new_hyp_variable_ptrs = []NEWLINE is_same_variable_mask = []NEWLINE beam_start_hyp_pos = 0NEWLINE for beam_id, (ast_id, beam) in enumerate(beams.items()):NEWLINE beam_end_hyp_pos = beam_start_hyp_pos + len(beam)NEWLINE # (live_beam_size, vocab_size)NEWLINE beam_cont_cand_hyp_scores = cont_cand_hyp_scores[beam_start_hyp_pos: beam_end_hyp_pos]NEWLINE cont_beam_size = beam_size - len(completed_hyps[ast_id])NEWLINE beam_new_hyp_scores, beam_new_hyp_positions = torch.topk(beam_cont_cand_hyp_scores.view(-1),NEWLINE k=cont_beam_size,NEWLINE dim=-1)NEWLINENEWLINE # (cont_beam_size)NEWLINE beam_prev_hyp_ids = beam_new_hyp_positions / tgt_vocab_sizeNEWLINE beam_hyp_var_name_ids = beam_new_hyp_positions % tgt_vocab_sizeNEWLINENEWLINE _prev_hyp_ids = beam_prev_hyp_ids.cpu()NEWLINE _hyp_var_name_ids = beam_hyp_var_name_ids.cpu()NEWLINE _new_hyp_scores = beam_new_hyp_scores.cpu()NEWLINENEWLINE for i in range(cont_beam_size):NEWLINE prev_hyp_id = _prev_hyp_ids[i].item()NEWLINE prev_hyp = beam[prev_hyp_id]NEWLINE hyp_var_name_id = _hyp_var_name_ids[i].item()NEWLINE new_hyp_score = _new_hyp_scores[i].item()NEWLINENEWLINE variable_ptr = prev_hyp.variable_ptrNEWLINE if hyp_var_name_id == end_of_variable_id:NEWLINE variable_ptr += 1NEWLINENEWLINE # remove empty casesNEWLINE if len(prev_hyp.variable_list) == 0 or prev_hyp.variable_list[-1] == end_of_variable_id:NEWLINE continueNEWLINENEWLINE new_hyp = self.Hypothesis(variable_list=list(prev_hyp.variable_list) + [hyp_var_name_id],NEWLINE variable_ptr=variable_ptr,NEWLINE score=new_hyp_score)NEWLINENEWLINE if variable_ptr == variable_nums[ast_id]:NEWLINE completed_hyps[ast_id].append(new_hyp)NEWLINE else:NEWLINE new_beams.setdefault(ast_id, []).append(new_hyp)NEWLINE live_beam_ids.append(beam_id)NEWLINE new_hyp_scores.append(new_hyp_score)NEWLINE live_prev_hyp_ids.append(beam_start_hyp_pos + prev_hyp_id)NEWLINE new_hyp_var_name_ids.append(hyp_var_name_id)NEWLINE new_hyp_ast_ids.append(ast_id)NEWLINE new_hyp_variable_ptrs.append(variable_ptr)NEWLINE is_same_variable_mask.append(1. if prev_hyp.variable_ptr == variable_ptr else 0.)NEWLINENEWLINE beam_start_hyp_pos = beam_end_hyp_posNEWLINENEWLINE if live_beam_ids:NEWLINE hyp_scores_tm1 = torch.tensor(new_hyp_scores, device=self.device)NEWLINE h_tm1 = (h_t[0][live_prev_hyp_ids], h_t[1][live_prev_hyp_ids])NEWLINE att_tm1 = q_t[live_prev_hyp_ids]NEWLINENEWLINE variable_name_embed_tm1 = self.state2names.weight[new_hyp_var_name_ids]NEWLINE hyp_ast_ids_t = new_hyp_ast_idsNEWLINE hyp_variable_ptrs_t = new_hyp_variable_ptrsNEWLINENEWLINE beams = new_beamsNEWLINENEWLINE if self.independent_prediction_for_each_variable:NEWLINE is_same_variable_mask = torch.tensor(is_same_variable_mask, device=self.device, dtype=torch.float).unsqueeze(-1)NEWLINE h_tm1 = (h_tm1[0] * is_same_variable_mask, h_tm1[1] * is_same_variable_mask)NEWLINE att_tm1 = att_tm1 * is_same_variable_maskNEWLINE variable_name_embed_tm1 = variable_name_embed_tm1 * is_same_variable_maskNEWLINE else:NEWLINE breakNEWLINENEWLINE variable_rename_results = []NEWLINE for i, hyps in enumerate(completed_hyps):NEWLINE variable_rename_result = dict()NEWLINE ast = examples[i].astNEWLINE hyps = sorted(hyps, key=lambda hyp: -hyp.score)NEWLINENEWLINE if not hyps:NEWLINE # return identity renamingsNEWLINE print(f'Failed to found a hypothesis for function {ast.compilation_unit}', file=sys.stderr)NEWLINE for old_name in ast.variables:NEWLINE variable_rename_result[old_name] = {'new_name': old_name,NEWLINE 'prob': 0.}NEWLINE else:NEWLINE top_hyp = hyps[0]NEWLINE sub_token_ptr = 0NEWLINE for old_name in ast.variables:NEWLINE sub_token_begin = sub_token_ptrNEWLINE while top_hyp.variable_list[sub_token_ptr] != end_of_variable_id:NEWLINE sub_token_ptr += 1NEWLINE sub_token_ptr += 1 # point to first sub-token of next variableNEWLINE sub_token_end = sub_token_ptrNEWLINENEWLINE var_name_token_ids = top_hyp.variable_list[sub_token_begin: sub_token_end] # include ending NEWLINE if var_name_token_ids == [same_variable_id, end_of_variable_id]:NEWLINE new_var_name = old_nameNEWLINE else:NEWLINE new_var_name = self.vocab.target.subtoken_model.decode_ids(var_name_token_ids)NEWLINENEWLINE variable_rename_result[old_name] = {'new_name': new_var_name,NEWLINE 'prob': top_hyp.score}NEWLINENEWLINE variable_rename_results.append(variable_rename_result)NEWLINENEWLINE return variable_rename_resultsNEWLINE from bingads.v13.bulk.entities.audiences.bulk_campaign_audience_association import BulkCampaignAudienceAssociationNEWLINENEWLINEclass BulkCampaignProductAudienceAssociation(BulkCampaignAudienceAssociation):NEWLINE """ Represents an Campaign Product Audience Association that can be read or written in a bulk file.NEWLINENEWLINE For more information, see Campaign Product Audience Association at https://go.microsoft.com/fwlink/?linkid=846127.NEWLINENEWLINE *See also:*NEWLINENEWLINE * :class:`.BulkServiceManager`NEWLINE * :class:`.BulkOperation`NEWLINE * :class:`.BulkFileReader`NEWLINE * :class:`.BulkFileWriter`NEWLINE """NEWLINE from pycocotools.coco import COCONEWLINENEWLINEimport matplotlib.pyplot as pltNEWLINEimport cv2NEWLINENEWLINEimport osNEWLINEimport numpy as npNEWLINEimport randomNEWLINEimport torchNEWLINEimport torchvision.transforms as transformsNEWLINEfrom torch.utils.data import DataLoader,DatasetNEWLINEfrom skimage import io,transformNEWLINEimport matplotlib.pyplot as pltNEWLINEimport osNEWLINEimport torchNEWLINEfrom torchvision import transformsNEWLINEimport numpy as npNEWLINEimport PIL.Image as ImageNEWLINEfrom skimage import measureNEWLINEfrom tqdm import tqdmNEWLINEimport torch.nn.functional as FNEWLINEfrom skimage.morphology import convex_hull_imageNEWLINENEWLINEclass SuperPixelGet(Dataset): #继承DatasetNEWLINE def __init__(self, segments_label, segments_tensor, g_theta_m, data_num):NEWLINE self.segments_label = segments_label.cuda()NEWLINE self.segments_tensor = segments_tensor.cuda()NEWLINE self.g_theta_m = g_theta_m.cuda()NEWLINE self.data_num = data_numNEWLINENEWLINENEWLINE self.zero_layer = torch.zeros_like(self.segments_tensor)NEWLINE self.one_layer = torch.ones_like(self.segments_tensor)NEWLINENEWLINE NEWLINE def __len__(self):NEWLINE return self.data_numNEWLINE NEWLINE def __getitem__(self, index):NEWLINENEWLINE attack_region_tmp = self.zero_layer.clone()NEWLINE flag = torch.rand_like( self.segments_label) < self.g_theta_m NEWLINE for i in range(flag.shape[0]):NEWLINE if flag[i]:NEWLINE sp = self.segments_label[i]NEWLINE attack_region_tmp = torch.where(self.segments_tensor==sp, self.one_layer, attack_region_tmp)NEWLINE NEWLINE # # get convex envolopeNEWLINE # attack_region_tmp_np = attack_region_tmp.cpu().numpy()NEWLINE # attack_region_tmp_label_np = measure.label(attack_region_tmp_np)NEWLINE # connect_region_number = int(np.max(attack_region_tmp_label_np))NEWLINE NEWLINE # one_np = np.ones_like(attack_region_tmp_np)NEWLINE # zero_np = np.zeros_like(attack_region_tmp_np)NEWLINE # attack_region_envolope_np = np.zeros_like(attack_region_tmp_np)NEWLINENEWLINE # for i in range(connect_region_number):NEWLINE # binary_map = np.where(attack_region_tmp_label_np==i+1, one_np, zero_np)NEWLINE # convex_env = convex_hull_image(binary_map)NEWLINENEWLINE # attack_region_envolope_np = attack_region_envolope_np + convex_envNEWLINE # passNEWLINENEWLINENEWLINE # attack_region_tmp = torch.from_numpy(attack_region_envolope_np)NEWLINE # attack_region_tmp = torch.clamp(attack_region_tmp, 0, 1).cuda()NEWLINENEWLINE return attack_region_tmp, flagNEWLINENEWLINEif __name__=='__main__':NEWLINE segments_tensor = [NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,5,5,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,4,5,5,0,0],NEWLINE [0,0,1,1,1,2,3,3,3,3,4,4,4,5,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE ]NEWLINE segments_tensor = torch.Tensor(segments_tensor)NEWLINE g_theta_m = torch.Tensor([0.1,0.2,0.3,0.4,0.5,0.6])NEWLINE data_num = 555NEWLINE data = SuperPixelGet(torch.Tensor([1,2,3,4,5,6]), segments_tensor, g_theta_m, data_num)NEWLINE dataloader = DataLoader(data, batch_size=128,shuffle=False) #使用DataLoader加载数据NEWLINENEWLINE max_len = 0NEWLINE for epoch in range(10):NEWLINE for i_batch, batch_data in enumerate(dataloader):NEWLINENEWLINE sum_tensor = torch.sum(batch_data, dim=0)NEWLINE sum_tensor = sum_tensor/torch.max(sum_tensor)NEWLINE sum_tensor = sum_tensor.unsqueeze(0).unsqueeze(0)NEWLINE sum_tensor = F.interpolate(sum_tensor, (800, 800), mode='nearest').squeeze()NEWLINE sum_pil = transforms.ToPILImage()(sum_tensor)NEWLINE sum_pil.show()NEWLINENEWLINE passNEWLINENEWLINENEWLINE # Licensed under the Apache License, Version 2.0 (the "License"); you mayNEWLINE# not use this file except in compliance with the License. You may obtainNEWLINE# a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS, WITHOUTNEWLINE# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See theNEWLINE# License for the specific language governing permissions and limitationsNEWLINE# under the License.NEWLINENEWLINEfrom neutron.objects.qos import policy as qos_policyNEWLINEfrom neutron.objects.qos import rule as qos_ruleNEWLINEfrom neutron_lib.api.definitions import portbindingsNEWLINEfrom neutron_lib import constantsNEWLINEfrom neutron_lib import context as n_contextNEWLINEfrom neutron_lib.db import constants as db_constsNEWLINEfrom neutron_lib.plugins import directoryNEWLINEfrom neutron_lib.services.qos import baseNEWLINEfrom neutron_lib.services.qos import constants as qos_constsNEWLINEfrom oslo_config import cfgNEWLINEfrom oslo_log import log as loggingNEWLINENEWLINEfrom networking_ovn.common import utilsNEWLINENEWLINELOG = logging.getLogger(__name__)NEWLINENEWLINEOVN_QOS = 'qos'NEWLINESUPPORTED_RULES = {NEWLINE qos_consts.RULE_TYPE_BANDWIDTH_LIMIT: {NEWLINE qos_consts.MAX_KBPS: {NEWLINE 'type:range': [0, db_consts.DB_INTEGER_MAX_VALUE]},NEWLINE qos_consts.MAX_BURST: {NEWLINE 'type:range': [0, db_consts.DB_INTEGER_MAX_VALUE]},NEWLINE qos_consts.DIRECTION: {NEWLINE 'type:values': [constants.EGRESS_DIRECTION]}NEWLINE },NEWLINE}NEWLINENEWLINEVIF_TYPES = [portbindings.VIF_TYPE_OVS, portbindings.VIF_TYPE_VHOST_USER]NEWLINEVNIC_TYPES = [portbindings.VNIC_NORMAL]NEWLINENEWLINENEWLINEclass OVNQosNotificationDriver(base.DriverBase):NEWLINE """OVN notification driver for QoS."""NEWLINENEWLINE def __init__(self, name='OVNQosDriver',NEWLINE vif_types=VIF_TYPES,NEWLINE vnic_types=VNIC_TYPES,NEWLINE supported_rules=SUPPORTED_RULES,NEWLINE requires_rpc_notifications=False):NEWLINE super(OVNQosNotificationDriver, self).__init__(NEWLINE name, vif_types, vnic_types, supported_rules,NEWLINE requires_rpc_notifications)NEWLINENEWLINE @classmethodNEWLINE def create(cls, plugin_driver):NEWLINE cls._driver = plugin_driverNEWLINE return cls()NEWLINENEWLINE @propertyNEWLINE def is_loaded(self):NEWLINE return OVN_QOS in cfg.CONF.ml2.extension_driversNEWLINENEWLINE def create_policy(self, context, policy):NEWLINE # No need to update OVN on createNEWLINE passNEWLINENEWLINE def update_policy(self, context, policy):NEWLINE # Call into OVN client to update the policyNEWLINE self._driver._ovn_client._qos_driver.update_policy(context, policy)NEWLINENEWLINE def delete_policy(self, context, policy):NEWLINE # No need to update OVN on deleteNEWLINE passNEWLINENEWLINENEWLINEclass OVNQosDriver(object):NEWLINE """Qos driver for OVN"""NEWLINENEWLINE def __init__(self, driver):NEWLINE LOG.info("Starting OVNQosDriver")NEWLINE super(OVNQosDriver, self).__init__()NEWLINE self._driver = driverNEWLINE self._plugin_property = NoneNEWLINENEWLINE @propertyNEWLINE def _plugin(self):NEWLINE if self._plugin_property is None:NEWLINE self._plugin_property = directory.get_plugin()NEWLINE return self._plugin_propertyNEWLINENEWLINE def _generate_port_options(self, context, policy_id):NEWLINE if policy_id is None:NEWLINE return {}NEWLINE options = {}NEWLINE # The policy might not have any rulesNEWLINE all_rules = qos_rule.get_rules(qos_policy.QosPolicy,NEWLINE context, policy_id)NEWLINE for rule in all_rules:NEWLINE if isinstance(rule, qos_rule.QosBandwidthLimitRule):NEWLINE if rule.max_kbps:NEWLINE options['qos_max_rate'] = str(rule.max_kbps * 1000)NEWLINE if rule.max_burst_kbps:NEWLINE options['qos_burst'] = str(rule.max_burst_kbps * 1000)NEWLINE return optionsNEWLINENEWLINE def get_qos_options(self, port):NEWLINE # Is qos service enabledNEWLINE if 'qos_policy_id' not in port:NEWLINE return {}NEWLINE # Don't apply qos rules to network devicesNEWLINE if utils.is_network_device_port(port):NEWLINE return {}NEWLINENEWLINE # Determine if port or network policy should be usedNEWLINE context = n_context.get_admin_context()NEWLINE port_policy_id = port.get('qos_policy_id')NEWLINE network_policy_id = NoneNEWLINE if not port_policy_id:NEWLINE network_policy = qos_policy.QosPolicy.get_network_policy(NEWLINE context, port['network_id'])NEWLINE network_policy_id = network_policy.id if network_policy else NoneNEWLINENEWLINE # Generate qos options for the selected policyNEWLINE policy_id = port_policy_id or network_policy_idNEWLINE return self._generate_port_options(context, policy_id)NEWLINENEWLINE def _update_network_ports(self, context, network_id, options):NEWLINE # Retrieve all ports for this networkNEWLINE ports = self._plugin.get_ports(context,NEWLINE filters={'network_id': [network_id]})NEWLINE for port in ports:NEWLINE # Don't apply qos rules if port has a policyNEWLINE port_policy_id = port.get('qos_policy_id')NEWLINE if port_policy_id:NEWLINE continueNEWLINE # Don't apply qos rules to network devicesNEWLINE if utils.is_network_device_port(port):NEWLINE continueNEWLINE # Call into OVN client to update portNEWLINE self._driver.update_port(port, qos_options=options)NEWLINENEWLINE def update_network(self, network):NEWLINE # Is qos service enabledNEWLINE if 'qos_policy_id' not in network:NEWLINE returnNEWLINENEWLINE # Update the qos options on each network portNEWLINE context = n_context.get_admin_context()NEWLINE options = self._generate_port_options(NEWLINE context, network['qos_policy_id'])NEWLINE self._update_network_ports(context, network.get('id'), options)NEWLINENEWLINE def update_policy(self, context, policy):NEWLINE options = self._generate_port_options(context, policy.id)NEWLINENEWLINE # Update each network bound to this policyNEWLINE network_bindings = policy.get_bound_networks()NEWLINE for network_id in network_bindings:NEWLINE self._update_network_ports(context, network_id, options)NEWLINENEWLINE # Update each port bound to this policyNEWLINE port_bindings = policy.get_bound_ports()NEWLINE for port_id in port_bindings:NEWLINE port = self._plugin.get_port(context, port_id)NEWLINE self._driver.update_port(port, qos_options=options)NEWLINE from discord.ext import commandsNEWLINEimport discordNEWLINEimport requestsNEWLINEfrom bs4 import BeautifulSoupNEWLINEimport reNEWLINENEWLINEclass neorg_cmds(commands.Cog):NEWLINENEWLINE def __init__(self, bot):NEWLINE self.bot = botNEWLINENEWLINE @commands.command()NEWLINE async def wiki(self, ctx, *, query):NEWLINE query = query.strip().lower().replace(' ', '-')NEWLINE neorg_wiki = {}NEWLINE wiki_url = "https://github.com/vhyrro/neorg/wiki"NEWLINENEWLINE stuff = BeautifulSoup(requests.get(wiki_url).text, 'lxml')NEWLINE lis = stuff.find_all("div", {"class": "Box-body wiki-custom-sidebar markdown-body"})[0]NEWLINENEWLINE for li in lis.find_all('li'):NEWLINE part = li.a['href']NEWLINE neorg_wiki[part[37:].lower()] = partNEWLINENEWLINE wiki = [neorg_wiki[k] for k in neorg_wiki.keys() if query in k.lower()]NEWLINENEWLINE if len(wiki) == 0:NEWLINE await ctx.send(embed=discord.Embed(description="No Results Found!", colour=0x4878BE))NEWLINE returnNEWLINE NEWLINE for i in wiki:NEWLINE em = discord.Embed(description=i, colour=0x4878BE)NEWLINE await ctx.send(embed=em)NEWLINENEWLINE @commands.command()NEWLINE async def spec(self, ctx, *, query):NEWLINE query = query.strip().lower().replace(' ', '-')NEWLINE url = "https://raw.githubusercontent.com/vhyrro/neorg/main/docs/NFF-0.1-spec.md"NEWLINE og_url = "https://github.com/vhyrro/neorg/blob/main/docs/NFF-0.1-spec.md"NEWLINENEWLINE soup = re.findall( r"\[(.+)\]\((.+)\)", requests.get(url).text[:1500])NEWLINE neorg_specs = {}NEWLINENEWLINE for k,v in soup:NEWLINE neorg_specs[k.lower().replace(' ', '-')] = og_url + vNEWLINENEWLINE spec = [neorg_specs[k] for k in neorg_specs.keys() if query in k.lower()]NEWLINENEWLINE if len(spec) == 0:NEWLINE await ctx.send(embed=discord.Embed(description="No Results Found!", colour=0x4878BE))NEWLINE returnNEWLINENEWLINE for i in spec:NEWLINE em = discord.Embed(description=i, colour=0x4878BE)NEWLINE await ctx.send(embed=em)NEWLINENEWLINE @commands.command(aliases=["norg"])NEWLINE async def neorg(self, ctx):NEWLINE """Fetch the Neorg repository"""NEWLINE await ctx.send("Neorg - https://github.com/vhyrro/neorg")NEWLINENEWLINEdef setup(bot):NEWLINE bot.add_cog(neorg_cmds(bot))NEWLINE from django.db import modelsNEWLINEtipo_choices=(NEWLINE ('colegio','Colegio'),NEWLINE ('iglesia','Iglesia'),NEWLINE ('plaza','Plaza'),NEWLINE ('restaurante','Restaurante'),NEWLINE ('alojamiento','Alojamiento'),NEWLINE )NEWLINENEWLINEclass admin_agregar (models.Model):NEWLINE cod_ubicacion= models.AutoField(primary_key = True)NEWLINE latitud = models.CharField(max_length=200, blank=False, null=False)NEWLINE longitud = models.CharField(max_length=200, blank=False, null=False)NEWLINE tipo = models.CharField(max_length=200, blank=False, null=False, choices=tipo_choices)NEWLINE def __STR__(self):NEWLINE return self.tipoNEWLINENEWLINEclass colegio(models.Model):NEWLINE cod_colegio=models.AutoField(primary_key=True)NEWLINE nombre= models.CharField(max_length=200, blank=False, null=False)NEWLINE fecha_fundacion = models.CharField(max_length=200,blank=False, null=False)NEWLINE clasificacion = models.CharField(max_length=200, blank=False)NEWLINE cod_ubicacion=models.ForeignKey(admin_agregar, on_delete=models.CASCADE)NEWLINENEWLINEclass iglesia(models.Model):NEWLINE cod_iglesia=models.AutoField(primary_key=True)NEWLINE nombre= models.CharField(max_length=200, blank=False, null=False)NEWLINE fecha_fundacion = models.CharField(max_length=200,blank=False, null=False)NEWLINE religion= models.CharField(max_length=200, blank=False, null=False)NEWLINE capacidad=models.CharField(max_length=200, blank=False, null=False)NEWLINE cod_ubicacion=models.ForeignKey(admin_agregar, on_delete=models.CASCADE)NEWLINENEWLINEclass alojamiento(models.Model):NEWLINE cod_alojamiento=models.AutoField(primary_key=True)NEWLINE nombre= models.CharField(max_length=200, blank=False, null=False)NEWLINE clasificacion = models.CharField(max_length=200,blank=False, null=False)NEWLINE fecha_fundacion = models.CharField(max_length=200,blank=False, null=False)NEWLINE cod_ubicacion=models.ForeignKey(admin_agregar, on_delete=models.CASCADE)NEWLINENEWLINEclass plaza(models.Model):NEWLINE cod_plaza=models.AutoField(primary_key=True)NEWLINE nombre=models.CharField(max_length=200, blank=False, null=False)NEWLINE fecha_fundacion = models.DateField(blank=False, null=False)NEWLINE cod_ubicacion=models.OneToOneField(admin_agregar, on_delete=models.CASCADE)NEWLINENEWLINENEWLINENEWLINEclass restaurante(models.Model):NEWLINE cod_restaurante=models.AutoField(primary_key=True)NEWLINE nombre=models.CharField(max_length=200, blank=False, null=False)NEWLINE capacidad=models.CharField(max_length=200, blank=False, null=False)NEWLINE clasificacion = models.CharField(max_length=200,blank=False, null=False)NEWLINE cod_ubicacion= models.ForeignKey(admin_agregar, on_delete=models.CASCADE) #NEWLINE# PySNMP MIB module DES-1210-28MEbx (http://snmplabs.com/pysmi)NEWLINE# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DES-1210-28MEbxNEWLINE# Produced by pysmi-0.3.4 at Wed May 1 12:38:52 2019NEWLINE# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4NEWLINE# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) NEWLINE#NEWLINEInteger, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")NEWLINENamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")NEWLINEConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint")NEWLINEdot1dBasePort, dot1dBasePortEntry, dot1dBridge = mibBuilder.importSymbols("BRIDGE-MIB", "dot1dBasePort", "dot1dBasePortEntry", "dot1dBridge")NEWLINEAddressFamilyNumbers, = mibBuilder.importSymbols("IANA-ADDRESS-FAMILY-NUMBERS-MIB", "AddressFamilyNumbers")NEWLINEInterfaceIndex, InterfaceIndexOrZero = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex", "InterfaceIndexOrZero")NEWLINEInetAddress, = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress")NEWLINEVlanId, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "VlanId")NEWLINESnmpSecurityLevel, SnmpEngineID, SnmpAdminString = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpSecurityLevel", "SnmpEngineID", "SnmpAdminString")NEWLINEModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")NEWLINEBits, ObjectIdentity, ModuleIdentity, Unsigned32, NotificationType, MibIdentifier, iso, Gauge32, Integer32, enterprises, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Counter32, IpAddress, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "ObjectIdentity", "ModuleIdentity", "Unsigned32", "NotificationType", "MibIdentifier", "iso", "Gauge32", "Integer32", "enterprises", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "Counter32", "IpAddress", "Counter64")NEWLINETruthValue, MacAddress, RowStatus, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "MacAddress", "RowStatus", "DisplayString", "TextualConvention")NEWLINEdes_1210_28mebx = ModuleIdentity((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2)).setLabel("des-1210-28mebx")NEWLINEdes_1210_28mebx.setRevisions(('2015-06-03 00:00', '2015-04-16 00:00', '2014-03-06 00:00',))NEWLINENEWLINEif getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):NEWLINE if mibBuilder.loadTexts: des_1210_28mebx.setRevisionsDescriptions((' In order to pass the web www.simpleweb.org to verify severity level 3, which must be change the SYNTAX of mib file.', 'Add trafficCtrlAutoRecoverTime object.', 'Initial version, published as D-Link des-1210 28ME mib.',))NEWLINEif mibBuilder.loadTexts: des_1210_28mebx.setLastUpdated('201506030000Z')NEWLINEif mibBuilder.loadTexts: des_1210_28mebx.setOrganization('DES-1210-28-BX-6-07-017.mib')NEWLINEif mibBuilder.loadTexts: des_1210_28mebx.setContactInfo('')NEWLINEif mibBuilder.loadTexts: des_1210_28mebx.setDescription(' In order to pass the web www.simpleweb.org to verify severity level 3, which must be change the SYNTAX of mib file.')NEWLINEd_link = MibIdentifier((1, 3, 6, 1, 4, 1, 171)).setLabel("d-link")NEWLINEdlink_products = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10)).setLabel("dlink-products")NEWLINEdlink_DES1210SeriesProd = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75)).setLabel("dlink-DES1210SeriesProd")NEWLINEdes_1210_28me = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15)).setLabel("des-1210-28me")NEWLINEclass VlanIndex(TextualConvention, Unsigned32):NEWLINE description = 'A value used to index per-VLAN tables: values of 0 and 4095 are not permitted; if the value is between 1 and 4094 inclusive, it represents an IEEE 802.1Q VLAN-ID with global scope within a given bridged domain (see VlanId textual convention). If the value is greater than 4095 then it represents a VLAN with scope local to the particular agent, i.e. one without a global VLAN-ID assigned to it. Such VLANs are outside the scope of IEEE 802.1Q but it is convenient to be able to manage them in the same way using this MIB.'NEWLINE status = 'current'NEWLINENEWLINEclass PortList(TextualConvention, OctetString):NEWLINE description = "Each octet within this value specifies a set of eight ports, with the first octet specifying ports 1 through 8, the second octet specifying ports 9 through 16, etc. Within each octet, the most significant bit represents the lowest numbered port, and the least significant bit represents the highest numbered port. Thus, each port of the bridge is represented by a single bit within the value of this object. If that bit has a value of '1' then that port is included in the set of ports; the port is not included if its bit has a value of '0'."NEWLINE status = 'current'NEWLINENEWLINEclass BridgeId(TextualConvention, OctetString):NEWLINE description = "The Bridge-Identifier as used in the Spanning Tree Protocol to uniquely identify a bridge. Its first two octets (in network byte order) contain a priority value and its last 6 octets contain the MAC address used to refer to a bridge in a unique fashion (typically, the numerically smallest MAC address of all ports on the bridge). Several objects in this MIB module represent values of timers used by the Spanning Tree Protocol. In this MIB, these timers have values in units of hundreths of a second (i.e. 1/100 secs). These timers, when stored in a Spanning Tree Protocol's BPDU, are in units of 1/256 seconds. Note, however, that 802.1D-1990 specifies a settable granularity of no more than 1 second for these timers. To avoid ambiguity, a data type is defined here as a textual convention and all representation of these timers in this MIB module are defined using this data type. An algorithm is also defined for converting between the different units, to ensure a timer's value is not distorted by multiple conversions."NEWLINE status = 'current'NEWLINE subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(8, 8)NEWLINE fixedLength = 8NEWLINENEWLINEclass Timeout(TextualConvention, Integer32):NEWLINE description = 'A STP timer in units of 1/100 seconds To convert a Timeout value into a value in units of 1/256 seconds, the following algorithm should be used: b = floor( (n * 256) / 100) where: floor = quotient [ignore remainder] n is the value in 1/100 second units b is the value in 1/256 second units To convert the value from 1/256 second units back to 1/100 seconds, the following algorithm should be used: n = ceiling( (b * 100) / 256) where: ceiling = quotient [if remainder is 0], or quotient + 1 [if remainder is non-zero] n is the value in 1/100 second units b is the value in 1/256 second units Note: it is important that the arithmetic operations are done in the order specified (i.e., multiply first, divide second).'NEWLINE status = 'current'NEWLINE displayHint = 'd4'NEWLINENEWLINEclass LldpManAddress(TextualConvention, OctetString):NEWLINE description = 'The value of a management address associated with the LLDP agent that may be used to reach higher layer entities to assist discovery by network management. It should be noted that appropriate security credentials, such as SNMP engineId, may be required to access the LLDP agent using a management address. These necessary credentials should be known by the network management and the objects associated with the credentials are not included in the LLDP agent.'NEWLINE status = 'current'NEWLINE subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 31)NEWLINENEWLINEclass OwnerString(TextualConvention, OctetString):NEWLINE description = "This data type is used to model an administratively assigned name of the owner of a resource. Implementations must accept values composed of well-formed NVT ASCII sequences. In addition, implementations should accept values composed of well-formed UTF-8 sequences. It is suggested that this name contain one or more of the following: IP address, management station name, network manager's name, location, or phone number. In some cases the agent itself will be the owner of an entry. In these cases, this string shall be set to a string starting with 'monitor'. SNMP access control is articulated entirely in terms of the contents of MIB views; access to a particular SNMP object instance depends only upon its presence or absence in a particular MIB view and never upon its value or the value of related object instances. Thus, objects of this type afford resolution of resource contention only among cooperating managers; they realize no access control function with respect to uncooperative parties."NEWLINE status = 'current'NEWLINE subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 127)NEWLINENEWLINEclass RmonStatus(TextualConvention, Integer32):NEWLINE description = 'The status of a table entry. Setting this object to the value invalid(4) has the effect of invalidating the corresponding entry. That is, it effectively disassociates the mapping identified with said entry. It is an implementation-specific matter as to whether the agent removes an invalidated entry from the table. Accordingly, management stations must be prepared to receive tabular information from agents that corresponds to entries currently not in use. Proper interpretation of such entries requires examination of the relevant RmonStatus object. An existing instance of this object cannot be set to createRequest(2). This object may only be set to createRequest(2) when this instance is created. When this object is created, the agent may wish to create supplemental object instances with default values to complete a conceptual row in this table. Because the creation of these default objects is entirely at the option of the agent, the manager must not assume that any will be created, but may make use of any that are created. Immediately after completing the create operation, the agent must set this object to underCreation(3). When in the underCreation(3) state, an entry is allowed to exist in a possibly incomplete, possibly inconsistent state, usually to allow it to be modified in multiple PDUs. When in this state, an entry is not fully active. Entries shall exist in the underCreation(3) state until the management station is finished configuring the entry and sets this object to valid(1) or aborts, setting this object to invalid(4). If the agent determines that an entry has been in the underCreation(3) state for an abnormally long time, it may decide that the management station has crashed. If the agent makes this decision, it may set this object to invalid(4) to reclaim the entry. A prudent agent will understand that the management station may need to wait for human input and will allow for that possibility in its determination of this abnormally long period. An entry in the valid(1) state is fully configured and consistent and fully represents the configuration or operation such a row is intended to represent. For example, it could be a statistical function that is configured and active, or a filter that is available in the list of filters processed by the packet capture process. A manager is restricted to changing the state of an entry in the following ways: To: valid createRequest underCreation invalid From: valid OK NO OK OK createRequest N/A N/A N/A N/A underCreation OK NO OK OK invalid NO NO NO OK nonExistent NO OK NO OK In the table above, it is not applicable to move the state from the createRequest state to any other state because the manager will never find the variable in that state. The nonExistent state is not a value of the enumeration, rather it means that the entryStatus variable does not exist at all. An agent may allow an entryStatus variable to change state in additional ways, so long as the semantics of the states are followed. This allowance is made to ease the implementation of the agent and is made despite the fact that managers should never exercise these additional state transitions.'NEWLINE status = 'current'NEWLINE subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))NEWLINE namedValues = NamedValues(("valid", 1), ("createRequest", 2), ("underCreation", 3), ("invalid", 4))NEWLINENEWLINEclass Ipv6Address(TextualConvention, OctetString):NEWLINE description = 'This data type is used to model IPv6 addresses. This is a binary string of 16 octets in network byte-order.'NEWLINE status = 'current'NEWLINE displayHint = '2x:'NEWLINE subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(16, 16)NEWLINE fixedLength = 16NEWLINENEWLINEcompanySystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1))NEWLINEcompanyIpifGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2))NEWLINEcompanyTftpGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3))NEWLINEcompanyMiscGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 4))NEWLINEcompanySNMPV3 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5))NEWLINEcompanySTP = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6))NEWLINEcompanyDot1qVlanGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7))NEWLINEcompanyLA = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8))NEWLINEcompanyStaticMAC = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9))NEWLINEcompanyIgsGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10))NEWLINEcompanyGVRPGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11))NEWLINEcompanyQoSGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12))NEWLINEcompanyTrafficMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13))NEWLINEcompanySecurity = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14))NEWLINEcompanyACLGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15))NEWLINEcompanySyslog = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16))NEWLINEcompanyLBD = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17))NEWLINEcompanyMirror = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18))NEWLINEcompanyStaticMcast = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19))NEWLINEcompanySNTPSetting = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20))NEWLINEcompanyRMON = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22))NEWLINEcompanyAuthGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23))NEWLINEcompanyGuestVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 24))NEWLINEcompanyMacNotify = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25))NEWLINEcompanyISMVLAN = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27))NEWLINEcompanyDHCPRelay = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28))NEWLINEcompanyDHCPLocalRelay = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29))NEWLINEcompanyTrapSetting = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30))NEWLINEsysFirmwareInfomation = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31))NEWLINEcompanyLLDPSetting = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32))NEWLINEcompanyCPUInterfaceFilterGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33))NEWLINEcompanyStaticARP = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34))NEWLINEcompanyCableDiagnostic = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35))NEWLINEcompanyVLANTrunk = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36))NEWLINEcompanyQinQ = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37))NEWLINEcompanyTimeRangeMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38))NEWLINEcompanySMTP = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40))NEWLINEcompanyLimitIp = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45))NEWLINEcompanyGratuitousARP = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48))NEWLINEcompanyMulticastFilter = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49))NEWLINEcompanyNeighbor = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50))NEWLINEcompanyEoam = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51))NEWLINEcompanyDuld = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52))NEWLINEcompanyMacBasedVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70))NEWLINEcompanyBPDUAttack = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77))NEWLINEcompanyDHCPv6Relay = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86))NEWLINEcompanyMldsGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88))NEWLINEcompanyPPPoE = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98))NEWLINEcompanyDoSCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99))NEWLINEcompanyAgentBasicInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100))NEWLINEcompanyProtocolVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101))NEWLINEcompanyL2PT = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102))NEWLINEcompanySfpVendorInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104))NEWLINEcompanyDDM = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105))NEWLINEcompanyFTPGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107))NEWLINEcompanyTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120))NEWLINEsysSwitchName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSwitchName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSwitchName.setDescription('System name used for identification of the device. The following characters are allowed to input. 0 ~ 9 / a ~ z / A ~ Z Special character: ( ) V + _ = .')NEWLINEsysHardwareVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysHardwareVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysHardwareVersion.setDescription('Version number of the Hardware.')NEWLINEsysFirmwareVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysFirmwareVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysFirmwareVersion.setDescription('Version number of the Firmware.')NEWLINEsysLoginTimeoutInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(3, 30)).clone(5)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLoginTimeoutInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLoginTimeoutInterval.setDescription('This time interval is used to count the time and logout web interface automatically.')NEWLINEsysLocationName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLocationName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLocationName.setDescription("The location name of this node (e.g., `telephone closet, 3rd floor'). If the location is unknown, the value is the zero-length string.")NEWLINEsysGroupInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(120, 1225), ))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGroupInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGroupInterval.setDescription('Group Interval is used to send D-link Discover packet to D-link SmartConsole Utility frequency. The timer in units of seconds. Set value 0 to disable group Interval.')NEWLINEsysSafeGuardEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('enable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSafeGuardEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSafeGuardEnable.setDescription('This object is used to set Safeguard Enable\\Disable.')NEWLINEsysRestart = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 9), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysRestart.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysRestart.setDescription("This object allows the user to restart the Switch (i.e)the entire switch will operationally go down and start again. Setting a value of 'true' causes the switch to be restarted. When the switch operationally goes down, configuration save operation is initiated based on the configuration save option chosen. When the switch operationally come up, the saved configurations are restored based on the restore option chosen. Once the switch is restarted, the value of this object reverts to 'false'.")NEWLINEsysSave = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("true", 1), ("false", 2), ("config-1", 3), ("config-2", 4))).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSave.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSave.setDescription('This object is used to save Configuration , value 1 save config_1 , value 2 is not in process , value 3 is save config_1 and value 4 is save config_2.')NEWLINEsysJumboFrameEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysJumboFrameEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysJumboFrameEnable.setDescription('Gigabit Web Smart Switches support jumbo frames (frames larger than the Ethernet frame size of 1522 bytes) of up to 10,000 bytes (tagged). Default jumbo frame is disabled.')NEWLINEsysPortCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13), )NEWLINEif mibBuilder.loadTexts: sysPortCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlTable.setDescription('A table to control the port specific parameters of the device like speed, duplex mode, etc.')NEWLINEsysPortCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysPortCtrlIndex"), (0, "DES-1210-28MEbx", "sysPortCtrlMediumType"))NEWLINEif mibBuilder.loadTexts: sysPortCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlEntry.setDescription('An entry appears in this table for each interface in the system. Index to the table is the interface index of the port.')NEWLINEsysPortCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlIndex.setDescription('Interface index of the port for the configuration in this entry applies.')NEWLINEsysPortCtrlMediumType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(100, 101))).clone(namedValues=NamedValues(("copper", 100), ("fiber", 101)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlMediumType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlMediumType.setDescription('This object indicates the port type: fiber 1G/100M or copper.')NEWLINEsysPortCtrlSpeed = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("rate1000M-Full", 1), ("rate100M-Full", 2), ("rate100M-Half", 3), ("rate10M-Full", 4), ("rate10M-Half", 5), ("auto", 6), ("disable", 7)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortCtrlSpeed.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlSpeed.setDescription('Configures interface speed.')NEWLINEsysPortCtrlOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("down", 1), ("rate1000M-Full", 2), ("rate100M-Full", 3), ("rate100M-Half", 4), ("rate10M-Full", 5), ("rate10M-Half", 6), ("rate10G-Full", 7)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlOperStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlOperStatus.setDescription("The port's operating speed state.")NEWLINEsysPortCtrlMDI = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("auto", 1), ("mdi", 2), ("mdix", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortCtrlMDI.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlMDI.setDescription('Configures interface auto/mdi/mdix mode. The default setting is Auto.')NEWLINEsysPortCtrlFlowControl = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortCtrlFlowControl.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlFlowControl.setDescription('Enables / disables flow control for the interface.')NEWLINEsysPortCtrlFlowControlOper = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlFlowControlOper.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlFlowControlOper.setDescription("The link parner negotiate port's operating flow control state.")NEWLINEsysPortCtrlType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("fastethernet", 1), ("gigabitethernet", 2), ("fiberwith100Base-and-1000BaseSFPModule", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlType.setDescription("The port's media type.")NEWLINEsysPortCtrlCapability = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 9), Bits().clone(namedValues=NamedValues(("rate10-half", 0), ("rate10-full", 1), ("rate100-half", 2), ("rate100-full", 3), ("reserve", 4), ("rate1000-full", 5)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortCtrlCapability.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlCapability.setDescription("The port's capability advertised.")NEWLINEsysPortDescriptionTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14), )NEWLINEif mibBuilder.loadTexts: sysPortDescriptionTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescriptionTable.setDescription('The port description table.')NEWLINEsysPortDescriptionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysPortDescIndex"), (0, "DES-1210-28MEbx", "sysPortDescMediumType"))NEWLINEif mibBuilder.loadTexts: sysPortDescriptionEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescriptionEntry.setDescription('The port description entry.')NEWLINEsysPortDescIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortDescIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescIndex.setDescription('This object indicates the port index.')NEWLINEsysPortDescMediumType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(100, 101))).clone(namedValues=NamedValues(("copper", 100), ("fiber", 101)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortDescMediumType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescMediumType.setDescription('This object indicates the port type: fiber 1G/100M or copper.')NEWLINEsysPortDescString = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortDescString.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescString.setDescription('This object indicates the port description.')NEWLINEsysPortUpLinkTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortUpLinkTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortUpLinkTime.setDescription('This object indicates the port link up time.')NEWLINEsysPortErrTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15), )NEWLINEif mibBuilder.loadTexts: sysPortErrTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrTable.setDescription('The port error table.')NEWLINEsysPortErrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysPortErrPortIndex"))NEWLINEif mibBuilder.loadTexts: sysPortErrEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrEntry.setDescription('A list of information for the err port of the device.')NEWLINEsysPortErrPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortErrPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrPortIndex.setDescription("This object indicates the module's port number.(1..Max port number in the module)")NEWLINEsysPortErrPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortErrPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrPortState.setDescription('This object decides whether the port state is enabled or disabled.')NEWLINEsysPortErrPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("err-disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortErrPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrPortStatus.setDescription('This object decides whether the PortStatus is err-disabled.')NEWLINEsysPortErrPortReason = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("lbd", 1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortErrPortReason.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrPortReason.setDescription('This object decides whether the PortStatus is LBD.')NEWLINEsysDhcpAutoConfiguration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysDhcpAutoConfiguration.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysDhcpAutoConfiguration.setDescription('This object indicates auto config is enabled or disabled.')NEWLINEsysWebState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysWebState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysWebState.setDescription('This object is for Enabled(1) or Disabled(2) Web state in the system.')NEWLINEsysWebPortNumber = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 18), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(80)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysWebPortNumber.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysWebPortNumber.setDescription('Web Server Port Number.')NEWLINEsysARPAgingTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 19), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysARPAgingTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysARPAgingTime.setDescription('This object is for ARP aging time.')NEWLINEsysMACAgingTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 20), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 1000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMACAgingTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMACAgingTime.setDescription('This object is for MAC aging time.')NEWLINEbaudRateConfiguration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(9600, 19200, 38400, 115200))).clone(namedValues=NamedValues(("baudrate9600", 9600), ("baudrate19200", 19200), ("baudrate38400", 38400), ("baudrate115200", 115200)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: baudRateConfiguration.setStatus('current')NEWLINEif mibBuilder.loadTexts: baudRateConfiguration.setDescription('To set SerialPort baud-rate configuration.')NEWLINEautologoutConfiguration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(120, 300, 600, 900, 0))).clone(namedValues=NamedValues(("logouttime2mins", 120), ("logouttime5mins", 300), ("logouttime10mins", 600), ("logouttime15mins", 900), ("logouttimenever", 0)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: autologoutConfiguration.setStatus('current')NEWLINEif mibBuilder.loadTexts: autologoutConfiguration.setDescription('To set SerialPort auto-logout-time configuration.')NEWLINEtelnetsettingManagementOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 23), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: telnetsettingManagementOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: telnetsettingManagementOnOff.setDescription('Enable/Disable management Telnetsetting mechanism.')NEWLINEtelnetUDPPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 24), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(23)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: telnetUDPPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: telnetUDPPort.setDescription("The value is for setting telnet's UDP Port.")NEWLINEautoRefreshConfiguration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("refreshimenever", 0), ("refreshtime10secs", 1), ("refreshtime30secs", 2), ("refreshtime1min", 3), ("refreshtime5mins", 4)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: autoRefreshConfiguration.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoRefreshConfiguration.setDescription('To set the WEB panel auto refresh timer.')NEWLINEfloodfdbOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 26), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: floodfdbOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: floodfdbOnOff.setDescription('To set enable status for flood fdb.')NEWLINEsysContactName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 27), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysContactName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysContactName.setDescription('To set system contact name.')NEWLINEsysDhcpAutoConfigTimeout = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 28), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysDhcpAutoConfigTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysDhcpAutoConfigTimeout.setDescription('To set dhcp auto config timeout.')NEWLINEsysCommandLogging = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 29), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysCommandLogging.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysCommandLogging.setDescription('To set enable status for CommandLogging.')NEWLINEsysSerialNumber = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 30), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 13))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysSerialNumber.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSerialNumber.setDescription('To get the serial number.')NEWLINEsysVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysVersion.setDescription('The version of firmware information.')NEWLINEsysSize = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysSize.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSize.setDescription('The size of firmware information.')NEWLINEsysUpdateTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysUpdateTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysUpdateTime.setDescription('The Update Time of firmware information.')NEWLINEsysFromIP = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 4), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysFromIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysFromIP.setDescription('The IP address of firmware information.')NEWLINEsysUser = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 9))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysUser.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysUser.setDescription('The user of firmware infomation.')NEWLINEsysType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, -1))).clone(namedValues=NamedValues(("console", 1), ("telnet", 2), ("ssh", 3), ("web", 4), ("unknown", -1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysType.setDescription('The type of firmware infomation.')NEWLINEsysBootupConfigID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 33), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBootupConfigID.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBootupConfigID.setDescription('To get/set bootup config ID.')NEWLINEsysDhcpAutoImage = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 34), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysDhcpAutoImage.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysDhcpAutoImage.setDescription('This object indicates auto image is enabled or disabled.')NEWLINEsysPortMediaTypeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36), )NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeTable.setDescription('A table to control the port specific parameters of the device like speed, Vendor name, etc.')NEWLINEsysPortMediaTypeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysPortMediaTypeIndex"), (0, "DES-1210-28MEbx", "sysPortMediaType"))NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeEntry.setDescription('An entry appears in this table for each interface in the system. Index to the table is the interface index of the port.')NEWLINEsysPortMediaTypeIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeIndex.setDescription('Interface index of the port for the configuration in this entry applies.')NEWLINEsysPortMediaType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(100, 101))).clone(namedValues=NamedValues(("copper", 100), ("fiber", 101)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaType.setDescription('This object indicates the port type: fiber 1G/100M or copper.')NEWLINEsysPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("rate100M", 1), ("rate1000M", 2), ("rate10G", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortType.setDescription('Configures interface speed.')NEWLINEsysPortMediaTypeVendorName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeVendorName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeVendorName.setDescription("The port's VendorName.")NEWLINEsysPortMediaTypeOui = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeOui.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeOui.setDescription("The port's Oui.")NEWLINEsysPortMediaTypePn = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypePn.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypePn.setDescription("The port's Pn.")NEWLINEsysPortMediaTypeRev = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeRev.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeRev.setDescription("The port's Rev.")NEWLINEsysPortMediaTypeSn = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeSn.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeSn.setDescription("The port's Sn.")NEWLINEsysPortMediaTypeDateCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeDateCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeDateCode.setDescription("The port's DateCode.")NEWLINEipv4sysIpAddrCfgMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("manual", 1), ("dynamic", 2))).clone('manual')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIpAddrCfgMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIpAddrCfgMode.setDescription("Specifies the means by which the default interface in the device gets the IP address. If 'manual' mode is selected, the default interface takes the 'sysDefaultIpAddr' configured in the system. If 'dynamic' mode is selected, the default interface gets the IP address through dynamic IP address configuration protocols such as RARP client, BootP client, DHCP Client, etc. If the system fails to get the IP address dynamically through all the above protocols, the default interface uses the 'sysDefaultIpAddr' configured in the system.")NEWLINEipv4sysIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIpAddr.setDescription('Default IP Address of the system. This IP address, if modified, will take effect only when the configuration is stored & restored.')NEWLINEipv4sysIpSubnetMask = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 3), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIpSubnetMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIpSubnetMask.setDescription('IP subnet mask for the default IP address. This subnet mask, if modified, will take effect only when the configuration is stored & restored.')NEWLINEipv4sysGateway = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 4), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysGateway.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysGateway.setDescription('Gateway')NEWLINEipv4dhcpOption12Status = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4dhcpOption12Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4dhcpOption12Status.setDescription('Status of DHCP Option12')NEWLINEipv4dhcpOption12HostName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 6), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4dhcpOption12HostName.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4dhcpOption12HostName.setDescription('Host name in DHCP option 12')NEWLINEipifSupportV4V6Info = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7))NEWLINEsysIpAddrCfgMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("manual", 1), ("dynamic", 2))).clone('manual')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysIpAddrCfgMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysIpAddrCfgMode.setDescription("Specifies the means by which the default interface in the device gets the IP address. If 'manual' mode is selected, the default interface takes the 'sysDefaultIpAddr' configured in the system. If 'dynamic' mode is selected, the default interface gets the IP address through dynamic IP address configuration protocols such as RARP client, BootP client, DHCP Client, etc. If the system fails to get the IP address dynamically through all the above protocols, the default interface uses the 'sysDefaultIpAddr' configured in the system.")NEWLINEsysIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysIpAddr.setDescription('Default IP Address of the system. This IP address, if modified, will take effect only when the configuration is stored & restored.')NEWLINEsysIpSubnetMask = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 3), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysIpSubnetMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysIpSubnetMask.setDescription('IP subnet mask for the default IP address. This subnet mask, if modified, will take effect only when the configuration is stored & restored.')NEWLINEsysGateway = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 4), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGateway.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGateway.setDescription('Gateway')NEWLINEdhcpOption12Status = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpOption12Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpOption12Status.setDescription('Status of DHCP Option12')NEWLINEdhcpOption12HostName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 6), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpOption12HostName.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpOption12HostName.setDescription('Host name in DHCP option 12')NEWLINEipifName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 7), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifName.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifName.setDescription('The Description for the interface.')NEWLINEipifVLANname = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 8), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifVLANname.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifVLANname.setDescription('The vlan name for the interface.')NEWLINEipifv6GlobalStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6GlobalStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6GlobalStatus.setDescription('The ID of VLAN that you want this interface to be in. It must be a exist vlan id.')NEWLINEipifv6DHCPStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6DHCPStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6DHCPStatus.setDescription('The state of DHCPv6 that you want this interface to be in. It must be a exist vlan id.')NEWLINEipifv6AutolinkloStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6AutolinkloStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6AutolinkloStatus.setDescription('The global state of link local that you want this interface to be in. It must be a exist vlan id.')NEWLINEipifv6NSRetransmitTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 12), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6NSRetransmitTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6NSRetransmitTime.setDescription("The NS's retransmit time that you want this interface to be in. It must be a exist vlan id (1~3600).")NEWLINEipifv6DefaultGateway = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 13), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6DefaultGateway.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6DefaultGateway.setDescription('The ipv6 default gateway that you want this interface to be in. It must be a exist vlan id.')NEWLINEipifV6AddressTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14), )NEWLINEif mibBuilder.loadTexts: ipifV6AddressTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressTable.setDescription('A list of interface entries.')NEWLINEipifV6AddressEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipifV6AddressMainIndex"), (0, "DES-1210-28MEbx", "ipifV6AddressIpAddr"), (0, "DES-1210-28MEbx", "ipifV6AddressIpPrefix"))NEWLINEif mibBuilder.loadTexts: ipifV6AddressEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressEntry.setDescription('An entry containing management information applicable to a particular interface.')NEWLINEipifV6AddressMainIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifV6AddressMainIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressMainIndex.setDescription('The index of this IPv6 entry.')NEWLINEipifV6AddressIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 2), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpAddr.setDescription('The ip address of this IPv6 entry.')NEWLINEipifV6AddressIpPrefix = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpPrefix.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpPrefix.setDescription('The ip prefix of this IPv6 entry.')NEWLINEipifV6AddressIpType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("unicast", 1), ("anycast", 2), ("linklocal", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpType.setDescription('The ip type of this IPv6 entry.')NEWLINEipifV6AddressRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 5), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipifV6AddressRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressRowStatus.setDescription('The status of an entry in the Multi Interface Table. Only a subset of the rowstatus variables (active, createAndWait, destroy) are available.')NEWLINEipv4sysIprouteGateway = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 8), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIprouteGateway.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIprouteGateway.setDescription('IProute Gateway of the system.')NEWLINEipv4sysIprouteHops = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 9), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIprouteHops.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIprouteHops.setDescription('IProute Hops of the system.')NEWLINEtftpFwServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 1), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwServerIpAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpFwServerIpAddress.setDescription("The TFTP server's IP address is used to upload or download firmware.")NEWLINEtftpFwImageFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwImageFileName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpFwImageFileName.setDescription('Configure firmware filename to download.')NEWLINEtftpFwTftpOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("download", 1), ("upload", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTftpOperation.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpFwTftpOperation.setDescription('The tftp operates to perform downloading the firmware image to the unit. This object is used in conjunction with configBootTftpServerIp and configBootImageFileName.')NEWLINEtftpFwTftpOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3), ("transmit", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: tftpFwTftpOperationStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpFwTftpOperationStatus.setDescription('The tftp operation status represent firmware backup or upgrade status.')NEWLINEtftpCfgServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 5), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgServerIpAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpCfgServerIpAddress.setDescription("The TFTP server's IP address is used to upload or download configuration file.")NEWLINEtftpConfigFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpConfigFileName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpConfigFileName.setDescription('The configuration filename is used to store or retrieve config from the tftp server.')NEWLINEtftpConfigTftpOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("download", 1), ("upload", 2), ("progressing", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpConfigTftpOperation.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpConfigTftpOperation.setDescription('The tftp operates to perform either downloading the configuration file to the unit or uploading the current configuration file to the tftp server. This object is used in conjunction with configTftpServerIpAddress and configTftpServerFileName.')NEWLINEtftpConfigTftpOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: tftpConfigTftpOperationStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpConfigTftpOperationStatus.setDescription('The tftp operation status represent configuration file backup or restore status.')NEWLINEtftpFwTargetGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9))NEWLINEtftpFwTargetServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 1), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetServerIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetServerIpAddress.setDescription("The TFTP server's IP address is used to upload or download firmware.")NEWLINEtftpFwTargetServerIpType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetServerIpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetServerIpType.setDescription('Type of IP interface.')NEWLINEtftpFwTargetInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 3), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetInterfaceName.setDescription('Specifies the interface name when the tftpFwTargetServerIpAddress is linklocal address.')NEWLINEtftpFwTargetImageFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetImageFileName.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetImageFileName.setDescription('Configure firmware filename to download.')NEWLINEtftpFwTargetTftpOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("download", 1), ("upload", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetTftpOperation.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetTftpOperation.setDescription('The tftp operates to perform downloading the firmware image to the unit. This object is used in conjunction with configBootTftpServerIp and configBootImageFileName.')NEWLINEtftpFwTargetTftpOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3), ("transmit", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: tftpFwTargetTftpOperationStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetTftpOperationStatus.setDescription('The tftp operation status represent firmware backup or upgrade status.')NEWLINEtftpCfgTargetGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10))NEWLINEtftpCfgTargetServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 1), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetServerIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetServerIpAddress.setDescription("The TFTP server's IP address is used to upload or download configuration file.")NEWLINEtftpCfgTargetServerIpType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetServerIpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetServerIpType.setDescription('Type of IP interface.')NEWLINEtftpCfgTargetInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 3), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetInterfaceName.setDescription('Specifies the interface name when the tftpCfgTargetServerIpAddress is linklocal address.')NEWLINEtftpCfgTargetImageFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetImageFileName.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetImageFileName.setDescription('The configuration filename is used to store or retrieve config from the tftp server.')NEWLINEtftpCfgTargetTftpOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("download", 1), ("upload", 2), ("progressing", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpOperation.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpOperation.setDescription('The tftp operates to perform either downloading the configuration file to the unit or uploading the current configuration file to the tftp server. This object is used in conjunction with configTftpServerIpAddress and configTftpServerFileName.')NEWLINEtftpCfgTargetTftpOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpOperationStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpOperationStatus.setDescription('The tftp operation status represent configuration file backup or restore status.')NEWLINEtftpCfgTargetTftpConfigID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("configId-1", 1), ("configId-2", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpConfigID.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpConfigID.setDescription('The tftp config ID determine which config what you need.')NEWLINEtftpCfgTargetTftpIncrement = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("false", 0), ("true", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpIncrement.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpIncrement.setDescription('The tftp increment determine download config behavior.')NEWLINEmiscReset = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 4, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("reset", 1), ("noop", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: miscReset.setStatus('current')NEWLINEif mibBuilder.loadTexts: miscReset.setDescription('Physically resets the unit - use with care. A (1) resets the unit, a (2) does nothing.')NEWLINEmiscStatisticsReset = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 4, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("reset", 1), ("noop", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: miscStatisticsReset.setStatus('current')NEWLINEif mibBuilder.loadTexts: miscStatisticsReset.setDescription('Resets the units statistics. A (1) resets the statistics count, a (2) does nothing.')NEWLINEsecurityIpMacPortBinding = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10))NEWLINEimpbSettingTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1), )NEWLINEif mibBuilder.loadTexts: impbSettingTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbSettingTable.setDescription('A table to control IP-MAC-Port Binding Setting features of the device.')NEWLINEimpbSettingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbPortIndex"))NEWLINEif mibBuilder.loadTexts: impbSettingEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbSettingEntry.setDescription('An entry appears in IP-MAC-Port Binding Setting table for each interface in the system.')NEWLINEimpbPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortIndex.setDescription("Specifies the port numbers through which the authorized manager can access the switch. By default the authorized manager is allowed to access the switch through all the ports. If a set of ports are configured in the 'PortList', the manager can access the switch only through the configured ports.")NEWLINEimpbPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortState.setDescription('Disable / enable IP-MAC-Port Binding admin state for the interface.')NEWLINEimpbPortDHCPSnoopingState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPSnoopingState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPSnoopingState.setDescription('Disable / enable IP-MAC-Port Binding DHCP snooping state for the interface.')NEWLINEimpbPortArpInspectionState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("disabled", 0), ("strict", 1), ("loose", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortArpInspectionState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortArpInspectionState.setDescription('Set IP-MAC-Port Binding ARP Inspection state for the interface.')NEWLINEimpbPortIpInspectionState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortIpInspectionState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortIpInspectionState.setDescription('Set IP-MAC-Port Binding IP Inspection state for the interface.')NEWLINEimpbPortAllowZeroIPState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortAllowZeroIPState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortAllowZeroIPState.setDescription('Disable / enable IP-MAC-Port Binding Allow-Zero-IP state for the interface.')NEWLINEimpbPortForwardDHCPPktState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortForwardDHCPPktState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortForwardDHCPPktState.setDescription('Disable / enable IP-MAC-Port Binding Forward-DHCP-Packet state for the interface.')NEWLINEimpbPortDHCPMaxEntryIPv4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 10))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPMaxEntryIPv4.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPMaxEntryIPv4.setDescription('Set the maximum number of IPv4 entries that can be learned for the interface.')NEWLINEimpbPortDHCPMaxEntryIPv6 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 10))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPMaxEntryIPv6.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPMaxEntryIPv6.setDescription('Set the maximum number of IPv6 entries that can be learned for the interface.')NEWLINEimpbPortNDInspectionState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortNDInspectionState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortNDInspectionState.setDescription('Set IP-MAC-Port Binding ND Inspection state for the interface.')NEWLINEimpbPortProtocolState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("ipv4", 0), ("ipv6", 1), ("all", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortProtocolState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortProtocolState.setDescription('Set IP-MAC-Port Binding protocol state for the interface.')NEWLINEimpbPortDHCPv4SetVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 13), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4SetVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4SetVlanList.setDescription('A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. The set of vlans configured by management to map for this Instance. If the VlanId to Instance Mapping has to be known then any one of the VlanMapped object should be used.If a vlan is already mapped to this Instance, it may not be mapped again. This object is used only for SET operation. GET Operation returns null values.')NEWLINEimpbPortDHCPv4VlanList1k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 14), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList1k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList1k.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCP snooping, the bit corresponding to that VLAN is set to '1'. ")NEWLINEimpbPortDHCPv4VlanList2k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 15), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList2k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1025 through 2048. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv4 snooping, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv4VlanList3k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 16), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2049 through 3072. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv4 snooping the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv4VlanList4k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 17), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3073 through 4094. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv4 snooping, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv6SetVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 18), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6SetVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6SetVlanList.setDescription('A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. The set of vlans configured by management to map for this Instance. If the VlanId to Instance Mapping has to be known then any one of the VlanMapped object should be used.If a vlan is already mapped to this Instance, it may not be mapped again. This object is used only for SET operation. GET Operation returns null values.')NEWLINEimpbPortDHCPv6VlanList1k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 19), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList1k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList1k.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCP snooping, the bit corresponding to that VLAN is set to '1'. ")NEWLINEimpbPortDHCPv6VlanList2k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 20), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList2k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1025 through 2048. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv6 snooping, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv6VlanList3k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 21), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2049 through 3072. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv6 snooping the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv6VlanList4k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 22), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3073 through 4094. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv6 snooping, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbAutoScanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2), )NEWLINEif mibBuilder.loadTexts: impbAutoScanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanTable.setDescription('A table to control auto scan features of the device.')NEWLINEimpbAutoScanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbAutoScanMacAddress"), (0, "DES-1210-28MEbx", "impbAutoScanPort"), (0, "DES-1210-28MEbx", "impbAutoScanIpAddress"))NEWLINEif mibBuilder.loadTexts: impbAutoScanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanEntry.setDescription('An entry appears in auto scan table for each interface in the system.')NEWLINEimpbAutoScanMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 1), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanMacAddress.setDescription('The MAC address associated of the auto scan entry.')NEWLINEimpbAutoScanPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanPort.setDescription('The port number of the auto scan entry. For all machines give maximum port number.')NEWLINEimpbAutoScanIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 3), DisplayString().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddress.setDescription('The IP address associated of the auto scan entry.')NEWLINEimpbAutoScanVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanVlanId.setDescription('The VLAN ID of the auto scan entry.')NEWLINEimpbAutoScanBinding = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbAutoScanBinding.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanBinding.setDescription('Disable / enable IP-MAC-Port Binding for the entry.')NEWLINEimpbBindingListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3), )NEWLINEif mibBuilder.loadTexts: impbBindingListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListTable.setDescription('A table to control Manual IP-MAC-Port Binding white list features of the device.')NEWLINEimpbBindingListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbBindingListIpAddress"), (0, "DES-1210-28MEbx", "impbBindingListMacAddress"))NEWLINEif mibBuilder.loadTexts: impbBindingListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListEntry.setDescription('An entry appears in Manual IP-MAC-Port Binding white list table for each interface in the system.')NEWLINEimpbBindingListIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1, 1), DisplayString().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBindingListIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListIpAddress.setDescription('The IP address associated of the Manual IP-MAC-PORT Binding white list entry.')NEWLINEimpbBindingListMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1, 2), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBindingListMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListMacAddress.setDescription('The MAC address associated of the Manual IP-MAC-PORT Binding white list entry.')NEWLINEimpbBindingListPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1, 3), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbBindingListPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListPort.setDescription('The port number of the Manual IP-MAC-PORT Binding white list entry.')NEWLINEimpbBindingListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: impbBindingListRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListRowStatus.setDescription('The status of a row in impbBindingListTable. By setting this object, new entries can be created in impbBindingListTable and existing entries can be removed from impbBindingListTable. It can be used as specified in the SNMP v2 standard.')NEWLINEimpbBlockListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4), )NEWLINEif mibBuilder.loadTexts: impbBlockListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListTable.setDescription('A table to control IP-MAC-Port Binding black list of the device.')NEWLINEimpbBlockListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbBlockListMacAddress"), (0, "DES-1210-28MEbx", "impbBlockListVlanId"), (0, "DES-1210-28MEbx", "impbBlockListPort"))NEWLINEif mibBuilder.loadTexts: impbBlockListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListEntry.setDescription('An entry appears in Manual IP-MAC-Port Binding black list table for each interface in the system.')NEWLINEimpbBlockListMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 1), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBlockListMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListMacAddress.setDescription('The MAC address associated of the IP-MAC-PORT Binding black list entry.')NEWLINEimpbBlockListVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBlockListVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListVlanId.setDescription('The VLAN ID of the IP-MAC-PORT Binding black list entry.')NEWLINEimpbBlockListPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBlockListPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListPort.setDescription('The port number of the IP-MAC-PORT Binding black list entry.')NEWLINEimpbBlockListIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 4), DisplayString().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBlockListIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListIpAddress.setDescription('The IP address associated of the IP-MAC-PORT Binding black list entry.')NEWLINEimpbBlockListStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("nothing", 0), ("deleted", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbBlockListStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListStatus.setDescription('nothing/delete IP-MAC-Port Binding for the interface.')NEWLINEimpbAutoScanIpAddressFrom = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 5), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddressFrom.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddressFrom.setDescription('The begin for IP address associated of the IP-MAC-PORT Binding auto scan entry.')NEWLINEimpbAutoScanIpAddressTo = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 6), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddressTo.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddressTo.setDescription('The end for IP address associated of the IP-MAC-PORT Binding auto scan entry.')NEWLINEimpbAutoScanStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("nothing", 0), ("scan", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbAutoScanStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanStatus.setDescription('Nothing / scan IP-MAC-Port Binding auto scan for the interface.')NEWLINEimpbDhcpSnoopingTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8), )NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingTable.setDescription('A table to display DHCP snooping entries of the device.')NEWLINEimpbDhcpSnoopingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbDhcpSnoopingMacAddress"), (0, "DES-1210-28MEbx", "impbDhcpSnoopingIpAddress"))NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingEntry.setDescription('An entry appears in DHCP snooping table for each interface in the system.')NEWLINEimpbDhcpSnoopingMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1, 1), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingMacAddress.setDescription('The MAC address associated of the DHCP snooping entry.')NEWLINEimpbDhcpSnoopingIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1, 2), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingIpAddress.setDescription('The IP address associated of the DHCP snooping entry.')NEWLINEimpbDhcpSnoopingLeaseTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1, 3), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingLeaseTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingLeaseTime.setDescription('The lease time associated of the DHCP snooping entry.')NEWLINEimpbDhcpSnoopingPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingPort.setDescription('The port number associated of the DHCP snooping entry.')NEWLINEimpbRoamingState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbRoamingState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbRoamingState.setDescription('Disable / enable IP-MAC-Port Binding roaming state.')NEWLINEimpbVlanModeState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbVlanModeState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbVlanModeState.setDescription('Disable / enable IP-MAC-Port Binding vlan mode state.')NEWLINEimpbVlanModeVlanList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 11), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbVlanModeVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbVlanModeVlanList.setDescription('IP-MAC-Port Binding vlan mode VID list.')NEWLINEimpbLogState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("disabled", 0), ("ipv4", 1), ("ipv6", 2), ("all", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbLogState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbLogState.setDescription('Configure IP-MAC-Port Binding log state.')NEWLINEimpbDHCPv6PrefixDelegationSnoopState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbDHCPv6PrefixDelegationSnoopState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDHCPv6PrefixDelegationSnoopState.setDescription('Configure DHCPv6 PD snooping state.')NEWLINEimpbBindingtraplog = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2, 1))).clone(namedValues=NamedValues(("disabled", 2), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbBindingtraplog.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingtraplog.setDescription('This object is for enabling or disabling topology change event trap in the system.')NEWLINEimpbBindingtrap = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 15))NEWLINEimpbBindingtrapsign = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 15, 1))NEWLINEif mibBuilder.loadTexts: impbBindingtrapsign.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingtrapsign.setDescription('The object is for IMPB trap sign in the system.')NEWLINEimpbAutoScanCurrentStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("stop", 0), ("scanning", 1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanCurrentStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanCurrentStatus.setDescription('Show Auto scan status')NEWLINEstpBridgeGlobal = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1))NEWLINEstpModuleStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpModuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpModuleStatus.setDescription('The administrative status requested by management for the MST feature. The value enabled(1) indicates that Mst should be enabled in the device on all ports. The value disabled(2) indicates that Mst should be disabled in the device on all ports. The object can be set to enabled(1) if and only if, fsMIMstSystemControl set to start.')NEWLINEstpProtocolVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("stp", 1), ("rstp", 2), ("mstp", 3))).clone('mstp')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpProtocolVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpProtocolVersion.setDescription("The version of Spanning Tree Protocol the bridge is currently running. The value 'stpCompatible(0)' indicates the Spanning Tree Protocol specified in IEEE 802.1D and 'rstp(2)' indicates the Rapid Spanning Tree Protocol specified in IEEE 802.1w and 'mstp(3)' indicates the Multiple Spanning Tree Protocol Specified in IEEE 802.1s.")NEWLINEstpBridgePriority = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 61440)).clone(32768)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpBridgePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpBridgePriority.setDescription('The Value of the writable portion of the Bridge Identifier comprising of the first two octets. The values that are set for Bridge Priority must be in steps of 4096.')NEWLINEstpTxHoldCount = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10)).clone(3)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpTxHoldCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpTxHoldCount.setDescription('The value used by the Port Transmit state machine to limit the maximum transmission rate.')NEWLINEstpBridgeMaxAge = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 5), Timeout().subtype(subtypeSpec=ValueRangeConstraint(600, 4000)).clone(2000)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpBridgeMaxAge.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpBridgeMaxAge.setDescription('The value that all bridges use for MaxAge when this bridge is acting as the root. The granularity of this timer is specified to be 1 second. An agent may return a badValue error if a set is attempted to a value which is not a whole number of seconds.')NEWLINEstpBridgeHelloTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 6), Timeout().subtype(subtypeSpec=ValueRangeConstraint(100, 1000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpBridgeHelloTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpBridgeHelloTime.setDescription('The amount of time between the transmission of Configuration bridge PDUs by this node in units of hundredths of a second.')NEWLINEstpBridgeForwardDelay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 7), Timeout().subtype(subtypeSpec=ValueRangeConstraint(400, 3000)).clone(1500)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpBridgeForwardDelay.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpBridgeForwardDelay.setDescription('The value that all bridges use for ForwardDelay when this bridge is acting as the root. Note that 802.1D specifies that the range for this parameter is related to the value of BridgeMaxAge. The granularity of this timer is specified to be 1 second. An agent may return a badValue error if a set is attempted to a value which is not a whole number of seconds.')NEWLINEstpFowardBPDU = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpFowardBPDU.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpFowardBPDU.setDescription('This object is for enabling or disabling forward BPDU.')NEWLINEstpRootBridge = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 9), BridgeId()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpRootBridge.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpRootBridge.setDescription('The bridge identifier of the Root of the common spanning tree as determined by the Spanning Tree Protocol as executed by this node. This value is used as the CIST Root Identifier parameter in all Configuration Bridge PDUs originated by this node.')NEWLINEstpRootCost = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 10), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpRootCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpRootCost.setDescription('The Cost of the path to the CIST Root as seen from this bridge.')NEWLINEstpMaxAge = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 11), Timeout()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpMaxAge.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpMaxAge.setDescription('The maximum age of Spanning Tree Protocol information learned from the network on any port before it is discarded, in units of hundredths of a second. This is the actual value that this bridge is currently using.')NEWLINEstpForwardDelay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 12), Timeout()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpForwardDelay.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpForwardDelay.setDescription('This time value, measured in units of hundredths of a second, controls how fast a port changes its spanning state when moving towards the Forwarding state. The value determines how long the port stays in a particular state before moving to the next state.')NEWLINEstpRootPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 13), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpRootPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpRootPort.setDescription('The Port Number of the Port which offers the lowest path cost from this bridge to the CIST Root Bridge.')NEWLINEstpTopologyChangeTrapStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpTopologyChangeTrapStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpTopologyChangeTrapStatus.setDescription('This object is for enabling or disabling topology change event trap in the system.')NEWLINEstpNewRootTrapStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpNewRootTrapStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpNewRootTrapStatus.setDescription('This object is for enabling or disabling new root event trap in the system.')NEWLINEstpNewRootTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 16))NEWLINEbrgAddress = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 16, 1))NEWLINEif mibBuilder.loadTexts: brgAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: brgAddress.setDescription('The MAC address used by this bridge when it must be referred to in a unique fashion.')NEWLINEoldDesignatedRoot = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 16, 2))NEWLINEif mibBuilder.loadTexts: oldDesignatedRoot.setStatus('current')NEWLINEif mibBuilder.loadTexts: oldDesignatedRoot.setDescription('The bridge identifier of the old root of the spanning tree instance as determined by the Spanning Tree Protocol as executed by this node.')NEWLINEmstiBridgeRegionalRoot = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 16, 3))NEWLINEif mibBuilder.loadTexts: mstiBridgeRegionalRoot.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstiBridgeRegionalRoot.setDescription('MSTI Regional Root Identifier value for the Instance.')NEWLINEstpPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2), )NEWLINEif mibBuilder.loadTexts: stpPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortTable.setDescription('A table that contains port-specific information for the Spanning Tree Protocol.')NEWLINEstpPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "stpPort"))NEWLINEif mibBuilder.loadTexts: stpPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortEntry.setDescription('A list of information maintained by every port about the Spanning Tree Protocol state for that port.')NEWLINEstpPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPort.setDescription('The Port number of the port for which this entry contains spanning tree information.')NEWLINEstpPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 0))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 0)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortStatus.setDescription("Current state of the Port which can be changed to either Disabled or Enabled for ALL spanning tree instances. Setting this object will override the port's status in any of the MSTI contexts")NEWLINEstpPortPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 240)).clone(128)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortPriority.setDescription('The four most significant bits of the Port Identifier of the Spanning Tree instance can be modified by setting the CistPortPriority value. The values that are set for Port Priority must be in steps of 16.')NEWLINEstpAdminPortPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpAdminPortPathCost.setReference('IEEE 802.1D-2004')NEWLINEif mibBuilder.loadTexts: stpAdminPortPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpAdminPortPathCost.setDescription("The contribution of this port to the path cost of paths towards the spanning tree root which include this port. Writing a value of '0' assigns the automatically calculated default Path Cost value to the ohter object stpPortPathCost. If the default Path Cost is being used,this object returns '0' when read.")NEWLINEstpPortPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 200000000))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpPortPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortPathCost.setDescription('The contribution of this port to the path cost of paths towards the CIST Root which include this port.')NEWLINEstpPortProtocolMigration = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("false", 0), ("true", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortProtocolMigration.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortProtocolMigration.setDescription('Indicates the Protocol migration state of this Port. When operating in RSTP/MSTP (version >= 2) mode, writing TRUE(1) to this object forces this port to transmit MSTP BPDUs without instance information. Any other operation on this object has no effect and it always returns FALSE(2) when read.')NEWLINEstpPortEdge = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 0, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 0), ("auto", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortEdge.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortEdge.setDescription(' This parameter when TRUE(1) indicates that detection of a port as Edge Port happens automatically and FALSE(2) indicates that this feature is disabled.')NEWLINEstpPortAdminP2P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("forceTrue", 0), ("forceFalse", 1), ("auto", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortAdminP2P.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortAdminP2P.setDescription('The administrative point-to-point status of the LAN segment attached to this port. A value of forceTrue(0) indicates that this port should always be treated as if it is connected to a point-to-point link. A value of forceFalse(1) indicates that this port should be treated as having a shared media connection. A value of auto(2) indicates that this port is considered to have a point-to-point link if it is an Aggregator and all of its members are aggregatable, or if the MAC entity is configured for full duplex operation, either through auto-negotiation or by management means.')NEWLINEstpPortRestrictedRole = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 9), TruthValue()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortRestrictedRole.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortRestrictedRole.setDescription("A Boolean value set by management. If TRUE causes the Port not to be selected as Root Port for the CIST or any MSTI, even it has the best spanning tree priority vector. Such a Port will be selected as an Alternate Port after the Root Port has been selected. This parameter should be FALSE by default. If set it can cause lack of spanning tree connectivity. It is set by a network administrator to prevent bridges external to a core region of the network influencing the spanning tree active topology, possibly because those bridges are not under the full control of the administrator. This administrator configuration is also known as 'Root Guard'.")NEWLINEstpPortRestrictedTCN = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 10), TruthValue()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortRestrictedTCN.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortRestrictedTCN.setDescription('A Boolean value set by management. If TRUE causes the Port not to propagate received topology change notifications and topology changes to other Ports. This parameter should be FALSE by default. If set it can cause temporary loss of connectivity after changes in a spanning trees active topology as a result of persistent incorrectly learnt station location information. It is set by a network administrator to prevent bridges external to a core region of the network causing address flushing in that region, possibly because those bridges are not under the full control of the administrator or MAC_Operational for the attached LANs transitions frequently.')NEWLINEstpPortHelloTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 11), Timeout().subtype(subtypeSpec=ValueRangeConstraint(100, 1000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortHelloTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortHelloTime.setDescription('The amount of time between the transmission of Configuration bridge PDUs by this node in units of hundredths of a second.')NEWLINEstpPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 4, 5))).clone(namedValues=NamedValues(("disabled", 1), ("discarding", 2), ("learning", 4), ("forwarding", 5)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortState.setDescription('Current state of the Port as defined by the Common spanning tree protocol.')NEWLINEstpPortFowardBPDU = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortFowardBPDU.setReference('IEEE 802.1D-2004')NEWLINEif mibBuilder.loadTexts: stpPortFowardBPDU.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortFowardBPDU.setDescription('This object is for enabling or disabling forward BPDU.')NEWLINEmstConfigurationIdentification = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3))NEWLINEmstiConfigurationName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstiConfigurationName.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstiConfigurationName.setDescription("The Name for the Region's configuration. By Default Region Name will be equal to the Bridge Mac Address.")NEWLINEmstiRevisionLevel = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstiRevisionLevel.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstiRevisionLevel.setDescription('Version of the MST Region.')NEWLINEmstCistVlanMapped = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'.")NEWLINEmstCistVlanMapped2k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped2k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1024 through 2047. The first octet corresponds to VLANs with VlanIndex values 1024 through 1031; the second octet to VLANs 1032 through 1039 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstCistVlanMapped3k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2048 through 3071. The first octet corresponds to VLANs with VlanIndex values of 2048 through 2055; the second octet to VLANs 2056 through 2063 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstCistVlanMapped4k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3072 through 4095. The first octet corresponds to VLANs with VlanIndex values 3072 through 3079; the second octet to VLANs 3080 through 3087 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstVlanMstiMappingTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7), )NEWLINEif mibBuilder.loadTexts: mstVlanMstiMappingTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstVlanMstiMappingTable.setDescription('This table contains one entry for each instance of MSTP. This table maintains context ID as one more index to support Multiple Instances.')NEWLINEmstVlanMstiMappingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mstInstanceIndex"))NEWLINEif mibBuilder.loadTexts: mstVlanMstiMappingEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstVlanMstiMappingEntry.setDescription('A conceptual row containing the status of the MSTP instance.')NEWLINEmstInstanceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceIndex.setDescription('An arbitrary integer within the range from 1 to the value of Max Instance Number that uniquely identifies an instance.')NEWLINEmstSetVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstSetVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstSetVlanList.setDescription('A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. The set of vlans configured by management to map for this Instance. If the VlanId to Instance Mapping has to be known then any one of the VlanMapped object should be used.If a vlan is already mapped to this Instance, it may not be mapped again. This object is used only for SET operation. GET Operation returns null values.')NEWLINEmstResetVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstResetVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstResetVlanList.setDescription('A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. The set of vlans configured by management to unmap from this Instance. A vlan may not be unmapped from this instance if it is not already mapped to this Instance. This object is used only for SET operation.GET Operation returns null values.')NEWLINEmstInstanceVlanMapped = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'.")NEWLINEmstInstanceVlanMapped2k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped2k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1024 through 2047. The first octet corresponds to VLANs with VlanIndex values 1024 through 1031; the second octet to VLANs 1032 through 1039 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstInstanceVlanMapped3k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2048 through 3071. The first octet corresponds to VLANs with VlanIndex values of 2048 through 2055; the second octet to VLANs 2056 through 2063 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstInstanceVlanMapped4k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3072 through 4095. The first octet corresponds to VLANs with VlanIndex values 3072 through 3079; the second octet to VLANs 3080 through 3087 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEstpInstance = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4))NEWLINEmstCistBridgePriority = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 61440)).clone(32768)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstCistBridgePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistBridgePriority.setDescription('The writable portion of the MSTI Bridge Identifier. comprising of the first two octets. The values that are set for Bridge Priority must be in steps of 4096.')NEWLINEmstCistStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistStatus.setDescription('The administrative status requested by management for the MST feature. The value enabled(1) indicates that Mst should be enabled in the device on all ports. The value disabled(2) indicates that Mst should be disabled in the device on all ports. The object can be set to enabled(1) if and only if, fsMIMstSystemControl set to start.')NEWLINEmstMstiBridgeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3), )NEWLINEif mibBuilder.loadTexts: mstMstiBridgeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiBridgeTable.setDescription('Table containing Bridge Information specific to Spanning Tree Instance. This table maintains context ID as one more index to support Multiple Instances.')NEWLINEmstMstiBridgeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mstMstiInstanceIndex"))NEWLINEif mibBuilder.loadTexts: mstMstiBridgeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiBridgeEntry.setDescription('Entry indicating the Bridge Information.')NEWLINEmstMstiInstanceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiInstanceIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiInstanceIndex.setDescription('Spanning Tree Instance to which the information belongs.')NEWLINEmstMstiBridgePriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 61440)).clone(32768)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstMstiBridgePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiBridgePriority.setDescription('The writable portion of the MSTI Bridge Identifier. comprising of the first two octets. The values that are set for Bridge Priority must be in steps of 4096.')NEWLINEmstMstiStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiStatus.setDescription('The administrative status requested by management for the MST feature. The value enabled(1) indicates that Mst should be enabled in the device on all ports. The value disabled(2) indicates that Mst should be disabled in the device on all ports. The object can be set to enabled(1) if and only if, fsMIMstSystemControl set to start.')NEWLINEstpInstancePortTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5))NEWLINEmstCistPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1), )NEWLINEif mibBuilder.loadTexts: mstCistPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortTable.setDescription('This table contains Common Spanning Tree Port Information.')NEWLINEmstCistPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mstCistPort"))NEWLINEif mibBuilder.loadTexts: mstCistPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortEntry.setDescription('A list of information maintained by every port for Common Spanning tree.')NEWLINEmstCistPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))NEWLINEif mibBuilder.loadTexts: mstCistPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPort.setDescription('The Port number of the port for which this entry contains spanning tree information.')NEWLINEmstCistPortDesignatedBridge = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 2), BridgeId()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistPortDesignatedBridge.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortDesignatedBridge.setDescription("The unique Bridge Identifier of the bridge which this port considers to be the Designated Bridge for the port's segment.")NEWLINEmstCistPortAdminPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstCistPortAdminPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortAdminPathCost.setDescription('The contribution of this port to the path cost of paths towards the MSTI Root which include this port.')NEWLINEmstCistPortPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstCistPortPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortPathCost.setDescription('The contribution of this port to the path cost of paths towards the MSTI Root which include this port.')NEWLINEmstCistPortPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 240)).clone(128)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstCistPortPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortPriority.setDescription('The four most significant bits of the Port Identifier for a given Spanning Tree instance can be modified independently for each Spanning Tree instance supported by the Bridge. The values that are set for Port Priority must be in steps of 16.')NEWLINEmstCistForcePortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistForcePortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistForcePortState.setDescription("Current state of the Port which can be changed to either Disabled or Enabled for the specific spanning tree instance. This object can be set to enabled only if the 'fsMIMstCistForcePortState' is set to 'enabled' for this port")NEWLINEmstCistCurrentPortRole = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("disabled", 0), ("alternate", 1), ("backup", 2), ("root", 3), ("designated", 4), ("master", 5)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistCurrentPortRole.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistCurrentPortRole.setDescription('Current Port Role of the port for this spanning tree instance.')NEWLINEmstMstiPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2), )NEWLINEif mibBuilder.loadTexts: mstMstiPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortTable.setDescription('This table contains Spanning Tree Instance Specific Port Information.')NEWLINEmstMstiPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mstMstiPort"), (0, "DES-1210-28MEbx", "mstInstanceIndex"))NEWLINEif mibBuilder.loadTexts: mstMstiPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortEntry.setDescription('A list of information maintained by every port for each and every spanning tree instance.')NEWLINEmstMstiPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))NEWLINEif mibBuilder.loadTexts: mstMstiPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPort.setDescription('The Port number of the port for which this entry contains spanning tree information.')NEWLINEmstMstiPortDesignatedBridge = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 2), BridgeId()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiPortDesignatedBridge.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortDesignatedBridge.setDescription("The unique Bridge Identifier of the bridge which this port considers to be the Designated Bridge for the port's segment.")NEWLINEmstMstiPortAdminPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstMstiPortAdminPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortAdminPathCost.setDescription('The contribution of this port to the path cost of paths towards the MSTI Root which include this port.')NEWLINEmstMstiPortPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstMstiPortPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortPathCost.setDescription('The contribution of this port to the path cost of paths towards the MSTI Root which include this port.')NEWLINEmstMstiPortPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 240)).clone(128)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstMstiPortPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortPriority.setDescription('The four most significant bits of the Port Identifier for a given Spanning Tree instance can be modified independently for each Spanning Tree instance supported by the Bridge. The values that are set for Port Priority must be in steps of 16.')NEWLINEmstMstiForcePortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiForcePortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiForcePortState.setDescription("Current state of the Port which can be changed to either Disabled or Enabled for the specific spanning tree instance. This object can be set to enabled only if the 'fsMIMstCistForcePortState' is set to 'enabled' for this port")NEWLINEmstMstiCurrentPortRole = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("disabled", 0), ("alternate", 1), ("backup", 2), ("root", 3), ("designated", 4), ("master", 5)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiCurrentPortRole.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiCurrentPortRole.setDescription('Current Port Role of the port for this spanning tree instance.')NEWLINEstaticMcastTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1), )NEWLINEif mibBuilder.loadTexts: staticMcastTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastTable.setDescription('A list of the Static MACs')NEWLINEstaticMcastEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "staticMcastVlanID"), (0, "DES-1210-28MEbx", "staticMcastMac"), (0, "DES-1210-28MEbx", "staticMcastEgressPorts"), (0, "DES-1210-28MEbx", "staticMcastIpAddr"))NEWLINEif mibBuilder.loadTexts: staticMcastEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastEntry.setDescription('A Static MAC entry containing the mac and forwarding port.')NEWLINEstaticMcastVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMcastVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastVlanID.setDescription('The VLAN ID of the static MAC entry.')NEWLINEstaticMcastMac = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 2), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMcastMac.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastMac.setDescription('The MAC address associated of the static MAC entry.')NEWLINEstaticMcastEgressPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 3), PortList().subtype(subtypeSpec=ValueSizeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMcastEgressPorts.setReference('IEEE 802.1Q/D11 Section 12.7.7.3, 11.2.3.2.3')NEWLINEif mibBuilder.loadTexts: staticMcastEgressPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastEgressPorts.setDescription('The set of ports to which frames received from a specific port and destined for a specific Multicast or Broadcast MAC address must be forwarded, regardless of any dynamic information e.g. from GMRP. A port may not be added in this set if it is already a member of the set of ports in dot1qStaticMulticastForbiddenEgressPorts. The default value of this object is a string of ones of appropriate length.')NEWLINEstaticMcastIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 4), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMcastIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastIpAddr.setDescription('Static Multicast IP Address.')NEWLINEstaticMcastStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 5), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticMcastStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastStatus.setDescription('The status of an entry in the Static Mcast Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINEdot1qVlanManagementOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanManagementOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanManagementOnOff.setDescription('Enable/Disable management VLAN mechanism.')NEWLINEdot1qVlanManagementid = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 3), Integer32().clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanManagementid.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanManagementid.setDescription('The management VLAN ID, which will allow to forward packets of that VLAN to CPU.')NEWLINEdot1qVlanAsyOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanAsyOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanAsyOnOff.setDescription('Enable/Disable IEEE 802.1Q Asymmetric VLAN')NEWLINEdot1qVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6), )NEWLINEif mibBuilder.loadTexts: dot1qVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanTable.setDescription('A table containing static configuration information for each VLAN configured into the device by (local or network) management. All entries are permanent and will be restored after the device is reset.')NEWLINEdot1qVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dot1qVlanName"))NEWLINEif mibBuilder.loadTexts: dot1qVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanEntry.setDescription('Information for a VLAN configured into the device by (local or network) management.')NEWLINEdot1qVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanName.setReference('IEEE 802.1Q/D11 Section 12.10.2.1')NEWLINEif mibBuilder.loadTexts: dot1qVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanName.setDescription('An administratively assigned string, which may be used to identify the VLAN.')NEWLINEdot1qVlanEgressPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 2), PortList()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanEgressPorts.setReference('IEEE 802.1Q/D11 Section 12.7.7.3, 11.2.3.2.3')NEWLINEif mibBuilder.loadTexts: dot1qVlanEgressPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanEgressPorts.setDescription('The set of ports which are permanently assigned to the egress list for this VLAN by management. Changes to a bit in this object affect the per-port per-VLAN Registrar control for Registration Fixed for the relevant GVRP state machine on each port. A port may not be added in this set if it is already a member of the set of ports in dot1qVlanForbiddenEgressPorts. The default value of this object is a string of zeros of appropriate length, indicating not fixed.')NEWLINEdot1qVlanForbiddenPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanForbiddenPorts.setReference('IEEE 802.1Q/D11 Section 12.7.7.3, 11.2.3.2.3')NEWLINEif mibBuilder.loadTexts: dot1qVlanForbiddenPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanForbiddenPorts.setDescription('The set of ports which are prohibited by management from being included in the egress list for this VLAN. Changes to this object that cause a port to be included or excluded affect the per-port per-VLAN Registrar control for Registration Forbidden for the relevant GVRP state machine on each port. A port may not be added in this set if it is already a member of the set of ports in dot1qVlanEgressPorts. The default value of this object is a string of zeros of appropriate length, excluding all ports from the forbidden set.')NEWLINEdot1qVlanUntaggedPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 4), PortList()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanUntaggedPorts.setReference('IEEE 802.1Q/D11 Section 12.10.2.1')NEWLINEif mibBuilder.loadTexts: dot1qVlanUntaggedPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanUntaggedPorts.setDescription('The set of ports which should transmit egress packets for this VLAN as untagged. The default value of this object for the default VLAN (dot1qVlanIndex = 1) is a string of appropriate length including all ports. There is no specified default for other VLANs. If a device agent cannot support the set of ports being set then it will reject the set operation with an error. An example might be if a manager attempts to set more than one VLAN to be untagged on egress where the device does not support this IEEE 802.1Q option.')NEWLINEdot1qVlanAdvertisementStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanAdvertisementStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanAdvertisementStatus.setDescription('Enable/Disable Advertisement Status of the IEEE 802.1Q VLAN.')NEWLINEdot1qVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 6), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanRowStatus.setDescription('The status of a row in dot1qVlanTable. By setting this object, new entries can be created in dot1qVlanTable and existing entries can be removed from dot1qVlanTable. It can be used as specified in the SNMP v2 standard.')NEWLINEdot1qVlanPVIDAutoAssignOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanPVIDAutoAssignOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanPVIDAutoAssignOnOff.setDescription('Enable/Disable VLAN PVID auto assignment')NEWLINEgvrpGVRPGlobalSettingsOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpGVRPGlobalSettingsOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpGVRPGlobalSettingsOnOff.setDescription('Enable/Disable GVRP mechanism.')NEWLINEgvrpSettingsJoinTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100, 100000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsJoinTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsJoinTime.setDescription('The Join Time value assigned to this Join Time field. This 16-bit value is read-write.')NEWLINEgvrpSettingsLeaveTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100, 100000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsLeaveTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsLeaveTime.setDescription('The Leave Time value assigned to this Leave Time field. This 16-bit value is read-write.')NEWLINEgvrpSettingsLeaveAllTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100, 100000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsLeaveAllTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsLeaveAllTime.setDescription('The Leave_All Time value assigned to this Leave_All Time field. This 16-bit value is read-write.')NEWLINEgvrpSettingsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5), )NEWLINEif mibBuilder.loadTexts: gvrpSettingsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsTable.setDescription('A table containing static configuration information for each GVRP configured into the device by (local or network) management. All entries are permanent and will be restored after the device is reset.')NEWLINEgvrpSettingsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "gvrpSettingsPortControlIndex"))NEWLINEif mibBuilder.loadTexts: gvrpSettingsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsEntry.setDescription('Information for a GVRP configured into the device by (local or network) management.')NEWLINEgvrpSettingsPortControlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: gvrpSettingsPortControlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsPortControlIndex.setDescription('The index of the port.')NEWLINEgvrpSettingsPVID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsPVID.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsPVID.setDescription('The PVID value assigned to this Aggregation Port. This 16-bit value is read-write.')NEWLINEgvrpSettingsGVRPState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsGVRPState.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsGVRPState.setDescription('Enable/Disable GVRP State to this Aggregation Port.')NEWLINEgvrpSettingsIngressChecking = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsIngressChecking.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsIngressChecking.setDescription('Enable/Disable Ingress Checking mechanism of GVRP to this Aggregation Port.')NEWLINEgvrpSettingsAcceptableFrameType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allFrames", 1), ("taggedOnly", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsAcceptableFrameType.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsAcceptableFrameType.setDescription('Chose types All Frames/Tagged to this Aggregation Port.')NEWLINEdhcpBOOTPRelayControl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1))NEWLINEdhcpBOOTPRelayManagement = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2))NEWLINEdhcpBOOTPRelayManagementOption82 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2))NEWLINEdhcpBOOTPRelayState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayState.setDescription('This object indicates DHCP relay function is enabled or disabled.')NEWLINEdhcpBOOTPRelayHopCount = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayHopCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayHopCount.setDescription('This object indicates the maximum number of router hops that the BOOTP packets can cross.')NEWLINEdhcpBOOTPRelayTimeThreshold = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayTimeThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayTimeThreshold.setDescription('This object indicates the minimum time in seconds within which the switch must relay the DHCP request. If this time is exceeded, the switch will drop the DHCP packet.')NEWLINEdhcpBOOTPRelayEnablePortlist = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayEnablePortlist.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayEnablePortlist.setDescription('This object indicates DHCP relay function is enabled or disabled by portlist.')NEWLINEdhcpRelayVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 5), )NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanTable.setDescription('This table indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpRelayVlanTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpRelayVlanSettingsVLANID"))NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanTableEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanTableEntry.setDescription('A list of information indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpRelayVlanSettingsVLANID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanSettingsVLANID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanSettingsVLANID.setDescription('This object displays the current VLAN ID of the device.')NEWLINEdhcpRelayVlanSettingsState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanSettingsState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanSettingsState.setDescription('This object indicates DHCP relay function of VLAN is enabled or disabled.')NEWLINEdhcpBOOTPRelayInterfaceSettingsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1), )NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsTable.setDescription('This table indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpBOOTPRelayInterfaceSettingsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpBOOTPRelayInterface"), (0, "DES-1210-28MEbx", "dhcpBOOTPRelayServerIP"))NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsEntry.setDescription('A list of information indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpBOOTPRelayInterface = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 12))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterface.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterface.setDescription('This object indicates the name of the IP interface.')NEWLINEdhcpBOOTPRelayServerIP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1, 1, 2), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayServerIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayServerIP.setDescription('This object indicates the DHCP server IP address.')NEWLINEdhcpBOOTPRelayInterfaceSettingsRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1, 1, 3), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEdhcpBOOTPRelayOption82State = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82State.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82State.setDescription('This object indicates DHCP relay option 82 function is enabled or disabled.')NEWLINEdhcpBOOTPRelayOption82CheckState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CheckState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CheckState.setDescription('This object indicates DHCP relay option 82 Check function is enabled or disabled.')NEWLINEdhcpBOOTPRelayOption82Policy = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("replace", 1), ("drop", 2), ("keep", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82Policy.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82Policy.setDescription('This object indicates DHCP relay option 82 policy.')NEWLINEdhcpBOOTPRelayOption82RemoteIDType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("default", 1), ("userdefined", 2), ("userdefinedhex", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82RemoteIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82RemoteIDType.setDescription('This object indicates the type of remote ID. If the type is default, the remote ID will be the MAC address of the device, otherwise, the remote ID can be defined by writing to the swDHCPRelayOption82RemoteID object.')NEWLINEdhcpBOOTPRelayOption82RemoteID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 5), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82RemoteID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82RemoteID.setDescription('This object displays the current remote ID of the device. If swDHCPRelayOption82RemoteIDType is set to default, the value will be the MAC address of the device, and this object cannot be modified. If swDHCPRelayOption82RemoteIDType is set to user-defined or user-defined-hex, a new value can be written to this object.')NEWLINEdhcpBOOTPRelayOption82CircuitIDType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("default", 1), ("userdefined", 2), ("userdefinedhex", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CircuitIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CircuitIDType.setDescription('This object indicates the type of remote ID. If the type is default, the circuit ID will be blank, otherwise, the circuit ID can be defined by writing to the dhcpBOOTPRelayOption82CircuitID object.')NEWLINEdhcpBOOTPRelayOption82CircuitID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 8), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CircuitID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CircuitID.setDescription('This object displays the current remote ID of the device. If dhcpBOOTPRelayOption82CircuitIDType is set to default, the value will be the MAC address of the device, and this object cannot be modified. If dhcpBOOTPRelayOption82CircuitIDType is set to user-defined or user-defined-hex, a new value can be written to this object.')NEWLINEdhcpLocalRelayGlobalState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayGlobalState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayGlobalState.setDescription('This object indicates DHCP local relay function of VLAN is enabled or disabled.')NEWLINEdhcpLocalRelayTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 2), )NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayTable.setDescription('This table indicates the IP address as a destination to forward (local relay) DHCP packets to.')NEWLINEdhcpLocalRelayTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpLocalRelaySettingsVLANID"))NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayTableEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayTableEntry.setDescription('A list of information indicates the IP address as a destination to forward (local relay) DHCP packets to.')NEWLINEdhcpLocalRelaySettingsVLANID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpLocalRelaySettingsVLANID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelaySettingsVLANID.setDescription('This object displays the current VLAN ID of the device.')NEWLINEdhcpLocalRelaySettingsState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpLocalRelaySettingsState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelaySettingsState.setDescription('This object indicates DHCP local relay function of VLAN is enabled or disabled.')NEWLINEdhcpLocalRelayEnablePortlist = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayEnablePortlist.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayEnablePortlist.setDescription('This object indicates DHCP local relay function is enabled or disabled by portlist.')NEWLINElaSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1))NEWLINElaPortControl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2))NEWLINEclass PortLaMode(TextualConvention, Integer32):NEWLINE description = 'Defines how a Port Channel does channeling. lacp(1) - place the port into passive negotiation state, in which the port waits for its peer to initiate negotiation. static(2) - force the port to enable channeling. disable(3) - channeling is disabled.'NEWLINE status = 'current'NEWLINE subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))NEWLINE namedValues = NamedValues(("lacp", 1), ("static", 2), ("disable", 3))NEWLINENEWLINEclass LacpKey(TextualConvention, Integer32):NEWLINE description = 'The Actor or Partner Key value (0..65535).'NEWLINE status = 'current'NEWLINE subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 65535)NEWLINENEWLINElaStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: laStatus.setDescription('Sets the Link Aggregation Module administrative status as enabled or disabled.')NEWLINElaPortChannelTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3), )NEWLINEif mibBuilder.loadTexts: laPortChannelTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelTable.setDescription('A Port-channel is created through ifMain table. After the creation of the port-channel, corresponding logical interface will be created in the ifMain table. This Port-channel table is indexed through Key values and allows to configure link selection policy and the Mac address for the port-channel. All other objects in this table displays the details of the port-channel.')NEWLINElaPortChannelEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "laPortChannelIfIndex"))NEWLINEif mibBuilder.loadTexts: laPortChannelEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelEntry.setDescription('There is one entry in this table for each created port-channel port.')NEWLINElaPortChannelIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: laPortChannelIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelIfIndex.setDescription("The index of the port-channel(Aggregator's interface index). ")NEWLINElaPortChannelMemberList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1, 2), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortChannelMemberList.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelMemberList.setDescription('Member Port list of the port channel. Add the ports as a aggregation member associated of a port-channel.')NEWLINElaPortChannelMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1, 3), PortLaMode()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortChannelMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelMode.setDescription('Current Operating Channel Mode of the port channel Lacp(1) - forcing the port to negotiate with the partner. manual(2) - force the port to enable channeling (Manual). disable(3) - channeling is disabled.')NEWLINElaPortChannelMasterPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1, 4), InterfaceIndex()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortChannelMasterPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelMasterPort.setDescription('The master port of the port-channel. ')NEWLINElaAlgorithm = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("sourceMAC", 1), ("destMAC", 2), ("sourceAndDestMAC", 3), ("sourceIP", 4), ("destIP", 5), ("sourceAndDestIP", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laAlgorithm.setStatus('current')NEWLINEif mibBuilder.loadTexts: laAlgorithm.setDescription('Sets the Link Aggregation load balance algorithm.')NEWLINElaPortControlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1), )NEWLINEif mibBuilder.loadTexts: laPortControlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortControlTable.setDescription('A table that contains Link Aggregation Control configuration information about every Aggregation Port associated with this device. A row appears in this table for each physical port.')NEWLINElaPortControlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "laPortControlIndex"))NEWLINEif mibBuilder.loadTexts: laPortControlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortControlEntry.setDescription('A list of Link Aggregation Control configuration parameters for each Aggregation Port on this device.')NEWLINElaPortControlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: laPortControlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortControlIndex.setDescription('The index of the port.')NEWLINElaPortActorPortPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortActorPortPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortActorPortPriority.setDescription('The priority value assigned to this Aggregation Port. This 16-bit value is read-write.')NEWLINElaPortActorActivity = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("active", 1), ("passive", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortActorActivity.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortActorActivity.setDescription('This object indicates LACP_Activity to this Aggregation Port. LACP can be configured in one of two modes: active or passive. In active mode it will always send frames along the configured links. If the actor and partner are both in passive mode, they do not exchange LACP packets.')NEWLINElaPortActorTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("short", 1), ("long", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortActorTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortActorTimeout.setDescription('This object indicates LACP_Timeout to this Aggregation Port. short(1) - LACP Timeout 3 seconds. long (2) - LACP Timeout 90 seconds.')NEWLINEstaticVlanBaseTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5))NEWLINEstaticDisableAutoLearn = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("on", 1), ("off", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticDisableAutoLearn.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticDisableAutoLearn.setDescription('Set on to disable Auto Learning Excluding Uplink Port and set off to enable Auto Learning.')NEWLINEstaticAutoLearningList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 2), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticAutoLearningList.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticAutoLearningList.setDescription("The set of the device's member ports that belong to the Static MAC auto learning enable/disable. For example, when Disable Auto Learning is enable, the octet value set up as '# 0x0F 0xFF 0xFF 0xFF' means from port 1 to port 4 are not in auto learning state, the other ports are in auto learning state. It can be set up when Disable Auto Learning is enable.")NEWLINEstaticTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3), )NEWLINEif mibBuilder.loadTexts: staticTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticTable.setDescription('A list of the Static MACs')NEWLINEstaticEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "staticVlanID"), (0, "DES-1210-28MEbx", "staticMac"), (0, "DES-1210-28MEbx", "staticPort"))NEWLINEif mibBuilder.loadTexts: staticEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticEntry.setDescription('A Static MAC entry containing the mac and forwarding port.')NEWLINEstaticVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanID.setDescription('The VLAN ID of the static MAC entry.')NEWLINEstaticMac = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1, 2), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMac.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMac.setDescription('The MAC address associated of the static MAC entry.')NEWLINEstaticPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticPort.setDescription('The forwarding port of the static MAC entry. For all machines give maximum port number.')NEWLINEstaticStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1, 4), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticStatus.setDescription('The status of an entry in the Static MAC Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available. The trunk member port can not set up static MAC.')NEWLINEautoFdbTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4), )NEWLINEif mibBuilder.loadTexts: autoFdbTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbTable.setDescription('A list of the Auto Fdb')NEWLINEautoFdbEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "autoFdbIPAddress"))NEWLINEif mibBuilder.loadTexts: autoFdbEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbEntry.setDescription('A auto fdb entry containing the ipaddress')NEWLINEautoFdbIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 1), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbIPAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbIPAddress.setDescription('The IpAddress of the autoFdbEntry.')NEWLINEautoFdbVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbVlanID.setDescription('The VlanID of the autoFdbEntry.')NEWLINEautoFdbMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbMacAddress.setDescription('The Mac Address of the autoFdbEntry.')NEWLINEautoFdbPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbPort.setDescription('The Port of the autoFdbEntry.')NEWLINEautoFdbTimeStamp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 5), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbTimeStamp.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbTimeStamp.setDescription('The Time Stamp of the autoFdbEntry.')NEWLINEautoFdbStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 6), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: autoFdbStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbStatus.setDescription('The status of an entry in the Auto Fdb Table. Only a subset of the rowstatus variables (createAndGo, createAndWait,destroy) are available.')NEWLINEstaticVlanBaseAutoLearnList1k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList1k.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList1k.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this Auto Learn, the bit corresponding to that VLAN is set to '1'. Write AutoLearnList1k use 256 character, and conform to the foregoing rules.")NEWLINEstaticVlanBaseAutoLearnList2k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList2k.setDescription('A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1025 through 2048. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this Auto Learn. Write AutoLearnList2k use 256 character, and conform to the foregoing rules.')NEWLINEstaticVlanBaseAutoLearnList3k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2049 through 3072. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this Auto Learn the bit corresponding to that VLAN is set to '1'. Write AutoLearnList3k use 256 character, and conform to the foregoing rules.")NEWLINEstaticVlanBaseAutoLearnList4k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3073 through 4094. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this Auto Learn the bit corresponding to that VLAN is set to '1'. Write AutoLearnList4k use 256 character, and conform to the foregoing rules.")NEWLINEstaticVlanBaseEnableAutoLearn = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseEnableAutoLearn.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseEnableAutoLearn.setDescription('Set enable vlan list to auto learn, and range 1-4094.')NEWLINEstaticVlanBaseDisableAutoLearn = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseDisableAutoLearn.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseDisableAutoLearn.setDescription('Set disable vlan list to auto learn, and range 1-4094.')NEWLINEigsSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1))NEWLINEigsVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3))NEWLINEigsHost = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6))NEWLINEigsStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsStatus.setDescription("Enables or disables IGMP snooping in the system. When set to 'enabled', the IGS module starts protocol operations. When set to 'disabled', the IGS module stops performing protocol operations.")NEWLINEigsRouterPortPurgeInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60, 600)).clone(260)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsRouterPortPurgeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsRouterPortPurgeInterval.setDescription("This is the interval (in seconds) after which a learnt router port entry will be purged. For each router port learnt, this timer runs for 'RouterPortPurgeInterval' seconds.When the timer expires, the learnt router port entry is purged. However if control messages are received from the router before the timer expiry, then the timer is restarted.")NEWLINEigsHostPortPurgeInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(130, 153025)).clone(260)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsHostPortPurgeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostPortPurgeInterval.setDescription("This is the interval (in seconds) after which a learnt port entry will be purged. For each port on which report has been received this timer runs for 'PortPurgeInterval' seconds. This timer will be restarted whenever a report message is received from a host on the specific port. If the timer expires, then , the learnt port entry will be purged from the multicast group.")NEWLINEigsDataDrivenLearningMaxLearnedEntryVlaue = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024)).clone(64)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsDataDrivenLearningMaxLearnedEntryVlaue.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsDataDrivenLearningMaxLearnedEntryVlaue.setDescription('The maximum data driven learning entry value.')NEWLINEigsReportToAllPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsReportToAllPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsReportToAllPort.setDescription("Enables or disables IGMP snooping in the system. When set to 'enabled', the IGS module forwards packets to report to all port. When set to 'disabled', the IGS module forwards packets to router port only.")NEWLINEigsVlanRouterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 3), )NEWLINEif mibBuilder.loadTexts: igsVlanRouterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRouterTable.setDescription('This table contains the list of ports through which a router, in a particular VLAN is reachable.')NEWLINEigsVlanRouterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igsVlanRouterVlanId"))NEWLINEif mibBuilder.loadTexts: igsVlanRouterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRouterEntry.setDescription('Contains the VLAN ID and list of ports on which routers are present in the VLAN.')NEWLINEigsVlanRouterVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanRouterVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRouterVlanId.setDescription('VLAN ID of the ports through which router is reachable.')NEWLINEigsVlanRouterPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 3, 1, 2), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanRouterPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRouterPortList.setDescription('List of ports on which routers are present. These router ports are learnt through control messages received from routers, and can also be configured statically.')NEWLINEigsVlanFilterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4), )NEWLINEif mibBuilder.loadTexts: igsVlanFilterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFilterTable.setDescription('This table contains configuration of snooping on specific Vlans. This Table is valid only when VLAN is enabled in the system.')NEWLINEigsVlanFilterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igsVlanFilterVlanId"))NEWLINEif mibBuilder.loadTexts: igsVlanFilterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFilterEntry.setDescription('Contains snooping status , version and fast leave configuration for a specific VLAN.')NEWLINEigsVlanFilterVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanFilterVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFilterVlanId.setDescription('Index of IgsVlanFilterEntry. This object indicates the VLAN ID for which the snooping configurations in IgsVlanFilterEntry is to be done.')NEWLINEigsVlanSnoopStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanSnoopStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanSnoopStatus.setDescription('This object allows you to enable/disable IGS function on a specific VLAN.')NEWLINEigsVlanQuerier = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanQuerier.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanQuerier.setDescription('Indicates whether the switch is configured as a querier in the VLAN')NEWLINEigsVlanCfgQuerier = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanCfgQuerier.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanCfgQuerier.setDescription("The snooping switch can be configured as a querier via this object to send out IGMP general queries when IGMP routers are not present in the VLAN. When set to 'enabled', the switch will generate general queries.")NEWLINEigsVlanQueryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60, 600)).clone(125)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanQueryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanQueryInterval.setDescription('This is the interval (in seconds) for which the switch sends general queries when it is configured as a querier for the VLAN. A switch should be configured as a querier for a VLAN only when there is no queriers in the network.')NEWLINEigsVlanRtrPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanRtrPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRtrPortList.setDescription('List of ports which are configured statically as router ports')NEWLINEigsVlanFbdRtrPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 7), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanFbdRtrPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFbdRtrPortList.setDescription('List of ports which can be configured statically as forbidden router ports.')NEWLINEigsVlanFastLeave = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanFastLeave.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFastLeave.setDescription("Enables or disables fast leave for the VLAN. When it is 'disabled',on reception of a leave message, the switch checks if they are any interested receivers for the group by sending a group specific query before removing the port from the forwarding table. If set to 'enabled', the switch does not send a group specific query and immediately removes the port from the forwarding table.")NEWLINEigsVlanDataDrivenLearningStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanDataDrivenLearningStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanDataDrivenLearningStatus.setDescription('This object allows you to enable/disable Data Driven Learning function on a specific VLAN.')NEWLINEigsVlanQuerierVersionStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(3, 2))).clone(namedValues=NamedValues(("igmp-v3", 3), ("igmp-v2", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanQuerierVersionStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanQuerierVersionStatus.setDescription('This object allows you to enable/disable Querier Version function on a specific VLAN.')NEWLINEigsVlanDataDrivenLearningAgeOutStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanDataDrivenLearningAgeOutStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanDataDrivenLearningAgeOutStatus.setDescription('This object allows you to enable/disable Data Driven Learning Age Out State on a specific VLAN.')NEWLINEigsVlanReportSuppression = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanReportSuppression.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanReportSuppression.setDescription('Enables or disables Report suppression in the system.')NEWLINEigsVlanRobustnessValue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 255)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanRobustnessValue.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRobustnessValue.setDescription("When the switch receives leave message on a port, it sends group specific query to check if there are any other interested receivers for the group. This attribute defines the maximum number of queries sent by the switch before deleting the port from the group membership information in the forwarding database. If the maximum retry count exceeds 'igsRobustnessValue', then the port will be deleted from the multicast group membership information in the forwarding database and received leave message will be forwarded onto the router ports if there are no interested receivers for the group.")NEWLINEigsVlanGrpQueryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 14), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 25)).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanGrpQueryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanGrpQueryInterval.setDescription("The value of this attribute defines the time period with which the switch will send group specific queries on a port to check if there is any intersted receivers. The switch will send 'igsRobustnessValue' queries before removing the port from the group membership information in the forwarding database.")NEWLINEigsVlanQueryMaxResponseTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 15), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 25)).clone(10)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanQueryMaxResponseTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanQueryMaxResponseTime.setDescription('The maximum query response time advertised in IGMPv2 general queries on this interface.')NEWLINEigsVlanMulticastGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5), )NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupTable.setDescription('This table contains MAC based multicast forwarding information.')NEWLINEigsVlanMulticastGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igsVlanMulticastGroupVlanId"), (0, "DES-1210-28MEbx", "igsVlanMulticastGroupIpAddress"))NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupEntry.setDescription('This table contains VLAN ID, multicast group MAC address and the list of ports onto which the multicast data packets for group should be forwarded.')NEWLINEigsVlanMulticastGroupVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupVlanId.setDescription('VLAN ID pertaining to the Multicast forwarding entry')NEWLINEigsVlanMulticastGroupIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1, 2), InetAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupIpAddress.setDescription('Multicast group IP address. This object indicates that a multicast group address was learned in the switch and be represented as IP address format.')NEWLINEigsVlanMulticastGroupMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupMacAddress.setDescription('Multicast group MAC address. This object indicates that a multicast group address was learned in the switch and be represented as MAC address format.')NEWLINEigsVlanMulticastGroupPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1, 4), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupPortList.setDescription('List of ports onto which the multicast data packets destined for this group will be forwarded.')NEWLINEigsHostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1), )NEWLINEif mibBuilder.loadTexts: igsHostTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTable.setDescription('This table is used to manage the IGMP Host based Fast Leave function of the switch.')NEWLINEigsHostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igsHostTableVLANID"), (0, "DES-1210-28MEbx", "igsHostTableGroupAddress"), (0, "DES-1210-28MEbx", "igsHostTablePort"), (0, "DES-1210-28MEbx", "igsHostTableHostIPAddress"))NEWLINEif mibBuilder.loadTexts: igsHostEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostEntry.setDescription('Contains management entities for IGMP Host based fast leave function.')NEWLINEigsHostTableVLANID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsHostTableVLANID.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTableVLANID.setDescription('VLAN ID of Host table entry.')NEWLINEigsHostTableGroupAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1, 2), InetAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsHostTableGroupAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTableGroupAddress.setDescription('Group address of Host table entry.')NEWLINEigsHostTablePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsHostTablePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTablePort.setDescription('Port number of Host table entry. For all machines give maximum port number.')NEWLINEigsHostTableHostIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1, 4), InetAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsHostTableHostIPAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTableHostIPAddress.setDescription('Host IP address of Group in Host table entry.')NEWLINEmldsSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1))NEWLINEmldsVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3))NEWLINEmldsHost = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4))NEWLINEmldsStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsStatus.setDescription("Enables or disables MLD snooping in the system. When set to 'enabled', the MLDS module starts protocol operations. When set to 'disabled', the MLDS module stops performing protocol operations.")NEWLINEmldsRouterPortPurgeInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60, 600)).clone(260)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsRouterPortPurgeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsRouterPortPurgeInterval.setDescription("This is the interval (in seconds) after which a learnt router port entry will be purged. For each router port learnt, this timer runs for 'RouterPortPurgeInterval' seconds.When the timer expires, the learnt router port entry is purged. However if control messages are received from the router before the timer expiry, then the timer is restarted.")NEWLINEmldsHostPortPurgeInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(130, 153025)).clone(260)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsHostPortPurgeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostPortPurgeInterval.setDescription("This is the interval (in seconds) after which a learnt port entry will be purged. For each port on which report has been received this timer runs for 'PortPurgeInterval' seconds. This timer will be restarted whenever a report message is received from a host on the specific port. If the timer expires, then , the learnt port entry will be purged from the multicast group.")NEWLINEmldsDataDrivenLearningMaxLearnedEntryVlaue = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024)).clone(64)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsDataDrivenLearningMaxLearnedEntryVlaue.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsDataDrivenLearningMaxLearnedEntryVlaue.setDescription('The maximum data driven learning entry value.')NEWLINEmldsVlanRouterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 3), )NEWLINEif mibBuilder.loadTexts: mldsVlanRouterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRouterTable.setDescription('This table contains the list of ports through which a router, in a particular VLAN is reachable.')NEWLINEmldsVlanRouterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mldsVlanRouterVlanId"))NEWLINEif mibBuilder.loadTexts: mldsVlanRouterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRouterEntry.setDescription('Contains the VLAN ID and list of ports on which routers are present in the VLAN.')NEWLINEmldsVlanRouterVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanRouterVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRouterVlanId.setDescription('VLAN ID of the ports through which router is reachable.')NEWLINEmldsVlanRouterPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 3, 1, 2), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanRouterPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRouterPortList.setDescription('List of ports on which routers are present. These router ports are learnt through control messages received from routers, and can also be configured statically.')NEWLINEmldsVlanFilterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4), )NEWLINEif mibBuilder.loadTexts: mldsVlanFilterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFilterTable.setDescription('This table contains configuration of snooping on specific Vlans. This Table is valid only when VLAN is enabled in the system.')NEWLINEmldsVlanFilterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mldsVlanFilterVlanId"))NEWLINEif mibBuilder.loadTexts: mldsVlanFilterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFilterEntry.setDescription('Contains snooping status , version and fast leave configuration for a specific VLAN.')NEWLINEmldsVlanFilterVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanFilterVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFilterVlanId.setDescription('Index of MldsVlanFilterEntry. This object indicates the VLAN ID for which the snooping configurations in MldsVlanFilterEntry is to be done.')NEWLINEmldsVlanSnoopStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanSnoopStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanSnoopStatus.setDescription('This object allows you to enable/disable MLDS function on a specific VLAN.')NEWLINEmldsVlanQuerier = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanQuerier.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanQuerier.setDescription('Indicates whether the switch is configured as a querier in the VLAN')NEWLINEmldsVlanCfgQuerier = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanCfgQuerier.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanCfgQuerier.setDescription("The snooping switch can be configured as a querier via this object to send out MLD general queries when IGMP routers are not present in the VLAN. When set to 'enabled', the switch will generate general queries.")NEWLINEmldsVlanQueryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60, 600)).clone(125)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanQueryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanQueryInterval.setDescription('This is the interval (in seconds) for which the switch sends general queries when it is configured as a querier for the VLAN. A switch should be configured as a querier for a VLAN only when there is no queriers in the network.')NEWLINEmldsVlanRtrPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanRtrPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRtrPortList.setDescription('List of ports which are configured statically as router ports')NEWLINEmldsVlanFbdRtrPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 7), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanFbdRtrPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFbdRtrPortList.setDescription('List of ports which can be configured statically as forbidden router ports.')NEWLINEmldsVlanFastLeave = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanFastLeave.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFastLeave.setDescription("Enables or disables fast leave for the VLAN. When it is 'disabled',on reception of a leave message, the switch checks if they are any interested receivers for the group by sending a group specific query before removing the port from the forwarding table. If set to 'enabled', the switch does not send a group specific query and immediately removes the port from the forwarding table.")NEWLINEmldsVlanDataDrivenLearningStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanDataDrivenLearningStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanDataDrivenLearningStatus.setDescription('This object allows you to enable/disable Data Driven Learning function on a specific VLAN.')NEWLINEmldsVlanReportSuppression = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanReportSuppression.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanReportSuppression.setDescription('Enables or disables Report suppression in the system.')NEWLINEmldsVlanRobustnessValue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 255)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanRobustnessValue.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRobustnessValue.setDescription("When the switch receives leave message on a port, it sends group specific query to check if there are any other interested receivers for the group. This attribute defines the maximum number of queries sent by the switch before deleting the port from the group membership information in the forwarding database. If the maximum retry count exceeds 'mldsRobustnessValue', then the port will be deleted from the multicast group membership information in the forwarding database and received leave message will be forwarded onto the router ports if there are no interested receivers for the group.")NEWLINEmldsVlanGrpQueryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 25)).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanGrpQueryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanGrpQueryInterval.setDescription("The value of this attribute defines the time period with which the switch will send group specific queries on a port to check if there is any intersted receivers. The switch will send 'mldsRobustnessValue' queries before removing the port from the group membership information in the forwarding database.")NEWLINEmldsVlanQueryMaxResponseTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 25)).clone(10)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanQueryMaxResponseTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanQueryMaxResponseTime.setDescription('The maximum query response time advertised in MLDv1 general queries on this interface.')NEWLINEmldsVlanMulticastGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5), )NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupTable.setDescription('This table contains MAC based multicast forwarding information.')NEWLINEmldsVlanMulticastGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mldsVlanMulticastGroupVlanId"), (0, "DES-1210-28MEbx", "mldsVlanMulticastGroupIpAddress"))NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupEntry.setDescription('This table contains VLAN ID, multicast group MAC address and the list of ports onto which the multicast data packets for group should be forwarded.')NEWLINEmldsVlanMulticastGroupVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupVlanId.setDescription('VLAN ID pertaining to the Multicast forwarding entry')NEWLINEmldsVlanMulticastGroupIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1, 2), InetAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupIpAddress.setDescription('Multicast group IP address. This object indicates that a multicast group address was learned in the switch and be represented as IP address format.')NEWLINEmldsVlanMulticastGroupMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupMacAddress.setDescription('Multicast group MAC address. This object indicates that a multicast group address was learned in the switch and be represented as MAC address format.')NEWLINEmldsVlanMulticastGroupPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1, 4), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupPortList.setDescription('List of ports onto which the multicast data packets destined for this group will be forwarded.')NEWLINEmldsHostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1), )NEWLINEif mibBuilder.loadTexts: mldsHostTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTable.setDescription('This table is used to manage the IGMP Host based Fast Leave function of the switch.')NEWLINEmldsHostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mldsHostTableVLANID"), (0, "DES-1210-28MEbx", "mldsHostTableGroupAddress"), (0, "DES-1210-28MEbx", "mldsHostTablePort"), (0, "DES-1210-28MEbx", "mldsHostTableHostIPAddress"))NEWLINEif mibBuilder.loadTexts: mldsHostEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostEntry.setDescription('Contains management entities for IGMP Host based fast leave function.')NEWLINEmldsHostTableVLANID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsHostTableVLANID.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTableVLANID.setDescription('VLAN ID of IPv6 Host table entry.')NEWLINEmldsHostTableGroupAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1, 2), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsHostTableGroupAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTableGroupAddress.setDescription('Group address of IPv6 Host table entry.')NEWLINEmldsHostTablePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsHostTablePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTablePort.setDescription('Port number of IPv6 Host table entry. For all machines give maximum port number.')NEWLINEmldsHostTableHostIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1, 4), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsHostTableHostIPAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTableHostIPAddress.setDescription('Host IP address of Group in IPv6 Host table entry.')NEWLINEswAuthenCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1))NEWLINEswAuthStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthStatus.setDescription('Enable/Disable Static 802.1x.')NEWLINEswAuthMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("portBase", 1), ("macBase", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthMode.setDescription('This object indicates the authentication mode of the device.')NEWLINEauthProtocol = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("authProtocolRadiusEap", 1), ("authProtocolLocal", 2))).clone('authProtocolRadiusEap')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: authProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: authProtocol.setDescription('The authentication method used to authenticate users.')NEWLINEswAuthCtrlPktFwdMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("authForwardEap", 1), ("authDropEap", 2))).clone('authForwardEap')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthCtrlPktFwdMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthCtrlPktFwdMode.setDescription('When 802.1x disable, this item can decided eap packet be forward or drop.')NEWLINEswAuthPortAccessCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2))NEWLINEswAuthPortAccessControlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1), )NEWLINEif mibBuilder.loadTexts: swAuthPortAccessControlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthPortAccessControlTable.setDescription('A table that contains the configuration objects for the Authenticator PAE associated with each port. An entry appears in this table for each port that may authenticate access to itself.')NEWLINEswAuthPortAccessControlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "swAuthAuthConfigPortNumber"))NEWLINEif mibBuilder.loadTexts: swAuthPortAccessControlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthPortAccessControlEntry.setDescription('The configuration information for an Authenticator Port.')NEWLINEswAuthAuthConfigPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortNumber.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortNumber.setDescription('A unique value for each port that correlates to port index. Its value ranges between 1 and the value of port number. For all machines give maximum port number.')NEWLINEswAuthAuthQuietPeriod = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)).clone(60)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthQuietPeriod.setReference('9.4.1, quietPeriod.')NEWLINEif mibBuilder.loadTexts: swAuthAuthQuietPeriod.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthQuietPeriod.setDescription('The value, in seconds, of the quietPeriod constant currently in use by the Authenticator PAE state machine.')NEWLINEswAuthAuthSuppTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(12)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthSuppTimeout.setReference('9.4.1, suppTimeout.')NEWLINEif mibBuilder.loadTexts: swAuthAuthSuppTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthSuppTimeout.setDescription('The value, in seconds, of the suppTimeout constant currently in use by the Backend Authentication state machine.')NEWLINEswAuthAuthServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(16)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthServerTimeout.setReference('9.4.1, serverTimeout.')NEWLINEif mibBuilder.loadTexts: swAuthAuthServerTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthServerTimeout.setDescription('The value, in seconds, of the serverTimeout constant currently in use by the Backend Authentication state machine.')NEWLINEswAuthAuthMaxReq = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthMaxReq.setReference('9.4.1, maxReq.')NEWLINEif mibBuilder.loadTexts: swAuthAuthMaxReq.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthMaxReq.setDescription('The value of the maxReq constant currently in use by the Backend Authentication state machine.')NEWLINEswAuthAuthTxPeriod = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(24)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthTxPeriod.setReference('9.4.1, txPeriod.')NEWLINEif mibBuilder.loadTexts: swAuthAuthTxPeriod.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthTxPeriod.setDescription('The value, in seconds, of the txPeriod constant currently in use by the Authenticator PAE state machine.')NEWLINEswAuthAuthReAuthPeriod = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(3600)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthPeriod.setReference('9.4.1, reAuthPerio.')NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthPeriod.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthPeriod.setDescription('The value, in seconds, of the reAuthPeriod constant currently in use by the Reauthentication Timer state machine.')NEWLINEswAuthAuthReAuthentication = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthentication.setReference('9.4.1, reAuthEnable.')NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthentication.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthentication.setDescription('The enable/disable control used by the Reauthentication Timer state machine (8.5.5.1).')NEWLINEswAuthAuthConfigPortControl = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("forceUnauthorized", 1), ("auto", 2), ("forceAuthorized", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortControl.setReference('9.4.1, AuthControlledPortControl.')NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortControl.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortControl.setDescription('The current value of the controlled Port control parameter for the Port.')NEWLINEswAuthAuthCapability = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("authenticator", 1), ("none", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthCapability.setReference('AuthCapability.')NEWLINEif mibBuilder.loadTexts: swAuthAuthCapability.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthCapability.setDescription('The current value of the controlled Port control parameter for the Port.')NEWLINEswAuthAuthDirection = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("both", 0), ("in", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthDirection.setReference('AuthDirection.')NEWLINEif mibBuilder.loadTexts: swAuthAuthDirection.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthDirection.setDescription('The current value of the controlled Port control parameter for the Port.')NEWLINEswAuthUser = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3))NEWLINEswAuthUserTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1), )NEWLINEif mibBuilder.loadTexts: swAuthUserTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserTable.setDescription('A table that contains the configuration objects for the Authenticator PAE associated with each port. An entry appears in this table for each port that may authenticate access to itself.')NEWLINEswAuthUserEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "swAuthUserName"))NEWLINEif mibBuilder.loadTexts: swAuthUserEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserEntry.setDescription('The configuration information for an Authenticator Port.')NEWLINEswAuthUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: swAuthUserName.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserName.setDescription('The unique index value of a row in this table. This object is used to set 802.1X Local user name, The following characters are allowed to input: semicolon, question mark, space, and double quotation mark.')NEWLINEswAuthUserPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthUserPassword.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserPassword.setDescription('This object is used to set 802.1X Local user Password, The following characters are allowed to input: semicolon, question mark, space, and double quotation mark.')NEWLINEswAuthUserStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1, 1, 3), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: swAuthUserStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserStatus.setDescription('The status of this conceptual row in the swAuthUserTable. An entry in this table is not qualified for activation until instances of all corresponding columns have been initialized, either through default values, or through Set operations. The swAuthUserName objects must be explicitly set.')NEWLINEswAuthRadiusServer = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4))NEWLINEiPv4swAuthRadiusServerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1), )NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerTable.setDescription('A table that contains the configuration objects for the Authenticator PAE associated with each port. An entry appears in this table for each port that may authenticate access to itself.')NEWLINEiPv4swAuthRadiusServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "iPv4swAuthRadiusServerIndex"))NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerEntry.setDescription('The configuration information for an Authenticator Port.')NEWLINEiPv4swAuthRadiusServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerIndex.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerIndex.setDescription('A unique value for Authentication RADIUS Server index. Its value ranges between 1 and 3.')NEWLINEiPv4swAuthRadiusServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAddress.setDescription('The IP address of the RADIUS server referred to in this table entry.')NEWLINEiPv4swAuthRadiusServerAuthenticationPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1812)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAuthenticationPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAuthenticationPort.setDescription('The value is for setting UDP Port.')NEWLINEiPv4swAuthRadiusServerAccountingPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1813)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAccountingPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAccountingPort.setDescription('The value is for setting UDP Port.')NEWLINEiPv4swAuthRadiusServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)).clone(5)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerTimeout.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerTimeout.setDescription('The value is for setting UDP Port.')NEWLINEiPv4swAuthRadiusServerRetransmit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerRetransmit.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerRetransmit.setDescription('The value is for setting UDP Port.')NEWLINEiPv4swAuthRadiusServerKey = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerKey.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerKey.setDescription('This object is used to set 802.1X Radius Server Key, The following characters are allowed to input: semicolon, question mark, space, and double quotation mark.')NEWLINEiPv4swAuthRadiusServerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 8), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerStatus.setDescription('The status of this conceptual row in the swAuthRadiusServerTable. An entry in this table is not qualified for activation until instances of all corresponding columns have been initialized, either through default values, or through Set operations. The swAuthRadiusServerIndex objects must be explicitly set.')NEWLINEswAuthRadiusServerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2), )NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerTable.setDescription('A table that contains the configuration objects for the Authenticator PAE associated with each port. An entry appears in this table for each port that may authenticate access to itself.')NEWLINEswAuthRadiusServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "swAuthRadiusServerIndex"))NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerEntry.setDescription('The configuration information for an Authenticator Port.')NEWLINEswAuthRadiusServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerIndex.setDescription('A unique value for Authentication RADIUS Server index. Its value ranges between 1 and 3.')NEWLINEswAuthRadiusIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2)).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusIPType.setDescription('The IP address of the RADIUS server IP type referred to in this table entry.')NEWLINEswAuthRadiusServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 3), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAddress.setDescription('The IP address of the RADIUS server referred to in this table entry.')NEWLINEswAuthRadiusServerInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 4), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerInterfaceName.setDescription('Specifies the interface name when the swAuthRadiusServerAddress is linklocal address.')NEWLINEswAuthRadiusServerAuthenticationPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1812)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAuthenticationPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAuthenticationPort.setDescription('The value is for setting UDP Port.')NEWLINEswAuthRadiusServerAccountingPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1813)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAccountingPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAccountingPort.setDescription('The value is for setting UDP Port.')NEWLINEswAuthRadiusServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)).clone(5)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerTimeout.setDescription('The value is for setting UDP Port.')NEWLINEswAuthRadiusServerRetransmit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerRetransmit.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerRetransmit.setDescription('The value is for setting UDP Port.')NEWLINEswAuthRadiusServerKey = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerKey.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerKey.setDescription('This object is used to set 802.1X Radius Server Key, The following characters are allowed to input: semicolon, question mark, space, and double quotation mark.')NEWLINEswAuthRadiusServerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 10), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerStatus.setDescription('The status of this conceptual row in the swAuthRadiusServerTable. An entry in this table is not qualified for activation until instances of all corresponding columns have been initialized, either through default values, or through Set operations. The swAuthRadiusServerIndex objects must be explicitly set.')NEWLINEcosScheduleMechanism = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("strictPriority", 1), ("wrr", 2), ("strict3wrr", 3), ("strict2wrr", 4)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cosScheduleMechanism.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosScheduleMechanism.setDescription('Queuing mechanism. strictPriority(1) : Strict Priority wrr(2) : Weighted Round Robin Strict-priority scheduling is implemented with a special strict-priority scheduler node that is stacked directly above the port. Queues stacked on top of the strict-priority scheduler node always get bandwidth before other queues. Weighted round-robin scheduling is designed to better handle queues with different processing capacities. Each queue has a weight : Low is 1, Medium is 2, High is 4 and Highest is 8 for WS3 spec. Queues with higher weights get bandwidth before than other queues with less weights. ')NEWLINEcosOutputSchedule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2))NEWLINEcosClassTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2, 1), )NEWLINEif mibBuilder.loadTexts: cosClassTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosClassTable.setDescription('A list of cosOutputSchedule.')NEWLINEcosClassEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cosClassIndex"))NEWLINEif mibBuilder.loadTexts: cosClassEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosClassEntry.setDescription('A list of cosOutputClass Weight.')NEWLINEcosClassIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosClassIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosClassIndex.setDescription('A index of class 0 ~ 3.')NEWLINEcosWeight = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 55))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cosWeight.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosWeight.setDescription('cos weight ')NEWLINEcosBandwidthCtrlSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9))NEWLINEcosBandwidthCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1), )NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlTable.setDescription('A list of cosBandwidthCtrlEntry default priority Entries.')NEWLINEcosBandwidthCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cosBandwidthCtrlPortIndex"), (0, "DES-1210-28MEbx", "cosBandwidthCtrlClassIndex"))NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlEntry.setDescription('A list of cosBandwidthCtrlEntry default priority priorities.')NEWLINEcosBandwidthCtrlPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlPortIndex.setDescription('A port identifier that is in the range of 1 to ifNumber.')NEWLINEcosBandwidthCtrlClassIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlClassIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlClassIndex.setDescription('A BandwidthCtrlClassIndex identifier that is in the range of 1 to ifNumber.')NEWLINEcosBandwidthValue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 3), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cosBandwidthValue.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthValue.setDescription('The BandwidthValue return value.')NEWLINEcosBandwidthEffectiveRX = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosBandwidthEffectiveRX.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthEffectiveRX.setDescription('A speed rate of Effective RX.')NEWLINEcosBandwidthEffectiveTX = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 5), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosBandwidthEffectiveTX.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthEffectiveTX.setDescription('A speed value of Effective TX.')NEWLINEqosDefaultUserPri = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4))NEWLINEqosDefaultUserPriTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1), )NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriTable.setDescription('A list of 802.1p port default priority Entries.')NEWLINEqosDefaultUserPriEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qosDefaultUserPriPortIndex"))NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriEntry.setDescription('A list of 802.1p port default priority priorities.')NEWLINEqosDefaultUserPriPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriPortIndex.setDescription('A port identifier that is in the range of 1 to ifNumber.')NEWLINEqosDefaultPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("priority0", 0), ("priority1", 1), ("priority2", 2), ("priority3", 3), ("priority4", 4), ("priority5", 5), ("priority6", 6), ("priority7", 7)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDefaultPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDefaultPriority.setDescription("For ingress untagged packets, the per port 'Default Priority' setting will be applied to packets of each port to provide port-based traffic prioritization when 802.1p is enabled.")NEWLINEqosEffectiveDefaultPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("priority0", 0), ("priority1", 1), ("priority2", 2), ("priority3", 3), ("priority4", 4), ("priority5", 5), ("priority6", 6), ("priority7", 7)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qosEffectiveDefaultPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosEffectiveDefaultPriority.setDescription("For ingress untagged packets, the per port 'Effective Default Priority' setting will be applied to packets of each port to provide port-based traffic prioritization when 802.1p is enabled.")NEWLINEqosUserPriority = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5))NEWLINEqosUserPriorityTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5, 1), )NEWLINEif mibBuilder.loadTexts: qosUserPriorityTable.setReference('ISO/IEC 15802-3 Table 7-2')NEWLINEif mibBuilder.loadTexts: qosUserPriorityTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosUserPriorityTable.setDescription('A table mapping evaluated User Priority to Traffic Class, for forwarding by the bridge. Traffic class is a number in the range (0..3).')NEWLINEqosUserPriEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qosUserPriIndex"))NEWLINEif mibBuilder.loadTexts: qosUserPriEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosUserPriEntry.setDescription('User Priority to Traffic Class mapping.')NEWLINEqosUserPriIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qosUserPriIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosUserPriIndex.setDescription('For ingress tagged packets, D-Link Smart Switches will refer to these information and prioritize them with 4 different priority queues. If 802.1p is enabled.')NEWLINEqosUserPriClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosUserPriClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosUserPriClass.setDescription('The User Class the received frame is mapped to.')NEWLINEqosPriSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7))NEWLINEqosPriSettingsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7, 1), )NEWLINEif mibBuilder.loadTexts: qosPriSettingsTable.setReference('ISO/IEC 15802-3 Table 7-2')NEWLINEif mibBuilder.loadTexts: qosPriSettingsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosPriSettingsTable.setDescription('A list of port priority settings.')NEWLINEqosPriSettingsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qosPriSetPortIndex"))NEWLINEif mibBuilder.loadTexts: qosPriSettingsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosPriSettingsEntry.setDescription('A list of port priority settings Entries.')NEWLINEqosPriSetPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qosPriSetPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosPriSetPortIndex.setDescription('A port identifier that is in the range of 1 to ifNumber.')NEWLINEqosPriSetPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 4, 6))).clone(namedValues=NamedValues(("none", 0), ("ieee8021P", 2), ("dscp-tos", 4), ("ieee8021P-dscp-tos", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosPriSetPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosPriSetPortType.setDescription('The port priority setting type. (ex. none = 0, 802.1p = 2, DSCP = 4. If you want enable 802.1p & DSCP, the value is 2 + 4 = 6. ')NEWLINEqosDiffServTOS = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6))NEWLINEqosDSCPTOSMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("tos", 1), ("dscp", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDSCPTOSMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDSCPTOSMode.setDescription('Settings of Qos mode: DSCP QoS or TOS Qos. IEEE 802.1p : It specifies a priority(0~7) value to four queues in WS3 : Low(1,2), Medium(0,3), High(4,5) and Highest(6,7), inclusive that can be used by Quality of Service (QoS) disciplines to differentiate traffic. DSCP : Differentiated services enhancements to the Internet protocol are intended to enable scalable service discrimination in the Internet without the need for per-flow state and signaling at every hop. ')NEWLINEqosDiffServTypeGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2))NEWLINEqosDiffServType00 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType00.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType00.setDescription('DiffServ Type 0 : IP ToS value = 0')NEWLINEqosDiffServType01 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType01.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType01.setDescription('DiffServ Type 01 : IP ToS value = 4')NEWLINEqosDiffServType02 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType02.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType02.setDescription('DiffServ Type 02 : IP ToS value = 8')NEWLINEqosDiffServType03 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType03.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType03.setDescription('DiffServ Type 03 : IP ToS value = 12')NEWLINEqosDiffServType04 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType04.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType04.setDescription('DiffServ Type 04 : IP ToS value = 16')NEWLINEqosDiffServType05 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType05.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType05.setDescription('DiffServ Type 05 : IP ToS value = 20')NEWLINEqosDiffServType06 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType06.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType06.setDescription('DiffServ Type 06 : IP ToS value = 24')NEWLINEqosDiffServType07 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType07.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType07.setDescription('DiffServ Type 07 : IP ToS value = 28')NEWLINEqosDiffServType08 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType08.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType08.setDescription('DiffServ Type 08 : IP ToS value = 32')NEWLINEqosDiffServType09 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType09.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType09.setDescription('DiffServ Type 09 : IP ToS value = 36')NEWLINEqosDiffServType10 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType10.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType10.setDescription('DiffServ Type 10 : IP ToS value = 40')NEWLINEqosDiffServType11 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType11.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType11.setDescription('DiffServ Type 11 : IP ToS value = 44')NEWLINEqosDiffServType12 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType12.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType12.setDescription('DiffServ Type 12 : IP ToS value = 48')NEWLINEqosDiffServType13 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType13.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType13.setDescription('DiffServ Type 13 : IP ToS value = 52')NEWLINEqosDiffServType14 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType14.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType14.setDescription('DiffServ Type 14 : IP ToS value = 56')NEWLINEqosDiffServType15 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType15.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType15.setDescription('DiffServ Type 15 : IP ToS value = 60')NEWLINEqosDiffServType16 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType16.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType16.setDescription('DiffServ Type 16 : IP ToS value = 64')NEWLINEqosDiffServType17 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType17.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType17.setDescription('DiffServ Type 17 : IP ToS value = 68')NEWLINEqosDiffServType18 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType18.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType18.setDescription('DiffServ Type 18 : IP ToS value = 72')NEWLINEqosDiffServType19 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType19.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType19.setDescription('DiffServ Type 19 : IP ToS value = 76')NEWLINEqosDiffServType20 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType20.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType20.setDescription('DiffServ Type 20 : IP ToS value = 80')NEWLINEqosDiffServType21 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType21.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType21.setDescription('DiffServ Type 21 : IP ToS value = 84')NEWLINEqosDiffServType22 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 23), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType22.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType22.setDescription('DiffServ Type 22 : IP ToS value = 88')NEWLINEqosDiffServType23 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType23.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType23.setDescription('DiffServ Type 23 : IP ToS value = 92')NEWLINEqosDiffServType24 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType24.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType24.setDescription('DiffServ Type 24 : IP ToS value = 96')NEWLINEqosDiffServType25 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 26), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType25.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType25.setDescription('DiffServ Type 25 : IP ToS value = 100')NEWLINEqosDiffServType26 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 27), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType26.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType26.setDescription('DiffServ Type 26 : IP ToS value = 104')NEWLINEqosDiffServType27 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 28), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType27.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType27.setDescription('DiffServ Type 27 : IP ToS value = 108')NEWLINEqosDiffServType28 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 29), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType28.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType28.setDescription('DiffServ Type 28 : IP ToS value = 112')NEWLINEqosDiffServType29 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType29.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType29.setDescription('DiffServ Type 29 : IP ToS value = 116')NEWLINEqosDiffServType30 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 31), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType30.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType30.setDescription('DiffServ Type 30 : IP ToS value = 120')NEWLINEqosDiffServType31 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType31.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType31.setDescription('DiffServ Type 31 : IP ToS value = 124')NEWLINEqosDiffServType32 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 33), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType32.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType32.setDescription('DiffServ Type 32 : IP ToS value = 128')NEWLINEqosDiffServType33 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 34), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType33.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType33.setDescription('DiffServ Type 33 : IP ToS value = 132')NEWLINEqosDiffServType34 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 35), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType34.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType34.setDescription('DiffServ Type 34 : IP ToS value = 136')NEWLINEqosDiffServType35 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 36), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType35.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType35.setDescription('DiffServ Type 35 : IP ToS value = 140')NEWLINEqosDiffServType36 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 37), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType36.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType36.setDescription('DiffServ Type 36 : IP ToS value = 144')NEWLINEqosDiffServType37 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 38), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType37.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType37.setDescription('DiffServ Type 37 : IP ToS value = 148')NEWLINEqosDiffServType38 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 39), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType38.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType38.setDescription('DiffServ Type 38 : IP ToS value = 152')NEWLINEqosDiffServType39 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 40), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType39.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType39.setDescription('DiffServ Type 39 : IP ToS value = 156')NEWLINEqosDiffServType40 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 41), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType40.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType40.setDescription('DiffServ Type 40 : IP ToS value = 160')NEWLINEqosDiffServType41 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 42), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType41.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType41.setDescription('DiffServ Type 41 : IP ToS value = 164')NEWLINEqosDiffServType42 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 43), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType42.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType42.setDescription('DiffServ Type 42 : IP ToS value = 168')NEWLINEqosDiffServType43 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 44), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType43.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType43.setDescription('DiffServ Type 43 : IP ToS value = 172')NEWLINEqosDiffServType44 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 45), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType44.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType44.setDescription('DiffServ Type 44 : IP ToS value = 176')NEWLINEqosDiffServType45 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 46), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType45.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType45.setDescription('DiffServ Type 45 : IP ToS value = 180')NEWLINEqosDiffServType46 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 47), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType46.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType46.setDescription('DiffServ Type 46 : IP ToS value = 184')NEWLINEqosDiffServType47 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 48), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType47.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType47.setDescription('DiffServ Type 47 : IP ToS value = 188')NEWLINEqosDiffServType48 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 49), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType48.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType48.setDescription('DiffServ Type 48 : IP ToS value = 192')NEWLINEqosDiffServType49 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 50), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType49.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType49.setDescription('DiffServ Type 49 : IP ToS value = 196')NEWLINEqosDiffServType50 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 51), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType50.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType50.setDescription('DiffServ Type 50 : IP ToS value = 200')NEWLINEqosDiffServType51 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 52), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType51.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType51.setDescription('DiffServ Type 51 : IP ToS value = 204')NEWLINEqosDiffServType52 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 53), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType52.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType52.setDescription('DiffServ Type 52 : IP ToS value = 208')NEWLINEqosDiffServType53 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 54), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType53.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType53.setDescription('DiffServ Type 53 : IP ToS value = 212')NEWLINEqosDiffServType54 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 55), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType54.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType54.setDescription('DiffServ Type 54 : IP ToS value = 216')NEWLINEqosDiffServType55 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 56), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType55.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType55.setDescription('DiffServ Type 55 : IP ToS value = 220')NEWLINEqosDiffServType56 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 57), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType56.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType56.setDescription('DiffServ Type 56 : IP ToS value = 224')NEWLINEqosDiffServType57 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 58), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType57.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType57.setDescription('DiffServ Type 57 : IP ToS value = 228')NEWLINEqosDiffServType58 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 59), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType58.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType58.setDescription('DiffServ Type 58 : IP ToS value = 232')NEWLINEqosDiffServType59 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 60), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType59.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType59.setDescription('DiffServ Type 59 : IP ToS value = 236')NEWLINEqosDiffServType60 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 61), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType60.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType60.setDescription('DiffServ Type 60 : IP ToS value = 240')NEWLINEqosDiffServType61 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 62), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType61.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType61.setDescription('DiffServ Type 61 : IP ToS value = 244')NEWLINEqosDiffServType62 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 63), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType62.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType62.setDescription('DiffServ Type 62 : IP ToS value = 248')NEWLINEqosDiffServType63 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 64), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType63.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType63.setDescription('DiffServ Type 63 : IP ToS value = 252')NEWLINEqosTOSGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3))NEWLINEqosTOSType00 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType00.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType00.setDescription('TOS 0')NEWLINEqosTOSType01 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType01.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType01.setDescription('TOS 01')NEWLINEqosTOSType02 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType02.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType02.setDescription('TOS 02')NEWLINEqosTOSType03 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType03.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType03.setDescription('TOS 03')NEWLINEqosTOSType04 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType04.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType04.setDescription('TOS 04')NEWLINEqosTOSType05 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType05.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType05.setDescription('TOS 05')NEWLINEqosTOSType06 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType06.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType06.setDescription('TOS 06')NEWLINEqosTOSType07 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType07.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType07.setDescription('TOS 07')NEWLINEqosAclPrioritySettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8))NEWLINEipv4aclQosTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1), )NEWLINEif mibBuilder.loadTexts: ipv4aclQosTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosTable.setDescription('A list of priority by acl setting.')NEWLINEipv4aclQosEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4aclQosIndex"))NEWLINEif mibBuilder.loadTexts: ipv4aclQosEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosEntry.setDescription('A list of priority by acl setting entry.')NEWLINEipv4aclQosIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclQosIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosIndex.setDescription('Index of priority by acl setting.')NEWLINEipv4aclQosType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("mac", 0), ("ip", 1), ("tcp", 2), ("udp", 3), ("vlanid", 4), ("protocol", 5)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosType.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosType.setDescription('Type of priority by acl setting.')NEWLINEipv4aclQosMACAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 3), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosMACAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosMACAddr.setDescription('Dst MAC of priority by acl setting.')NEWLINEipv4aclQosIPAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 4), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosIPAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosIPAddr.setDescription('Dst IP of priority by acl setting')NEWLINEipv4aclQosTCPUDPPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosTCPUDPPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosTCPUDPPort.setDescription('Dst TCP/UDP port of priority by acl setting')NEWLINEipv4aclQosVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosVlanID.setDescription('VLAN ID of priority by acl setting')NEWLINEipv4aclQosProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosProtocol.setDescription('Ip protocol number of priority by acl setting')NEWLINEipv4aclQosAssignClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("class0", 0), ("class1", 1), ("class2", 2), ("class3", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosAssignClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosAssignClass.setDescription('Be mapped class of priority by acl setting.')NEWLINEipv4aclQosStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 9), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosStatus.setDescription('Status of priority by acl setting.')NEWLINEaclQosTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2), )NEWLINEif mibBuilder.loadTexts: aclQosTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosTable.setDescription('A list of priority by acl setting.')NEWLINEaclQosEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclQosIndex"))NEWLINEif mibBuilder.loadTexts: aclQosEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosEntry.setDescription('A list of priority by acl setting entry.')NEWLINEaclQosIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclQosIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosIndex.setDescription('Index of priority by acl setting.')NEWLINEaclQosType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("mac", 0), ("ip", 1), ("tcp", 2), ("udp", 3), ("vlanid", 4), ("protocol", 5), ("ipv6", 6), ("ipv6traffic-class", 7)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosType.setDescription('Type of priority by acl setting.')NEWLINEaclQosMACAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 3), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosMACAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosMACAddr.setDescription('Dst MAC of priority by acl setting.')NEWLINEaclQosIPAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 4), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosIPAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosIPAddr.setDescription('Dst IP of priority by acl setting')NEWLINEaclQosIPv6Addr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 5), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosIPv6Addr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosIPv6Addr.setDescription('Dst IP of priority by acl setting. ')NEWLINEaclQosTCPUDPPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosTCPUDPPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosTCPUDPPort.setDescription('Dst TCP/UDP port of priority by acl setting')NEWLINEaclQosVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosVlanID.setDescription('VLAN ID of priority by acl setting')NEWLINEaclQosProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosProtocol.setDescription('Ip protocol number of priority by acl setting')NEWLINEaclQosIP6TC = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosIP6TC.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosIP6TC.setDescription('Ipv6 Traffic Class number of priority by acl setting')NEWLINEaclQosAssignClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 98), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("class0", 0), ("class1", 1), ("class2", 2), ("class3", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosAssignClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosAssignClass.setDescription('Be mapped class of priority by acl setting.')NEWLINEaclQosStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 99), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosStatus.setDescription('Status of priority by acl setting.')NEWLINEbandwidthCtrlSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1))NEWLINEbandwidthCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2), )NEWLINEif mibBuilder.loadTexts: bandwidthCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlTable.setDescription('A table to control the rate limiting parameters either for the entire switch or for each interface in the switch.')NEWLINEbandwidthCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "bandwidthCtrlIndex"))NEWLINEif mibBuilder.loadTexts: bandwidthCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlEntry.setDescription('An entry appears in this table for each physical interface in the switch.')NEWLINEbandwidthCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: bandwidthCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlIndex.setDescription('The interface index for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEbandwidthCtrlTxThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(64, 1024000), ))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: bandwidthCtrlTxThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlTxThreshold.setDescription("Configures interface Rate Limit (Packet that can be transferred on a port at a particular second). This object's value will take effect on the interface speed. Based on the operating speed of the port, the rate limit will be applied. This value can also be affected by the metering. A value of zero(0) disable rate limiting i.e. sets the port to full speed. The value can be set between 64~102400(Kbits per second) in FE port, 64~1024000 (Kbits per second) in GE port.")NEWLINEbandwidthCtrlRxThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(64, 1024000), ))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: bandwidthCtrlRxThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlRxThreshold.setDescription('Allows to configure the limiting value for the maximum number of receive packets that can be transmitted per second over this interface. Setting this object to the value zero disables rate limiting for receive packets on this interface. The value that can be set for this object is limited by the underlying hardware. The value can be set between 64~102400(Kbits per second) in FE port, 64~1024000(Kbits per second) in GE port.')NEWLINEbandwidthEffecTxThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: bandwidthEffecTxThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthEffecTxThreshold.setDescription("This object's value will take effect on the interface speed. Based on the operating speed of the port, the rate limit will be applied. This value can also be affected by the metering. A value of zero(0) disable rate limiting i.e. sets the port to full speed. ")NEWLINEbandwidthEffecRxThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 5), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: bandwidthEffecRxThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthEffecRxThreshold.setDescription('Allows to configure the limiting value for the maximum number of receive packets that can be transmitted per second over this interface. Setting this object to the value zero disables rate limiting for receive packets on this interface. The value that can be set for this object is limited by the underlying hardware. ')NEWLINEtrafficCtrlSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4))NEWLINEtrafficCtrlTrap = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("stormOccurred", 1), ("stormCleared", 2), ("both", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlTrap.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlTrap.setDescription('The trap setting of traffic control.')NEWLINEtrafficCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2), )NEWLINEif mibBuilder.loadTexts: trafficCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlTable.setDescription('The traffic control table.')NEWLINEtrafficCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "trafficCtrlIndex"))NEWLINEif mibBuilder.loadTexts: trafficCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlEntry.setDescription('The traffic control entry.')NEWLINEtrafficCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trafficCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlIndex.setDescription('The traffic control index.')NEWLINEtrafficCtrlActionMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("drop", 0), ("shutdown", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlActionMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlActionMode.setDescription('The action mode of traffic control.')NEWLINEtrafficCtrlType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("none", 0), ("b", 1), ("m", 2), ("mb", 3), ("u", 4), ("ub", 5), ("um", 6), ("umb", 7)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlType.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlType.setDescription('The control type of traffic control. (b: Broadcast, m: Multicast, u: Unknown Unicast)')NEWLINEtrafficCtrlThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 102400))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlThreshold.setDescription('The threshold of traffic control.')NEWLINEtrafficCtrlCountDown = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 30))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlCountDown.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlCountDown.setDescription('The count down value of traffic control.')NEWLINEtrafficCtrlTimeInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(5, 30))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlTimeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlTimeInterval.setDescription('The time interval of traffic control.')NEWLINEtrafficCtrlAutoRecoverTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlAutoRecoverTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlAutoRecoverTime.setDescription('The recover time of traffic control.')NEWLINEsecurityTrustedHost = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1))NEWLINEtrustedHostStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trustedHostStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostStatus.setDescription('This object indicates trusted host function is enabled or disabled. When trusted host function is enabled, D-Link Smart Switches will only allow hosts which you trust to access and control the switch. Your local host IP Addresses must be one of the IP Addresses to avoid disconnection.')NEWLINEipv4trustedHostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2), )NEWLINEif mibBuilder.loadTexts: ipv4trustedHostTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostTable.setDescription('A table to configure trusted host in the system.')NEWLINEipv4trustedHostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4trustedHostIpAddr"), (0, "DES-1210-28MEbx", "ipv4trustedHostIpMask"))NEWLINEif mibBuilder.loadTexts: ipv4trustedHostEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostEntry.setDescription('Each entry in this table represents rules for particular trusted host.')NEWLINEipv4trustedHostIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2, 1, 1), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4trustedHostIpAddr.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostIpAddr.setDescription('The IP address of host you allow to access to D-Link Smart Switch. Your local host IP Addresses must be one of the IP Addresses to avoid disconnection.')NEWLINEipv4trustedHostIpMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2, 1, 2), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4trustedHostIpMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostIpMask.setDescription('Used to mask with IP address, it allow you set a subnet as a trusted host entry.')NEWLINEipv4trustedHostRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2, 1, 3), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4trustedHostRowStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostRowStatus.setDescription('The status of an entry in the Trusted Host Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINEtrustedHostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3), )NEWLINEif mibBuilder.loadTexts: trustedHostTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostTable.setDescription('A table to configure trusted host for in the system.')NEWLINEtrustedHostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "trustedHostIPType"), (0, "DES-1210-28MEbx", "trustedHostIpAddr"), (0, "DES-1210-28MEbx", "trustedHostIpMask"))NEWLINEif mibBuilder.loadTexts: trustedHostEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostEntry.setDescription('Each entry in this table represents rules for particular trusted host.')NEWLINEtrustedHostIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trustedHostIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostIPType.setDescription('Type of IP interface.')NEWLINEtrustedHostIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1, 2), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trustedHostIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostIpAddr.setDescription('The IP address of host you allow to access to D-Link Smart Switch. Your local host IPv4/6 Addresses must be one of the IP Addresses to avoid disconnection.')NEWLINEtrustedHostIpMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1, 3), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trustedHostIpMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostIpMask.setDescription('Used to mask with IPv4/6 address, it allow you set a subnet as a trusted host entry.')NEWLINEtrustedHostRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: trustedHostRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostRowStatus.setDescription('The status of an entry in the Trusted Host Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINEsecurityARPSpoofPrevent = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3))NEWLINEaRPSpoofPreventTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1), )NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventTable.setDescription('A table to control ARP Spoofing prevention for the entire switch or for each interface in the switch.')NEWLINEaRPSpoofPreventEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aRPSpoofPreventIpAddr"))NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEaRPSpoofPreventIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1, 1), IpAddress())NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventIpAddr.setDescription("Specifies either the Network or Host address from which the switch can be managed. An address 0.0.0.0 indicates 'Any Manager'.")NEWLINEaRPSpoofPreventMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1, 2), MacAddress().clone(hexValue="000102030405")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventMacAddress.setDescription('Ethernet Mac Address.')NEWLINEaRPSpoofPreventPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventPortList.setDescription("Specifies the port numbers through which the authorized manager can access the switch. By default the authorized manager is allowed to access the switch through all the ports. If a set of ports are configured in the 'PortList', the manager can access the switch only through the configured ports.")NEWLINEaRPSpoofPreventRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEsecuritySSL = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 5))NEWLINEsslSecurityHttpStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 5, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sslSecurityHttpStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sslSecurityHttpStatus.setDescription('This object is for enabling or disabling secure HTTP in the system.')NEWLINEsslCiphers = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 5, 2))NEWLINEsslCipherSuiteList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 5, 2, 1), Bits().clone(namedValues=NamedValues(("rsa-null-md5", 0), ("rsa-null-sha", 1), ("rsa-des-sha", 2), ("rsa-3des-sha", 3), ("dh-rsa-des-sha", 4), ("dh-rsa-3des-sha", 5), ("rsa-exp1024-des-sha", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sslCipherSuiteList.setStatus('current')NEWLINEif mibBuilder.loadTexts: sslCipherSuiteList.setDescription('This object is to configure the cipher-suites list.')NEWLINEsecuritySSH = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8))NEWLINEsshSecurityStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshSecurityStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshSecurityStatus.setDescription('This object is for enabling or disabling ssh in the system.')NEWLINEsshMaxAuthFailAttempts = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshMaxAuthFailAttempts.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshMaxAuthFailAttempts.setDescription('This object indicates the max auth fail retry attempt times.')NEWLINEsshSessionKeyRekeying = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("never", 0), ("ten-min", 1), ("thirty-min", 2), ("sixty-min", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshSessionKeyRekeying.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshSessionKeyRekeying.setDescription('This object indicates one SSH session rekey time interval.')NEWLINEsshMaxSession = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshMaxSession.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshMaxSession.setDescription('This object indicates max SSH session number supported in system.')NEWLINEsshConnectionTimeout = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(120, 600))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshConnectionTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshConnectionTimeout.setDescription('This object indicates SSH connection timeout value.')NEWLINEsshAuthenMethodPassWordAdmin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshAuthenMethodPassWordAdmin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshAuthenMethodPassWordAdmin.setDescription('The object indicates authen method password is enabled or disabled.')NEWLINEsshAuthenMethodPubKeyAdmin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshAuthenMethodPubKeyAdmin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshAuthenMethodPubKeyAdmin.setDescription('The object indicates authen method public-key is enabled or disabled.')NEWLINEsshAuthenMethodHostKeyAdmin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshAuthenMethodHostKeyAdmin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshAuthenMethodHostKeyAdmin.setDescription('The object indicates authen method host-key is enabled or disabled.')NEWLINEsshCipherSuiteList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 9), Bits().clone(namedValues=NamedValues(("tripleDESCBC", 0)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sshCipherSuiteList.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshCipherSuiteList.setDescription('This object is to configure the cipher-suites list.')NEWLINEsshMacSuiteList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 10), Bits().clone(namedValues=NamedValues(("hMAC-SHA1", 0), ("hMAC-MD5", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshMacSuiteList.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshMacSuiteList.setDescription('This object is to configure the MAC-list.')NEWLINEsshPublKeyRSAAdmin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshPublKeyRSAAdmin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshPublKeyRSAAdmin.setDescription('The object indicates Public key generating algorithm RSA is enabled or disabled.')NEWLINEsshUserInfoTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12), )NEWLINEif mibBuilder.loadTexts: sshUserInfoTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoTable.setDescription('A table to configure SSH user auth in the system.')NEWLINEsshUserInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sshUserInfoID"))NEWLINEif mibBuilder.loadTexts: sshUserInfoEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoEntry.setDescription('An entry to configure user auth in the system.')NEWLINEsshUserInfoID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sshUserInfoID.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoID.setDescription('The Schedule identifier. The maximum number of Schedule entry is the number of ports supported PoE function. The value must be between 1 and 8.')NEWLINEsshUserInfoUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sshUserInfoUserName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoUserName.setDescription("The ssh user name associated with the SSH suer Info. entry (e.g., `admin, user').")NEWLINEsshUserInfoAuth = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4, 2, 1))).clone(namedValues=NamedValues(("publickey", 4), ("password", 2), ("hostbased", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshUserInfoAuth.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoAuth.setDescription('The object indicates which auth used by the user.')NEWLINEsshUserInfoHostName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshUserInfoHostName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoHostName.setDescription("The ssh host name associated with the SSH suer Info. entry (e.g., `DUT1, DUT2').")NEWLINEsshUserInfoHostIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 5), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshUserInfoHostIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoHostIp.setDescription('SSH HostBased IP Address of the system.')NEWLINEsecurityPortSecurity = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2))NEWLINEportSecTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1), )NEWLINEif mibBuilder.loadTexts: portSecTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecTable.setDescription('A table to control port security features of the device.')NEWLINEportSecEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "portSecIndex"))NEWLINEif mibBuilder.loadTexts: portSecEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecEntry.setDescription('An entry appears in port security table for each interface in the system.')NEWLINEportSecIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecIndex.setDescription('The interface index for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEportSecState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: portSecState.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecState.setDescription("Enable / disable port security admin state for the interface. A given ports' dynamic MAC address learning will be stopped such that the current source MAC addresses entered into the MAC address forwarding table can not be changed once the port security admin state is enabled.")NEWLINEportSecMLA = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: portSecMLA.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecMLA.setDescription("Configures interface port security maximum learning address numbers. When given ports' admin state is enabled, allows forwarding table learning address number. The number can be set 0 to 64. Note: Set value 0 means cannot learn MAC address.")NEWLINEportSecLockAddrMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("deleteOnReset", 1), ("deleteOnTimeout", 2), ("permanent", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: portSecLockAddrMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecLockAddrMode.setDescription('Configures port security lock address mode for the interface. deleteOnReset : The locked addresses will not age out until the Switch has been reset. deleteOnTimeout : The locked addresses will age out after the aging timer expires. Permanent : The locked addresses will not age out after the aging timer expires.')NEWLINEportSecFDBPermanentTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2), )NEWLINEif mibBuilder.loadTexts: portSecFDBPermanentTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermanentTable.setDescription('A table to control port security FDB Permanent of the device.')NEWLINEportSecFDBPermanentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "portSecFDBPermPort"), (0, "DES-1210-28MEbx", "portSecFDBPermIndex"))NEWLINEif mibBuilder.loadTexts: portSecFDBPermanentEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermanentEntry.setDescription('An entry appears in port security table for each interface in the system.')NEWLINEportSecFDBPermIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecFDBPermIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermIndex.setDescription('The index of the port security MAC entry. For all machines give maximum port number.')NEWLINEportSecFDBPermVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecFDBPermVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermVlanID.setDescription('The VLAN ID of the port security MAC entry.')NEWLINEportSecFDBPermMac = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecFDBPermMac.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermMac.setDescription('The MAC address associated of the port security MAC entry.')NEWLINEportSecFDBPermPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecFDBPermPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermPort.setDescription('The forwarding port of the port security MAC entry. For all machines give maximum port number.')NEWLINEcableDiagTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1), )NEWLINEif mibBuilder.loadTexts: cableDiagTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagTable.setDescription('A table that contains the cable situation for each port.')NEWLINEcableDiagEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cableDiagPortIndex"))NEWLINEif mibBuilder.loadTexts: cableDiagEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagEntry.setDescription('A list of cable situations for each port on the device.')NEWLINEcableDiagPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPortIndex.setDescription('The interface index for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEcableDiagPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("fastEthernet", 0), ("gigaEthernet", 1), ("other", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPortType.setDescription('Indicates the supported port data rate classification.')NEWLINEcableDiagLinkStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("linkdown", 0), ("linkup", 1), ("other", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagLinkStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagLinkStatus.setDescription('This object indicates the link status.')NEWLINEcableDiagPair1Status = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("ok", 0), ("open", 1), ("short", 2), ("open-short", 3), ("crosstalk", 4), ("unknown", 5), ("count", 6), ("no-cable", 7), ("other", 8)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair1Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair1Status.setDescription('Cable diagnostics pair 1 test result.')NEWLINEcableDiagPair2Status = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("ok", 0), ("open", 1), ("short", 2), ("open-short", 3), ("crosstalk", 4), ("unknown", 5), ("count", 6), ("no-cable", 7), ("other", 8)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair2Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair2Status.setDescription('Cable diagnostics pair 2 test result.')NEWLINEcableDiagPair3Status = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("ok", 0), ("open", 1), ("short", 2), ("open-short", 3), ("crosstalk", 4), ("unknown", 5), ("count", 6), ("no-cable", 7), ("other", 8)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair3Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair3Status.setDescription('Cable diagnostics pair 3 test result.')NEWLINEcableDiagPair4Status = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("ok", 0), ("open", 1), ("short", 2), ("open-short", 3), ("crosstalk", 4), ("unknown", 5), ("count", 6), ("no-cable", 7), ("other", 8)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair4Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair4Status.setDescription('Cable diagnostics pair 4 test result.')NEWLINEcableDiagPair1Length = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 8), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair1Length.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair1Length.setDescription('Cable Diagnostics pair 1 fault distance.')NEWLINEcableDiagPair2Length = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 9), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair2Length.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair2Length.setDescription('Cable diagnostics pair 2 fault distance.')NEWLINEcableDiagPair3Length = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 10), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair3Length.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair3Length.setDescription('Cable diagnostics pair 3 fault distance.')NEWLINEcableDiagPair4Length = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 11), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair4Length.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair4Length.setDescription('Cable diagnostics pair 4 fault distance.')NEWLINEcableDiagAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("action", 1), ("processing", 2), ("other", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cableDiagAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagAction.setDescription('Function to run the cable diagnostic on selected port. Can not detect fiber ports')NEWLINEcableDiagStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("notrun", 1), ("processing", 2), ("lasttestok", 3), ("lasttestfailed", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagStatus.setDescription('Indicates the status of cable diagnostics on the port. not-run - cable diagnostics has never been run for this port processing - cable diagnostics is currently running on the port last-test-ok - the last cable diagnostics done on the port was successful last-test-failed - the last cable diagnostics done on the port failed')NEWLINEaclProfile = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1))NEWLINEipv4aclProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1), )NEWLINEif mibBuilder.loadTexts: ipv4aclProfileTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileTable.setDescription(' A table to ACL profile . ')NEWLINEipv4aclProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4aclProfileNo"))NEWLINEif mibBuilder.loadTexts: ipv4aclProfileEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileEntry.setDescription(' Each entry in this table is a ACL profile. Index to the table is ACL profile ID. ')NEWLINEipv4aclProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileNo.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileNo.setDescription('The ACL Profile ID. The ID 1 to 50 is user-defined ACL, and the ID more than 50 is reserved for system-defined ACL. The user only allow to create user-defined ACL ID. And system-defined ACL is read only.')NEWLINEipv4aclProfileType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 8, 9))).clone(namedValues=NamedValues(("l2", 1), ("l3", 2), ("impb", 3), ("arpSP-permit", 4), ("arpSP-deny", 5), ("aclQos", 8), ("userDefined", 9)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileType.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileType.setDescription('The ACL Profile type, possible value are l2 (1) - for MAC-based rule, l3 (2) - for IPv4-based rule, arpSP_permit(4) - for ARP Spoofing prevention entry, arpSP_deny(5) - for ARP Spoofing prevention entry, voiceVlan(6) - for Voice VLAN OUI entry. userDefined(9) - for User Defined entry. Note that only l2, l3 and userDefined could be set by user, other is reserved for system to show information. ')NEWLINEipv4aclProfileRuleCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileRuleCount.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileRuleCount.setDescription('The number of rules in this profile.')NEWLINEipv4aclProfileMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileMask.setDescription('Indicate which field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ L2 DST_MAC 0 (LSB) L2 SRC_MAC 1 L2 VID 2 L2 8021P_PRIORITY 3 L2 ETHER_TYPE 4 L3 DSCP 5 L3 ICMP_TYPE 6 L3 ICMP_CODE 7 L3 IGMP_TYPE 8 L3 DST_IP 9 L3 SRC_IP 10 L3 DST_PORT 11 L3 SRC_PORT 12 L3 TCPFLAG 13 ARP-SP ARP_SENDER_MAC 14 ARP-SP ARP_SENDER_IP 15 L3 TOS 16 UDF UDF1 17 UDF UDF2 18 UDF UDF3 19 UDF UDF4 20 L3v6 TRAFFIC_CLASS 21 L3v6 DST_IPV6 22 L3v6 SRC_IPV6 23 (MSB) ------------------------------------------- The value is in Hex format. ')NEWLINEipv4aclProfileDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstMacAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstMacAddrMask.setDescription('The ACL Profile destination MAC address mask. If DST_MAC is turn on in aclProfileMask, it will work with its member rule field,aclL2RuleDstMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEipv4aclProfileSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 6), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcMacAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcMacAddrMask.setDescription('The ACL Profile source MAC address mask. If SRC_MAC is turn on in aclProfileMask, it will work with its member rule field,aclL2RuleSrcMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEipv4aclProfileIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 6, 17, 58, 256))).clone(namedValues=NamedValues(("none", 0), ("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17), ("icmpv6", 58), ("ipProtocolMask", 256)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileIPProtocol.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileIPProtocol.setDescription('Indicate which IP Protocol will be care in this profile. Only profile type is l3 can set the IP protocol. For others, this field will be none. ')NEWLINEipv4aclProfileIPProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 8), OctetString().clone(hexValue="FF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileIPProtocolMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileIPProtocolMask.setDescription('The ACL Profile IP protocol mask. If aclProfileIPProtocol set to ipMask, this field will be refered. It will work with its member rule field,aclL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ')NEWLINEipv4aclProfileDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 9), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstIpAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstIpAddrMask.setDescription("The ACL Profile destination IP address mask. If DST_IP is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleDstIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEipv4aclProfileSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 10), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcIpAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcIpAddrMask.setDescription("The ACL Profile source IP address mask. If SRC_IP is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleSrcIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEipv4aclProfileDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 11), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstPortMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstPortMask.setDescription('The ACL Profile UDP/TCP destination port mask. If DST_PORT is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleTcpUdpDstPort, to caculate a range of destination port which is really care. The value is in HEX format. ')NEWLINEipv4aclProfileSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 12), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcPortMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcPortMask.setDescription('The ACL Profile UDP/TCP source port mask. If SRC_PORT is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleTcpUdpSrcPort, to caculate a range of source port which is really care. The value is in HEX format. ')NEWLINEipv4aclProfileArpSenderMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 13), MacAddress().clone(hexValue="FFFFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileArpSenderMacAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileArpSenderMacAddrMask.setDescription("The ACL Profile Sender MAC mask. This is only for ARP Spoofing Prevention which is System-defined ACL, and it's not allow to modify. The value is in HEX format. ")NEWLINEipv4aclProfileArpSenderIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 14), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileArpSenderIpAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileArpSenderIpAddrMask.setDescription("The ACL Profile Sender IP mask. This is only for ARP Spoofing Prevention which is System-defined ACL, and it's not allow to modify. The value is in HEX format. ")NEWLINEipv4aclProfileUdfOffsetMap = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 15), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileUdfOffsetMap.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileUdfOffsetMap.setDescription('Indicate which Udf field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ UDF Offset1 0 (LSB) UDF Offset2 1 UDF Offset3 2 UDF Offset4 3 ------------------------------------------- The value is in Hex format. ')NEWLINEipv4aclUdfOffsetBase1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase1.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase1.setDescription('The value of offset Base.')NEWLINEipv4aclUdfOffsetByte1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 17), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte1.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte1.setDescription('The value of offset Byte from base.')NEWLINEipv4aclUdfOffsetMask1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 18), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask1.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask1.setDescription('The value of offset MAsk.')NEWLINEipv4aclUdfOffsetBase2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase2.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase2.setDescription('The value of offset Base.')NEWLINEipv4aclUdfOffsetByte2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 20), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte2.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte2.setDescription('The value of offset Byte from base.')NEWLINEipv4aclUdfOffsetMask2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 21), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask2.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask2.setDescription('The value of offset MAsk.')NEWLINEipv4aclUdfOffsetBase3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase3.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase3.setDescription('The value of offset Base.')NEWLINEipv4aclUdfOffsetByte3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 23), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte3.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte3.setDescription('The value of offset Byte from base.')NEWLINEipv4aclUdfOffsetMask3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 24), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask3.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask3.setDescription('The value of offset MAsk.')NEWLINEipv4aclUdfOffsetBase4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase4.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase4.setDescription('The value of offset Base.')NEWLINEipv4aclUdfOffsetByte4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 26), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte4.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte4.setDescription('The value of offset Byte from base.')NEWLINEipv4aclUdfOffsetMask4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 27), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask4.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask4.setDescription('The value of offset MAsk.')NEWLINEipv4aclProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 28), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileStatus.setDescription(" This object indicates the status of this entry, can only be set to 'createAndWait','active' and 'destroy'. When the value of the entry status is 'createAndWait', it could be set to 'active' only if the three values of aclProfileType, aclProfileMask and ProtocolType are not conflicted. ")NEWLINEaclProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2), )NEWLINEif mibBuilder.loadTexts: aclProfileTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileTable.setDescription(' A table to ACL profile . ')NEWLINEaclProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclProfileNo"))NEWLINEif mibBuilder.loadTexts: aclProfileEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileEntry.setDescription(' Each entry in this table is a ACL profile. Index to the table is ACL profile ID. ')NEWLINEaclProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileNo.setDescription('The ACL Profile ID. The ID 1 to 50 is user-defined ACL, and the ID more than 50 is reserved for system-defined ACL. The user only allow to create user-defined ACL ID. And system-defined ACL is read only.')NEWLINEaclProfileType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 11, 3, 4, 5, 8, 9))).clone(namedValues=NamedValues(("l2", 1), ("l3v4", 2), ("l3v6", 11), ("impb", 3), ("arpSP-permit", 4), ("arpSP-deny", 5), ("aclQos", 8), ("userDefined", 9)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileType.setDescription('The ACL Profile type, possible value are l2 (1) - for MAC-based rule, l3v4 (2) - for IPv4-based rule, l3v6 (11) - for IPv6-based rule, arpSP_permit(4) - for ARP Spoofing prevention entry, arpSP_deny(5) - for ARP Spoofing prevention entry, voiceVlan(6) - for Voice VLAN OUI entry. userDefined(9) - for User Defined entry. Note that only l2, l3 and userDefined could be set by user, other is reserved for system to show information. ')NEWLINEaclProfileRuleCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclProfileRuleCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileRuleCount.setDescription('The number of rules in this profile.')NEWLINEaclProfileMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileMask.setDescription('Indicate which field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ L2 DST_MAC 0 (LSB) L2 SRC_MAC 1 L2 VID 2 L2 8021P_PRIORITY 3 L2 ETHER_TYPE 4 L3 DSCP 5 L3 ICMP_TYPE 6 L3 ICMP_CODE 7 L3 IGMP_TYPE 8 L3 DST_IP 9 L3 SRC_IP 10 L3 DST_PORT 11 L3 SRC_PORT 12 L3 TCPFLAG 13 ARP-SP ARP_SENDER_MAC 14 ARP-SP ARP_SENDER_IP 15 L3 TRAFFIC_CLASS 21 L3 TOS 16 UDF UDF1 17 UDF UDF2 18 UDF UDF3 19 UDF UDF4 20 L3v6 TRAFFIC_CLASS 21 L3v6 DST_IPV6 22 L3v6 SRC_IPV6 23 (MSB) ------------------------------------------- The value is in Hex format. ')NEWLINEaclProfileDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileDstMacAddrMask.setDescription('The ACL Profile destination MAC address mask. If DST_MAC is turn on in aclProfileMask, it will work with its member rule field,aclL2RuleDstMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEaclProfileSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 6), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileSrcMacAddrMask.setDescription('The ACL Profile source MAC address mask. If SRC_MAC is turn on in aclProfileMask, it will work with its member rule field,aclL2RuleSrcMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEaclProfileIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 6, 17, 58, 256))).clone(namedValues=NamedValues(("none", 0), ("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17), ("icmpv6", 58), ("ipProtocolMask", 256)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileIPProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileIPProtocol.setDescription('Indicate which IP Protocol will be care in this profile. Only profile type is l3 can set the IP protocol. For others, this field will be none. ')NEWLINEaclProfileIPProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 8), OctetString().clone(hexValue="FF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileIPProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileIPProtocolMask.setDescription('The ACL Profile IP protocol mask. If aclProfileIPProtocol set to ipMask, this field will be refered. It will work with its member rule field,aclL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ')NEWLINEaclProfileDstIpAddrMaskType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileDstIpAddrMaskType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileDstIpAddrMaskType.setDescription('IPv6 Address type.')NEWLINEaclProfileDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 10), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileDstIpAddrMask.setDescription("The ACL Profile destination IP address mask. If DST_IP is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleDstIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEaclProfileSrcIpAddrMaskType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileSrcIpAddrMaskType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileSrcIpAddrMaskType.setDescription('IPv6 Address type.')NEWLINEaclProfileSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 12), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileSrcIpAddrMask.setDescription("The ACL Profile source IP address mask. If SRC_IP is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleSrcIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEaclProfileDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 13), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileDstPortMask.setDescription('The ACL Profile UDP/TCP destination port mask. If DST_PORT is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleTcpUdpDstPort, to caculate a range of destination port which is really care. The value is in HEX format. ')NEWLINEaclProfileSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 14), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileSrcPortMask.setDescription('The ACL Profile UDP/TCP source port mask. If SRC_PORT is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleTcpUdpSrcPort, to caculate a range of source port which is really care. The value is in HEX format. ')NEWLINEaclProfileArpSenderMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 15), MacAddress().clone(hexValue="FFFFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclProfileArpSenderMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileArpSenderMacAddrMask.setDescription("The ACL Profile Sender MAC mask. This is only for ARP Spoofing Prevention which is System-defined ACL, and it's not allow to modify. The value is in HEX format. ")NEWLINEaclProfileArpSenderIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 16), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclProfileArpSenderIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileArpSenderIpAddrMask.setDescription("The ACL Profile Sender IP mask. This is only for ARP Spoofing Prevention which is System-defined ACL, and it's not allow to modify. The value is in HEX format. ")NEWLINEaclProfileUdfOffsetMap = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 17), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileUdfOffsetMap.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileUdfOffsetMap.setDescription('Indicate which Udf field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ UDF Offset1 0 (LSB) UDF Offset2 1 UDF Offset3 2 UDF Offset4 3 ------------------------------------------- The value is in Hex format. ')NEWLINEaclUdfOffsetBase1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase1.setDescription('The value of offset Base.')NEWLINEaclUdfOffsetByte1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 19), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte1.setDescription('The value of offset Byte from base.')NEWLINEaclUdfOffsetMask1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 20), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask1.setDescription('The value of offset MAsk.')NEWLINEaclUdfOffsetBase2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase2.setDescription('The value of offset Base.')NEWLINEaclUdfOffsetByte2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 22), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte2.setDescription('The value of offset Byte from base.')NEWLINEaclUdfOffsetMask2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 23), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask2.setDescription('The value of offset MAsk.')NEWLINEaclUdfOffsetBase3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase3.setDescription('The value of offset Base.')NEWLINEaclUdfOffsetByte3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 25), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte3.setDescription('The value of offset Byte from base.')NEWLINEaclUdfOffsetMask3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 26), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask3.setDescription('The value of offset MAsk.')NEWLINEaclUdfOffsetBase4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 27), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase4.setDescription('The value of offset Base.')NEWLINEaclUdfOffsetByte4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 28), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte4.setDescription('The value of offset Byte from base.')NEWLINEaclUdfOffsetMask4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 29), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask4.setDescription('The value of offset MAsk.')NEWLINEaclProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 30), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclProfileStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileStatus.setDescription(" This object indicates the status of this entry, can only be set to 'createAndWait','active' and 'destroy'. When the value of the entry status is 'createAndWait', it could be set to 'active' only if the three values of aclProfileType, aclProfileMask and ProtocolType are not conflicted. ")NEWLINEaclL2Rule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2))NEWLINEaclL2RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1), )NEWLINEif mibBuilder.loadTexts: aclL2RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleTable.setDescription('A table to configure L2 filter rules in the system.')NEWLINEaclL2RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclL2ProfileID"), (0, "DES-1210-28MEbx", "aclL2AccessID"))NEWLINEif mibBuilder.loadTexts: aclL2RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleEntry.setDescription('Each entry in this table is a L2 filter rule. Index to the table is the L2 filter number and Profile ID.')NEWLINEaclL2AccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL2AccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2AccessID.setDescription('L2 Filter rule ID. 0 means auto assign.')NEWLINEaclL2ProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50)).clone(1)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL2ProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2ProfileID.setDescription('ACL Profile ID which this rule join.')NEWLINEaclL2RuleEtherType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(1501, 65535), )).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleEtherType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleEtherType.setDescription("The value in the Type/Len field of a frame that will be matched to trigger this filter. The default value of this object is '-1', which means the rule don't care this condition.")NEWLINEaclL2RuleDstMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 4), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleDstMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleDstMacAddr.setDescription("Destination MAC address to be matched with the packet. By Default, the Destination Mac Address will be zero,which means the rule don't care this condition.")NEWLINEaclL2RuleSrcMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleSrcMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleSrcMacAddr.setDescription("Source MAC address to be matched with the packet. By Default, the Source Mac Address will be zero, which means the rule don't care this condition.. address")NEWLINEaclL2RuleVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 4094)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleVlanId.setDescription("Vlan Id to be filtered. In case of Provider bridges, This Vlan Id will be treated as customer Vlan Id. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEaclL2Rule1pPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2Rule1pPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2Rule1pPriority.setDescription("802.1p priority to be matched with the packet. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEaclL2RuleDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 8), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL2RuleDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleDstMacAddrMask.setDescription("The MAC address Mask work for Destination MAC address. This field is read-only and copy from it's Profile setting.")NEWLINEaclL2RuleSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 9), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL2RuleSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleSrcMacAddrMask.setDescription("The MAC address Mask work for Source MAC address. This field is read-only and copy from it's Profile setting.")NEWLINEaclL2RuleInPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 10), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleInPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleInPortList.setDescription('Specifies the complete set of ports over which this filter is applied for packets ingress at ports in this list.')NEWLINEaclL2RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 5, 6, 7))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2), ("mirror", 3), ("replaceDSCP", 5), ("replace1P", 6), ("replaceQueue", 7))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleAction.setDescription("Specifies the action to be taken on the packet if the filter rule matches. If the action is 'allow', the packet will be forwarded according to the forwarding rules. If the action is 'drop', the packet will be discarded.")NEWLINEaclL2RuleRateLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 12), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleRateLimit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleRateLimit.setDescription('Rate limit for matched packet.')NEWLINEaclL2RuleReplaceDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleReplaceDSCP.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleReplaceDSCP.setDescription('Replace DSCP for matched packet.')NEWLINEaclL2RuleReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 14), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleReplace1P.setDescription('Replace DSCP for matched packet.')NEWLINEaclL2RuleReplaceQueue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 15), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleReplaceQueue.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleReplaceQueue.setDescription('ACL L2 Rule Replace Queue.')NEWLINEaclL2RuleFilterTimeRange = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 16), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL2RuleFilterTimeRange.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleFilterTimeRange.setDescription('ACL L2 Filter Time Range')NEWLINEaclL2RuleVlanIdMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 17), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleVlanIdMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleVlanIdMask.setDescription("Vlan Id to be filtered. In case of Provider bridges, This Vlan Id will be treated as customer Vlan Id. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEaclL2RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL2RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaclL3Rule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3))NEWLINEaclL3RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1), )NEWLINEif mibBuilder.loadTexts: aclL3RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTable.setDescription(' A table to configure L3 filter rules in the system. ')NEWLINEaclL3RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclL3RuleProfileNo"), (0, "DES-1210-28MEbx", "aclL3RuleAccessID"))NEWLINEif mibBuilder.loadTexts: aclL3RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleEntry.setDescription(' Each entry in this table is a L3 filter rule. Index to the table is L3 filter number and Profile ID.')NEWLINEaclL3RuleAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleAccessID.setDescription('L3 Filter rule ID. 0 means auto assign.')NEWLINEaclL3RuleProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleProfileNo.setDescription('The Profile ID which this rule join.')NEWLINEaclL3RuleProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 6, 17))).clone(namedValues=NamedValues(("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleProtocol.setDescription(' The type of protocol to be checked against the packet.')NEWLINEaclL3RuleProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 4), OctetString().clone(hexValue="FF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleProtocolMask.setDescription("The IP protocol mask. This field is read-only and copy from it's Profile setting. It will work with the other field,aclL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ")NEWLINEaclL3RuleICMPMessageType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleICMPMessageType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleICMPMessageType.setDescription(" The message type to be checked against the packet. If the message type matches with the packet, then the packet will be dropped / allowed based on the action set in aclL3RuleAction. The default value is '-1',which means the rule don't care this condition. Some ICMP message types are: echoReply(0), destinationUnreachable(3), sourceQuench(4), redirect(5), echoRequest(8), timeExceeded(11), parameterProblem(12), timestampRequest(13), timestampReply(14), informationRequest(15), informationReply(16), addressMaskRequest(17), addressMaskReply (18), ")NEWLINEaclL3RuleICMPMessageCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleICMPMessageCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleICMPMessageCode.setDescription(" The message code to be checked against the packet. If the packet matches with the message code, then the packet will be dropped / allowed based on the action set in aclL3RuleAction. The default value is '-1', which means the rule don't care this condition. Some ICMP message codes are : networkUnreachable(0), hostUnreachable(1), protocolUnreachable(2), portUnreachable(3), fragmentNeed(4), sourceRouteFail(5), destNetworkUnknown(6), destHostUnknown(7), srcHostIsolated(8), destNetworkAdminProhibited(9), destHostAdminProhibited(10), networkUnreachableTOS(11), hostUnreachableTOS(12), ")NEWLINEaclL3RuleDstIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 7), IpAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleDstIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleDstIpAddr.setDescription("Destination IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEaclL3RuleSrcIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 8), IpAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleSrcIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleSrcIpAddr.setDescription("Source IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEaclL3RuleDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 9), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleDstIpAddrMask.setDescription("The IP subnet mask for Destination IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEaclL3RuleSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 10), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleSrcIpAddrMask.setDescription("The IP subnet mask for Source IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEaclL3RuleTcpUdpDstPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpDstPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpDstPort.setDescription("The TCP / UDP destination port. The default value is -1, which means the rule don't care this condition.")NEWLINEaclL3RuleTcpUdpSrcPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpSrcPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpSrcPort.setDescription("The TCP / UDP source port. The default value is -1, which means the rule don't care this condition.")NEWLINEaclL3RuleTcpUdpDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 13), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpDstPortMask.setDescription("The TCP / UDP Destination port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEaclL3RuleTcpUdpSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 14), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpSrcPortMask.setDescription("The TCP / UDP Source port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEaclL3RuleTcpAckBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpAckBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpAckBit.setDescription(" The TCP ACK bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleTcpRstBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpRstBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpRstBit.setDescription(" The TCP RST bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleTcpUrgBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUrgBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUrgBit.setDescription(" The TCP Urg bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleTcpPshBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpPshBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpPshBit.setDescription(" The TCP Psh bit to be checked against the packet. The default value is 'dont_care'(-1). which means the rule don't care this condition.")NEWLINEaclL3RuleTcpSynBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpSynBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpSynBit.setDescription(" The TCP Syn bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleTcpFinBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpFinBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpFinBit.setDescription(" The TCP Fin bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleDscp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleDscp.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleDscp.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEaclL3RuleTos = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 22), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTos.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTos.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEaclL3RuleIgmpType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 23), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleIgmpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleIgmpType.setDescription(" The IGMP Type to be checked against the packet.A default value is '-1', which means the rule don't care this condition.")NEWLINEaclL3RulePortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 24), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RulePortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RulePortList.setDescription('Specifies the complete set of ports over which if the packet arrives this filter rule will be applicable.')NEWLINEaclL3RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 5, 6, 7))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2), ("mirror", 3), ("replaceDSCP", 5), ("replace1P", 6), ("replaceQueue", 7))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleAction.setDescription('Specifies the action to be taken on the packet if the filter rule matches.')NEWLINEaclL3RuleRateLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 26), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleRateLimit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleRateLimit.setDescription('Rate limit for matched packet.')NEWLINEaclL3RuleReplaceDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 27), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleReplaceDSCP.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleReplaceDSCP.setDescription('ReplaceDSCP for matched packet.')NEWLINEaclL3RuleReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 28), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleReplace1P.setDescription('ReplaceDSCP for matched packet.')NEWLINEaclL3RuleReplaceQueue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 29), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleReplaceQueue.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleReplaceQueue.setDescription('Acl L3 Rule Replace Queue.')NEWLINEaclL3RuleFilterTimeRange = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 30), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleFilterTimeRange.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleFilterTimeRange.setDescription('ACL L3 Filter Time Range')NEWLINEaclL3RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaclv6L3RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2), )NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTable.setDescription(' A table to configure L3 filter rules in the system. ')NEWLINEaclv6L3RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclv6L3RuleProfileNo"), (0, "DES-1210-28MEbx", "aclv6L3RuleAccessID"))NEWLINEif mibBuilder.loadTexts: aclv6L3RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleEntry.setDescription(' Each entry in this table is a L3 filter rule. Index to the table is L3 filter number and Profile ID.')NEWLINEaclv6L3RuleAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleAccessID.setDescription('L3 Filter rule ID. 0 means auto assign.')NEWLINEaclv6L3RuleProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProfileNo.setDescription('The Profile ID which this rule join.')NEWLINEaclv6L3RuleProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(6, 17, 58))).clone(namedValues=NamedValues(("tcp", 6), ("udp", 17), ("icmpv6", 58)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProtocol.setDescription(' The type of protocol to be checked against the packet.')NEWLINEaclv6L3RuleProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 4), OctetString().clone(hexValue="FF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProtocolMask.setDescription("The IP protocol mask. This field is read-only and copy from it's Profile setting. It will work with the other field,aclL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ")NEWLINEaclv6L3RuleICMPMessageType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleICMPMessageType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleICMPMessageType.setDescription(" The message type to be checked against the packet. If the message type matches with the packet, then the packet will be dropped / allowed based on the action set in aclL3RuleAction. The default value is '-1',which means the rule don't care this condition. Some ICMP message types are: echoReply(0), destinationUnreachable(3), sourceQuench(4), redirect(5), echoRequest(8), timeExceeded(11), parameterProblem(12), timestampRequest(13), timestampReply(14), informationRequest(15), informationReply(16), addressMaskRequest(17), addressMaskReply (18), ")NEWLINEaclv6L3RuleICMPMessageCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleICMPMessageCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleICMPMessageCode.setDescription(" The message code to be checked against the packet. If the packet matches with the message code, then the packet will be dropped / allowed based on the action set in aclL3RuleAction. The default value is '-1', which means the rule don't care this condition. Some ICMP message codes are : networkUnreachable(0), hostUnreachable(1), protocolUnreachable(2), portUnreachable(3), fragmentNeed(4), sourceRouteFail(5), destNetworkUnknown(6), destHostUnknown(7), srcHostIsolated(8), destNetworkAdminProhibited(9), destHostAdminProhibited(10), networkUnreachableTOS(11), hostUnreachableTOS(12), ")NEWLINEaclv6L3RuleDstIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 7), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleDstIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleDstIpAddr.setDescription("Destination IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEaclv6L3RuleSrcIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 8), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleSrcIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleSrcIpAddr.setDescription("Source IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEaclv6L3RuleDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 9), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleDstIpAddrMask.setDescription("The IP subnet mask for Destination IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEaclv6L3RuleSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 10), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleSrcIpAddrMask.setDescription("The IP subnet mask for Source IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEaclv6L3RuleTcpUdpDstPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpDstPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpDstPort.setDescription("The TCP / UDP destination port. The default value is -1, which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpUdpSrcPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpSrcPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpSrcPort.setDescription("The TCP / UDP source port. The default value is -1, which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpUdpDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 13), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpDstPortMask.setDescription("The TCP / UDP Destination port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEaclv6L3RuleTcpUdpSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 14), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpSrcPortMask.setDescription("The TCP / UDP Source port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEaclv6L3RuleTcpAckBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpAckBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpAckBit.setDescription(" The TCP ACK bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpRstBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpRstBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpRstBit.setDescription(" The TCP RST bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpUrgBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUrgBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUrgBit.setDescription(" The TCP Urg bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpPshBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpPshBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpPshBit.setDescription(" The TCP Psh bit to be checked against the packet. The default value is 'dont_care'(-1). which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpSynBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpSynBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpSynBit.setDescription(" The TCP Syn bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpFinBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpFinBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpFinBit.setDescription(" The TCP Fin bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTrafficClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTrafficClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTrafficClass.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEaclv6L3RulePortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 23), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RulePortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RulePortList.setDescription('Specifies the complete set of ports over which if the packet arrives this filter rule will be applicable.')NEWLINEaclv6L3RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 5, 6, 7))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2), ("mirror", 3), ("replaceDSCP", 5), ("replace1P", 6), ("replaceQueue", 7))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleAction.setDescription('Specifies the action to be taken on the packet if the filter rule matches.')NEWLINEaclv6L3RuleRateLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 25), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleRateLimit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleRateLimit.setDescription('Rate limit for matched packet.')NEWLINEaclv6L3RuleReplaceDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 26), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplaceDSCP.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplaceDSCP.setDescription('Replace DSCP for matched packet.')NEWLINEaclv6L3RuleReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 27), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplace1P.setDescription('Replace DSCP for matched packet.')NEWLINEaclv6L3RuleReplaceQueue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 28), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplaceQueue.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplaceQueue.setDescription('Acl IPV6 L3 Rule Replace Queue.')NEWLINEaclv6L3RuleFilterTimeRange = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 29), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleFilterTimeRange.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleFilterTimeRange.setDescription('ACL IPV6 L3 Filter Time Range')NEWLINEaclv6L3RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaclPacketRule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4))NEWLINEaclPacketRuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1), )NEWLINEif mibBuilder.loadTexts: aclPacketRuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleTable.setDescription('A table to configure Packet Content filter rules in the system.')NEWLINEaclPacketRuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclPacketProfileID"), (0, "DES-1210-28MEbx", "aclPacketAccessID"))NEWLINEif mibBuilder.loadTexts: aclPacketRuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleEntry.setDescription('Each entry in this table is a Packet filter rule. Index to the table is the Packet filter number and Profile ID.')NEWLINEaclPacketAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclPacketAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketAccessID.setDescription('Packet Filter rule ID. 0 means auto assign.')NEWLINEaclPacketProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclPacketProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketProfileID.setDescription('ACL Profile ID which this rule join.')NEWLINEaclPacketRuleOffsetValue1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 3), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue1.setDescription('The filter value of Offset 1.')NEWLINEaclPacketRuleOffsetValue2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue2.setDescription('The filter value of Offset 2.')NEWLINEaclPacketRuleOffsetValue3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 5), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue3.setDescription('The filter value of Offset 3.')NEWLINEaclPacketRuleOffsetValue4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 6), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue4.setDescription('The filter value of Offset 4.')NEWLINEaclPacketRuleInPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 7), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleInPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleInPortList.setDescription('Specifies the complete set of ports over which this filter is applied for packets ingress at ports in this list.')NEWLINEaclPacketRuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 5, 6, 7))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2), ("mirror", 3), ("replaceDSCP", 5), ("replace1P", 6), ("replaceQueue", 7))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleAction.setDescription("Specifies the action to be taken on the packet if the filter rule matches. If the action is 'allow', the packet will be forwarded according to the forwarding rules. If the action is 'drop', the packet will be discarded.")NEWLINEaclPacketRuleRateLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 9), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleRateLimit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleRateLimit.setDescription('Rate limit for matched packet.')NEWLINEaclPacketRuleReplaceDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplaceDSCP.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplaceDSCP.setDescription('Replace DSCP for matched packet.')NEWLINEaclPacketRuleReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplace1P.setDescription('Replace 1p for matched packet.')NEWLINEaclPacketRuleReplaceQueue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 12), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplaceQueue.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplaceQueue.setDescription('Acl Rule Replace Queue.')NEWLINEaclPacketRuleFilterTimeRange = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 13), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclPacketRuleFilterTimeRange.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleFilterTimeRange.setDescription('Acl Filter Time Range')NEWLINEaclPacketRuleOffsetValue1Mask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 14), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue1Mask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue1Mask.setDescription('The filter Mask of Offset 1.')NEWLINEaclPacketRuleOffsetValue2Mask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 15), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue2Mask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue2Mask.setDescription('The filter Mask of Offset 2.')NEWLINEaclPacketRuleOffsetValue3Mask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 16), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue3Mask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue3Mask.setDescription('The filter Mask of Offset 3.')NEWLINEaclPacketRuleOffsetValue4Mask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 17), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue4Mask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue4Mask.setDescription('The filter Mask of Offset 4.')NEWLINEaclPacketRuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclPacketRuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaclFlowMeterRule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10))NEWLINEaclFlowMeterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1), )NEWLINEif mibBuilder.loadTexts: aclFlowMeterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterTable.setDescription('A table to configure L2 filter rules in the system.')NEWLINEaclFlowMeterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclFlowMeterProfileID"), (0, "DES-1210-28MEbx", "aclFlowMeterAccessID"))NEWLINEif mibBuilder.loadTexts: aclFlowMeterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterEntry.setDescription('Each entry in this table is a L2 filter rule. Index to the table is the L2 filter number and Profile ID.')NEWLINEaclFlowMeterProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclFlowMeterProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterProfileID.setDescription('ACL Profile ID which this flow meter join.')NEWLINEaclFlowMeterAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclFlowMeterAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterAccessID.setDescription('ACL Access ID which this flow meter join.')NEWLINEaclFlowMeterRate = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(64, 1024000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclFlowMeterRate.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterRate.setDescription('The rate limiter of meter.')NEWLINEaclFlowMeterBurstSize = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1016))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclFlowMeterBurstSize.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterBurstSize.setDescription('The burst size of meter.')NEWLINEaclFlowMeterReplaceDscp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclFlowMeterReplaceDscp.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterReplaceDscp.setDescription('Replace DSCP for matched out-band packets when aclFlowMeterAction is replace DSCP.')NEWLINEaclFlowMeterAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2, 5))).clone(namedValues=NamedValues(("drop", 2), ("replaceDSCP", 5))).clone('drop')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclFlowMeterAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterAction.setDescription("Specifies the action to be taken on the out-band packet if the filter rule matches. If the action is 'drop', the packet will be discarded.")NEWLINEaclFlowMeterStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclFlowMeterStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEcpuFilterProfile = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1))NEWLINEipv4cpuFilterProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1), )NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileTable.setDescription(' A table to CPUInterfaceFilter profile . ')NEWLINEipv4cpuFilterProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4cpuFilterProfileNo"))NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileEntry.setDescription(' Each entry in this table is a CPUInterfaceFilter profile. Index to the table is CPUInterfaceFilter profile ID. ')NEWLINEipv4cpuFilterProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileNo.setDescription('The CPUInterfaceFilter Profile ID. The ID 1 to 50 is user-defined CPUInterfaceFilter, and the ID more than 50 is reserved for system-defined CPUInterfaceFilter. The user only allow to create user-defined CPUInterfaceFilter ID. And system-defined CPUInterfaceFilter is read only.')NEWLINEipv4cpuFilterProfileType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 11))).clone(namedValues=NamedValues(("l2", 1), ("l3", 2), ("l3v6", 11)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileType.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileType.setDescription('The CPUInterfaceFilter Profile type, possible value are l2 (1) - for MAC-based rule, l3 (2) - for IPv4-based rule, l3v6 (11) - for IPv6-based rule ')NEWLINEipv4cpuFilterProfileRuleCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileRuleCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileRuleCount.setDescription('The number of rules in this profile.')NEWLINEipv4cpuFilterProfileMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileMask.setDescription('Indicate which field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ L2 DST_MAC 0 (LSB) L2 SRC_MAC 1 L2 VID 2 L2 8021P_PRIORITY 3 L2 ETHER_TYPE 4 L3 DSCP 5 L3 ICMP_TYPE 6 L3 ICMP_CODE 7 L3 IGMP_TYPE 8 L3 DST_IP 9 L3 SRC_IP 10 L3 DST_PORT 11 L3 SRC_PORT 12 L3 TCPFLAG 13 (MSB) ------------------------------------------- The value is in Hex format. ')NEWLINEipv4cpuFilterProfileDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstMacAddrMask.setDescription('The CPUInterfaceFilter Profile destination MAC address mask. If DST_MAC is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL2RuleDstMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEipv4cpuFilterProfileSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 6), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcMacAddrMask.setDescription('The CPUInterfaceFilter Profile source MAC address mask. If SRC_MAC is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL2RuleSrcMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEipv4cpuFilterProfileIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 6, 17, 255))).clone(namedValues=NamedValues(("none", 0), ("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17), ("ipMask", 255)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileIPProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileIPProtocol.setDescription('Indicate which IP Protocol will be care in this profile. Only profile type is l3 can set the IP protocol. For others, this field will be none. ')NEWLINEipv4cpuFilterProfileIPProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 8), OctetString().clone(hexValue="FF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileIPProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileIPProtocolMask.setDescription('The CPUInterfaceFilter Profile IP protocol mask. If cpuFilterProfileIPProtocol set to ipMask, this field will be refered. It will work with its member rule field,cpuFilterL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ')NEWLINEipv4cpuFilterProfileDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 9), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstIpAddrMask.setDescription("The CPUInterfaceFilter Profile destination IP address mask. If DST_IP is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleDstIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEipv4cpuFilterProfileSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 10), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcIpAddrMask.setDescription("The CPUInterfaceFilter Profile source IP address mask. If SRC_IP is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleSrcIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEipv4cpuFilterProfileDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 11), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstPortMask.setDescription('The CPUInterfaceFilter Profile UDP/TCP destination port mask. If DST_PORT is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleTcpUdpDstPort, to caculate a range of destination port which is really care. The value is in HEX format. ')NEWLINEipv4cpuFilterProfileSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 12), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcPortMask.setDescription('The CPUInterfaceFilter Profile UDP/TCP source port mask. If SRC_PORT is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleTcpUdpSrcPort, to caculate a range of source port which is really care. The value is in HEX format. ')NEWLINEipv4cpuFilterProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 15), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileStatus.setDescription(" This object indicates the status of this entry, can only be set to 'createAndWait','active' and 'destroy'. When the value of the entry status is 'createAndWait', it could be set to 'active' only if the three values of cpuFilterProfileType, cpuFilterProfileMask and ProtocolType are not conflicted. ")NEWLINEcpuFilterProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2), )NEWLINEif mibBuilder.loadTexts: cpuFilterProfileTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileTable.setDescription(' A table to CPUInterfaceFilter profile . ')NEWLINEcpuFilterProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cpuFilterProfileNo"))NEWLINEif mibBuilder.loadTexts: cpuFilterProfileEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileEntry.setDescription(' Each entry in this table is a CPUInterfaceFilter profile. Index to the table is CPUInterfaceFilter profile ID. ')NEWLINEcpuFilterProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileNo.setDescription('The CPUInterfaceFilter Profile ID. The ID 1 to 50 is user-defined CPUInterfaceFilter, and the ID more than 50 is reserved for system-defined CPUInterfaceFilter. The user only allow to create user-defined CPUInterfaceFilter ID. And system-defined CPUInterfaceFilter is read only.')NEWLINEcpuFilterProfileType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 11))).clone(namedValues=NamedValues(("l2", 1), ("l3", 2), ("l3v6", 11)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileType.setDescription('The CPUInterfaceFilter Profile type, possible value are l2 (1) - for MAC-based rule, l3 (2) - for IPv4-based rule, l3v6 (11) - for IPv6-based rule ')NEWLINEcpuFilterProfileRuleCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileRuleCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileRuleCount.setDescription('The number of rules in this profile.')NEWLINEcpuFilterProfileMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileMask.setDescription('Indicate which field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ L2 DST_MAC 0 (LSB) L2 SRC_MAC 1 L2 VID 2 L2 8021P_PRIORITY 3 L2 ETHER_TYPE 4 L3 DSCP 5 L3 ICMP_TYPE 6 L3 ICMP_CODE 7 L3 IGMP_TYPE 8 L3 DST_IP 9 L3 SRC_IP 10 L3 DST_PORT 11 L3 SRC_PORT 12 L3 TCPFLAG 13 (MSB) L3 TRAFFIC_CLASS 21 ------------------------------------------- The value is in Hex format. ')NEWLINEcpuFilterProfileDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstMacAddrMask.setDescription('The CPUInterfaceFilter Profile destination MAC address mask. If DST_MAC is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL2RuleDstMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEcpuFilterProfileSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 6), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcMacAddrMask.setDescription('The CPUInterfaceFilter Profile source MAC address mask. If SRC_MAC is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL2RuleSrcMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEcpuFilterProfileIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 6, 17, 255))).clone(namedValues=NamedValues(("none", 0), ("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17), ("ipMask", 255)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileIPProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileIPProtocol.setDescription('Indicate which IP Protocol will be care in this profile. Only profile type is l3 can set the IP protocol. For others, this field will be none. ')NEWLINEcpuFilterProfileIPProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 8), OctetString().clone(hexValue="FF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileIPProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileIPProtocolMask.setDescription('The CPUInterfaceFilter Profile IP protocol mask. If cpuFilterProfileIPProtocol set to ipMask, this field will be refered. It will work with its member rule field,cpuFilterL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ')NEWLINEcpuFilterProfileDstIpAddrMaskType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstIpAddrMaskType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstIpAddrMaskType.setDescription('IPv6 Address type.')NEWLINEcpuFilterProfileDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 10), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstIpAddrMask.setDescription("The CPUInterfaceFilter Profile destination IP address mask. If DST_IP is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleDstIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEcpuFilterProfileSrcIpAddrMaskType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcIpAddrMaskType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcIpAddrMaskType.setDescription('IPv6 Address type.')NEWLINEcpuFilterProfileSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 12), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcIpAddrMask.setDescription("The CPUInterfaceFilter Profile source IP address mask. If SRC_IP is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleSrcIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEcpuFilterProfileDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 13), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstPortMask.setDescription('The CPUInterfaceFilter Profile UDP/TCP destination port mask. If DST_PORT is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleTcpUdpDstPort, to caculate a range of destination port which is really care. The value is in HEX format. ')NEWLINEcpuFilterProfileSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 14), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcPortMask.setDescription('The CPUInterfaceFilter Profile UDP/TCP source port mask. If SRC_PORT is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleTcpUdpSrcPort, to caculate a range of source port which is really care. The value is in HEX format. ')NEWLINEcpuFilterProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 15), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileStatus.setDescription(" This object indicates the status of this entry, can only be set to 'createAndWait','active' and 'destroy'. When the value of the entry status is 'createAndWait', it could be set to 'active' only if the three values of cpuFilterProfileType, cpuFilterProfileMask and ProtocolType are not conflicted. ")NEWLINEcpuFilterL2Rule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2))NEWLINEcpuFilterL2RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1), )NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleTable.setDescription('A table to configure L2 filter rules in the system.')NEWLINEcpuFilterL2RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cpuFilterL2ProfileID"), (0, "DES-1210-28MEbx", "cpuFilterL2AccessID"))NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleEntry.setDescription('Each entry in this table is a L2 filter rule. Index to the table is the L2 filter number and Profile ID.')NEWLINEcpuFilterL2ProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL2ProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2ProfileID.setDescription('L2 Filter rule ID.')NEWLINEcpuFilterL2AccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 5)).clone(1)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL2AccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2AccessID.setDescription('CPUInterfaceFilter Profile ID which this rule join.')NEWLINEcpuFilterL2RuleEtherType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(1501, 65535), )).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleEtherType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleEtherType.setDescription("The value in the Type/Len field of a frame that will be matched to trigger this filter. The default value of this object is '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL2RuleDstMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 4), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleDstMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleDstMacAddr.setDescription("Destination MAC address to be matched with the packet. By Default, the Destination Mac Address will be zero,which means the rule don't care this condition.")NEWLINEcpuFilterL2RuleSrcMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleSrcMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleSrcMacAddr.setDescription("Source MAC address to be matched with the packet. By Default, the Source Mac Address will be zero, which means the rule don't care this condition.. address")NEWLINEcpuFilterL2RuleVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 4094)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleVlanId.setDescription("Vlan Id to be filtered. In case of Provider bridges, This Vlan Id will be treated as customer Vlan Id. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL2Rule1pPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2Rule1pPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2Rule1pPriority.setDescription("802.1p priority to be matched with the packet. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL2RuleDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 8), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleDstMacAddrMask.setDescription("The MAC address Mask work for Destination MAC address. This field is read-only and copy from it's Profile setting.")NEWLINEcpuFilterL2RuleSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 9), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleSrcMacAddrMask.setDescription("The MAC address Mask work for Source MAC address. This field is read-only and copy from it's Profile setting.")NEWLINEcpuFilterL2RuleInPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 10), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleInPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleInPortList.setDescription('Specifies the complete set of ports over which this filter is applied for packets ingress at ports in this list.')NEWLINEcpuFilterL2RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleAction.setDescription("Specifies the action to be taken on the packet if the filter rule matches. If the action is 'allow', the packet will be forwarded according to the forwarding rules. If the action is 'drop', the packet will be discarded.")NEWLINEcpuFilterL2RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 14), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEcpuFilterL3Rule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3))NEWLINEcpuFilterL3RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1), )NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTable.setDescription(' A table to configure L3 filter rules in the system. ')NEWLINEcpuFilterL3RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cpuFilterL3RuleProfileNo"), (0, "DES-1210-28MEbx", "cpuFilterL3RuleAccessID"))NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleEntry.setDescription(' Each entry in this table is a L3 filter rule. Index to the table is L3 filter number and Profile ID.')NEWLINEcpuFilterL3RuleProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 5))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProfileNo.setDescription('L3 Filter rule ID.')NEWLINEcpuFilterL3RuleAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleAccessID.setDescription('The Profile ID which this rule join.')NEWLINEcpuFilterL3RuleProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 6, 17))).clone(namedValues=NamedValues(("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProtocol.setDescription(' The type of protocol to be checked against the packet.')NEWLINEcpuFilterL3RuleProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 4), OctetString().clone(hexValue="FF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProtocolMask.setDescription("The IP protocol mask. This field is read-only and copy from it's Profile setting. It will work with the other field,cpuFilterL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ")NEWLINEcpuFilterL3RuleICMPMessageType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleICMPMessageType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleICMPMessageType.setDescription(" The message type to be checked against the packet. If the message type matches with the packet, then the packet will be dropped / allowed based on the action set in cpuFilterL3RuleAction. The default value is '-1',which means the rule don't care this condition. Some ICMP message types are: echoReply(0), destinationUnreachable(3), sourceQuench(4), redirect(5), echoRequest(8), timeExceeded(11), parameterProblem(12), timestampRequest(13), timestampReply(14), informationRequest(15), informationReply(16), addressMaskRequest(17), addressMaskReply (18), ")NEWLINEcpuFilterL3RuleICMPMessageCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleICMPMessageCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleICMPMessageCode.setDescription(" The message code to be checked against the packet. If the packet matches with the message code, then the packet will be dropped / allowed based on the action set in cpuFilterL3RuleAction. The default value is '-1', which means the rule don't care this condition. Some ICMP message codes are : networkUnreachable(0), hostUnreachable(1), protocolUnreachable(2), portUnreachable(3), fragmentNeed(4), sourceRouteFail(5), destNetworkUnknown(6), destHostUnknown(7), srcHostIsolated(8), destNetworkAdminProhibited(9), destHostAdminProhibited(10), networkUnreachableTOS(11), hostUnreachableTOS(12), ")NEWLINEcpuFilterL3RuleDstIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 7), IpAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDstIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDstIpAddr.setDescription("Destination IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleSrcIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 8), IpAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleSrcIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleSrcIpAddr.setDescription("Source IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 9), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDstIpAddrMask.setDescription("The IP subnet mask for Destination IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterL3RuleSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 10), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleSrcIpAddrMask.setDescription("The IP subnet mask for Source IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterL3RuleTcpUdpDstPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpDstPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpDstPort.setDescription("The TCP / UDP destination port. The default value is -1, which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpUdpSrcPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpSrcPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpSrcPort.setDescription("The TCP / UDP source port. The default value is -1, which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpUdpDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 13), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpDstPortMask.setDescription("The TCP / UDP Destination port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterL3RuleTcpUdpSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 14), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpSrcPortMask.setDescription("The TCP / UDP Source port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterL3RuleTcpAckBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpAckBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpAckBit.setDescription(" The TCP ACK bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpRstBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpRstBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpRstBit.setDescription(" The TCP RST bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpUrgBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUrgBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUrgBit.setDescription(" The TCP Urg bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpPshBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpPshBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpPshBit.setDescription(" The TCP Psh bit to be checked against the packet. The default value is 'dontcare'(-1). which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpSynBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpSynBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpSynBit.setDescription(" The TCP Syn bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpFinBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpFinBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpFinBit.setDescription(" The TCP Fin bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleDscp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDscp.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDscp.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleIgmpType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 22), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleIgmpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleIgmpType.setDescription(" The IGMP Type to be checked against the packet.A default value is '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL3RulePortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 23), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RulePortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RulePortList.setDescription('Specifies the complete set of ports over which if the packet arrives this filter rule will be applicable.')NEWLINEcpuFilterL3RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleAction.setDescription('Specifies the action to be taken on the packet if the filter rule matches.')NEWLINEcpuFilterL3RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 27), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEcpuFilterv6L3RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2), )NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTable.setDescription(' A table to configure L3 filter rules in the system. ')NEWLINEcpuFilterv6L3RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cpuFilterv6L3RuleProfileNo"), (0, "DES-1210-28MEbx", "cpuFilterv6L3RuleAccessID"))NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleEntry.setDescription(' Each entry in this table is a L3 filter rule. Index to the table is L3 filter number and Profile ID.')NEWLINEcpuFilterv6L3RuleProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 5))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProfileNo.setDescription('L3 Filter rule ID.')NEWLINEcpuFilterv6L3RuleAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleAccessID.setDescription('The Profile ID which this rule join.')NEWLINEcpuFilterv6L3RuleProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 6, 17))).clone(namedValues=NamedValues(("icmp", 1), ("tcp", 6), ("udp", 17)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProtocol.setDescription(' The type of protocol to be checked against the packet.')NEWLINEcpuFilterv6L3RuleProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 4), OctetString().clone(hexValue="FF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProtocolMask.setDescription("The IP protocol mask. This field is read-only and copy from it's Profile setting. It will work with the other field,cpuFilterL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ")NEWLINEcpuFilterv6L3RuleICMPMessageType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleICMPMessageType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleICMPMessageType.setDescription(" The message type to be checked against the packet. If the message type matches with the packet, then the packet will be dropped / allowed based on the action set in cpuFilterL3RuleAction. The default value is '-1',which means the rule don't care this condition. Some ICMP message types are: echoReply(0), destinationUnreachable(3), sourceQuench(4), redirect(5), echoRequest(8), timeExceeded(11), parameterProblem(12), timestampRequest(13), timestampReply(14), informationRequest(15), informationReply(16), addressMaskRequest(17), addressMaskReply (18), ")NEWLINEcpuFilterv6L3RuleICMPMessageCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleICMPMessageCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleICMPMessageCode.setDescription(" The message code to be checked against the packet. If the packet matches with the message code, then the packet will be dropped / allowed based on the action set in cpuFilterL3RuleAction. The default value is '-1', which means the rule don't care this condition. Some ICMP message codes are : networkUnreachable(0), hostUnreachable(1), protocolUnreachable(2), portUnreachable(3), fragmentNeed(4), sourceRouteFail(5), destNetworkUnknown(6), destHostUnknown(7), srcHostIsolated(8), destNetworkAdminProhibited(9), destHostAdminProhibited(10), networkUnreachableTOS(11), hostUnreachableTOS(12), ")NEWLINEcpuFilterv6L3RuleDstIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 7), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleDstIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleDstIpAddr.setDescription("Destination IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleSrcIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 8), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleSrcIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleSrcIpAddr.setDescription("Source IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 9), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleDstIpAddrMask.setDescription("The IP subnet mask for Destination IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterv6L3RuleSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 10), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleSrcIpAddrMask.setDescription("The IP subnet mask for Source IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterv6L3RuleTcpUdpDstPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpDstPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpDstPort.setDescription("The TCP / UDP destination port. The default value is -1, which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpUdpSrcPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpSrcPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpSrcPort.setDescription("The TCP / UDP source port. The default value is -1, which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpUdpDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 13), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpDstPortMask.setDescription("The TCP / UDP Destination port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterv6L3RuleTcpUdpSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 14), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpSrcPortMask.setDescription("The TCP / UDP Source port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterv6L3RuleTcpAckBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpAckBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpAckBit.setDescription(" The TCP ACK bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpRstBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpRstBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpRstBit.setDescription(" The TCP RST bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpUrgBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUrgBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUrgBit.setDescription(" The TCP Urg bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpPshBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpPshBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpPshBit.setDescription(" The TCP Psh bit to be checked against the packet. The default value is 'dontcare'(-1). which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpSynBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpSynBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpSynBit.setDescription(" The TCP Syn bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpFinBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpFinBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpFinBit.setDescription(" The TCP Fin bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTrafficClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTrafficClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTrafficClass.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RulePortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 22), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RulePortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RulePortList.setDescription('Specifies the complete set of ports over which if the packet arrives this filter rule will be applicable.')NEWLINEcpuFilterv6L3RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 23), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleAction.setDescription('Specifies the action to be taken on the packet if the filter rule matches.')NEWLINEcpuFilterv6L3RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 24), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEsnmpGlobalState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpGlobalState.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpGlobalState.setDescription('This object is for enabling or disabling SNMP Community function.')NEWLINEsnmpV3User = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2))NEWLINEsnmpV3Group = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3))NEWLINEsnmpV3ViewTree = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4))NEWLINEsnmpV3Community = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5))NEWLINEsnmpV3Host = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6))NEWLINEsnmpV3EngineID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 7), SnmpEngineID()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3EngineID.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3EngineID.setDescription("An SNMP engine's administratively-unique identifier. In a simple agent, this value is always that agent's own snmpEngineID value. The value can also take the value of the snmpEngineID of a remote SNMP engine with which this user can communicate.")NEWLINEsnmpV3Trap = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8))NEWLINEsnmpV3UserTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1), )NEWLINEif mibBuilder.loadTexts: snmpV3UserTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserTable.setDescription('')NEWLINEsnmpV3UserEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3UserName"), (0, "DES-1210-28MEbx", "snmpV3UserVersion"))NEWLINEif mibBuilder.loadTexts: snmpV3UserEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserEntry.setDescription('')NEWLINEsnmpV3UserName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3UserName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserName.setDescription('A human readable string representing the name of the user. This is the (User-based Security) Model dependent security ID. ')NEWLINEsnmpV3UserVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("v1", 1), ("v2c", 2), ("v3", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3UserVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserVersion.setDescription('A human readable string representing the name of the user. This is the (User-based Security) Model dependent security ID. ')NEWLINEsnmpV3UserGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserGroupName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserGroupName.setDescription('The name of the group to which this entry (e.g., the combination of securityModel and securityName) belongs. This groupName is used as index into the vacmAccessTable to select an access control policy. However, a value in this table does not imply that an instance with the value exists in table vacmAccesTable. ')NEWLINEsnmpV3UserAuthProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("md5", 2), ("sha", 3)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserAuthProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserAuthProtocol.setDescription("An indication of whether messages sent on behalf of this user to/from the SNMP engine identified by usmUserEngineID, can be authenticated, and if so, the type of authentication protocol which is used. An instance of this object is created concurrently with the creation of any other object instance for the same user (i.e., as part of the processing of the set operation which creates the first object instance in the same conceptual row). If an initial set operation (i.e. at row creation time) tries to set a value for an unknown or unsupported protocol, then a 'wrongValue' error must be returned. The value will be overwritten/set when a set operation is performed on the corresponding instance of UserCloneFrom. Once instantiated, the value of such an instance of this object can only be changed via a set operation to the value of the NoAuthProtocol. If a set operation tries to change the value of an existing instance of this object to any value other than NoAuthProtocol, then an 'inconsistentValue' error must be returned. If a set operation tries to set the value to the NoAuthProtocol while the UserPrivProtocol value in the same row is not equal to NoPrivProtocol, then an 'inconsistentValue' error must be returned. That means that an SNMP command generator application must first ensure that the UserPrivProtocol is set to the NoPrivProtocol value before it can set the UserAuthProtocol value to NoAuthProtocol. ")NEWLINEsnmpV3UserAuthProtocolPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 5), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserAuthProtocolPassword.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserAuthProtocolPassword.setDescription('')NEWLINEsnmpV3UserPrivProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("none", 1), ("des", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserPrivProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserPrivProtocol.setDescription("An indication of whether messages sent on behalf of this user to/from the SNMP engine identified by usmUserEngineID, can be protected from disclosure, and if so, the type of privacy protocol which is used. An instance of this object is created concurrently with the creation of any other object instance for the same user (i.e., as part of the processing of the set operation which creates the first object instance in the same conceptual row). If an initial set operation (i.e. at row creation time) tries to set a value for an unknown or unsupported protocol, then a 'wrongValue' error must be returned. The value will be overwritten/set when a set operation is performed on the corresponding instance of usmUserCloneFrom. Once instantiated, the value of such an instance of this object can only be changed via a set operation to the value of the NoPrivProtocol. If a set operation tries to change the value of an existing instance of this object to any value other than NoPrivProtocol, then an 'inconsistentValue' error must be returned. Note that if any privacy protocol is used, then you must also use an authentication protocol. In other words, if usmUserPrivProtocol is set to anything else than NoPrivProtocol, then the corresponding instance of usmUserAuthProtocol cannot have a value of usmNoAuthProtocol. If it does, then an 'inconsistentValue' error must be returned. ")NEWLINEsnmpV3UserPrivProtocolPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 7), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserPrivProtocolPassword.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserPrivProtocolPassword.setDescription('')NEWLINEsnmpV3UserStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 8), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserStatus.setDescription("The status of this conceptual row. Until instances of all corresponding columns are appropriately configured, the value of the corresponding instance of the usmUserStatus column is 'notReady'. In particular, a newly created row for a user who employs authentication, cannot be made active until the corresponding usmUserCloneFrom and usmUserAuthKeyChange have been set. Further, a newly created row for a user who also employs privacy, cannot be made active until the usmUserPrivKeyChange has been set. The RowStatus TC [RFC2579] requires that this DESCRIPTION clause states under which circumstances other objects in this row can be modified: The value of this object has no effect on whether other objects in this conceptual row can be modified, except for usmUserOwnAuthKeyChange and usmUserOwnPrivKeyChange. For these 2 objects, the value of usmUserStatus MUST be active. ")NEWLINEsnmpV3GroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1), )NEWLINEif mibBuilder.loadTexts: snmpV3GroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupTable.setDescription('')NEWLINEsnmpV3GroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3GroupName"), (0, "DES-1210-28MEbx", "snmpV3GroupSecurityModel"), (0, "DES-1210-28MEbx", "snmpV3GroupSecurityLevel"))NEWLINEif mibBuilder.loadTexts: snmpV3GroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupEntry.setDescription('')NEWLINEsnmpV3GroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3GroupName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupName.setDescription('The name of the group to which this entry (e.g., the combination of securityModel and securityName) belongs. This groupName is used as index into the vacmAccessTable to select an access control policy. However, a value in this table does not imply that an instance with the value exists in table vacmAccesTable. ')NEWLINEsnmpV3GroupSecurityModel = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("v1", 1), ("v2c", 2), ("v3", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3GroupSecurityModel.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupSecurityModel.setDescription('In order to gain the access rights allowed by this conceptual row, this securityModel must be in use. ')NEWLINEsnmpV3GroupSecurityLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 3), SnmpSecurityLevel()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3GroupSecurityLevel.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupSecurityLevel.setDescription('The minimum level of security required in order to gain the access rights allowed by this conceptual row. A securityLevel of noAuthNoPriv is less than authNoPriv which in turn is less than authPriv. If multiple entries are equally indexed except for this vacmAccessSecurityLevel index, then the entry which has the highest value for vacmAccessSecurityLevel is selected. ')NEWLINEsnmpV3GroupReadViewName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 4), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3GroupReadViewName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupReadViewName.setDescription('The value of an instance of this object identifies the MIB view of the SNMP context to which this conceptual row authorizes read access. The identified MIB view is that one for which the vacmViewTreeFamilyViewName has the same value as the instance of this object; if the value is the empty string or if there is no active MIB view having this value of vacmViewTreeFamilyViewName, then no access is granted. ')NEWLINEsnmpV3GroupWriteViewName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 5), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3GroupWriteViewName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupWriteViewName.setDescription('The value of an instance of this object identifies the MIB view of the SNMP context to which this conceptual row authorizes write access. The identified MIB view is that one for which the vacmViewTreeFamilyViewName has the same value as the instance of this object; if the value is the empty string or if there is no active MIB view having this value of vacmViewTreeFamilyViewName, then no access is granted. ')NEWLINEsnmpV3GroupNotifyViewName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 6), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3GroupNotifyViewName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupNotifyViewName.setDescription('The value of an instance of this object identifies the MIB view of the SNMP context to which this conceptual row authorizes access for notifications. The identified MIB view is that one for which the vacmViewTreeFamilyViewName has the same value as the instance of this object; if the value is the empty string or if there is no active MIB view having this value of vacmViewTreeFamilyViewName, then no access is granted. ')NEWLINEsnmpV3GroupStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 7), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3GroupStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupStatus.setDescription('The status of this conceptual row. The RowStatus TC [RFC2579] requires that this DESCRIPTION clause states under which circumstances other objects in this row can be modified: The value of this object has no effect on whether other objects in this conceptual row can be modified. ')NEWLINEsnmpV3ViewTreeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1), )NEWLINEif mibBuilder.loadTexts: snmpV3ViewTreeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3ViewTreeTable.setDescription('')NEWLINEsnmpV3ViewTreeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3viewTreeName"), (0, "DES-1210-28MEbx", "snmpV3viewTreeSubtree"))NEWLINEif mibBuilder.loadTexts: snmpV3ViewTreeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3ViewTreeEntry.setDescription('')NEWLINEsnmpV3viewTreeName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeName.setDescription('The human readable name for a family of view subtrees. ')NEWLINEsnmpV3viewTreeSubtree = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeSubtree.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeSubtree.setDescription('The MIB subtree which when combined with the corresponding instance of vacmViewTreeFamilyMask defines a family of view subtrees. ')NEWLINEsnmpV3viewTreeMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeMask.setDescription("The bit mask which, in combination with the corresponding instance of vacmViewTreeFamilySubtree, defines a family of view subtrees. Each bit of this bit mask corresponds to a sub-identifier of vacmViewTreeFamilySubtree, with the most significant bit of the i-th octet of this octet string value (extended if necessary, see below) corresponding to the (8*i - 7)-th sub-identifier, and the least significant bit of the i-th octet of this octet string corresponding to the (8*i)-th sub-identifier, where i is in the range 1 through 16. Each bit of this bit mask specifies whether or not the corresponding sub-identifiers must match when determining if an OBJECT IDENTIFIER is in this family of view subtrees; a '1' indicates that an exact match must occur; a '0' indicates 'wild card', i.e., any sub-identifier value matches. Thus, the OBJECT IDENTIFIER X of an object instance is contained in a family of view subtrees if, for each sub-identifier of the value of vacmViewTreeFamilySubtree, either: the i-th bit of vacmViewTreeFamilyMask is 0, or the i-th sub-identifier of X is equal to the i-th sub-identifier of the value of vacmViewTreeFamilySubtree. If the value of this bit mask is M bits long and there are more than M sub-identifiers in the corresponding instance of vacmViewTreeFamilySubtree, then the bit mask is extended with 1's to be the required length. Note that when the value of this object is the zero-length string, this extension rule results in a mask of all-1's being used (i.e., no 'wild card'), and the family of view subtrees is the one view subtree uniquely identified by the corresponding instance of vacmViewTreeFamilySubtree. Note that masks of length greater than zero length do not need to be supported. In this case this object is made read-only. ")NEWLINEsnmpV3viewTreeType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("included", 1), ("excluded", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeType.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeType.setDescription('Indicates whether the corresponding instances of vacmViewTreeFamilySubtree and vacmViewTreeFamilyMask define a family of view subtrees which is included in or excluded from the MIB view. ')NEWLINEsnmpV3viewTreeStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 5), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeStatus.setDescription('The status of this conceptual row. The RowStatus TC [RFC2579] requires that this DESCRIPTION clause states under which circumstances other objects in this row can be modified: The value of this object has no effect on whether other objects in this conceptual row can be modified. ')NEWLINEsnmpV3CommunityTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1), )NEWLINEif mibBuilder.loadTexts: snmpV3CommunityTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityTable.setDescription('')NEWLINEsnmpV3CommunityEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3CommunityName"))NEWLINEif mibBuilder.loadTexts: snmpV3CommunityEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityEntry.setDescription('')NEWLINEsnmpV3CommunityName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3CommunityName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityName.setDescription('The unique index value of a row in this table.')NEWLINEsnmpV3CommunityPolicy = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3CommunityPolicy.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityPolicy.setDescription('A human readable string representing the corresponding value of snmpCommunityName in a Security Model independent format.')NEWLINEsnmpV3CommunityStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1, 1, 3), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3CommunityStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityStatus.setDescription('The status of this conceptual row in the snmpCommunityTable. An entry in this table is not qualified for activation until instances of all corresponding columns have been initialized, either through default values, or through Set operations. The snmpCommunityName and snmpCommunitySecurityName objects must be explicitly set. There is no restriction on setting columns in this table when the value of snmpCommunityStatus is active(1).')NEWLINEipv4snmpV3HostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1), )NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostTable.setDescription('')NEWLINEipv4snmpV3HostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4snmpV3HostAddress"))NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostEntry.setDescription('')NEWLINEipv4snmpV3HostAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1, 1), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostAddress.setDescription('This object contains a transport address. The format of this address depends on the value of the snmpTargetAddrTDomain object. And this object is unique identifier associated with this snmpNotifyEntry.')NEWLINEipv4snmpV3HostCommunityName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostCommunityName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostCommunityName.setDescription('The locally arbitrary.')NEWLINEipv4snmpV3HostVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("v1", 1), ("v2c", 2), ("v3NoAuthNoPriv", 3), ("v3AuthNoPriv", 4), ("v3AuthPriv", 5)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostVersion.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostVersion.setDescription('The Level of Security to be used when generating SNMP messages using this entry.')NEWLINEipv4snmpV3HostStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostStatus.setDescription('')NEWLINEsnmpV3HostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2), )NEWLINEif mibBuilder.loadTexts: snmpV3HostTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostTable.setDescription('')NEWLINEsnmpV3HostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3HostAddress"), (0, "DES-1210-28MEbx", "snmpV3IPType"))NEWLINEif mibBuilder.loadTexts: snmpV3HostEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostEntry.setDescription('')NEWLINEsnmpV3HostAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 1), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3HostAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostAddress.setDescription('This object contains a transport address. The format of this address depends on the value of the snmpTargetAddrTDomain object. And this object is unique identifier associated with this snmpNotifyEntry.')NEWLINEsnmpV3IPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3IPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3IPType.setDescription('Type of IP interface.')NEWLINEsnmpV3HostCommunityName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3HostCommunityName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostCommunityName.setDescription('The locally arbitrary.')NEWLINEsnmpV3HostVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("v1", 1), ("v2c", 2), ("v3NoAuthNoPriv", 3), ("v3AuthNoPriv", 4), ("v3AuthPriv", 5)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3HostVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostVersion.setDescription('The Level of Security to be used when generating SNMP messages using this entry.')NEWLINEsnmpV3HostInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 5), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3HostInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostInterfaceName.setDescription('Specifies the interface name when the syslogSrvIP is linklocal address.')NEWLINEsnmpV3HostStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 6), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3HostStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostStatus.setDescription('')NEWLINEsnmpV3TrapSNMPAuthentication = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapSNMPAuthentication.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapSNMPAuthentication.setDescription('This object is for enabling or disabling SNMP login fail event trap in the system.')NEWLINEsnmpV3TrapColdStart = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapColdStart.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapColdStart.setDescription('This object is for enabling or disabling devie Bootup event trap in the system.')NEWLINEsnmpV3TrapWarmStart = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapWarmStart.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapWarmStart.setDescription('This object is for enabling or disabling devie Bootup event trap in the system.')NEWLINEsnmpV3TrapLinkUpDown = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapLinkUpDown.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapLinkUpDown.setDescription('This object is for enabling or disabling Copper link up / link down event trap in the system.')NEWLINEsnmpV3TrapRSTPStateChange = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapRSTPStateChange.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapRSTPStateChange.setDescription('This object is for enabling or disabling RSTP topology change event trap in the system.')NEWLINEsnmpV3TrapFirmUpgrade = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapFirmUpgrade.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapFirmUpgrade.setDescription('This object is for enabling or disabling Firmware upgrade suess or fail event trap in the system.')NEWLINEsnmpV3TrapBPDUAttack = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("attackDetected", 2), ("attackCleared", 3), ("both", 4))).clone('none')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapBPDUAttack.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapBPDUAttack.setDescription('Used to configure trap settings for BPDU attack protection events.')NEWLINEsnmpV3TrapPortSecurity = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapPortSecurity.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapPortSecurity.setDescription('')NEWLINEsnmpV3TrapIMPBViolation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapIMPBViolation.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapIMPBViolation.setDescription('')NEWLINEsnmpV3TrapLBD = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapLBD.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapLBD.setDescription('')NEWLINEsnmpV3TrapDHCPServerScreening = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapDHCPServerScreening.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapDHCPServerScreening.setDescription('')NEWLINEsnmpV3TrapDuplicateIPDetected = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapDuplicateIPDetected.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapDuplicateIPDetected.setDescription('This object is for enabling or disabling send gratuitous trap when IP address conflicted in the network.')NEWLINEsnmpV3CommunityEncryption = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3CommunityEncryption.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityEncryption.setDescription('This object is for enabling or disabling community encryption.')NEWLINEtraps = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0))NEWLINEsnmpTrapSNMPAuthentication = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 1))NEWLINEif mibBuilder.loadTexts: snmpTrapSNMPAuthentication.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapSNMPAuthentication.setDescription('SnmpV3TrapSNMPAuthentication.')NEWLINEsnmpTrapColdStart = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 2))NEWLINEif mibBuilder.loadTexts: snmpTrapColdStart.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapColdStart.setDescription('SnmpV3TrapColdStart.')NEWLINEsnmpTrapWarmStart = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 3))NEWLINEif mibBuilder.loadTexts: snmpTrapWarmStart.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapWarmStart.setDescription('SnmpV3TrapWarmStart.')NEWLINEsnmpTrapCopperLinkUpDown = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 4))NEWLINEif mibBuilder.loadTexts: snmpTrapCopperLinkUpDown.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapCopperLinkUpDown.setDescription('SnmpV3TrapCopperLinkUpDown.')NEWLINEsnmpTrapRSTPStateChange = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 5))NEWLINEif mibBuilder.loadTexts: snmpTrapRSTPStateChange.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapRSTPStateChange.setDescription('SnmpV3TrapRSTPStateChange.')NEWLINEsnmpTrapFirmUpgrade = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 6))NEWLINEif mibBuilder.loadTexts: snmpTrapFirmUpgrade.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapFirmUpgrade.setDescription('SnmpV3TrapFirmUpgrade.')NEWLINEsnmpTrapBPDUAttack = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 11))NEWLINEif mibBuilder.loadTexts: snmpTrapBPDUAttack.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapBPDUAttack.setDescription('SnmpV3TrapBPDUAttack.')NEWLINEsnmpTrapPortSecurity = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 12))NEWLINEif mibBuilder.loadTexts: snmpTrapPortSecurity.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapPortSecurity.setDescription('SnmpV3TrapPortSecurity.')NEWLINEsnmpTrapIMPBv2 = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 13))NEWLINEif mibBuilder.loadTexts: snmpTrapIMPBv2.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapIMPBv2.setDescription('SnmpV3TrapIMPBv2.')NEWLINEsnmpTrapLBD = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 14))NEWLINEif mibBuilder.loadTexts: snmpTrapLBD.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapLBD.setDescription('SnmpV3TrapLBD.')NEWLINEsnmpTrapDHCPScreen = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 15))NEWLINEif mibBuilder.loadTexts: snmpTrapDHCPScreen.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapDHCPScreen.setDescription('SnmpV3TrapDHCPScreen.')NEWLINEsnmpTrapGratuitousArp = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 16))NEWLINEif mibBuilder.loadTexts: snmpTrapGratuitousArp.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapGratuitousArp.setDescription('SnmpV3TrapGratuitousArp.')NEWLINEmacNotificatiotn = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 17))NEWLINEif mibBuilder.loadTexts: macNotificatiotn.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotificatiotn.setDescription(' This trap indicates the MAC address variations in the address table . ')NEWLINEduplicateIP = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 21))NEWLINEif mibBuilder.loadTexts: duplicateIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: duplicateIP.setDescription(' duplicateIP . ')NEWLINEtrafficControl = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 22))NEWLINEif mibBuilder.loadTexts: trafficControl.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficControl.setDescription(' trafficControl. ')NEWLINEtopologyChange = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 23))NEWLINEif mibBuilder.loadTexts: topologyChange.setStatus('current')NEWLINEif mibBuilder.loadTexts: topologyChange.setDescription(' topologyChange. ')NEWLINEnewRootBrgaddress = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 24))NEWLINEif mibBuilder.loadTexts: newRootBrgaddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: newRootBrgaddress.setDescription(' newRootBrgaddress. ')NEWLINEnewRootOlddesignatedroot = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 25))NEWLINEif mibBuilder.loadTexts: newRootOlddesignatedroot.setStatus('current')NEWLINEif mibBuilder.loadTexts: newRootOlddesignatedroot.setDescription(' newRootOlddesignatedroot. ')NEWLINEnewRootMSTibridgeregionalroot = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 26))NEWLINEif mibBuilder.loadTexts: newRootMSTibridgeregionalroot.setStatus('current')NEWLINEif mibBuilder.loadTexts: newRootMSTibridgeregionalroot.setDescription(' topologyChange. ')NEWLINEsyslogSettingGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 1))NEWLINEsyslogEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogEnable.setDescription('This object is for enabling or disabling syslog alert features in the system and the syslog will save to flash or send to remote syslog server. System Logs record and manage events, as well as report errors and informational messages.')NEWLINEsyslogSaveMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("onDemand", 0), ("timeInterval", 1), ("logTrigger", 2))).clone('logTrigger')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogSaveMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogSaveMode.setDescription('This object is for choosing the method to save syslog into flash.')NEWLINEsyslogSaveMinutes = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(30)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogSaveMinutes.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogSaveMinutes.setDescription("When savemode is time interval, it's used to set the interval minutes of system save syslog to flash.")NEWLINEipv4syslogServerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2))NEWLINEipv4syslogServTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1), )NEWLINEif mibBuilder.loadTexts: ipv4syslogServTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServTable.setDescription('The table of syslog remote server.')NEWLINEipv4syslogServEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4syslogServIndex"))NEWLINEif mibBuilder.loadTexts: ipv4syslogServEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServEntry.setDescription('The list of syslog remote server entry.')NEWLINEipv4syslogServIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4syslogServIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServIndex.setDescription('The index of syslog remote server.')NEWLINEipv4syslogServAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 2), IpAddress()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServAddr.setDescription('The IP Address of syslog remote server.')NEWLINEipv4syslogServSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4, 6, 7))).clone(namedValues=NamedValues(("warning", 4), ("information", 6), ("all", 7)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServSeverity.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServSeverity.setDescription('Specifies the log level option to be set for a specific server.')NEWLINEipv4syslogServFacility = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(128, 136, 144, 152, 160, 168, 176, 184))).clone(namedValues=NamedValues(("local0", 128), ("local1", 136), ("local2", 144), ("local3", 152), ("local4", 160), ("local5", 168), ("local6", 176), ("local7", 184))).clone('local0')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServFacility.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServFacility.setDescription('The Syslog standard facilities. The facility to be used when sending Syslog messages to this server.')NEWLINEipv4syslogServUDPport = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(514, 514), ValueRangeConstraint(6000, 65535), ))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServUDPport.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServUDPport.setDescription('The value is for setting UDP Port.')NEWLINEipv4syslogServSrvStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServSrvStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServSrvStatus.setDescription('The status for this server. If enable, system will send message to this server.')NEWLINEipv4syslogServSrvRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 7), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4syslogServSrvRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServSrvRowStatus.setDescription('Row status of this server entry.')NEWLINEsyslogServerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3))NEWLINEsyslogServTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1), )NEWLINEif mibBuilder.loadTexts: syslogServTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServTable.setDescription('The table of syslog remote server.')NEWLINEsyslogServEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "syslogServIndex"))NEWLINEif mibBuilder.loadTexts: syslogServEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServEntry.setDescription('The list of syslog remote server entry.')NEWLINEsyslogServIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: syslogServIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServIndex.setDescription('The index of syslog remote server.')NEWLINEsyslogServAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipv4", 1), ("ipv6", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServAddrType.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServAddrType.setDescription('Specifies the Address type of server.Address type shall be ipv4 or ipv6.')NEWLINEsyslogServAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 3), Ipv6Address()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServAddr.setDescription('Specifies the ServerIP to which the syslog shall be forwarded.')NEWLINEsyslogServInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 4), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServInterfaceName.setDescription('Specifies the interface name when the syslogServInterfaceName is linklocal address.')NEWLINEsyslogServSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4, 6, 7))).clone(namedValues=NamedValues(("warning", 4), ("information", 6), ("all", 7)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServSeverity.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServSeverity.setDescription('Specifies the log level option to be set for a specific server.')NEWLINEsyslogServFacility = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(128, 136, 144, 152, 160, 168, 176, 184))).clone(namedValues=NamedValues(("local0", 128), ("local1", 136), ("local2", 144), ("local3", 152), ("local4", 160), ("local5", 168), ("local6", 176), ("local7", 184))).clone('local0')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServFacility.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServFacility.setDescription('The Syslog standard facilities. The facility to be used when sending Syslog messages to this server.')NEWLINEsyslogServUDPport = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(514, 514), ValueRangeConstraint(6000, 65535), ))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServUDPport.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServUDPport.setDescription('The value is for setting UDP Port.')NEWLINEsyslogServSrvStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogServSrvStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServSrvStatus.setDescription('The status for this server. If enable, system will send message to this server.')NEWLINEsyslogServSrvRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 9), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogServSrvRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServSrvRowStatus.setDescription('Row status of this server entry.')NEWLINEsysLBDStateEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDStateEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDStateEnable.setDescription('Enable/Disable Loopback detection function. The Loopback Detection function is used to detect the loop created by a specific port while Spanning Tree Protocol (STP) is not enabled in the network, especially when the down links are hubs or unmanaged switchs.The Switch will automatically shutdown the port and sends a log to the administrator.')NEWLINEsysLBDMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("port", 1), ("vlan", 2))).clone('port')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDMode.setDescription('Loopback detection function mode.')NEWLINEsysLBDInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32767)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDInterval.setDescription('Set a Loop detection Interval between 1 and 32767 seconds. The default is 2 seconds. This time interval to be used at counting time seconds to resend the CTP packet automatically.')NEWLINEsysLBDRecoverTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(60, 1000000), )).clone(60)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDRecoverTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDRecoverTime.setDescription('This time interval to be used at counting time seconds to recover the disabled port automatically. The Loop Detection Recover Time can be set at 0 seconds, or 60 to 1000000 seconds. Entering 0 will disable the Loop Detection Recover Time. The default is 60 seconds.')NEWLINEsysLBDCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5), )NEWLINEif mibBuilder.loadTexts: sysLBDCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDCtrlTable.setDescription('A table to control Loopback detection features either for the entire switch or for each interface in the switch.')NEWLINEsysLBDCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysLBDCtrlIndex"))NEWLINEif mibBuilder.loadTexts: sysLBDCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDCtrlEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEsysLBDCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysLBDCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDCtrlIndex.setDescription('The interface index of the port for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEsysLBDPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDPortStatus.setDescription('Provides control to per port enable or disable the loopback detection function. Default is disabled.')NEWLINEsysLBDPortLoopStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("normal", 1), ("loop", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysLBDPortLoopStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDPortLoopStatus.setDescription('The loop status for this port.')NEWLINEsysLBDVlanLoopTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 6), )NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopTable.setDescription('A table to display Loopback detection features by vlan mode .')NEWLINEsysLBDVlanLoopEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 6, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysLBDVlanLoopIndex"))NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEsysLBDVlanLoopIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopIndex.setDescription('Display port lists loop status by vlan.')NEWLINEsysLBDVlanLoopPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 6, 1, 2), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopPorts.setDescription('Display port lists loop status by vlan.')NEWLINEsysMirrorStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMirrorStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMirrorStatus.setDescription('Enable/Disable Port Mirroring function. Default is disabled. Port Mirroring is a method of monitoring network traffic that forwards a copy of each incoming and/or outgoing packet from one port of the Switch to another port where the packet can be studied.')NEWLINEsysMirrorTargetPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18, 2), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMirrorTargetPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMirrorTargetPort.setDescription('Specifies the port to which the mirrored traffic in the system is to be copied.')NEWLINEsysMirrorCtrlIngressMirroring = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMirrorCtrlIngressMirroring.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMirrorCtrlIngressMirroring.setDescription('Provides control to enable or disable mirroring of ingress traffic over this interface to the mirrored-to port.')NEWLINEsysMirrorCtrlEgressMirroring = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMirrorCtrlEgressMirroring.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMirrorCtrlEgressMirroring.setDescription('Provides control to enable or disable mirroring of egress traffic over this interface to the mirrored-to port.')NEWLINEsysTrapIP = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 1), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapIP.setDescription("The smart console utility's IP address is used to recive trap events.")NEWLINEsysTrapSystemEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("deviceBootUp", 1), ("illegalLogin", 2), ("both", 3))).clone('none')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapSystemEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapSystemEvent.setDescription('Enable/Disable system trap events in the switch system.')NEWLINEsysTrapFiberPortEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapFiberPortEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapFiberPortEvent.setDescription('Enable/Disable fiber port trap event in the system.')NEWLINEsysTrapTwistedPortEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapTwistedPortEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapTwistedPortEvent.setDescription('Enable/Disable twisted port trap event in the system.')NEWLINEsysTrapStateChangeEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapStateChangeEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapStateChangeEvent.setDescription('Enable/Disable RSTP state change trap event in the system.')NEWLINEsysTrapFirmUpgradeEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapFirmUpgradeEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapFirmUpgradeEvent.setDescription('Enable/Disable firmware upgrading trap event in the system.')NEWLINEsysTrapStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapStatus.setDescription('Enable/Disable trap event in the system.')NEWLINEsysTrapPortSecurity = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapPortSecurity.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapPortSecurity.setDescription('')NEWLINEsysTrapIMPBViolation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapIMPBViolation.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapIMPBViolation.setDescription('')NEWLINEsysTrapLBD = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapLBD.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapLBD.setDescription('')NEWLINEsysTrapDHCPServerScreening = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapDHCPServerScreening.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapDHCPServerScreening.setDescription('')NEWLINEsysTrapDuplicateIPDetected = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapDuplicateIPDetected.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapDuplicateIPDetected.setDescription('This object is for enabling or disabling send gratuitous trap when IP address conflicted in the network.')NEWLINEipv4sysSNTPTimeSeconds = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 1), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPTimeSeconds.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPTimeSeconds.setDescription('This object is for setting the system time in seconds from Epoch (00:00:00 UTC, January 1, 2009). Notice : input value must larger than 1230768000 (00:00:00 UTC, January 1, 2009) and smaller than 2145916799 (23:59:59 UTC, December 31, 2037).')NEWLINEipv4sysSNTPFirstServer = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPFirstServer.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPFirstServer.setDescription("SNTP First Server's IP Address")NEWLINEipv4sysSNTPSecondServer = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 3), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPSecondServer.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPSecondServer.setDescription("SNTP Second Server's IP Address")NEWLINEipv4sysSNTPPollInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 4), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPPollInterval.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPPollInterval.setDescription('SNTP Poll Interval In Seconds (30-99999) ')NEWLINEipv4sysSNTPState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("sntp", 1), ("local", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPState.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPState.setDescription('Enable/Disable SNTP function in the system.')NEWLINEipv4sysSNTPDSTOffset = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(30, 60, 90, 120))).clone(namedValues=NamedValues(("offset30min", 30), ("offset60min", 60), ("offset90min", 90), ("offset120min", 120)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTOffset.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTOffset.setDescription('This object is for Daylight Saving Time Offset In (30/60/90/120) Minutes.')NEWLINEipv4sysSNTPGMTMinutes = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 7), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPGMTMinutes.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPGMTMinutes.setDescription('Specifies the Time Zone Offset from GMT in +/- Minutes. (+780 ~ -720)')NEWLINEipv4sysSNTPDSTStartMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 8), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartMon.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartMon.setDescription('The start month of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTStartDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 9), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartDay.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartDay.setDescription('The start day of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTStartHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 10), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartHour.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartHour.setDescription('The start hour of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTStartMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 11), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartMin.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartMin.setDescription('The start minute of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTEndMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 12), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndMon.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndMon.setDescription('The end month of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTEndDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 13), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndDay.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndDay.setDescription('The end day of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTEndHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 14), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndHour.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndHour.setDescription('The end hour of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTEndMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 15), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndMin.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndMin.setDescription('The end minute of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("annual", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTState.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTState.setDescription('This object is for Annual(1) or Disabled(2) DST state in the system.')NEWLINEsysSNTPServerTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17))NEWLINEsysSNTPTimeSeconds = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 1), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPTimeSeconds.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPTimeSeconds.setDescription('This object is for setting the system time in seconds from Epoch (00:00:00 UTC, January 1, 2009). Notice : input value must larger than 1230768000 (00:00:00 UTC, January 1, 2009) and smaller than 2145916799 (23:59:59 UTC, December 31, 2037).')NEWLINEsysSNTPFirstServer = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 2), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPFirstServer.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPFirstServer.setDescription("SNTP First Server's IPv6 Address")NEWLINEsysSNTPFirstType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPFirstType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPFirstType.setDescription("SNTP First Server's IPv6 Address type.")NEWLINEsysSNTPFirstInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPFirstInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPFirstInterfaceName.setDescription('Specifies the interface name when the sysSNTPFirstServer is linklocal address.')NEWLINEsysSNTPSecondServer = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 5), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPSecondServer.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPSecondServer.setDescription("SNTP Second Server's IPv6 Address")NEWLINEsysSNTPSecondType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPSecondType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPSecondType.setDescription("SNTP First Server's IPv6 Address type.")NEWLINEsysSNTPSecondInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 7), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPSecondInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPSecondInterfaceName.setDescription('Specifies the interface name when the sysSNTPSecondServer is linklocal address.')NEWLINEsysSNTPPollInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 8), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPPollInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPPollInterval.setDescription('SNTP Poll Interval In Seconds (30-99999) ')NEWLINEsysSNTPState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("sntp", 1), ("local", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPState.setDescription('Enable/Disable SNTP function in the system.')NEWLINEsysSNTPDSTOffset = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(30, 60, 90, 120))).clone(namedValues=NamedValues(("offset30min", 30), ("offset60min", 60), ("offset90min", 90), ("offset120min", 120)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTOffset.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTOffset.setDescription('This object is for Daylight Saving Time Offset In (30/60/90/120) Minutes.')NEWLINEsysSNTPGMTMinutes = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 11), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPGMTMinutes.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPGMTMinutes.setDescription('Specifies the Time Zone Offset from GMT in +/- Minutes. (+780 ~ -720)')NEWLINEsysSNTPDSTStartMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 12), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartMon.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartMon.setDescription('The start month of Daylight Saving Time.')NEWLINEsysSNTPDSTStartDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 13), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartDay.setDescription('The start day of Daylight Saving Time.')NEWLINEsysSNTPDSTStartHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 14), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartHour.setDescription('The start hour of Daylight Saving Time.')NEWLINEsysSNTPDSTStartMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 15), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartMin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartMin.setDescription('The start minute of Daylight Saving Time.')NEWLINEsysSNTPDSTEndMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 16), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndMon.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndMon.setDescription('The end month of Daylight Saving Time.')NEWLINEsysSNTPDSTEndDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 17), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndDay.setDescription('The end day of Daylight Saving Time.')NEWLINEsysSNTPDSTEndHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 18), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndHour.setDescription('The end hour of Daylight Saving Time.')NEWLINEsysSNTPDSTEndMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 19), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndMin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndMin.setDescription('The end minute of Daylight Saving Time.')NEWLINEsysSNTPDSTState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTState.setDescription('This object is for Enabled(1) or Disabled(2) DST state in the system.')NEWLINEsysSNTPDSTMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("annual", 1), ("repeating", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTMethod.setDescription('This object is for Annual(1) or Repeating(2) DST method in the system.')NEWLINEsysSNTPDSTRepeatStartMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 31), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartMon.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartMon.setDescription('The start month of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatStartWeek = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("last", 0), ("first", 1), ("second", 2), ("third", 3), ("fourth", 4), ("fifth", 5)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartWeek.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartWeek.setDescription('The start week of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatStartWeekDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 33), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("sun", 0), ("mon", 1), ("tue", 2), ("wed", 3), ("thu", 4), ("fri", 5), ("sat", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartWeekDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartWeekDay.setDescription('The start weekday of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatStartHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 34), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartHour.setDescription('The start hour of Daylight Saving Time in Repeating mode..')NEWLINEsysSNTPDSTRepeatStartMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 35), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartMin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartMin.setDescription('The start minute of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatEndMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 36), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndMon.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndMon.setDescription('The end month of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatEndWeek = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 37), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("last", 0), ("first", 1), ("second", 2), ("third", 3), ("fourth", 4), ("fifth", 5)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndWeek.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndWeek.setDescription('The end week of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatEndWeekDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 38), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("sun", 0), ("mon", 1), ("tue", 2), ("wed", 3), ("thu", 4), ("fri", 5), ("sat", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndWeekDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndWeekDay.setDescription('The end weekday of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatEndHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 39), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndHour.setDescription('The end hour of Daylight Saving Time in Repeating mode..')NEWLINEsysSNTPDSTRepeatEndMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 40), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndMin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndMin.setDescription('The end minute of Daylight Saving Time in Repeating mode.')NEWLINElimitIpMulticastProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1), )NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileTable.setDescription('A list of the limit ip multicast Profile Table.')NEWLINElimitIpMulticastProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "limitIpMulticastIPType"), (0, "DES-1210-28MEbx", "limitIpMulticastProfileID"))NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileEntry.setDescription('A limit ip multicast entry maintain by the start IP Address, end ip address, profile id.')NEWLINElimitIpMulticastIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipv4", 1), ("ipv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastIPType.setDescription('Indicate the IP type of profile.')NEWLINElimitIpMulticastProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 24))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileID.setDescription('The ProfileID of the limit ip multicast profile entry.')NEWLINElimitIpMulticastProfileName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileName.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileName.setDescription('The ProfileName of the limit ip multicast profile entry.')NEWLINElimitIpMulticastProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1, 4), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileStatus.setDescription('The status of an entry in the limit ip multicast profile Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINElimitIpMulticastEntryTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2), )NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryTable.setDescription('A list of the limit ip multicast entry Table.')NEWLINElimitIpMulticastEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "limitIpMulticastEntryIPType"), (0, "DES-1210-28MEbx", "limitIpMulticastEntryProfileID"), (0, "DES-1210-28MEbx", "limitIpMulticaststartIpAddr"), (0, "DES-1210-28MEbx", "limitIpMulticastendIpAddr"))NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntry.setDescription('A limit ip multicast entry maintain by the start IP Address, end ip address, profile id.')NEWLINElimitIpMulticastEntryIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipv4", 1), ("ipv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryIPType.setDescription('Indicate the IP type of entry.')NEWLINElimitIpMulticastEntryProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 24))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryProfileID.setDescription('The ProfileID of the limit ip multicast entry.')NEWLINElimitIpMulticaststartIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticaststartIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticaststartIpAddr.setDescription('The limit ip multicast IP address is used to set start ip')NEWLINElimitIpMulticastendIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastendIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastendIpAddr.setDescription('The limit ip multicast IP address is used to set end ip')NEWLINElimitIpMulticastStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 5), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastStatus.setDescription('The status of an entry in the limit ip multicast entry Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINElimitIpMulticastPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3), )NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortTable.setDescription('A list of the limit ip multicast Port entry Table.')NEWLINElimitIpMulticastPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "limitIpMulticastPortIPType"), (0, "DES-1210-28MEbx", "limitIpMulticastPortID"))NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortEntry.setDescription('A limit ip multicast entry maintain by the Port Index.')NEWLINElimitIpMulticastPortIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipv4", 1), ("ipv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortIPType.setDescription('Indicate the IP type of entry.')NEWLINElimitIpMulticastPortID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortID.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortID.setDescription('The Port Index of the limit ip multicast port entry. For all machines give maximum port number.')NEWLINElimitIpMulticastPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("permit", 1), ("deny", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortState.setDescription('The limit ip multicast port state')NEWLINElimitIpMulticastPortProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortProfileID.setDescription('The limit ip multicast port mapping profileID list.')NEWLINElimitIpMulticastPortMaxGrp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 256))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortMaxGrp.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortMaxGrp.setDescription('The limit ip multicast per-port max group.')NEWLINEguestVlanName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 24, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: guestVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: guestVlanName.setDescription('The VLAN name of guest VLAN.')NEWLINEguestVlanPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 24, 2), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: guestVlanPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: guestVlanPort.setDescription('This object indicates the guest VLAN port members of this device.')NEWLINEguestVlanDelState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 24, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("none", 1), ("start", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: guestVlanDelState.setStatus('current')NEWLINEif mibBuilder.loadTexts: guestVlanDelState.setDescription('Used to delete the guest VLAN.')NEWLINEprotocolGroupNameTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 1), )NEWLINEif mibBuilder.loadTexts: protocolGroupNameTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupNameTable.setDescription('A table to control protocol group name features of the device.')NEWLINEprotocolGroupNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "protocolGroupGID"))NEWLINEif mibBuilder.loadTexts: protocolGroupNameEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupNameEntry.setDescription('An entry appears in protocol group name table for each interface in the system.')NEWLINEprotocolGroupGID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolGroupGID.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupGID.setDescription('The group ID of protocol group name table.')NEWLINEprotocolGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: protocolGroupName.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupName.setDescription('The group name of protocol group name table.')NEWLINEprotocolGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2), )NEWLINEif mibBuilder.loadTexts: protocolGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupTable.setDescription('A table to control protocol group features of the device.')NEWLINEprotocolGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "protocolGroupId"), (0, "DES-1210-28MEbx", "protocolGroupFrameType"), (0, "DES-1210-28MEbx", "protocolGroupProtocolValue"))NEWLINEif mibBuilder.loadTexts: protocolGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupEntry.setDescription('An entry appears in protocol group table for each interface in the system.')NEWLINEprotocolGroupId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolGroupId.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupId.setDescription('The group ID of protocol group table.')NEWLINEprotocolGroupFrameType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ethernet", 1), ("ieee8023-snap", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolGroupFrameType.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupFrameType.setDescription('The frame type of protocol group table.')NEWLINEprotocolGroupProtocolValue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolGroupProtocolValue.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupProtocolValue.setDescription('The protocol value of protocol group table.')NEWLINEprotocolGroupRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: protocolGroupRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupRowStatus.setDescription('The row status of protocol group table.')NEWLINEprotocolVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3), )NEWLINEif mibBuilder.loadTexts: protocolVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanTable.setDescription('A table to control protocol vlan features of the device.')NEWLINEprotocolVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "protocolVlanPort"), (0, "DES-1210-28MEbx", "protocolVlanVID"), (0, "DES-1210-28MEbx", "protocolVlanGroupID"))NEWLINEif mibBuilder.loadTexts: protocolVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanEntry.setDescription('An entry appears in protocol vlan table for each interface in the system.')NEWLINEprotocolVlanPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolVlanPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanPort.setDescription('The interface number of protocol vlan table.')NEWLINEprotocolVlanVID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolVlanVID.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanVID.setDescription('The vlan ID of protocol vlan table.')NEWLINEprotocolVlanGroupID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolVlanGroupID.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanGroupID.setDescription('The group ID of protocol vlan table.')NEWLINEprotocolVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: protocolVlanRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanRowStatus.setDescription('The row status of protocol vlan table.')NEWLINEmacNotifyState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyState.setDescription('This object can enabled or disabled MAC Notification.')NEWLINEmacNotifyInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macNotifyInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyInterval.setDescription('This object indicates the time interval in second for trigger the MAC notify message. ')NEWLINEmacNotifyHistorySize = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 500))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macNotifyHistorySize.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyHistorySize.setDescription('This object indicates the history size of variation MAC in address table. The default value is 1 .')NEWLINEmacNotifyCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 4), )NEWLINEif mibBuilder.loadTexts: macNotifyCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyCtrlTable.setDescription('A table to control Loopback detection features either for the entire switch or for each interface in the switch.')NEWLINEmacNotifyCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "macNotifyCtrlIndex"))NEWLINEif mibBuilder.loadTexts: macNotifyCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyCtrlEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEmacNotifyCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: macNotifyCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyCtrlIndex.setDescription('The interface index of the port for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEmacNotifyPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macNotifyPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyPortStatus.setDescription('Provides control to per port enable or disable the loopback detection function. Default is disabled.')NEWLINEmacNotifyInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 5))NEWLINEmacNotifyInfoDiscription = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 5, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1024))).setMaxAccess("accessiblefornotify")NEWLINEif mibBuilder.loadTexts: macNotifyInfoDiscription.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyInfoDiscription.setDescription('This object indicates the information for the device MAC address changes. And the detailed information include: Operation Code + MAC address + Box ID + Port Number + Zero... Operation Code: 1, 2 and 3 1 means learned a new MAC address 2 means deleted an old MAC address. 3 means station movement. Box ID: The switch box ID, for standalone device, it always 1. Port Number: The port number learned or deleted for the box. Zero: Used to separate each message (Operate Code + MAC address + Box ID + Port Number).')NEWLINEsysBPDUAttackStateEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackStateEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackStateEnable.setDescription('Use this to enable BPDU attack protection. The BPDU Attack Protection function and Spanning Tree Protocol for ports are mutually exclusive. When the STP function is enabled on a particular port, BPDU Attack Protection cannot be enabled.')NEWLINEsysBPDUAttackRecoverTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(60, 1000000), )).clone(60)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackRecoverTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackRecoverTime.setDescription('When a port enters under attack state, it can be disabled or blocked based on the configuration. The state can be recovered manually or by the auto recovery mechanism. This command is used to configure the auto-recovery timer. To manually recover the port, the user needs to disable and re-enable the port.')NEWLINEsysBPDUAttackCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3), )NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlTable.setDescription('A table to control BPDU Attack features either for the entire switch or for each interface in the switch.')NEWLINEsysBPDUAttackCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysBPDUAttackCtrlIndex"))NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEsysBPDUAttackCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlIndex.setDescription('The interface index of the port for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEsysBPDUAttackPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortState.setDescription('Used to configure the BPDU Attack Protection state of a port. The default state is disable.')NEWLINEsysBPDUAttackPortMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("drop", 1), ("block", 2), ("shutdown", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortMode.setDescription('Used to configure the BPDU Attack Protection mode of a port.')NEWLINEsysBPDUAttackPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("normal", 1), ("underAttack", 2))).clone('normal')).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortStatus.setDescription('Use this to view per port BPDU attack protection status.')NEWLINEsysBPDUAttackLog = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("attackDetected", 2), ("attackCleared", 3), ("both", 4))).clone('none')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackLog.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackLog.setDescription('Used to configure log settings for BPDU attack protection events.')NEWLINEvlanTrunkSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1))NEWLINEvlanTrunkGlobalStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanTrunkGlobalStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkGlobalStatus.setDescription('This indicates the global state of the VLAN trunking feature of the device.')NEWLINEvlanTrunkTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 2), )NEWLINEif mibBuilder.loadTexts: vlanTrunkTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkTable.setDescription('This table is used to manage the VLAN trunking feature of the device.')NEWLINEvlanTrunkEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "vlanTrunkIfIndex"))NEWLINEif mibBuilder.loadTexts: vlanTrunkEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkEntry.setDescription('There is one entry in this table for each created port-channel port.')NEWLINEvlanTrunkIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 2, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: vlanTrunkIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkIfIndex.setDescription('The index of the port. ')NEWLINEvlanTrunkState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanTrunkState.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkState.setDescription('Sets the VLAN trunk status as enabled or disabled.')NEWLINEqinqSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1))NEWLINEqinqVLANTranslation = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2))NEWLINEqinqGlobalStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqGlobalStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqGlobalStatus.setDescription('This object is used to enable/disable the Q-in-Q status.')NEWLINEqinqTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2), )NEWLINEif mibBuilder.loadTexts: qinqTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqTable.setDescription('A table that contains Q-in-Q VLAN mode information about each port.')NEWLINEqinqEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qinqIfIndex"))NEWLINEif mibBuilder.loadTexts: qinqEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqEntry.setDescription('A list of Q-in-Q VLAN mode information for each port.')NEWLINEqinqIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qinqIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqIfIndex.setDescription('The index of the port. ')NEWLINEqinqRoleState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("nni", 1), ("uni", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqRoleState.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqRoleState.setDescription('Sets the QinQ Role as NNI or UNI.')NEWLINEqinqOuterTPID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 3), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqOuterTPID.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqOuterTPID.setDescription('Sets the QinQ Outer TPID value.')NEWLINEqinqTrustCVIDState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqTrustCVIDState.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqTrustCVIDState.setDescription('Sets the QinQ Trust CVID state as enabled or disabled.')NEWLINEqinqVLANTranslationState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqVLANTranslationState.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVLANTranslationState.setDescription('Sets the QinQ VLANTranslation state as enabled or disabled.')NEWLINEqinqVlanTranslationCVIDTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1), )NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDTable.setDescription("A table that contains VLAN translation information applied in enabling port's swQinQPortVlanTranslation, swQinQPortTrustCVID and QinQ.")NEWLINEqinqVlanTranslationCVIDEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qinqVlanTranslationCVID"))NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDEntry.setDescription("A list of VLAN translation information applied in enabling a port's swQinQPortVlanTranslation, swQinQPortTrustCVID and QinQ.")NEWLINEqinqVlanTranslationCVID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1, 1), Unsigned32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVID.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVID.setDescription('The customer VLAN identifier in a C-TAG.')NEWLINEqinqVlanTranslationSVID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1, 2), Unsigned32()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationSVID.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationSVID.setDescription('A VLAN identifier conveyed in an S-TAG.')NEWLINEqinqVlanTranslationSVIDOperation = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("add", 1), ("replace", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationSVIDOperation.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationSVIDOperation.setDescription("The 'add' action indicates to add a tag for the assigned SP-VLAN before the C-VLAN tag. If there is S-TAG in the packet, this rule will not take effect. The 'replace' action indicates to replace the C-VLAN in the tag by the SP-VLAN. If there is no C-TAG in the packet, this rule will not take effect.")NEWLINEqinqVlanTranslationCVIDRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEeoamSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1))NEWLINEeoamLinkMonitor = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2))NEWLINEeoamTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2), )NEWLINEif mibBuilder.loadTexts: eoamTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamTable.setDescription('A table that contains EOAM mode information about each port.')NEWLINEeoamEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "eoamIfIndex"))NEWLINEif mibBuilder.loadTexts: eoamEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamEntry.setDescription('A list of EOAM mode information for each port.')NEWLINEeoamIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: eoamIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamIfIndex.setDescription('The index of the port. ')NEWLINEeoamState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamState.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamState.setDescription('Sets the EOAM state enabled or disabled.')NEWLINEeoamMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("passive", 1), ("active", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamMode.setDescription('Sets the EOAM mode as active or passive.')NEWLINEeoamReceivedRemoteLoopback = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ignore", 1), ("process", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamReceivedRemoteLoopback.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamReceivedRemoteLoopback.setDescription('Sets the EOAM received or ignore remote loopback packets.')NEWLINEeoamRemoteLoopback = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("noLoopBack", 1), ("startLoopBack", 2), ("remoteLoopBack", 3), ("stopLoopBack", 4), ("localLoopBack", 5), ("unknownLoopBack", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamRemoteLoopback.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamRemoteLoopback.setDescription('Sets the EOAM remote loopback start or stop.')NEWLINEeoamDyingGaspEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamDyingGaspEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamDyingGaspEnable.setDescription('Sets the EOAM dying gasp state enabled or disabled.')NEWLINEeoamCriticalEventEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamCriticalEventEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamCriticalEventEnable.setDescription('Sets the EOAM critical event state enabled or disabled.')NEWLINEeoamLinkMonitorTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1), )NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorTable.setDescription('A table that contains EOAM link monitor information about each port.')NEWLINEeoamLinkMonitorEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "eoamLinkMonitorIfIndex"))NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorEntry.setDescription('A list of EOAM link monitor information for each port.')NEWLINEeoamLinkMonitorIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorIfIndex.setDescription('The index of the port. ')NEWLINEerrorSymbolNotifyState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorSymbolNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorSymbolNotifyState.setDescription('Sets the EOAM error symbol notify state enabled or disabled.')NEWLINEerrorSymbolThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 3), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorSymbolThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorSymbolThreshold.setDescription('Sets the EOAM error symbol threshold.')NEWLINEerrorSymbolWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 4), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorSymbolWindow.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorSymbolWindow.setDescription('Sets the EOAM error symbol window.')NEWLINEerrorFrameNotifyState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameNotifyState.setDescription('Sets the EOAM error frame notify state enabled or disabled.')NEWLINEerrorFrameThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 6), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameThreshold.setDescription('Sets the EOAM error frame threshold.')NEWLINEerrorFrameWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 7), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameWindow.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameWindow.setDescription('Sets the EOAM error symbol window.')NEWLINEerrorFrameSecondsNotifyState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameSecondsNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameSecondsNotifyState.setDescription('Sets the EOAM error symbol notify state enabled or disabled.')NEWLINEerrorFrameSecondsThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 9), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameSecondsThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameSecondsThreshold.setDescription('Sets the EOAM error symbol threshold.')NEWLINEerrorFrameSecondsWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 10), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameSecondsWindow.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameSecondsWindow.setDescription('Sets the EOAM error symbol window.')NEWLINEerrorFramePeriodNotifyState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFramePeriodNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFramePeriodNotifyState.setDescription('Sets the EOAM error symbol notify state enabled or disabled.')NEWLINEerrorFramePeriodThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 12), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFramePeriodThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFramePeriodThreshold.setDescription('Sets the EOAM error symbol threshold.')NEWLINEerrorFramePeriodWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 13), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFramePeriodWindow.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFramePeriodWindow.setDescription('Sets the EOAM error symbol window.')NEWLINEduldSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1))NEWLINEduldTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1), )NEWLINEif mibBuilder.loadTexts: duldTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldTable.setDescription('A table that contains DULD mode information about each port.')NEWLINEduldEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "duldIfIndex"))NEWLINEif mibBuilder.loadTexts: duldEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldEntry.setDescription('A list of DULD mode information for each port.')NEWLINEduldIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: duldIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldIfIndex.setDescription('The index of the port. ')NEWLINEduldState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: duldState.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldState.setDescription('Sets the DULD admin state enabled or disabled.')NEWLINEduldOperState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: duldOperState.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldOperState.setDescription('Gets the DULD Oper state enabled or disabled.')NEWLINEduldMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("shutdown", 1), ("normal", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: duldMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldMode.setDescription('Sets the DULD mode as shutdown or normal.')NEWLINEduldLinkStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("unknow", 1), ("bidirectional", 2), ("txFault", 3), ("rxFault", 4), ("linkDown", 5)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: duldLinkStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldLinkStatus.setDescription('Gets the DULD link status.')NEWLINEduldDiscoveryTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 6), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(5, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: duldDiscoveryTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldDiscoveryTime.setDescription('Sets the DULD discovery time.')NEWLINEduldRecoverTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 2), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(60, 1000000), )).clone(60)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: duldRecoverTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldRecoverTime.setDescription('Duld auto recover time.')NEWLINEdoSCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1), )NEWLINEif mibBuilder.loadTexts: doSCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlTable.setDescription('A table that holds the DoS prevention settings of the device.')NEWLINEdoSCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "doSCtrlType"))NEWLINEif mibBuilder.loadTexts: doSCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlEntry.setDescription('A list of DoS prevention settings of the device.')NEWLINEdoSCtrlType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("land-attack", 1), ("blat-attack", 2), ("smurf-attack", 3), ("tcp-null-scan", 4), ("tcp-xmascan", 5), ("tcp-synfin", 6), ("tcp-syn-srcport-less-1024", 7)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: doSCtrlType.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlType.setDescription('This object indicates the DoS prevention type.')NEWLINEdoSCtrlState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlState.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlState.setDescription('This object indicates the status of the DoS prevention type.')NEWLINEdoSCtrlActionType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("drop", 0), ("mirror", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlActionType.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlActionType.setDescription("This object indicates the action for the DoS prevention type. If this object is set to 'mirror' and DoSCtrlState is set to 'enable', the configuration will not take effect until a valid mirror port is specified. If mirror port is not valid the behavior will be the same as 'drop'")NEWLINEdoSCtrlMirrorPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorPort.setDescription("This object indicates the port to which the attack packet will be forwarded. A value of 0 means that the DoS prevention action type is either not set to 'mirror'. or the 'mirror' DoS action is not active. When DoSCtrlActionType is set to 'mirror' with DoSCtrlState set to 'enable', setting this value to a valid port number will activate the 'mirror' DoS action.")NEWLINEdoSCtrlMirrorReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorReplace1P.setDescription('This object indicates the packet to which the attack packet will be replaced 1p to mirror port. The Range of 1p is 0 ~ 7. If value set to -1, it means no chenged.')NEWLINEdoSCtrlMirrorRxRate = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1024000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorRxRate.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorRxRate.setDescription('This object indicates the packet to which the attack packet will be rate limited to mirror port. The Range of rx limit is 0 or 64~1024000. If rate set to 0, it means no limit.')NEWLINEdoSCtrlFrameCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 7), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: doSCtrlFrameCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlFrameCount.setDescription('This object indicates the frame counts of the DoS prevention type.')NEWLINEdoSCtrlClearFrameCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("normal", 0), ("clear", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlClearFrameCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlClearFrameCount.setDescription('This object will clear frame count when set to clear.')NEWLINEdosCtrlTrapLogState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dosCtrlTrapLogState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dosCtrlTrapLogState.setDescription('Enable/Disable Dos Trap Log function. Default is disabled.')NEWLINEswTimeRangeSettingTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1), )NEWLINEif mibBuilder.loadTexts: swTimeRangeSettingTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeSettingTable.setDescription('A table to configure time Range in the system.')NEWLINEswTimeRangeSettingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "swTimeRangeIndex"))NEWLINEif mibBuilder.loadTexts: swTimeRangeSettingEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeSettingEntry.setDescription('A schedule entry to configure time Range in the system.')NEWLINEswTimeRangeIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 52))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: swTimeRangeIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeIndex.setDescription('The Time Range identifier. The maximum number of Schedule entry is the number of ports supported PoE function. The value must be between 1 and 52.')NEWLINEswTimeRangeName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeName.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeName.setDescription("The Schedule name associated with the Schedule entry (e.g., `abc, bbb').")NEWLINEswTimeRangeDate = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeDate.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeDate.setDescription('Enable/Disable date range checking while executing time base PoE.')NEWLINEswTimeRangeStartYear = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037))).clone(namedValues=NamedValues(("y2009", 2009), ("y2010", 2010), ("y2011", 2011), ("y2012", 2012), ("y2013", 2013), ("y2014", 2014), ("y2015", 2015), ("y2016", 2016), ("y2017", 2017), ("y2018", 2018), ("y2019", 2019), ("y2020", 2020), ("y2021", 2021), ("y2022", 2022), ("y2023", 2023), ("y2024", 2024), ("y2025", 2025), ("y2026", 2026), ("y2027", 2027), ("y2028", 2028), ("y2029", 2029), ("y2030", 2030), ("y2031", 2031), ("y2032", 2032), ("y2033", 2033), ("y2034", 2034), ("y2035", 2035), ("y2036", 2036), ("y2037", 2037)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartYear.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartYear.setDescription('Start year of the Schedule entry.')NEWLINEswTimeRangeStartMonth = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=NamedValues(("january", 1), ("february", 2), ("march", 3), ("april", 4), ("may", 5), ("june", 6), ("july", 7), ("august", 8), ("september", 9), ("october", 10), ("november", 11), ("december", 12)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartMonth.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartMonth.setDescription('Start month of the Schedule entry.')NEWLINEswTimeRangeStartDay = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartDay.setDescription('Start day of the Schedule entry. The value must be from 1 to 31.')NEWLINEswTimeRangeStartHour = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 23))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartHour.setDescription('Start hour of the Schedule entry. The value must be from 0 to 23.')NEWLINEswTimeRangeStartMinute = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 59))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartMinute.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartMinute.setDescription('Start minute of the Schedule entry. The value must be from 0 to 59.')NEWLINEswTimeRangeEndYear = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037))).clone(namedValues=NamedValues(("y2009", 2009), ("y2010", 2010), ("y2011", 2011), ("y2012", 2012), ("y2013", 2013), ("y2014", 2014), ("y2015", 2015), ("y2016", 2016), ("y2017", 2017), ("y2018", 2018), ("y2019", 2019), ("y2020", 2020), ("y2021", 2021), ("y2022", 2022), ("y2023", 2023), ("y2024", 2024), ("y2025", 2025), ("y2026", 2026), ("y2027", 2027), ("y2028", 2028), ("y2029", 2029), ("y2030", 2030), ("y2031", 2031), ("y2032", 2032), ("y2033", 2033), ("y2034", 2034), ("y2035", 2035), ("y2036", 2036), ("y2037", 2037)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndYear.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndYear.setDescription('End year of the Schedule entry.')NEWLINEswTimeRangeEndMonth = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=NamedValues(("january", 1), ("february", 2), ("march", 3), ("april", 4), ("may", 5), ("june", 6), ("july", 7), ("august", 8), ("september", 9), ("october", 10), ("november", 11), ("december", 12)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndMonth.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndMonth.setDescription('End month of the Schedule entry.')NEWLINEswTimeRangeEndDay = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndDay.setDescription('End day of the Schedule entry. The value must be from 1 to 31.')NEWLINEswTimeRangeEndHour = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 23))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndHour.setDescription('End hour of the Schedule entry. The value must be from 0 to 23.')NEWLINEswTimeRangeEndMinute = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 59))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndMinute.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndMinute.setDescription('End minute of the Schedule entry. The value must be from 0 to 59.')NEWLINEswTimeRangeMonday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeMonday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeMonday.setDescription('Enable/Disble scheduling Monday.')NEWLINEswTimeRangeTuesday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeTuesday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeTuesday.setDescription('Enable/Disble scheduling Tuesday.')NEWLINEswTimeRangeWednesday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeWednesday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeWednesday.setDescription('Enable/Disble scheduling Wednesday.')NEWLINEswTimeRangeThursday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeThursday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeThursday.setDescription('Enable/Disble scheduling Thursday.')NEWLINEswTimeRangeFriday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeFriday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeFriday.setDescription('Enable/Disble scheduling Friday.')NEWLINEswTimeRangeSaturday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeSaturday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeSaturday.setDescription('Enable/Disble scheduling Saturday.')NEWLINEswTimeRangeSunday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeSunday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeSunday.setDescription('Enable/Disble scheduling Sunday.')NEWLINEswTimeRangeRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 21), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: swTimeRangeRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeRowStatus.setDescription('The status of an entry in the Time Range Information Table. Only a subset of the rowstatus variables (active, notinservice, createAndWait, destroy) are available.')NEWLINEdlinklldpState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpState.setDescription('This object is used for enabling or disabling LLDP in the system.')NEWLINEdlinklldpMsgHoldMultiplier = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 10))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpMsgHoldMultiplier.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpMsgHoldMultiplier.setDescription('The time-to-live value expressed as a multiple of the lldpMessageTxInterval object.The actual time-to-live value used in LLDP frames, transmitted on behalf of this LLDP agent, can be expressed by the following formula: TTL = min(65535, (lldpMessageTxInterval * lldpMessageTxHoldMultiplier))')NEWLINEdlinklldpMsgTxInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(5, 32768))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpMsgTxInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpMsgTxInterval.setDescription('This object is used for LLDP packet update frequency. The timer in units of seconds.')NEWLINEdlinklldpReinitDelay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpReinitDelay.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpReinitDelay.setDescription('This object is used for LLDP Reinitialization Delay. The timer in units of seconds.')NEWLINEdlinklldpTxDelay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8192))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpTxDelay.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpTxDelay.setDescription('The lldpTxDelay indicates the delay (in units of seconds) between successive LLDP frame transmissions initiated by value/status changes in the LLDP local systems MIB. The recommended value for the lldpTxDelay is set by the following formula: 1 <= lldpTxDelay <= (0.25 * lldpMessageTxInterval).')NEWLINEdlinklldpConfigManAddrPortsTxEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpConfigManAddrPortsTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: dlinklldpConfigManAddrPortsTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpConfigManAddrPortsTxEnable.setDescription('A set of ports that are identified by a PortList, in which each port is represented as a bit. The corresponding local system management address instance will be transmitted on the member ports of the lldpManAddrPortsTxEnable. The default value for lldpConfigManAddrPortsTxEnable object is empty binary string, which means no ports are specified for advertising indicated management address instance.')NEWLINEclass LldpPortNumber(TextualConvention, Integer32):NEWLINE description = "Each port contained in the chassis (that is known to the LLDP agent) is uniquely identified by a port number. A port number has no mandatory relationship to an InterfaceIndex object (of the interfaces MIB, IETF RFC 2863). If the LLDP agent is a IEEE 802.1D, IEEE 802.1Q bridge, the LldpPortNumber will have the same value as the dot1dBasePort object (defined in IETF RFC 1493) associated corresponding bridge port. If the system hosting LLDP agent is not an IEEE 802.1D or an IEEE 802.1Q bridge, the LldpPortNumber will have the same value as the corresponding interface's InterfaceIndex object. Port numbers should be in the range of 1 and 4096 since a particular port is also represented by the corresponding port number bit in LldpPortList."NEWLINE status = 'current'NEWLINE displayHint = 'd'NEWLINE subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 4096)NEWLINENEWLINElldpPortConfigTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11), )NEWLINEif mibBuilder.loadTexts: lldpPortConfigTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigTable.setDescription('The table that controls LLDP frame transmission on individual ports.')NEWLINElldpPortConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpPortConfigPortNum"))NEWLINEif mibBuilder.loadTexts: lldpPortConfigEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigEntry.setDescription('LLDP configuration information for a particular port. This configuration parameter controls the transmission and the reception of LLDP frames on those ports whose rows are created in this table.')NEWLINElldpPortConfigPortNum = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1, 1), LldpPortNumber())NEWLINEif mibBuilder.loadTexts: lldpPortConfigPortNum.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigPortNum.setDescription('The index value used to identify the port component (contained in the local chassis with the LLDP agent) associated with this entry. The value of this object is used as a port index to the lldpPortConfigTable.')NEWLINElldpPortConfigAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("txOnly", 1), ("rxOnly", 2), ("txAndRx", 3), ("disabled", 4))).clone('txAndRx')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpPortConfigAdminStatus.setReference('IEEE 802.1AB-2005 10.5.1')NEWLINEif mibBuilder.loadTexts: lldpPortConfigAdminStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigAdminStatus.setDescription("The administratively desired status of the local LLDP agent. If the associated lldpPortConfigAdminStatus object has a value of 'txOnly(1)', then LLDP agent will transmit LLDP frames on this port and it will not store any information about the remote systems connected. If the associated lldpPortConfigAdminStatus object has a value of 'rxOnly(2)', then the LLDP agent will receive, but it will not transmit LLDP frames on this port. If the associated lldpPortConfigAdminStatus object has a value of 'txAndRx(3)', then the LLDP agent will transmit and receive LLDP frames on this port. If the associated lldpPortConfigAdminStatus object has a value of 'disabled(4)', then LLDP agent will not transmit or receive LLDP frames on this port. If there is remote systems information which is received on this port and stored in other tables, before the port's lldpPortConfigAdminStatus becomes disabled, then the information will naturally age out.")NEWLINElldpPortConfigNotificationEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1, 3), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpPortConfigNotificationEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigNotificationEnable.setDescription('The lldpPortConfigNotificationEnable controls, on a per port basis, whether or not notifications from the agent are enabled. The value true(1) means that notifications are enabled; the value false(2) means that they are not.')NEWLINElldpPortConfigTLVsTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1, 4), Bits().clone(namedValues=NamedValues(("portDesc", 0), ("sysName", 1), ("sysDesc", 2), ("sysCap", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpPortConfigTLVsTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpPortConfigTLVsTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigTLVsTxEnable.setDescription("The lldpPortConfigTLVsTxEnable, defined as a bitmap, includes the basic set of LLDP TLVs whose transmission is allowed on the local LLDP agent by the network management. Each bit in the bitmap corresponds to a TLV type associated with a specific optional TLV. It should be noted that the organizationally-specific TLVs are excluded from the lldpTLVsTxEnable bitmap. LLDP Organization Specific Information Extension MIBs should have similar configuration object to control transmission of their organizationally defined TLVs. The bit 'portDesc(0)' indicates that LLDP agent should transmit 'Port Description TLV'. The bit 'sysName(1)' indicates that LLDP agent should transmit 'System Name TLV'. The bit 'sysDesc(2)' indicates that LLDP agent should transmit 'System Description TLV'. The bit 'sysCap(3)' indicates that LLDP agent should transmit 'System Capabilities TLV'. There is no bit reserved for the management address TLV type since transmission of management address TLVs are controlled by another object, lldpConfigManAddrTable. The default value for lldpPortConfigTLVsTxEnable object is empty set, which means no enumerated values are set. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.")NEWLINElldpXdot3Objects = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12))NEWLINElldpXdot3Config = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 1))NEWLINElldpXdot3LocalData = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2))NEWLINElldpXdot3RemoteData = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3))NEWLINEclass LldpPowerPortClass(TextualConvention, Integer32):NEWLINE description = 'This TC describes the Power over Ethernet (PoE) port class.'NEWLINE status = 'current'NEWLINE subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))NEWLINE namedValues = NamedValues(("pClassPSE", 1), ("pClassPD", 2))NEWLINENEWLINEclass LldpLinkAggStatusMap(TextualConvention, Bits):NEWLINE description = "This TC describes the link aggregation status. The bit 'aggCapable(0)' indicates the link is capable of being aggregated. The bit 'aggEnabled(1)' indicates the link is currently in aggregation."NEWLINE status = 'current'NEWLINE namedValues = NamedValues(("aggCapable", 0), ("aggEnabled", 1))NEWLINENEWLINElldpXdot3PortConfigTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 1, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTable.setDescription('A table that controls selection of LLDP TLVs to be transmitted on individual ports.')NEWLINElldpXdot3PortConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 1, 1, 1), )NEWLINElldpPortConfigEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot3PortConfigEntry"))NEWLINElldpXdot3PortConfigEntry.setIndexNames(*lldpPortConfigEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigEntry.setDescription('LLDP configuration information that controls the transmission of IEEE 802.3 organizationally defined TLVs on LLDP transmission capable ports. This configuration object augments the lldpPortConfigEntry of the LLDP-MIB, therefore it is only present along with the port configuration defined by the associated lldpPortConfigEntry entry. Each active lldpXdot3PortConfigEntry must be from non-volatile storage (along with the corresponding lldpPortConfigEntry) after a re-initialization of the management system.')NEWLINElldpXdot3PortConfigTLVsTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 1, 1, 1, 1), Bits().clone(namedValues=NamedValues(("macPhyConfigStatus", 0), ("powerViaMDI", 1), ("linkAggregation", 2), ("maxFrameSize", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTLVsTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTLVsTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTLVsTxEnable.setDescription("The lldpXdot3PortConfigTLVsTxEnable, defined as a bitmap, includes the IEEE 802.3 organizationally defined set of LLDP TLVs whose transmission is allowed on the local LLDP agent by the network management. Each bit in the bitmap corresponds to an IEEE 802.3 subtype associated with a specific IEEE 802.3 optional TLV. The bit 0 is not used since there is no corresponding subtype. The bit 'macPhyConfigStatus(0)' indicates that LLDP agent should transmit 'MAC/PHY configuration/status TLV'. The bit 'powerViaMDI(1)' indicates that LLDP agent should transmit 'Power via MDI TLV'. The bit 'linkAggregation(2)' indicates that LLDP agent should transmit 'Link Aggregation TLV'. The bit 'maxFrameSize(3)' indicates that LLDP agent should transmit 'Maximum-frame-size TLV'. The default value for lldpXdot3PortConfigTLVsTxEnable object is an empty set, which means no enumerated values are set. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.")NEWLINElldpXdot3LocPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortTable.setDescription('This table contains one row per port of Ethernet port information (as a part of the LLDP 802.3 organizational extension) on the local system known to this agent.')NEWLINElldpXdot3LocPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3LocPortAutoNegSupported"))NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortEntry.setDescription('Information about a particular port component.')NEWLINElldpXdot3LocPortAutoNegSupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1, 1), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegSupported.setReference('IEEE 802.1AB-2005 G.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegSupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegSupported.setDescription('The truth value used to indicate whether the given port (associated with the local system) supports Auto-negotiation.')NEWLINElldpXdot3LocPortAutoNegEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegEnabled.setReference('IEEE 802.1AB-2005 G.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegEnabled.setDescription('The truth value used to indicate whether port Auto-negotiation is enabled on the given port associated with the local system.')NEWLINElldpXdot3LocPortAutoNegAdvertisedCap = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(2, 2)).setFixedLength(2)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegAdvertisedCap.setReference('IEEE 802.1AB-2005 G.2.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegAdvertisedCap.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegAdvertisedCap.setDescription('This object contains the value (bitmap) of the ifMauAutoNegCapAdvertisedBits object (defined in IETF RFC 3636) which is associated with the given port on the local system.')NEWLINElldpXdot3LocPortOperMauType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortOperMauType.setReference('IEEE 802.1AB-2005 G.2.3')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortOperMauType.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortOperMauType.setDescription('An integer value that indicates the operational MAU type of the given port on the local system. This object contains the integer value derived from the list position of the corresponding dot3MauType as listed in IETF RFC 3636 (or subsequent revisions) and is equal to the last number in the respective dot3MauType OID. For example, if the ifMauType object is dot3MauType1000BaseTHD which corresponds to {dot3MauType 29}, the numerical value of this field will be 29. For MAU types not listed in RFC 3636 (or subsequent revisions), the value of this field shall be set to zero.')NEWLINElldpXdot3LocPowerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerTable.setDescription('This table contains one row per port of power ethernet information (as a part of the LLDP 802.3 organizational extension) on the local system known to this agent.')NEWLINElldpXdot3LocPowerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3LocPowerPortClass"))NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerEntry.setDescription('Information about a particular port component.')NEWLINElldpXdot3LocPowerPortClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 1), LldpPowerPortClass()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPortClass.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPortClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPortClass.setDescription('The value that identifies the port Class of the given port associated with the local system.')NEWLINElldpXdot3LocPowerMDISupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDISupported.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDISupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDISupported.setDescription('The truth value used to indicate whether the MDI power is supported on the given port associated with the local system.')NEWLINElldpXdot3LocPowerMDIEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 3), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDIEnabled.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDIEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDIEnabled.setDescription('The truth value used to identify whether MDI power is enabled on the given port associated with the local system.')NEWLINElldpXdot3LocPowerPairControlable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 4), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairControlable.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairControlable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairControlable.setDescription('The truth value is derived from the value of pethPsePortPowerPairsControlAbility object (defined in IETF RFC 3621) and is used to indicate whether the pair selection can be controlled on the given port associated with the local system.')NEWLINElldpXdot3LocPowerPairs = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(1, 1), ValueRangeConstraint(2, 2), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairs.setReference('IEEE 802.1AB-2005 G.3.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairs.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairs.setDescription('This object contains the value of the pethPsePortPowerPairs object (defined in IETF RFC 3621) which is associated with the given port on the local system.')NEWLINElldpXdot3LocPowerClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(1, 1), ValueRangeConstraint(2, 2), ValueRangeConstraint(3, 3), ValueRangeConstraint(4, 4), ValueRangeConstraint(5, 5), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerClass.setReference('IEEE 802.1AB-2005 G.3.3')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerClass.setDescription('This object contains the value of the pethPsePortPowerClassifications object (defined in IETF RFC 3621) which is associated with the given port on the local system.')NEWLINElldpXdot3LocLinkAggTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggTable.setDescription('This table contains one row per port of link aggregation information (as a part of the LLDP 802.3 organizational extension) on the local system known to this agent.')NEWLINElldpXdot3LocLinkAggEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3LocLinkAggStatus"))NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggEntry.setDescription('Link Aggregation information about a particular port component.')NEWLINElldpXdot3LocLinkAggStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 3, 1, 1), LldpLinkAggStatusMap()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggStatus.setReference('IEEE 802.1AB-2005 G.4.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggStatus.setDescription('The bitmap value contains the link aggregation capabilities and the current aggregation status of the link.')NEWLINElldpXdot3LocLinkAggPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 2147483647), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggPortId.setReference('IEEE 802.1AB-2005 G.4.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggPortId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggPortId.setDescription('This object contains the IEEE 802.3 aggregated port identifier, aAggPortID (IEEE 802.3-2002, 30.7.2.1.1), derived from the ifNumber of the ifIndex for the port component in link aggregation. If the port is not in link aggregation state and/or it does not support link aggregation, this value should be set to zero.')NEWLINElldpXdot3LocMaxFrameSizeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSizeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSizeTable.setDescription('This table contains one row per port of maximum frame size information (as a part of the LLDP 802.3 organizational extension) on the local system known to this agent.')NEWLINElldpXdot3LocMaxFrameSizeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3LocMaxFrameSize"))NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSizeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSizeEntry.setDescription('Maximum Frame Size information about a particular port component.')NEWLINElldpXdot3LocMaxFrameSize = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSize.setReference('IEEE 802.1AB-2005 G.5.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSize.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSize.setDescription('An integer value indicating the maximum supported frame size in octets on the given port of the local system.')NEWLINElldpXdot3RemPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortTable.setDescription('This table contains Ethernet port information (as a part of the LLDP 802.3 organizational extension) of the remote system.')NEWLINElldpXdot3RemPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3RemPortAutoNegSupported"))NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortEntry.setDescription('Information about a particular physical network connection.')NEWLINElldpXdot3RemPortAutoNegSupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1, 1), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegSupported.setReference('IEEE 802.1AB-2005 G.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegSupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegSupported.setDescription('The truth value used to indicate whether the given port (associated with remote system) supports Auto-negotiation.')NEWLINElldpXdot3RemPortAutoNegEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegEnabled.setReference('IEEE 802.1AB-2005 G.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegEnabled.setDescription('The truth value used to indicate whether port Auto-negotiation is enabled on the given port associated with the remote system.')NEWLINElldpXdot3RemPortAutoNegAdvertisedCap = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(2, 2)).setFixedLength(2)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegAdvertisedCap.setReference('IEEE 802.1AB-2005 G.2.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegAdvertisedCap.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegAdvertisedCap.setDescription('This object contains the value (bitmap) of the ifMauAutoNegCapAdvertisedBits object (defined in IETF RFC 3636) which is associated with the given port on the remote system.')NEWLINElldpXdot3RemPortOperMauType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortOperMauType.setReference('IEEE 802.1AB-2005 G.2.3')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortOperMauType.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortOperMauType.setDescription('An integer value that indicates the operational MAU type of the sending device. This object contains the integer value derived from the list position of the corresponding dot3MauType as listed in in IETF RFC 3636 (or subsequent revisions) and is equal to the last number in the respective dot3MauType OID. For example, if the ifMauType object is dot3MauType1000BaseTHD which corresponds to {dot3MauType 29}, the numerical value of this field will be 29. For MAU types not listed in RFC 3636 (or subsequent revisions), the value of this field shall be set to zero.')NEWLINElldpXdot3RemPowerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerTable.setDescription('This table contains Ethernet power information (as a part of the LLDP 802.3 organizational extension) of the remote system.')NEWLINElldpXdot3RemPowerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3RemPowerPortClass"))NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerEntry.setDescription('Information about a particular physical network connection.')NEWLINElldpXdot3RemPowerPortClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 1), LldpPowerPortClass()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPortClass.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPortClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPortClass.setDescription('The value that identifies the port Class of the given port associated with the remote system.')NEWLINElldpXdot3RemPowerMDISupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDISupported.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDISupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDISupported.setDescription('The truth value used to indicate whether the MDI power is supported on the given port associated with the remote system.')NEWLINElldpXdot3RemPowerMDIEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 3), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDIEnabled.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDIEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDIEnabled.setDescription('The truth value used to identify whether MDI power is enabled on the given port associated with the remote system.')NEWLINElldpXdot3RemPowerPairControlable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 4), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairControlable.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairControlable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairControlable.setDescription('The truth value is derived from the value of pethPsePortPowerPairsControlAbility object (defined in IETF RFC 3621) and is used to indicate whether the pair selection can be controlled on the given port associated with the remote system.')NEWLINElldpXdot3RemPowerPairs = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(1, 1), ValueRangeConstraint(2, 2), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairs.setReference('IEEE 802.1AB-2005 G.3.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairs.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairs.setDescription('This object contains the value of the pethPsePortPowerPairs object (defined in IETF RFC 3621) which is associated with the given port on the remote system.')NEWLINElldpXdot3RemPowerClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(1, 1), ValueRangeConstraint(2, 2), ValueRangeConstraint(3, 3), ValueRangeConstraint(4, 4), ValueRangeConstraint(5, 5), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerClass.setReference('IEEE 802.1AB-2005 G.3.3')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerClass.setDescription('This object contains the value of the pethPsePortPowerClassifications object (defined in IETF RFC 3621) which is associated with the given port on the remote system.')NEWLINElldpXdot3RemLinkAggTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggTable.setDescription('This table contains port link aggregation information (as a part of the LLDP 802.3 organizational extension) of the remote system.')NEWLINElldpXdot3RemLinkAggEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3RemLinkAggStatus"))NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggEntry.setDescription("Link Aggregation information about remote system's port component.")NEWLINElldpXdot3RemLinkAggStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 3, 1, 1), LldpLinkAggStatusMap()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggStatus.setReference('IEEE 802.1AB-2005 G.4.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggStatus.setDescription('The bitmap value contains the link aggregation capabilities and the current aggregation status of the link.')NEWLINElldpXdot3RemLinkAggPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 2147483647), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggPortId.setReference('IEEE 802.1AB-2005 G.4.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggPortId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggPortId.setDescription('This object contains the IEEE 802.3 aggregated port identifier, aAggPortID (IEEE 802.3-2002, 30.7.2.1.1), derived from the ifNumber of the ifIndex for the port component associated with the remote system. If the remote port is not in link aggregation state and/or it does not support link aggregation, this value should be zero.')NEWLINElldpXdot3RemMaxFrameSizeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSizeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSizeTable.setDescription('This table contains one row per port of maximum frame size information (as a part of the LLDP 802.3 organizational extension) of the remote system.')NEWLINElldpXdot3RemMaxFrameSizeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3RemMaxFrameSize"))NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSizeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSizeEntry.setDescription('Maximum Frame Size information about a particular port component.')NEWLINElldpXdot3RemMaxFrameSize = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSize.setReference('IEEE 802.1AB-2005 G.5.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSize.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSize.setDescription('An integer value indicating the maximum supported frame size in octets on the port component associated with the remote system.')NEWLINElldpXdot1Objects = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13))NEWLINElldpXdot1Config = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1))NEWLINElldpXdot1LocalData = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2))NEWLINElldpXdot1RemoteData = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3))NEWLINElldpXdot1ConfigPortVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTable.setDescription('A table that controls selection of LLDP Port VLAN-ID TLVs to be transmitted on individual ports.')NEWLINElldpXdot1ConfigPortVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 1, 1), )NEWLINElldpPortConfigEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot1ConfigPortVlanEntry"))NEWLINElldpXdot1ConfigPortVlanEntry.setIndexNames(*lldpPortConfigEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanEntry.setDescription('LLDP configuration information that controls the transmission of IEEE 802.1 organizationally defined Port VLAN-ID TLV on LLDP transmission capable ports. This configuration object augments the lldpPortConfigEntry of the LLDP-MIB, therefore it is only present along with the port configuration defined by the associated lldpPortConfigEntry entry. Each active lldpConfigEntry must be restored from non-volatile storage (along with the corresponding lldpPortConfigEntry) after a re-initialization of the management system.')NEWLINElldpXdot1ConfigPortVlanTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 1, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTxEnable.setDescription('The lldpXdot1ConfigPortVlanTxEnable, which is defined as a truth value and configured by the network management, determines whether the IEEE 802.1 organizationally defined port VLAN TLV transmission is allowed on a given LLDP transmission capable port. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.')NEWLINElldpXdot1LocVlanNameTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanNameTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanNameTable.setDescription('This table contains one or more rows per IEEE 802.1Q VLAN name information on the local system known to this agent.')NEWLINElldpXdot1LocVlanNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1LocVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanNameEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanNameEntry.setDescription('VLAN name Information about a particular port component. There may be multiple VLANs, identified by a particular lldpXdot1LocVlanId, configured on the given port.')NEWLINElldpXdot1LocVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 3, 1, 1), VlanId())NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanId.setReference('IEEE 802.1AB-2005 F.4.2')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanId.setDescription('The integer value used to identify the IEEE 802.1Q VLAN IDs with which the given port is compatible.')NEWLINElldpXdot1LocVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 3, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanName.setReference('IEEE 802.1AB-2005 F.4.4')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanName.setDescription('The string value used to identify VLAN name identified by the Vlan Id associated with the given port on the local system. This object should contain the value of the dot1QVLANStaticName object (defined in IETF RFC 2674) identified with the given lldpXdot1LocVlanId.')NEWLINElldpXdot1ConfigVlanNameTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTable.setDescription('The table that controls selection of LLDP VLAN name TLV instances to be transmitted on individual ports.')NEWLINElldpXdot1ConfigVlanNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 2, 1), )NEWLINElldpXdot1LocVlanNameEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot1ConfigVlanNameEntry"))NEWLINElldpXdot1ConfigVlanNameEntry.setIndexNames(*lldpXdot1LocVlanNameEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameEntry.setDescription('LLDP configuration information that specifies the set of ports (represented as a PortList) on which the Local System VLAN name instance will be transmitted. This configuration object augments the lldpLocVlanEntry, therefore it is only present along with the VLAN Name instance contained in the associated lldpLocVlanNameEntry entry. Each active lldpXdot1ConfigVlanNameEntry must be restored from non-volatile storage (along with the corresponding lldpXdot1LocVlanNameEntry) after a re-initialization of the management system.')NEWLINElldpXdot1ConfigVlanNameTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 2, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTxEnable.setDescription('The boolean value that indicates whether the corresponding Local System VLAN name instance will be transmitted on the port defined by the given lldpXdot1LocVlanNameEntry. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.')NEWLINElldpXdot1LocProtoVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanTable.setDescription('This table contains one or more rows per Port and Protocol VLAN information about the local system.')NEWLINElldpXdot1LocProtoVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1LocProtoVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEntry.setDescription('Port and protocol VLAN ID Information about a particular port component. There may be multiple port and protocol VLANs, identified by a particular lldpXdot1LocProtoVlanId, configured on the given port.')NEWLINElldpXdot1LocProtoVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), )))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanId.setReference('IEEE 802.1AB-2005 F.3.2')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanId.setDescription('The integer value used to identify the port and protocol VLANs associated with the given port associated with the local system. A value of zero shall be used if the system either does not know the protocol VLAN ID (PPVID) or does not support port and protocol VLAN operation.')NEWLINElldpXdot1LocProtoVlanSupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanSupported.setReference('IEEE 802.1AB-2005 F.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanSupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanSupported.setDescription('The truth value used to indicate whether the given port (associated with the local system) supports port and protocol VLANs.')NEWLINElldpXdot1LocProtoVlanEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2, 1, 3), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEnabled.setReference('IEEE 802.1AB-2005 F.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEnabled.setDescription('The truth value used to indicate whether the port and protocol VLANs are enabled on the given port associated with the local system.')NEWLINElldpXdot1ConfigProtoVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTable.setDescription('The table that controls selection of LLDP Port and Protocol VLAN ID TLV instances to be transmitted on individual ports.')NEWLINElldpXdot1ConfigProtoVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 3, 1), )NEWLINElldpXdot1LocProtoVlanEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot1ConfigProtoVlanEntry"))NEWLINElldpXdot1ConfigProtoVlanEntry.setIndexNames(*lldpXdot1LocProtoVlanEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanEntry.setDescription('LLDP configuration information that specifies the set of ports (represented as a PortList) on which the Local System Protocol VLAN instance will be transmitted. This configuration object augments the lldpXdot1LocVlanEntry, therefore it is only present along with the Port and Protocol VLAN ID instance contained in the associated lldpXdot1LocVlanEntry entry. Each active lldpXdot1ConfigProtoVlanEntry must be restored from non-volatile storage (along with the corresponding lldpXdot1LocProtoVlanEntry) after a re-initialization of the management system.')NEWLINElldpXdot1ConfigProtoVlanTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 3, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTxEnable.setDescription('The boolean value that indicates whether the corresponding Local System Port and Protocol VLAN instance will be transmitted on the port defined by the given lldpXdot1LocProtoVlanEntry. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.')NEWLINElldpXdot1LocProtocolTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolTable.setReference('IEEE 802.1AB-2005 F.5')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolTable.setDescription('This table contains one or more rows per protocol identity information on the local system known to this agent.')NEWLINElldpXdot1LocProtocolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1LocProtocolIndex"))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolEntry.setReference('IEEE 802.1AB-2005 F.5')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolEntry.setDescription('Information about particular protocols that are accessible through the given port component. There may be multiple protocols, identified by particular lldpXdot1ProtocolIndex, and lldpLocPortNum.')NEWLINElldpXdot1LocProtocolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolIndex.setDescription('This object represents an arbitrary local integer value used by this agent to identify a particular protocol identity.')NEWLINElldpXdot1LocProtocolId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 4, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolId.setReference('IEEE 802.1AB-2005 F.5.3')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolId.setDescription('The octet string value used to identify the protocols associated with the given port of the local system.')NEWLINElldpXdot1ConfigProtocolTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTable.setDescription('The table that controls selection of LLDP Protocol TLV instances to be transmitted on individual ports.')NEWLINElldpXdot1ConfigProtocolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 4, 1), )NEWLINElldpXdot1LocProtocolEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot1ConfigProtocolEntry"))NEWLINElldpXdot1ConfigProtocolEntry.setIndexNames(*lldpXdot1LocProtocolEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolEntry.setDescription('LLDP configuration information that specifies the set of ports (represented as a PortList) on which the Local System Protocol instance will be transmitted. This configuration object augments the lldpXdot1LocProtoEntry, therefore it is only present along with the Protocol instance contained in the associated lldpXdot1LocProtoEntry entry. Each active lldpXdot1ConfigProtocolEntry must be restored from non-volatile storage (along with the corresponding lldpXdot1LocProtocolEntry) after a re-initialization of the management system.')NEWLINElldpXdot1ConfigProtocolTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 4, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTxEnable.setDescription('The boolean value that indicates whether the corresponding Local System Protocol Identity instance will be transmitted on the port defined by the given lldpXdot1LocProtocolEntry. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.')NEWLINElldpXdot1LocTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot1LocTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocTable.setDescription('This table contains one row per port for IEEE 802.1 organizationally defined LLDP extension on the local system known to this agent.')NEWLINElldpXdot1LocEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1LocPortVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocEntry.setDescription('Information about IEEE 802.1 organizationally defined LLDP extension.')NEWLINElldpXdot1LocPortVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocPortVlanId.setReference('IEEE 802.1AB-2005 F.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocPortVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocPortVlanId.setDescription("The integer value used to identify the port's VLAN identifier associated with the local system. A value of zero shall be used if the system either does not know the PVID or does not support port-based VLAN operation.")NEWLINElldpXdot1RemTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot1RemTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemTable.setDescription('This table contains one or more rows per physical network connection known to this agent. The agent may wish to ensure that only one lldpXdot1RemEntry is present for each local port, or it may choose to maintain multiple lldpXdot1RemEntries for the same local port.')NEWLINElldpXdot1RemEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1RemPortVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemEntry.setDescription('Information about a particular port component.')NEWLINElldpXdot1RemPortVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemPortVlanId.setReference('IEEE 802.1AB-2005 F.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemPortVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemPortVlanId.setDescription("The integer value used to identify the port's VLAN identifier associated with the remote system. if the remote system either does not know the PVID or does not support port-based VLAN operation, the value of lldpXdot1RemPortVlanId should be zero.")NEWLINElldpXdot1RemProtoVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanTable.setDescription('This table contains one or more rows per Port and Protocol VLAN information about the remote system, received on the given port.')NEWLINElldpXdot1RemProtoVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1RemProtoVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEntry.setDescription('Port and protocol VLAN name Information about a particular port component. There may be multiple protocol VLANs, identified by a particular lldpXdot1RemProtoVlanId, configured on the remote system.')NEWLINElldpXdot1RemProtoVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), )))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanId.setReference('IEEE 802.1AB-2005 F.3.2')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanId.setDescription('The integer value used to identify the port and protocol VLANs associated with the given port associated with the remote system. If port and protocol VLANs are not supported on the given port associated with the remote system, or if the port is not enabled with any port and protocol VLAN, the value of lldpXdot1RemProtoVlanId should be zero.')NEWLINElldpXdot1RemProtoVlanSupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanSupported.setReference('IEEE 802.1AB-2005 F.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanSupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanSupported.setDescription('The truth value used to indicate whether the given port (associated with the remote system) is capable of supporting port and protocol VLANs.')NEWLINElldpXdot1RemProtoVlanEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2, 1, 3), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEnabled.setReference('IEEE 802.1AB-2005 F.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEnabled.setDescription('The truth value used to indicate whether the port and protocol VLANs are enabled on the given port associated with the remote system.')NEWLINElldpXdot1RemVlanNameTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameTable.setReference('IEEE 802.1AB-2005 F.4')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameTable.setDescription('This table contains one or more rows per IEEE 802.1Q VLAN name information about the remote system, received on the given port.')NEWLINElldpXdot1RemVlanNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1RemVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameEntry.setDescription('VLAN name Information about a particular port component. There may be multiple VLANs, identified by a particular lldpXdot1RemVlanId, received on the given port.')NEWLINElldpXdot1RemVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 3, 1, 1), VlanId())NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanId.setReference('IEEE 802.1AB-2005 F.4.2')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanId.setDescription('The integer value used to identify the IEEE 802.1Q VLAN IDs with which the given port of the remote system is compatible.')NEWLINElldpXdot1RemVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 3, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanName.setReference('IEEE 802.1AB-2005 F.4.4')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanName.setDescription('The string value used to identify VLAN name identified by the VLAN Id associated with the remote system.')NEWLINElldpXdot1RemProtocolTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolTable.setDescription('This table contains one or more rows per protocol information about the remote system, received on the given port.')NEWLINElldpXdot1RemProtocolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1RemProtocolIndex"))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolEntry.setDescription('Protocol information about a particular port component. There may be multiple protocols, identified by a particular lldpXdot1ProtocolIndex, received on the given port.')NEWLINElldpXdot1RemProtocolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolIndex.setDescription('This object represents an arbitrary local integer value used by this agent to identify a particular protocol identity.')NEWLINElldpXdot1RemProtocolId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 4, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolId.setReference('IEEE 802.1AB-2005 F.5.3')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolId.setDescription('The octet string value used to identify the protocols associated with the given port of remote system.')NEWLINEsecurityDhcpServerScreen = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7))NEWLINEdhcpServerScreenEnablePortlist = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 1), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpServerScreenEnablePortlist.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpServerScreenEnablePortlist.setDescription('To enable or disable DHCP Server Screening port list.')NEWLINEdhcpServerScreenEnableVlanlist = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 2), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpServerScreenEnableVlanlist.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpServerScreenEnableVlanlist.setDescription('To enable or disable DHCP Server Screening vlan list.')NEWLINEdhcpServerScreenLogSuppressDuration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 5, 30))).clone(namedValues=NamedValues(("one-min", 1), ("five-min", 5), ("thirty-min", 30)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpServerScreenLogSuppressDuration.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpServerScreenLogSuppressDuration.setDescription('DSS Trap Log Suppress Duration.')NEWLINEfilterDHCPServerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4), )NEWLINEif mibBuilder.loadTexts: filterDHCPServerTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerTable.setDescription('A table to control filter DHCP Server for the entire switch or for each interface in the switch.')NEWLINEfilterDHCPServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "filterDHCPServerIpAddr"), (0, "DES-1210-28MEbx", "filterDHCPServerClientMacAddr"))NEWLINEif mibBuilder.loadTexts: filterDHCPServerEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEfilterDHCPServerIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 1), IpAddress())NEWLINEif mibBuilder.loadTexts: filterDHCPServerIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerIpAddr.setDescription("Specifies either the Network or Host address from which the switch can be managed. An address 0.0.0.0 indicates 'Any Manager'.")NEWLINEfilterDHCPServerClientMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 2), MacAddress().clone(hexValue="000102030405"))NEWLINEif mibBuilder.loadTexts: filterDHCPServerClientMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerClientMacAddr.setDescription('Ethernet Mac Address.')NEWLINEfilterDHCPServerPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: filterDHCPServerPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerPortList.setDescription("Specifies the port numbers through which the authorized manager can access the switch. By default the authorized manager is allowed to access the switch through all the ports. If a set of ports are configured in the 'PortList', the manager can access the switch only through the configured ports.")NEWLINEfilterDHCPServerVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: filterDHCPServerVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerVlanList.setDescription("Specifies the port numbers through which the authorized manager can access the switch. By default the authorized manager is allowed to access the switch through all the ports. If a set of ports are configured in the 'PortList', the manager can access the switch only through the configured ports.")NEWLINEfilterDHCPServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: filterDHCPServerRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEsecurityTrafficSeg = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9))NEWLINEtrafficSegTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9, 1), )NEWLINEif mibBuilder.loadTexts: trafficSegTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficSegTable.setDescription('A Port-channel is created through ifMain table. After the creation of the port-channel, corresponding logical interface will be created in the ifMain table. This Port-channel table is indexed through Key values and allows to configure link selection policy and the Mac address for the port-channel. All other objects in this table displays the details of the port-channel')NEWLINEtrafficSegEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "trafficSegIfIndex"))NEWLINEif mibBuilder.loadTexts: trafficSegEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficSegEntry.setDescription('There is one entry in this table for each created port-channel port')NEWLINEtrafficSegIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trafficSegIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficSegIfIndex.setDescription("The ifIndex of the port-channel(Aggregator's interface index). ")NEWLINEtrafficSegMemberList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9, 1, 1, 2), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficSegMemberList.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficSegMemberList.setDescription('Port list of port channel.')NEWLINEsecurityAAC = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11))NEWLINEaacAuthenAdminState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAuthenAdminState.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAuthenAdminState.setDescription('This object indicates the Access Authentication is enable or disable.')NEWLINEaacAuthParamResponseTimeout = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAuthParamResponseTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAuthParamResponseTimeout.setDescription('Timeout in second for login authentication response.')NEWLINEaacAuthParamAttempt = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAuthParamAttempt.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAuthParamAttempt.setDescription('The amount for login authentication, if login failure exceed, connection or access would be locked.')NEWLINEaacAPAuthMethodGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4))NEWLINEaacAPLoginMethod = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1))NEWLINEaacAPEnableMethod = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2))NEWLINEaacAPConsoleLoginMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPConsoleLoginMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPConsoleLoginMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via local console')NEWLINEaacAPTelnetLoginMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPTelnetLoginMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPTelnetLoginMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via telnet.')NEWLINEaacAPSSHLoginMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPSSHLoginMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPSSHLoginMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via SSH.')NEWLINEaacAPHttpLoginMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPHttpLoginMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPHttpLoginMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via HTTP.')NEWLINEaacAPConsoleEnableMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPConsoleEnableMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPConsoleEnableMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via local console.')NEWLINEaacAPTelnetEnableMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPTelnetEnableMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPTelnetEnableMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via telnet.')NEWLINEaacAPSSHEnableMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPSSHEnableMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPSSHEnableMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via SSH.')NEWLINEaacAPHttpEnableMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPHttpEnableMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPHttpEnableMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via HTTP.')NEWLINEaacServerGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5), )NEWLINEif mibBuilder.loadTexts: aacServerGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupTable.setDescription('A table that contains informations about server group.')NEWLINEaacServerGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacServerGroupIndex"))NEWLINEif mibBuilder.loadTexts: aacServerGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupEntry.setDescription('A list of the group including servers.')NEWLINEaacServerGroupIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 9))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacServerGroupIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupIndex.setDescription('A value that uniquely identifies this SwAACServerGroupEntry .')NEWLINEaacServerGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerGroupName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupName.setDescription("A human-readable text string of the method group. The name is writable only if Group is new created, which the value of aacServerGroupRowStatus is 'notReady'.")NEWLINEaacServersInGroup = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1, 3), Bits().clone(namedValues=NamedValues(("id1", 0), ("id2", 1), ("id3", 2), ("id4", 3), ("id5", 4), ("id6", 5), ("id7", 6), ("id8", 7), ("id9", 8), ("id10", 9), ("id11", 10), ("id12", 11), ("id13", 12), ("id14", 13), ("id15", 14), ("id16", 15)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServersInGroup.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServersInGroup.setDescription('The list of servers in the group, each bit indicates a specified server ID. The server must be created before including it.')NEWLINEaacServerGroupRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacServerGroupRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEiPv4aacServerInfoTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6), )NEWLINEif mibBuilder.loadTexts: iPv4aacServerInfoTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerInfoTable.setDescription('A table that contains information about severs.')NEWLINEiPv4aacServerInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1), ).setIndexNames((0, "DES-1210-28MEbx", "iPv4aacServerIndex"))NEWLINEif mibBuilder.loadTexts: iPv4aacServerInfoEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerInfoEntry.setDescription('A list of the information of server .')NEWLINEiPv4aacServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: iPv4aacServerIndex.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerIndex.setDescription('A value that uniquely identifies this SwAACServerGroupEntry.')NEWLINEiPv4aacServerIPAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerIPAddr.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerIPAddr.setDescription('The IP address of Server')NEWLINEiPv4aacServerAuthProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthProtocol.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthProtocol.setDescription('The authentication protocol provided by the Server.')NEWLINEiPv4aacServerAuthPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthPort.setDescription('The TCP/IP port .')NEWLINEiPv4aacServerAuthKey = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 254))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthKey.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthKey.setDescription('The key used while authentication process.')NEWLINEiPv4aacServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerTimeout.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerTimeout.setDescription('Server response timeout .')NEWLINEiPv4aacServerRetryCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerRetryCount.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerRetryCount.setDescription('Client retry count . (-1: No retry mechanism)')NEWLINEiPv4aacServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 8), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: iPv4aacServerRowStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacServerInfoTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7), )NEWLINEif mibBuilder.loadTexts: aacServerInfoTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerInfoTable.setDescription('A table that contains information about severs.')NEWLINEaacServerInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacServerIndex"))NEWLINEif mibBuilder.loadTexts: aacServerInfoEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerInfoEntry.setDescription('A list of the information of server .')NEWLINEaacServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacServerIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerIndex.setDescription('A value that uniquely identifies this SwAACServerGroupEntry.')NEWLINEaacServerIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2)).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerIPType.setDescription('The IP address of the AAC server IP type referred to in this table entry. (IPv4=1, IPv6=2)')NEWLINEaacServerIPAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 3), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerIPAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerIPAddr.setDescription('The IP address of Server')NEWLINEaacServerInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 4), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacServerInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerInterfaceName.setDescription('Specifies the interface name when the aacServerIPAddr is linklocal address.')NEWLINEaacServerAuthProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerAuthProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerAuthProtocol.setDescription('The authentication protocol provided by the Server.')NEWLINEaacServerAuthPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerAuthPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerAuthPort.setDescription('The TCP/IP port .')NEWLINEaacServerAuthKey = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 254))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerAuthKey.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerAuthKey.setDescription('The key used while authentication process.')NEWLINEaacServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerTimeout.setDescription('Server response timeout .')NEWLINEaacServerRetryCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerRetryCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerRetryCount.setDescription('Client retry count . (-1: No retry mechanism)')NEWLINEaacServerAccountingPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerAccountingPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerAccountingPort.setDescription('The accounting port .')NEWLINEaacServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacServerRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacLoginMethodListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8), )NEWLINEif mibBuilder.loadTexts: aacLoginMethodListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListTable.setDescription('A table that contains information about Login authentication method lists.')NEWLINEaacLoginMethodListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacLoginMethodListIndex"))NEWLINEif mibBuilder.loadTexts: aacLoginMethodListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListEntry.setDescription('A list of the Authentication methods.')NEWLINEaacLoginMethodListIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacLoginMethodListIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListIndex.setDescription('A value that identifies this method list.')NEWLINEaacLoginMethodListName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethodListName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListName.setDescription('A human-readable text string of the method list.')NEWLINEaacLoginMethod1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethod1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethod1.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacLoginMethod2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethod2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethod2.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacLoginMethod3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethod3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethod3.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacLoginMethod4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethod4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethod4.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacLoginMethodListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 7), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacLoginMethodListRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacEnableMethodListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9), )NEWLINEif mibBuilder.loadTexts: aacEnableMethodListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListTable.setDescription('A table that contains information about Enable authentication method lists.')NEWLINEaacEnableMethodListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacEnableMethodListIndex"))NEWLINEif mibBuilder.loadTexts: aacEnableMethodListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListEntry.setDescription('A list of the Authentication methods.')NEWLINEaacEnableMethodListIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacEnableMethodListIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListIndex.setDescription('A value that identifies this method list.')NEWLINEaacEnableMethodListName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethodListName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListName.setDescription('A human-readable text string of the method list.')NEWLINEaacEnableMethod1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethod1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethod1.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacEnableMethod2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethod2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethod2.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacEnableMethod3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethod3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethod3.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacEnableMethod4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethod4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethod4.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacEnableMethodListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 7), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacEnableMethodListRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacLocalEnablePassword = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 10), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLocalEnablePassword.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLocalEnablePassword.setDescription('This object is used to set Local Enable Password.')NEWLINEaacAccountingMethodListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11), )NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListTable.setDescription('A table that contains information about Accounting authentication method lists.')NEWLINEaacAccountingMethodListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacAccountingMethodListIndex"))NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListEntry.setDescription('A list of the Authentication methods.')NEWLINEaacAccountingMethodListIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListIndex.setDescription('A value that identifies this method list.')NEWLINEaacAccountingMethodListName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListName.setDescription('A human-readable text string of the method list.')NEWLINEaacAccountingMethod1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethod1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethod1.setDescription('The type of Accounting method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacAccountingMethod2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethod2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethod2.setDescription('The type of Accounting method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacAccountingMethod3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethod3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethod3.setDescription('The type of Accounting method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacAccountingMethod4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethod4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethod4.setDescription('The type of Accounting method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacAccountingMethodListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 7), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacAccountingServiceIndex = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 12))NEWLINEaacAccountingServiceNetwork = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 12, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, -1))).clone(namedValues=NamedValues(("radius-only", 0), ("default-method-list", 1), ("method-list-name", 2), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceNetwork.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceNetwork.setDescription('This object indicates aac Accounting Service Network is radius_only, default_method_list, method_list_name and disable about Accounting Service Network.')NEWLINEaacAccountingServiceShell = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 12, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, -1))).clone(namedValues=NamedValues(("radius-only", 0), ("default-method-list", 1), ("method-list-name", 2), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceShell.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceShell.setDescription('This object indicates aac Accounting Service Shell is radius_only, default_method_list, method_list_name and disable about Accounting Service Network.')NEWLINEaacAccountingServiceSystem = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 12, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, -1))).clone(namedValues=NamedValues(("radius-only", 0), ("default-method-list", 1), ("method-list-name", 2), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceSystem.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceSystem.setDescription('This object indicates aac Accounting System Shell is radius_only, default_method_list, method_list_name and disable about Accounting Service Network.')NEWLINEaacAccountingServiceCommand = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13))NEWLINEaacAccountingServiceCommandAdministrator = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, -1))).clone(namedValues=NamedValues(("method1", 0), ("method2", 1), ("method3", 2), ("method4", 3), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandAdministrator.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandAdministrator.setDescription('This object indicates aac Accounting Command Admin is method1, method2, method3 , method4 and disable about Accounting Service Command')NEWLINEaacAccountingServiceCommandOperator = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, -1))).clone(namedValues=NamedValues(("method1", 0), ("method2", 1), ("method3", 2), ("method4", 3), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandOperator.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandOperator.setDescription('This object indicates aac Accounting Command Operato is method1, method2, method3 , method4 and disable about Accounting Service Command')NEWLINEaacAccountingServiceCommandPoweruser = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, -1))).clone(namedValues=NamedValues(("method1", 0), ("method2", 1), ("method3", 2), ("method4", 3), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandPoweruser.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandPoweruser.setDescription('This object indicates aac Accounting Command Power user is method1, method2, method3 , method4 and disable about Accounting Service Command')NEWLINEaacAccountingServiceCommandUser = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, -1))).clone(namedValues=NamedValues(("method1", 0), ("method2", 1), ("method3", 2), ("method4", 3), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandUser.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandUser.setDescription('This object indicates aac Accounting Command User is method1, method2, method3 , method4 and disable about Accounting Service Command')NEWLINEaacServerPasswordEncryption = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerPasswordEncryption.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerPasswordEncryption.setDescription('This object is used to configure server password encryption status.')NEWLINEmcastFilterPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49, 1), )NEWLINEif mibBuilder.loadTexts: mcastFilterPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mcastFilterPortTable.setDescription('A table to control multicast filtering modes.')NEWLINEmcastFilterPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mcastFilterPortIndex"))NEWLINEif mibBuilder.loadTexts: mcastFilterPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mcastFilterPortEntry.setDescription('An entry appears in this table for each interface in the mcastFiltertem. Index to the table is the interface index of the port.')NEWLINEmcastFilterPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28)))NEWLINEif mibBuilder.loadTexts: mcastFilterPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: mcastFilterPortIndex.setDescription('Interface index of the port for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEmcastFilterPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("forward", 1), ("filter", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mcastFilterPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: mcastFilterPortType.setDescription('Configures the multicast filtering modes as below : forward -Forwards all unregistered groups. filter -Filters all unregistered groups.')NEWLINEstaticARPTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2), )NEWLINEif mibBuilder.loadTexts: staticARPTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPTable.setDescription('A list of the Static MACs')NEWLINEstaticARPEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "staticARPIP"), (0, "DES-1210-28MEbx", "staticARPMac"))NEWLINEif mibBuilder.loadTexts: staticARPEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPEntry.setDescription('A Static MAC entry containing the mac and forwarding port.')NEWLINEstaticARPIP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2, 1, 2), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticARPIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPIP.setDescription('The VLAN ID of the static ARP IP.')NEWLINEstaticARPMac = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticARPMac.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPMac.setDescription('The MAC address associated of the static ARP entry.')NEWLINEstaticARPRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2, 1, 5), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticARPRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPRowStatus.setDescription('The status of an entry in the Static ARP Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available. The trunk member port can not set up static ARP.')NEWLINEsysGratuitousARPGlobalSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 1))NEWLINEsysGratuitousARPSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2))NEWLINEsysGratuitousARPIPIfStatusUp = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPIPIfStatusUp.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPIPIfStatusUp.setDescription('This object indicates Send On IP Interface Status Up is enabled or disabled.')NEWLINEsysGratuitousARPDuplicateIPDetected = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPDuplicateIPDetected.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPDuplicateIPDetected.setDescription('This object indicates Send On Duplicate IP Detected is enabled or disabled.')NEWLINEsysGratuitousARPLearning = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPLearning.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPLearning.setDescription('This object indicates Gratuitous ARP Learning is enabled or disabled.')NEWLINEsysGratuitousARPTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2, 1), )NEWLINEif mibBuilder.loadTexts: sysGratuitousARPTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPTable.setDescription('Set/Add Gratuitous ARP interface name and interval time.')NEWLINEsysGratuitousARPEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysGratuitousARPIFName"))NEWLINEif mibBuilder.loadTexts: sysGratuitousARPEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPEntry.setDescription('The entry of gratuitous ARP!')NEWLINEsysGratuitousARPIFName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2, 1, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 24))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPIFName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPIFName.setDescription('Interface name.')NEWLINEsysGratuitousARPInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPInterval.setDescription('Gratuitous ARP interval time for each interface.')NEWLINEagentCPUutilization = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 1))NEWLINEagentMEMutilization = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 2))NEWLINEagentCPUutilizationIn5sec = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 1, 1), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn5sec.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn5sec.setDescription('The time scale is set at 5 second intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentCPUutilizationIn1min = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 1, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn1min.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn1min.setDescription('The time scale is set at 1 minute intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentCPUutilizationIn5min = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 1, 3), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn5min.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn5min.setDescription('The time scale is set at 5 minute intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentMEMutilizationIn5sec = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 2, 1), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn5sec.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn5sec.setDescription('The time scale is set at 5 second intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentMEMutilizationIn1min = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 2, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn1min.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn1min.setDescription('The time scale is set at 1 minute intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentMEMutilizationIn5min = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 2, 3), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn5min.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn5min.setDescription('The time scale is set at 5 minute intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEl2PTState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: l2PTState.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTState.setDescription('This object indicates the global state of Layer 2 protocol tunneling.')NEWLINEl2PTPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2), )NEWLINEif mibBuilder.loadTexts: l2PTPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTPortTable.setDescription('A table that cont ains the cable situation for each port.')NEWLINEl2PTEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "l2PTPortIndex"))NEWLINEif mibBuilder.loadTexts: l2PTEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTEntry.setDescription('A list of cable situations for each port on the device.')NEWLINEl2PTPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28)))NEWLINEif mibBuilder.loadTexts: l2PTPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTPortIndex.setDescription('This object indicates the port number. For all machines give maximum port number.')NEWLINEl2PTPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("uni", 2), ("nni", 3))).clone('none')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: l2PTPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTPortType.setDescription("This object indicates the Layer 2 protocol tunneling port type. The 'none' value indicates that the port is normal. Layer 2 protocol tunneling is disabled on this port. The 'uni' value indicates that the port is connected to the customer site. A Layer 2 PDU received on a UNI port can be tunneled to a remote customer site across the provider network. The 'nni' value indicates that the port is connected to the provider network. A Tunneled Layer 2 PDU received on an NNI port will be restored to its original format.")NEWLINEl2PTProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2, 1, 3), Bits().clone(namedValues=NamedValues(("stp", 0), ("gvrp", 1), ("macCC", 2), ("macCD", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: l2PTProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTProtocol.setDescription("This object indicates the tunneled protocols on this port. This object can only be applied on a UNI port. If the 'stp' BIT is set, the STP BPDU will be tunneled. If the 'gvrp' BIT is set, the GVRP PDU will be tunneled. If the 'mac-01-00-0C-CC-CC-CC' BIT is set, the PDU with the destination MAC address 01-00-0C-CC-CC-CC will be tunneled . If the 'mac-01-00-0C-CC-CC-CD' BIT is set, then the PDU with the destination MAC address 01-00-0C-CC-CC-CD will be tunneled.")NEWLINEl2PTThresholdTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 3), )NEWLINEif mibBuilder.loadTexts: l2PTThresholdTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTThresholdTable.setDescription('This table contains the protocol tunneling threshold of a UNI port.')NEWLINEl2PTThresholdEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "l2PTPortIndex"), (0, "DES-1210-28MEbx", "l2PTProtocolIndex"))NEWLINEif mibBuilder.loadTexts: l2PTThresholdEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTThresholdEntry.setDescription('A list with the Layer2 Protocol tunneling threshold.')NEWLINEl2PTProtocolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("stp", 1), ("gvrp", 2), ("macCC", 3), ("macCD", 4))))NEWLINEif mibBuilder.loadTexts: l2PTProtocolIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTProtocolIndex.setDescription('This object indicates the tunneled protocol of the port.')NEWLINEl2PTDropThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: l2PTDropThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTDropThreshold.setDescription('This object indicates the drop threshold for a given protocol on a UNI port. If the arrival rate of a tunneled protocol has reached its threshold, the received PDUs of this protocol will be dropped. The value 0 indicates there is no threshold for the protocol.')NEWLINEipv4smtpState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpState.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4smtpState.setDescription('Enable or Disable SMTP function.')NEWLINEipv4smtpServerAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpServerAddr.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4smtpServerAddr.setDescription("SMTP Server's IP Address")NEWLINEipv4smtpServerPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 3), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpServerPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4smtpServerPort.setDescription("SMTP Server's port")NEWLINEipv4smtpSelfMailAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpSelfMailAddr.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4smtpSelfMailAddr.setDescription("The sender's (DUT) mail address .")NEWLINEipv4smtpRecvMailAddrTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5), )NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrTable.setDescription("Receivers' mail address table.")NEWLINEipv4smtpRecvMailAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4smtpRecvMailAddrIndex"))NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrEntry.setDescription("Receivers' mail address entry.")NEWLINEipv4smtpRecvMailAddrIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrIndex.setDescription("Receivers' mail address index (1~8).")NEWLINEipv4smtpRecvMailAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5, 1, 2), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddr.setDescription("Receivers' mail address.")NEWLINEipv4smtpRecvMailAddrStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5, 1, 3), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrStatus.setDescription("Rowstatus of the receiver's mail address.")NEWLINEsysSMTPServerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6))NEWLINEsmtpState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpState.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpState.setDescription('Enable or Disable SMTP function.')NEWLINEsmtpServerAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 2), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpServerAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpServerAddr.setDescription("SMTP Server's IP Address")NEWLINEsmtpServerAddrType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpServerAddrType.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpServerAddrType.setDescription("SMTP Server's Address type.")NEWLINEsmtpServerAddrInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpServerAddrInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpServerAddrInterfaceName.setDescription('Specifies the interface name when the smtpServerAddrInterfaceName is linklocal address.')NEWLINEsmtpServerPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 5), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpServerPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpServerPort.setDescription("SMTP Server's port")NEWLINEsmtpSelfMailAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 6), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpSelfMailAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpSelfMailAddr.setDescription("The sender's (DUT) mail address .")NEWLINEsmtpRecvMailAddrTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7), )NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrTable.setDescription("Receivers' mail address table.")NEWLINEsmtpRecvMailAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7, 1), ).setIndexNames((0, "DES-1210-28MEbx", "smtpRecvMailAddrIndex"))NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrEntry.setDescription("Receivers' mail address entry.")NEWLINEsmtpRecvMailAddrIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrIndex.setDescription("Receivers' mail address index (1~8).")NEWLINEsmtpRecvMailAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7, 1, 2), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddr.setDescription("Receivers' mail address.")NEWLINEsmtpRecvMailAddrStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7, 1, 3), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrStatus.setDescription("Rowstatus of the receiver's mail address.")NEWLINEigmpMulticastVlanStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanStatus.setDescription('Enable/Disable IGMP Multicast Vlan function.')NEWLINEigmpMulticastVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2), )NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanTable.setDescription('Information about the IGMP snooping multicast VLAN table.')NEWLINEigmpMulticastVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igmpMulticastVlanid"))NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanEntry.setDescription('The entry of igmpMulticastVlanTable.')NEWLINEigmpMulticastVlanid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanid.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanid.setDescription('This object indicates the VLAN ID of the IGMP snooping multicast VLAN entry.')NEWLINEigmpMulticastVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanName.setDescription('This object indicates the VLAN name of the IGMP snooping multicast VLAN entry.')NEWLINEigmpMulticastVlanSourcePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanSourcePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanSourcePort.setDescription('This object indicates the port list of the source ports of the IGMP snooping multicast VLAN. The source ports will be set as tag ports of the VLAN entry and the IGMP control messages received from the member ports will be forwarded to the source ports.')NEWLINEigmpMulticastVlanMemberPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanMemberPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanMemberPort.setDescription('This object indicates the port list of the member ports of the IGMP snooping multicast VLAN. The source ports will be set as untagged ports of the VLAN entry and the IGMP control messages received from the member ports will be forwarded to the source ports.')NEWLINEigmpMulticastVlanTagMemberPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 5), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanTagMemberPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanTagMemberPort.setDescription('This object indicates the port list of the tag member ports of the IGMP snooping multicast VLAN.')NEWLINEigmpMulticastVlanUntaggedSourcePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanUntaggedSourcePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanUntaggedSourcePort.setDescription('This object indicates the port list of the untag source ports of the IGMP snooping multicast VLAN.')NEWLINEigmpMulticastVlanState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanState.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanState.setDescription('This object can be used to enable or disable the IGMP snooping multicast VLAN.')NEWLINEigmpMulticastVlanReplaceSourceIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 8), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanReplaceSourceIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanReplaceSourceIp.setDescription('The replacement source IP of this multicast VLAN.')NEWLINEigmpMulticastVlanRemapPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanRemapPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanRemapPriority.setDescription('The remap priority of this multicast VLAN.')NEWLINEigmpMulticastVlanReplacePriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanReplacePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanReplacePriority.setDescription('The replacement priority of this multicast VLAN.')NEWLINEigmpMulticastVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 11), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEigmpMulticastVlanGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3), )NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupTable.setDescription('The table containing the IGMP snooping multicast VLAN group information')NEWLINEigmpMulticastVlanGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igmpMulticastVlanGroupVid"), (0, "DES-1210-28MEbx", "igmpMulticastVlanGroupFromIp"), (0, "DES-1210-28MEbx", "igmpMulticastVlanGroupToIp"))NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupEntry.setDescription('Information about the current IGMP snooping multicast VLAN group.')NEWLINEigmpMulticastVlanGroupVid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupVid.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupVid.setDescription('This object indicates the VID of the IGMP snooping multicast VLAN group.')NEWLINEigmpMulticastVlanGroupFromIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1, 2), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupFromIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupFromIp.setDescription('Specifies the multicast address list for this VLAN.')NEWLINEigmpMulticastVlanGroupToIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1, 3), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupToIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupToIp.setDescription('Specifies the multicast address list for this VLAN.')NEWLINEigmpMulticastVlanGroupStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupStatus.setDescription('This object indicates the status of this entry.')NEWLINEmulticastVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4), )NEWLINEif mibBuilder.loadTexts: multicastVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanTable.setDescription('Information about the IGMP/MLD snooping multicast VLAN table.')NEWLINEmulticastVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "multicastVlanid"))NEWLINEif mibBuilder.loadTexts: multicastVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanEntry.setDescription('The entry of multicastVlanTable.')NEWLINEmulticastVlanid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanid.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanid.setDescription('This object indicates the VLAN ID of the IGMP/MLD snooping multicast VLAN entry.')NEWLINEmulticastVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: multicastVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanName.setDescription('This object indicates the VLAN name of the IGMP/MLD snooping multicast VLAN entry.')NEWLINEmulticastVlanSourcePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanSourcePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanSourcePort.setDescription('This object indicates the port list of the source ports of the IGMP/MLD snooping multicast VLAN. The source ports will be set as tag ports of the VLAN entry and the IGMP control messages received from themember ports will be forwarded to the source ports.')NEWLINEmulticastVlanMemberPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanMemberPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanMemberPort.setDescription('This object indicates the port list of the member ports of the IGMP/MLD snooping multicast VLAN. The source ports will be set as untagged ports of the VLAN entry and the IGMP control messages received from themember ports will be forwarded to the source ports.')NEWLINEmulticastVlanTagMemberPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 5), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanTagMemberPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanTagMemberPort.setDescription('This object indicates the port list of the tag member ports of the IGMP/MLD snooping multicast VLAN.')NEWLINEmulticastVlanUntaggedSourcePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanUntaggedSourcePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanUntaggedSourcePort.setDescription('This object indicates the port list of the untag source ports of the IGMP/MLD snooping multicast VLAN.')NEWLINEmulticastVlanState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanState.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanState.setDescription('This object can be used to enable or disable the IGMP/MLD snooping multicast VLAN.')NEWLINEmulticastVlanIgmpReplaceSourceIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 8), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanIgmpReplaceSourceIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanIgmpReplaceSourceIp.setDescription('The replacement source IP of this IGMP snooping multicast VLAN.')NEWLINEmulticastVlanMldReplaceSourceIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 9), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanMldReplaceSourceIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanMldReplaceSourceIp.setDescription('The replacement source IP of this MLD snooping multicast VLAN.')NEWLINEmulticastVlanRemapPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanRemapPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanRemapPriority.setDescription('The remap priority of this multicast VLAN.')NEWLINEmulticastVlanReplacePriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanReplacePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanReplacePriority.setDescription('The replacement priority of this multicast VLAN.')NEWLINEmulticastVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 12), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: multicastVlanRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEmulticastVlanGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5), )NEWLINEif mibBuilder.loadTexts: multicastVlanGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupTable.setDescription('The table containing the IGMP/MLD snooping multicast VLAN group information')NEWLINEmulticastVlanGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "multicastVlanGroupVid"), (0, "DES-1210-28MEbx", "multicastVlanGroupIpType"), (0, "DES-1210-28MEbx", "multicastVlanGroupFromIp"), (0, "DES-1210-28MEbx", "multicastVlanGroupToIp"))NEWLINEif mibBuilder.loadTexts: multicastVlanGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupEntry.setDescription('The entry of multicastVlanGroupTable.')NEWLINEmulticastVlanGroupVid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupVid.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupVid.setDescription('This object indicates the VID of the IGMP/MLD snooping multicast VLAN group.')NEWLINEmulticastVlanGroupIpType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupIpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupIpType.setDescription('Type of specifies the multicast address list for this VLAN.')NEWLINEmulticastVlanGroupFromIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 3), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupFromIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupFromIp.setDescription('Specifies the multicast address list for this VLAN.')NEWLINEmulticastVlanGroupToIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 4), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupToIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupToIp.setDescription('Specifies the multicast address list for this VLAN.')NEWLINEmulticastVlanGroupStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 5), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupStatus.setDescription('This object indicates the status of this entry.')NEWLINEpppoeGlobalState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoeGlobalState.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoeGlobalState.setDescription('PPPoE global state')NEWLINEpppoePortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2), )NEWLINEif mibBuilder.loadTexts: pppoePortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortTable.setDescription('A table to control PPPoE features of the device.')NEWLINEpppoePortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "pppoePortIndex"))NEWLINEif mibBuilder.loadTexts: pppoePortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortEntry.setDescription('An entry appears in PPPoE table for each interface in the system.')NEWLINEpppoePortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 6))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: pppoePortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortIndex.setDescription('Interface index of the port for the configuration in this entry applies.')NEWLINEpppoePortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortState.setDescription('PPPoE per port state')NEWLINEpppoePortCircuitIDType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("ip", 0), ("mac", 1), ("udf", 2), ("vendor2", 3), ("vendor3", 4)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortCircuitIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortCircuitIDType.setDescription('PPPoE per port circuit ID type')NEWLINEpppoePortUDFString = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortUDFString.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortUDFString.setDescription('PPPoE per port UDF string')NEWLINEpppoePortCircuitIDVendor3String = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortCircuitIDVendor3String.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortCircuitIDVendor3String.setDescription('PPPoE per port circuit ID vendor3 string')NEWLINEpppoePortRemoteIDType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("default", 0), ("vendor2", 1), ("vendor3", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortRemoteIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortRemoteIDType.setDescription('PPPoE per port remote ID type')NEWLINEpppoePortRemoteIDVendor3String = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortRemoteIDVendor3String.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortRemoteIDVendor3String.setDescription('PPPoE per port remote ID vendor3 string')NEWLINErmonGlobalState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: rmonGlobalState.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonGlobalState.setDescription('This object is for enabling or disabling RMON function.')NEWLINErmonStatistics = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2))NEWLINErmonHistory = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3))NEWLINErmonAlarm = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4))NEWLINErmonEvent = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5))NEWLINErmonStatsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1), )NEWLINEif mibBuilder.loadTexts: rmonStatsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsTable.setDescription('A list of Ethernet statistics entries.')NEWLINErmonStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "rmonStatsIndex"))NEWLINEif mibBuilder.loadTexts: rmonStatsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsEntry.setDescription('A collection of statistics kept for a particular Ethernet interface. As an example, an instance of the etherStatsPkts object might be named etherStatsPkts.1')NEWLINErmonStatsIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: rmonStatsIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsIndex.setDescription('The value of this object uniquely identifies this etherStats entry.')NEWLINErmonStatsDataSource = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonStatsDataSource.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsDataSource.setDescription('This object identifies the source of the data that this etherStats entry is configured to analyze. This source can be any ethernet interface on this device. In order to identify a particular interface, this object shall identify the instance of the ifIndex object, defined in RFC 2233 [17], for the desired interface. For example, if an entry were to receive data from interface #1, this object would be set to ifIndex.1. The statistics in this group reflect all packets on the local network segment attached to the identified interface. An agent may or may not be able to tell if fundamental changes to the media of the interface have occurred and necessitate an invalidation of this entry. For example, a hot-pluggable ethernet card could be pulled out and replaced by a token-ring card. In such a case, if the agent has such knowledge of the change, it is recommended that it invalidate this entry. This object may not be modified if the associated etherStatsStatus object is equal to valid(1).')NEWLINErmonStatsOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1, 3), OwnerString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonStatsOwner.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsOwner.setDescription('The entity that configured this entry and is therefore using the resources assigned to it.')NEWLINErmonStatsStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1, 4), RmonStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonStatsStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsStatus.setDescription('The status of this etherStats entry.')NEWLINErmonHistoryTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1), )NEWLINEif mibBuilder.loadTexts: rmonHistoryTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryTable.setDescription('A list of history control entries.')NEWLINErmonHistoryEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "rmonHistoryIndex"))NEWLINEif mibBuilder.loadTexts: rmonHistoryEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryEntry.setDescription('A list of parameters that set up a periodic sampling of statistics. As an example, an instance of the historyControlInterval object might be named historyControlInterval.2')NEWLINErmonHistoryIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: rmonHistoryIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryIndex.setDescription('An index that uniquely identifies an entry in the historyControl table. Each such entry defines a set of samples at a particular interval for an interface on the device.')NEWLINErmonHistoryDataSource = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryDataSource.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryDataSource.setDescription('This object identifies the source of the data for which historical data was collected and placed in a media-specific table on behalf of this historyControlEntry. This source can be any interface on this device. In order to identify a particular interface, this object shall identify the instance of the ifIndex object, defined in RFC 2233 [17], for the desired interface. For example, if an entry were to receive data from interface #1, this object would be set to ifIndex.1. The statistics in this group reflect all packets on the local network segment attached to the identified interface. An agent may or may not be able to tell if fundamental changes to the media of the interface have occurred and necessitate an invalidation of this entry. For example, a hot-pluggable ethernet card could be pulled out and replaced by a token-ring card. In such a case, if the agent has such knowledge of the change, it is recommended that it invalidate this entry. This object may not be modified if the associated historyControlStatus object is equal to valid(1).')NEWLINErmonHistoryBucketsRequested = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(50)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryBucketsRequested.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryBucketsRequested.setDescription('The requested number of discrete time intervals over which data is to be saved in the part of the media-specific table associated with this historyControlEntry. When this object is created or modified, the probe should set historyControlBucketsGranted as closely to this object as is possible for the particular probe implementation and available resources.')NEWLINErmonHistoryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3600)).clone(1800)).setUnits('Seconds').setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryInterval.setDescription("The interval in seconds over which the data is sampled for each bucket in the part of the media-specific table associated with this historyControlEntry. This interval can be set to any number of seconds between 1 and 3600 (1 hour). Because the counters in a bucket may overflow at their maximum value with no indication, a prudent manager will take into account the possibility of overflow in any of the associated counters. It is important to consider the minimum time in which any counter could overflow on a particular media type and set the historyControlInterval object to a value less than this interval. This is typically most important for the 'octets' counter in any media-specific table. For example, on an Ethernet network, the etherHistoryOctets counter could overflow in about one hour at the Ethernet's maximum utilization. This object may not be modified if the associated historyControlStatus object is equal to valid(1).")NEWLINErmonHistoryOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 5), OwnerString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryOwner.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryOwner.setDescription('The entity that configured this entry and is therefore using the resources assigned to it.')NEWLINErmonHistoryStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 6), RmonStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryStatus.setDescription('The status of this historyControl entry. Each instance of the media-specific table associated with this historyControlEntry will be deleted by the agent if this historyControlEntry is not equal to valid(1).')NEWLINErmonAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1), )NEWLINEif mibBuilder.loadTexts: rmonAlarmTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmTable.setDescription('A list of alarm entries.')NEWLINErmonAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "rmonAlarmIndex"))NEWLINEif mibBuilder.loadTexts: rmonAlarmEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmEntry.setDescription('A list of parameters that set up a periodic checking for alarm conditions. For example, an instance of the alarmValue object might be named alarmValue.8')NEWLINErmonAlarmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: rmonAlarmIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmIndex.setDescription('An index that uniquely identifies an entry in the alarm table. Each such entry defines a diagnostic sample at a particular interval for an object on the device.')NEWLINErmonAlarmInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 2), Integer32()).setUnits('Seconds').setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmInterval.setDescription('The interval in seconds over which the data is sampled and compared with the rising and falling thresholds. When setting this variable, care should be taken in the case of deltaValue sampling - the interval should be set short enough that the sampled variable is very unlikely to increase or decrease by more than 2^31 - 1 during a single sampling interval. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmVariable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 3), ObjectIdentifier()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmVariable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmVariable.setDescription('The object identifier of the particular variable to be sampled. Only variables that resolve to an ASN.1 primitive type of INTEGER (INTEGER, Integer32, Counter32, Counter64, Gauge, or TimeTicks) may be sampled. Because SNMP access control is articulated entirely in terms of the contents of MIB views, no access control mechanism exists that can restrict the value of this object to identify only those objects that exist in a particular MIB view. Because there is thus no acceptable means of restricting the read access that could be obtained through the alarm mechanism, the probe must only grant write access to this object in those views that have read access to all objects on the probe. During a set operation, if the supplied variable name is not available in the selected MIB view, a badValue error must be returned. If at any time the variable name of an established alarmEntry is no longer available in the selected MIB view, the probe must change the status of this alarmEntry to invalid(4). This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmSampleType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("absoluteValue", 1), ("deltaValue", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmSampleType.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmSampleType.setDescription('The method of sampling the selected variable and calculating the value to be compared against the thresholds. If the value of this object is absoluteValue(1), the value of the selected variable will be compared directly with the thresholds at the end of the sampling interval. If the value of this object is deltaValue(2), the value of the selected variable at the last sample will be subtracted from the current value, and the difference compared with the thresholds. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmRisingThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 5), Integer32()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmRisingThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmRisingThreshold.setDescription('A threshold for the sampled statistic. When the current sampled value is greater than or equal to this threshold, and the value at the last sampling interval was less than this threshold, a single event will be generated. A single event will also be generated if the first sample after this entry becomes valid is greater than or equal to this threshold and the associated alarmStartupAlarm is equal to risingAlarm(1) or risingOrFallingAlarm(3). After a rising event is generated, another such event will not be generated until the sampled value falls below this threshold and reaches the alarmFallingThreshold. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmFallingThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 6), Integer32()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmFallingThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmFallingThreshold.setDescription('A threshold for the sampled statistic. When the current sampled value is less than or equal to this threshold, and the value at the last sampling interval was greater than this threshold, a single event will be generated. A single event will also be generated if the first sample after this entry becomes valid is less than or equal to this threshold and the associated alarmStartupAlarm is equal to fallingAlarm(2) or risingOrFallingAlarm(3). After a falling event is generated, another such event will not be generated until the sampled value rises above this threshold and reaches the alarmRisingThreshold. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmRisingEventIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmRisingEventIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmRisingEventIndex.setDescription('The index of the eventEntry that is used when a rising threshold is crossed. The eventEntry identified by a particular value of this index is the same as identified by the same value of the eventIndex object. If there is no corresponding entry in the eventTable, then no association exists. In particular, if this value is zero, no associated event will be generated, as zero is not a valid event index. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmFallingEventIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmFallingEventIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmFallingEventIndex.setDescription('The index of the eventEntry that is used when a falling threshold is crossed. The eventEntry identified by a particular value of this index is the same as identified by the same value of the eventIndex object. If there is no corresponding entry in the eventTable, then no association exists. In particular, if this value is zero, no associated event will be generated, as zero is not a valid event index. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 9), OwnerString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmOwner.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmOwner.setDescription('The entity that configured this entry and is therefore using the resources assigned to it.')NEWLINErmonAlarmStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 10), RmonStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmStatus.setDescription('The status of this alarm entry.')NEWLINErmonEventTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1), )NEWLINEif mibBuilder.loadTexts: rmonEventTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventTable.setDescription('A list of events to be generated.')NEWLINErmonEventEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "rmonEventIndex"))NEWLINEif mibBuilder.loadTexts: rmonEventEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventEntry.setDescription('A set of parameters that describe an event to be generated when certain conditions are met. As an example, an instance of the eventLastTimeSent object might be named eventLastTimeSent.6')NEWLINErmonEventIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: rmonEventIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventIndex.setDescription('An index that uniquely identifies an entry in the event table. Each such entry defines one event that is to be generated when the appropriate conditions occur.')NEWLINErmonEventDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 127))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventDescription.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventDescription.setDescription('A comment describing this event entry.')NEWLINErmonEventType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("log", 2), ("snmptrap", 3), ("logandtrap", 4)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventType.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventType.setDescription('The type of notification that the probe will make about this event. In the case of log, an entry is made in the log table for each event. In the case of snmp-trap, an SNMP trap is sent to one or more management stations.')NEWLINErmonEventCommunity = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 127))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventCommunity.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventCommunity.setDescription('If an SNMP trap is to be sent, it will be sent to the SNMP community specified by this octet string.')NEWLINErmonEventOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 5), OwnerString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventOwner.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventOwner.setDescription("The entity that configured this entry and is therefore using the resources assigned to it. If this object contains a string starting with 'monitor' and has associated entries in the log table, all connected management stations should retrieve those log entries, as they may have significance to all management stations connected to this device")NEWLINErmonEventStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 6), RmonStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventStatus.setDescription('The status of this event entry. If this object is not equal to valid(1), all associated log entries shall be deleted by the agent.')NEWLINEneighborTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1), )NEWLINEif mibBuilder.loadTexts: neighborTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborTable.setDescription('A list of the Neighbor Cache Table.')NEWLINEneighborEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "neighborIfindex"), (0, "DES-1210-28MEbx", "neighborIPv6Addr"), (0, "DES-1210-28MEbx", "neighborMACAddr"))NEWLINEif mibBuilder.loadTexts: neighborEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborEntry.setDescription('A Neighbor cache entry containing the ifindex and ipv6 addr.')NEWLINEneighborIfindex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborIfindex.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborIfindex.setDescription('The interface index of the Neighbor entry. Must be conform to the existing interface name.')NEWLINEneighborIPv6Addr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 2), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborIPv6Addr.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborIPv6Addr.setDescription('Allows the entry of an IP address that will be a Neighbor entry into the Neighbor Cache Table.')NEWLINEneighborMACAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborMACAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborMACAddr.setDescription('The MAC address associated of the Neighbor entry.')NEWLINEneighborType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("static", 1), ("dynamic", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborType.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborType.setDescription('The type associated of the Neighbor entry.')NEWLINEneighborCacheState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("static", 1), ("reachable", 2), ("incomplete", 3), ("stale", 4), ("delay", 5), ("probe", 6), ("notinservice", 7)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborCacheState.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborCacheState.setDescription('The type associated of the Neighbor entry.')NEWLINEneighborActiveStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("active", 1), ("inactive", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborActiveStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborActiveStatus.setDescription('The active status of the Neighbor entry.')NEWLINEneighborRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 7), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: neighborRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborRowStatus.setDescription('The status of an entry in the Neighbor Cache Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINEdhcpv6RelayControl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 1))NEWLINEdhcpv6RelayManagement = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2))NEWLINEdhcpv6RelayOption37 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3))NEWLINEdhcpv6RelayOption38 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4))NEWLINEdhcpv6RelayOption18 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 5))NEWLINEdhcpv6RelayState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayState.setDescription('This object indicates DHCPv6 relay function is enabled or disabled.')NEWLINEdhcpv6RelayHopCount = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayHopCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayHopCount.setDescription('This object indicates the maximum number of router hops that the DHCPv6 packets can cross.')NEWLINEdhcpv6RelayInterfaceSettingsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1), )NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsTable.setDescription('This table indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpv6RelayInterfaceSettingsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpv6RelayInterface"), (0, "DES-1210-28MEbx", "dhcpv6RelayServerIP"))NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsEntry.setDescription('A list of information indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpv6RelayInterface = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 12))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterface.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterface.setDescription('This object indicates the maximum number of router hops that the DHCPv6 packets can cross.')NEWLINEdhcpv6RelayServerIP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1, 1, 2), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayServerIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayServerIP.setDescription('This object indicates the DHCP server IP address.')NEWLINEdhcpv6RelayInterfaceSettingsRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEdhcpv6RelayOption37State = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37State.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37State.setDescription('This object indicates DHCPv6 relay option 37 function is enabled or disabled.')NEWLINEdhcpv6RelayOption37CheckState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37CheckState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37CheckState.setDescription('This object indicates DHCPv6 relay option 37 Check function is enabled or disabled.')NEWLINEdhcpv6RelayOption37RemoteIDType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("default", 0), ("cid-with-user-define", 1), ("user-define", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37RemoteIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37RemoteIDType.setDescription('This object indicates the type of remote ID.')NEWLINEdhcpv6RelayOption37RemoteID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3, 4), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37RemoteID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37RemoteID.setDescription('This object displays the current remote ID of the device. If RemoteIDType is set to default, the value will be the MAC address of the device, and this object cannot be modified. If RemoteIDType is set to user-defined, a new value can be written to this object.')NEWLINEdhcpv6RelayOpt38Table = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1), )NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38Table.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38Table.setDescription('A table to control port security features of the device.')NEWLINEdhcpv6RelayOpt38Entry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpv6RelayOpt38PortIndex"))NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38Entry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38Entry.setDescription('An entry appears in port security table for each interface in the system.')NEWLINEdhcpv6RelayOpt38PortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortIndex.setDescription('The interface index for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEdhcpv6RelayOpt38PortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortState.setDescription('Enable / disable option 38 port state.')NEWLINEdhcpv6RelayOpt38PortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("default", 0), ("user-defined", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortType.setDescription('Configure option 38 port Type.')NEWLINEdhcpv6RelayOpt38PortID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1, 4), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortID.setDescription('Configure option 38 port ID. Only works when type is user-defined')NEWLINEdhcpv6RelayOption18State = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 5, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18State.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18State.setDescription('This object indicates DHCPv6 relay option 18 function is enabled or disabled.')NEWLINEdhcpv6RelayOption18CheckState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 5, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18CheckState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18CheckState.setDescription('This object indicates DHCPv6 relay option 18 Check function is enabled or disabled.')NEWLINEdhcpv6RelayOption18InterfaceIDType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 5, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("default", 0), ("cid", 1), ("vendor1", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18InterfaceIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18InterfaceIDType.setDescription('This object indicates the type of Interface ID.')NEWLINEmacBasedVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1), )NEWLINEif mibBuilder.loadTexts: macBasedVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: macBasedVlanTable.setDescription('A table that contains information on Vlan-MAC address mapping.')NEWLINEmacBasedVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "vlanMacMapIndex"))NEWLINEif mibBuilder.loadTexts: macBasedVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: macBasedVlanEntry.setDescription('Entry that contains Vlan-MAC address mapping.')NEWLINEvlanMacMapIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: vlanMacMapIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapIndex.setDescription('Index of cmMacBasedVlanEntry. This object indicates the mac vlan entry for which the configurations in cmMacBasedVlanEntry is to be done.')NEWLINEvlanMacMapAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 2), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanMacMapAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapAddr.setDescription('The Mac address for which the Vlan mapping is present in the entry.')NEWLINEvlanMacMapAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 3), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanMacMapAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapAddrMask.setDescription('The Mac address for which the Vlan mapping is present in the entry.')NEWLINEvlanMacMapVid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 4), VlanIndex()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanMacMapVid.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapVid.setDescription('The Vlan to which the mac address of this entry is mapped to.')NEWLINEvlanMacStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 5), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: vlanMacStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacStatus.setDescription('The status given to the mac-vlan entry.')NEWLINEvlanMacType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 6), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: vlanMacType.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacType.setDescription('The type given to the mac-vlan entry.')NEWLINEvlanMacMapRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 99), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanMacMapRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapRowStatus.setDescription('The row status of the entry.')NEWLINEmacBasedVlanMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("single", 1), ("range", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macBasedVlanMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: macBasedVlanMethod.setDescription('A method of Vlan-MAC address mapping.')NEWLINEsfpVendorInfoTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1), )NEWLINEif mibBuilder.loadTexts: sfpVendorInfoTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorInfoTable.setDescription('This table indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEsfpVendorInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sfpPortIndex"))NEWLINEif mibBuilder.loadTexts: sfpVendorInfoEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorInfoEntry.setDescription('A list of information indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEsfpPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpPortIndex.setDescription('The available of index for fiber ports.')NEWLINEsfpConnectorType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 2), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpConnectorType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpConnectorType.setDescription('')NEWLINEsfpTranceiverCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 3), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpTranceiverCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpTranceiverCode.setDescription('')NEWLINEsfpBaudRate = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 4), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpBaudRate.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpBaudRate.setDescription('')NEWLINEsfpVendorName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 5), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorName.setDescription('')NEWLINEsfpVendorOui = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 6), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorOui.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorOui.setDescription('')NEWLINEsfpVendorPn = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 7), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorPn.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorPn.setDescription('')NEWLINEsfpVendorRev = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 8), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorRev.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorRev.setDescription('')NEWLINEsfpWavelength = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 9), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpWavelength.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpWavelength.setDescription('')NEWLINEsfpVendorSn = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 10), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorSn.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorSn.setDescription('')NEWLINEsfpDateCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 11), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpDateCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpDateCode.setDescription('')NEWLINEddmCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1))NEWLINEddmInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2))NEWLINEddmPowerUnit = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("mw", 0), ("dbm", 1))).clone('mw')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmPowerUnit.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmPowerUnit.setDescription('This object indicates the TX/RX power global unit.')NEWLINEddmActionMgmtTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2), )NEWLINEif mibBuilder.loadTexts: ddmActionMgmtTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ddmActionMgmtTable.setDescription('This table contains the configuration of the action taken when any parameter exceeds its threshold.')NEWLINEddmActionMgmtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ddmActionPort"))NEWLINEif mibBuilder.loadTexts: ddmActionMgmtEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ddmActionMgmtEntry.setDescription('This is an entry of the swDdmConfigActionTable.')NEWLINEddmActionPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmActionPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmActionPort.setDescription('This object indicates the port. The available of index for fiber ports.')NEWLINEddmActionState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmActionState.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ddmActionState.setDescription('This object indicates the action type.')NEWLINEddmActionShutdown = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("alarm", 1), ("warning", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmActionShutdown.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ddmActionShutdown.setDescription('This object indicates the action type.')NEWLINEddmThresholdMgmtTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3), )NEWLINEif mibBuilder.loadTexts: ddmThresholdMgmtTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmThresholdMgmtTable.setDescription('This table contains DDM temperature configuration information.')NEWLINEddmThresholdMgmtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ddmThresholdPort"), (0, "DES-1210-28MEbx", "ddmThresholdType"))NEWLINEif mibBuilder.loadTexts: ddmThresholdMgmtEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmThresholdMgmtEntry.setDescription('This is an entry of the swDdmConfigThresholdTable.')NEWLINEddmThresholdPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmThresholdPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmThresholdPort.setDescription('This object indicates the port. The available of index for fiber ports.')NEWLINEddmThresholdType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("temperature", 0), ("voltage", 1), ("bias", 2), ("txPower", 3), ("rxPower", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmThresholdType.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmThresholdType.setDescription('This object indicates the threshold type.')NEWLINEddmHighAlarm = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 3), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmHighAlarm.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmHighAlarm.setDescription('This object indicates the high alarm threshold value to be configured. As the value is a floating point data type, the DisplayString type is used to define this parameter.')NEWLINEddmLowAlarm = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 4), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmLowAlarm.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmLowAlarm.setDescription('This object indicates the low alarm threshold value to be configured. As the value is a floating data type, the DisplayString type is used to define this parameter.')NEWLINEddmHighWarning = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 5), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmHighWarning.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmHighWarning.setDescription('This object indicates the high warning threshold value to be configured. As the value is a floating data type, the DisplayString type is used to define this parameter.')NEWLINEddmLowWarning = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 6), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmLowWarning.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmLowWarning.setDescription('This object indicates the low warning threshold value to be configured. As the value is a floating data type, the DisplayString type is used to define this parameter.')NEWLINEddmStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1))NEWLINEddmStatusTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1), )NEWLINEif mibBuilder.loadTexts: ddmStatusTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmStatusTable.setDescription('This table contains the DDM status information.')NEWLINEddmStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ddmStatusPort"))NEWLINEif mibBuilder.loadTexts: ddmStatusEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmStatusEntry.setDescription('This is an entry of the ddmStatusTable.')NEWLINEddmStatusPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmStatusPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmStatusPort.setDescription('This object indicates the port. The available of index for fiber ports.')NEWLINEddmTemperature = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 2), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmTemperature.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmTemperature.setDescription('This object indicates the real time value of the temperature. As the value is a floating point data type, the DisplayString type is used to define this parameter.')NEWLINEddmVoltage = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 3), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmVoltage.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmVoltage.setDescription('This object indicates the real time value of the supply voltage. As the value value is a floating point data type, the DisplayString type is used to define this parameter.')NEWLINEddmBiasCurrent = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 4), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmBiasCurrent.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmBiasCurrent.setDescription('This object indicates the real time value of the tx bias.')NEWLINEddmTxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 5), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmTxPower.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmTxPower.setDescription('This object indicates the real time value of the tx power. As the value is a floating point data type, the DisplayString type is used to define this parameter.')NEWLINEddmRxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 6), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmRxPower.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmRxPower.setDescription('This object indicates the real time value of the rx power. As the value is a floating data type, the DisplayString type is used to define this parameter.')NEWLINEftpFwTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1))NEWLINEftpConfigTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2))NEWLINEftpFwServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwServerIpAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwServerIpAddress.setDescription("The FTP server's IPv4 address or IPv6 address is used to upload or download firmware.")NEWLINEftpFwImageFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwImageFileName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwImageFileName.setDescription('Firmware file name used to upload or download firmware.')NEWLINEftpFwUsername = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwUsername.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwUsername.setDescription('FTP username to login FTP.')NEWLINEftpFwPassword = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwPassword.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwPassword.setDescription('FTP password to login FTP.')NEWLINEftpFwPath = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwPath.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwPath.setDescription('FTP path can find file folder.')NEWLINEftpFwPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwPort.setDescription('FTP port to login FTP.')NEWLINEftpFwFTPOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("download", 1), ("upload", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwFTPOperation.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwFTPOperation.setDescription('The FTP operates to perform downloading the firmware image to the unit. This object is used in conjunction with FTP settings')NEWLINEftpFwFTPOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3), ("transmit", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ftpFwFTPOperationStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwFTPOperationStatus.setDescription('The FTP operation status represent firmware backup or upgrade status.')NEWLINEftpConfigServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigServerIpAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigServerIpAddress.setDescription("The FTP server's IPv4 address or IPv6 address is used to upload or download firmware.")NEWLINEftpConfigFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigFileName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigFileName.setDescription('Config file name used to upload or download Config.')NEWLINEftpConfigUsername = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigUsername.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigUsername.setDescription('FTP username to login FTP.')NEWLINEftpConfigPassword = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigPassword.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigPassword.setDescription('FTP password to login FTP.')NEWLINEftpConfigPath = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigPath.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigPath.setDescription('FTP path can find file folder.')NEWLINEftpConfigPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigPort.setDescription('FTP port to login FTP.')NEWLINEftpConfigConfigID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("configID1", 1), ("configID2", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigConfigID.setStatus('current')NEWLINEif mibBuilder.loadTexts: ftpConfigConfigID.setDescription('Config image id can select imageid1 or imageid2 to flash')NEWLINEftpConfigFTPOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("download", 1), ("upload", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigFTPOperation.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigFTPOperation.setDescription('The FTP operates to perform downloading the config image to the unit. This object is used in conjunction with FTP settings')NEWLINEftpConfigFTPOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3), ("transmit", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ftpConfigFTPOperationStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigFTPOperationStatus.setDescription('The FTP operation status represent config backup or upgrade status.')NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", swAuthRadiusServerTable=swAuthRadiusServerTable, stpNewRootTrapStatus=stpNewRootTrapStatus, ipv4sysSNTPDSTEndMon=ipv4sysSNTPDSTEndMon, cpuFilterv6L3RuleProfileNo=cpuFilterv6L3RuleProfileNo, iPv4aacServerAuthKey=iPv4aacServerAuthKey, pppoePortRemoteIDType=pppoePortRemoteIDType, ipv4aclProfileEntry=ipv4aclProfileEntry, sysPortErrPortIndex=sysPortErrPortIndex, ipv4aclQosVlanID=ipv4aclQosVlanID, dlinklldpState=dlinklldpState, laPortControl=laPortControl, cpuFilterProfileStatus=cpuFilterProfileStatus, sfpDateCode=sfpDateCode, impbBlockListMacAddress=impbBlockListMacAddress, swAuthUserName=swAuthUserName, companyDHCPv6Relay=companyDHCPv6Relay, aclL3RuleTcpPshBit=aclL3RuleTcpPshBit, lldpXdot3RemLinkAggEntry=lldpXdot3RemLinkAggEntry, portSecFDBPermanentTable=portSecFDBPermanentTable, aacEnableMethodListEntry=aacEnableMethodListEntry, cpuFilterL3RuleSrcIpAddr=cpuFilterL3RuleSrcIpAddr, trafficCtrlTimeInterval=trafficCtrlTimeInterval, companyQoSGroup=companyQoSGroup, cpuFilterL2RuleDstMacAddrMask=cpuFilterL2RuleDstMacAddrMask, mldsHostTable=mldsHostTable, protocolVlanEntry=protocolVlanEntry, swAuthAuthConfigPortControl=swAuthAuthConfigPortControl, errorSymbolWindow=errorSymbolWindow, ipv4aclUdfOffsetBase1=ipv4aclUdfOffsetBase1, mstCistPortEntry=mstCistPortEntry, iPv4swAuthRadiusServerAuthenticationPort=iPv4swAuthRadiusServerAuthenticationPort, OwnerString=OwnerString, staticAutoLearningList=staticAutoLearningList, VlanIndex=VlanIndex, lldpXdot1RemTable=lldpXdot1RemTable, dhcpBOOTPRelayTimeThreshold=dhcpBOOTPRelayTimeThreshold, ipv4trustedHostEntry=ipv4trustedHostEntry, igmpMulticastVlanRowStatus=igmpMulticastVlanRowStatus, aclL2RuleEntry=aclL2RuleEntry, aclL3RuleAction=aclL3RuleAction, aacAccountingMethod1=aacAccountingMethod1, ftpConfigConfigID=ftpConfigConfigID, tftpCfgTargetServerIpAddress=tftpCfgTargetServerIpAddress, igmpMulticastVlanGroupToIp=igmpMulticastVlanGroupToIp, dhcpBOOTPRelayInterface=dhcpBOOTPRelayInterface, lldpXdot3RemMaxFrameSizeTable=lldpXdot3RemMaxFrameSizeTable, sysDhcpAutoConfigTimeout=sysDhcpAutoConfigTimeout, pppoePortEntry=pppoePortEntry, rmonAlarmFallingEventIndex=rmonAlarmFallingEventIndex, snmpV3GroupSecurityModel=snmpV3GroupSecurityModel, rmonAlarmTable=rmonAlarmTable, sshUserInfoID=sshUserInfoID, snmpTrapCopperLinkUpDown=snmpTrapCopperLinkUpDown, snmpV3CommunityEncryption=snmpV3CommunityEncryption, mldsVlanCfgQuerier=mldsVlanCfgQuerier, ipv4cpuFilterProfileMask=ipv4cpuFilterProfileMask, qinqEntry=qinqEntry, aclUdfOffsetMask2=aclUdfOffsetMask2, neighborActiveStatus=neighborActiveStatus, qosDiffServType31=qosDiffServType31, qosUserPriIndex=qosUserPriIndex, ipv4cpuFilterProfileTable=ipv4cpuFilterProfileTable, ipv4aclQosStatus=ipv4aclQosStatus, sysBPDUAttackRecoverTime=sysBPDUAttackRecoverTime, cosBandwidthCtrlSettings=cosBandwidthCtrlSettings, staticVlanBaseAutoLearnList3k=staticVlanBaseAutoLearnList3k, ipv4sysSNTPDSTStartDay=ipv4sysSNTPDSTStartDay, cableDiagPair1Length=cableDiagPair1Length, ipv4syslogServUDPport=ipv4syslogServUDPport, ipv4sysSNTPTimeSeconds=ipv4sysSNTPTimeSeconds, ipv4aclUdfOffsetBase4=ipv4aclUdfOffsetBase4, lldpXdot3RemLinkAggPortId=lldpXdot3RemLinkAggPortId, ftpConfigServerIpAddress=ftpConfigServerIpAddress, autoFdbMacAddress=autoFdbMacAddress, qosPriSettings=qosPriSettings, lldpPortConfigEntry=lldpPortConfigEntry, lldpXdot3RemPortAutoNegEnabled=lldpXdot3RemPortAutoNegEnabled, ipifV6AddressIpType=ipifV6AddressIpType, ipv4aclUdfOffsetByte4=ipv4aclUdfOffsetByte4, aclProfileArpSenderIpAddrMask=aclProfileArpSenderIpAddrMask, swTimeRangeThursday=swTimeRangeThursday, rmonAlarmStatus=rmonAlarmStatus, igmpMulticastVlanName=igmpMulticastVlanName, cpuFilterL3RuleTable=cpuFilterL3RuleTable, rmonStatsStatus=rmonStatsStatus, rmonHistory=rmonHistory, ddmLowWarning=ddmLowWarning, sshPublKeyRSAAdmin=sshPublKeyRSAAdmin, companySNMPV3=companySNMPV3, staticMac=staticMac, aclL3Rule=aclL3Rule, aacAccountingServiceCommand=aacAccountingServiceCommand, trafficCtrlSettings=trafficCtrlSettings, snmpV3GroupTable=snmpV3GroupTable, ipifV6AddressRowStatus=ipifV6AddressRowStatus, rmonEvent=rmonEvent, sysGratuitousARPEntry=sysGratuitousARPEntry, macNotifyCtrlTable=macNotifyCtrlTable, eoamIfIndex=eoamIfIndex, qinqVlanTranslationSVIDOperation=qinqVlanTranslationSVIDOperation, ddmThresholdMgmtTable=ddmThresholdMgmtTable, stpMaxAge=stpMaxAge, aacServerGroupName=aacServerGroupName, ftpFwImageFileName=ftpFwImageFileName, sshSecurityStatus=sshSecurityStatus, snmpV3viewTreeType=snmpV3viewTreeType, sysLBDVlanLoopEntry=sysLBDVlanLoopEntry, dhcpBOOTPRelayOption82CheckState=dhcpBOOTPRelayOption82CheckState, aclv6L3RuleTable=aclv6L3RuleTable, stpBridgeGlobal=stpBridgeGlobal, neighborMACAddr=neighborMACAddr, laStatus=laStatus, dlinklldpMsgHoldMultiplier=dlinklldpMsgHoldMultiplier, aacAPHttpLoginMethod=aacAPHttpLoginMethod, dhcpv6RelayInterfaceSettingsTable=dhcpv6RelayInterfaceSettingsTable, aclFlowMeterEntry=aclFlowMeterEntry, sysPortMediaType=sysPortMediaType, sysPortMediaTypeOui=sysPortMediaTypeOui, dhcpv6RelayOption37State=dhcpv6RelayOption37State, stpTxHoldCount=stpTxHoldCount, sshMaxSession=sshMaxSession, sysSNTPTimeSeconds=sysSNTPTimeSeconds, swAuthAuthQuietPeriod=swAuthAuthQuietPeriod, sshConnectionTimeout=sshConnectionTimeout, ipv4cpuFilterProfileRuleCount=ipv4cpuFilterProfileRuleCount, securitySSL=securitySSL, bandwidthCtrlSettings=bandwidthCtrlSettings, syslogServSrvStatus=syslogServSrvStatus, sysGratuitousARPGlobalSettings=sysGratuitousARPGlobalSettings, ftpConfigTable=ftpConfigTable, cpuFilterProfileDstPortMask=cpuFilterProfileDstPortMask, cpuFilterv6L3RuleTcpSynBit=cpuFilterv6L3RuleTcpSynBit, cpuFilterProfileMask=cpuFilterProfileMask, ipv4cpuFilterProfileSrcPortMask=ipv4cpuFilterProfileSrcPortMask, impbPortDHCPv6VlanList3k=impbPortDHCPv6VlanList3k, aRPSpoofPreventRowStatus=aRPSpoofPreventRowStatus, aacAuthParamResponseTimeout=aacAuthParamResponseTimeout, iPv4aacServerTimeout=iPv4aacServerTimeout, rmonStatistics=rmonStatistics, sysUser=sysUser, multicastVlanTable=multicastVlanTable, sysLBDRecoverTime=sysLBDRecoverTime, aclv6L3RuleRateLimit=aclv6L3RuleRateLimit, companyAuthGroup=companyAuthGroup, aclFlowMeterBurstSize=aclFlowMeterBurstSize, lldpXdot3RemPowerClass=lldpXdot3RemPowerClass, qosDiffServType10=qosDiffServType10, sfpBaudRate=sfpBaudRate, ipv4snmpV3HostTable=ipv4snmpV3HostTable, cpuFilterL3RuleDstIpAddrMask=cpuFilterL3RuleDstIpAddrMask, aclL3RuleFilterTimeRange=aclL3RuleFilterTimeRange, staticVlanBaseAutoLearnList4k=staticVlanBaseAutoLearnList4k, trafficCtrlAutoRecoverTime=trafficCtrlAutoRecoverTime, macNotifyHistorySize=macNotifyHistorySize, sysGratuitousARPIFName=sysGratuitousARPIFName, cpuFilterL3RuleTcpSynBit=cpuFilterL3RuleTcpSynBit, lldpXdot3RemPowerEntry=lldpXdot3RemPowerEntry, gvrpSettingsLeaveAllTime=gvrpSettingsLeaveAllTime, sysSNTPDSTStartMin=sysSNTPDSTStartMin, aclL3RuleTcpFinBit=aclL3RuleTcpFinBit, impbBindingtrapsign=impbBindingtrapsign, cpuFilterProfileSrcPortMask=cpuFilterProfileSrcPortMask, cableDiagLinkStatus=cableDiagLinkStatus, snmpV3viewTreeName=snmpV3viewTreeName, newRootBrgaddress=newRootBrgaddress, qosDiffServType34=qosDiffServType34, igmpMulticastVlanUntaggedSourcePort=igmpMulticastVlanUntaggedSourcePort, ipv4cpuFilterProfileDstIpAddrMask=ipv4cpuFilterProfileDstIpAddrMask, ipv4sysIpAddr=ipv4sysIpAddr, cpuFilterL3RuleIgmpType=cpuFilterL3RuleIgmpType, snmpV3HostAddress=snmpV3HostAddress, macNotifyCtrlIndex=macNotifyCtrlIndex, mldsVlanRouterVlanId=mldsVlanRouterVlanId, swTimeRangeEndYear=swTimeRangeEndYear, qosTOSType02=qosTOSType02, doSCtrlMirrorPort=doSCtrlMirrorPort, lldpXdot3LocPowerMDISupported=lldpXdot3LocPowerMDISupported, cpuFilterL3RuleAction=cpuFilterL3RuleAction, multicastVlanMldReplaceSourceIp=multicastVlanMldReplaceSourceIp, cpuFilterv6L3RuleAction=cpuFilterv6L3RuleAction, sysMirrorCtrlEgressMirroring=sysMirrorCtrlEgressMirroring, sysSNTPFirstInterfaceName=sysSNTPFirstInterfaceName, trustedHostStatus=trustedHostStatus, impbPortDHCPSnoopingState=impbPortDHCPSnoopingState, iPv4swAuthRadiusServerAddress=iPv4swAuthRadiusServerAddress, ipifV6AddressEntry=ipifV6AddressEntry, stpModuleStatus=stpModuleStatus, cpuFilterL3RuleDscp=cpuFilterL3RuleDscp, mldsVlanMulticastGroupTable=mldsVlanMulticastGroupTable, portSecEntry=portSecEntry, baudRateConfiguration=baudRateConfiguration, lldpXdot1LocProtocolIndex=lldpXdot1LocProtocolIndex, cpuFilterProfileDstIpAddrMaskType=cpuFilterProfileDstIpAddrMaskType, ipv4snmpV3HostStatus=ipv4snmpV3HostStatus, tftpCfgTargetTftpOperationStatus=tftpCfgTargetTftpOperationStatus, trafficCtrlActionMode=trafficCtrlActionMode, syslogServFacility=syslogServFacility, cpuFilterProfileType=cpuFilterProfileType, pppoeGlobalState=pppoeGlobalState, qosDiffServType55=qosDiffServType55, aclQosStatus=aclQosStatus, mstCistPort=mstCistPort, staticMcastVlanID=staticMcastVlanID, igsHostTableHostIPAddress=igsHostTableHostIPAddress, aacLoginMethodListRowStatus=aacLoginMethodListRowStatus, sysSNTPDSTStartHour=sysSNTPDSTStartHour, staticARPRowStatus=staticARPRowStatus, sysPortCtrlMediumType=sysPortCtrlMediumType, mstMstiPortTable=mstMstiPortTable, sysLoginTimeoutInterval=sysLoginTimeoutInterval, lldpXdot1RemVlanNameEntry=lldpXdot1RemVlanNameEntry, laPortChannelMode=laPortChannelMode, ipv4cpuFilterProfileEntry=ipv4cpuFilterProfileEntry, aclL2RuleEtherType=aclL2RuleEtherType, aclQosProtocol=aclQosProtocol, cpuFilterL2RuleTable=cpuFilterL2RuleTable, swAuthRadiusServerTimeout=swAuthRadiusServerTimeout, aclL3RuleTcpRstBit=aclL3RuleTcpRstBit, companyL2PT=companyL2PT, duldRecoverTime=duldRecoverTime, trafficCtrlEntry=trafficCtrlEntry, cpuFilterL3RuleDstIpAddr=cpuFilterL3RuleDstIpAddr, smtpServerAddrInterfaceName=smtpServerAddrInterfaceName, aclL3RuleTos=aclL3RuleTos, tftpCfgTargetInterfaceName=tftpCfgTargetInterfaceName, aclPacketRuleOffsetValue2=aclPacketRuleOffsetValue2, lldpXdot3RemPowerPortClass=lldpXdot3RemPowerPortClass, aacAccountingMethodListIndex=aacAccountingMethodListIndex, iPv4swAuthRadiusServerEntry=iPv4swAuthRadiusServerEntry, aclProfileTable=aclProfileTable, qosTOSType01=qosTOSType01, aacServersInGroup=aacServersInGroup, ipv4aclUdfOffsetMask2=ipv4aclUdfOffsetMask2, sysSNTPDSTRepeatStartMin=sysSNTPDSTRepeatStartMin, snmpV3viewTreeSubtree=snmpV3viewTreeSubtree, stpPortPathCost=stpPortPathCost, lldpXdot3RemPowerPairControlable=lldpXdot3RemPowerPairControlable, qosTOSType03=qosTOSType03, PYSNMP_MODULE_ID=des_1210_28mebx, qinqVlanTranslationCVIDEntry=qinqVlanTranslationCVIDEntry, aclUdfOffsetMask4=aclUdfOffsetMask4, aclL3RuleTable=aclL3RuleTable, sfpVendorOui=sfpVendorOui, igsStatus=igsStatus, impbPortState=impbPortState, autoFdbPort=autoFdbPort, ipv4snmpV3HostCommunityName=ipv4snmpV3HostCommunityName, cpuFilterL2Rule1pPriority=cpuFilterL2Rule1pPriority, lldpXdot3RemPortOperMauType=lldpXdot3RemPortOperMauType, ddmActionState=ddmActionState, aclProfileNo=aclProfileNo, lldpXdot1LocProtocolEntry=lldpXdot1LocProtocolEntry, mldsVlanMulticastGroupIpAddress=mldsVlanMulticastGroupIpAddress, protocolGroupId=protocolGroupId)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", qosDiffServType23=qosDiffServType23, aacAPLoginMethod=aacAPLoginMethod, companyIpifGroup=companyIpifGroup, sysSNTPDSTRepeatEndWeek=sysSNTPDSTRepeatEndWeek, igsHost=igsHost, eoamEntry=eoamEntry, sshCipherSuiteList=sshCipherSuiteList, ddmActionShutdown=ddmActionShutdown, cosBandwidthEffectiveTX=cosBandwidthEffectiveTX, dhcpv6RelayManagement=dhcpv6RelayManagement, rmonEventStatus=rmonEventStatus, snmpV3GroupStatus=snmpV3GroupStatus, Ipv6Address=Ipv6Address, aacEnableMethodListRowStatus=aacEnableMethodListRowStatus, sysSNTPDSTMethod=sysSNTPDSTMethod, aacLoginMethod4=aacLoginMethod4, aacServerTimeout=aacServerTimeout, companyTrapSetting=companyTrapSetting, limitIpMulticastProfileID=limitIpMulticastProfileID, ddmThresholdMgmtEntry=ddmThresholdMgmtEntry, qinqRoleState=qinqRoleState, qosDiffServType01=qosDiffServType01, qinqVlanTranslationCVID=qinqVlanTranslationCVID, sshUserInfoEntry=sshUserInfoEntry, dlinklldpMsgTxInterval=dlinklldpMsgTxInterval, sysGratuitousARPIPIfStatusUp=sysGratuitousARPIPIfStatusUp, sysSave=sysSave, sysRestart=sysRestart, dhcpv6RelayOpt38PortID=dhcpv6RelayOpt38PortID, lldpXdot3LocLinkAggPortId=lldpXdot3LocLinkAggPortId, swAuthRadiusServerAddress=swAuthRadiusServerAddress, igsVlanMulticastGroupMacAddress=igsVlanMulticastGroupMacAddress, sysLBDCtrlIndex=sysLBDCtrlIndex, aclPacketRuleOffsetValue3=aclPacketRuleOffsetValue3, aclv6L3RuleDstIpAddr=aclv6L3RuleDstIpAddr, dot1qVlanManagementOnOff=dot1qVlanManagementOnOff, aacAccountingMethod2=aacAccountingMethod2, securityPortSecurity=securityPortSecurity, impbDhcpSnoopingMacAddress=impbDhcpSnoopingMacAddress, lldpXdot1ConfigProtoVlanEntry=lldpXdot1ConfigProtoVlanEntry, bandwidthCtrlEntry=bandwidthCtrlEntry, igsVlanRobustnessValue=igsVlanRobustnessValue, vlanMacType=vlanMacType, snmpV3TrapFirmUpgrade=snmpV3TrapFirmUpgrade, companyGuestVlan=companyGuestVlan, cpuFilterProfileDstMacAddrMask=cpuFilterProfileDstMacAddrMask, cpuFilterL3RuleTcpUdpDstPort=cpuFilterL3RuleTcpUdpDstPort, ipv4cpuFilterProfileStatus=ipv4cpuFilterProfileStatus, swTimeRangeTuesday=swTimeRangeTuesday, cpuFilterv6L3RuleTcpFinBit=cpuFilterv6L3RuleTcpFinBit, sshMacSuiteList=sshMacSuiteList, mstMstiPort=mstMstiPort, cosBandwidthCtrlEntry=cosBandwidthCtrlEntry, swAuthCtrlPktFwdMode=swAuthCtrlPktFwdMode, l2PTPortTable=l2PTPortTable, aclv6L3RuleReplace1P=aclv6L3RuleReplace1P, sysPortCtrlType=sysPortCtrlType, sysLBDMode=sysLBDMode, pppoePortCircuitIDType=pppoePortCircuitIDType, duldTable=duldTable, qosDiffServType37=qosDiffServType37, ipv4sysSNTPGMTMinutes=ipv4sysSNTPGMTMinutes, sysBPDUAttackCtrlEntry=sysBPDUAttackCtrlEntry, aclL3RuleDscp=aclL3RuleDscp, limitIpMulticastIPType=limitIpMulticastIPType, companyAgentBasicInfo=companyAgentBasicInfo, newRootOlddesignatedroot=newRootOlddesignatedroot, bandwidthEffecTxThreshold=bandwidthEffecTxThreshold, sysSNTPFirstServer=sysSNTPFirstServer, igsVlanRouterTable=igsVlanRouterTable, limitIpMulticastEntryIPType=limitIpMulticastEntryIPType, duldState=duldState, aclv6L3RuleReplaceQueue=aclv6L3RuleReplaceQueue, snmpV3Trap=snmpV3Trap, igsVlanQuerierVersionStatus=igsVlanQuerierVersionStatus, ftpConfigPort=ftpConfigPort, multicastVlanUntaggedSourcePort=multicastVlanUntaggedSourcePort, companyMulticastFilter=companyMulticastFilter, sysGratuitousARPTable=sysGratuitousARPTable, sfpVendorRev=sfpVendorRev, aclUdfOffsetByte3=aclUdfOffsetByte3, aclL3RuleProtocolMask=aclL3RuleProtocolMask, vlanMacMapVid=vlanMacMapVid, lldpXdot1ConfigVlanNameTable=lldpXdot1ConfigVlanNameTable, aacServerGroupIndex=aacServerGroupIndex, aclL3RuleTcpUdpSrcPort=aclL3RuleTcpUdpSrcPort, doSCtrlMirrorRxRate=doSCtrlMirrorRxRate, cpuFilterL2RuleVlanId=cpuFilterL2RuleVlanId, aclL3RulePortList=aclL3RulePortList, sysGratuitousARPInterval=sysGratuitousARPInterval, swAuthUserPassword=swAuthUserPassword, aacServerIndex=aacServerIndex, impbBindingListTable=impbBindingListTable, igsVlanMulticastGroupIpAddress=igsVlanMulticastGroupIpAddress, rmonAlarmRisingThreshold=rmonAlarmRisingThreshold, vlanTrunkEntry=vlanTrunkEntry, lldpXdot3LocMaxFrameSizeEntry=lldpXdot3LocMaxFrameSizeEntry, companyStaticMAC=companyStaticMAC, dhcpv6RelayOption38=dhcpv6RelayOption38, impbPortDHCPMaxEntryIPv6=impbPortDHCPMaxEntryIPv6, stpRootCost=stpRootCost, aclL2RuleReplace1P=aclL2RuleReplace1P, aclQosIndex=aclQosIndex, syslogServTable=syslogServTable, lldpXdot1LocTable=lldpXdot1LocTable, sfpWavelength=sfpWavelength, multicastVlanRemapPriority=multicastVlanRemapPriority, trustedHostIPType=trustedHostIPType, trafficCtrlTrap=trafficCtrlTrap, rmonAlarmEntry=rmonAlarmEntry, qosDiffServTypeGroup=qosDiffServTypeGroup, dhcpOption12HostName=dhcpOption12HostName, companyTimeRangeMgmt=companyTimeRangeMgmt, impbBindingtrap=impbBindingtrap, multicastVlanIgmpReplaceSourceIp=multicastVlanIgmpReplaceSourceIp, qinqVlanTranslationCVIDTable=qinqVlanTranslationCVIDTable, qosUserPriorityTable=qosUserPriorityTable, qosDiffServType04=qosDiffServType04, qosAclPrioritySettings=qosAclPrioritySettings, portSecIndex=portSecIndex, iPv4swAuthRadiusServerAccountingPort=iPv4swAuthRadiusServerAccountingPort, aclUdfOffsetBase2=aclUdfOffsetBase2, stpAdminPortPathCost=stpAdminPortPathCost, aclL2RuleVlanId=aclL2RuleVlanId, ipv4sysSNTPDSTState=ipv4sysSNTPDSTState, trafficControl=trafficControl, cpuFilterv6L3RuleTrafficClass=cpuFilterv6L3RuleTrafficClass, tftpCfgTargetTftpOperation=tftpCfgTargetTftpOperation, ddmActionPort=ddmActionPort, qosDiffServType53=qosDiffServType53, cpuFilterL2AccessID=cpuFilterL2AccessID, dhcpBOOTPRelayInterfaceSettingsEntry=dhcpBOOTPRelayInterfaceSettingsEntry, limitIpMulticastPortTable=limitIpMulticastPortTable, aacServerIPType=aacServerIPType, ftpFwFTPOperationStatus=ftpFwFTPOperationStatus, swTimeRangeSettingEntry=swTimeRangeSettingEntry, qosDiffServType51=qosDiffServType51, sysLBDCtrlEntry=sysLBDCtrlEntry, ipifVLANname=ipifVLANname, igmpMulticastVlanGroupVid=igmpMulticastVlanGroupVid, multicastVlanGroupStatus=multicastVlanGroupStatus, ipv4cpuFilterProfileIPProtocol=ipv4cpuFilterProfileIPProtocol, stpInstance=stpInstance, snmpV3GroupEntry=snmpV3GroupEntry, ipv4cpuFilterProfileNo=ipv4cpuFilterProfileNo, sysSNTPDSTStartDay=sysSNTPDSTStartDay, aclUdfOffsetByte1=aclUdfOffsetByte1, dlinklldpTxDelay=dlinklldpTxDelay, qosDiffServType17=qosDiffServType17, lldpXdot1LocProtoVlanEnabled=lldpXdot1LocProtoVlanEnabled, errorFramePeriodWindow=errorFramePeriodWindow, qosDiffServType06=qosDiffServType06, snmpV3Host=snmpV3Host, gvrpSettingsIngressChecking=gvrpSettingsIngressChecking, sysSNTPDSTStartMon=sysSNTPDSTStartMon, sysBPDUAttackCtrlTable=sysBPDUAttackCtrlTable, macNotificatiotn=macNotificatiotn, qosDiffServType57=qosDiffServType57, companyTftpGroup=companyTftpGroup, swAuthRadiusServer=swAuthRadiusServer, rmonHistoryInterval=rmonHistoryInterval, aclv6L3RuleTcpUdpDstPortMask=aclv6L3RuleTcpUdpDstPortMask, dhcpBOOTPRelayState=dhcpBOOTPRelayState, mldsHost=mldsHost, autoFdbVlanID=autoFdbVlanID, impbPortDHCPv4VlanList2k=impbPortDHCPv4VlanList2k, igsVlanRouterVlanId=igsVlanRouterVlanId, eoamLinkMonitorIfIndex=eoamLinkMonitorIfIndex, swAuthAuthDirection=swAuthAuthDirection, qosDSCPTOSMode=qosDSCPTOSMode, companyTraps=companyTraps, securityTrafficSeg=securityTrafficSeg, cpuFilterv6L3RuleICMPMessageType=cpuFilterv6L3RuleICMPMessageType, companyBPDUAttack=companyBPDUAttack, sysPortMediaTypeDateCode=sysPortMediaTypeDateCode, mldsVlanFastLeave=mldsVlanFastLeave, lldpXdot3RemLinkAggTable=lldpXdot3RemLinkAggTable, aacLoginMethodListTable=aacLoginMethodListTable, mcastFilterPortTable=mcastFilterPortTable, companyDHCPRelay=companyDHCPRelay, aclUdfOffsetByte2=aclUdfOffsetByte2, aacServerRowStatus=aacServerRowStatus, mstCistVlanMapped2k=mstCistVlanMapped2k, l2PTPortType=l2PTPortType, rmonHistoryIndex=rmonHistoryIndex, ftpConfigFTPOperation=ftpConfigFTPOperation, limitIpMulticastEntryTable=limitIpMulticastEntryTable, aRPSpoofPreventPortList=aRPSpoofPreventPortList, sysTrapIMPBViolation=sysTrapIMPBViolation, stpTopologyChangeTrapStatus=stpTopologyChangeTrapStatus, impbPortNDInspectionState=impbPortNDInspectionState, qosDiffServType59=qosDiffServType59, lldpXdot1LocProtoVlanTable=lldpXdot1LocProtoVlanTable, staticARPIP=staticARPIP, snmpV3UserName=snmpV3UserName, eoamRemoteLoopback=eoamRemoteLoopback, aclProfileMask=aclProfileMask, vlanTrunkSystem=vlanTrunkSystem, aclProfileRuleCount=aclProfileRuleCount, qosDiffServType60=qosDiffServType60, snmpV3Community=snmpV3Community, rmonEventDescription=rmonEventDescription, mldsVlanFilterTable=mldsVlanFilterTable, cpuFilterL3RuleProtocolMask=cpuFilterL3RuleProtocolMask, snmpGlobalState=snmpGlobalState, cpuFilterProfileSrcMacAddrMask=cpuFilterProfileSrcMacAddrMask, qosDiffServType12=qosDiffServType12, ipv4trustedHostIpAddr=ipv4trustedHostIpAddr, qosDiffServType62=qosDiffServType62, stpProtocolVersion=stpProtocolVersion, snmpTrapIMPBv2=snmpTrapIMPBv2, limitIpMulticastPortIPType=limitIpMulticastPortIPType, ddmLowAlarm=ddmLowAlarm, ipv4syslogServEntry=ipv4syslogServEntry, aacAPSSHEnableMethod=aacAPSSHEnableMethod, sfpPortIndex=sfpPortIndex, sshAuthenMethodHostKeyAdmin=sshAuthenMethodHostKeyAdmin, aclL2RuleFilterTimeRange=aclL2RuleFilterTimeRange, qosDiffServType38=qosDiffServType38, mldsVlanRouterEntry=mldsVlanRouterEntry, cpuFilterL3RuleICMPMessageCode=cpuFilterL3RuleICMPMessageCode, duplicateIP=duplicateIP, cpuFilterProfile=cpuFilterProfile, companySTP=companySTP, igsVlanQueryMaxResponseTime=igsVlanQueryMaxResponseTime, qosPriSetPortType=qosPriSetPortType, snmpV3CommunityPolicy=snmpV3CommunityPolicy, lldpXdot1RemProtocolIndex=lldpXdot1RemProtocolIndex, mldsVlanRouterTable=mldsVlanRouterTable, gvrpSettingsGVRPState=gvrpSettingsGVRPState, snmpV3UserPrivProtocol=snmpV3UserPrivProtocol, sysBootupConfigID=sysBootupConfigID, swTimeRangeStartDay=swTimeRangeStartDay, agentMEMutilizationIn5min=agentMEMutilizationIn5min, mldsVlanDataDrivenLearningStatus=mldsVlanDataDrivenLearningStatus, qosDiffServType32=qosDiffServType32, companySfpVendorInfo=companySfpVendorInfo, aacEnableMethod3=aacEnableMethod3, eoamTable=eoamTable, aclv6L3RulePortList=aclv6L3RulePortList, swTimeRangeFriday=swTimeRangeFriday, igsVlanRtrPortList=igsVlanRtrPortList, swAuthRadiusServerInterfaceName=swAuthRadiusServerInterfaceName, pppoePortCircuitIDVendor3String=pppoePortCircuitIDVendor3String, mcastFilterPortEntry=mcastFilterPortEntry, aclL2RuleSrcMacAddrMask=aclL2RuleSrcMacAddrMask, snmpV3TrapDuplicateIPDetected=snmpV3TrapDuplicateIPDetected, companyNeighbor=companyNeighbor, cosClassEntry=cosClassEntry, qosUserPriEntry=qosUserPriEntry, aclL3RuleTcpUrgBit=aclL3RuleTcpUrgBit, aacAccountingServiceCommandOperator=aacAccountingServiceCommandOperator, staticMcastEntry=staticMcastEntry, snmpTrapSNMPAuthentication=snmpTrapSNMPAuthentication)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", cpuFilterL3Rule=cpuFilterL3Rule, impbLogState=impbLogState, mldsVlanReportSuppression=mldsVlanReportSuppression, aclL3RuleTcpUdpDstPortMask=aclL3RuleTcpUdpDstPortMask, ipv4aclProfileDstMacAddrMask=ipv4aclProfileDstMacAddrMask, sysSNTPDSTRepeatStartMon=sysSNTPDSTRepeatStartMon, trustedHostTable=trustedHostTable, staticVlanBaseDisableAutoLearn=staticVlanBaseDisableAutoLearn, cpuFilterL2RuleSrcMacAddrMask=cpuFilterL2RuleSrcMacAddrMask, aclL2RuleDstMacAddrMask=aclL2RuleDstMacAddrMask, aacLoginMethod1=aacLoginMethod1, companyProtocolVlan=companyProtocolVlan, snmpV3TrapLinkUpDown=snmpV3TrapLinkUpDown, sshSessionKeyRekeying=sshSessionKeyRekeying, tftpCfgTargetGroup=tftpCfgTargetGroup, ftpConfigFileName=ftpConfigFileName, stpPortState=stpPortState, cableDiagPair1Status=cableDiagPair1Status, ipv4cpuFilterProfileSrcIpAddrMask=ipv4cpuFilterProfileSrcIpAddrMask, qosDiffServType03=qosDiffServType03, rmonEventTable=rmonEventTable, igsVlanFilterTable=igsVlanFilterTable, aacAccountingServiceShell=aacAccountingServiceShell, limitIpMulticastendIpAddr=limitIpMulticastendIpAddr, lldpXdot3PortConfigEntry=lldpXdot3PortConfigEntry, dhcpv6RelayServerIP=dhcpv6RelayServerIP, pppoePortRemoteIDVendor3String=pppoePortRemoteIDVendor3String, swAuthUser=swAuthUser, sysSerialNumber=sysSerialNumber, qosDiffServType22=qosDiffServType22, swTimeRangeStartHour=swTimeRangeStartHour, sysLBDCtrlTable=sysLBDCtrlTable, mstMstiForcePortState=mstMstiForcePortState, qosDiffServType02=qosDiffServType02, qosDiffServType00=qosDiffServType00, snmpV3TrapIMPBViolation=snmpV3TrapIMPBViolation, impbPortDHCPv6VlanList2k=impbPortDHCPv6VlanList2k, ipv4sysSNTPSecondServer=ipv4sysSNTPSecondServer, swAuthAuthReAuthPeriod=swAuthAuthReAuthPeriod, swAuthRadiusServerStatus=swAuthRadiusServerStatus, impbBlockListPort=impbBlockListPort, impbBlockListEntry=impbBlockListEntry, rmonGlobalState=rmonGlobalState, protocolVlanGroupID=protocolVlanGroupID, syslogServSrvRowStatus=syslogServSrvRowStatus, ipv4cpuFilterProfileSrcMacAddrMask=ipv4cpuFilterProfileSrcMacAddrMask, snmpV3GroupSecurityLevel=snmpV3GroupSecurityLevel, staticARPEntry=staticARPEntry, errorFramePeriodNotifyState=errorFramePeriodNotifyState, stpPortProtocolMigration=stpPortProtocolMigration, sysWebPortNumber=sysWebPortNumber, ftpFwPassword=ftpFwPassword, aacAPTelnetEnableMethod=aacAPTelnetEnableMethod, guestVlanPort=guestVlanPort, sysMACAgingTime=sysMACAgingTime, ipv4aclProfileDstIpAddrMask=ipv4aclProfileDstIpAddrMask, sysLBDInterval=sysLBDInterval, dhcpv6RelayHopCount=dhcpv6RelayHopCount, stpNewRootTraps=stpNewRootTraps, sysGateway=sysGateway, ipifv6DHCPStatus=ipifv6DHCPStatus, igmpMulticastVlanReplacePriority=igmpMulticastVlanReplacePriority, swTimeRangeName=swTimeRangeName, sshUserInfoTable=sshUserInfoTable, staticMcastMac=staticMcastMac, doSCtrlClearFrameCount=doSCtrlClearFrameCount, protocolGroupNameEntry=protocolGroupNameEntry, neighborIPv6Addr=neighborIPv6Addr, agentCPUutilizationIn5min=agentCPUutilizationIn5min, rmonAlarmIndex=rmonAlarmIndex, qosDiffServType35=qosDiffServType35, smtpRecvMailAddrStatus=smtpRecvMailAddrStatus, dhcpServerScreenEnablePortlist=dhcpServerScreenEnablePortlist, limitIpMulticastPortProfileID=limitIpMulticastPortProfileID, impbAutoScanStatus=impbAutoScanStatus, aclL2RuleDstMacAddr=aclL2RuleDstMacAddr, smtpServerAddr=smtpServerAddr, trafficCtrlTable=trafficCtrlTable, authProtocol=authProtocol, igsVlanQueryInterval=igsVlanQueryInterval, igmpMulticastVlanGroupFromIp=igmpMulticastVlanGroupFromIp, rmonHistoryTable=rmonHistoryTable, sysPortDescIndex=sysPortDescIndex, cosWeight=cosWeight, staticMcastTable=staticMcastTable, macBasedVlanTable=macBasedVlanTable, aclv6L3RuleTcpUrgBit=aclv6L3RuleTcpUrgBit, dlinklldpReinitDelay=dlinklldpReinitDelay, impbAutoScanPort=impbAutoScanPort, lldpXdot3LocPowerPortClass=lldpXdot3LocPowerPortClass, aclPacketRuleStatus=aclPacketRuleStatus, sysContactName=sysContactName, lldpXdot1ConfigPortVlanEntry=lldpXdot1ConfigPortVlanEntry, floodfdbOnOff=floodfdbOnOff, eoamDyingGaspEnable=eoamDyingGaspEnable, cableDiagPortIndex=cableDiagPortIndex, impbVlanModeState=impbVlanModeState, snmpV3HostStatus=snmpV3HostStatus, tftpFwTargetTftpOperationStatus=tftpFwTargetTftpOperationStatus, lldpXdot3RemLinkAggStatus=lldpXdot3RemLinkAggStatus, duldMode=duldMode, ipv4aclProfileMask=ipv4aclProfileMask, ipv4cpuFilterProfileDstPortMask=ipv4cpuFilterProfileDstPortMask, vlanTrunkIfIndex=vlanTrunkIfIndex, staticEntry=staticEntry, ftpFwServerIpAddress=ftpFwServerIpAddress, portSecTable=portSecTable, aclv6L3RuleStatus=aclv6L3RuleStatus, igsVlanSnoopStatus=igsVlanSnoopStatus, aclL3RuleTcpUdpDstPort=aclL3RuleTcpUdpDstPort, aclL2ProfileID=aclL2ProfileID, autologoutConfiguration=autologoutConfiguration, portSecLockAddrMode=portSecLockAddrMode, sysPortMediaTypeEntry=sysPortMediaTypeEntry, l2PTThresholdEntry=l2PTThresholdEntry, mldsHostTablePort=mldsHostTablePort, stpPort=stpPort, aacLocalEnablePassword=aacLocalEnablePassword, swAuthAuthConfigPortNumber=swAuthAuthConfigPortNumber, mstInstanceIndex=mstInstanceIndex, mldsHostTableVLANID=mldsHostTableVLANID, aclQosIP6TC=aclQosIP6TC, l2PTState=l2PTState, ipv4trustedHostTable=ipv4trustedHostTable, portSecMLA=portSecMLA, swAuthRadiusServerRetransmit=swAuthRadiusServerRetransmit, mldsVlanQuerier=mldsVlanQuerier, mstCistPortDesignatedBridge=mstCistPortDesignatedBridge, aacServerInfoTable=aacServerInfoTable, swAuthPortAccessControlEntry=swAuthPortAccessControlEntry, sysPortMediaTypeIndex=sysPortMediaTypeIndex, aacLoginMethodListName=aacLoginMethodListName, dhcpBOOTPRelayOption82CircuitIDType=dhcpBOOTPRelayOption82CircuitIDType, ipv4aclProfileDstPortMask=ipv4aclProfileDstPortMask, qosDiffServType16=qosDiffServType16, aclFlowMeterAction=aclFlowMeterAction, stpFowardBPDU=stpFowardBPDU, trustedHostIpMask=trustedHostIpMask, aacServerAuthKey=aacServerAuthKey, cableDiagPair4Status=cableDiagPair4Status, mstCistPortPathCost=mstCistPortPathCost, ipv4sysSNTPDSTStartHour=ipv4sysSNTPDSTStartHour, portSecFDBPermIndex=portSecFDBPermIndex, ipv4aclProfileIPProtocolMask=ipv4aclProfileIPProtocolMask, lldpXdot1Objects=lldpXdot1Objects, mstCistCurrentPortRole=mstCistCurrentPortRole, smtpState=smtpState, igsVlanDataDrivenLearningStatus=igsVlanDataDrivenLearningStatus, syslogServUDPport=syslogServUDPport, swTimeRangeStartMonth=swTimeRangeStartMonth, rmonAlarmFallingThreshold=rmonAlarmFallingThreshold, aclProfileDstMacAddrMask=aclProfileDstMacAddrMask, impbPortAllowZeroIPState=impbPortAllowZeroIPState, cpuFilterL3RuleEntry=cpuFilterL3RuleEntry, ipv4aclUdfOffsetMask1=ipv4aclUdfOffsetMask1, staticVlanBaseAutoLearnList1k=staticVlanBaseAutoLearnList1k, mstInstanceVlanMapped=mstInstanceVlanMapped, ipv4syslogServFacility=ipv4syslogServFacility, aclPacketProfileID=aclPacketProfileID, qosDiffServType20=qosDiffServType20, sshMaxAuthFailAttempts=sshMaxAuthFailAttempts, aacEnableMethod2=aacEnableMethod2, sysMirrorCtrlIngressMirroring=sysMirrorCtrlIngressMirroring, rmonAlarmSampleType=rmonAlarmSampleType, multicastVlanGroupIpType=multicastVlanGroupIpType, sysBPDUAttackPortMode=sysBPDUAttackPortMode, sysPortCtrlTable=sysPortCtrlTable, snmpV3UserEntry=snmpV3UserEntry, sysSNTPDSTRepeatEndMon=sysSNTPDSTRepeatEndMon, tftpCfgTargetTftpIncrement=tftpCfgTargetTftpIncrement, mstMstiPortPathCost=mstMstiPortPathCost, aclFlowMeterRule=aclFlowMeterRule, cpuFilterL2Rule=cpuFilterL2Rule, securityIpMacPortBinding=securityIpMacPortBinding, sysSNTPSecondInterfaceName=sysSNTPSecondInterfaceName, smtpSelfMailAddr=smtpSelfMailAddr, snmpV3Group=snmpV3Group, mstMstiPortAdminPathCost=mstMstiPortAdminPathCost, cosBandwidthEffectiveRX=cosBandwidthEffectiveRX, dot1qVlanPVIDAutoAssignOnOff=dot1qVlanPVIDAutoAssignOnOff, mstCistVlanMapped3k=mstCistVlanMapped3k, vlanTrunkState=vlanTrunkState, swAuthAuthMaxReq=swAuthAuthMaxReq, dhcpLocalRelayTable=dhcpLocalRelayTable, aclv6L3RuleTrafficClass=aclv6L3RuleTrafficClass, ftpConfigFTPOperationStatus=ftpConfigFTPOperationStatus, limitIpMulticastPortMaxGrp=limitIpMulticastPortMaxGrp, impbPortIpInspectionState=impbPortIpInspectionState, ftpFwPort=ftpFwPort, aclv6L3RuleSrcIpAddr=aclv6L3RuleSrcIpAddr, ddmThresholdPort=ddmThresholdPort, igmpMulticastVlanEntry=igmpMulticastVlanEntry, companyFTPGroup=companyFTPGroup, aclL2RuleVlanIdMask=aclL2RuleVlanIdMask, companyStaticARP=companyStaticARP, tftpCfgTargetTftpConfigID=tftpCfgTargetTftpConfigID, igsVlanFilterVlanId=igsVlanFilterVlanId, sysLBDVlanLoopTable=sysLBDVlanLoopTable, sysDhcpAutoImage=sysDhcpAutoImage, sysTrapStatus=sysTrapStatus, mldsVlanMulticastGroupMacAddress=mldsVlanMulticastGroupMacAddress, sysPortCtrlOperStatus=sysPortCtrlOperStatus, dhcpBOOTPRelayOption82RemoteIDType=dhcpBOOTPRelayOption82RemoteIDType, LldpManAddress=LldpManAddress, ddmHighWarning=ddmHighWarning, gvrpSettingsAcceptableFrameType=gvrpSettingsAcceptableFrameType, ddmActionMgmtTable=ddmActionMgmtTable, qosDiffServType50=qosDiffServType50, lldpXdot3RemPowerMDISupported=lldpXdot3RemPowerMDISupported, protocolVlanTable=protocolVlanTable, snmpV3UserStatus=snmpV3UserStatus, lldpXdot1LocVlanNameEntry=lldpXdot1LocVlanNameEntry, sysSNTPDSTEndDay=sysSNTPDSTEndDay, aclL2Rule1pPriority=aclL2Rule1pPriority, stpBridgeMaxAge=stpBridgeMaxAge, aclL2AccessID=aclL2AccessID, gvrpSettingsPVID=gvrpSettingsPVID, staticVlanID=staticVlanID, ipv4sysSNTPDSTEndHour=ipv4sysSNTPDSTEndHour, aacAccountingMethodListRowStatus=aacAccountingMethodListRowStatus, cpuFilterL2RuleEtherType=cpuFilterL2RuleEtherType, ipv4smtpRecvMailAddrStatus=ipv4smtpRecvMailAddrStatus, impbAutoScanMacAddress=impbAutoScanMacAddress, lldpXdot1ConfigPortVlanTxEnable=lldpXdot1ConfigPortVlanTxEnable, impbPortDHCPMaxEntryIPv4=impbPortDHCPMaxEntryIPv4, ipv4syslogServSrvRowStatus=ipv4syslogServSrvRowStatus, mstConfigurationIdentification=mstConfigurationIdentification, tftpCfgTargetImageFileName=tftpCfgTargetImageFileName, oldDesignatedRoot=oldDesignatedRoot, dhcpBOOTPRelayOption82Policy=dhcpBOOTPRelayOption82Policy, mstCistVlanMapped=mstCistVlanMapped, swAuthAuthTxPeriod=swAuthAuthTxPeriod, aacAccountingServiceCommandAdministrator=aacAccountingServiceCommandAdministrator, sfpVendorName=sfpVendorName, aclUdfOffsetByte4=aclUdfOffsetByte4, iPv4swAuthRadiusServerKey=iPv4swAuthRadiusServerKey, snmpV3ViewTreeTable=snmpV3ViewTreeTable, cpuFilterL3RuleAccessID=cpuFilterL3RuleAccessID, filterDHCPServerVlanList=filterDHCPServerVlanList, impbAutoScanIpAddressFrom=impbAutoScanIpAddressFrom, laPortControlTable=laPortControlTable, dhcpBOOTPRelayOption82State=dhcpBOOTPRelayOption82State, aclv6L3RuleProtocol=aclv6L3RuleProtocol, sysSNTPSecondServer=sysSNTPSecondServer, dhcpv6RelayInterfaceSettingsRowStatus=dhcpv6RelayInterfaceSettingsRowStatus, mldsVlanQueryInterval=mldsVlanQueryInterval, stpBridgeForwardDelay=stpBridgeForwardDelay, mldsVlanFilterVlanId=mldsVlanFilterVlanId, companyTrafficMgmt=companyTrafficMgmt, ipv4snmpV3HostAddress=ipv4snmpV3HostAddress, sysBPDUAttackPortState=sysBPDUAttackPortState, des_1210_28mebx=des_1210_28mebx, sysPortMediaTypePn=sysPortMediaTypePn, aacServerInterfaceName=aacServerInterfaceName)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", laPortChannelTable=laPortChannelTable, mldsVlanMulticastGroupPortList=mldsVlanMulticastGroupPortList, rmonHistoryOwner=rmonHistoryOwner, sysBPDUAttackLog=sysBPDUAttackLog, aacAPConsoleEnableMethod=aacAPConsoleEnableMethod, multicastVlanMemberPort=multicastVlanMemberPort, cableDiagPair2Length=cableDiagPair2Length, qosEffectiveDefaultPriority=qosEffectiveDefaultPriority, ipv4aclQosTCPUDPPort=ipv4aclQosTCPUDPPort, sysPortCtrlSpeed=sysPortCtrlSpeed, igmpMulticastVlanTagMemberPort=igmpMulticastVlanTagMemberPort, ddmPowerUnit=ddmPowerUnit, sysTrapDHCPServerScreening=sysTrapDHCPServerScreening, ipv4syslogServIndex=ipv4syslogServIndex, lldpXdot3RemPowerPairs=lldpXdot3RemPowerPairs, igsVlanMulticastGroupEntry=igsVlanMulticastGroupEntry, aclProfileSrcIpAddrMaskType=aclProfileSrcIpAddrMaskType, cpuFilterv6L3RuleStatus=cpuFilterv6L3RuleStatus, lldpXdot3LocLinkAggEntry=lldpXdot3LocLinkAggEntry, qosDiffServType05=qosDiffServType05, dhcpServerScreenLogSuppressDuration=dhcpServerScreenLogSuppressDuration, dhcpv6RelayOption37RemoteID=dhcpv6RelayOption37RemoteID, sysBPDUAttackCtrlIndex=sysBPDUAttackCtrlIndex, lldpXdot3Config=lldpXdot3Config, iPv4aacServerInfoEntry=iPv4aacServerInfoEntry, mldsVlanQueryMaxResponseTime=mldsVlanQueryMaxResponseTime, aclL3RuleICMPMessageCode=aclL3RuleICMPMessageCode, staticARPTable=staticARPTable, LldpPortNumber=LldpPortNumber, lldpXdot1RemoteData=lldpXdot1RemoteData, mstiRevisionLevel=mstiRevisionLevel, sslCipherSuiteList=sslCipherSuiteList, sysTrapIP=sysTrapIP, cpuFilterv6L3RuleTable=cpuFilterv6L3RuleTable, cosBandwidthCtrlClassIndex=cosBandwidthCtrlClassIndex, mldsVlanSnoopStatus=mldsVlanSnoopStatus, aclPacketRuleTable=aclPacketRuleTable, protocolGroupTable=protocolGroupTable, stpPortFowardBPDU=stpPortFowardBPDU, cpuFilterProfileIPProtocol=cpuFilterProfileIPProtocol, ipv4aclQosMACAddr=ipv4aclQosMACAddr, sslSecurityHttpStatus=sslSecurityHttpStatus, aclL3RuleReplaceDSCP=aclL3RuleReplaceDSCP, snmpV3viewTreeStatus=snmpV3viewTreeStatus, protocolGroupGID=protocolGroupGID, snmpV3GroupWriteViewName=snmpV3GroupWriteViewName, aacServerAuthProtocol=aacServerAuthProtocol, dhcpLocalRelaySettingsState=dhcpLocalRelaySettingsState, dhcpBOOTPRelayControl=dhcpBOOTPRelayControl, cableDiagAction=cableDiagAction, aacServerInfoEntry=aacServerInfoEntry, neighborTable=neighborTable, eoamLinkMonitor=eoamLinkMonitor, ipv4aclUdfOffsetMask3=ipv4aclUdfOffsetMask3, qosDiffServType25=qosDiffServType25, securityDhcpServerScreen=securityDhcpServerScreen, sfpVendorInfoEntry=sfpVendorInfoEntry, multicastVlanReplacePriority=multicastVlanReplacePriority, ipv4sysSNTPFirstServer=ipv4sysSNTPFirstServer, sshUserInfoUserName=sshUserInfoUserName, mstCistForcePortState=mstCistForcePortState, dhcpBOOTPRelayOption82RemoteID=dhcpBOOTPRelayOption82RemoteID, ipv4sysIpAddrCfgMode=ipv4sysIpAddrCfgMode, aclProfileSrcPortMask=aclProfileSrcPortMask, cpuFilterL3RuleTcpRstBit=cpuFilterL3RuleTcpRstBit, mcastFilterPortIndex=mcastFilterPortIndex, cpuFilterL2RuleStatus=cpuFilterL2RuleStatus, mcastFilterPortType=mcastFilterPortType, impbAutoScanVlanId=impbAutoScanVlanId, impbAutoScanCurrentStatus=impbAutoScanCurrentStatus, qosDiffServType45=qosDiffServType45, cosBandwidthValue=cosBandwidthValue, lldpXdot3LocPortOperMauType=lldpXdot3LocPortOperMauType, mldsRouterPortPurgeInterval=mldsRouterPortPurgeInterval, aacLoginMethodListEntry=aacLoginMethodListEntry, ftpFwPath=ftpFwPath, tftpCfgServerIpAddress=tftpCfgServerIpAddress, staticVlanBaseAutoLearnList2k=staticVlanBaseAutoLearnList2k, aclL3RuleReplaceQueue=aclL3RuleReplaceQueue, companyLLDPSetting=companyLLDPSetting, laPortActorTimeout=laPortActorTimeout, iPv4aacServerIndex=iPv4aacServerIndex, cpuFilterL3RuleStatus=cpuFilterL3RuleStatus, snmpV3UserGroupName=snmpV3UserGroupName, aclProfile=aclProfile, snmpV3TrapRSTPStateChange=snmpV3TrapRSTPStateChange, rmonStatsTable=rmonStatsTable, swAuthRadiusServerIndex=swAuthRadiusServerIndex, lldpXdot1RemProtoVlanEntry=lldpXdot1RemProtoVlanEntry, aacEnableMethod4=aacEnableMethod4, cpuFilterL3RuleTcpUdpSrcPortMask=cpuFilterL3RuleTcpUdpSrcPortMask, autoFdbIPAddress=autoFdbIPAddress, qosDefaultUserPriEntry=qosDefaultUserPriEntry, limitIpMulticastProfileStatus=limitIpMulticastProfileStatus, aclL2RuleInPortList=aclL2RuleInPortList, lldpXdot1RemProtoVlanId=lldpXdot1RemProtoVlanId, lldpXdot1RemProtocolTable=lldpXdot1RemProtocolTable, macBasedVlanEntry=macBasedVlanEntry, newRootMSTibridgeregionalroot=newRootMSTibridgeregionalroot, dhcpv6RelayInterface=dhcpv6RelayInterface, aclFlowMeterStatus=aclFlowMeterStatus, ipv4smtpRecvMailAddrIndex=ipv4smtpRecvMailAddrIndex, sysPortDescMediumType=sysPortDescMediumType, mstInstanceVlanMapped2k=mstInstanceVlanMapped2k, swAuthUserTable=swAuthUserTable, sysFirmwareVersion=sysFirmwareVersion, aclQosAssignClass=aclQosAssignClass, swTimeRangeEndMonth=swTimeRangeEndMonth, tftpConfigTftpOperation=tftpConfigTftpOperation, mstCistPortAdminPathCost=mstCistPortAdminPathCost, ddmTxPower=ddmTxPower, miscReset=miscReset, companyDuld=companyDuld, lldpPortConfigTLVsTxEnable=lldpPortConfigTLVsTxEnable, aacAPConsoleLoginMethod=aacAPConsoleLoginMethod, sysPortUpLinkTime=sysPortUpLinkTime, aacEnableMethodListTable=aacEnableMethodListTable, duldSystem=duldSystem, syslogEnable=syslogEnable, sysPortErrTable=sysPortErrTable, cableDiagPair4Length=cableDiagPair4Length, ipv4sysIpSubnetMask=ipv4sysIpSubnetMask, swAuthAuthCapability=swAuthAuthCapability, companyMiscGroup=companyMiscGroup, telnetUDPPort=telnetUDPPort, qosDiffServType63=qosDiffServType63, qosDiffServType28=qosDiffServType28, lldpXdot1RemProtoVlanEnabled=lldpXdot1RemProtoVlanEnabled, igsHostTablePort=igsHostTablePort, qosDiffServType07=qosDiffServType07, cosBandwidthCtrlPortIndex=cosBandwidthCtrlPortIndex, lldpXdot1ConfigProtocolTxEnable=lldpXdot1ConfigProtocolTxEnable, telnetsettingManagementOnOff=telnetsettingManagementOnOff, rmonEventIndex=rmonEventIndex, rmonStatsDataSource=rmonStatsDataSource, companySecurity=companySecurity, mstSetVlanList=mstSetVlanList, sshAuthenMethodPassWordAdmin=sshAuthenMethodPassWordAdmin, snmpV3TrapBPDUAttack=snmpV3TrapBPDUAttack, sfpTranceiverCode=sfpTranceiverCode, swAuthMode=swAuthMode, dhcpServerScreenEnableVlanlist=dhcpServerScreenEnableVlanlist, staticMcastEgressPorts=staticMcastEgressPorts, qosDiffServType15=qosDiffServType15, igsVlanRouterEntry=igsVlanRouterEntry, dhcpv6RelayOption18CheckState=dhcpv6RelayOption18CheckState, aclL2RuleReplaceDSCP=aclL2RuleReplaceDSCP, igmpMulticastVlanTable=igmpMulticastVlanTable, lldpXdot1LocPortVlanId=lldpXdot1LocPortVlanId, ipv4smtpRecvMailAddrEntry=ipv4smtpRecvMailAddrEntry, ipv4syslogServTable=ipv4syslogServTable, doSCtrlMirrorReplace1P=doSCtrlMirrorReplace1P, limitIpMulticastProfileEntry=limitIpMulticastProfileEntry, sysIpAddr=sysIpAddr, ipv4cpuFilterProfileIPProtocolMask=ipv4cpuFilterProfileIPProtocolMask, cpuFilterL3RuleTcpUdpDstPortMask=cpuFilterL3RuleTcpUdpDstPortMask, cpuFilterL2RuleSrcMacAddr=cpuFilterL2RuleSrcMacAddr, mstMstiPortPriority=mstMstiPortPriority, aclFlowMeterProfileID=aclFlowMeterProfileID, qosTOSType04=qosTOSType04, rmonAlarmInterval=rmonAlarmInterval, aclUdfOffsetMask1=aclUdfOffsetMask1, rmonAlarmRisingEventIndex=rmonAlarmRisingEventIndex, snmpV3HostVersion=snmpV3HostVersion, eoamLinkMonitorEntry=eoamLinkMonitorEntry, dhcpLocalRelayEnablePortlist=dhcpLocalRelayEnablePortlist, swAuthRadiusServerKey=swAuthRadiusServerKey, staticTable=staticTable, companySyslog=companySyslog, qosDiffServType36=qosDiffServType36, sysSNTPDSTRepeatStartWeek=sysSNTPDSTRepeatStartWeek, aclv6L3RuleProfileNo=aclv6L3RuleProfileNo, cpuFilterv6L3RuleICMPMessageCode=cpuFilterv6L3RuleICMPMessageCode, cableDiagPair3Status=cableDiagPair3Status, aclPacketRuleOffsetValue2Mask=aclPacketRuleOffsetValue2Mask, tftpConfigFileName=tftpConfigFileName, dot1qVlanForbiddenPorts=dot1qVlanForbiddenPorts, multicastVlanSourcePort=multicastVlanSourcePort, stpBridgePriority=stpBridgePriority, sysJumboFrameEnable=sysJumboFrameEnable, ipv4sysSNTPDSTStartMon=ipv4sysSNTPDSTStartMon, lldpXdot3LocPortAutoNegSupported=lldpXdot3LocPortAutoNegSupported, dhcpv6RelayOpt38PortIndex=dhcpv6RelayOpt38PortIndex, trustedHostRowStatus=trustedHostRowStatus, syslogServInterfaceName=syslogServInterfaceName, limitIpMulticastPortState=limitIpMulticastPortState, companySMTP=companySMTP, portSecFDBPermanentEntry=portSecFDBPermanentEntry, neighborEntry=neighborEntry, cpuFilterv6L3RuleTcpUdpDstPort=cpuFilterv6L3RuleTcpUdpDstPort, lldpXdot3LocPortEntry=lldpXdot3LocPortEntry, mldsHostEntry=mldsHostEntry, igsHostPortPurgeInterval=igsHostPortPurgeInterval, snmpV3TrapPortSecurity=snmpV3TrapPortSecurity, sysPortErrPortState=sysPortErrPortState, lldpXdot1RemVlanNameTable=lldpXdot1RemVlanNameTable, dhcpBOOTPRelayHopCount=dhcpBOOTPRelayHopCount, impbBlockListVlanId=impbBlockListVlanId, ddmActionMgmtEntry=ddmActionMgmtEntry, stpPortHelloTime=stpPortHelloTime, RmonStatus=RmonStatus, cpuFilterL3RuleProfileNo=cpuFilterL3RuleProfileNo, ddmRxPower=ddmRxPower, ipv4aclQosTable=ipv4aclQosTable, cpuFilterv6L3RuleTcpUdpSrcPortMask=cpuFilterv6L3RuleTcpUdpSrcPortMask, ddmCtrl=ddmCtrl, companyLimitIp=companyLimitIp, syslogServerGroup=syslogServerGroup, sysType=sysType, sysCommandLogging=sysCommandLogging, igsVlanQuerier=igsVlanQuerier, qosDiffServType21=qosDiffServType21, aacServerAccountingPort=aacServerAccountingPort, ipv4aclQosIndex=ipv4aclQosIndex, snmpV3HostCommunityName=snmpV3HostCommunityName, lldpXdot1RemProtocolEntry=lldpXdot1RemProtocolEntry, impbAutoScanBinding=impbAutoScanBinding, eoamState=eoamState, sysLBDVlanLoopIndex=sysLBDVlanLoopIndex, vlanMacStatus=vlanMacStatus, trafficSegIfIndex=trafficSegIfIndex, qinqVlanTranslationCVIDRowStatus=qinqVlanTranslationCVIDRowStatus, multicastVlanEntry=multicastVlanEntry, igmpMulticastVlanGroupTable=igmpMulticastVlanGroupTable, cpuFilterL2RuleEntry=cpuFilterL2RuleEntry, duldDiscoveryTime=duldDiscoveryTime, doSCtrlTable=doSCtrlTable, aacEnableMethodListName=aacEnableMethodListName, igsRouterPortPurgeInterval=igsRouterPortPurgeInterval, dhcpBOOTPRelayServerIP=dhcpBOOTPRelayServerIP, syslogSettingGroup=syslogSettingGroup, snmpTrapRSTPStateChange=snmpTrapRSTPStateChange, dhcpv6RelayOpt38PortType=dhcpv6RelayOpt38PortType, ipv4syslogServSeverity=ipv4syslogServSeverity, swAuthRadiusServerAccountingPort=swAuthRadiusServerAccountingPort, aclv6L3RuleTcpPshBit=aclv6L3RuleTcpPshBit, limitIpMulticaststartIpAddr=limitIpMulticaststartIpAddr, dosCtrlTrapLogState=dosCtrlTrapLogState, cosScheduleMechanism=cosScheduleMechanism, lldpXdot3LocPowerClass=lldpXdot3LocPowerClass, guestVlanDelState=guestVlanDelState, impbAutoScanEntry=impbAutoScanEntry, autoFdbTable=autoFdbTable, lldpXdot1RemVlanName=lldpXdot1RemVlanName, sysSNTPDSTEndMon=sysSNTPDSTEndMon, ipv4aclProfileSrcIpAddrMask=ipv4aclProfileSrcIpAddrMask, impbPortDHCPv4VlanList1k=impbPortDHCPv4VlanList1k, lldpXdot1ConfigProtoVlanTxEnable=lldpXdot1ConfigProtoVlanTxEnable, qosDiffServType19=qosDiffServType19, l2PTThresholdTable=l2PTThresholdTable, ipifV6AddressIpPrefix=ipifV6AddressIpPrefix, swTimeRangeStartMinute=swTimeRangeStartMinute, snmpTrapLBD=snmpTrapLBD, aclProfileType=aclProfileType)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", cpuFilterL3RuleICMPMessageType=cpuFilterL3RuleICMPMessageType, pppoePortState=pppoePortState, companyVLANTrunk=companyVLANTrunk, snmpV3UserTable=snmpV3UserTable, sysSNTPDSTRepeatStartHour=sysSNTPDSTRepeatStartHour, aclv6L3RuleICMPMessageType=aclv6L3RuleICMPMessageType, sysPortMediaTypeRev=sysPortMediaTypeRev, mstiBridgeRegionalRoot=mstiBridgeRegionalRoot, mldsHostPortPurgeInterval=mldsHostPortPurgeInterval, dot1qVlanUntaggedPorts=dot1qVlanUntaggedPorts, lldpXdot1LocProtocolTable=lldpXdot1LocProtocolTable, igmpMulticastVlanReplaceSourceIp=igmpMulticastVlanReplaceSourceIp, dhcpLocalRelaySettingsVLANID=dhcpLocalRelaySettingsVLANID, aclQosEntry=aclQosEntry, igsVlanReportSuppression=igsVlanReportSuppression, laAlgorithm=laAlgorithm, swAuthUserStatus=swAuthUserStatus, companyRMON=companyRMON, dhcpBOOTPRelayInterfaceSettingsTable=dhcpBOOTPRelayInterfaceSettingsTable, companyQinQ=companyQinQ, aclL3RuleProfileNo=aclL3RuleProfileNo, rmonEventCommunity=rmonEventCommunity, sysSNTPDSTOffset=sysSNTPDSTOffset, aclProfileDstIpAddrMask=aclProfileDstIpAddrMask, sysFromIP=sysFromIP, swAuthPortAccessCtrl=swAuthPortAccessCtrl, qinqVLANTranslation=qinqVLANTranslation, ipv4smtpRecvMailAddrTable=ipv4smtpRecvMailAddrTable, ftpFwUsername=ftpFwUsername, bandwidthCtrlTable=bandwidthCtrlTable, vlanMacMapAddrMask=vlanMacMapAddrMask, igmpMulticastVlanRemapPriority=igmpMulticastVlanRemapPriority, qosDiffServType27=qosDiffServType27, lldpXdot1LocEntry=lldpXdot1LocEntry, cpuFilterv6L3RuleTcpRstBit=cpuFilterv6L3RuleTcpRstBit, cpuFilterL3RuleTcpUdpSrcPort=cpuFilterL3RuleTcpUdpSrcPort, iPv4aacServerIPAddr=iPv4aacServerIPAddr, dhcpv6RelayOption18InterfaceIDType=dhcpv6RelayOption18InterfaceIDType, smtpServerAddrType=smtpServerAddrType, mldsVlanGrpQueryInterval=mldsVlanGrpQueryInterval, aclQosTCPUDPPort=aclQosTCPUDPPort, sysFirmwareInfomation=sysFirmwareInfomation, swTimeRangeRowStatus=swTimeRangeRowStatus, ddmStatusPort=ddmStatusPort, lldpXdot1ConfigProtocolTable=lldpXdot1ConfigProtocolTable, aclL3RuleDstIpAddrMask=aclL3RuleDstIpAddrMask, doSCtrlEntry=doSCtrlEntry, dhcpBOOTPRelayManagement=dhcpBOOTPRelayManagement, eoamMode=eoamMode, aacLoginMethod3=aacLoginMethod3, impbAutoScanTable=impbAutoScanTable, aclQosVlanID=aclQosVlanID, ipv4aclQosType=ipv4aclQosType, multicastVlanGroupVid=multicastVlanGroupVid, stpForwardDelay=stpForwardDelay, iPv4aacServerRowStatus=iPv4aacServerRowStatus, igmpMulticastVlanStatus=igmpMulticastVlanStatus, lldpXdot3LocPortAutoNegAdvertisedCap=lldpXdot3LocPortAutoNegAdvertisedCap, sysPortCtrlFlowControlOper=sysPortCtrlFlowControlOper, mldsStatus=mldsStatus, aacAPSSHLoginMethod=aacAPSSHLoginMethod, ipv4trustedHostRowStatus=ipv4trustedHostRowStatus, pppoePortIndex=pppoePortIndex, sshUserInfoHostName=sshUserInfoHostName, aclPacketAccessID=aclPacketAccessID, snmpV3UserPrivProtocolPassword=snmpV3UserPrivProtocolPassword, sysTrapPortSecurity=sysTrapPortSecurity, d_link=d_link, swAuthRadiusIPType=swAuthRadiusIPType, aacEnableMethod1=aacEnableMethod1, macNotifyInfo=macNotifyInfo, iPv4swAuthRadiusServerTable=iPv4swAuthRadiusServerTable, lldpXdot1RemVlanId=lldpXdot1RemVlanId, stpPortRestrictedTCN=stpPortRestrictedTCN, aclv6L3RuleFilterTimeRange=aclv6L3RuleFilterTimeRange, dot1qVlanManagementid=dot1qVlanManagementid, qosUserPriClass=qosUserPriClass, aclUdfOffsetBase1=aclUdfOffsetBase1, aclPacketRuleFilterTimeRange=aclPacketRuleFilterTimeRange, multicastVlanState=multicastVlanState, aclUdfOffsetBase4=aclUdfOffsetBase4, companyMacNotify=companyMacNotify, companyCableDiagnostic=companyCableDiagnostic, mldsHostTableGroupAddress=mldsHostTableGroupAddress, autoFdbStatus=autoFdbStatus, snmpV3CommunityEntry=snmpV3CommunityEntry, ipv4aclQosEntry=ipv4aclQosEntry, swAuthAuthReAuthentication=swAuthAuthReAuthentication, gvrpSettingsLeaveTime=gvrpSettingsLeaveTime, ipv4smtpSelfMailAddr=ipv4smtpSelfMailAddr, lldpXdot1Config=lldpXdot1Config, aacAuthenAdminState=aacAuthenAdminState, qosDiffServType43=qosDiffServType43, lldpXdot1LocVlanId=lldpXdot1LocVlanId, filterDHCPServerEntry=filterDHCPServerEntry, cpuFilterv6L3RuleTcpUdpSrcPort=cpuFilterv6L3RuleTcpUdpSrcPort, LldpPowerPortClass=LldpPowerPortClass, trafficCtrlCountDown=trafficCtrlCountDown, sysSNTPDSTRepeatStartWeekDay=sysSNTPDSTRepeatStartWeekDay, aclL3RuleICMPMessageType=aclL3RuleICMPMessageType, mstCistStatus=mstCistStatus, sysIpSubnetMask=sysIpSubnetMask, ddmStatusEntry=ddmStatusEntry, aacServerIPAddr=aacServerIPAddr, snmpV3UserVersion=snmpV3UserVersion, mldsHostTableHostIPAddress=mldsHostTableHostIPAddress, aclProfileDstIpAddrMaskType=aclProfileDstIpAddrMaskType, lldpXdot3LocPortTable=lldpXdot3LocPortTable, agentMEMutilizationIn5sec=agentMEMutilizationIn5sec, igsVlanCfgQuerier=igsVlanCfgQuerier, doSCtrlFrameCount=doSCtrlFrameCount, aclPacketRuleOffsetValue1=aclPacketRuleOffsetValue1, cosClassIndex=cosClassIndex, errorFrameWindow=errorFrameWindow, mldsVlanMulticastGroupEntry=mldsVlanMulticastGroupEntry, aacServerGroupRowStatus=aacServerGroupRowStatus, rmonStatsOwner=rmonStatsOwner, snmpV3TrapWarmStart=snmpV3TrapWarmStart, macNotifyInterval=macNotifyInterval, sysVersion=sysVersion, sysSafeGuardEnable=sysSafeGuardEnable, portSecState=portSecState, cpuFilterv6L3RuleSrcIpAddr=cpuFilterv6L3RuleSrcIpAddr, qinqGlobalStatus=qinqGlobalStatus, sysTrapDuplicateIPDetected=sysTrapDuplicateIPDetected, sysLBDVlanLoopPorts=sysLBDVlanLoopPorts, qinqTable=qinqTable, aRPSpoofPreventTable=aRPSpoofPreventTable, companyEoam=companyEoam, protocolGroupRowStatus=protocolGroupRowStatus, agentMEMutilization=agentMEMutilization, dhcpBOOTPRelayEnablePortlist=dhcpBOOTPRelayEnablePortlist, swTimeRangeSaturday=swTimeRangeSaturday, mstiConfigurationName=mstiConfigurationName, dhcpBOOTPRelayInterfaceSettingsRowStatus=dhcpBOOTPRelayInterfaceSettingsRowStatus, cosBandwidthCtrlTable=cosBandwidthCtrlTable, vlanMacMapAddr=vlanMacMapAddr, eoamSystem=eoamSystem, aclL3RuleProtocol=aclL3RuleProtocol, tftpFwTargetServerIpType=tftpFwTargetServerIpType, staticDisableAutoLearn=staticDisableAutoLearn, traps=traps, aclUdfOffsetMask3=aclUdfOffsetMask3, staticMcastIpAddr=staticMcastIpAddr, multicastVlanid=multicastVlanid, errorFrameSecondsWindow=errorFrameSecondsWindow, lldpXdot1ConfigVlanNameEntry=lldpXdot1ConfigVlanNameEntry, impbPortDHCPv6VlanList4k=impbPortDHCPv6VlanList4k, cpuFilterv6L3RuleTcpAckBit=cpuFilterv6L3RuleTcpAckBit, lldpXdot3LocPowerPairControlable=lldpXdot3LocPowerPairControlable, agentCPUutilizationIn5sec=agentCPUutilizationIn5sec, qosDiffServType61=qosDiffServType61, sfpVendorPn=sfpVendorPn, staticVlanBaseTable=staticVlanBaseTable, lldpXdot3PortConfigTLVsTxEnable=lldpXdot3PortConfigTLVsTxEnable, stpBridgeHelloTime=stpBridgeHelloTime, macNotifyInfoDiscription=macNotifyInfoDiscription, lldpXdot3LocMaxFrameSizeTable=lldpXdot3LocMaxFrameSizeTable, aclProfileDstPortMask=aclProfileDstPortMask, sysPortCtrlEntry=sysPortCtrlEntry, aclPacketRuleRateLimit=aclPacketRuleRateLimit, ipv4aclProfileSrcPortMask=ipv4aclProfileSrcPortMask, ipifSupportV4V6Info=ipifSupportV4V6Info, sysPortDescriptionTable=sysPortDescriptionTable, aclProfileArpSenderMacAddrMask=aclProfileArpSenderMacAddrMask, sysSNTPSecondType=sysSNTPSecondType, impbPortArpInspectionState=impbPortArpInspectionState, aclv6L3RuleAccessID=aclv6L3RuleAccessID, limitIpMulticastPortEntry=limitIpMulticastPortEntry, igsVlanMulticastGroupTable=igsVlanMulticastGroupTable, impbBlockListIpAddress=impbBlockListIpAddress, companyACLGroup=companyACLGroup, portSecFDBPermMac=portSecFDBPermMac, aacAPAuthMethodGroup=aacAPAuthMethodGroup, sysHardwareVersion=sysHardwareVersion, aclv6L3RuleICMPMessageCode=aclv6L3RuleICMPMessageCode, ftpConfigPassword=ftpConfigPassword, ipv4aclUdfOffsetByte3=ipv4aclUdfOffsetByte3, dhcpBOOTPRelayOption82CircuitID=dhcpBOOTPRelayOption82CircuitID, qosDiffServType48=qosDiffServType48, l2PTDropThreshold=l2PTDropThreshold, companyMldsGroup=companyMldsGroup, mstCistBridgePriority=mstCistBridgePriority, companyDHCPLocalRelay=companyDHCPLocalRelay, sysPortCtrlIndex=sysPortCtrlIndex, lldpXdot3LocPowerMDIEnabled=lldpXdot3LocPowerMDIEnabled, protocolVlanRowStatus=protocolVlanRowStatus, aclQosMACAddr=aclQosMACAddr, mldsVlanFbdRtrPortList=mldsVlanFbdRtrPortList, aclv6L3RuleTcpRstBit=aclv6L3RuleTcpRstBit, igsHostTableGroupAddress=igsHostTableGroupAddress, aclL3RuleReplace1P=aclL3RuleReplace1P, sysLBDPortLoopStatus=sysLBDPortLoopStatus, ipv4smtpRecvMailAddr=ipv4smtpRecvMailAddr, ipv4aclUdfOffsetBase2=ipv4aclUdfOffsetBase2, cpuFilterProfileIPProtocolMask=cpuFilterProfileIPProtocolMask, aacLoginMethodListIndex=aacLoginMethodListIndex, vlanMacMapIndex=vlanMacMapIndex, stpRootBridge=stpRootBridge, bandwidthCtrlIndex=bandwidthCtrlIndex, aclL3RuleTcpAckBit=aclL3RuleTcpAckBit, aclv6L3RuleDstIpAddrMask=aclv6L3RuleDstIpAddrMask, rmonHistoryEntry=rmonHistoryEntry, aacAccountingServiceSystem=aacAccountingServiceSystem, laPortChannelIfIndex=laPortChannelIfIndex, dhcpLocalRelayTableEntry=dhcpLocalRelayTableEntry, rmonEventType=rmonEventType, aacAccountingServiceCommandPoweruser=aacAccountingServiceCommandPoweruser, sysPortErrEntry=sysPortErrEntry, qinqTrustCVIDState=qinqTrustCVIDState, aclL3RuleTcpUdpSrcPortMask=aclL3RuleTcpUdpSrcPortMask, doSCtrlState=doSCtrlState, PortList=PortList, ipv4cpuFilterProfileDstMacAddrMask=ipv4cpuFilterProfileDstMacAddrMask, qosDiffServTOS=qosDiffServTOS, aclFlowMeterRate=aclFlowMeterRate, aacAPEnableMethod=aacAPEnableMethod, qosDefaultUserPri=qosDefaultUserPri, qinqSystem=qinqSystem, macNotifyCtrlEntry=macNotifyCtrlEntry, dot1qVlanEntry=dot1qVlanEntry, lldpXdot1ConfigPortVlanTable=lldpXdot1ConfigPortVlanTable, macBasedVlanMethod=macBasedVlanMethod, aclv6L3RuleTcpFinBit=aclv6L3RuleTcpFinBit, multicastVlanName=multicastVlanName, dhcpv6RelayOption37=dhcpv6RelayOption37, lldpXdot3RemMaxFrameSizeEntry=lldpXdot3RemMaxFrameSizeEntry, dhcpv6RelayOption18State=dhcpv6RelayOption18State, swAuthStatus=swAuthStatus, companyIgsGroup=companyIgsGroup, neighborIfindex=neighborIfindex, sysPortMediaTypeVendorName=sysPortMediaTypeVendorName, aclv6L3RuleProtocolMask=aclv6L3RuleProtocolMask, mldsDataDrivenLearningMaxLearnedEntryVlaue=mldsDataDrivenLearningMaxLearnedEntryVlaue, stpPortPriority=stpPortPriority, doSCtrlActionType=doSCtrlActionType, ipv4aclUdfOffsetMask4=ipv4aclUdfOffsetMask4, impbAutoScanIpAddress=impbAutoScanIpAddress, aclPacketRuleOffsetValue4=aclPacketRuleOffsetValue4, swTimeRangeMonday=swTimeRangeMonday, aclv6L3RuleTcpUdpSrcPortMask=aclv6L3RuleTcpUdpSrcPortMask, aacAccountingMethodListEntry=aacAccountingMethodListEntry, impbBindingListRowStatus=impbBindingListRowStatus, ddmStatusTable=ddmStatusTable, lldpXdot1LocProtocolId=lldpXdot1LocProtocolId, cpuFilterL2ProfileID=cpuFilterL2ProfileID, companyGVRPGroup=companyGVRPGroup, aclL3RuleEntry=aclL3RuleEntry, Timeout=Timeout, aclv6L3RuleTcpSynBit=aclv6L3RuleTcpSynBit, sysSNTPState=sysSNTPState, errorFrameSecondsThreshold=errorFrameSecondsThreshold, snmpV3GroupName=snmpV3GroupName, lldpXdot1ConfigVlanNameTxEnable=lldpXdot1ConfigVlanNameTxEnable)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", ftpConfigPath=ftpConfigPath, ipv4aclUdfOffsetByte2=ipv4aclUdfOffsetByte2, snmpV3GroupNotifyViewName=snmpV3GroupNotifyViewName, snmpV3UserAuthProtocolPassword=snmpV3UserAuthProtocolPassword, BridgeId=BridgeId, aclPacketRuleOffsetValue3Mask=aclPacketRuleOffsetValue3Mask, vlanMacMapRowStatus=vlanMacMapRowStatus, laSystem=laSystem, dlink_DES1210SeriesProd=dlink_DES1210SeriesProd, protocolGroupNameTable=protocolGroupNameTable, ipv4aclProfileType=ipv4aclProfileType, ddmThresholdType=ddmThresholdType, ddmInfo=ddmInfo, iPv4aacServerInfoTable=iPv4aacServerInfoTable, limitIpMulticastProfileTable=limitIpMulticastProfileTable, aclv6L3RuleSrcIpAddrMask=aclv6L3RuleSrcIpAddrMask, lldpXdot1RemProtoVlanTable=lldpXdot1RemProtoVlanTable, multicastVlanGroupTable=multicastVlanGroupTable, autoFdbEntry=autoFdbEntry, limitIpMulticastEntryProfileID=limitIpMulticastEntryProfileID, companySystem=companySystem, aclProfileUdfOffsetMap=aclProfileUdfOffsetMap, impbPortDHCPv6VlanList1k=impbPortDHCPv6VlanList1k, sysSNTPGMTMinutes=sysSNTPGMTMinutes, mldsVlanMulticastGroupVlanId=mldsVlanMulticastGroupVlanId, aclL3RuleSrcIpAddr=aclL3RuleSrcIpAddr, aclL3RuleStatus=aclL3RuleStatus, stpPortRestrictedRole=stpPortRestrictedRole, lldpPortConfigNotificationEnable=lldpPortConfigNotificationEnable, aclFlowMeterReplaceDscp=aclFlowMeterReplaceDscp, aclv6L3RuleEntry=aclv6L3RuleEntry, rmonAlarmOwner=rmonAlarmOwner, qosTOSType00=qosTOSType00, ipv4sysIprouteHops=ipv4sysIprouteHops, limitIpMulticastProfileName=limitIpMulticastProfileName, mldsVlanRtrPortList=mldsVlanRtrPortList, cpuFilterL3RuleTcpFinBit=cpuFilterL3RuleTcpFinBit, macNotifyPortStatus=macNotifyPortStatus, rmonEventOwner=rmonEventOwner, mstResetVlanList=mstResetVlanList, cpuFilterv6L3RuleProtocol=cpuFilterv6L3RuleProtocol, aclProfileSrcMacAddrMask=aclProfileSrcMacAddrMask, tftpFwServerIpAddress=tftpFwServerIpAddress, swAuthAuthServerTimeout=swAuthAuthServerTimeout, lldpXdot3LocLinkAggStatus=lldpXdot3LocLinkAggStatus, agentCPUutilization=agentCPUutilization, cableDiagEntry=cableDiagEntry, cpuFilterL2RuleAction=cpuFilterL2RuleAction, cpuFilterL3RuleTcpUrgBit=cpuFilterL3RuleTcpUrgBit, pppoePortTable=pppoePortTable, securityTrustedHost=securityTrustedHost, syslogSaveMode=syslogSaveMode, dhcpv6RelayOption18=dhcpv6RelayOption18, eoamReceivedRemoteLoopback=eoamReceivedRemoteLoopback, impbDhcpSnoopingTable=impbDhcpSnoopingTable, aacAccountingMethod4=aacAccountingMethod4, swAuthRadiusServerEntry=swAuthRadiusServerEntry, impbBindingListPort=impbBindingListPort, snmpTrapBPDUAttack=snmpTrapBPDUAttack, duldOperState=duldOperState, snmpV3CommunityStatus=snmpV3CommunityStatus, dhcpv6RelayState=dhcpv6RelayState, aacAPTelnetLoginMethod=aacAPTelnetLoginMethod, cpuFilterL3RuleProtocol=cpuFilterL3RuleProtocol, ipv4aclProfileNo=ipv4aclProfileNo, rmonHistoryDataSource=rmonHistoryDataSource, sysPortType=sysPortType, mstMstiBridgeEntry=mstMstiBridgeEntry, aclL3RuleSrcIpAddrMask=aclL3RuleSrcIpAddrMask, swTimeRangeSunday=swTimeRangeSunday, stpPortStatus=stpPortStatus, igmpMulticastVlanid=igmpMulticastVlanid, dhcpRelayVlanSettingsVLANID=dhcpRelayVlanSettingsVLANID, bandwidthEffecRxThreshold=bandwidthEffecRxThreshold, impbPortForwardDHCPPktState=impbPortForwardDHCPPktState, sysPortDescriptionEntry=sysPortDescriptionEntry, aclPacketRuleOffsetValue4Mask=aclPacketRuleOffsetValue4Mask, lldpXdot1LocProtoVlanSupported=lldpXdot1LocProtoVlanSupported, aclL2RuleAction=aclL2RuleAction, aacAccountingServiceIndex=aacAccountingServiceIndex, sysSize=sysSize, swTimeRangeSettingTable=swTimeRangeSettingTable, sysSNTPDSTRepeatEndHour=sysSNTPDSTRepeatEndHour, aclL3RuleDstIpAddr=aclL3RuleDstIpAddr, aclL3RuleAccessID=aclL3RuleAccessID, swAuthenCtrl=swAuthenCtrl, ipv4aclQosIPAddr=ipv4aclQosIPAddr, lldpXdot1LocVlanName=lldpXdot1LocVlanName, limitIpMulticastEntry=limitIpMulticastEntry, aclProfileEntry=aclProfileEntry, qosDiffServType33=qosDiffServType33, LldpLinkAggStatusMap=LldpLinkAggStatusMap, igmpMulticastVlanMemberPort=igmpMulticastVlanMemberPort, aclPacketRuleInPortList=aclPacketRuleInPortList, lldpXdot3RemMaxFrameSize=lldpXdot3RemMaxFrameSize, ipv4dhcpOption12HostName=ipv4dhcpOption12HostName, pppoePortUDFString=pppoePortUDFString, aRPSpoofPreventIpAddr=aRPSpoofPreventIpAddr, l2PTProtocol=l2PTProtocol, multicastVlanGroupFromIp=multicastVlanGroupFromIp, filterDHCPServerTable=filterDHCPServerTable, sysSMTPServerGroup=sysSMTPServerGroup, cosOutputSchedule=cosOutputSchedule, lldpXdot3PortConfigTable=lldpXdot3PortConfigTable, multicastVlanTagMemberPort=multicastVlanTagMemberPort, lldpXdot3RemPortEntry=lldpXdot3RemPortEntry, ipv4syslogServSrvStatus=ipv4syslogServSrvStatus, swTimeRangeEndHour=swTimeRangeEndHour, companyLA=companyLA, snmpV3TrapColdStart=snmpV3TrapColdStart, lldpPortConfigTable=lldpPortConfigTable, swTimeRangeStartYear=swTimeRangeStartYear, qosDiffServType40=qosDiffServType40, aclPacketRuleReplaceDSCP=aclPacketRuleReplaceDSCP, limitIpMulticastStatus=limitIpMulticastStatus, snmpV3ViewTree=snmpV3ViewTree, stpPortEntry=stpPortEntry, impbBindingtraplog=impbBindingtraplog, cpuFilterv6L3RuleEntry=cpuFilterv6L3RuleEntry, errorFrameThreshold=errorFrameThreshold, lldpXdot3RemPowerTable=lldpXdot3RemPowerTable, protocolGroupProtocolValue=protocolGroupProtocolValue, aacLoginMethod2=aacLoginMethod2, sysUpdateTime=sysUpdateTime, companyMacBasedVlan=companyMacBasedVlan, snmpV3CommunityName=snmpV3CommunityName, igsHostTable=igsHostTable, qosPriSettingsTable=qosPriSettingsTable, cpuFilterv6L3RuleTcpUdpDstPortMask=cpuFilterv6L3RuleTcpUdpDstPortMask, qinqOuterTPID=qinqOuterTPID, lldpPortConfigPortNum=lldpPortConfigPortNum, guestVlanName=guestVlanName, impbDhcpSnoopingEntry=impbDhcpSnoopingEntry, aclQosTable=aclQosTable, sysTrapLBD=sysTrapLBD, LacpKey=LacpKey, qosPriSetPortIndex=qosPriSetPortIndex, qosDiffServType29=qosDiffServType29, ipv4sysSNTPState=ipv4sysSNTPState, cpuFilterL3RuleTcpAckBit=cpuFilterL3RuleTcpAckBit, ipv4aclUdfOffsetByte1=ipv4aclUdfOffsetByte1, aclL2RuleTable=aclL2RuleTable, lldpXdot3RemoteData=lldpXdot3RemoteData, cableDiagPair3Length=cableDiagPair3Length, cpuFilterProfileNo=cpuFilterProfileNo, mstMstiStatus=mstMstiStatus, sysBPDUAttackStateEnable=sysBPDUAttackStateEnable, qosDiffServType44=qosDiffServType44, trafficCtrlIndex=trafficCtrlIndex, companyCPUInterfaceFilterGroup=companyCPUInterfaceFilterGroup, qosDefaultPriority=qosDefaultPriority, companyGratuitousARP=companyGratuitousARP, qosDiffServType47=qosDiffServType47, ipv4aclProfileUdfOffsetMap=ipv4aclProfileUdfOffsetMap, ipifV6AddressIpAddr=ipifV6AddressIpAddr, snmpTrapFirmUpgrade=snmpTrapFirmUpgrade, impbVlanModeVlanList=impbVlanModeVlanList, dhcpv6RelayOption37RemoteIDType=dhcpv6RelayOption37RemoteIDType, bandwidthCtrlTxThreshold=bandwidthCtrlTxThreshold, aclL2RuleStatus=aclL2RuleStatus, dhcpv6RelayOpt38PortState=dhcpv6RelayOpt38PortState, lldpXdot1RemEntry=lldpXdot1RemEntry, cableDiagStatus=cableDiagStatus, mldsVlanFilterEntry=mldsVlanFilterEntry, duldEntry=duldEntry, qosDiffServType18=qosDiffServType18, lldpXdot1LocalData=lldpXdot1LocalData, agentMEMutilizationIn1min=agentMEMutilizationIn1min, laPortActorActivity=laPortActorActivity, companyMirror=companyMirror, sysPortMediaTypeSn=sysPortMediaTypeSn, swAuthPortAccessControlTable=swAuthPortAccessControlTable, aclv6L3RuleTcpUdpSrcPort=aclv6L3RuleTcpUdpSrcPort, aacAccountingMethodListName=aacAccountingMethodListName, impbPortDHCPv4VlanList4k=impbPortDHCPv4VlanList4k, swTimeRangeIndex=swTimeRangeIndex, tftpFwTargetInterfaceName=tftpFwTargetInterfaceName, multicastVlanRowStatus=multicastVlanRowStatus, impbAutoScanIpAddressTo=impbAutoScanIpAddressTo, ipifv6NSRetransmitTime=ipifv6NSRetransmitTime, mstMstiInstanceIndex=mstMstiInstanceIndex, limitIpMulticastPortID=limitIpMulticastPortID, eoamLinkMonitorTable=eoamLinkMonitorTable, impbPortDHCPv6SetVlanList=impbPortDHCPv6SetVlanList, impbDhcpSnoopingIpAddress=impbDhcpSnoopingIpAddress, cpuFilterProfileSrcIpAddrMask=cpuFilterProfileSrcIpAddrMask, swTimeRangeEndDay=swTimeRangeEndDay, mstCistVlanMapped4k=mstCistVlanMapped4k, gvrpGVRPGlobalSettingsOnOff=gvrpGVRPGlobalSettingsOnOff, dhcpv6RelayInterfaceSettingsEntry=dhcpv6RelayInterfaceSettingsEntry, snmpV3UserAuthProtocol=snmpV3UserAuthProtocol, lldpXdot3RemPowerMDIEnabled=lldpXdot3RemPowerMDIEnabled, qosTOSType06=qosTOSType06, ipv4smtpServerPort=ipv4smtpServerPort, aacAccountingMethod3=aacAccountingMethod3, laPortControlIndex=laPortControlIndex, gvrpSettingsPortControlIndex=gvrpSettingsPortControlIndex, aacServerPasswordEncryption=aacServerPasswordEncryption, sysBPDUAttackPortStatus=sysBPDUAttackPortStatus, qosUserPriority=qosUserPriority, impbDhcpSnoopingLeaseTime=impbDhcpSnoopingLeaseTime, iPv4aacServerRetryCount=iPv4aacServerRetryCount, ipv4aclProfileRuleCount=ipv4aclProfileRuleCount, dhcpv6RelayOpt38Entry=dhcpv6RelayOpt38Entry, companyDoSCtrl=companyDoSCtrl, protocolVlanVID=protocolVlanVID, ddmHighAlarm=ddmHighAlarm, sysSwitchName=sysSwitchName, portSecFDBPermVlanID=portSecFDBPermVlanID, ipv4aclProfileTable=ipv4aclProfileTable, des_1210_28me=des_1210_28me, igsVlanFastLeave=igsVlanFastLeave, iPv4swAuthRadiusServerRetransmit=iPv4swAuthRadiusServerRetransmit, miscStatisticsReset=miscStatisticsReset, ipv4sysSNTPDSTStartMin=ipv4sysSNTPDSTStartMin, lldpXdot3LocalData=lldpXdot3LocalData, mstInstanceVlanMapped4k=mstInstanceVlanMapped4k, trustedHostEntry=trustedHostEntry, ftpConfigUsername=ftpConfigUsername, igsDataDrivenLearningMaxLearnedEntryVlaue=igsDataDrivenLearningMaxLearnedEntryVlaue, multicastVlanGroupToIp=multicastVlanGroupToIp, ipv4dhcpOption12Status=ipv4dhcpOption12Status, errorFrameNotifyState=errorFrameNotifyState, qosDiffServType39=qosDiffServType39, aacAuthParamAttempt=aacAuthParamAttempt, ipifV6AddressMainIndex=ipifV6AddressMainIndex, sysTrapTwistedPortEvent=sysTrapTwistedPortEvent, staticStatus=staticStatus, sysMirrorTargetPort=sysMirrorTargetPort, qinqIfIndex=qinqIfIndex, mldsVlanRobustnessValue=mldsVlanRobustnessValue, swAuthUserEntry=swAuthUserEntry, errorSymbolNotifyState=errorSymbolNotifyState, tftpFwTftpOperationStatus=tftpFwTftpOperationStatus, qosDiffServType30=qosDiffServType30, cpuFilterL2RuleDstMacAddr=cpuFilterL2RuleDstMacAddr, lldpPortConfigAdminStatus=lldpPortConfigAdminStatus, agentCPUutilizationIn1min=agentCPUutilizationIn1min, ipv4snmpV3HostVersion=ipv4snmpV3HostVersion, sysGratuitousARPLearning=sysGratuitousARPLearning, ipv4smtpServerAddr=ipv4smtpServerAddr, aacServerAuthPort=aacServerAuthPort, qosTOSGroup=qosTOSGroup, ddmTemperature=ddmTemperature, cpuFilterv6L3RuleDstIpAddrMask=cpuFilterv6L3RuleDstIpAddrMask, sshUserInfoAuth=sshUserInfoAuth, impbBlockListStatus=impbBlockListStatus, ipv4aclProfileIPProtocol=ipv4aclProfileIPProtocol, ipv4aclProfileStatus=ipv4aclProfileStatus, lldpXdot1RemPortVlanId=lldpXdot1RemPortVlanId, sysSNTPServerTable=sysSNTPServerTable, sysSNTPDSTEndMin=sysSNTPDSTEndMin, qosDefaultUserPriTable=qosDefaultUserPriTable, rmonEventEntry=rmonEventEntry)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", dot1qVlanAdvertisementStatus=dot1qVlanAdvertisementStatus, lldpXdot3LocPowerTable=lldpXdot3LocPowerTable, qosDiffServType26=qosDiffServType26, aclv6L3RuleTcpAckBit=aclv6L3RuleTcpAckBit, filterDHCPServerRowStatus=filterDHCPServerRowStatus, impbPortIndex=impbPortIndex, ipv4trustedHostIpMask=ipv4trustedHostIpMask, ddmVoltage=ddmVoltage, aacAPHttpEnableMethod=aacAPHttpEnableMethod, swAuthAuthSuppTimeout=swAuthAuthSuppTimeout, snmpV3TrapSNMPAuthentication=snmpV3TrapSNMPAuthentication, sysPortErrPortReason=sysPortErrPortReason, staticVlanBaseEnableAutoLearn=staticVlanBaseEnableAutoLearn, gvrpSettingsJoinTime=gvrpSettingsJoinTime, macNotifyState=macNotifyState, aacServerGroupEntry=aacServerGroupEntry, igmpMulticastVlanGroupStatus=igmpMulticastVlanGroupStatus, mldsVlan=mldsVlan, impbPortDHCPv4SetVlanList=impbPortDHCPv4SetVlanList, qosTOSType05=qosTOSType05, ddmBiasCurrent=ddmBiasCurrent, cpuFilterv6L3RuleProtocolMask=cpuFilterv6L3RuleProtocolMask, qosDiffServType13=qosDiffServType13, mldsSystem=mldsSystem, staticARPMac=staticARPMac, ipv4sysSNTPDSTEndMin=ipv4sysSNTPDSTEndMin, qosTOSType07=qosTOSType07, rmonHistoryStatus=rmonHistoryStatus, tftpFwTargetTftpOperation=tftpFwTargetTftpOperation, aclQosIPv6Addr=aclQosIPv6Addr, igsVlan=igsVlan, qosDiffServType09=qosDiffServType09, lldpXdot1LocVlanNameTable=lldpXdot1LocVlanNameTable, ipv4sysIprouteGateway=ipv4sysIprouteGateway, duldLinkStatus=duldLinkStatus, stpPortTable=stpPortTable, gvrpSettingsTable=gvrpSettingsTable, dot1qVlanName=dot1qVlanName, ipifName=ipifName, trafficSegMemberList=trafficSegMemberList, swTimeRangeEndMinute=swTimeRangeEndMinute, cpuFilterv6L3RuleDstIpAddr=cpuFilterv6L3RuleDstIpAddr, sysSNTPDSTRepeatEndMin=sysSNTPDSTRepeatEndMin, sysTrapFirmUpgradeEvent=sysTrapFirmUpgradeEvent, qosDiffServType46=qosDiffServType46, l2PTPortIndex=l2PTPortIndex, aRPSpoofPreventMacAddress=aRPSpoofPreventMacAddress, cpuFilterProfileDstIpAddrMask=cpuFilterProfileDstIpAddrMask, aacAccountingServiceNetwork=aacAccountingServiceNetwork, sysPortCtrlMDI=sysPortCtrlMDI, iPv4swAuthRadiusServerStatus=iPv4swAuthRadiusServerStatus, dlink_products=dlink_products, impbBindingListMacAddress=impbBindingListMacAddress, dhcpBOOTPRelayManagementOption82=dhcpBOOTPRelayManagementOption82, aacEnableMethodListIndex=aacEnableMethodListIndex, sysSNTPPollInterval=sysSNTPPollInterval, lldpXdot3Objects=lldpXdot3Objects, sysPortCtrlCapability=sysPortCtrlCapability, mstMstiPortEntry=mstMstiPortEntry, snmpV3GroupReadViewName=snmpV3GroupReadViewName, ftpFwFTPOperation=ftpFwFTPOperation, mstMstiBridgeTable=mstMstiBridgeTable, aclProfileIPProtocol=aclProfileIPProtocol, securitySSH=securitySSH, aclL2RuleReplaceQueue=aclL2RuleReplaceQueue, qosDiffServType08=qosDiffServType08, lldpXdot3RemPortAutoNegAdvertisedCap=lldpXdot3RemPortAutoNegAdvertisedCap, trafficSegTable=trafficSegTable, snmpV3TrapDHCPServerScreening=snmpV3TrapDHCPServerScreening, mstMstiCurrentPortRole=mstMstiCurrentPortRole, dhcpv6RelayOption37CheckState=dhcpv6RelayOption37CheckState, igmpMulticastVlanSourcePort=igmpMulticastVlanSourcePort, stpInstancePortTable=stpInstancePortTable, trafficCtrlThreshold=trafficCtrlThreshold, trustedHostIpAddr=trustedHostIpAddr, ipv4snmpV3HostEntry=ipv4snmpV3HostEntry, cpuFilterv6L3RuleSrcIpAddrMask=cpuFilterv6L3RuleSrcIpAddrMask, staticPort=staticPort, companySNTPSetting=companySNTPSetting, cableDiagPortType=cableDiagPortType, snmpV3HostTable=snmpV3HostTable, aclPacketRuleReplace1P=aclPacketRuleReplace1P, igsSystem=igsSystem, dlinklldpConfigManAddrPortsTxEnable=dlinklldpConfigManAddrPortsTxEnable, impbRoamingState=impbRoamingState, sysLocationName=sysLocationName, vlanTrunkGlobalStatus=vlanTrunkGlobalStatus, rmonHistoryBucketsRequested=rmonHistoryBucketsRequested, lldpXdot3LocPowerEntry=lldpXdot3LocPowerEntry, smtpRecvMailAddrTable=smtpRecvMailAddrTable, sysPortMediaTypeTable=sysPortMediaTypeTable, sysMirrorStatus=sysMirrorStatus, syslogServEntry=syslogServEntry, aclPacketRuleOffsetValue1Mask=aclPacketRuleOffsetValue1Mask, snmpV3IPType=snmpV3IPType, securityARPSpoofPrevent=securityARPSpoofPrevent, lldpXdot3RemPortAutoNegSupported=lldpXdot3RemPortAutoNegSupported, aclv6L3RuleTcpUdpDstPort=aclv6L3RuleTcpUdpDstPort, cpuFilterv6L3RuleTcpUrgBit=cpuFilterv6L3RuleTcpUrgBit, igsVlanRouterPortList=igsVlanRouterPortList, syslogServIndex=syslogServIndex, impbPortDHCPv4VlanList3k=impbPortDHCPv4VlanList3k, companyLBD=companyLBD, aclProfileStatus=aclProfileStatus, sysWebState=sysWebState, sysIpAddrCfgMode=sysIpAddrCfgMode, rmonAlarmVariable=rmonAlarmVariable, stpRootPort=stpRootPort, sysGroupInterval=sysGroupInterval, qosDiffServType52=qosDiffServType52, tftpConfigTftpOperationStatus=tftpConfigTftpOperationStatus, aclv6L3RuleReplaceDSCP=aclv6L3RuleReplaceDSCP, lldpXdot3RemPortTable=lldpXdot3RemPortTable, ipv4smtpState=ipv4smtpState, errorFramePeriodThreshold=errorFramePeriodThreshold, protocolGroupName=protocolGroupName, PortLaMode=PortLaMode, igsVlanFbdRtrPortList=igsVlanFbdRtrPortList, ipv4sysSNTPDSTEndDay=ipv4sysSNTPDSTEndDay, qinqVLANTranslationState=qinqVLANTranslationState, snmpTrapGratuitousArp=snmpTrapGratuitousArp, igsVlanMulticastGroupVlanId=igsVlanMulticastGroupVlanId, aclFlowMeterAccessID=aclFlowMeterAccessID, dhcpRelayVlanTable=dhcpRelayVlanTable, companyDot1qVlanGroup=companyDot1qVlanGroup, portSecFDBPermPort=portSecFDBPermPort, cpuFilterProfileRuleCount=cpuFilterProfileRuleCount, snmpV3HostInterfaceName=snmpV3HostInterfaceName, ipifv6DefaultGateway=ipifv6DefaultGateway, cpuFilterProfileTable=cpuFilterProfileTable, aacAccountingServiceCommandUser=aacAccountingServiceCommandUser, cpuFilterProfileEntry=cpuFilterProfileEntry, duldIfIndex=duldIfIndex, protocolGroupEntry=protocolGroupEntry, stpPortEdge=stpPortEdge, snmpTrapPortSecurity=snmpTrapPortSecurity, l2PTProtocolIndex=l2PTProtocolIndex, smtpServerPort=smtpServerPort, ipifV6AddressTable=ipifV6AddressTable, trafficSegEntry=trafficSegEntry, qosDiffServType49=qosDiffServType49, aclQosType=aclQosType, vlanTrunkTable=vlanTrunkTable, cosClassTable=cosClassTable, mstCistPortTable=mstCistPortTable, tftpCfgTargetServerIpType=tftpCfgTargetServerIpType, qosDiffServType42=qosDiffServType42, dhcpRelayVlanTableEntry=dhcpRelayVlanTableEntry, aacServerGroupTable=aacServerGroupTable, dot1qVlanAsyOnOff=dot1qVlanAsyOnOff, protocolGroupFrameType=protocolGroupFrameType, laPortChannelMasterPort=laPortChannelMasterPort, aacAccountingMethodListTable=aacAccountingMethodListTable, l2PTEntry=l2PTEntry, igsReportToAllPort=igsReportToAllPort, neighborRowStatus=neighborRowStatus, brgAddress=brgAddress, qinqVlanTranslationSVID=qinqVlanTranslationSVID, cpuFilterL3RulePortList=cpuFilterL3RulePortList, lldpXdot3LocPowerPairs=lldpXdot3LocPowerPairs, impbPortProtocolState=impbPortProtocolState, qosPriSettingsEntry=qosPriSettingsEntry, filterDHCPServerIpAddr=filterDHCPServerIpAddr, sysGratuitousARPDuplicateIPDetected=sysGratuitousARPDuplicateIPDetected, tftpFwImageFileName=tftpFwImageFileName, ipv4aclProfileArpSenderIpAddrMask=ipv4aclProfileArpSenderIpAddrMask, syslogServAddr=syslogServAddr, sysPortCtrlFlowControl=sysPortCtrlFlowControl, aclv6L3RuleAction=aclv6L3RuleAction, lldpXdot1LocProtoVlanId=lldpXdot1LocProtoVlanId, sysPortErrPortStatus=sysPortErrPortStatus, mldsVlanRouterPortList=mldsVlanRouterPortList, laPortControlEntry=laPortControlEntry, iPv4swAuthRadiusServerTimeout=iPv4swAuthRadiusServerTimeout, ipv4aclQosProtocol=ipv4aclQosProtocol, snmpTrapWarmStart=snmpTrapWarmStart, dhcpRelayVlanSettingsState=dhcpRelayVlanSettingsState, multicastVlanGroupEntry=multicastVlanGroupEntry, autoRefreshConfiguration=autoRefreshConfiguration, filterDHCPServerPortList=filterDHCPServerPortList, topologyChange=topologyChange, securityAAC=securityAAC, lldpXdot1RemProtocolId=lldpXdot1RemProtocolId, cpuFilterProfileSrcIpAddrMaskType=cpuFilterProfileSrcIpAddrMaskType, syslogServAddrType=syslogServAddrType, ipv4syslogServerGroup=ipv4syslogServerGroup, cpuFilterv6L3RulePortList=cpuFilterv6L3RulePortList, mstCistPortPriority=mstCistPortPriority, swTimeRangeDate=swTimeRangeDate, sysDhcpAutoConfiguration=sysDhcpAutoConfiguration, sysLBDStateEnable=sysLBDStateEnable, tftpFwTargetGroup=tftpFwTargetGroup, sysSNTPDSTState=sysSNTPDSTState, igsVlanGrpQueryInterval=igsVlanGrpQueryInterval, snmpV3CommunityTable=snmpV3CommunityTable, tftpFwTftpOperation=tftpFwTftpOperation, companyDDM=companyDDM, qosDiffServType24=qosDiffServType24, igmpMulticastVlanState=igmpMulticastVlanState, aRPSpoofPreventEntry=aRPSpoofPreventEntry, snmpTrapDHCPScreen=snmpTrapDHCPScreen, smtpRecvMailAddrIndex=smtpRecvMailAddrIndex, cableDiagPair2Status=cableDiagPair2Status, aclPacketRuleReplaceQueue=aclPacketRuleReplaceQueue, impbSettingTable=impbSettingTable, impbDHCPv6PrefixDelegationSnoopState=impbDHCPv6PrefixDelegationSnoopState, protocolVlanPort=protocolVlanPort, mstMstiPortDesignatedBridge=mstMstiPortDesignatedBridge, lldpXdot1LocProtoVlanEntry=lldpXdot1LocProtoVlanEntry, sysTrapSystemEvent=sysTrapSystemEvent, ipv4aclQosAssignClass=ipv4aclQosAssignClass, lldpXdot3LocPortAutoNegEnabled=lldpXdot3LocPortAutoNegEnabled, igsVlanFilterEntry=igsVlanFilterEntry, aclProfileSrcIpAddrMask=aclProfileSrcIpAddrMask, igsHostTableVLANID=igsHostTableVLANID, aclL3RuleIgmpType=aclL3RuleIgmpType, swAuthRadiusServerAuthenticationPort=swAuthRadiusServerAuthenticationPort, sysSNTPDSTEndHour=sysSNTPDSTEndHour, lldpXdot1RemProtoVlanSupported=lldpXdot1RemProtoVlanSupported, ipv4aclProfileSrcMacAddrMask=ipv4aclProfileSrcMacAddrMask, sysTrapFiberPortEvent=sysTrapFiberPortEvent, ipv4aclUdfOffsetBase3=ipv4aclUdfOffsetBase3, lldpXdot3LocMaxFrameSize=lldpXdot3LocMaxFrameSize, iPv4aacServerAuthProtocol=iPv4aacServerAuthProtocol, trafficCtrlType=trafficCtrlType, sfpConnectorType=sfpConnectorType, companyPPPoE=companyPPPoE, syslogSaveMinutes=syslogSaveMinutes, errorFrameSecondsNotifyState=errorFrameSecondsNotifyState, cpuFilterL2RuleInPortList=cpuFilterL2RuleInPortList, ipifv6AutolinkloStatus=ipifv6AutolinkloStatus, impbBindingListEntry=impbBindingListEntry, iPv4aacServerAuthPort=iPv4aacServerAuthPort, aclProfileIPProtocolMask=aclProfileIPProtocolMask, smtpRecvMailAddrEntry=smtpRecvMailAddrEntry, laPortChannelEntry=laPortChannelEntry, tftpFwTargetServerIpAddress=tftpFwTargetServerIpAddress, rmonStatsIndex=rmonStatsIndex, ftpFwTable=ftpFwTable, laPortChannelMemberList=laPortChannelMemberList, aclPacketRule=aclPacketRule, qosDiffServType54=qosDiffServType54, cpuFilterv6L3RuleTcpPshBit=cpuFilterv6L3RuleTcpPshBit, sysARPAgingTime=sysARPAgingTime, errorSymbolThreshold=errorSymbolThreshold, qosDefaultUserPriPortIndex=qosDefaultUserPriPortIndex, aclPacketRuleAction=aclPacketRuleAction, aclL2RuleSrcMacAddr=aclL2RuleSrcMacAddr, qosDiffServType56=qosDiffServType56, snmpV3HostEntry=snmpV3HostEntry, swTimeRangeWednesday=swTimeRangeWednesday, dhcpOption12Status=dhcpOption12Status, filterDHCPServerClientMacAddr=filterDHCPServerClientMacAddr, aclL2RuleRateLimit=aclL2RuleRateLimit)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", cpuFilterL3RuleTcpPshBit=cpuFilterL3RuleTcpPshBit, sysGratuitousARPSettings=sysGratuitousARPSettings, igsVlanMulticastGroupPortList=igsVlanMulticastGroupPortList, snmpV3ViewTreeEntry=snmpV3ViewTreeEntry, sshUserInfoHostIp=sshUserInfoHostIp, autoFdbTimeStamp=autoFdbTimeStamp, mstVlanMstiMappingTable=mstVlanMstiMappingTable, igsHostEntry=igsHostEntry, sshAuthenMethodPubKeyAdmin=sshAuthenMethodPubKeyAdmin, dot1qVlanRowStatus=dot1qVlanRowStatus, staticMcastStatus=staticMcastStatus, impbDhcpSnoopingPort=impbDhcpSnoopingPort, aclL2Rule=aclL2Rule, aclFlowMeterTable=aclFlowMeterTable, sysPortDescString=sysPortDescString, aclUdfOffsetBase3=aclUdfOffsetBase3, ipv4cpuFilterProfileType=ipv4cpuFilterProfileType, sfpVendorSn=sfpVendorSn, snmpTrapColdStart=snmpTrapColdStart, impbBindingListIpAddress=impbBindingListIpAddress, mstMstiBridgePriority=mstMstiBridgePriority, dot1qVlanEgressPorts=dot1qVlanEgressPorts, cpuFilterL3RuleSrcIpAddrMask=cpuFilterL3RuleSrcIpAddrMask, aclL3RuleRateLimit=aclL3RuleRateLimit, gvrpSettingsEntry=gvrpSettingsEntry, mstInstanceVlanMapped3k=mstInstanceVlanMapped3k, doSCtrlType=doSCtrlType, aclL3RuleTcpSynBit=aclL3RuleTcpSynBit, bandwidthCtrlRxThreshold=bandwidthCtrlRxThreshold, sysTrapStateChangeEvent=sysTrapStateChangeEvent, ipifv6GlobalStatus=ipifv6GlobalStatus, rmonStatsEntry=rmonStatsEntry, stpPortAdminP2P=stpPortAdminP2P, mstVlanMstiMappingEntry=mstVlanMstiMappingEntry, iPv4swAuthRadiusServerIndex=iPv4swAuthRadiusServerIndex, qosDiffServType11=qosDiffServType11, syslogServSeverity=syslogServSeverity, dhcpv6RelayControl=dhcpv6RelayControl, sslCiphers=sslCiphers, aclQosIPAddr=aclQosIPAddr, lldpXdot1ConfigProtoVlanTable=lldpXdot1ConfigProtoVlanTable, qosDiffServType58=qosDiffServType58, ipv4sysGateway=ipv4sysGateway, impbBlockListTable=impbBlockListTable, aclPacketRuleEntry=aclPacketRuleEntry, eoamCriticalEventEnable=eoamCriticalEventEnable, snmpV3TrapLBD=snmpV3TrapLBD, sfpVendorInfoTable=sfpVendorInfoTable, ipv4aclProfileArpSenderMacAddrMask=ipv4aclProfileArpSenderMacAddrMask, dot1qVlanTable=dot1qVlanTable, lldpXdot1ConfigProtocolEntry=lldpXdot1ConfigProtocolEntry, igmpMulticastVlanGroupEntry=igmpMulticastVlanGroupEntry, cpuFilterv6L3RuleAccessID=cpuFilterv6L3RuleAccessID, sysLBDPortStatus=sysLBDPortStatus, snmpV3EngineID=snmpV3EngineID, aacServerRetryCount=aacServerRetryCount, smtpRecvMailAddr=smtpRecvMailAddr, cableDiagTable=cableDiagTable, neighborType=neighborType, ipv4syslogServAddr=ipv4syslogServAddr, tftpFwTargetImageFileName=tftpFwTargetImageFileName, dhcpv6RelayOpt38Table=dhcpv6RelayOpt38Table, ddmStatus=ddmStatus, snmpV3viewTreeMask=snmpV3viewTreeMask, companyISMVLAN=companyISMVLAN, lldpXdot3LocLinkAggTable=lldpXdot3LocLinkAggTable, sysSNTPDSTRepeatEndWeekDay=sysSNTPDSTRepeatEndWeekDay, ipv4sysSNTPDSTOffset=ipv4sysSNTPDSTOffset, neighborCacheState=neighborCacheState, igsVlanDataDrivenLearningAgeOutStatus=igsVlanDataDrivenLearningAgeOutStatus, impbSettingEntry=impbSettingEntry, snmpV3User=snmpV3User, laPortActorPortPriority=laPortActorPortPriority, dhcpLocalRelayGlobalState=dhcpLocalRelayGlobalState, companyStaticMcast=companyStaticMcast, rmonAlarm=rmonAlarm, sysSNTPFirstType=sysSNTPFirstType, qosDiffServType14=qosDiffServType14, qosDiffServType41=qosDiffServType41, ipv4sysSNTPPollInterval=ipv4sysSNTPPollInterval)NEWLINE NEWLINE# This file helps to compute a version number in source trees obtained fromNEWLINE# git-archive tarball (such as those provided by githubs download-from-tagNEWLINE# feature). Distribution tarballs (built by setup.py sdist) and buildNEWLINE# directories (produced by setup.py build) will contain a much shorter fileNEWLINE# that just contains the computed version number.NEWLINENEWLINE# This file is released into the public domain. Generated byNEWLINE# versioneer-0.18 (https://github.com/warner/python-versioneer)NEWLINENEWLINE"""Git implementation of _version.py."""NEWLINENEWLINEimport errnoNEWLINEimport osNEWLINEimport reNEWLINEimport subprocessNEWLINEimport sysNEWLINENEWLINENEWLINEdef get_keywords():NEWLINE """Get the keywords needed to look up the version information."""NEWLINE # these strings will be replaced by git during git-archive.NEWLINE # setup.py/versioneer.py will grep for the variable names, so they mustNEWLINE # each be defined on a line of their own. _version.py will just callNEWLINE # get_keywords().NEWLINE git_refnames = "$Format:%d$"NEWLINE git_full = "$Format:%H$"NEWLINE git_date = "$Format:%ci$"NEWLINE keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}NEWLINE return keywordsNEWLINENEWLINENEWLINEclass VersioneerConfig:NEWLINE """Container for Versioneer configuration parameters."""NEWLINENEWLINENEWLINEdef get_config():NEWLINE """Create, populate and return the VersioneerConfig() object."""NEWLINE # these strings are filled in when 'setup.py versioneer' createsNEWLINE # _version.pyNEWLINE cfg = VersioneerConfig()NEWLINE cfg.VCS = "git"NEWLINE cfg.style = ""NEWLINE cfg.tag_prefix = ""NEWLINE cfg.parentdir_prefix = "magic-wormhole-mailbox-server"NEWLINE cfg.versionfile_source = "src/wormhole_mailbox_server/_version.py"NEWLINE cfg.verbose = FalseNEWLINE return cfgNEWLINENEWLINENEWLINEclass NotThisMethod(Exception):NEWLINE """Exception raised if a method is not valid for the current scenario."""NEWLINENEWLINENEWLINELONG_VERSION_PY = {}NEWLINEHANDLERS = {}NEWLINENEWLINENEWLINEdef register_vcs_handler(vcs, method): # decoratorNEWLINE """Decorator to mark a method as the handler for a particular VCS."""NEWLINE def decorate(f):NEWLINE """Store f in HANDLERS[vcs][method]."""NEWLINE if vcs not in HANDLERS:NEWLINE HANDLERS[vcs] = {}NEWLINE HANDLERS[vcs][method] = fNEWLINE return fNEWLINE return decorateNEWLINENEWLINENEWLINEdef run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,NEWLINE env=None):NEWLINE """Call the given command(s)."""NEWLINE assert isinstance(commands, list)NEWLINE p = NoneNEWLINE for c in commands:NEWLINE try:NEWLINE dispcmd = str([c] + args)NEWLINE # remember shell=False, so use git.cmd on windows, not just gitNEWLINE p = subprocess.Popen([c] + args, cwd=cwd, env=env,NEWLINE stdout=subprocess.PIPE,NEWLINE stderr=(subprocess.PIPE if hide_stderrNEWLINE else None))NEWLINE breakNEWLINE except EnvironmentError:NEWLINE e = sys.exc_info()[1]NEWLINE if e.errno == errno.ENOENT:NEWLINE continueNEWLINE if verbose:NEWLINE print("unable to run %s" % dispcmd)NEWLINE print(e)NEWLINE return None, NoneNEWLINE else:NEWLINE if verbose:NEWLINE print("unable to find command, tried %s" % (commands,))NEWLINE return None, NoneNEWLINE stdout = p.communicate()[0].strip()NEWLINE if sys.version_info[0] >= 3:NEWLINE stdout = stdout.decode()NEWLINE if p.returncode != 0:NEWLINE if verbose:NEWLINE print("unable to run %s (error)" % dispcmd)NEWLINE print("stdout was %s" % stdout)NEWLINE return None, p.returncodeNEWLINE return stdout, p.returncodeNEWLINENEWLINENEWLINEdef versions_from_parentdir(parentdir_prefix, root, verbose):NEWLINE """Try to determine the version from the parent directory name.NEWLINENEWLINE Source tarballs conventionally unpack into a directory that includes bothNEWLINE the project name and a version string. We will also support searching upNEWLINE two directory levels for an appropriately named parent directoryNEWLINE """NEWLINE rootdirs = []NEWLINENEWLINE for i in range(3):NEWLINE dirname = os.path.basename(root)NEWLINE if dirname.startswith(parentdir_prefix):NEWLINE return {"version": dirname[len(parentdir_prefix):],NEWLINE "full-revisionid": None,NEWLINE "dirty": False, "error": None, "date": None}NEWLINE else:NEWLINE rootdirs.append(root)NEWLINE root = os.path.dirname(root) # up a levelNEWLINENEWLINE if verbose:NEWLINE print("Tried directories %s but none started with prefix %s" %NEWLINE (str(rootdirs), parentdir_prefix))NEWLINE raise NotThisMethod("rootdir doesn't start with parentdir_prefix")NEWLINENEWLINENEWLINE@register_vcs_handler("git", "get_keywords")NEWLINEdef git_get_keywords(versionfile_abs):NEWLINE """Extract version information from the given file."""NEWLINE # the code embedded in _version.py can just fetch the value of theseNEWLINE # keywords. When used from setup.py, we don't want to import _version.py,NEWLINE # so we do it with a regexp instead. This function is not used fromNEWLINE # _version.py.NEWLINE keywords = {}NEWLINE try:NEWLINE f = open(versionfile_abs, "r")NEWLINE for line in f.readlines():NEWLINE if line.strip().startswith("git_refnames ="):NEWLINE mo = re.search(r'=\s*"(.*)"', line)NEWLINE if mo:NEWLINE keywords["refnames"] = mo.group(1)NEWLINE if line.strip().startswith("git_full ="):NEWLINE mo = re.search(r'=\s*"(.*)"', line)NEWLINE if mo:NEWLINE keywords["full"] = mo.group(1)NEWLINE if line.strip().startswith("git_date ="):NEWLINE mo = re.search(r'=\s*"(.*)"', line)NEWLINE if mo:NEWLINE keywords["date"] = mo.group(1)NEWLINE f.close()NEWLINE except EnvironmentError:NEWLINE passNEWLINE return keywordsNEWLINENEWLINENEWLINE@register_vcs_handler("git", "keywords")NEWLINEdef git_versions_from_keywords(keywords, tag_prefix, verbose):NEWLINE """Get version information from git keywords."""NEWLINE if not keywords:NEWLINE raise NotThisMethod("no keywords at all, weird")NEWLINE date = keywords.get("date")NEWLINE if date is not None:NEWLINE # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliantNEWLINE # datestamp. However we prefer "%ci" (which expands to an "ISO-8601NEWLINE # -like" string, which we must then edit to make compliant), becauseNEWLINE # it's been around since git-1.5.3, and it's too difficult toNEWLINE # discover which version we're using, or to work around using anNEWLINE # older one.NEWLINE date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)NEWLINE refnames = keywords["refnames"].strip()NEWLINE if refnames.startswith("$Format"):NEWLINE if verbose:NEWLINE print("keywords are unexpanded, not using")NEWLINE raise NotThisMethod("unexpanded keywords, not a git-archive tarball")NEWLINE refs = set([r.strip() for r in refnames.strip("()").split(",")])NEWLINE # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead ofNEWLINE # just "foo-1.0". If we see a "tag: " prefix, prefer those.NEWLINE TAG = "tag: "NEWLINE tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])NEWLINE if not tags:NEWLINE # Either we're using git < 1.8.3, or there really are no tags. We useNEWLINE # a heuristic: assume all version tags have a digit. The old git %dNEWLINE # expansion behaves like git log --decorate=short and strips out theNEWLINE # refs/heads/ and refs/tags/ prefixes that would let us distinguishNEWLINE # between branches and tags. By ignoring refnames without digits, weNEWLINE # filter out many common branch names like "release" andNEWLINE # "stabilization", as well as "HEAD" and "master".NEWLINE tags = set([r for r in refs if re.search(r'\d', r)])NEWLINE if verbose:NEWLINE print("discarding '%s', no digits" % ",".join(refs - tags))NEWLINE if verbose:NEWLINE print("likely tags: %s" % ",".join(sorted(tags)))NEWLINE for ref in sorted(tags):NEWLINE # sorting will prefer e.g. "2.0" over "2.0rc1"NEWLINE if ref.startswith(tag_prefix):NEWLINE r = ref[len(tag_prefix):]NEWLINE if verbose:NEWLINE print("picking %s" % r)NEWLINE return {"version": r,NEWLINE "full-revisionid": keywords["full"].strip(),NEWLINE "dirty": False, "error": None,NEWLINE "date": date}NEWLINE # no suitable tags, so version is "0+unknown", but full hex is still thereNEWLINE if verbose:NEWLINE print("no suitable tags, using unknown + full revision id")NEWLINE return {"version": "0+unknown",NEWLINE "full-revisionid": keywords["full"].strip(),NEWLINE "dirty": False, "error": "no suitable tags", "date": None}NEWLINENEWLINENEWLINE@register_vcs_handler("git", "pieces_from_vcs")NEWLINEdef git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):NEWLINE """Get version from 'git describe' in the root of the source tree.NEWLINENEWLINE This only gets called if the git-archive 'subst' keywords were *not*NEWLINE expanded, and _version.py hasn't already been rewritten with a shortNEWLINE version string, meaning we're inside a checked out source tree.NEWLINE """NEWLINE GITS = ["git"]NEWLINE if sys.platform == "win32":NEWLINE GITS = ["git.cmd", "git.exe"]NEWLINENEWLINE out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root,NEWLINE hide_stderr=True)NEWLINE if rc != 0:NEWLINE if verbose:NEWLINE print("Directory %s not under git control" % root)NEWLINE raise NotThisMethod("'git rev-parse --git-dir' returned error")NEWLINENEWLINE # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]NEWLINE # if there isn't one, this yields HEX[-dirty] (no NUM)NEWLINE describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",NEWLINE "--always", "--long",NEWLINE "--match", "%s*" % tag_prefix],NEWLINE cwd=root)NEWLINE # --long was added in git-1.5.5NEWLINE if describe_out is None:NEWLINE raise NotThisMethod("'git describe' failed")NEWLINE describe_out = describe_out.strip()NEWLINE full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)NEWLINE if full_out is None:NEWLINE raise NotThisMethod("'git rev-parse' failed")NEWLINE full_out = full_out.strip()NEWLINENEWLINE pieces = {}NEWLINE pieces["long"] = full_outNEWLINE pieces["short"] = full_out[:7] # maybe improved laterNEWLINE pieces["error"] = NoneNEWLINENEWLINE # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]NEWLINE # TAG might have hyphens.NEWLINE git_describe = describe_outNEWLINENEWLINE # look for -dirty suffixNEWLINE dirty = git_describe.endswith("-dirty")NEWLINE pieces["dirty"] = dirtyNEWLINE if dirty:NEWLINE git_describe = git_describe[:git_describe.rindex("-dirty")]NEWLINENEWLINE # now we have TAG-NUM-gHEX or HEXNEWLINENEWLINE if "-" in git_describe:NEWLINE # TAG-NUM-gHEXNEWLINE mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)NEWLINE if not mo:NEWLINE # unparseable. Maybe git-describe is misbehaving?NEWLINE pieces["error"] = ("unable to parse git-describe output: '%s'"NEWLINE % describe_out)NEWLINE return piecesNEWLINENEWLINE # tagNEWLINE full_tag = mo.group(1)NEWLINE if not full_tag.startswith(tag_prefix):NEWLINE if verbose:NEWLINE fmt = "tag '%s' doesn't start with prefix '%s'"NEWLINE print(fmt % (full_tag, tag_prefix))NEWLINE pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"NEWLINE % (full_tag, tag_prefix))NEWLINE return piecesNEWLINE pieces["closest-tag"] = full_tag[len(tag_prefix):]NEWLINENEWLINE # distance: number of commits since tagNEWLINE pieces["distance"] = int(mo.group(2))NEWLINENEWLINE # commit: short hex revision IDNEWLINE pieces["short"] = mo.group(3)NEWLINENEWLINE else:NEWLINE # HEX: no tagsNEWLINE pieces["closest-tag"] = NoneNEWLINE count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"],NEWLINE cwd=root)NEWLINE pieces["distance"] = int(count_out) # total number of commitsNEWLINENEWLINE # commit date: see ISO-8601 comment in git_versions_from_keywords()NEWLINE date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"],NEWLINE cwd=root)[0].strip()NEWLINE pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)NEWLINENEWLINE return piecesNEWLINENEWLINENEWLINEdef plus_or_dot(pieces):NEWLINE """Return a + if we don't already have one, else return a ."""NEWLINE if "+" in pieces.get("closest-tag", ""):NEWLINE return "."NEWLINE return "+"NEWLINENEWLINENEWLINEdef render_pep440(pieces):NEWLINE """Build up version string, with post-release "local version identifier".NEWLINENEWLINE Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if youNEWLINE get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirtyNEWLINENEWLINE Exceptions:NEWLINE 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"] or pieces["dirty"]:NEWLINE rendered += plus_or_dot(pieces)NEWLINE rendered += "%d.g%s" % (pieces["distance"], pieces["short"])NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dirty"NEWLINE else:NEWLINE # exception #1NEWLINE rendered = "0+untagged.%d.g%s" % (pieces["distance"],NEWLINE pieces["short"])NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dirty"NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_pep440_pre(pieces):NEWLINE """TAG[.post.devDISTANCE] -- No -dirty.NEWLINENEWLINE Exceptions:NEWLINE 1: no tags. 0.post.devDISTANCENEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"]:NEWLINE rendered += ".post.dev%d" % pieces["distance"]NEWLINE else:NEWLINE # exception #1NEWLINE rendered = "0.post.dev%d" % pieces["distance"]NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_pep440_post(pieces):NEWLINE """TAG[.postDISTANCE[.dev0]+gHEX] .NEWLINENEWLINE The ".dev0" means dirty. Note that .dev0 sorts backwardsNEWLINE (a dirty tree will appear "older" than the corresponding clean one),NEWLINE but you shouldn't be releasing software with -dirty anyways.NEWLINENEWLINE Exceptions:NEWLINE 1: no tags. 0.postDISTANCE[.dev0]NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"] or pieces["dirty"]:NEWLINE rendered += ".post%d" % pieces["distance"]NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dev0"NEWLINE rendered += plus_or_dot(pieces)NEWLINE rendered += "g%s" % pieces["short"]NEWLINE else:NEWLINE # exception #1NEWLINE rendered = "0.post%d" % pieces["distance"]NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dev0"NEWLINE rendered += "+g%s" % pieces["short"]NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_pep440_old(pieces):NEWLINE """TAG[.postDISTANCE[.dev0]] .NEWLINENEWLINE The ".dev0" means dirty.NEWLINENEWLINE Eexceptions:NEWLINE 1: no tags. 0.postDISTANCE[.dev0]NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"] or pieces["dirty"]:NEWLINE rendered += ".post%d" % pieces["distance"]NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dev0"NEWLINE else:NEWLINE # exception #1NEWLINE rendered = "0.post%d" % pieces["distance"]NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dev0"NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_git_describe(pieces):NEWLINE """TAG[-DISTANCE-gHEX][-dirty].NEWLINENEWLINE Like 'git describe --tags --dirty --always'.NEWLINENEWLINE Exceptions:NEWLINE 1: no tags. HEX[-dirty] (note: no 'g' prefix)NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"]:NEWLINE rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])NEWLINE else:NEWLINE # exception #1NEWLINE rendered = pieces["short"]NEWLINE if pieces["dirty"]:NEWLINE rendered += "-dirty"NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_git_describe_long(pieces):NEWLINE """TAG-DISTANCE-gHEX[-dirty].NEWLINENEWLINE Like 'git describe --tags --dirty --always -long'.NEWLINE The distance/hash is unconditional.NEWLINENEWLINE Exceptions:NEWLINE 1: no tags. HEX[-dirty] (note: no 'g' prefix)NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])NEWLINE else:NEWLINE # exception #1NEWLINE rendered = pieces["short"]NEWLINE if pieces["dirty"]:NEWLINE rendered += "-dirty"NEWLINE return renderedNEWLINENEWLINENEWLINEdef render(pieces, style):NEWLINE """Render the given version pieces into the requested style."""NEWLINE if pieces["error"]:NEWLINE return {"version": "unknown",NEWLINE "full-revisionid": pieces.get("long"),NEWLINE "dirty": None,NEWLINE "error": pieces["error"],NEWLINE "date": None}NEWLINENEWLINE if not style or style == "default":NEWLINE style = "pep440" # the defaultNEWLINENEWLINE if style == "pep440":NEWLINE rendered = render_pep440(pieces)NEWLINE elif style == "pep440-pre":NEWLINE rendered = render_pep440_pre(pieces)NEWLINE elif style == "pep440-post":NEWLINE rendered = render_pep440_post(pieces)NEWLINE elif style == "pep440-old":NEWLINE rendered = render_pep440_old(pieces)NEWLINE elif style == "git-describe":NEWLINE rendered = render_git_describe(pieces)NEWLINE elif style == "git-describe-long":NEWLINE rendered = render_git_describe_long(pieces)NEWLINE else:NEWLINE raise ValueError("unknown style '%s'" % style)NEWLINENEWLINE return {"version": rendered, "full-revisionid": pieces["long"],NEWLINE "dirty": pieces["dirty"], "error": None,NEWLINE "date": pieces.get("date")}NEWLINENEWLINENEWLINEdef get_versions():NEWLINE """Get version information or return default if unable to do so."""NEWLINE # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we haveNEWLINE # __file__, we can work backwards from there to the root. SomeNEWLINE # py2exe/bbfreeze/non-CPython implementations don't do __file__, in whichNEWLINE # case we can only use expanded keywords.NEWLINENEWLINE cfg = get_config()NEWLINE verbose = cfg.verboseNEWLINENEWLINE try:NEWLINE return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,NEWLINE verbose)NEWLINE except NotThisMethod:NEWLINE passNEWLINENEWLINE try:NEWLINE root = os.path.realpath(__file__)NEWLINE # versionfile_source is the relative path from the top of the sourceNEWLINE # tree (where the .git directory might live) to this file. InvertNEWLINE # this to find the root from __file__.NEWLINE for i in cfg.versionfile_source.split('/'):NEWLINE root = os.path.dirname(root)NEWLINE except NameError:NEWLINE return {"version": "0+unknown", "full-revisionid": None,NEWLINE "dirty": None,NEWLINE "error": "unable to find root of source tree",NEWLINE "date": None}NEWLINENEWLINE try:NEWLINE pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)NEWLINE return render(pieces, cfg.style)NEWLINE except NotThisMethod:NEWLINE passNEWLINENEWLINE try:NEWLINE if cfg.parentdir_prefix:NEWLINE return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)NEWLINE except NotThisMethod:NEWLINE passNEWLINENEWLINE return {"version": "0+unknown", "full-revisionid": None,NEWLINE "dirty": None,NEWLINE "error": "unable to compute version", "date": None}NEWLINE # Copyright 2017 AT&T Intellectual Property. All other rights reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE"""Noop driver for manually executing OOB tasks."""NEWLINENEWLINEimport timeNEWLINEimport loggingNEWLINENEWLINEfrom oslo_config import cfgNEWLINENEWLINEimport drydock_provisioner.error as errorsNEWLINENEWLINEimport drydock_provisioner.objects.fields as hd_fieldsNEWLINENEWLINEimport drydock_provisioner.drivers.oob.driver as oobNEWLINENEWLINENEWLINEclass ManualDriver(oob.OobDriver):NEWLINENEWLINE oob_types_supported = ['manual']NEWLINENEWLINE def __init__(self, **kwargs):NEWLINE super(ManualDriver, self).__init__(**kwargs)NEWLINENEWLINE self.driver_name = "manual_driver"NEWLINE self.driver_key = "manual_driver"NEWLINE self.driver_desc = "Manual (Noop) OOB Driver"NEWLINENEWLINE self.logger = logging.getLogger(cfg.CONF.logging.oobdriver_logger_name)NEWLINENEWLINE def execute_task(self, task_id):NEWLINE task = self.state_manager.get_task(task_id)NEWLINENEWLINE if task is None:NEWLINE self.logger.error("Invalid task %s" % (task_id))NEWLINE raise errors.DriverError("Invalid task %s" % (task_id))NEWLINENEWLINE if task.action not in self.supported_actions:NEWLINE self.logger.error("Driver %s doesn't support task action %s" %NEWLINE (self.driver_desc, task.action))NEWLINE raise errors.DriverError("Driver %s doesn't support task action %s"NEWLINE % (self.driver_desc, task.action))NEWLINENEWLINE design_ref = task.design_refNEWLINENEWLINE if design_ref is None:NEWLINE raise errors.DriverError(NEWLINE "No design ID specified in task %s" % (task_id))NEWLINENEWLINE self.orchestrator.task_field_update(NEWLINE task.get_id(), status=hd_fields.TaskStatus.Running)NEWLINENEWLINE self.logger.info("Sleeping 60s to allow time for manual OOB %s action"NEWLINE % task.action)NEWLINENEWLINE time.sleep(60)NEWLINENEWLINE task.set_status(hd_fields.TaskStatus.Complete)NEWLINE task.success()NEWLINE task.save()NEWLINENEWLINE returnNEWLINE from datetime import dateNEWLINEfrom datetime import datetimeNEWLINEfrom datetime import timedelta as deltaNEWLINENEWLINEimport sysNEWLINEimport numpy as npNEWLINEimport xarray as xrNEWLINENEWLINEfrom parcels.grid import GridCodeNEWLINEfrom parcels.grid import CurvilinearGridNEWLINEfrom parcels.kernel import KernelNEWLINEfrom parcels.particle import JITParticleNEWLINEfrom parcels.particlefile import ParticleFileNEWLINEfrom parcels.tools.statuscodes import StateCodeNEWLINEfrom .baseparticleset import BaseParticleSetNEWLINEfrom .collectionsoa import ParticleCollectionSOANEWLINEfrom .collectionsoa import ParticleCollectionIteratorSOANEWLINEfrom parcels.tools.converters import _get_cftime_calendarsNEWLINEfrom parcels.tools.loggers import loggerNEWLINEtry:NEWLINE from mpi4py import MPINEWLINEexcept:NEWLINE MPI = NoneNEWLINE# == comment CK: prevents us from adding KDTree as 'mandatory' dependency == #NEWLINEtry:NEWLINE from pykdtree.kdtree import KDTreeNEWLINEexcept:NEWLINE KDTree = NoneNEWLINENEWLINE__all__ = ['ParticleSet', 'ParticleSetSOA']NEWLINENEWLINENEWLINEdef _convert_to_array(var):NEWLINE """Convert lists and single integers/floats to one-dimensional numpyNEWLINE arraysNEWLINE """NEWLINE if isinstance(var, np.ndarray):NEWLINE return var.flatten()NEWLINE elif isinstance(var, (int, float, np.float32, np.int32)):NEWLINE return np.array([var])NEWLINE else:NEWLINE return np.array(var)NEWLINENEWLINENEWLINEdef _convert_to_reltime(time):NEWLINE """Check to determine if the value of the time parameter needs to beNEWLINE converted to a relative value (relative to the time_origin).NEWLINE """NEWLINE if isinstance(time, np.datetime64) or (hasattr(time, 'calendar') and time.calendar in _get_cftime_calendars()):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINEclass ParticleSetSOA(BaseParticleSet):NEWLINE """Container class for storing particle and executing kernel over them.NEWLINENEWLINE Please note that this currently only supports fixed size particle sets.NEWLINENEWLINE :param fieldset: :mod:`parcels.fieldset.FieldSet` object from which to sample velocity.NEWLINE While fieldset=None is supported, this will throw a warning as it breaks most Parcels functionalityNEWLINE :param pclass: Optional :mod:`parcels.particle.JITParticle` orNEWLINE :mod:`parcels.particle.ScipyParticle` object that defines custom particleNEWLINE :param lon: List of initial longitude values for particlesNEWLINE :param lat: List of initial latitude values for particlesNEWLINE :param depth: Optional list of initial depth values for particles. Default is 0mNEWLINE :param time: Optional list of initial time values for particles. Default is fieldset.U.grid.time[0]NEWLINE :param repeatdt: Optional interval (in seconds) on which to repeat the release of the ParticleSetNEWLINE :param lonlatdepth_dtype: Floating precision for lon, lat, depth particle coordinates.NEWLINE It is either np.float32 or np.float64. Default is np.float32 if fieldset.U.interp_method is 'linear'NEWLINE and np.float64 if the interpolation method is 'cgrid_velocity'NEWLINE :param pid_orig: Optional list of (offsets for) the particle IDsNEWLINE :param partitions: List of cores on which to distribute the particles for MPI runs. Default: None, in which case particlesNEWLINE are distributed automatically on the processorsNEWLINENEWLINE Other Variables can be initialised using further arguments (e.g. v=... for a Variable named 'v')NEWLINE """NEWLINENEWLINE def __init__(self, fieldset=None, pclass=JITParticle, lon=None, lat=None, depth=None, time=None, repeatdt=None, lonlatdepth_dtype=None, pid_orig=None, **kwargs):NEWLINE super(ParticleSetSOA, self).__init__()NEWLINE self.fieldset = fieldsetNEWLINE if self.fieldset is None:NEWLINE logger.warning_once("No FieldSet provided in ParticleSet generation. "NEWLINE "This breaks most Parcels functionality")NEWLINE else:NEWLINE self.fieldset.check_complete()NEWLINE partitions = kwargs.pop('partitions', None)NEWLINENEWLINE lon = np.empty(shape=0) if lon is None else _convert_to_array(lon)NEWLINE lat = np.empty(shape=0) if lat is None else _convert_to_array(lat)NEWLINENEWLINE if isinstance(pid_orig, (type(None), type(False))):NEWLINE pid_orig = np.arange(lon.size)NEWLINENEWLINE if depth is None:NEWLINE mindepth = self.fieldset.gridset.dimrange('depth')[0] if self.fieldset is not None else 0NEWLINE depth = np.ones(lon.size) * mindepthNEWLINE else:NEWLINE depth = _convert_to_array(depth)NEWLINE assert lon.size == lat.size and lon.size == depth.size, (NEWLINE 'lon, lat, depth don''t all have the same lenghts')NEWLINENEWLINE time = _convert_to_array(time)NEWLINE time = np.repeat(time, lon.size) if time.size == 1 else timeNEWLINENEWLINE if time.size > 0 and type(time[0]) in [datetime, date]:NEWLINE time = np.array([np.datetime64(t) for t in time])NEWLINE self.time_origin = fieldset.time_origin if self.fieldset is not None else 0NEWLINE if time.size > 0 and isinstance(time[0], np.timedelta64) and not self.time_origin:NEWLINE raise NotImplementedError('If fieldset.time_origin is not a date, time of a particle must be a double')NEWLINE time = np.array([self.time_origin.reltime(t) if _convert_to_reltime(t) else t for t in time])NEWLINE assert lon.size == time.size, (NEWLINE 'time and positions (lon, lat, depth) don''t have the same lengths.')NEWLINENEWLINE if lonlatdepth_dtype is None:NEWLINE if fieldset is not None:NEWLINE lonlatdepth_dtype = self.lonlatdepth_dtype_from_field_interp_method(fieldset.U)NEWLINE else:NEWLINE lonlatdepth_dtype = np.float32NEWLINE assert lonlatdepth_dtype in [np.float32, np.float64], \NEWLINE 'lon lat depth precision should be set to either np.float32 or np.float64'NEWLINENEWLINE for kwvar in kwargs:NEWLINE kwargs[kwvar] = _convert_to_array(kwargs[kwvar])NEWLINE assert lon.size == kwargs[kwvar].size, (NEWLINE '%s and positions (lon, lat, depth) don''t have the same lengths.' % kwvar)NEWLINENEWLINE self.repeatdt = repeatdt.total_seconds() if isinstance(repeatdt, delta) else repeatdtNEWLINE if self.repeatdt:NEWLINE if self.repeatdt <= 0:NEWLINE raise('Repeatdt should be > 0')NEWLINE if time[0] and not np.allclose(time, time[0]):NEWLINE raise ('All Particle.time should be the same when repeatdt is not None')NEWLINE self.repeatpclass = pclassNEWLINE self.repeatkwargs = kwargsNEWLINENEWLINE ngrids = fieldset.gridset.size if fieldset is not None else 1NEWLINE self._collection = ParticleCollectionSOA(pclass, lon=lon, lat=lat, depth=depth, time=time, lonlatdepth_dtype=lonlatdepth_dtype, pid_orig=pid_orig, partitions=partitions, ngrid=ngrids, **kwargs)NEWLINENEWLINE if self.repeatdt:NEWLINE if len(time) > 0 and time[0] is None:NEWLINE self.repeat_starttime = time[0]NEWLINE else:NEWLINE if self._collection.data['time'][0] and not np.allclose(self._collection.data['time'], self._collection.data['time'][0]):NEWLINE raise ValueError('All Particle.time should be the same when repeatdt is not None')NEWLINE self.repeat_starttime = self._collection.data['time'][0]NEWLINE self.repeatlon = self._collection.data['lon']NEWLINE self.repeatlat = self._collection.data['lat']NEWLINE self.repeatdepth = self._collection.data['depth']NEWLINE for kwvar in kwargs:NEWLINE self.repeatkwargs[kwvar] = self._collection.data[kwvar]NEWLINENEWLINE if self.repeatdt:NEWLINE if MPI and self._collection.pu_indicators is not None:NEWLINE mpi_comm = MPI.COMM_WORLDNEWLINE mpi_rank = mpi_comm.Get_rank()NEWLINE self.repeatpid = pid_orig[self._collection.pu_indicators == mpi_rank]NEWLINENEWLINE self.kernel = NoneNEWLINENEWLINE def _set_particle_vector(self, name, value):NEWLINE """Set attributes of all particles to new values.NEWLINENEWLINE :param name: Name of the attribute (str).NEWLINE :param value: New value to set the attribute of the particles to.NEWLINE """NEWLINE self.collection._data[name][:] = valueNEWLINENEWLINE def _impute_release_times(self, default):NEWLINE """Set attribute 'time' to default if encountering NaN values.NEWLINENEWLINE :param default: Default release time.NEWLINE :return: Minimum and maximum release times.NEWLINE """NEWLINE if np.any(np.isnan(self._collection.data['time'])):NEWLINE self._collection.data['time'][np.isnan(self._collection.data['time'])] = defaultNEWLINE return np.min(self._collection.data['time']), np.max(self._collection.data['time'])NEWLINENEWLINE def data_indices(self, variable_name, compare_values, invert=False):NEWLINE """Get the indices of all particles where the value ofNEWLINE `variable_name` equals (one of) `compare_values`.NEWLINENEWLINE :param variable_name: Name of the variable to check.NEWLINE :param compare_values: Value or list of values to compare to.NEWLINE :param invert: Whether to invert the selection. I.e., when True,NEWLINE return all indices that do not equal (one of)NEWLINE `compare_values`.NEWLINE :return: Numpy array of indices that satisfy the test.NEWLINE """NEWLINE compare_values = np.array([compare_values, ]) if type(compare_values) not in [list, dict, np.ndarray] else compare_valuesNEWLINE return np.where(np.isin(self._collection.data[variable_name], compare_values, invert=invert))[0]NEWLINENEWLINE def indexed_subset(self, indices):NEWLINE return ParticleCollectionIteratorSOA(self._collection,NEWLINE subset=indices)NEWLINENEWLINE def populate_indices(self):NEWLINE """Pre-populate guesses of particle xi/yi indices using a kdtree.NEWLINENEWLINE This is only intended for curvilinear grids, where the initial index searchNEWLINE may be quite expensive.NEWLINE """NEWLINENEWLINE if self.fieldset is None:NEWLINE # we need to be attached to a fieldset to have a validNEWLINE # gridset to search for indicesNEWLINE returnNEWLINENEWLINE if KDTree is None:NEWLINE returnNEWLINE else:NEWLINE for i, grid in enumerate(self.fieldset.gridset.grids):NEWLINE if not isinstance(grid, CurvilinearGrid):NEWLINE continueNEWLINENEWLINE tree_data = np.stack((grid.lon.flat, grid.lat.flat), axis=-1)NEWLINE tree = KDTree(tree_data)NEWLINE # stack all the particle positions for a single queryNEWLINE pts = np.stack((self._collection.data['lon'], self._collection.data['lat']), axis=-1)NEWLINE # query datatype needs to match tree datatypeNEWLINE _, idx = tree.query(pts.astype(tree_data.dtype))NEWLINE yi, xi = np.unravel_index(idx, grid.lon.shape)NEWLINENEWLINE self._collection.data['xi'][:, i] = xiNEWLINE self._collection.data['yi'][:, i] = yiNEWLINENEWLINE @propertyNEWLINE def error_particles(self):NEWLINE """Get an iterator over all particles that are in an error state.NEWLINENEWLINE :return: Collection iterator over error particles.NEWLINE """NEWLINE error_indices = self.data_indices('state', [StateCode.Success, StateCode.Evaluate], invert=True)NEWLINE return ParticleCollectionIteratorSOA(self._collection, subset=error_indices)NEWLINENEWLINE @propertyNEWLINE def num_error_particles(self):NEWLINE """Get the number of particles that are in an error state.NEWLINENEWLINE :return: The number of error particles.NEWLINE """NEWLINE return np.sum(np.isin(NEWLINE self._collection.data['state'],NEWLINE [StateCode.Success, StateCode.Evaluate], invert=True))NEWLINENEWLINE def __getitem__(self, index):NEWLINE """Get a single particle by index"""NEWLINE return self._collection.get_single_by_index(index)NEWLINENEWLINE def cstruct(self):NEWLINE """NEWLINE 'cstruct' returns the ctypes mapping of the combined collections cstruct and the fieldset cstruct.NEWLINE This depends on the specific structure in question.NEWLINE """NEWLINE cstruct = self._collection.cstruct()NEWLINE return cstructNEWLINENEWLINE @propertyNEWLINE def ctypes_struct(self):NEWLINE return self.cstruct()NEWLINENEWLINE @classmethodNEWLINE def monte_carlo_sample(cls, start_field, size, mode='monte_carlo'):NEWLINE """NEWLINE Converts a starting field into a monte-carlo sample of lons and lats.NEWLINENEWLINE :param start_field: :mod:`parcels.fieldset.Field` object for initialising particles stochastically (horizontally) according to the presented density field.NEWLINENEWLINE returns list(lon), list(lat)NEWLINE """NEWLINE if mode == 'monte_carlo':NEWLINE data = start_field.data if isinstance(start_field.data, np.ndarray) else np.array(start_field.data)NEWLINE if start_field.interp_method == 'cgrid_tracer':NEWLINE p_interior = np.squeeze(data[0, 1:, 1:])NEWLINE else: # if A-gridNEWLINE d = dataNEWLINE p_interior = (d[0, :-1, :-1] + d[0, 1:, :-1] + d[0, :-1, 1:] + d[0, 1:, 1:])/4.NEWLINE p_interior = np.where(d[0, :-1, :-1] == 0, 0, p_interior)NEWLINE p_interior = np.where(d[0, 1:, :-1] == 0, 0, p_interior)NEWLINE p_interior = np.where(d[0, 1:, 1:] == 0, 0, p_interior)NEWLINE p_interior = np.where(d[0, :-1, 1:] == 0, 0, p_interior)NEWLINE p = np.reshape(p_interior, (1, p_interior.size))NEWLINE inds = np.random.choice(p_interior.size, size, replace=True, p=p[0] / np.sum(p))NEWLINE xsi = np.random.uniform(size=len(inds))NEWLINE eta = np.random.uniform(size=len(inds))NEWLINE j, i = np.unravel_index(inds, p_interior.shape)NEWLINE grid = start_field.gridNEWLINE lon, lat = ([], [])NEWLINE if grid.gtype in [GridCode.RectilinearZGrid, GridCode.RectilinearSGrid]:NEWLINE lon = grid.lon[i] + xsi * (grid.lon[i + 1] - grid.lon[i])NEWLINE lat = grid.lat[j] + eta * (grid.lat[j + 1] - grid.lat[j])NEWLINE else:NEWLINE lons = np.array([grid.lon[j, i], grid.lon[j, i+1], grid.lon[j+1, i+1], grid.lon[j+1, i]])NEWLINE if grid.mesh == 'spherical':NEWLINE lons[1:] = np.where(lons[1:] - lons[0] > 180, lons[1:]-360, lons[1:])NEWLINE lons[1:] = np.where(-lons[1:] + lons[0] > 180, lons[1:]+360, lons[1:])NEWLINE lon = (1-xsi)*(1-eta) * lons[0] +\NEWLINE xsi*(1-eta) * lons[1] +\NEWLINE xsi*eta * lons[2] +\NEWLINE (1-xsi)*eta * lons[3]NEWLINE lat = (1-xsi)*(1-eta) * grid.lat[j, i] +\NEWLINE xsi*(1-eta) * grid.lat[j, i+1] +\NEWLINE xsi*eta * grid.lat[j+1, i+1] +\NEWLINE (1-xsi)*eta * grid.lat[j+1, i]NEWLINE return list(lon), list(lat)NEWLINE else:NEWLINE raise NotImplementedError('Mode %s not implemented. Please use "monte carlo" algorithm instead.' % mode)NEWLINENEWLINE @classmethodNEWLINE def from_field(cls, fieldset, pclass, start_field, size, mode='monte_carlo', depth=None, time=None, repeatdt=None, lonlatdepth_dtype=None):NEWLINE """Initialise the ParticleSet randomly drawn according to distribution from a fieldNEWLINENEWLINE :param fieldset: :mod:`parcels.fieldset.FieldSet` object from which to sample velocityNEWLINE :param pclass: mod:`parcels.particle.JITParticle` or :mod:`parcels.particle.ScipyParticle`NEWLINE object that defines custom particleNEWLINE :param start_field: Field for initialising particles stochastically (horizontally) according to the presented density field.NEWLINE :param size: Initial size of particle setNEWLINE :param mode: Type of random sampling. Currently only 'monte_carlo' is implementedNEWLINE :param depth: Optional list of initial depth values for particles. Default is 0mNEWLINE :param time: Optional start time value for particles. Default is fieldset.U.time[0]NEWLINE :param repeatdt: Optional interval (in seconds) on which to repeat the release of the ParticleSetNEWLINE :param lonlatdepth_dtype: Floating precision for lon, lat, depth particle coordinates.NEWLINE It is either np.float32 or np.float64. Default is np.float32 if fieldset.U.interp_method is 'linear'NEWLINE and np.float64 if the interpolation method is 'cgrid_velocity'NEWLINE """NEWLINE lon, lat = cls.monte_carlo_sample(start_field, size, mode)NEWLINENEWLINE return cls(fieldset=fieldset, pclass=pclass, lon=lon, lat=lat, depth=depth, time=time,NEWLINE lonlatdepth_dtype=lonlatdepth_dtype, repeatdt=repeatdt)NEWLINENEWLINE @classmethodNEWLINE def from_particlefile(cls, fieldset, pclass, filename, restart=True, restarttime=None, repeatdt=None, lonlatdepth_dtype=None, **kwargs):NEWLINE """Initialise the ParticleSet from a netcdf ParticleFile.NEWLINE This creates a new ParticleSet based on locations of all particles writtenNEWLINE in a netcdf ParticleFile at a certain time. Particle IDs are preserved if restart=TrueNEWLINENEWLINE :param fieldset: :mod:`parcels.fieldset.FieldSet` object from which to sample velocityNEWLINE :param pclass: mod:`parcels.particle.JITParticle` or :mod:`parcels.particle.ScipyParticle`NEWLINE object that defines custom particleNEWLINE :param filename: Name of the particlefile from which to read initial conditionsNEWLINE :param restart: Boolean to signal if pset is used for a restart (default is True).NEWLINE In that case, Particle IDs are preserved.NEWLINE :param restarttime: time at which the Particles will be restarted. Default is the last time written.NEWLINE Alternatively, restarttime could be a time value (including np.datetime64) orNEWLINE a callable function such as np.nanmin. The last is useful when running with dt < 0.NEWLINE :param repeatdt: Optional interval (in seconds) on which to repeat the release of the ParticleSetNEWLINE :param lonlatdepth_dtype: Floating precision for lon, lat, depth particle coordinates.NEWLINE It is either np.float32 or np.float64. Default is np.float32 if fieldset.U.interp_method is 'linear'NEWLINE and np.float64 if the interpolation method is 'cgrid_velocity'NEWLINE """NEWLINENEWLINE if repeatdt is not None:NEWLINE logger.warning('Note that the `repeatdt` argument is not retained from %s, and that 'NEWLINE 'setting a new repeatdt will start particles from the _new_ particle 'NEWLINE 'locations.' % filename)NEWLINENEWLINE pfile = xr.open_dataset(str(filename), decode_cf=True)NEWLINE pfile_vars = [v for v in pfile.data_vars]NEWLINENEWLINE vars = {}NEWLINE to_write = {}NEWLINE for v in pclass.getPType().variables:NEWLINE if v.name in pfile_vars:NEWLINE vars[v.name] = np.ma.filled(pfile.variables[v.name], np.nan)NEWLINE elif v.name not in ['xi', 'yi', 'zi', 'ti', 'dt', '_next_dt', 'depth', 'id', 'fileid', 'state'] \NEWLINE and v.to_write:NEWLINE raise RuntimeError('Variable %s is in pclass but not in the particlefile' % v.name)NEWLINE to_write[v.name] = v.to_writeNEWLINE vars['depth'] = np.ma.filled(pfile.variables['z'], np.nan)NEWLINE vars['id'] = np.ma.filled(pfile.variables['trajectory'], np.nan)NEWLINENEWLINE if isinstance(vars['time'][0, 0], np.timedelta64):NEWLINE vars['time'] = np.array([t/np.timedelta64(1, 's') for t in vars['time']])NEWLINENEWLINE if restarttime is None:NEWLINE restarttime = np.nanmax(vars['time'])NEWLINE elif callable(restarttime):NEWLINE restarttime = restarttime(vars['time'])NEWLINE else:NEWLINE restarttime = restarttimeNEWLINENEWLINE inds = np.where(vars['time'] == restarttime)NEWLINE for v in vars:NEWLINE if to_write[v] is True:NEWLINE vars[v] = vars[v][inds]NEWLINE elif to_write[v] == 'once':NEWLINE vars[v] = vars[v][inds[0]]NEWLINE if v not in ['lon', 'lat', 'depth', 'time', 'id']:NEWLINE kwargs[v] = vars[v]NEWLINENEWLINE if restart:NEWLINE pclass.setLastID(0) # reset to zero offsetNEWLINE else:NEWLINE vars['id'] = NoneNEWLINENEWLINE return cls(fieldset=fieldset, pclass=pclass, lon=vars['lon'], lat=vars['lat'],NEWLINE depth=vars['depth'], time=vars['time'], pid_orig=vars['id'],NEWLINE lonlatdepth_dtype=lonlatdepth_dtype, repeatdt=repeatdt, **kwargs)NEWLINENEWLINE def to_dict(self, pfile, time, deleted_only=False):NEWLINE """NEWLINE Convert all Particle data from one time step to a python dictionary.NEWLINE :param pfile: ParticleFile object requesting the conversionNEWLINE :param time: Time at which to write ParticleSetNEWLINE :param deleted_only: Flag to write only the deleted ParticlesNEWLINE returns two dictionaries: one for all variables to be written each outputdt,NEWLINE and one for all variables to be written onceNEWLINE """NEWLINE return self._collection.toDictionary(pfile=pfile, time=time,NEWLINE deleted_only=deleted_only)NEWLINENEWLINE @propertyNEWLINE def size(self):NEWLINE # ==== to change at some point - len and size are different things ==== #NEWLINE return len(self._collection)NEWLINENEWLINE def __repr__(self):NEWLINE return "\n".join([str(p) for p in self])NEWLINENEWLINE def __len__(self):NEWLINE return len(self._collection)NEWLINENEWLINE def __sizeof__(self):NEWLINE return sys.getsizeof(self._collection)NEWLINENEWLINE def __iadd__(self, particles):NEWLINE """Add particles to the ParticleSet. Note that this is anNEWLINE incremental add, the particles will be added to the ParticleSetNEWLINE on which this function is called.NEWLINENEWLINE :param particles: Another ParticleSet containing particles to addNEWLINE to this one.NEWLINE :return: The current ParticleSetNEWLINE """NEWLINE self.add(particles)NEWLINE return selfNEWLINENEWLINE def add(self, particles):NEWLINE """Add particles to the ParticleSet. Note that this is anNEWLINE incremental add, the particles will be added to the ParticleSetNEWLINE on which this function is called.NEWLINENEWLINE :param particles: Another ParticleSet containing particles to addNEWLINE to this one.NEWLINE :return: The current ParticleSetNEWLINE """NEWLINE if isinstance(particles, BaseParticleSet):NEWLINE particles = particles.collectionNEWLINE self._collection += particlesNEWLINE return selfNEWLINENEWLINE def remove_indices(self, indices):NEWLINE """Method to remove particles from the ParticleSet, based on their `indices`"""NEWLINE if type(indices) in [int, np.int32, np.intp]:NEWLINE self._collection.remove_single_by_index(indices)NEWLINE else:NEWLINE self._collection.remove_multi_by_indices(indices)NEWLINENEWLINE def remove_booleanvector(self, indices):NEWLINE """Method to remove particles from the ParticleSet, based on an array of booleans"""NEWLINE self.remove_indices(np.where(indices)[0])NEWLINENEWLINE def show(self, with_particles=True, show_time=None, field=None, domain=None, projection=None,NEWLINE land=True, vmin=None, vmax=None, savefile=None, animation=False, **kwargs):NEWLINE """Method to 'show' a Parcels ParticleSetNEWLINENEWLINE :param with_particles: Boolean whether to show particlesNEWLINE :param show_time: Time at which to show the ParticleSetNEWLINE :param field: Field to plot under particles (either None, a Field object, or 'vector')NEWLINE :param domain: dictionary (with keys 'N', 'S', 'E', 'W') defining domain to showNEWLINE :param projection: type of cartopy projection to use (default PlateCarree)NEWLINE :param land: Boolean whether to show land. This is ignored for flat meshesNEWLINE :param vmin: minimum colour scale (only in single-plot mode)NEWLINE :param vmax: maximum colour scale (only in single-plot mode)NEWLINE :param savefile: Name of a file to save the plot toNEWLINE :param animation: Boolean whether result is a single plot, or an animationNEWLINE """NEWLINE from parcels.plotting import plotparticlesNEWLINE plotparticles(particles=self, with_particles=with_particles, show_time=show_time, field=field, domain=domain,NEWLINE projection=projection, land=land, vmin=vmin, vmax=vmax, savefile=savefile, animation=animation, **kwargs)NEWLINENEWLINE def density(self, field_name=None, particle_val=None, relative=False, area_scale=False):NEWLINE """Method to calculate the density of particles in a ParticleSet from their locations,NEWLINE through a 2D histogram.NEWLINENEWLINE :param field: Optional :mod:`parcels.field.Field` object to calculate the histogramNEWLINE on. Default is `fieldset.U`NEWLINE :param particle_val: Optional numpy-array of values to weigh each particle with,NEWLINE or string name of particle variable to use weigh particles with.NEWLINE Default is None, resulting in a value of 1 for each particleNEWLINE :param relative: Boolean to control whether the density is scaled by the totalNEWLINE weight of all particles. Default is FalseNEWLINE :param area_scale: Boolean to control whether the density is scaled by the areaNEWLINE (in m^2) of each grid cell. Default is FalseNEWLINE """NEWLINENEWLINE field_name = field_name if field_name else "U"NEWLINE field = getattr(self.fieldset, field_name)NEWLINENEWLINE f_str = """NEWLINEdef search_kernel(particle, fieldset, time):NEWLINE x = fieldset.{}[time, particle.depth, particle.lat, particle.lon]NEWLINE """.format(field_name)NEWLINENEWLINE k = Kernel(NEWLINE self.fieldset,NEWLINE self._collection.ptype,NEWLINE funcname="search_kernel",NEWLINE funcvars=["particle", "fieldset", "time", "x"],NEWLINE funccode=f_str,NEWLINE )NEWLINE self.execute(pyfunc=k, runtime=0)NEWLINENEWLINE if isinstance(particle_val, str):NEWLINE particle_val = self._collection._data[particle_val]NEWLINE else:NEWLINE particle_val = particle_val if particle_val else np.ones(self.size)NEWLINE density = np.zeros((field.grid.lat.size, field.grid.lon.size), dtype=np.float32)NEWLINENEWLINE for i, p in enumerate(self):NEWLINE try: # breaks if either p.xi, p.yi, p.zi, p.ti do not exist (in scipy) or field not in fieldsetNEWLINE if p.ti[field.igrid] < 0: # xi, yi, zi, ti, not initialisedNEWLINE raise('error')NEWLINE xi = p.xi[field.igrid]NEWLINE yi = p.yi[field.igrid]NEWLINE except:NEWLINE _, _, _, xi, yi, _ = field.search_indices(p.lon, p.lat, p.depth, 0, 0, search2D=True)NEWLINE density[yi, xi] += particle_val[i]NEWLINENEWLINE if relative:NEWLINE density /= np.sum(particle_val)NEWLINENEWLINE if area_scale:NEWLINE density /= field.cell_areas()NEWLINENEWLINE return densityNEWLINENEWLINE def Kernel(self, pyfunc, c_include="", delete_cfiles=True):NEWLINE """Wrapper method to convert a `pyfunc` into a :class:`parcels.kernel.Kernel` objectNEWLINE based on `fieldset` and `ptype` of the ParticleSetNEWLINENEWLINE :param delete_cfiles: Boolean whether to delete the C-files after compilation in JIT mode (default is True)NEWLINE """NEWLINE return Kernel(self.fieldset, self.collection.ptype, pyfunc=pyfunc, c_include=c_include,NEWLINE delete_cfiles=delete_cfiles)NEWLINENEWLINE def ParticleFile(self, *args, **kwargs):NEWLINE """Wrapper method to initialise a :class:`parcels.particlefile.ParticleFile`NEWLINE object from the ParticleSet"""NEWLINE return ParticleFile(*args, particleset=self, **kwargs)NEWLINENEWLINE def set_variable_write_status(self, var, write_status):NEWLINE """NEWLINE Method to set the write status of a VariableNEWLINE :param var: Name of the variable (string)NEWLINE :param write_status: Write status of the variable (True, False orNEWLINE 'once')NEWLINE """NEWLINE self._collection.set_variable_write_status(var, write_status)NEWLINENEWLINENEWLINE# ParticleSet is an alias for ParticleSetSOA, i.e. the defaultNEWLINE# implementation for storing particles is the Structure of ArraysNEWLINE# approach.NEWLINEParticleSet = ParticleSetSOANEWLINE import FWCore.ParameterSet.Config as cmsNEWLINENEWLINEprocess = cms.Process("TEST")NEWLINENEWLINEprocess.source = cms.Source("EmptySource",NEWLINE firstRun = cms.untracked.uint32(1),NEWLINE firstLuminosityBlock = cms.untracked.uint32(2),NEWLINE firstEvent = cms.untracked.uint32(15),NEWLINE numberEventsInRun = cms.untracked.uint32(100),NEWLINE numberEventsInLuminosityBlock = cms.untracked.uint32(100)NEWLINE)NEWLINENEWLINEprocess.maxEvents = cms.untracked.PSet(NEWLINE input = cms.untracked.int32(1)NEWLINE)NEWLINENEWLINEprocess.out = cms.OutputModule("PoolOutputModule",NEWLINE fileName = cms.untracked.string('testRandomServiceTest2.root')NEWLINE)NEWLINEprocess.RandomNumberGeneratorService = cms.Service("RandomNumberGeneratorService",NEWLINENEWLINE t1 = cms.PSet(NEWLINE initialSeed = cms.untracked.uint32(7)NEWLINE ),NEWLINE t2 = cms.PSet(NEWLINE engineName = cms.untracked.string('RanecuEngine'),NEWLINE initialSeedSet = cms.untracked.vuint32(7, 7)NEWLINE ),NEWLINE t3 = cms.PSet(NEWLINE initialSeed = cms.untracked.uint32(7),NEWLINE engineName = cms.untracked.string('TRandom3')NEWLINE ),NEWLINE t4 = cms.PSet(NEWLINE engineName = cms.untracked.string('HepJamesRandom'),NEWLINE initialSeed = cms.untracked.uint32(7)NEWLINE ),NEWLINE t5 = cms.PSet(NEWLINE initialSeed = cms.untracked.uint32(7),NEWLINE engineName = cms.untracked.string('TRandom3')NEWLINE ),NEWLINE enableChecking = cms.untracked.bool(True),NEWLINE restoreFileName = cms.untracked.string('StashState3.data')NEWLINE)NEWLINENEWLINEprocess.t1 = cms.EDAnalyzer("TestRandomNumberServiceGlobal",NEWLINE engineName = cms.untracked.string('HepJamesRandom'),NEWLINE seeds = cms.untracked.vuint32(81),NEWLINE offset = cms.untracked.uint32(2),NEWLINE maxEvents = cms.untracked.uint32(15),NEWLINE nStreams = cms.untracked.uint32(1),NEWLINE skippedEvents = cms.untracked.vuint32(4),NEWLINE seedByLumi = cms.untracked.vuint32(0, 82, 82, 202, 202)NEWLINE)NEWLINEprocess.t2 = cms.EDAnalyzer("TestRandomNumberServiceGlobal",NEWLINE engineName = cms.untracked.string('RanecuEngine'),NEWLINE seeds = cms.untracked.vuint32(1, 2),NEWLINE offset = cms.untracked.uint32(2),NEWLINE maxEvents = cms.untracked.uint32(15),NEWLINE nStreams = cms.untracked.uint32(1),NEWLINE skippedEvents = cms.untracked.vuint32(4),NEWLINE seedByLumi = cms.untracked.vuint32(0, 2, 2, 203, 203)NEWLINE)NEWLINEprocess.t3 = cms.EDAnalyzer("TestRandomNumberServiceGlobal",NEWLINE engineName = cms.untracked.string('TRandom3'),NEWLINE seeds = cms.untracked.vuint32(83),NEWLINE offset = cms.untracked.uint32(2),NEWLINE maxEvents = cms.untracked.uint32(15),NEWLINE nStreams = cms.untracked.uint32(1),NEWLINE skippedEvents = cms.untracked.vuint32(4),NEWLINE seedByLumi = cms.untracked.vuint32(0, 84, 84, 204, 204)NEWLINE)NEWLINEprocess.t4 = cms.EDAnalyzer("TestRandomNumberServiceGlobal",NEWLINE engineName = cms.untracked.string('HepJamesRandom'),NEWLINE seeds = cms.untracked.vuint32(84),NEWLINE offset = cms.untracked.uint32(2),NEWLINE maxEvents = cms.untracked.uint32(15),NEWLINE nStreams = cms.untracked.uint32(1),NEWLINE skippedEvents = cms.untracked.vuint32(4),NEWLINE seedByLumi = cms.untracked.vuint32(0, 85, 85, 205, 205)NEWLINE)NEWLINENEWLINEprocess.p = cms.Path(process.t1+process.t2+process.t3+process.t4)NEWLINEprocess.o = cms.EndPath(process.out)NEWLINE from typing import Any, Dict, GeneratorNEWLINENEWLINEimport pytestNEWLINEfrom pydantic import BaseModelNEWLINENEWLINEfrom xpresso import App, Dependant, FromFormData, Path, SecurityNEWLINEfrom xpresso.security import OAuth2, OAuth2PasswordRequestFormStrictNEWLINEfrom xpresso.testclient import TestClientNEWLINEfrom xpresso.typing import AnnotatedNEWLINENEWLINEreusable_oauth2 = OAuth2(NEWLINE flows={NEWLINE "password": {NEWLINE "tokenUrl": "token",NEWLINE "scopes": {"read:users": "Read the users", "write:users": "Create users"},NEWLINE }NEWLINE }NEWLINE)NEWLINENEWLINENEWLINEclass User(BaseModel):NEWLINE username: strNEWLINENEWLINENEWLINE# Here we use string annotations to test themNEWLINEdef get_current_user(oauth_header: "Annotated[str, Security(reusable_oauth2)]"):NEWLINE user = User(username=oauth_header)NEWLINE return userNEWLINENEWLINENEWLINE# Here we use string annotations to test themNEWLINEdef login(form_data: "FromFormData[OAuth2PasswordRequestFormStrict]"):NEWLINE return form_dataNEWLINENEWLINENEWLINE# Here we use string annotations to test themNEWLINEdef read_current_user(current_user: "Annotated[User, Dependant(get_current_user)]"):NEWLINE return current_userNEWLINENEWLINENEWLINEapp = App(NEWLINE [NEWLINE Path("/users/me", get=read_current_user),NEWLINE Path("/login", post=login),NEWLINE ]NEWLINE)NEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef client() -> Generator[TestClient, None, None]:NEWLINE with TestClient(app) as client:NEWLINE yield clientNEWLINENEWLINENEWLINEopenapi_schema: Dict[str, Any] = {NEWLINE "openapi": "3.0.3",NEWLINE "info": {"title": "API", "version": "0.1.0"},NEWLINE "paths": {NEWLINE "/users/me": {NEWLINE "get": {NEWLINE "responses": {"200": {"description": "Successful Response"}},NEWLINE "security": [{"OAuth2": []}],NEWLINE }NEWLINE },NEWLINE "/login": {NEWLINE "post": {NEWLINE "responses": {NEWLINE "200": {"description": "Successful Response"},NEWLINE "422": {NEWLINE "description": "Validation Error",NEWLINE "content": {NEWLINE "application/json": {NEWLINE "schema": {NEWLINE "$ref": "#/components/schemas/HTTPValidationError"NEWLINE }NEWLINE }NEWLINE },NEWLINE },NEWLINE },NEWLINE "requestBody": {NEWLINE "content": {NEWLINE "application/x-www-form-urlencoded": {NEWLINE "schema": {NEWLINE "required": [NEWLINE "grant_type",NEWLINE "username",NEWLINE "password",NEWLINE "scopes",NEWLINE ],NEWLINE "type": "object",NEWLINE "properties": {NEWLINE "grant_type": {NEWLINE "title": "Grant Type",NEWLINE "enum": ["password"],NEWLINE "type": "string",NEWLINE },NEWLINE "username": {"title": "Username", "type": "string"},NEWLINE "password": {"title": "Password", "type": "string"},NEWLINE "scopes": {NEWLINE "title": "Scopes",NEWLINE "type": "array",NEWLINE "items": {"type": "string"},NEWLINE },NEWLINE "client_id": {NEWLINE "title": "Client Id",NEWLINE "type": "string",NEWLINE "nullable": True,NEWLINE },NEWLINE "client_secret": {NEWLINE "title": "Client Secret",NEWLINE "type": "string",NEWLINE "nullable": True,NEWLINE },NEWLINE },NEWLINE },NEWLINE "encoding": {NEWLINE "grant_type": {"style": "form", "explode": True},NEWLINE "username": {"style": "form", "explode": True},NEWLINE "password": {"style": "form", "explode": True},NEWLINE "scopes": {"style": "spaceDelimited", "explode": False},NEWLINE "client_id": {"style": "form", "explode": True},NEWLINE "client_secret": {"style": "form", "explode": True},NEWLINE },NEWLINE }NEWLINE },NEWLINE "required": True,NEWLINE },NEWLINE }NEWLINE },NEWLINE },NEWLINE "components": {NEWLINE "schemas": {NEWLINE "ValidationError": {NEWLINE "title": "ValidationError",NEWLINE "required": ["loc", "msg", "type"],NEWLINE "type": "object",NEWLINE "properties": {NEWLINE "loc": {NEWLINE "title": "Location",NEWLINE "type": "array",NEWLINE "items": {"oneOf": [{"type": "string"}, {"type": "integer"}]},NEWLINE },NEWLINE "msg": {"title": "Message", "type": "string"},NEWLINE "type": {"title": "Error Type", "type": "string"},NEWLINE },NEWLINE },NEWLINE "HTTPValidationError": {NEWLINE "title": "HTTPValidationError",NEWLINE "type": "object",NEWLINE "properties": {NEWLINE "detail": {NEWLINE "title": "Detail",NEWLINE "type": "array",NEWLINE "items": {"$ref": "#/components/schemas/ValidationError"},NEWLINE }NEWLINE },NEWLINE },NEWLINE },NEWLINE "securitySchemes": {NEWLINE "OAuth2": {NEWLINE "type": "oauth2",NEWLINE "flows": {NEWLINE "password": {NEWLINE "scopes": {NEWLINE "read:users": "Read the users",NEWLINE "write:users": "Create users",NEWLINE },NEWLINE "tokenUrl": "token",NEWLINE }NEWLINE },NEWLINE }NEWLINE },NEWLINE },NEWLINE}NEWLINENEWLINENEWLINEdef test_openapi_schema(client: TestClient):NEWLINE response = client.get("/openapi.json")NEWLINE assert response.status_code == 200, response.textNEWLINE assert response.json() == openapi_schemaNEWLINENEWLINENEWLINEdef test_security_oauth2(client: TestClient):NEWLINE response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"})NEWLINE assert response.status_code == 200, response.textNEWLINE assert response.json() == {"username": "Bearer footokenbar"}NEWLINENEWLINENEWLINEdef test_security_oauth2_password_other_header(client: TestClient):NEWLINE response = client.get("/users/me", headers={"Authorization": "Other footokenbar"})NEWLINE assert response.status_code == 200, response.textNEWLINE assert response.json() == {"username": "Other footokenbar"}NEWLINENEWLINENEWLINEdef test_security_oauth2_password_bearer_no_header(client: TestClient):NEWLINE response = client.get("/users/me")NEWLINE assert response.status_code == 401, response.textNEWLINE assert response.json() == {"detail": "Not authenticated"}NEWLINENEWLINENEWLINErequired_params = {NEWLINE "detail": [NEWLINE {NEWLINE "loc": ["body", "grant_type"],NEWLINE "msg": "field required",NEWLINE "type": "value_error.missing",NEWLINE },NEWLINE {NEWLINE "loc": ["body", "username"],NEWLINE "msg": "field required",NEWLINE "type": "value_error.missing",NEWLINE },NEWLINE {NEWLINE "loc": ["body", "password"],NEWLINE "msg": "field required",NEWLINE "type": "value_error.missing",NEWLINE },NEWLINE ]NEWLINE}NEWLINENEWLINEgrant_type_required = {NEWLINE "detail": [NEWLINE {NEWLINE "loc": ["body", "grant_type"],NEWLINE "msg": "field required",NEWLINE "type": "value_error.missing",NEWLINE }NEWLINE ]NEWLINE}NEWLINENEWLINEgrant_type_incorrect = {NEWLINE "detail": [NEWLINE {NEWLINE "loc": ["body", "grant_type"],NEWLINE "msg": "unexpected value; permitted: 'password'",NEWLINE "type": "value_error.const",NEWLINE "ctx": {"given": "incorrect", "permitted": ["password"]},NEWLINE }NEWLINE ]NEWLINE}NEWLINENEWLINENEWLINE@pytest.mark.parametrize(NEWLINE "data,expected_status,expected_response",NEWLINE [NEWLINE (None, 422, required_params),NEWLINE ({"username": "johndoe", "password": "secret"}, 422, grant_type_required),NEWLINE (NEWLINE {"username": "johndoe", "password": "secret", "grant_type": "incorrect"},NEWLINE 422,NEWLINE grant_type_incorrect,NEWLINE ),NEWLINE (NEWLINE {"username": "johndoe", "password": "secret", "grant_type": "password"},NEWLINE 200,NEWLINE {NEWLINE "grant_type": "password",NEWLINE "username": "johndoe",NEWLINE "password": "secret",NEWLINE "scopes": [],NEWLINE "client_id": None,NEWLINE "client_secret": None,NEWLINE },NEWLINE ),NEWLINE ],NEWLINE)NEWLINEdef test_strict_login(data, expected_status, expected_response, client: TestClient):NEWLINE response = client.post(NEWLINE "/login",NEWLINE data=data,NEWLINE headers={"Content-Type": "application/x-www-form-urlencoded"},NEWLINE )NEWLINE assert response.status_code == expected_statusNEWLINE assert response.json() == expected_responseNEWLINE #!/usr/bin/env python3NEWLINE# -*- coding: utf-8 -*-NEWLINE"""NEWLINECreated on Thu Feb 20 17:06:27 2020NEWLINENEWLINE@author: priyankaNEWLINE"""NEWLINENEWLINE # -*- coding: utf-8 -*-NEWLINENEWLINE# Form implementation generated from reading ui file 'test_v1_tabs.ui'NEWLINE#NEWLINE# Created by: PyQt5 UI code generator 5.12.2NEWLINE#NEWLINE# WARNING! All changes made in this file will be lost!NEWLINENEWLINEfrom PyQt5 import QtCore, QtGui, QtWidgetsNEWLINEfrom PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QPushButton, QWidget, QMessageBox, QFormLayout, QGroupBox, QScrollAreaNEWLINEfrom PyQt5.QtSvg import QSvgWidgetNEWLINEfrom PyQt5.QtCore import QProcess, QBasicTimerNEWLINEfrom PyQt5.QtGui import QPainter, QBrush, QPenNEWLINEimport webbrowserNEWLINEimport fileinputNEWLINEimport pandas as pdNEWLINEimport numpy as npNEWLINEimport gzipNEWLINEfrom multiprocessing import ProcessNEWLINEimport globNEWLINEimport datetime as dtNEWLINEimport pickleNEWLINEimport subprocessNEWLINEimport timeNEWLINEimport shlexNEWLINEimport osNEWLINEimport loggingNEWLINEimport stringNEWLINEimport reNEWLINEimport pickleNEWLINEimport sysNEWLINENEWLINENEWLINEmodule_dir=os.path.dirname(__file__)NEWLINEclass Ui_MainWindow(object):NEWLINE def setupUi(self, MainWindow):NEWLINE MainWindow.setObjectName("iCOMIC Pipeline")NEWLINE MainWindow.resize(725, 746)NEWLINE MainWindow.setFixedSize(725, 746)NEWLINE# MainWindow.setStyleSheet("background-image: url(os.path.join(module_dir,'./mainwindow.png'));")NEWLINE sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)NEWLINE sizePolicy.setHorizontalStretch(0)NEWLINE sizePolicy.setVerticalStretch(0)NEWLINE sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())NEWLINE MainWindow.setSizePolicy(sizePolicy)NEWLINE self.centralwidget = QtWidgets.QWidget(MainWindow)NEWLINE self.centralwidget.setObjectName("centralwidget")NEWLINE MainWindow.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint);NEWLINE ## ADDed##NEWLINE self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)NEWLINE self.verticalLayout.setObjectName("verticalLayout")NEWLINE ##NEWLINE self.PipelinetabWidget = QtWidgets.QTabWidget(self.centralwidget)NEWLINE self.PipelinetabWidget.setGeometry(QtCore.QRect(10, 10, 701, 530))NEWLINE self.PipelinetabWidget.setObjectName("PipelinetabWidget")NEWLINE self.DNAseq = QtWidgets.QWidget()NEWLINE self.DNAseq.setObjectName("DNAseq")NEWLINE self.DNAtabWidget = QtWidgets.QTabWidget(self.DNAseq)NEWLINE self.DNAtabWidget.setGeometry(QtCore.QRect(0, 0, 695, 507))NEWLINE self.DNAtabWidget.setObjectName("DNAtabWidget")NEWLINE dnatab_img = os.path.join(module_dir,'dnatab.png')NEWLINE self.DNAtabWidget.setStyleSheet("background-image: url({});".format(dnatab_img))NEWLINE NEWLINENEWLINE ### Test Run Button Grey ###NEWLINE self.one_passed = FalseNEWLINE self.two_passed = FalseNEWLINE ## Make Input as first tab ##NEWLINE self.input_dna = QtWidgets.QWidget()NEWLINE self.input_dna.setObjectName("input_dna")NEWLINE self.SamplesYesradioButton = QtWidgets.QRadioButton(self.input_dna)NEWLINE self.SamplesYesradioButton.move(70, 30)NEWLINE self.SamplesYesradioButton.setObjectName("SamplesYesradioButton")NEWLINE self.SamplesYesradioButton.setChecked(True)NEWLINE self.SamplesNoradioButton = QtWidgets.QRadioButton(self.input_dna)NEWLINE self.SamplesNoradioButton.move(70, 90)NEWLINE self.SamplesNoradioButton.setObjectName("SamplesNoradioButton")NEWLINE self.SampleOrlabel = QtWidgets.QLabel(self.input_dna)NEWLINE self.SampleOrlabel.move(130, 60)NEWLINE font = QtGui.QFont()NEWLINE font.setPointSize(12)NEWLINE font.setItalic(True)NEWLINE self.SampleOrlabel.setFont(font)NEWLINE self.SampleOrlabel.setObjectName("SampleOrlabel")NEWLINE NEWLINE NEWLINE font_label = QtGui.QFont()NEWLINE font_label.setPointSize(8.5)NEWLINE color = QtGui.QColor(233, 10, 150)NEWLINE self.SampleFilelabelDNA = QtWidgets.QLabel(self.input_dna)NEWLINE self.SampleFilelabelDNA.setGeometry(QtCore.QRect(20, 150, 93, 23))NEWLINE self.SampleFilelabelDNA.setObjectName("SampleFilelabelDNA")NEWLINE self.SampleFilelabelDNA.setEnabled(True)NEWLINE self.SampleslineEditDNA = QtWidgets.QLineEdit(self.input_dna)NEWLINE self.SampleslineEditDNA.setGeometry(QtCore.QRect(200, 150, 385, 23))NEWLINE self.SampleslineEditDNA.setObjectName("SampleslineEditDNA")NEWLINE self.SampleslineEditDNA.setEnabled(True)NEWLINE self.SamplesBrowseButtonDNA = QtWidgets.QPushButton(self.input_dna)NEWLINE self.SamplesBrowseButtonDNA.setGeometry(QtCore.QRect(600, 150, 30, 25))NEWLINE self.SamplesBrowseButtonDNA.setObjectName("SamplesBrowseButtonDNA")NEWLINE self.SamplesBrowseButtonDNA.setEnabled(True)NEWLINE self.SamplesErrortextDNA = QtWidgets.QLabel(self.input_dna)NEWLINE self.SamplesErrortextDNA.setGeometry(QtCore.QRect(200, 170, 385, 23))NEWLINE self.SamplesErrortextDNA.setFont(font_label)NEWLINE self.SamplesErrortextDNA.setStyleSheet("color: red")NEWLINE self.UnitsFilelabelDNA = QtWidgets.QLabel(self.input_dna)NEWLINE self.UnitsFilelabelDNA.setGeometry(QtCore.QRect(20, 210, 95, 17))NEWLINE self.UnitsFilelabelDNA.setObjectName("UnitsFilelabelDNA")NEWLINE self.UnitsFilelabelDNA.setEnabled(False)NEWLINE self.UnitslineEditDNA = QtWidgets.QLineEdit(self.input_dna)NEWLINE self.UnitslineEditDNA.setGeometry(QtCore.QRect(200, 210, 385, 23))NEWLINE self.UnitslineEditDNA.setObjectName("UnitslineEditDNA")NEWLINE self.UnitslineEditDNA.setEnabled(False)NEWLINE self.UnitsBrowseButtonDNA = QtWidgets.QPushButton(self.input_dna)NEWLINE self.UnitsBrowseButtonDNA.setGeometry(QtCore.QRect(600, 210, 30, 25))NEWLINE self.UnitsBrowseButtonDNA.setObjectName("UnitsBrowseButtonDNA")NEWLINE self.UnitsBrowseButtonDNA.setEnabled(False)NEWLINE self.UnitsErrortextDNA = QtWidgets.QLabel(self.input_dna)NEWLINE self.UnitsErrortextDNA.setGeometry(QtCore.QRect(200, 230, 385, 23))NEWLINE self.UnitsErrortextDNA.setFont(font_label)NEWLINE self.UnitsErrortextDNA.setStyleSheet("color: red")NEWLINE self.UnitsErroriconDNA = QtWidgets.QPushButton(self.input_dna)NEWLINE self.UnitsErroriconDNA.setGeometry(QtCore.QRect(635, 107, 20, 20))NEWLINE self.UnitsErroriconDNA.setToolTip("Input Units file!")NEWLINE self.UnitsErroriconDNA.setFont(font_label)NEWLINE self.UnitsErroriconDNA.hide()NEWLINE self.UnitsErroriconDNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/warning.svg')))NEWLINE self.RefGenomelabelDNA = QtWidgets.QLabel(self.input_dna)NEWLINE self.RefGenomelabelDNA.setGeometry(QtCore.QRect(20, 270, 125, 17))NEWLINE self.RefGenomelabelDNA.setObjectName("RefGenomelabelDNA")NEWLINE self.RefGenomelineEditDNA = QtWidgets.QLineEdit(self.input_dna)NEWLINE self.RefGenomelineEditDNA.setGeometry(QtCore.QRect(200, 270, 385, 23))NEWLINE self.RefGenomelineEditDNA.setObjectName("RefGenomelineEditDNA")NEWLINE self.RefGenomeBrowseButtonDNA = QtWidgets.QPushButton(self.input_dna)NEWLINE self.RefGenomeBrowseButtonDNA.setGeometry(QtCore.QRect(600, 270, 30, 25))NEWLINE self.RefGenomeBrowseButtonDNA.setObjectName("RefGenomeBrowseButtonDNA")NEWLINE self.RefGenomeErrortextDNA = QtWidgets.QLabel(self.input_dna)NEWLINE self.RefGenomeErrortextDNA.setGeometry(QtCore.QRect(200, 300, 385, 23))NEWLINE self.RefGenomeErrortextDNA.setFont(font_label)NEWLINE self.RefGenomeErrortextDNA.setStyleSheet("color: red")NEWLINE self.RefVariantlabelDNA = QtWidgets.QLabel(self.input_dna)NEWLINE self.RefVariantlabelDNA.setGeometry(QtCore.QRect(20, 330, 157, 17))NEWLINE self.RefVariantlabelDNA.setObjectName("RefVariantlabelDNA")NEWLINE self.RefVariantlineEditDNA = QtWidgets.QLineEdit(self.input_dna)NEWLINE self.RefVariantlineEditDNA.setGeometry(QtCore.QRect(200, 330, 385, 23))NEWLINE self.RefVariantlineEditDNA.setObjectName("RefVariantlineEditDNA")NEWLINE self.RefVariantErrortextDNA = QtWidgets.QLabel(self.input_dna)NEWLINE self.RefVariantErrortextDNA.setGeometry(QtCore.QRect(200, 350, 385, 23))NEWLINE self.RefVariantErrortextDNA.setFont(font_label)NEWLINE self.RefVariantErrortextDNA.setStyleSheet("color: red")NEWLINE self.RefVariantpushButton = QtWidgets.QPushButton(self.input_dna)NEWLINE self.RefVariantpushButton.setGeometry(QtCore.QRect(600, 330, 30, 25))NEWLINE self.RefVariantpushButton.setObjectName("RefVariantpushButton")NEWLINE self.CorelabelDNA = QtWidgets.QLabel(self.input_dna)NEWLINE self.CorelabelDNA.setGeometry(QtCore.QRect(20, 390, 157, 17))NEWLINE self.CorelabelDNA.setObjectName("CorelabelDNA")NEWLINE self.CorelineEditDNA = QtWidgets.QLineEdit(self.input_dna)NEWLINE self.CorelineEditDNA.setGeometry(QtCore.QRect(200, 390, 250, 23))NEWLINE self.CorelineEditDNA.setObjectName("CorelineEditDNA")NEWLINE self.CoreErrortextDNA = QtWidgets.QLabel(self.input_dna)NEWLINE self.CoreErrortextDNA.setGeometry(QtCore.QRect(200, 415, 250, 23))NEWLINE self.CoreErrortextDNA.setFont(font_label)NEWLINE self.CoreErrortextDNA.setStyleSheet("color: red")NEWLINENEWLINE NEWLINE self.nextbuttoninputDNA = QtWidgets.QPushButton(self.input_dna)NEWLINE self.nextbuttoninputDNA.setGeometry(QtCore.QRect(635, 400, 45, 45))NEWLINE self.nextbuttoninputDNA.setObjectName("nextbuttoninputDNA")NEWLINENEWLINE NEWLINE #####info icon####NEWLINE ###dna###NEWLINE NEWLINE font_info = QtGui.QFont()NEWLINE font_info.setPointSize(8.5)NEWLINENEWLINE NEWLINE self.SampleFileinfoicon_dna = QtWidgets.QPushButton(self.input_dna)NEWLINE self.SampleFileinfoicon_dna.setFlat(True)NEWLINE self.SampleFileinfoicon_dna.setGeometry(QtCore.QRect(120, 153, 20, 20))NEWLINE self.SampleFileinfoicon_dna.setToolTip("Browse for the folder containing all the relevant sample files.\n The filenames for all the fastq input data are required to be in the following format.\n (sample_name)_(condition(tumor/normal))_Rep(replicate_number)_R(1 /2 {1 for read1 and 2 for read2}).fastq.\n Example:hcc1395_normal_Rep1_R1.fastq")NEWLINE self.SampleFileinfoicon_dna.setFont(font_info)NEWLINE self.SampleFileinfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.SampleFileinfoicon_dna.setIconSize(QtCore.QSize(13, 13))NEWLINE NEWLINE self.UnitsFileinfoicon_dna = QtWidgets.QPushButton(self.input_dna)NEWLINE self.UnitsFileinfoicon_dna.setFlat(True)NEWLINE self.UnitsFileinfoicon_dna.setGeometry(QtCore.QRect(116, 209, 20, 20))NEWLINE self.UnitsFileinfoicon_dna.setToolTip("Browse for the tab separated text file containing the sample information. \n The table is required to be formatted as follows.\n The column names should take the order: Sample, Unit, Condition, fq1, fq2.\n (Sample- Sample name, Unit- Number of replications, \n Condition- normal/ tumor/ leave blank if the condition is not specified, \n fq1 - Path of Read 1,fq2 - Path of Read 2/ leave blank for single-end reads).\n An example table has been provided for your reference")NEWLINE self.UnitsFileinfoicon_dna.setFont(font_info)NEWLINE self.UnitsFileinfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.UnitsFileinfoicon_dna.setIconSize(QtCore.QSize(13, 13))NEWLINE NEWLINE self.RefGenomeinfoicon_dna = QtWidgets.QPushButton(self.input_dna)NEWLINE self.RefGenomeinfoicon_dna.setFlat(True)NEWLINE self.RefGenomeinfoicon_dna.setGeometry(QtCore.QRect(142, 270, 20, 20))NEWLINE self.RefGenomeinfoicon_dna.setToolTip("A reference genome is a digital nucleic acid database \n assembled to be a representative example of a species’ set of genes.\n It allows for fast alignment of sequences as it is less computationally intensive \n to align sequences to a known sequence map rather than to assemble it piece by piece.\n For this field, specify the path to the pre-downloaded reference genome fastq file")NEWLINE self.RefGenomeinfoicon_dna.setFont(font_info)NEWLINE self.RefGenomeinfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.RefGenomeinfoicon_dna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.RefVariantinfoicon_dna = QtWidgets.QPushButton(self.input_dna)NEWLINE self.RefVariantinfoicon_dna.setFlat(True)NEWLINE self.RefVariantinfoicon_dna.setGeometry(QtCore.QRect(177, 329, 20, 20))NEWLINE self.RefVariantinfoicon_dna.setToolTip("A vcf file specifying the known variant locations")NEWLINE self.RefVariantinfoicon_dna.setFont(font_info)NEWLINE self.RefVariantinfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.RefVariantinfoicon_dna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.SamplesYesradioinfoicon_dna = QtWidgets.QPushButton(self.input_dna)NEWLINE self.SamplesYesradioinfoicon_dna.setFlat(True)NEWLINE self.SamplesYesradioinfoicon_dna.setGeometry(QtCore.QRect(210, 32, 20, 20))NEWLINE self.SamplesYesradioinfoicon_dna.setToolTip("Specify the path to the folder containing all the relevant sample files.\n The filenames for all the fastq input data are required to be in the following format.\n (sample_name)_(condition(tumor/normal))_Rep(replicate_number)_R(1 /2 {1 for read1 and 2 for read2}).fastq. \nExample:hcc1395_normal_Rep1_R1.fastq.")NEWLINE self.SamplesYesradioinfoicon_dna.setFont(font_info)NEWLINE self.SamplesYesradioinfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.SamplesYesradioinfoicon_dna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE NEWLINE self.SamplesNoradioinfoicon_dna = QtWidgets.QPushButton(self.input_dna)NEWLINE self.SamplesNoradioinfoicon_dna.setFlat(True)NEWLINE self.SamplesNoradioinfoicon_dna.setGeometry(QtCore.QRect(210, 90, 20, 20))NEWLINE self.SamplesNoradioinfoicon_dna.setToolTip("Specify the tab-delimited text file containing the sample information.\n The table is required to be formatted as follows.\n The column names should take the order: Sample, Unit, Condition, fq1, fq2. \n(Sample- Sample name, Unit- Number of replications, Condition- normal/ tumor/ leave blank if the condition is not specified,\n fq1 - Path of Read 1,fq2 - Path of Read 2/ leave blank for single-end reads).\n An example table has been provided for your reference")NEWLINE self.SamplesNoradioinfoicon_dna.setFont(font_info)NEWLINE self.SamplesNoradioinfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.SamplesNoradioinfoicon_dna.setIconSize(QtCore.QSize(13, 13))NEWLINENEWLINENEWLINE self.coreinfoicon_dna = QtWidgets.QPushButton(self.input_dna)NEWLINE self.coreinfoicon_dna.setFlat(True)NEWLINE self.coreinfoicon_dna.setGeometry(QtCore.QRect(140, 390, 20, 20))NEWLINE self.coreinfoicon_dna.setToolTip("Input the number of threads to run")NEWLINE self.coreinfoicon_dna.setFont(font_info)NEWLINE self.coreinfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.coreinfoicon_dna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.DNAtabWidget.addTab(self.input_dna, "")NEWLINE ## End ##NEWLINE ## Add QC ##NEWLINE self.QC_dna = QtWidgets.QWidget()NEWLINE self.QC_dna.setObjectName("QC_dna")NEWLINE# self.QC_dna.setEnabled(False)NEWLINE ## Added from QC_Index##NEWLINE self.QCresults = QtWidgets.QPushButton(self.QC_dna)NEWLINE self.QCresults.setGeometry(QtCore.QRect(10, 30, 150, 23))NEWLINE self.QCresults.setText("Quality Control Results")NEWLINE self.QCresults.setStyleSheet("background-color: #704214")NEWLINE self.QCresultsButtonErroricon = QtWidgets.QPushButton(self.QC_dna)NEWLINE self.QCresultsButtonErroricon.setGeometry(QtCore.QRect(186, 32, 20, 20))NEWLINE self.QCresultsButtonErroricon.setToolTip("Check and Run View Quality control Results Again!")NEWLINE self.QCresultsButtonErroricon.setFont(font_label)NEWLINE self.QCresultsButtonErroricon.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/warning.svg')))NEWLINE self.QCresultsButtonErroricon.hide()NEWLINE self.QClabel = QtWidgets.QLabel(self.QC_dna)NEWLINE self.QClabel.setGeometry(QtCore.QRect(10, 85, 151, 21))NEWLINE font = QtGui.QFont()NEWLINE font.setPointSize(12)NEWLINE font.setItalic(True)NEWLINE self.QClabel.setFont(font)NEWLINE self.QClabel.setObjectName("QClabel")NEWLINE self.QCYesradioButton = QtWidgets.QRadioButton(self.QC_dna)NEWLINE self.QCYesradioButton.setGeometry(QtCore.QRect(170, 85, 117, 22))NEWLINE self.QCYesradioButton.setObjectName("QCYesradioButton")NEWLINE# self.QCYesradioButton.setChecked(True)NEWLINE self.QCNoradioButton = QtWidgets.QRadioButton(self.QC_dna)NEWLINE self.QCNoradioButton.setGeometry(QtCore.QRect(250, 85, 117, 22))NEWLINE self.QCNoradioButton.setObjectName("QCNoradioButton")NEWLINE self.QCNoradioButton.setChecked(True)NEWLINE self.InputParamslabel = QtWidgets.QLabel(self.QC_dna)NEWLINE self.InputParamslabel.setGeometry(QtCore.QRect(10, 140, 171, 17))NEWLINE font = QtGui.QFont()NEWLINE font.setPointSize(12)NEWLINE font.setBold(True)NEWLINE font.setWeight(75)NEWLINE self.InputParamslabel.setFont(font)NEWLINE self.InputParamslabel.setObjectName("InputParamslabel")NEWLINENEWLINE self.CutadaptlineEdit = QtWidgets.QLineEdit(self.QC_dna)NEWLINE self.CutadaptlineEdit.setGeometry(QtCore.QRect(120, 200, 481, 23))NEWLINE self.CutadaptlineEdit.setObjectName("CutadaptlineEdit")NEWLINE self.Cutadaptlabel = QtWidgets.QLabel(self.QC_dna)NEWLINE self.Cutadaptlabel.setGeometry(QtCore.QRect(10, 200, 67, 17))NEWLINE self.Cutadaptlabel.setObjectName("Cutadaptlabel")NEWLINENEWLINE self.horizontalLayoutWidget = QtWidgets.QWidget(self.QC_dna)NEWLINE self.horizontalLayoutWidget.setGeometry(QtCore.QRect(235, 273, 240, 31))NEWLINE self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")NEWLINE self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)NEWLINE self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)NEWLINE self.horizontalLayout_4.setObjectName("horizontalLayout_4")NEWLINENEWLINE self.RunQCpushButton = QtWidgets.QPushButton(self.horizontalLayoutWidget)NEWLINE self.RunQCpushButton.setObjectName("RunQCpushButton")NEWLINE self.horizontalLayout_4.addWidget(self.RunQCpushButton)NEWLINE self.RunQCButtonErroricon = QtWidgets.QPushButton(self.QC_dna)NEWLINE self.RunQCButtonErroricon.setGeometry(QtCore.QRect(500, 277, 20, 20))NEWLINE self.RunQCButtonErroricon.setToolTip("Check and Run Trimming Again!")NEWLINE self.RunQCButtonErroricon.setFont(font_label)NEWLINE self.RunQCButtonErroricon.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/warning.svg')))NEWLINE# self.horizontalLayout_4.addWidget(self.RunQCButtonErroricon)NEWLINE self.RunQCButtonErroricon.hide()NEWLINE self.InputParamslabel.setEnabled(False)NEWLINE self.Cutadaptlabel.setEnabled(False)NEWLINE self.CutadaptlineEdit.setEnabled(False)NEWLINE self.RunQCpushButton.setEnabled(False)NEWLINE ##QC_Progressbar##NEWLINE self.progressBar_sub1_dna = QtWidgets.QProgressBar(self.QC_dna)NEWLINE self.progressBar_sub1_dna.setGeometry(QtCore.QRect(10, 355, 665, 17))NEWLINE self.progressBar_sub1_dna.setProperty("value", 0)NEWLINE self.progressBar_sub1_dna.setObjectName("progressBar_sub1_dna")NEWLINENEWLINE ###NEWLINE self.nextbuttonqcDNA = QtWidgets.QPushButton(self.QC_dna)NEWLINE self.nextbuttonqcDNA.setGeometry(QtCore.QRect(635, 400, 45, 45))NEWLINE self.nextbuttonqcDNA.setObjectName("nextbuttonqcDNA")NEWLINE self.nextbuttonqcDNA.setEnabled(True)NEWLINE ###NEWLINE self.previousbuttonqcDNA = QtWidgets.QPushButton(self.QC_dna)NEWLINE self.previousbuttonqcDNA.setGeometry(QtCore.QRect(10, 400, 45, 45))NEWLINE self.previousbuttonqcDNA.setObjectName("previousbuttonqcDNA")NEWLINE NEWLINE NEWLINE NEWLINE font_info = QtGui.QFont()NEWLINE font_info.setPointSize(8.5)NEWLINE NEWLINE self.QCresultsinfoicon_dna = QtWidgets.QPushButton(self.QC_dna)NEWLINE self.QCresultsinfoicon_dna.setFlat(True)NEWLINE self.QCresultsinfoicon_dna.setGeometry(QtCore.QRect(166, 33, 20, 20))NEWLINE self.QCresultsinfoicon_dna.setToolTip("Generates a MultiQC report consisting of statistical metrics\n aggregated from FastQC for each sample input file.\n If the results obtained are satisfactory, you may move onto the next tab.\n If not, proceed to trim the reads to improve the quality of your data")NEWLINE self.QCresultsinfoicon_dna.setFont(font_info)NEWLINE self.QCresultsinfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.QCresultsinfoicon_dna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.QClabelinfoicon_dna = QtWidgets.QPushButton(self.QC_dna)NEWLINE self.QClabelinfoicon_dna.setFlat(True)NEWLINE self.QClabelinfoicon_dna.setGeometry(QtCore.QRect(131, 87, 20, 20))NEWLINE self.QClabelinfoicon_dna.setToolTip("Selecting 'Yes' will remove the adapter sequences from your data thereby improving data quality.\n 'No' can be selected if you are satisfied with the data quality")NEWLINE self.QClabelinfoicon_dna.setFont(font_info)NEWLINE self.QClabelinfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.QClabelinfoicon_dna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.Cutadaptlabelinfoicon_dna = QtWidgets.QPushButton(self.QC_dna)NEWLINE self.Cutadaptlabelinfoicon_dna.setFlat(True)NEWLINE self.Cutadaptlabelinfoicon_dna.setGeometry(QtCore.QRect(70, 199, 20, 20))NEWLINE self.Cutadaptlabelinfoicon_dna.setToolTip("Please input the necessary parameters for the tool cutadapt.\n It may include the adapter sequences.\n Refer https://cutadapt.readthedocs.io/en/stable/guide.html#adapter-types for details")NEWLINE self.Cutadaptlabelinfoicon_dna.setFont(font_info)NEWLINE self.Cutadaptlabelinfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.Cutadaptlabelinfoicon_dna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.RunQCpushButtoninfoicon_dna = QtWidgets.QPushButton(self.QC_dna)NEWLINE self.RunQCpushButtoninfoicon_dna.setFlat(True)NEWLINE self.RunQCpushButtoninfoicon_dna.setGeometry(QtCore.QRect(480, 277, 20, 20))NEWLINE self.RunQCpushButtoninfoicon_dna.setToolTip("Please choose yes to trim your reads if the input sequences are of poor quality.\n You may proceed to the next section if your reads are good enough for alignment")NEWLINE self.RunQCpushButtoninfoicon_dna.setFont(font_info)NEWLINE self.RunQCpushButtoninfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.RunQCpushButtoninfoicon_dna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE NEWLINE self.DNAtabWidget.addTab(self.QC_dna, "")NEWLINE ## End ##NEWLINE self.Tool_dna = QtWidgets.QWidget()NEWLINE self.Tool_dna.setObjectName("Tool_dna")NEWLINENEWLINE self.create_aligner_groupbox()NEWLINE self.create_vc_groupbox()NEWLINE self.create_annotator_groupbox()NEWLINE self.create_group_next()NEWLINE NEWLINE NEWLINE NEWLINE self.layout = QtWidgets.QHBoxLayout(self.Tool_dna)NEWLINE self.scrollArea = QtWidgets.QScrollArea(self.Tool_dna)NEWLINE self.scrollArea.setWidgetResizable(True)NEWLINE self.scrollAreaWidgetContents = QtWidgets.QWidget()NEWLINE self.gridLayout = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)NEWLINE self.scrollArea.setWidget(self.scrollAreaWidgetContents)NEWLINE self.layout.addWidget(self.scrollArea)NEWLINE NEWLINE self.grp_list=[self.aligner_groupbox, self.vc_groupbox, self.annotator_groupbox, self.next_groupbox]NEWLINE for i in range(4):NEWLINE self.gridLayout.addWidget(self.grp_list[i], i,0)NEWLINE NEWLINE NEWLINE self.DNAtabWidget.addTab(self.Tool_dna, "")NEWLINENEWLINENEWLINE NEWLINENEWLINE ## End ##NEWLINE NEWLINE ##Add Run##NEWLINE self.run_dna = QtWidgets.QWidget()NEWLINE self.run_dna.setObjectName("run_dna")NEWLINE NEWLINE self.RunButton_dna = QtWidgets.QPushButton(self.run_dna)NEWLINE self.RunButton_dna.setGeometry(QtCore.QRect(300, 140, 100, 100))NEWLINE self.RunButton_dna.setObjectName("RunButton_dna")NEWLINE self.RunLabel_dna = QtWidgets.QLabel(self.run_dna)NEWLINE self.RunLabel_dna.setGeometry(QtCore.QRect(330, 255, 180, 17))NEWLINE self.RunLabel_dna.setObjectName("RunLabel_dna")NEWLINE NEWLINE NEWLINE self.RunButtonErroricon_dna = QtWidgets.QPushButton(self.run_dna)NEWLINE self.RunButtonErroricon_dna.setGeometry(QtCore.QRect(420, 172, 30, 30))NEWLINE self.RunButtonErroricon_dna.setToolTip("Click Run Button and Run Again!")NEWLINE self.RunButtonErroricon_dna.setFont(font_label)NEWLINE self.RunButtonErroricon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/warning.svg')))NEWLINE self.RunButtonErroricon_dna.hide() NEWLINE NEWLINENEWLINE NEWLINE self.progressBar_dna = QtWidgets.QProgressBar(self.run_dna)NEWLINE self.progressBar_dna.setGeometry(QtCore.QRect(10, 340, 670, 23))NEWLINE self.progressBar_dna.setProperty("value", 0)NEWLINE# self.progressBar.setMaximum(3)NEWLINE self.progressBar_dna.setObjectName("progressBar_dna") NEWLINE NEWLINE self.nextbuttonrunDNA = QtWidgets.QPushButton(self.run_dna)NEWLINE self.nextbuttonrunDNA.setGeometry(QtCore.QRect(635, 400, 45, 45))NEWLINE self.nextbuttonrunDNA.setObjectName("nextbuttonrunDNA")NEWLINE ###NEWLINE self.previousbuttonrunDNA = QtWidgets.QPushButton(self.run_dna)NEWLINE self.previousbuttonrunDNA.setGeometry(QtCore.QRect(10, 400,45, 45))NEWLINE self.previousbuttonrunDNA.setObjectName("previousbuttonrunDNA")NEWLINE NEWLINE font_info = QtGui.QFont()NEWLINE font_info.setPointSize(8.5)NEWLINE NEWLINE self.RunButtoninfoicon_dna = QtWidgets.QPushButton(self.run_dna)NEWLINE self.RunButtoninfoicon_dna.setFlat(True)NEWLINE self.RunButtoninfoicon_dna.setGeometry(QtCore.QRect(400, 180, 20, 20))NEWLINE self.RunButtoninfoicon_dna.setToolTip("Click to start your analysis")NEWLINE self.RunButtoninfoicon_dna.setFont(font_info)NEWLINE self.RunButtoninfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.RunButtoninfoicon_dna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINENEWLINE NEWLINE NEWLINE self.DNAtabWidget.addTab(self.run_dna, "")NEWLINE ##End##NEWLINE ##Add Result DNA##NEWLINE self.result_dna = QtWidgets.QWidget()NEWLINE self.result_dna.setObjectName("result_dna")NEWLINE NEWLINE self.DNAtabWidget.addTab(self.result_dna, "")NEWLINENEWLINE font_resulttab = QtGui.QFont()NEWLINE font_resulttab.setPointSize(16)NEWLINE self.pushbutton_result1_dna=QtWidgets.QPushButton(self.result_dna)NEWLINE self.pushbutton_result1_dna.setText(" Run statistics")NEWLINE self.pushbutton_result1_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/runstatistics.svg')))NEWLINE self.pushbutton_result1_dna.setIconSize(QtCore.QSize(40, 40))NEWLINE self.pushbutton_result1_dna.setFont(font_resulttab)NEWLINE self.pushbutton_result1_dna.setStyleSheet("background-color: #704214")NEWLINE self.pushbutton_result1_dna.setGeometry(QtCore.QRect(215, 50, 255, 48))NEWLINENEWLINE self.pushbutton_result2_dna=QtWidgets.QPushButton(self.result_dna)NEWLINE self.pushbutton_result2_dna.setText(" Variants called")NEWLINE self.pushbutton_result2_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/document.svg')))NEWLINE self.pushbutton_result2_dna.setIconSize(QtCore.QSize(40, 40))NEWLINE self.pushbutton_result2_dna.setFont(font_resulttab)NEWLINE self.pushbutton_result2_dna.setStyleSheet("background-color: #704214")NEWLINE self.pushbutton_result2_dna.setGeometry(QtCore.QRect(215, 125, 255, 48))NEWLINENEWLINE self.pushbutton_result3_dna=QtWidgets.QPushButton(self.result_dna)NEWLINE self.pushbutton_result3_dna.setText("Annotated variants")NEWLINE self.pushbutton_result3_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/document.svg')))NEWLINE self.pushbutton_result3_dna.setIconSize(QtCore.QSize(40, 40))NEWLINE self.pushbutton_result3_dna.setFont(font_resulttab)NEWLINE self.pushbutton_result3_dna.setStyleSheet("background-color: #704214")NEWLINE self.pushbutton_result3_dna.setGeometry(QtCore.QRect(215, 200, 255, 48))NEWLINE NEWLINE self.proceedlabel = QtWidgets.QLabel(self.result_dna)NEWLINE self.proceedlabel.setGeometry(QtCore.QRect(150, 285, 281, 21))NEWLINE font = QtGui.QFont()NEWLINE font.setPointSize(12)NEWLINE# font.setItalic(True)NEWLINE self.proceedlabel.setFont(font)NEWLINE self.proceedlabel.setObjectName("proceedlabel")NEWLINE self.proceedlabel.setText("Proceed with cTaG or NBDriver?")NEWLINE self.pYesradioButton = QtWidgets.QRadioButton(self.result_dna)NEWLINE self.pYesradioButton.setGeometry(QtCore.QRect(450, 285, 117, 22))NEWLINE self.pYesradioButton.setObjectName("pYesradioButton")NEWLINE self.pYesradioButton.setFont(font)NEWLINE self.pYesradioButton.setText("Yes")NEWLINE# self.SamplesNoradioButton.setText(_translate("MainWindow", "Upload from Table"))NEWLINE# self.QCYesradioButton.setChecked(True)NEWLINE self.pNoradioButton = QtWidgets.QRadioButton(self.result_dna)NEWLINE self.pNoradioButton.setGeometry(QtCore.QRect(530, 285, 117, 22))NEWLINE self.pNoradioButton.setObjectName("pNoradioButton")NEWLINE self.pNoradioButton.setFont(font)NEWLINE self.pNoradioButton.setText("No")NEWLINE self.pNoradioButton.setChecked(True)NEWLINE NEWLINE self.ctagradioButton = QtWidgets.QCheckBox(self.result_dna)NEWLINE self.ctagradioButton.setFont(font)NEWLINE self.ctagradioButton.setGeometry(QtCore.QRect(250, 345, 117, 22))NEWLINE self.ctagradioButton.setText("cTaG")NEWLINE self.nbradioButton = QtWidgets.QCheckBox(self.result_dna)NEWLINE self.nbradioButton.setFont(font)NEWLINE self.nbradioButton.setGeometry(QtCore.QRect(350, 345, 117, 22))NEWLINE self.nbradioButton.setText("NBDriver")NEWLINE# self.nbradioButton.setChecked(True)NEWLINE font_next = QtGui.QFont()NEWLINE font_next.setPointSize(12)NEWLINE self.nextbuttonresult = QtWidgets.QPushButton(self.result_dna)NEWLINE self.nextbuttonresult.setGeometry(QtCore.QRect(635, 400, 45, 45))NEWLINE self.nextbuttonresult.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow.svg')))NEWLINE self.nextbuttonresult.setStyleSheet("background-color: #704214")NEWLINE# self.nextbuttonresult.setFont(font_next)NEWLINE# self.nextbuttonresult.setText("Generate MAF file")NEWLINE self.nextbuttonresult.setIconSize(QtCore.QSize(35, 35))NEWLINE NEWLINE self.nbinfoiconradio = QtWidgets.QPushButton(self.result_dna)NEWLINE self.nbinfoiconradio.setFlat(True)NEWLINE self.nbinfoiconradio.setGeometry(QtCore.QRect(450, 347, 20, 20))NEWLINE self.nbinfoiconradio.setToolTip("NBDriver predictions has been derived using hg19 reference genome only and \n the input vcf file must be kept inside /NBDriver_ICOMIC/vcf")NEWLINE self.nbinfoiconradio.setFont(font_info)NEWLINE self.nbinfoiconradio.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.nbinfoiconradio.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.ctagradioButton.setEnabled(False)NEWLINE self.nbradioButton.setEnabled(False)NEWLINE self.nextbuttonresult.setEnabled(False)NEWLINE self.nbinfoiconradio.setEnabled(False)NEWLINE NEWLINE NEWLINE ##End## NEWLINE NEWLINENEWLINE ## End ##NEWLINE self.PipelinetabWidget.addTab(self.DNAseq, "")NEWLINENEWLINE self.RNAseq = QtWidgets.QWidget()NEWLINE self.RNAseq.setObjectName("RNAseq")NEWLINE self.RNAtabWidget = QtWidgets.QTabWidget(self.RNAseq)NEWLINE self.RNAtabWidget.setGeometry(QtCore.QRect(0, 0, 695, 507))NEWLINE self.RNAtabWidget.setMovable(False)NEWLINE self.RNAtabWidget.setTabBarAutoHide(False)NEWLINE self.RNAtabWidget.setObjectName("RNAtabWidget")NEWLINE# self.RNAtabWidget.setStyleSheet("background-color: #F0F9EC")NEWLINE dnatab_img = os.path.join(module_dir,'dnatab.png')NEWLINE self.RNAtabWidget.setStyleSheet("background-image: url({});".format(dnatab_img))NEWLINE ## Make Input as first tab ##NEWLINE self.input_rna = QtWidgets.QWidget()NEWLINE self.input_rna.setObjectName("input_rna")NEWLINE self.SamplesYesradioButton_rna = QtWidgets.QRadioButton(self.input_rna)NEWLINE self.SamplesYesradioButton_rna.move(70, 30)NEWLINE self.SamplesYesradioButton_rna.setObjectName("SamplesYesradioButton_rna")NEWLINE self.SamplesYesradioButton_rna.setChecked(True)NEWLINE self.SamplesNoradioButton_rna = QtWidgets.QRadioButton(self.input_rna)NEWLINE self.SamplesNoradioButton_rna.move(70, 90)NEWLINE self.SamplesNoradioButton_rna.setObjectName("SamplesNoradioButton_rna")NEWLINE self.SampleOrlabel_rna = QtWidgets.QLabel(self.input_rna)NEWLINE self.SampleOrlabel_rna.move(130, 60)NEWLINE font = QtGui.QFont()NEWLINE font.setPointSize(12)NEWLINE font.setItalic(True)NEWLINE self.SampleOrlabel_rna.setFont(font)NEWLINE self.SampleOrlabel_rna.setObjectName("SampleOrlabel_rna")NEWLINENEWLINE self.SampleFolderlabel = QtWidgets.QLabel(self.input_rna)NEWLINE self.SampleFolderlabel.setGeometry(QtCore.QRect(20, 135, 113, 23))NEWLINE self.SampleFolderlabel.setObjectName("SampleFolderlabel")NEWLINE self.SampleFolderlabel.setEnabled(True)NEWLINE self.SampleFolderLineEdit = QtWidgets.QLineEdit(self.input_rna)NEWLINE self.SampleFolderLineEdit.setGeometry(QtCore.QRect(200, 135, 385, 23))NEWLINE self.SampleFolderLineEdit.setObjectName("SampleFolderLineEdit")NEWLINE self.SampleFolderLineEdit.setEnabled(True)NEWLINE self.SampleFolderBrowseButton = QtWidgets.QPushButton(self.input_rna)NEWLINE self.SampleFolderBrowseButton.setGeometry(QtCore.QRect(600, 135, 30, 25))NEWLINE self.SampleFolderBrowseButton.setObjectName("SampleFolderBrowseButton")NEWLINE self.SampleFolderBrowseButton.setEnabled(True)NEWLINE self.SampleFolderErrortextRNA = QtWidgets.QLabel(self.input_rna)NEWLINE self.SampleFolderErrortextRNA.setGeometry(QtCore.QRect(200, 165, 385, 15))NEWLINE self.SampleFolderErrortextRNA.setFont(font_label)NEWLINE self.SampleFolderErrortextRNA.setStyleSheet("color: red")NEWLINE self.Sampletablelabel = QtWidgets.QLabel(self.input_rna)NEWLINE self.Sampletablelabel.setGeometry(QtCore.QRect(20, 190, 113, 17))NEWLINE self.Sampletablelabel.setObjectName("Sampletablelabel")NEWLINE self.Sampletablelabel.setEnabled(False)NEWLINE self.SampletablelineEdit = QtWidgets.QLineEdit(self.input_rna)NEWLINE self.SampletablelineEdit.setGeometry(QtCore.QRect(200, 190, 385, 23))NEWLINE self.SampletablelineEdit.setObjectName("SampletablelineEdit")NEWLINE self.SampletablelineEdit.setEnabled(False)NEWLINE self.SampletableBrowseButton = QtWidgets.QPushButton(self.input_rna)NEWLINE self.SampletableBrowseButton.setGeometry(QtCore.QRect(600, 190, 30, 25))NEWLINE self.SampletableBrowseButton.setObjectName("SampletableBrowseButton")NEWLINE self.SampletableBrowseButton.setEnabled(False)NEWLINE self.SampletableErrortextRNA = QtWidgets.QLabel(self.input_rna)NEWLINE self.SampletableErrortextRNA.setGeometry(QtCore.QRect(200, 220, 385, 23))NEWLINE self.SampletableErrortextRNA.setFont(font_label)NEWLINE self.SampletableErrortextRNA.setStyleSheet("color: red")NEWLINE self.FastaFilelabel = QtWidgets.QLabel(self.input_rna)NEWLINE self.FastaFilelabel.setGeometry(QtCore.QRect(20, 240, 131, 17))NEWLINE self.FastaFilelabel.setObjectName("FastaFilelabel")NEWLINE self.FastalineEdit = QtWidgets.QLineEdit(self.input_rna)NEWLINE self.FastalineEdit.setGeometry(QtCore.QRect(200, 240, 385, 23))NEWLINE self.FastalineEdit.setObjectName("FastalineEdit")NEWLINE self.FastaBrowseButton = QtWidgets.QPushButton(self.input_rna)NEWLINE self.FastaBrowseButton.setGeometry(QtCore.QRect(600, 240, 30, 25))NEWLINE self.FastaBrowseButton.setObjectName("FastaBrowseButton")NEWLINE self.FastaErrortextRNA = QtWidgets.QLabel(self.input_rna)NEWLINE self.FastaErrortextRNA.setGeometry(QtCore.QRect(200, 265, 385, 23))NEWLINE self.FastaErrortextRNA.setFont(font_label)NEWLINE self.FastaErrortextRNA.setStyleSheet("color: red")NEWLINE self.AnnotatedFilelabelRNA = QtWidgets.QLabel(self.input_rna)NEWLINE self.AnnotatedFilelabelRNA.setGeometry(QtCore.QRect(20, 290, 171, 17))NEWLINE self.AnnotatedFilelabelRNA.setObjectName("AnnotatedFilelabelRNA")NEWLINE self.AnnotatedlineEditRNA = QtWidgets.QLineEdit(self.input_rna)NEWLINE self.AnnotatedlineEditRNA.setGeometry(QtCore.QRect(200, 290, 385, 23))NEWLINE self.AnnotatedlineEditRNA.setObjectName("AnnotatedlineEditRNA")NEWLINE self.AnnotatedBrowserButtonRNA = QtWidgets.QPushButton(self.input_rna)NEWLINE self.AnnotatedBrowserButtonRNA.setGeometry(QtCore.QRect(600, 290, 30, 25))NEWLINE self.AnnotatedBrowserButtonRNA.setObjectName("AnnotatedBrowserButtonRNA")NEWLINE self.AnnotatedErrortextRNA = QtWidgets.QLabel(self.input_rna)NEWLINE self.AnnotatedErrortextRNA.setGeometry(QtCore.QRect(200, 315, 385, 23))NEWLINE self.AnnotatedErrortextRNA.setFont(font_label)NEWLINE self.AnnotatedErrortextRNA.setStyleSheet("color: red")NEWLINENEWLINE self.CorelabelRNA = QtWidgets.QLabel(self.input_rna)NEWLINE self.CorelabelRNA.setGeometry(QtCore.QRect(20, 340, 157, 17))NEWLINE self.CorelabelRNA.setObjectName("CorelabelRNA")NEWLINE self.CorelineEditRNA = QtWidgets.QLineEdit(self.input_rna)NEWLINE self.CorelineEditRNA.setGeometry(QtCore.QRect(200, 340, 250, 23))NEWLINE self.CorelineEditRNA.setObjectName("CorelineEditRNA")NEWLINE self.CoreErrortextRNA = QtWidgets.QLabel(self.input_rna)NEWLINE self.CoreErrortextRNA.setGeometry(QtCore.QRect(200, 365, 250, 23))NEWLINE self.CoreErrortextRNA.setFont(font_label)NEWLINE self.CoreErrortextRNA.setStyleSheet("color: red")NEWLINE NEWLINE ###NEWLINENEWLINE ###NEWLINE NEWLINE font_label = QtGui.QFont()NEWLINE font_label.setPointSize(8.5)NEWLINENEWLINE NEWLINE NEWLINE NEWLINE self.nextbuttoninputRNA = QtWidgets.QPushButton(self.input_rna)NEWLINE self.nextbuttoninputRNA.setGeometry(QtCore.QRect(635, 400, 45, 45))NEWLINE self.nextbuttoninputRNA.setObjectName("nextbuttoninputRNA")NEWLINE NEWLINE #####info icon####NEWLINE ###rna###NEWLINE font_info = QtGui.QFont()NEWLINE font_info.setPointSize(8.5) NEWLINE NEWLINENEWLINE NEWLINE self.SampleFolderinfoicon_rna = QtWidgets.QPushButton(self.input_rna)NEWLINE self.SampleFolderinfoicon_rna.setFlat(True)NEWLINE self.SampleFolderinfoicon_rna.setGeometry(QtCore.QRect(120, 139, 20, 20))NEWLINE self.SampleFolderinfoicon_rna.setToolTip("Browse for the folder containing all the relevant sample files.\n The filenames for all the fastq input data are required to be in the following format.\n (sample_name)_(condition(tumor/normal))_Rep(replicate_number)_R(1 /2 {1 for read1 and 2 for read2}).fastq.\n Example:hcc1395_normal_Rep1_R1.fastq")NEWLINE self.SampleFolderinfoicon_rna.setFont(font_info)NEWLINE self.SampleFolderinfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.SampleFolderinfoicon_rna.setIconSize(QtCore.QSize(13, 13))NEWLINE NEWLINE self.Sampletableinfoicon_rna = QtWidgets.QPushButton(self.input_rna)NEWLINE self.Sampletableinfoicon_rna.setFlat(True)NEWLINE self.Sampletableinfoicon_rna.setGeometry(QtCore.QRect(116, 190, 20, 20))NEWLINE self.Sampletableinfoicon_rna.setToolTip("Browse for the tab separated text file containing the sample information. \n The table is required to be formatted as follows.\n The column names should take the order: Sample, Unit, Condition, fq1, fq2.\n (Sample- Sample name, Unit- Number of replications, \n Condition- normal/ tumor/ leave blank if the condition is not specified, \n fq1 - Path of Read 1,fq2 - Path of Read 2/ leave blank for single-end reads).\n An example table has been provided for your reference")NEWLINE self.Sampletableinfoicon_rna.setFont(font_info)NEWLINE self.Sampletableinfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.Sampletableinfoicon_rna.setIconSize(QtCore.QSize(13, 13))NEWLINE NEWLINE self.FastaFileinfoicon_rna = QtWidgets.QPushButton(self.input_rna)NEWLINE self.FastaFileinfoicon_rna.setFlat(True)NEWLINE self.FastaFileinfoicon_rna.setGeometry(QtCore.QRect(84, 240, 20, 20))NEWLINE self.FastaFileinfoicon_rna.setToolTip("A reference genome is a digital nucleic acid database \n assembled to be a representative example of a species’ set of genes.\n It allows for fast alignment of sequences as it is less computationally intensive \n to align sequences to a known sequence map rather than to assemble it piece by piece.\n For this field, specify the path to the pre-downloaded reference genome fastq file")NEWLINE self.FastaFileinfoicon_rna.setFont(font_info)NEWLINE self.FastaFileinfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.FastaFileinfoicon_rna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.AnnotatedFileinfoicon_rna = QtWidgets.QPushButton(self.input_rna)NEWLINE self.AnnotatedFileinfoicon_rna.setFlat(True)NEWLINE self.AnnotatedFileinfoicon_rna.setGeometry(QtCore.QRect(114, 290, 20, 20))NEWLINE self.AnnotatedFileinfoicon_rna.setToolTip("An annotation file is the gene transfer format (GTF) file containing the gene structure information")NEWLINE self.AnnotatedFileinfoicon_rna.setFont(font_info)NEWLINE self.AnnotatedFileinfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.AnnotatedFileinfoicon_rna.setIconSize(QtCore.QSize(13, 13)) NEWLINENEWLINENEWLINE NEWLINE self.SamplesYesradioinfoicon_rna = QtWidgets.QPushButton(self.input_rna)NEWLINE self.SamplesYesradioinfoicon_rna.setFlat(True)NEWLINE self.SamplesYesradioinfoicon_rna.setGeometry(QtCore.QRect(210, 32, 20, 20))NEWLINE self.SamplesYesradioinfoicon_rna.setToolTip("Specify the path to the folder containing all the relevant sample files.\n The filenames for all the fastq input data are required to be in the following format.\n (sample_name)_(condition(tumor/normal))_Rep(replicate_number)_R(1 /2 {1 for read1 and 2 for read2}).fastq. \nExample:hcc1395_normal_Rep1_R1.fastq")NEWLINE self.SamplesYesradioinfoicon_rna.setFont(font_info)NEWLINE self.SamplesYesradioinfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.SamplesYesradioinfoicon_rna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE NEWLINE self.SamplesNoradioinfoicon_rna = QtWidgets.QPushButton(self.input_rna)NEWLINE self.SamplesNoradioinfoicon_rna.setFlat(True)NEWLINE self.SamplesNoradioinfoicon_rna.setGeometry(QtCore.QRect(210, 90, 20, 20))NEWLINE self.SamplesNoradioinfoicon_rna.setToolTip("Specify the tab-delimited text file containing the sample information.\n The table is required to be formatted as follows.\n The column names should take the order: Sample, Unit, Condition, fq1, fq2. \n(Sample- Sample name, Unit- Number of replications, Condition- normal/ tumor/ leave blank if the condition is not specified,\n fq1 - Path of Read 1,fq2 - Path of Read 2/ leave blank for single-end reads).\n An example table has been provided for your reference")NEWLINE self.SamplesNoradioinfoicon_rna.setFont(font_info)NEWLINE self.SamplesNoradioinfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.SamplesNoradioinfoicon_rna.setIconSize(QtCore.QSize(13, 13))NEWLINE NEWLINE self.coreinfoicon_rna = QtWidgets.QPushButton(self.input_rna)NEWLINE self.coreinfoicon_rna.setFlat(True)NEWLINE self.coreinfoicon_rna.setGeometry(QtCore.QRect(140, 340, 20, 20))NEWLINE self.coreinfoicon_rna.setToolTip("Input the number of threads to run")NEWLINE self.coreinfoicon_rna.setFont(font_info)NEWLINE self.coreinfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.coreinfoicon_rna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.RNAtabWidget.addTab(self.input_rna, "")NEWLINE ## End ##NEWLINE NEWLINE ## Add QC ##NEWLINE self.QC_rna = QtWidgets.QWidget()NEWLINE self.QC_rna.setObjectName("QC_rna")NEWLINE ##QC_RNA Added##NEWLINE self.QCresults_rna = QtWidgets.QPushButton(self.QC_rna)NEWLINE self.QCresults_rna.setGeometry(QtCore.QRect(10, 30, 150, 23))NEWLINE self.QCresults_rna.setText("Quality Control Results")NEWLINE self.QCresults_rna.setStyleSheet("background-color: #704214")NEWLINE self.QCresultsButtonErroricon_rna = QtWidgets.QPushButton(self.QC_rna)NEWLINE self.QCresultsButtonErroricon_rna.setGeometry(QtCore.QRect(186, 32, 20, 20))NEWLINE self.QCresultsButtonErroricon_rna.setToolTip("Check and Run View Quality control Results Again!")NEWLINE self.QCresultsButtonErroricon_rna.setFont(font_label)NEWLINE self.QCresultsButtonErroricon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/warning.svg')))NEWLINE self.QCresultsButtonErroricon_rna.hide()NEWLINE self.QClabel_rna = QtWidgets.QLabel(self.QC_rna)NEWLINE self.QClabel_rna.setGeometry(QtCore.QRect(10, 85, 151, 21))NEWLINE font = QtGui.QFont()NEWLINE font.setPointSize(12)NEWLINE font.setItalic(True)NEWLINE self.QClabel_rna.setFont(font)NEWLINE self.QClabel_rna.setObjectName("QClabel_rna")NEWLINE self.QCYesradioButton_rna = QtWidgets.QRadioButton(self.QC_rna)NEWLINE self.QCYesradioButton_rna.setGeometry(QtCore.QRect(170, 85, 117, 22))NEWLINE self.QCYesradioButton_rna.setObjectName("QCYesradioButton_rna")NEWLINE# self.QCYesradioButton_rna.setChecked(True)NEWLINE self.QCNoradioButton_rna = QtWidgets.QRadioButton(self.QC_rna)NEWLINE self.QCNoradioButton_rna.setGeometry(QtCore.QRect(250, 85, 117, 22))NEWLINE self.QCNoradioButton_rna.setObjectName("QCNoradioButton_rna")NEWLINE self.QCNoradioButton_rna.setChecked(True)NEWLINE self.InputParamslabel_rna = QtWidgets.QLabel(self.QC_rna)NEWLINE self.InputParamslabel_rna.setGeometry(QtCore.QRect(10, 140, 171, 17))NEWLINE self.InputParamslabel_rna.setEnabled(False)NEWLINE font = QtGui.QFont()NEWLINE font.setPointSize(12)NEWLINE font.setBold(True)NEWLINE font.setWeight(75)NEWLINE self.InputParamslabel_rna.setFont(font)NEWLINE self.InputParamslabel_rna.setObjectName("InputParamslabel_rna")NEWLINENEWLINE self.CutadaptlineEdit_rna = QtWidgets.QLineEdit(self.QC_rna)NEWLINE self.CutadaptlineEdit_rna.setGeometry(QtCore.QRect(120, 200, 481, 23))NEWLINE self.CutadaptlineEdit_rna.setObjectName("CutadaptlineEdit_rna")NEWLINE self.Cutadaptlabel_rna = QtWidgets.QLabel(self.QC_rna)NEWLINE self.Cutadaptlabel_rna.setGeometry(QtCore.QRect(10, 200, 67, 17))NEWLINE self.Cutadaptlabel_rna.setObjectName("Cutadaptlabel_rna")NEWLINE self.Cutadaptlabel_rna.setEnabled(False)NEWLINE self.CutadaptlineEdit_rna.setEnabled(False)NEWLINENEWLINE self.horizontalLayoutWidget_rna = QtWidgets.QWidget(self.QC_rna)NEWLINE self.horizontalLayoutWidget_rna.setGeometry(QtCore.QRect(235, 273, 240, 31))NEWLINE self.horizontalLayoutWidget_rna.setObjectName("horizontalLayoutWidget_rna")NEWLINE self.horizontalLayout_4_rna = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_rna)NEWLINE self.horizontalLayout_4_rna.setContentsMargins(0, 0, 0, 0)NEWLINE self.horizontalLayout_4_rna.setObjectName("horizontalLayout_4_rna")NEWLINENEWLINE self.RunQCpushButton_rna = QtWidgets.QPushButton(self.horizontalLayoutWidget_rna)NEWLINE self.RunQCpushButton_rna.setObjectName("RunQCpushButton_rna")NEWLINE self.RunQCpushButton_rna.setEnabled(False)NEWLINE self.horizontalLayout_4_rna.addWidget(self.RunQCpushButton_rna)NEWLINE self.RunQCButtonErroricon_rna = QtWidgets.QPushButton(self.QC_rna)NEWLINE self.RunQCButtonErroricon_rna.setGeometry(QtCore.QRect(500, 277, 20, 20))NEWLINE self.RunQCButtonErroricon_rna.setToolTip("Check and Run Trimming Again!")NEWLINE self.RunQCButtonErroricon_rna.setFont(font_label)NEWLINE self.RunQCButtonErroricon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/warning.svg')))NEWLINENEWLINE self.RunQCButtonErroricon_rna.hide()NEWLINE ##QC_Progressbar##NEWLINE self.progressBar_sub1_rna = QtWidgets.QProgressBar(self.QC_rna)NEWLINE self.progressBar_sub1_rna.setGeometry(QtCore.QRect(10, 355, 665, 17))NEWLINE self.progressBar_sub1_rna.setProperty("value", 0)NEWLINE self.progressBar_sub1_rna.setObjectName("progressBar_sub1_rna")NEWLINE ###NEWLINE self.nextbuttonqcRNA = QtWidgets.QPushButton(self.QC_rna)NEWLINE self.nextbuttonqcRNA.setGeometry(QtCore.QRect(635, 400, 45, 45))NEWLINE self.nextbuttonqcRNA.setObjectName("nextbuttonqcRNA")NEWLINE# self.nextbuttonqcRNA.setEnabled(False)NEWLINE ###NEWLINE self.previousbuttonqcRNA = QtWidgets.QPushButton(self.QC_rna)NEWLINE self.previousbuttonqcRNA.setGeometry(QtCore.QRect(10, 400,45, 45))NEWLINE self.previousbuttonqcRNA.setObjectName("previousbuttonqcRNA")NEWLINE NEWLINE NEWLINE font_info = QtGui.QFont()NEWLINE font_info.setPointSize(8.5)NEWLINE NEWLINE self.QCresultsinfoicon_rna = QtWidgets.QPushButton(self.QC_rna)NEWLINE self.QCresultsinfoicon_rna.setFlat(True)NEWLINE self.QCresultsinfoicon_rna.setGeometry(QtCore.QRect(166, 33, 20, 20))NEWLINE self.QCresultsinfoicon_rna.setToolTip("Generates a MultiQC report consisting of statistical metrics\n aggregated from FastQC for each sample input file.\n If the results obtained are satisfactory, you may move onto the next tab.\n If not, proceed to trim the reads to improve the quality of your data")NEWLINE self.QCresultsinfoicon_rna.setFont(font_info)NEWLINE self.QCresultsinfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.QCresultsinfoicon_rna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.QClabelinfoicon_rna = QtWidgets.QPushButton(self.QC_rna)NEWLINE self.QClabelinfoicon_rna.setFlat(True)NEWLINE self.QClabelinfoicon_rna.setGeometry(QtCore.QRect(131, 87, 20, 20))NEWLINE self.QClabelinfoicon_rna.setToolTip("Selecting 'Yes' will remove the adapter sequences from your data thereby improving data quality.\n 'No' can be selected if you are satisfied with the data quality")NEWLINE self.QClabelinfoicon_rna.setFont(font_info)NEWLINE self.QClabelinfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.QClabelinfoicon_rna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.Cutadaptlabelinfoicon_rna = QtWidgets.QPushButton(self.QC_rna)NEWLINE self.Cutadaptlabelinfoicon_rna.setFlat(True)NEWLINE self.Cutadaptlabelinfoicon_rna.setGeometry(QtCore.QRect(70, 199, 20, 20))NEWLINE self.Cutadaptlabelinfoicon_rna.setToolTip("Please input the necessary parameters for the tool cutadapt.\n It may include the adapter sequences.\n Refer https://cutadapt.readthedocs.io/en/stable/guide.html#adapter-types for details")NEWLINE self.Cutadaptlabelinfoicon_rna.setFont(font_info)NEWLINE self.Cutadaptlabelinfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.Cutadaptlabelinfoicon_rna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.RunQCpushButtoninfoicon_rna = QtWidgets.QPushButton(self.QC_rna)NEWLINE self.RunQCpushButtoninfoicon_rna.setFlat(True)NEWLINE self.RunQCpushButtoninfoicon_rna.setGeometry(QtCore.QRect(480, 277, 20, 20))NEWLINE self.RunQCpushButtoninfoicon_rna.setToolTip("Please choose yes to trim your reads if the input sequences are of poor quality.\n You may proceed to the next section if your reads are good enough for alignment")NEWLINE self.RunQCpushButtoninfoicon_rna.setFont(font_info)NEWLINE self.RunQCpushButtoninfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.RunQCpushButtoninfoicon_rna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.RNAtabWidget.addTab(self.QC_rna, "")NEWLINE ## End ##NEWLINE self.Tool_rna = QtWidgets.QWidget()NEWLINE self.Tool_rna.setObjectName("Tool_rna")NEWLINE NEWLINE toolstab_img = os.path.join(module_dir,'toolstab.png')NEWLINE self.Tool_rna.setStyleSheet("background-image: url({});".format(toolstab_img))NEWLINE NEWLINE self.create_aligner_groupbox_rna()NEWLINE self.create_em_groupbox()NEWLINE self.create_de_groupbox()NEWLINE self.create_group_next_rna()NEWLINE self.nextbuttoninputRNANEWLINE self.layout_rna = QtWidgets.QHBoxLayout(self.Tool_rna)NEWLINE self.scrollArea_rna = QtWidgets.QScrollArea(self.Tool_rna)NEWLINE self.scrollArea_rna.setWidgetResizable(True)NEWLINE self.scrollAreaWidgetContents_rna = QtWidgets.QWidget()NEWLINE self.gridLayout_rna = QtWidgets.QGridLayout(self.scrollAreaWidgetContents_rna)NEWLINE self.scrollArea_rna.setWidget(self.scrollAreaWidgetContents_rna)NEWLINE self.layout_rna.addWidget(self.scrollArea_rna)NEWLINE NEWLINE self.grp_list_rna=[self.aligner_groupbox_rna, self.em_groupbox, self.de_groupbox, self.next_groupbox_rna]NEWLINE for i in range(4):NEWLINE self.gridLayout_rna.addWidget(self.grp_list_rna[i], i,0)NEWLINE NEWLINE self.RNAtabWidget.addTab(self.Tool_rna, "")NEWLINENEWLINE ## End ##NEWLINE NEWLINE ##Add Run##NEWLINE self.run_rna = QtWidgets.QWidget()NEWLINE self.run_rna.setObjectName("run_rna")NEWLINE NEWLINE self.RunButton = QtWidgets.QPushButton(self.run_rna)NEWLINE self.RunButton.setGeometry(QtCore.QRect(300, 140, 100, 100))NEWLINE self.RunButton.setObjectName("RunButton")NEWLINE self.RunLabel = QtWidgets.QLabel(self.run_rna)NEWLINE self.RunLabel.setGeometry(QtCore.QRect(330, 255, 180, 17))NEWLINE self.RunLabel.setObjectName("RunLabel")NEWLINE NEWLINE self.RunButtonErroricon = QtWidgets.QPushButton(self.run_rna)NEWLINE self.RunButtonErroricon.setGeometry(QtCore.QRect(420, 172, 30, 30))NEWLINE self.RunButtonErroricon.setToolTip("Click Run Button and Run Again!")NEWLINE self.RunButtonErroricon.setFont(font_label)NEWLINE self.RunButtonErroricon.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/warning.svg')))NEWLINE self.RunButtonErroricon.hide() NEWLINE NEWLINE NEWLINE self.progressBar = QtWidgets.QProgressBar(self.run_rna)NEWLINE self.progressBar.setGeometry(QtCore.QRect(10, 340, 670, 23))NEWLINE self.progressBar.setProperty("value", 0)NEWLINE# self.progressBar.setMaximum(3)NEWLINE self.progressBar.setObjectName("progressBar") NEWLINE NEWLINE NEWLINE self.nextbuttonrunRNA = QtWidgets.QPushButton(self.run_rna)NEWLINE self.nextbuttonrunRNA.setGeometry(QtCore.QRect(635, 400, 45, 45))NEWLINE self.nextbuttonrunRNA.setObjectName("nextbuttonrunRNA")NEWLINE ###NEWLINE self.previousbuttonrunRNA = QtWidgets.QPushButton(self.run_rna)NEWLINE self.previousbuttonrunRNA.setGeometry(QtCore.QRect(10, 400,45, 45))NEWLINE self.previousbuttonrunRNA.setObjectName("previousbuttonrunRNA") NEWLINE NEWLINE NEWLINE font_info = QtGui.QFont()NEWLINE font_info.setPointSize(8.5)NEWLINE NEWLINE self.RunButtoninfoicon_rna = QtWidgets.QPushButton(self.run_rna)NEWLINE self.RunButtoninfoicon_rna.setFlat(True)NEWLINE self.RunButtoninfoicon_rna.setGeometry(QtCore.QRect(400, 180, 20, 20))NEWLINE self.RunButtoninfoicon_rna.setToolTip("Click to start your analysis")NEWLINE self.RunButtoninfoicon_rna.setFont(font_info)NEWLINE self.RunButtoninfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.RunButtoninfoicon_rna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINENEWLINE NEWLINE self.RNAtabWidget.addTab(self.run_rna, "")NEWLINE ##End##NEWLINE ##Add Result RNA##NEWLINE self.result_rna = QtWidgets.QWidget()NEWLINE self.result_rna.setObjectName("result_rna")NEWLINE font_resulttab = QtGui.QFont()NEWLINE font_resulttab.setPointSize(16)NEWLINENEWLINE self.pushbutton_result1_rna=QtWidgets.QPushButton(self.result_rna)NEWLINE self.pushbutton_result1_rna.setText("Run statistics")NEWLINE self.pushbutton_result1_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/runstatistics.svg')))NEWLINE self.pushbutton_result1_rna.setIconSize(QtCore.QSize(40, 40))NEWLINE self.pushbutton_result1_rna.setFont(font_resulttab)NEWLINE self.pushbutton_result1_rna.setStyleSheet("background-color: #704214")NEWLINE self.pushbutton_result1_rna.setGeometry(QtCore.QRect(215, 145, 255, 48))NEWLINENEWLINE self.pushbutton_result2_rna=QtWidgets.QPushButton(self.result_rna)NEWLINE self.pushbutton_result2_rna.setText("DE Genes")NEWLINE self.pushbutton_result2_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/document.svg')))NEWLINE self.pushbutton_result2_rna.setIconSize(QtCore.QSize(40, 40))NEWLINE self.pushbutton_result2_rna.setFont(font_resulttab)NEWLINE self.pushbutton_result2_rna.setStyleSheet("background-color: #704214")NEWLINE self.pushbutton_result2_rna.setGeometry(QtCore.QRect(215, 245, 255, 48))NEWLINENEWLINE self.pushbutton_result3_rna=QtWidgets.QPushButton(self.result_rna)NEWLINE self.pushbutton_result3_rna.setText("Plots")NEWLINE self.pushbutton_result3_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/plots.svg')))NEWLINE self.pushbutton_result3_rna.setIconSize(QtCore.QSize(40, 40))NEWLINE self.pushbutton_result3_rna.setFont(font_resulttab)NEWLINE self.pushbutton_result3_rna.setStyleSheet("background-color: #704214")NEWLINE self.pushbutton_result3_rna.setGeometry(QtCore.QRect(215, 345, 255, 48))NEWLINE NEWLINE self.RNAtabWidget.addTab(self.result_rna, "")NEWLINE ##End## NEWLINE NEWLINE ## Add Create ##NEWLINENEWLINE ## End ##NEWLINE self.PipelinetabWidget.addTab(self.RNAseq, "")NEWLINE NEWLINE self.CTAG = QtWidgets.QWidget()NEWLINE self.CTAG.setObjectName("CTAG")NEWLINE self.CTAGtabWidget = QtWidgets.QTabWidget(self.CTAG)NEWLINE self.CTAGtabWidget.setGeometry(QtCore.QRect(0, 0, 695, 507))NEWLINE self.CTAGtabWidget.setMovable(False)NEWLINE self.CTAGtabWidget.setTabBarAutoHide(False)NEWLINE self.CTAGtabWidget.setObjectName("CTAGtabWidget")NEWLINE dnatab_img = os.path.join(module_dir,'dnatab.png')NEWLINE self.CTAGtabWidget.setStyleSheet("background-image: url({});".format(dnatab_img))NEWLINE self.ctaglabel = QtWidgets.QLabel(self.CTAG)NEWLINE self.ctaglabel.setGeometry(QtCore.QRect(15, 25, 400, 20))NEWLINE self.ctaglabel.setObjectName("ctaglabel")NEWLINE self.ctaglabel.setEnabled(True)NEWLINE NEWLINE self.ctaglabel2 = QtWidgets.QLabel(self.CTAG)NEWLINE self.ctaglabel2.setGeometry(QtCore.QRect(20, 35, 1000, 100))NEWLINE self.ctaglabel2.setObjectName("ctaglabel2")NEWLINE self.ctaglabel2.setEnabled(True)NEWLINE NEWLINE self.ctaglabel3 = QtWidgets.QLabel(self.CTAG)NEWLINE self.ctaglabel3.setGeometry(QtCore.QRect(65, 90, 400, 100))NEWLINE self.ctaglabel3.setObjectName("ctaglabel3")NEWLINE self.ctaglabel3.setEnabled(True)NEWLINE self.ctaglabel3.setOpenExternalLinks(True)NEWLINE# urlLink = " NBDriver"NEWLINE self.ctaggithubbutton = QtWidgets.QPushButton(self.CTAG)NEWLINE self.ctaggithubbutton.setGeometry(QtCore.QRect(20, 130, 30, 25))NEWLINE self.ctaggithubbutton.setObjectName("ctaggithubbutton") NEWLINE NEWLINE self.maflineEdit = QtWidgets.QLineEdit(self.CTAG)NEWLINE self.maflineEdit.setGeometry(QtCore.QRect(160, 200, 450, 23))NEWLINE self.maflineEdit.setObjectName("maflineEdit")NEWLINE self.maflabel = QtWidgets.QLabel(self.CTAG)NEWLINE self.maflabel.setGeometry(QtCore.QRect(10, 200, 100, 17))NEWLINE self.maflabel.setObjectName("maflabel")NEWLINE self.maflabel.setEnabled(True)NEWLINE self.maflineEdit.setEnabled(True)NEWLINE self.mafBrowseButton = QtWidgets.QPushButton(self.CTAG)NEWLINE self.mafBrowseButton.setGeometry(QtCore.QRect(620, 200, 30, 25))NEWLINE self.mafBrowseButton.setObjectName("mafBrowseButton")NEWLINE NEWLINE self.mafparamlineEdit = QtWidgets.QLineEdit(self.CTAG)NEWLINE self.mafparamlineEdit.setGeometry(QtCore.QRect(200, 260, 155, 23))NEWLINE self.mafparamlineEdit.setObjectName("maflineEdit")NEWLINE self.mafparamlineEdit1 = QtWidgets.QLineEdit(self.CTAG)NEWLINE self.mafparamlineEdit1.setGeometry(QtCore.QRect(440, 260, 155, 23))NEWLINE self.mafparamlineEdit1.setObjectName("maflineEdit")NEWLINE self.mafparamlabel = QtWidgets.QLabel(self.CTAG)NEWLINE self.mafparamlabel.setGeometry(QtCore.QRect(10, 260, 100, 17))NEWLINE self.mafparamlabel.setObjectName("maflabel")NEWLINE self.mafparamlabel.setEnabled(True)NEWLINE self.mafparamlineEdit.setEnabled(True)NEWLINE self.mafparamlabel1 = QtWidgets.QLabel(self.CTAG)NEWLINE self.mafparamlabel1.setGeometry(QtCore.QRect(170, 260, 50, 17))NEWLINE self.mafparamlabel1.setObjectName("maflabel1")NEWLINE self.mafparamlabel2 = QtWidgets.QLabel(self.CTAG)NEWLINE self.mafparamlabel2.setGeometry(QtCore.QRect(410, 260, 50, 17))NEWLINE self.mafparamlabel2.setObjectName("maflabel2")NEWLINE self.runctagpushButton = QtWidgets.QPushButton(self.CTAG)NEWLINE self.runctagpushButton.setGeometry(QtCore.QRect(270, 350, 200, 30))NEWLINE self.runctagpushButton.setObjectName("runctagpushButton")NEWLINE NEWLINE self.resultctagpushButton = QtWidgets.QPushButton(self.CTAG)NEWLINE self.resultctagpushButton.setGeometry(QtCore.QRect(290, 410, 150, 50))NEWLINE self.resultctagpushButton.setObjectName("resultctagpushButton")NEWLINE NEWLINE self.ctaginfoiconmaf = QtWidgets.QPushButton(self.CTAG)NEWLINE self.ctaginfoiconmaf.setFlat(True)NEWLINE self.ctaginfoiconmaf.setGeometry(QtCore.QRect(109, 200, 20, 20))NEWLINE self.ctaginfoiconmaf.setToolTip("path to the maf file")NEWLINE self.ctaginfoiconmaf.setFont(font_info)NEWLINE self.ctaginfoiconmaf.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.ctaginfoiconmaf.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.ctaginfoiconparam = QtWidgets.QPushButton(self.CTAG)NEWLINE self.ctaginfoiconparam.setFlat(True)NEWLINE self.ctaginfoiconparam.setGeometry(QtCore.QRect(90, 260, 20, 20))NEWLINE self.ctaginfoiconparam.setToolTip("enter the parameters --maxmut and --percentile")NEWLINE self.ctaginfoiconparam.setFont(font_info)NEWLINE self.ctaginfoiconparam.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.ctaginfoiconparam.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.ctaginfoiconrun = QtWidgets.QPushButton(self.CTAG)NEWLINE self.ctaginfoiconrun.setFlat(True)NEWLINE self.ctaginfoiconrun.setGeometry(QtCore.QRect(472, 355, 20, 20))NEWLINE self.ctaginfoiconrun.setToolTip("Click Run to run the analysis")NEWLINE self.ctaginfoiconrun.setFont(font_info)NEWLINE self.ctaginfoiconrun.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.ctaginfoiconrun.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.ctaginfoiconres = QtWidgets.QPushButton(self.CTAG)NEWLINE self.ctaginfoiconres.setFlat(True)NEWLINE self.ctaginfoiconres.setGeometry(QtCore.QRect(447, 423, 20, 20))NEWLINE self.ctaginfoiconres.setToolTip("Click View Results to open the results")NEWLINE self.ctaginfoiconres.setFont(font_info)NEWLINE self.ctaginfoiconres.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.ctaginfoiconres.setIconSize(QtCore.QSize(13, 13))NEWLINE NEWLINE self.PipelinetabWidget.addTab(self.CTAG, "")NEWLINE NEWLINE self.NB = QtWidgets.QWidget()NEWLINE self.NB.setObjectName("NV")NEWLINE self.NBtabWidget = QtWidgets.QTabWidget(self.NB)NEWLINE self.NBtabWidget.setGeometry(QtCore.QRect(0, 0, 695, 507))NEWLINE self.NBtabWidget.setMovable(False)NEWLINE self.NBtabWidget.setTabBarAutoHide(False)NEWLINE self.NBtabWidget.setObjectName("NBtabWidget")NEWLINE dnatab_img = os.path.join(module_dir,'dnatab.png')NEWLINE self.NBtabWidget.setStyleSheet("background-image: url({});".format(dnatab_img))NEWLINE NEWLINE self.nblabel = QtWidgets.QLabel(self.NB)NEWLINE self.nblabel.setGeometry(QtCore.QRect(15, 25, 400, 20))NEWLINE self.nblabel.setObjectName("nblabel")NEWLINE self.nblabel.setEnabled(True)NEWLINE NEWLINE self.nblabel2 = QtWidgets.QLabel(self.NB)NEWLINE self.nblabel2.setGeometry(QtCore.QRect(20, 35, 1000, 100))NEWLINE self.nblabel2.setObjectName("nblabel2")NEWLINE self.nblabel2.setEnabled(True)NEWLINE NEWLINE self.nblabel3 = QtWidgets.QLabel(self.NB)NEWLINE self.nblabel3.setGeometry(QtCore.QRect(65, 90, 400, 100))NEWLINE self.nblabel3.setObjectName("nblabel3")NEWLINE self.nblabel3.setEnabled(True)NEWLINE self.nblabel3.setOpenExternalLinks(True)NEWLINE# urlLink = " NBDriver"NEWLINE self.nbgithubbutton = QtWidgets.QPushButton(self.NB)NEWLINE self.nbgithubbutton.setGeometry(QtCore.QRect(20, 130, 30, 25))NEWLINE self.nbgithubbutton.setObjectName("nbgithubbutton")NEWLINE self.nbpaperbutton = QtWidgets.QPushButton(self.NB)NEWLINE self.nbpaperbutton.setGeometry(QtCore.QRect(140, 130, 30, 25))NEWLINE self.nbpaperbutton.setObjectName("nbpaperbutton")NEWLINE NEWLINE self.nblabel5 = QtWidgets.QLabel(self.NB)NEWLINE self.nblabel5.setGeometry(QtCore.QRect(185, 90, 400, 100))NEWLINE self.nblabel5.setObjectName("nblabel5")NEWLINE self.nblabel5.setEnabled(True)NEWLINE self.nblabel5.setOpenExternalLinks(True)NEWLINE self.nblabel4 = QtWidgets.QLabel(self.NB)NEWLINE self.nblabel4.setGeometry(QtCore.QRect(10, 160, 1000, 100))NEWLINE self.nblabel4.setObjectName("nblabel4") NEWLINE self.nblabel6 = QtWidgets.QLabel(self.NB)NEWLINE self.nblabel6.setGeometry(QtCore.QRect(151, 161, 100, 100))NEWLINE self.nblabel6.setObjectName("nblabel6")NEWLINE self.nblabel6.setEnabled(True)NEWLINE self.nblabel6.setOpenExternalLinks(True)NEWLINE NEWLINE self.vcflineEdit = QtWidgets.QLineEdit(self.NB)NEWLINE self.vcflineEdit.setGeometry(QtCore.QRect(160, 250, 450, 23))NEWLINE self.vcflineEdit.setObjectName("vcflineEdit")NEWLINE self.vcflabel = QtWidgets.QLabel(self.NB)NEWLINE self.vcflabel.setGeometry(QtCore.QRect(10, 250, 100, 17))NEWLINE self.vcflabel.setObjectName("vcflabel")NEWLINE self.vcflabel.setEnabled(True)NEWLINE self.vcflineEdit.setEnabled(True)NEWLINE self.vcfBrowseButton = QtWidgets.QPushButton(self.NB)NEWLINE self.vcfBrowseButton.setGeometry(QtCore.QRect(620, 250, 30, 25))NEWLINE self.vcfBrowseButton.setObjectName("vcfBrowseButton")NEWLINE self.runnbpushButton = QtWidgets.QPushButton(self.NB)NEWLINE self.runnbpushButton.setGeometry(QtCore.QRect(270, 350, 200, 30))NEWLINE self.runnbpushButton.setObjectName("runnbpushButton")NEWLINE NEWLINE self.resultnbpushButton = QtWidgets.QPushButton(self.NB)NEWLINE self.resultnbpushButton.setGeometry(QtCore.QRect(290, 410, 150, 50))NEWLINE self.resultnbpushButton.setObjectName("resultnbpushButton")NEWLINE NEWLINE self.nbinfoiconvcf = QtWidgets.QPushButton(self.NB)NEWLINE self.nbinfoiconvcf.setFlat(True)NEWLINE self.nbinfoiconvcf.setGeometry(QtCore.QRect(109, 250, 20, 20))NEWLINE self.nbinfoiconvcf.setToolTip("path to the vcf file")NEWLINE self.nbinfoiconvcf.setFont(font_info)NEWLINE self.nbinfoiconvcf.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.nbinfoiconvcf.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.nbinfoiconrun = QtWidgets.QPushButton(self.NB)NEWLINE self.nbinfoiconrun.setFlat(True)NEWLINE self.nbinfoiconrun.setGeometry(QtCore.QRect(472, 355, 20, 20))NEWLINE self.nbinfoiconrun.setToolTip("Click Run to run the analysis")NEWLINE self.nbinfoiconrun.setFont(font_info)NEWLINE self.nbinfoiconrun.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.nbinfoiconrun.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.nbinfoiconres = QtWidgets.QPushButton(self.NB)NEWLINE self.nbinfoiconres.setFlat(True)NEWLINE self.nbinfoiconres.setGeometry(QtCore.QRect(447, 423, 20, 20))NEWLINE self.nbinfoiconres.setToolTip("Click View Results to open the results")NEWLINE self.nbinfoiconres.setFont(font_info)NEWLINE self.nbinfoiconres.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.nbinfoiconres.setIconSize(QtCore.QSize(13, 13))NEWLINE NEWLINE self.PipelinetabWidget.addTab(self.NB, "")NEWLINENEWLINENEWLINE NEWLINE self.ShellTab = QtWidgets.QTabWidget(self.centralwidget)NEWLINE self.ShellTab.setGeometry(QtCore.QRect(10, 550, 701, 151))NEWLINE self.ShellTab.setObjectName("ShellTab")NEWLINE# self.ShellTab.setStyleSheet("background-color: #F0F9EC")NEWLINE shell_img = os.path.join(module_dir,'shell1.png')NEWLINE self.ShellTab.setStyleSheet("background-image: url({});".format(shell_img)) NEWLINE NEWLINE self.SnakemakeOutputTab = QtWidgets.QWidget()NEWLINE self.SnakemakeOutputTab.setObjectName("SnakemakeOutputTab")NEWLINE self.textBrowser = QtWidgets.QTextBrowser(self.SnakemakeOutputTab)NEWLINE self.textBrowser.setGeometry(QtCore.QRect(0, 0, 695, 118))NEWLINE self.textBrowser.setObjectName("textBrowser")NEWLINE self.textBrowser.setReadOnly(True)NEWLINENEWLINE self.ShellTab.addTab(self.SnakemakeOutputTab, "")NEWLINE NEWLINE self.PipelinetabWidget.addTab(self.NB, "")NEWLINENEWLINENEWLINE# self.layoutWidget.raise_()NEWLINE self.PipelinetabWidget.raise_()NEWLINE self.progressBar_sub1_dna.raise_()NEWLINE self.progressBar_sub2_dna.raise_()NEWLINE# self.progressBar_sub3.raise_()NEWLINE# self.progressBar.raise_()NEWLINE self.ShellTab.raise_()NEWLINE self.RefVariantpushButton.raise_()NEWLINE self.UnitsBrowseButtonDNA.raise_()NEWLINE self.SampleslineEditDNA.raise_()NEWLINE self.RefGenomeBrowseButtonDNA.raise_()NEWLINE self.SampleFilelabelDNA.raise_()NEWLINE self.UnitsFilelabelDNA.raise_()NEWLINE self.RefVariantlabelDNA.raise_()NEWLINE# self.RefNamelineEdit.raise_()NEWLINE self.RefGenomelineEditDNA.raise_()NEWLINE self.RefGenomelabelDNA.raise_()NEWLINE self.RefNamelabelDNA.raise_()NEWLINE self.SamplesBrowseButtonDNA.raise_()NEWLINE self.UnitslineEditDNA.raise_()NEWLINE self.RefNamecomboBoxDNA.raise_()NEWLINE self.RefVariantpushButton.raise_()NEWLINE self.RefVariantlineEditDNA.raise_()NEWLINE self.UnitsBrowseButtonDNA.raise_()NEWLINE self.SampleslineEditDNA.raise_()NEWLINE self.RefGenomeBrowseButtonDNA.raise_()NEWLINE self.SampleFilelabelDNA.raise_()NEWLINE self.UnitsFilelabelDNA.raise_()NEWLINE self.RefVariantlabelDNA.raise_()NEWLINE self.RefGenomelineEditDNA.raise_()NEWLINE self.RefGenomelabelDNA.raise_()NEWLINE self.RefNamelabelDNA.raise_()NEWLINE self.SamplesBrowseButtonDNA.raise_()NEWLINE self.UnitslineEditDNA.raise_()NEWLINE MainWindow.setCentralWidget(self.centralwidget)NEWLINE self.statusbar = QtWidgets.QStatusBar(MainWindow)NEWLINE self.statusbar.setObjectName("statusbar")NEWLINE MainWindow.setStatusBar(self.statusbar)NEWLINE self.menubar = QtWidgets.QMenuBar(MainWindow)NEWLINE self.menubar.setGeometry(QtCore.QRect(0, 0, 619, 25))NEWLINE self.menubar.setObjectName("menubar")NEWLINE self.menuFile = QtWidgets.QMenu(self.menubar)NEWLINE self.menuFile.setObjectName("menuFile")NEWLINE self.menuOption = QtWidgets.QMenu(self.menubar)NEWLINE self.menuOption.setObjectName("menuOption")NEWLINE self.menuHelp = QtWidgets.QMenu(self.menubar)NEWLINE self.menuHelp.setObjectName("menuHelp")NEWLINE MainWindow.setMenuBar(self.menubar)NEWLINE self.actionQuit = QtWidgets.QAction(MainWindow)NEWLINE self.actionQuit.setObjectName("actionQuit")NEWLINE self.actionAbout = QtWidgets.QAction(MainWindow)NEWLINE self.actionAbout.setObjectName("actionAbout")NEWLINE self.actionQuick_Start = QtWidgets.QAction(MainWindow)NEWLINE self.actionQuick_Start.setObjectName("actionQuick_Start")NEWLINE self.actionAbout_2 = QtWidgets.QAction(MainWindow)NEWLINE self.actionAbout_2.setObjectName("actionAbout_2")NEWLINE self.actionSnakemake_Options = QtWidgets.QAction(MainWindow)NEWLINE self.actionSnakemake_Options.setObjectName("actionSnakemake_Options")NEWLINE self.menuFile.addAction(self.actionQuit)NEWLINE self.menuOption.addAction(self.actionSnakemake_Options)NEWLINE self.menuHelp.addAction(self.actionQuick_Start)NEWLINE self.menuHelp.addAction(self.actionAbout_2)NEWLINE self.menubar.addAction(self.menuFile.menuAction())NEWLINE self.menubar.addAction(self.menuOption.menuAction())NEWLINE self.menubar.addAction(self.menuHelp.menuAction())NEWLINENEWLINE self.retranslateUi(MainWindow)NEWLINE self.PipelinetabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.ShellTab.setCurrentIndex(0)NEWLINE self.actionQuit.triggered.connect(MainWindow.close)NEWLINE# QtCore.Qt.WindowMaximizeButton.hide()NEWLINE NEWLINE QtCore.QMetaObject.connectSlotsByName(MainWindow)NEWLINE self._colors = {NEWLINE 'green': QtGui.QColor(0,170,0),NEWLINE 'red': QtGui.QColor(170,0,0),NEWLINE 'orange': QtGui.QColor(170,150,0),NEWLINE 'blue': QtGui.QColor(0,90,154),NEWLINE 'black': QtGui.QColor(0,0,0),NEWLINE }NEWLINE NEWLINE ####set all tabs disabled###NEWLINE# =============================================================================NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE self.DNAtabWidget.setTabEnabled(2, False)NEWLINE self.DNAtabWidget.setTabEnabled(3, False)NEWLINE self.DNAtabWidget.setTabEnabled(4, False)NEWLINE self.DNAtabWidget.setTabEnabled(5, False)NEWLINE NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE self.RNAtabWidget.setTabEnabled(2, False)NEWLINE self.RNAtabWidget.setTabEnabled(3, False)NEWLINE self.RNAtabWidget.setTabEnabled(4, False)NEWLINE self.RNAtabWidget.setTabEnabled(5, False)NEWLINE# =============================================================================NEWLINENEWLINE NEWLINENEWLINE############NEWLINENEWLINENEWLINE############NEWLINE def retranslateUi(self, MainWindow):NEWLINE _translate = QtCore.QCoreApplication.translateNEWLINE MainWindow.setWindowTitle(_translate("MainWindow", "iCOMIC"))NEWLINE MainWindow.setWindowIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/taskbar1.png')))NEWLINE #self.PipelinetabWidget.setToolTip(_translate("MainWindow", "Performs Quality Control and Creates Mandatory files to run the pipeline"))NEWLINE ## Add Input as first tab ##NEWLINE# self.SampleOrlabel.setToolTip(_translate("MainWindow", "This option performs all the Quality Control operations like fastQC, Cutadapt and MultiQC "))NEWLINE self.SampleOrlabel.setText(_translate("MainWindow", "Or"))NEWLINE# self.SamplesYesradioButton.setToolTip(_translate("MainWindow", "Files should be in specified format"))NEWLINE self.SamplesYesradioButton.setText(_translate("MainWindow", "Upload from Folder"))NEWLINE# self.SamplesNoradioButton.setToolTip(_translate("MainWindow", "Tables should contain all the information"))NEWLINE self.SamplesNoradioButton.setText(_translate("MainWindow", "Upload from Table"))NEWLINE# self.UnitsBrowseButtonDNA.setText(_translate("MainWindow", "Browse"))NEWLINE self.UnitsBrowseButtonDNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/browse.png')))NEWLINE self.UnitsBrowseButtonDNA.setIconSize(QtCore.QSize(22, 22))NEWLINE self.UnitsBrowseButtonDNA.setToolTip("Browse Samples Table")NEWLINE# self.RefGenomeBrowseButtonDNA.setText(_translate("MainWindow", "Browse"))NEWLINE self.RefGenomeBrowseButtonDNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/browse.png')))NEWLINE# self.RefGenomeBrowseButtonDNA.setStyleSheet("background-color: #aeaeae")NEWLINE self.RefGenomeBrowseButtonDNA.setToolTip("Browse Reference Genome")NEWLINE self.RefGenomeBrowseButtonDNA.setIconSize(QtCore.QSize(22, 22))NEWLINE self.UnitsFilelabelDNA.setText(_translate("MainWindow", "Samples Table"))NEWLINE self.RefGenomelabelDNA.setText(_translate("MainWindow", "Reference Genome"))NEWLINE self.SampleFilelabelDNA.setText(_translate("MainWindow", "Samples Folder"))NEWLINE self.CorelabelDNA.setText(_translate("MainWindow", "Maximum threads"))NEWLINE self.CorelineEditDNA.setText(_translate("MainWindow", "1"))NEWLINE# self.SamplesBrowseButtonDNA.setText(_translate("MainWindow", "Browse"))NEWLINE self.SamplesBrowseButtonDNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/browse.png')))NEWLINE self.SamplesBrowseButtonDNA.setIconSize(QtCore.QSize(22, 22))NEWLINE# self.SamplesBrowseButtonDNA.setStyleSheet("background-color: #aeaeae")NEWLINE self.SamplesBrowseButtonDNA.setToolTip("Browse Samples Folder")NEWLINE self.RefVariantlabelDNA.setText(_translate("MainWindow", "Reference Known Variant"))NEWLINE# self.RefVariantpushButton.setText(_translate("MainWindow", "Browse"))NEWLINE self.RefVariantpushButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/browse.png')))NEWLINE# self.RefVariantpushButton.setStyleSheet("background-color: #aeaeae")NEWLINE self.RefVariantpushButton.setToolTip("Browse Reference Known Variant")NEWLINE self.RefVariantpushButton.setIconSize(QtCore.QSize(22, 22))NEWLINE self.RefNamelabelDNA.setText(_translate("MainWindow", "Reference Name (as in SnpEff Database)"))NEWLINENEWLINE self.nextbuttoninputDNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow.svg')))NEWLINE self.nextbuttoninputDNA.setIconSize(QtCore.QSize(35, 35))NEWLINE self.nextbuttoninputDNA.setStyleSheet("background-color: #704214")NEWLINE self.DNAtabWidget.setTabText(self.DNAtabWidget.indexOf(self.input_dna), _translate("MainWindow", " Input Data "))NEWLINE self.DNAtabWidget.setTabIcon(self.DNAtabWidget.indexOf(self.input_dna), QtGui.QIcon(os.path.join(module_dir,'./icons/input.svg')))NEWLINE# self.DNAtabWidget.setStyleSheet(self.DNAtabWidget.indexOf(self.input_dna), ("background-color: #EBF6F5"))NEWLINE self.DNAtabWidget.setIconSize(QtCore.QSize(22, 22))NEWLINE NEWLINE ## End ###NEWLINE NEWLINE ##Label progres bar##NEWLINENEWLINE NEWLINE ## Add QC ##NEWLINE self.QClabel.setToolTip(_translate("MainWindow", "This option performs all the Quality Control operations like fastQC, Cutadapt and MultiQC "))NEWLINE self.QClabel.setText(_translate("MainWindow", "Trim the reads"))NEWLINE self.QCYesradioButton.setToolTip(_translate("MainWindow", "Enables Quality Control Processing"))NEWLINE self.QCYesradioButton.setText(_translate("MainWindow", "Yes"))NEWLINE self.QCNoradioButton.setToolTip(_translate("MainWindow", "Disables Quality Control Processing"))NEWLINE self.QCNoradioButton.setText(_translate("MainWindow", "No"))NEWLINE self.InputParamslabel.setText(_translate("MainWindow", "Input Parameters:"))NEWLINENEWLINE self.Cutadaptlabel.setText(_translate("MainWindow", "Cutadapt"))NEWLINE self.CutadaptlineEdit.setText(_translate("MainWindow", "-q 20"))NEWLINENEWLINE self.RunQCpushButton.setText(_translate("MainWindow", "Trimming"))NEWLINE self.RunQCpushButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/run1.svg')))NEWLINE self.RunQCpushButton.setIconSize(QtCore.QSize(22, 22))NEWLINE self.RunQCpushButton.setStyleSheet("background-color: #704214")NEWLINE self.nextbuttonqcDNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow.svg')))NEWLINE self.nextbuttonqcDNA.setStyleSheet("background-color: #704214")NEWLINE self.nextbuttonqcDNA.setIconSize(QtCore.QSize(35, 35))NEWLINE self.previousbuttonqcDNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow1.svg')))NEWLINE self.previousbuttonqcDNA.setStyleSheet("background-color: #704214")NEWLINE self.previousbuttonqcDNA.setIconSize(QtCore.QSize(35, 35))NEWLINE self.DNAtabWidget.setTabText(self.DNAtabWidget.indexOf(self.QC_dna), _translate("MainWindow", " Quality Control "))NEWLINE self.DNAtabWidget.setTabIcon(self.DNAtabWidget.indexOf(self.QC_dna), QtGui.QIcon(os.path.join(module_dir,'./icons/qc.svg')))NEWLINE NEWLINE NEWLINE ## End ##NEWLINENEWLINE self.AlignercomboBoxDNA.setItemText(0, _translate("MainWindow", "BWA_MEM"))NEWLINE self.AlignercomboBoxDNA.setItemText(1, _translate("MainWindow", "GEM3"))NEWLINE self.AlignercomboBoxDNA.setItemText(2, _translate("MainWindow", "Bowtie2"))NEWLINE# NEWLINE self.AnnotatorcomboBoxDNA.setItemText(0, _translate("MainWindow", "SnpEff"))NEWLINE self.AnnotatorcomboBoxDNA.setItemText(1, _translate("MainWindow", "Annovar"))NEWLINENEWLINE self.nextbuttontoolDNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow.svg')))NEWLINE self.nextbuttontoolDNA.setStyleSheet("background-color: #704214")NEWLINE self.nextbuttontoolDNA.setIconSize(QtCore.QSize(35, 35))NEWLINE self.previousbuttontoolDNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow1.svg')))NEWLINE self.previousbuttontoolDNA.setStyleSheet("background-color: #704214")NEWLINE self.previousbuttontoolDNA.setIconSize(QtCore.QSize(35, 35))NEWLINE self.DNAtabWidget.setTabText(self.DNAtabWidget.indexOf(self.Tool_dna), _translate("MainWindow", " Tools Selection "))NEWLINE toolstab_img = os.path.join(module_dir,'toolstab.png')NEWLINE self.Tool_dna.setStyleSheet("background-image: url({});".format(toolstab_img))NEWLINE self.DNAtabWidget.setTabIcon(self.DNAtabWidget.indexOf(self.Tool_dna), QtGui.QIcon(os.path.join(module_dir,'./icons/tools.svg')))NEWLINE NEWLINE ## Add Index ##NEWLINENEWLINE self.BWAIndexlineEdit.setToolTip(_translate("MainWindow", "Input the path of the Index for " + self.AlignercomboBoxDNA.currentText()))NEWLINE self.BWAIndexpushButton.setToolTip(_translate("MainWindow", "Click this to select one of the already available index or for a custom index"))NEWLINE self.BWAIndexpushButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/browse.png')))NEWLINE self.BWAIndexpushButton.setIconSize(QtCore.QSize(22, 22))NEWLINE self.BWAIndexpushButton.setToolTip("Browse Index File")NEWLINE self.OrLabel_dna.setText(_translate("MainWindow", "Or"))NEWLINENEWLINE self.RunIndexdnapushButton.setText(_translate("MainWindow", "Generate Index"))NEWLINE self.RunIndexdnapushButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/run1.svg')))NEWLINE self.RunIndexdnapushButton.setStyleSheet("background-color: #704214")NEWLINE self.RunIndexdnapushButton.setIconSize(QtCore.QSize (22, 22))NEWLINE NEWLINE NEWLINENEWLINE NEWLINE ## Add run DNA##NEWLINE self.DNAtabWidget.setTabText(self.DNAtabWidget.indexOf(self.run_dna), _translate("MainWindow", " Run "))NEWLINE NEWLINE self.DNAtabWidget.setTabIcon(self.DNAtabWidget.indexOf(self.run_dna), QtGui.QIcon(os.path.join(module_dir,'./icons/run1.svg')))NEWLINE self.DNAtabWidget.setIconSize(QtCore.QSize(22, 22))NEWLINE NEWLINE self.nextbuttonrunDNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow.svg')))NEWLINE self.nextbuttonrunDNA.setStyleSheet("background-color: #704214")NEWLINE self.nextbuttonrunDNA.setIconSize(QtCore.QSize(35, 35))NEWLINE self.previousbuttonrunDNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow1.svg')))NEWLINE self.previousbuttonrunDNA.setStyleSheet("background-color: #704214")NEWLINE self.previousbuttonrunDNA.setIconSize(QtCore.QSize(35, 35))NEWLINE ##End##NEWLINE ##Add Result DNA##NEWLINE self.DNAtabWidget.setTabText(self.DNAtabWidget.indexOf(self.result_dna), _translate("MainWindow", " Results "))NEWLINE self.DNAtabWidget.setTabIcon(self.DNAtabWidget.indexOf(self.result_dna), QtGui.QIcon(os.path.join(module_dir,'./icons/results.svg')))NEWLINENEWLINE self.DNAtabWidget.setIconSize(QtCore.QSize(22, 22))NEWLINE ##End##NEWLINE NEWLINE ## Add run RNA##NEWLINE self.RNAtabWidget.setTabText(self.RNAtabWidget.indexOf(self.run_rna), _translate("MainWindow", " Run "))NEWLINE self.RNAtabWidget.setTabIcon(self.RNAtabWidget.indexOf(self.run_rna), QtGui.QIcon(os.path.join(module_dir,'./icons/run1.svg')))NEWLINE self.RNAtabWidget.setIconSize(QtCore.QSize(22, 22))NEWLINE self.nextbuttonrunRNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow.svg')))NEWLINE self.nextbuttonrunRNA.setStyleSheet("background-color: #704214")NEWLINE self.nextbuttonrunRNA.setIconSize(QtCore.QSize(35, 35))NEWLINE self.previousbuttonrunRNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow1.svg')))NEWLINE self.previousbuttonrunRNA.setStyleSheet("background-color: #704214")NEWLINE self.previousbuttonrunRNA.setIconSize(QtCore.QSize(35, 35))NEWLINE ##End##NEWLINE ##Add Result RNA##NEWLINE self.RNAtabWidget.setTabText(self.RNAtabWidget.indexOf(self.result_rna), _translate("MainWindow", " Results "))NEWLINE self.RNAtabWidget.setTabIcon(self.RNAtabWidget.indexOf(self.result_rna), QtGui.QIcon(os.path.join(module_dir,'./icons/results.svg')))NEWLINE self.RNAtabWidget.setIconSize(QtCore.QSize(22, 22))NEWLINE ##End## NEWLINE NEWLINE self.RunButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/run1.svg')))NEWLINE self.RunButton.setIconSize(QtCore.QSize(50, 50))NEWLINE self.RunButton.setStyleSheet("background-color:#704214")NEWLINE NEWLINE self.RunButton_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/run1.svg')))NEWLINE self.RunButton_dna.setIconSize(QtCore.QSize(50, 50))NEWLINE self.RunButton_dna.setStyleSheet("background-color:#704214") NEWLINE NEWLINENEWLINE self.RunLabel.setText(_translate("MainWindow", "Run"))NEWLINE font_label = QtGui.QFont()NEWLINE font_label.setPointSize(15)NEWLINE font_label.setBold(True)NEWLINE self.RunLabel.setFont(font_label)NEWLINE NEWLINE NEWLINE self.RunLabel_dna.setFont(font_label)NEWLINE self.RunLabel_dna.setText(_translate("MainWindow", "Run"))NEWLINE NEWLINENEWLINENEWLINE self.PipelinetabWidget.setTabText(self.PipelinetabWidget.indexOf(self.DNAseq), _translate("MainWindow", "DNA-Seq Pipeline"))NEWLINE self.PipelinetabWidget.setTabIcon(self.PipelinetabWidget.indexOf(self.DNAseq), QtGui.QIcon(os.path.join(module_dir,'./icons/dna.svg')))NEWLINE self.PipelinetabWidget.setIconSize(QtCore.QSize(22, 22))NEWLINENEWLINE self.PipelinetabWidget.setTabToolTip(self.PipelinetabWidget.indexOf(self.DNAseq), _translate("MainWindow", "Select this pipeline to generate Annotated VCFs"))NEWLINENEWLINE ## Make Input as first tab ##NEWLINE self.SampleOrlabel_rna.setText(_translate("MainWindow", "Or"))NEWLINE self.SamplesYesradioButton_rna.setText(_translate("MainWindow", "Upload from Folder"))NEWLINE self.SamplesNoradioButton_rna.setText(_translate("MainWindow", "Upload from Table"))NEWLINENEWLINE self.SampleFolderlabel.setText(_translate("MainWindow", "Samples Folder"))NEWLINE self.SampleFolderBrowseButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/browse.png')))NEWLINE self.SampleFolderBrowseButton.setIconSize(QtCore.QSize(22, 22))NEWLINE self.SampleFolderBrowseButton.setToolTip("Browse Samples Folder")NEWLINE self.Sampletablelabel.setText(_translate("MainWindow", "Samples Table"))NEWLINE NEWLINE self.FastaFilelabel.setText(_translate("MainWindow", "Fasta File"))NEWLINE self.AnnotatedFilelabelRNA.setText(_translate("MainWindow", "Annotated File"))NEWLINE NEWLINE self.SampletableBrowseButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/browse.png')))NEWLINE self.SampletableBrowseButton.setIconSize(QtCore.QSize(22, 22))NEWLINE self.SampletableBrowseButton.setToolTip("Browse Samples Table")NEWLINE NEWLINE self.FastaBrowseButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/browse.png')))NEWLINE self.FastaBrowseButton.setIconSize(QtCore.QSize(22, 22))NEWLINE self.FastaBrowseButton.setToolTip("Browse Fasta File")NEWLINE self.AnnotatedBrowserButtonRNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/browse.png')))NEWLINE self.AnnotatedBrowserButtonRNA.setIconSize(QtCore.QSize(22, 22))NEWLINE self.AnnotatedBrowserButtonRNA.setToolTip("Browse Annotated File")NEWLINENEWLINE self.CorelabelRNA.setText(_translate("MainWindow", "Maximum threads"))NEWLINE self.CorelineEditRNA.setText(_translate("MainWindow", "1"))NEWLINE NEWLINENEWLINE self.nextbuttoninputRNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow.svg')))NEWLINE self.nextbuttoninputRNA.setStyleSheet("background-color: #704214")NEWLINE self.nextbuttoninputRNA.setIconSize(QtCore.QSize(35, 35))NEWLINE self.RNAtabWidget.setTabText(self.RNAtabWidget.indexOf(self.input_rna), _translate("MainWindow", " Input Data "))NEWLINE self.RNAtabWidget.setTabIcon(self.RNAtabWidget.indexOf(self.input_rna), QtGui.QIcon(os.path.join(module_dir,'./icons/input.svg')))NEWLINE self.RNAtabWidget.setIconSize(QtCore.QSize(22, 22))NEWLINE NEWLINE ## End ##NEWLINE ## Add QC ##NEWLINE self.QClabel_rna.setToolTip(_translate("MainWindow", "This option performs all the Quality Control operations like fastQC, Cutadapt and MultiQC "))NEWLINE self.QClabel_rna.setText(_translate("MainWindow", "Trim the reads"))NEWLINE self.QCYesradioButton_rna.setToolTip(_translate("MainWindow", "Enables Quality Control Processing"))NEWLINE self.QCYesradioButton_rna.setText(_translate("MainWindow", "Yes"))NEWLINE self.QCNoradioButton_rna.setToolTip(_translate("MainWindow", "Disables Quality Control Processing"))NEWLINE self.QCNoradioButton_rna.setText(_translate("MainWindow", "No"))NEWLINE self.InputParamslabel_rna.setText(_translate("MainWindow", "Input Parameters:"))NEWLINENEWLINE self.Cutadaptlabel_rna.setText(_translate("MainWindow", "Cutadapt"))NEWLINE self.CutadaptlineEdit_rna.setText(_translate("MainWindow", " --adapter AGATCGGAAGAGCACACGTCTGAACTCCAGTCAC -A AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGTAGATCTCGGTGGTCGCCGTATCATT "))NEWLINENEWLINE self.RunQCpushButton_rna.setText(_translate("MainWindow", "Trimming"))NEWLINE self.RunQCpushButton_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/run1.svg')))NEWLINE self.RunQCpushButton_rna.setIconSize(QtCore.QSize(22, 22))NEWLINE self.RunQCpushButton_rna.setStyleSheet("background-color: #704214")NEWLINE self.nextbuttonqcRNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow.svg')))NEWLINE self.nextbuttonqcRNA.setStyleSheet("background-color: #704214")NEWLINE self.nextbuttonqcRNA.setIconSize(QtCore.QSize(35, 35))NEWLINE self.previousbuttonqcRNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow1.svg')))NEWLINE self.previousbuttonqcRNA.setStyleSheet("background-color: #704214")NEWLINE self.previousbuttonqcRNA.setIconSize(QtCore.QSize(35, 35))NEWLINE self.RNAtabWidget.setTabText(self.RNAtabWidget.indexOf(self.QC_rna), _translate("MainWindow", " Quality Control "))NEWLINE self.RNAtabWidget.setTabIcon(self.RNAtabWidget.indexOf(self.QC_rna), QtGui.QIcon(os.path.join(module_dir,'./icons/qc.svg')))NEWLINE NEWLINENEWLINE ## End ##NEWLINENEWLINE self.AlignercomboBoxRNA.setItemText(0, _translate("MainWindow", "HISAT2"))NEWLINE self.AlignercomboBoxRNA.setItemText(1, _translate("MainWindow", "STAR"))NEWLINENEWLINE self.EMcomboBoxRNA.setItemText(0, _translate("MainWindow", "StringTie"))NEWLINE self.EMcomboBoxRNA.setItemText(1, _translate("MainWindow", "HTSeq"))NEWLINENEWLINE self.DEcomboBoxRNA.setItemText(0, _translate("MainWindow", "ballgown"))NEWLINE self.DEcomboBoxRNA.setItemText(1, _translate("MainWindow", "DESeq2"))NEWLINE self.nextbuttontoolRNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow.svg')))NEWLINE self.nextbuttontoolRNA.setStyleSheet("background-color: #704214")NEWLINE self.nextbuttontoolRNA.setIconSize(QtCore.QSize(35, 35))NEWLINE self.previousbuttontoolRNA.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/arrow1.svg')))NEWLINE self.previousbuttontoolRNA.setStyleSheet("background-color: #704214")NEWLINE self.previousbuttontoolRNA.setIconSize(QtCore.QSize(35, 35))NEWLINE self.RNAtabWidget.setTabText(self.RNAtabWidget.indexOf(self.Tool_rna), _translate("MainWindow", " Tools Selection "))NEWLINE self.RNAtabWidget.setTabIcon(self.RNAtabWidget.indexOf(self.Tool_rna), QtGui.QIcon(os.path.join(module_dir,'./icons/tools.svg')))NEWLINE ## Add Index ##NEWLINE self.StarIndexlineEdit.setToolTip(_translate("MainWindow", "Input the path of the Index for" + self.AlignercomboBoxRNA.currentText()))NEWLINE self.StarIndexpushButton.setToolTip(_translate("MainWindow", "Click this to select one of the pre-installed index or for a custom index"))NEWLINE self.StarIndexpushButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/browse.png')))NEWLINE self.StarIndexpushButton.setIconSize(QtCore.QSize(22, 22))NEWLINE self.StarIndexpushButton.setToolTip("Browse Index File")NEWLINE self.OrLabel_rna.setText(_translate("MainWindow", "Or"))NEWLINENEWLINE self.RunIndexrnapushButton.setText(_translate("MainWindow", "Generate Index"))NEWLINE self.RunIndexrnapushButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/run1.svg')))NEWLINE self.RunIndexrnapushButton.setStyleSheet("background-color: #704214")NEWLINE self.RunIndexrnapushButton.setIconSize(QtCore.QSize(22, 22))NEWLINENEWLINE self.PipelinetabWidget.setTabText(self.PipelinetabWidget.indexOf(self.RNAseq), _translate("MainWindow", "RNA-Seq Pipeline"))NEWLINE self.PipelinetabWidget.setTabIcon(self.PipelinetabWidget.indexOf(self.RNAseq), QtGui.QIcon(os.path.join(module_dir,'./icons/rna.svg')))NEWLINE self.PipelinetabWidget.setTabToolTip(self.PipelinetabWidget.indexOf(self.RNAseq), _translate("MainWindow", "Select this pipeline to generate Differentially Expressed Genes"))NEWLINE self.ShellTab.setTabText(self.ShellTab.indexOf(self.SnakemakeOutputTab), _translate("MainWindow", "Logs"))NEWLINE self.ShellTab.setTabIcon(self.ShellTab.indexOf(self.SnakemakeOutputTab), QtGui.QIcon(os.path.join(module_dir,'./icons/log.svg')))NEWLINE self.ShellTab.setIconSize(QtCore.QSize(22, 22))NEWLINE NEWLINE NEWLINE self.PipelinetabWidget.setTabText(self.PipelinetabWidget.indexOf(self.CTAG), _translate("MainWindow", "cTaG"))NEWLINE NEWLINE font_label = QtGui.QFont()NEWLINE font_label.setPointSize(12)NEWLINE font_label.setBold(True)NEWLINE NEWLINE font_label2 = QtGui.QFont()NEWLINE font_label2.setPointSize(10)NEWLINE font_label2.setBold(False) NEWLINE NEWLINE self.maflabel.setText(_translate("MainWindow", "Path to MAF file"))NEWLINE self.mafparamlabel.setText(_translate("MainWindow", "Parameters"))NEWLINE self.mafparamlabel1.setText(_translate("MainWindow", "- m"))NEWLINE self.mafparamlabel2.setText(_translate("MainWindow", "- p"))NEWLINE self.mafparamlineEdit.setText(_translate("MainWindow", "2000"))NEWLINE self.mafparamlineEdit1.setText(_translate("MainWindow", "5"))NEWLINE NEWLINE self.ctaglabel.setText(_translate("MainWindow", "cTaG (classify TSG and OG)"))NEWLINE self.ctaglabel.setFont(font_label)NEWLINE self.ctaglabel2.setText(_translate("MainWindow", "cTaG is a tool used to identify tumour suppressor genes (TSGs)\n and oncogenes (OGs) using somatic mutation data.The cTaG model \n returns the list of all genes labelled as TSG or OG or unlabelled\n along with predictions made by each model and whether\n the gene is among the top predictions ")) NEWLINE self.ctaglabel2.setFont(font_label2)NEWLINE urlLink1 = "cTaG"NEWLINE self.ctaglabel3.setText(_translate("MainWindow", urlLink1 ))NEWLINE self.ctaggithubbutton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/github.png')))NEWLINE self.ctaggithubbutton.setIconSize(QtCore.QSize(22, 22))NEWLINE self.ctaggithubbutton.setToolTip("GitHub link")NEWLINE NEWLINE self.mafBrowseButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/browse.png')))NEWLINE self.mafBrowseButton.setToolTip("Browse MAF File")NEWLINE self.mafBrowseButton.setIconSize(QtCore.QSize(22, 22))NEWLINE NEWLINE self.runctagpushButton.setText(_translate("MainWindow", "cTaG"))NEWLINE self.runctagpushButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/run1.svg')))NEWLINE self.runctagpushButton.setText(_translate("MainWindow", " Run cTaG"))NEWLINE self.runctagpushButton.setIconSize(QtCore.QSize (22, 22)) NEWLINE NEWLINE self.resultctagpushButton.setText(_translate("MainWindow", "cTAG"))NEWLINE self.resultctagpushButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/document.svg')))NEWLINE self.resultctagpushButton.setText(_translate("MainWindow", " View Results"))NEWLINE self.resultctagpushButton.setIconSize(QtCore.QSize (22, 22)) NEWLINE NEWLINE self.PipelinetabWidget.setTabText(self.PipelinetabWidget.indexOf(self.NB), _translate("MainWindow", "NBDriver"))NEWLINE NEWLINE font_label = QtGui.QFont()NEWLINE font_label.setPointSize(12)NEWLINE font_label.setBold(True)NEWLINE NEWLINE font_label2 = QtGui.QFont()NEWLINE font_label2.setPointSize(10)NEWLINE font_label2.setBold(False)NEWLINE NEWLINE NEWLINE self.vcflabel.setText(_translate("MainWindow", "Path to VCF file"))NEWLINE self.nblabel.setText(_translate("MainWindow", "NBDriver (NEIGHBORHOOD Driver)"))NEWLINE self.nblabel.setFont(font_label)NEWLINE self.nblabel2.setText(_translate("MainWindow", "NBDriver is a tool used to differentiate between driver \n and passenger mutations using features derived from \n the neighborhood sequences of somatic mutations.NBDriver \n returns a list of all mutations labelled as Driver or Passenger")) NEWLINE self.nblabel2.setFont(font_label2)NEWLINE NEWLINE urlLink = "NBDriver"NEWLINE self.nblabel3.setText(_translate("MainWindow", urlLink ))NEWLINE urlLink1 = "Banerjee et al."NEWLINE self.nblabel5.setText(_translate("MainWindow", urlLink1 ))NEWLINE self.nbgithubbutton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/github.png')))NEWLINE self.nbgithubbutton.setIconSize(QtCore.QSize(22, 22))NEWLINE self.nbgithubbutton.setToolTip("GitHub link")NEWLINE self.nbpaperbutton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/document.svg')))NEWLINE self.nbpaperbutton.setIconSize(QtCore.QSize(22, 22))NEWLINE self.nbpaperbutton.setToolTip("GitHub link")NEWLINE urlLink2 = "link"NEWLINE self.nblabel4.setText(_translate("MainWindow", " NBDriver predictions has been derived using hg19 reference genome only. The user needs to download the \n reference file from this and put it in the /NBDriver_iCOMIC/ directory and the input vcf file must be \n kept inside /NBDriver_ICOMIC/vcf directory and renamed as NBDriver_vcf.vcf" ))NEWLINE self.nblabel6.setText(_translate("MainWindow", urlLink2 ))NEWLINE NEWLINE self.vcfBrowseButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/browse.png')))NEWLINE self.vcfBrowseButton.setToolTip("Browse VCF File")NEWLINE self.vcfBrowseButton.setIconSize(QtCore.QSize(22, 22))NEWLINE NEWLINE self.runnbpushButton.setText(_translate("MainWindow", "NBDriver"))NEWLINE self.runnbpushButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/run1.svg')))NEWLINE self.runnbpushButton.setText(_translate("MainWindow", " Run NBDriver"))NEWLINE self.runnbpushButton.setIconSize(QtCore.QSize (22, 22)) NEWLINE NEWLINE self.resultnbpushButton.setText(_translate("MainWindow", "NBDriver"))NEWLINE self.resultnbpushButton.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/document.svg')))NEWLINE self.resultnbpushButton.setText(_translate("MainWindow", " View Results"))NEWLINE self.resultnbpushButton.setIconSize(QtCore.QSize (22, 22)) NEWLINE NEWLINE NEWLINENEWLINE self.menuFile.setTitle(_translate("MainWindow", "File"))NEWLINE self.menuOption.setTitle(_translate("MainWindow", "Option"))NEWLINE self.menuHelp.setTitle(_translate("MainWindow", "Help"))NEWLINE self.actionQuit.setText(_translate("MainWindow", "Quit"))NEWLINE self.actionAbout.setText(_translate("MainWindow", "About"))NEWLINE self.actionQuick_Start.setText(_translate("MainWindow", "Quick Start"))NEWLINE self.actionAbout_2.setText(_translate("MainWindow", "About"))NEWLINE self.actionSnakemake_Options.setText(_translate("MainWindow", "Snakemake Options"))NEWLINE ##Changelabel on choosing tools##NEWLINENEWLINE NEWLINE self.nextbuttoninputDNA.clicked.connect(self.on_clicked_nextbuttoninputDNA)NEWLINE self.nextbuttonqcDNA.clicked.connect(self.on_clicked_nextbuttonqcDNA)NEWLINE self.nextbuttontoolDNA.clicked.connect(self.on_clicked_nextbuttonparamsDNA)NEWLINE self.nextbuttontoolDNA.clicked.connect(self.on_clicked_nextbuttontoolDNA)NEWLINE self.previousbuttonqcDNA.clicked.connect(self.on_clicked_previousbuttonqcDNA)NEWLINE self.previousbuttontoolDNA.clicked.connect(self.on_clicked_previousbuttontoolDNA)NEWLINE self.previousbuttonrunRNA.clicked.connect(self.on_clicked_previousbuttonrunDNA)NEWLINE self.nextbuttoninputRNA.clicked.connect(self.on_clicked_nextbuttoninputRNA)NEWLINE self.nextbuttonqcRNA.clicked.connect(self.on_clicked_nextbuttonqcRNA)NEWLINE self.nextbuttontoolRNA.clicked.connect(self.on_clicked_nextbuttonparamsRNA)NEWLINE self.nextbuttontoolRNA.clicked.connect(self.on_clicked_nextbuttontoolRNA)NEWLINE self.previousbuttonqcRNA.clicked.connect(self.on_clicked_previousbuttonqcRNA)NEWLINE self.previousbuttontoolRNA.clicked.connect(self.on_clicked_previousbuttontoolRNA)NEWLINE NEWLINE self.SamplesNoradioButton.toggled.connect(self.on_check_SamplesNo_dna)NEWLINE self.SamplesNoradioButton_rna.toggled.connect(self.on_check_SamplesNo_rna)NEWLINE self.QCresults.clicked.connect(self.show_qc_textbox)NEWLINE self.QCresults.clicked.connect(self.show_qc_results)NEWLINE NEWLINE self.QCYesradioButton.toggled.connect(self.on_check_QC_dna)NEWLINE self.QCYesradioButton_rna.toggled.connect(self.on_check_QC_rna)NEWLINE self.QCresults_rna.clicked.connect(self.show_qc_textbox)NEWLINE self.QCresults_rna.clicked.connect(self.show_qc_results_rna)NEWLINE NEWLINE self.aligner_add_dna.clicked.connect(self.advanced_aligner)NEWLINE self.vc_add_dna.clicked.connect(self.advanced_vc)NEWLINE self.annotator_add_dna.clicked.connect(self.advanced_annotator)NEWLINE self.aligner_add_rna.clicked.connect(self.advanced_aligner_rna)NEWLINE self.em_add_rna.clicked.connect(self.advanced_em)NEWLINE self.de_add_rna.clicked.connect(self.advanced_de)NEWLINE self.AnnotatorcomboBoxDNA.currentIndexChanged.connect(self.not_snpeff)NEWLINE self.AlignercomboBoxDNA.currentIndexChanged.connect(self.param_display)NEWLINE self.VCcomboBoxDNA.currentIndexChanged.connect(self.param_display)NEWLINE self.AnnotatorcomboBoxDNA.currentIndexChanged.connect(self.param_display)NEWLINE self.AlignercomboBoxRNA.currentIndexChanged.connect(self.param_display_rna)NEWLINE self.EMcomboBoxRNA.currentIndexChanged.connect(self.param_display_rna)NEWLINE self.DEcomboBoxRNA.currentIndexChanged.connect(self.param_display_rna)NEWLINE NEWLINE self.pushbutton_result1_dna.clicked.connect(self.multiqc_result)NEWLINE self.pushbutton_result2_dna.clicked.connect(self.vcf_result)NEWLINE self.pushbutton_result3_dna.clicked.connect(self.annotated_result)NEWLINE self.pushbutton_result1_rna.clicked.connect(self.multiqc_result_rna)NEWLINE self.pushbutton_result2_rna.clicked.connect(self.de_result)NEWLINE self.pushbutton_result3_rna.clicked.connect(self.plot_view)NEWLINE NEWLINE self.RunButton_dna.clicked.connect(self.run_action_textbox)NEWLINE self.RunButton_dna.clicked.connect(self.run_action_dna)NEWLINE self.RunButton.clicked.connect(self.run_action_textbox)NEWLINE self.RunButton.clicked.connect(self.run_action_rna)NEWLINE NEWLINE self.pYesradioButton.toggled.connect(self.on_check_proceed)NEWLINE self.nextbuttonresult.clicked.connect(self.on_click_nextresults)NEWLINENEWLINENEWLINENEWLINE ##data_browse##NEWLINE self.SamplesBrowseButtonDNA.clicked.connect(self.browse_data_samples)NEWLINE self.UnitsBrowseButtonDNA.clicked.connect(self.browse_data_units)NEWLINE self.RefGenomeBrowseButtonDNA.clicked.connect(self.browse_data_ref)NEWLINE self.RefVariantpushButton.clicked.connect(self.browse_data_kv)NEWLINE ##Enable browse button for index##NEWLINE self.BWAIndexpushButton.clicked.connect(self.browse_bwaindex_dna)NEWLINENEWLINE self.StarIndexpushButton.clicked.connect(self.browse_star_rna)NEWLINENEWLINE self.SampletableBrowseButton.clicked.connect(self.browse_data_sampletable)NEWLINE self.FastaBrowseButton.clicked.connect(self.browse_data_fasta)NEWLINE self.AnnotatedBrowserButtonRNA.clicked.connect(self.browse_data_annotated)NEWLINE self.SampleFolderBrowseButton.clicked.connect(self.browse_samples_folder)NEWLINE ##Run_QC##NEWLINENEWLINE self.RunQCpushButton.clicked.connect(self.run_qc_textbox)NEWLINE self.RunQCpushButton.clicked.connect(self.run_qc_dna)NEWLINENEWLINE self.RunQCpushButton_rna.clicked.connect(self.run_qc_rna_textbox)NEWLINE self.RunQCpushButton_rna.clicked.connect(self.run_qc_rna)NEWLINE NEWLINE ##Add additional parameters##NEWLINE ##Run_indexing##NEWLINENEWLINE self.RunIndexdnapushButton.clicked.connect(self.run_index_text)NEWLINE self.RunIndexdnapushButton.clicked.connect(self.run_index_dna)NEWLINE self.RunIndexrnapushButton.clicked.connect(self.run_index_text)NEWLINE self.RunIndexrnapushButton.clicked.connect(self.run_index_rna)NEWLINE ##Run_main##NEWLINE ##run cTAG##NEWLINE NEWLINE self.mafBrowseButton.clicked.connect(self.browse_data_maf)NEWLINE self.runctagpushButton.clicked.connect(self.on_click_run_ctag)NEWLINE self.resultctagpushButton.clicked.connect(self.on_click_result_ctag)NEWLINE NEWLINE NEWLINE self.vcfBrowseButton.clicked.connect(self.browse_data_vcf)NEWLINE self.runnbpushButton.clicked.connect(self.on_click_run_nbdriver)NEWLINE self.resultnbpushButton.clicked.connect(self.on_click_result_nbdriver)NEWLINE NEWLINE NEWLINE ##show dag##NEWLINE ##menu_popups##NEWLINE self.actionAbout_2.triggered.connect(self.about)NEWLINE self.actionQuick_Start.triggered.connect(self.quick_start)NEWLINENEWLINE# =============================================================================NEWLINE def on_click_nextresults(self):NEWLINE if self.ctagradioButton.isChecked() == True:NEWLINE self.PipelinetabWidget.setCurrentIndex(2)NEWLINE subprocess.run(["snakemake", "--use-conda", "-j", self.CorelineEditDNA.text(), "-s", "Snakefile_maf"]) NEWLINE elif self.nbradioButton.isChecked() == True:NEWLINE self.PipelinetabWidget.setCurrentIndex(3)NEWLINE else:NEWLINE passNEWLINE def on_click_run_ctag(self):NEWLINE subprocess.run(["python","cTaG/code/cTaG.py","-i", self.maflineEdit.text(), "-o", (os.getcwd()+"/cTaG/results"), "-c","/cTaG", "-m", self.mafparamlineEdit.text(), "-p", self.mafparamlineEdit1.text()])NEWLINE NEWLINE def on_click_result_ctag(self):NEWLINE path='cTaG/results/CVpredictions.txt'NEWLINE self.result_dialog= ResultsDialog(path)NEWLINE self.result_dialog.show()NEWLINE NEWLINE def on_click_run_nbdriver(self):NEWLINE subprocess.run([(os.getcwd()+"/NBDriver_ICOMIC/run.sh")])NEWLINE NEWLINE def on_click_result_nbdriver(self):NEWLINE path='NBDriver_Predictions.csv'NEWLINE self.result_dialog= ResultsDialog(path)NEWLINE self.result_dialog.show()NEWLINE NEWLINE def run_results_textbox(self):NEWLINE subprocess.run(["snakemake", "--unlock", "-j", "1"])NEWLINE self.textBrowser.setTextColor(self._colors['blue'])NEWLINE self.textBrowser.append("Please be patient, while we generate MAF files \n\n")NEWLINENEWLINENEWLINE def multiqc_result(self):NEWLINE if os.path.exists("results_dna/multiqc/multiqc.html"):NEWLINE self.textBrowser.setTextColor(self._colors['blue'])NEWLINE filename = "results_dna/multiqc/multiqc.html"NEWLINE webbrowser.get('google-chrome').open(filename, new=0, autoraise=True)NEWLINE else:NEWLINE passNEWLINE NEWLINE def vcf_result(self):NEWLINE path='results_dna/filtered/all.vcf.gz'NEWLINE self.result_dialog= ResultsDialog(path)NEWLINENEWLINE NEWLINE self.result_dialog.show()NEWLINE NEWLINE def annotated_result(self):NEWLINE if self.AnnotatorcomboBoxDNA.currentText()=="SnpEff":NEWLINE path = "results_dna/annotated/all.vcf"NEWLINE elif self.AnnotatorcomboBoxDNA.currentText()=="Annovar":NEWLINE path = "results_dna/annotated/all.hg19_multianno.vcf"NEWLINE# path = "results_dna/annotated/all.multianno.vcf"NEWLINE self.result_dialog= ResultsDialog(path)NEWLINE self.result_dialog.show()NEWLINE else:NEWLINE passNEWLINE self.result_dialog= ResultsDialog(path)NEWLINE self.result_dialog.show()NEWLINE NEWLINE def de_result(self):NEWLINE if self.DEcomboBoxRNA.currentText() == 'ballgown':NEWLINE path='results/de_results/SigDE.txt'NEWLINE elif self.DEcomboBoxRNA.currentText() == 'DESeq2':NEWLINE path = 'results/de_results/DESeq2_normalized_counts.txt'NEWLINE self.result_dialog= ResultsDialog(path)NEWLINE self.result_dialog.show()NEWLINE else:NEWLINE passNEWLINE self.result_dialog= ResultsDialog(path)NEWLINE self.result_dialog.show()NEWLINE NEWLINE def plot_view(self):NEWLINE if os.path.exists("results/de_results/plot_output.pdf"):NEWLINE filename = "results/de_results/plot_output.pdf"NEWLINE webbrowser.get('google-chrome').open(filename, new=0, autoraise=True)NEWLINE elif os.path.exists("results/de_results/Rplots.pdf"):NEWLINE filename = "results/de_results/Rplots.pdf "NEWLINE webbrowser.get('google-chrome').open(filename, new=0, autoraise=True)NEWLINE else:NEWLINE passNEWLINENEWLINE NEWLINE def multiqc_result_rna(self):NEWLINE if os.path.exists("results/multiqc/multiqc.html"):NEWLINE self.textBrowser.setTextColor(self._colors['blue'])NEWLINE filename = "results/multiqc/multiqc.html"NEWLINE webbrowser.get('google-chrome').open(filename, new=0, autoraise=True)NEWLINE else:NEWLINE passNEWLINE NEWLINE def create_aligner_groupbox(self):NEWLINE font_label = QtGui.QFont()NEWLINE font_label.setPointSize(8.5)NEWLINE color = QtGui.QColor(233, 10, 150)NEWLINE self.aligner_groupbox = QGroupBox("Aligner")NEWLINE self.vlayout= QtWidgets.QVBoxLayout()NEWLINE self.hlayout0_aligner = QtWidgets.QHBoxLayout()NEWLINE font_info = QtGui.QFont()NEWLINE font_info.setPointSize(8.5)NEWLINE self.Alignerninfoicon_dna = QtWidgets.QPushButton(self.aligner_groupbox)NEWLINE self.Alignerninfoicon_dna.setFlat(True)NEWLINE self.Alignerninfoicon_dna.setGeometry(QtCore.QRect(48, 0, 20, 20))NEWLINE self.Alignerninfoicon_dna.setToolTip("Software for arranging sequences to identify regions of similarity")NEWLINE self.Alignerninfoicon_dna.setFont(font_info)NEWLINE self.Alignerninfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.Alignerninfoicon_dna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.AlignercomboBoxDNA = QtWidgets.QComboBox()NEWLINE self.AlignercomboBoxDNA.move(20, 10)NEWLINE self.AlignercomboBoxDNA.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)NEWLINE self.AlignercomboBoxDNA.setObjectName("AlignercomboBoxDNA")NEWLINE self.AlignercomboBoxDNA.addItem("")NEWLINE self.AlignercomboBoxDNA.addItem("")NEWLINE self.AlignercomboBoxDNA.addItem("")NEWLINE self.hlayout0_aligner.addWidget(self.AlignercomboBoxDNA)NEWLINE self.hlayout0_aligner.addStretch(0)NEWLINE self.vlayout.addItem(self.hlayout0_aligner)NEWLINE self.hlayout1_aligner = QtWidgets.QHBoxLayout()NEWLINE self.hlayout1_aligner.setSpacing(10)NEWLINE self.BWAIndexlabel = QtWidgets.QLabel()NEWLINE self.BWAIndexlabel.setObjectName("BWAIndexlabel")NEWLINE self.BWAIndexlineEdit = QtWidgets.QLineEdit()NEWLINE self.BWAIndexlineEdit.setObjectName("BWAIndexlineEdit")NEWLINE self.BWAIndexpushButton = QtWidgets.QPushButton()NEWLINE self.BWAIndexpushButton.setObjectName("BWAIndexpushButton")NEWLINE NEWLINE self.hlayout1_aligner.addWidget(self.BWAIndexlabel)NEWLINE self.hlayout1_aligner.addWidget(self.BWAIndexlineEdit)NEWLINE self.hlayout1_aligner.addWidget(self.BWAIndexpushButton)NEWLINE self.vlayout.addItem(self.hlayout1_aligner)NEWLINE NEWLINE self.hlayout1_error_aligner = QtWidgets.QHBoxLayout()NEWLINE self.BWAIndexErrortext = QtWidgets.QLabel()NEWLINE self.BWAIndexErrortext.setGeometry(QtCore.QRect(170, 113, 331, 22))NEWLINE self.BWAIndexErrortext.setObjectName("BWAIndexErrortext")NEWLINE self.BWAIndexErrortext.setStyleSheet("color: red")NEWLINE self.BWAIndexErrortext.setFont(font_label)NEWLINE self.BWAIndexErrortext.hide()NEWLINE self.hlayout1_error_aligner.addWidget(self.BWAIndexErrortext, 0, alignment=QtCore.Qt.AlignCenter)NEWLINE self.vlayout.addItem(self.hlayout1_error_aligner)NEWLINE NEWLINE self.hlayout0_or = QtWidgets.QHBoxLayout()NEWLINE self.OrLabel_dna = QtWidgets.QLabel()NEWLINE self.OrLabel_dna.setGeometry(QtCore.QRect(340, 130, 270, 23))NEWLINE self.OrLabel_dna.setObjectName("OrLabel_dna")NEWLINE self.hlayout0_or.addWidget(self.OrLabel_dna, 0, alignment=QtCore.Qt.AlignCenter)NEWLINE self.vlayout.addItem(self.hlayout0_or)NEWLINE NEWLINE self.hlayout0_runindex = QtWidgets.QHBoxLayout()NEWLINE self.RunIndexdnapushButton = QtWidgets.QPushButton()NEWLINE self.RunIndexdnapushButton.setObjectName("RunIndexdnapushButton")NEWLINE self.hlayout0_runindex.addWidget(self.RunIndexdnapushButton, 0, alignment=QtCore.Qt.AlignCenter)NEWLINE self.RunIndexdnaButtonErroricon = QtWidgets.QPushButton()NEWLINE self.RunIndexdnaButtonErroricon.setGeometry(QtCore.QRect(480, 175, 20, 20))NEWLINE self.RunIndexdnaButtonErroricon.setToolTip("Check and Run Index Again!")NEWLINE self.RunIndexdnaButtonErroricon.setFont(font_label)NEWLINE self.RunIndexdnaButtonErroricon.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/warning.svg')))NEWLINE self.hlayout0_runindex.addWidget(self.RunIndexdnaButtonErroricon, 0, alignment=QtCore.Qt.AlignCenter)NEWLINE self.RunIndexdnaButtonErroricon.hide()NEWLINE self.vlayout.addItem(self.hlayout0_runindex)NEWLINE NEWLINE self.hlayout0_pb = QtWidgets.QHBoxLayout()NEWLINE self.hlayout0_pb.setGeometry(QtCore.QRect(10, 230, 665, 17))NEWLINE self.progressBar_sub2_dna = QtWidgets.QProgressBar()NEWLINE self.progressBar_sub2_dna.setProperty("value", 0)NEWLINE self.progressBar_sub2_dna.setObjectName("progressBar_sub2_dna")NEWLINE self.hlayout0_pb.addWidget(self.progressBar_sub2_dna)NEWLINE self.vlayout.addItem(self.hlayout0_pb)NEWLINENEWLINE NEWLINE NEWLINE self.param1_label_dna_1 = QtWidgets.QLabel()NEWLINE self.param1_label_dna_1.setGeometry(QtCore.QRect(20, 40, 91, 18))NEWLINE self.param1_lineEdit_dna_1 = QtWidgets.QLineEdit()NEWLINE self.param1_lineEdit_dna_1.setGeometry(QtCore.QRect(120, 40, 70, 18))NEWLINE self.param1_label_dna_3 = QtWidgets.QLabel()NEWLINE self.param1_label_dna_3.setGeometry(QtCore.QRect(200, 40, 91, 18))NEWLINE self.param1_lineEdit_dna_3 = QtWidgets.QLineEdit()NEWLINE self.param1_lineEdit_dna_3.setGeometry(QtCore.QRect(280, 40, 70, 18))NEWLINE self.param1_label_dna_5 = QtWidgets.QLabel()NEWLINE self.param1_label_dna_5.setGeometry(QtCore.QRect(360, 40, 91, 18))NEWLINE self.param1_lineEdit_dna_5 = QtWidgets.QLineEdit()NEWLINE self.param1_lineEdit_dna_5.setGeometry(QtCore.QRect(440, 40, 70, 18))NEWLINENEWLINE NEWLINE self.param1_label_dna_2 = QtWidgets.QLabel()NEWLINE self.param1_label_dna_2.setGeometry(QtCore.QRect(20, 65, 91, 18))NEWLINE self.param1_lineEdit_dna_2 = QtWidgets.QLineEdit()NEWLINE self.param1_lineEdit_dna_2.setGeometry(QtCore.QRect(120, 65, 70, 18))NEWLINE self.param1_label_dna_4 = QtWidgets.QLabel()NEWLINE self.param1_label_dna_4.setGeometry(QtCore.QRect(200, 65, 91, 18))NEWLINE self.param1_lineEdit_dna_4 = QtWidgets.QLineEdit()NEWLINE self.param1_lineEdit_dna_4.setGeometry(QtCore.QRect(280, 65, 70, 18))NEWLINE self.param1_label_dna_6 = QtWidgets.QLabel()NEWLINE self.param1_label_dna_6.setGeometry(QtCore.QRect(360, 65, 91, 18))NEWLINE self.param1_lineEdit_dna_6 = QtWidgets.QLineEdit()NEWLINE self.param1_lineEdit_dna_6.setGeometry(QtCore.QRect(440, 65, 70, 18))NEWLINE NEWLINE self.grid_aligner = QtWidgets.QGridLayout()NEWLINE self.grid_aligner.setSpacing(10)NEWLINE self.grid_aligner.addWidget(self.param1_label_dna_1, 0, 0)NEWLINE self.grid_aligner.addWidget(self.param1_lineEdit_dna_1, 0, 1)NEWLINE self.grid_aligner.addWidget(self.param1_label_dna_3, 0, 2)NEWLINE self.grid_aligner.addWidget(self.param1_lineEdit_dna_3, 0, 3)NEWLINE self.grid_aligner.addWidget(self.param1_label_dna_5, 0, 4)NEWLINE self.grid_aligner.addWidget(self.param1_lineEdit_dna_5, 0, 5)NEWLINE self.grid_aligner.addWidget(self.param1_label_dna_2, 1,0)NEWLINE self.grid_aligner.addWidget(self.param1_lineEdit_dna_2, 1,1)NEWLINE self.grid_aligner.addWidget(self.param1_label_dna_4, 1,2)NEWLINE self.grid_aligner.addWidget(self.param1_lineEdit_dna_4, 1, 3)NEWLINE self.grid_aligner.addWidget(self.param1_label_dna_6, 1,4)NEWLINE self.grid_aligner.addWidget(self.param1_lineEdit_dna_6, 1,5)NEWLINE NEWLINE self.vlayout.addItem(self.grid_aligner)NEWLINE NEWLINE NEWLINE self.hlayout4_aligner = QtWidgets.QHBoxLayout()NEWLINE self.hlayout4_aligner.addStretch(1)NEWLINE self.aligner_add_dna = QtWidgets.QPushButton()NEWLINE self.aligner_add_dna.setGeometry(QtCore.QRect(530, 45, 70, 30))NEWLINE self.aligner_add_dna.setText("Advanced")NEWLINE self.aligner_add_dna.setStyleSheet("background-color: #704214")NEWLINE self.hlayout4_aligner.addWidget(self.aligner_add_dna)NEWLINE self.vlayout.addItem(self.hlayout4_aligner)NEWLINE NEWLINE self.aligner_groupbox.setLayout(self.vlayout)NEWLINE NEWLINE font_param = QtGui.QFont()NEWLINE font_param.setBold(True)NEWLINENEWLINE NEWLINE ##set of lbels and lineedits for params##NEWLINE NEWLINE self.param1_label_dna_1.hide()NEWLINE self.param1_label_dna_2.hide()NEWLINE self.param1_label_dna_3.hide()NEWLINE self.param1_label_dna_4.hide()NEWLINE self.param1_label_dna_5.hide()NEWLINE self.param1_label_dna_6.hide()NEWLINE self.param1_lineEdit_dna_1.hide()NEWLINE self.param1_lineEdit_dna_2.hide()NEWLINE self.param1_lineEdit_dna_3.hide()NEWLINE self.param1_lineEdit_dna_4.hide()NEWLINE self.param1_lineEdit_dna_5.hide()NEWLINE self.param1_lineEdit_dna_6.hide()NEWLINE NEWLINE NEWLINE NEWLINE NEWLINE def create_vc_groupbox(self):NEWLINE self.vc_groupbox = QGroupBox("Variant caller")NEWLINE self.vlayout_vc= QtWidgets.QVBoxLayout()NEWLINE self.hlayout0_vc = QtWidgets.QHBoxLayout()NEWLINE NEWLINE font_info = QtGui.QFont()NEWLINE font_info.setPointSize(8.5)NEWLINE self.VariantCallerninfoicon_dna = QtWidgets.QPushButton(self.vc_groupbox)NEWLINE self.VariantCallerninfoicon_dna.setFlat(True)NEWLINE self.VariantCallerninfoicon_dna.setGeometry(QtCore.QRect(84, 0, 20, 20))NEWLINE self.VariantCallerninfoicon_dna.setToolTip("Variant calling is the process by which variants are identified from \n the sample sequence data in comparison to the reference sequence.")NEWLINE self.VariantCallerninfoicon_dna.setFont(font_info)NEWLINE self.VariantCallerninfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.VariantCallerninfoicon_dna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.VCcomboBoxDNA = QtWidgets.QComboBox()NEWLINE self.VCcomboBoxDNA.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)NEWLINE self.VCcomboBoxDNA.setObjectName("VCcomboBoxDNA")NEWLINE self.VCcomboBoxDNA.addItem("")NEWLINE self.hlayout0_vc.addWidget(self.VCcomboBoxDNA)NEWLINE self.hlayout0_vc.addStretch(0)NEWLINE self.vlayout_vc.addItem(self.hlayout0_vc)NEWLINE NEWLINE NEWLINE self.param2_label_dna_1 = QtWidgets.QLabel()NEWLINE self.param2_label_dna_1.setGeometry(QtCore.QRect(20, 40, 91, 18))NEWLINE self.param2_lineEdit_dna_1 = QtWidgets.QLineEdit()NEWLINE self.param2_lineEdit_dna_1.setGeometry(QtCore.QRect(120, 40, 70, 18))NEWLINE self.param2_label_dna_3 = QtWidgets.QLabel()NEWLINE self.param2_label_dna_3.setGeometry(QtCore.QRect(200, 40, 91, 18))NEWLINE self.param2_lineEdit_dna_3 = QtWidgets.QLineEdit()NEWLINE self.param2_lineEdit_dna_3.setGeometry(QtCore.QRect(280, 40, 70, 18))NEWLINE self.param2_label_dna_5 = QtWidgets.QLabel()NEWLINE self.param2_label_dna_5.setGeometry(QtCore.QRect(360, 40, 91, 18))NEWLINE self.param2_lineEdit_dna_5 = QtWidgets.QLineEdit()NEWLINE self.param2_lineEdit_dna_5.setGeometry(QtCore.QRect(440, 40, 70, 18))NEWLINE NEWLINE self.param2_label_dna_2 = QtWidgets.QLabel()NEWLINE self.param2_label_dna_2.setGeometry(QtCore.QRect(20, 65, 91, 18))NEWLINE self.param2_lineEdit_dna_2 = QtWidgets.QLineEdit()NEWLINE self.param2_lineEdit_dna_2.setGeometry(QtCore.QRect(120, 65, 70, 18))NEWLINE self.param2_label_dna_4 = QtWidgets.QLabel()NEWLINE self.param2_label_dna_4.setGeometry(QtCore.QRect(200, 65, 91, 18))NEWLINE self.param2_lineEdit_dna_4 = QtWidgets.QLineEdit()NEWLINE self.param2_lineEdit_dna_4.setGeometry(QtCore.QRect(280, 65, 70, 18))NEWLINE self.param2_label_dna_6 = QtWidgets.QLabel()NEWLINE self.param2_label_dna_6.setGeometry(QtCore.QRect(360, 65, 91, 18))NEWLINE self.param2_lineEdit_dna_6 = QtWidgets.QLineEdit()NEWLINE self.param2_lineEdit_dna_6.setGeometry(QtCore.QRect(440, 65, 70, 18))NEWLINE NEWLINE self.grid_vc = QtWidgets.QGridLayout()NEWLINE self.grid_vc.setSpacing(10)NEWLINE self.grid_vc.addWidget(self.param2_label_dna_1, 0, 0)NEWLINE self.grid_vc.addWidget(self.param2_lineEdit_dna_1, 0, 1)NEWLINE self.grid_vc.addWidget(self.param2_label_dna_3, 0, 2)NEWLINE self.grid_vc.addWidget(self.param2_lineEdit_dna_3, 0, 3)NEWLINE self.grid_vc.addWidget(self.param2_label_dna_5, 0, 4)NEWLINE self.grid_vc.addWidget(self.param2_lineEdit_dna_5, 0, 5)NEWLINE self.grid_vc.addWidget(self.param2_label_dna_2, 1,0)NEWLINE self.grid_vc.addWidget(self.param2_lineEdit_dna_2, 1,1)NEWLINE self.grid_vc.addWidget(self.param2_label_dna_4, 1,2)NEWLINE self.grid_vc.addWidget(self.param2_lineEdit_dna_4, 1, 3)NEWLINE self.grid_vc.addWidget(self.param2_label_dna_6, 1,4)NEWLINE self.grid_vc.addWidget(self.param2_lineEdit_dna_6, 1,5)NEWLINE NEWLINE self.vlayout_vc.addItem(self.grid_vc)NEWLINE self.param2_label_dna_1.hide()NEWLINE self.param2_label_dna_2.hide()NEWLINE self.param2_label_dna_3.hide()NEWLINE self.param2_label_dna_4.hide()NEWLINE self.param2_label_dna_5.hide()NEWLINE self.param2_label_dna_6.hide()NEWLINE self.param2_lineEdit_dna_1.hide()NEWLINE self.param2_lineEdit_dna_2.hide()NEWLINE self.param2_lineEdit_dna_3.hide()NEWLINE self.param2_lineEdit_dna_4.hide()NEWLINE self.param2_lineEdit_dna_5.hide()NEWLINE self.param2_lineEdit_dna_6.hide()NEWLINE NEWLINE self.hlayout4_vc = QtWidgets.QHBoxLayout()NEWLINE self.hlayout4_vc.addStretch(1)NEWLINE self.vc_add_dna = QtWidgets.QPushButton()NEWLINE self.vc_add_dna.setGeometry(QtCore.QRect(530, 45, 70, 30))NEWLINE self.vc_add_dna.setText("Advanced")NEWLINE self.vc_add_dna.setStyleSheet("background-color: #704214")NEWLINE self.hlayout4_vc.addWidget(self.vc_add_dna)NEWLINE self.vlayout_vc.addItem(self.hlayout4_vc)NEWLINE NEWLINE self.vc_groupbox.setLayout(self.vlayout_vc)NEWLINE NEWLINE def create_annotator_groupbox(self):NEWLINE self.annotator_groupbox = QGroupBox("Annotator")NEWLINE self.vlayout_annotator= QtWidgets.QVBoxLayout()NEWLINE self.vlayout.setSpacing(20)NEWLINE self.hlayout0_annotator = QtWidgets.QHBoxLayout()NEWLINE NEWLINE self.hlayout1_warning_annotator = QtWidgets.QHBoxLayout()NEWLINE self.AnnotatorWarningtext = QtWidgets.QLabel()NEWLINE self.AnnotatorWarningtext.setGeometry(QtCore.QRect(90, 0, 331, 22))NEWLINE self.AnnotatorWarningtext.setObjectName("AnnotatorWarningtext")NEWLINE self.AnnotatorWarningtext.setStyleSheet("color: orange")NEWLINE self.AnnotatorWarningtext.setText("Choose Annovar if proceeding for cTaG or NBDriver")NEWLINE self.hlayout1_warning_annotator.addWidget(self.AnnotatorWarningtext, 0, alignment=QtCore.Qt.AlignCenter)NEWLINE self.vlayout_annotator.addItem(self.hlayout1_warning_annotator)NEWLINE NEWLINE font_info = QtGui.QFont()NEWLINE font_info.setPointSize(8.5)NEWLINE self.Annotatorninfoicon_dna = QtWidgets.QPushButton(self.annotator_groupbox)NEWLINE self.Annotatorninfoicon_dna.setFlat(True)NEWLINE self.Annotatorninfoicon_dna.setGeometry(QtCore.QRect(64, 0, 20, 20))NEWLINE self.Annotatorninfoicon_dna.setToolTip("Software for functionally annotating the identified variants")NEWLINE self.Annotatorninfoicon_dna.setFont(font_info)NEWLINE self.Annotatorninfoicon_dna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.Annotatorninfoicon_dna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.AnnotatorcomboBoxDNA = QtWidgets.QComboBox()NEWLINE self.AnnotatorcomboBoxDNA.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)NEWLINE self.AnnotatorcomboBoxDNA.setObjectName("AnnotatorcomboBoxDNA")NEWLINE self.AnnotatorcomboBoxDNA.addItem("")NEWLINE self.AnnotatorcomboBoxDNA.addItem("")NEWLINE self.hlayout0_annotator.addWidget(self.AnnotatorcomboBoxDNA)NEWLINE self.hlayout0_annotator.addStretch(0)NEWLINE self.vlayout_annotator.addItem(self.hlayout0_annotator)NEWLINE NEWLINE self.hlayout1_annotator = QtWidgets.QHBoxLayout()NEWLINE self.RefNamelabelDNA = QtWidgets.QLabel()NEWLINE self.RefNamelabelDNA.setObjectName("RefNamelabelDNA")NEWLINE self.RefNamecomboBoxDNA = QtWidgets.QComboBox()NEWLINE self.RefNamecomboBoxDNA.setObjectName("RefNamecomboBoxDNA")NEWLINE self.RefNamecomboBoxDNA.addItem("hg38")NEWLINE self.RefNamecomboBoxDNA.addItem("GRCh38.86")NEWLINE self.RefNamecomboBoxDNA.addItem("hg19")NEWLINE self.RefNamecomboBoxDNA.addItem("GRCh37.75")NEWLINE self.hlayout1_annotator.addWidget(self.RefNamelabelDNA)NEWLINE self.hlayout1_annotator.addWidget(self.RefNamecomboBoxDNA)NEWLINE self.vlayout_annotator.addItem(self.hlayout1_annotator)NEWLINE NEWLINE NEWLINE self.param3_label_dna_1 = QtWidgets.QLabel()NEWLINE self.param3_label_dna_1.setGeometry(QtCore.QRect(20, 40, 91, 18))NEWLINE self.param3_lineEdit_dna_1 = QtWidgets.QLineEdit()NEWLINE self.param3_lineEdit_dna_1.setGeometry(QtCore.QRect(120, 40, 70, 18))NEWLINE self.param3_label_dna_3 = QtWidgets.QLabel()NEWLINE self.param3_label_dna_3.setGeometry(QtCore.QRect(200, 40, 91, 18))NEWLINE self.param3_lineEdit_dna_3 = QtWidgets.QLineEdit()NEWLINE self.param3_lineEdit_dna_3.setGeometry(QtCore.QRect(280, 40, 70, 18))NEWLINE self.param3_label_dna_5 = QtWidgets.QLabel()NEWLINE self.param3_label_dna_5.setGeometry(QtCore.QRect(360, 40, 91, 18))NEWLINE self.param3_lineEdit_dna_5 = QtWidgets.QLineEdit()NEWLINE self.param3_lineEdit_dna_5.setGeometry(QtCore.QRect(440, 40, 70, 18))NEWLINE NEWLINE self.param3_label_dna_2 = QtWidgets.QLabel()NEWLINE self.param3_label_dna_2.setGeometry(QtCore.QRect(20, 65, 91, 18))NEWLINE self.param3_lineEdit_dna_2 = QtWidgets.QLineEdit()NEWLINE self.param3_lineEdit_dna_2.setGeometry(QtCore.QRect(120, 65, 70, 18))NEWLINE self.param3_label_dna_4 = QtWidgets.QLabel()NEWLINE self.param3_label_dna_4.setGeometry(QtCore.QRect(200, 65, 91, 18))NEWLINE self.param3_lineEdit_dna_4 = QtWidgets.QLineEdit()NEWLINE self.param3_lineEdit_dna_4.setGeometry(QtCore.QRect(280, 65, 70, 18))NEWLINE self.param3_label_dna_6 = QtWidgets.QLabel()NEWLINE self.param3_label_dna_6.setGeometry(QtCore.QRect(360, 65, 91, 18))NEWLINE self.param3_lineEdit_dna_6 = QtWidgets.QLineEdit()NEWLINE self.param3_lineEdit_dna_6.setGeometry(QtCore.QRect(440, 65, 70, 18))NEWLINE NEWLINE self.grid_annotator = QtWidgets.QGridLayout()NEWLINE self.grid_annotator.setSpacing(10)NEWLINE self.grid_annotator.addWidget(self.param3_label_dna_1, 0, 0)NEWLINE self.grid_annotator.addWidget(self.param3_lineEdit_dna_1, 0, 1)NEWLINE self.grid_annotator.addWidget(self.param3_label_dna_3, 0, 2)NEWLINE self.grid_annotator.addWidget(self.param3_lineEdit_dna_3, 0, 3)NEWLINE self.grid_annotator.addWidget(self.param3_label_dna_5, 0, 4)NEWLINE self.grid_annotator.addWidget(self.param3_lineEdit_dna_5, 0, 5)NEWLINE self.grid_annotator.addWidget(self.param3_label_dna_2, 1,0)NEWLINE self.grid_annotator.addWidget(self.param3_lineEdit_dna_2, 1,1)NEWLINE self.grid_annotator.addWidget(self.param3_label_dna_4, 1,2)NEWLINE self.grid_annotator.addWidget(self.param3_lineEdit_dna_4, 1, 3)NEWLINE self.grid_annotator.addWidget(self.param3_label_dna_6, 1,4)NEWLINE self.grid_annotator.addWidget(self.param3_lineEdit_dna_6, 1,5)NEWLINE NEWLINE self.param3_label_dna_1.hide()NEWLINE self.param3_label_dna_2.hide()NEWLINE self.param3_label_dna_3.hide()NEWLINE self.param3_label_dna_4.hide()NEWLINE self.param3_label_dna_5.hide()NEWLINE self.param3_label_dna_6.hide()NEWLINE self.param3_lineEdit_dna_1.hide()NEWLINE self.param3_lineEdit_dna_2.hide()NEWLINE self.param3_lineEdit_dna_3.hide()NEWLINE self.param3_lineEdit_dna_4.hide()NEWLINE self.param3_lineEdit_dna_5.hide()NEWLINE self.param3_lineEdit_dna_6.hide()NEWLINE NEWLINE self.vlayout_annotator.addItem(self.grid_annotator)NEWLINE NEWLINE self.hlayout4_annotator = QtWidgets.QHBoxLayout()NEWLINE self.hlayout4_annotator.addStretch(1)NEWLINE self.annotator_add_dna = QtWidgets.QPushButton()NEWLINE self.annotator_add_dna.setGeometry(QtCore.QRect(530, 45, 70, 30))NEWLINE self.annotator_add_dna.setText("Advanced")NEWLINE self.annotator_add_dna.setStyleSheet("background-color: #704214")NEWLINE self.hlayout4_annotator.addWidget(self.annotator_add_dna)NEWLINE self.vlayout_annotator.addItem(self.hlayout4_annotator)NEWLINE self.annotator_groupbox.setLayout(self.vlayout_annotator)NEWLINE NEWLINE def create_group_next(self):NEWLINE self.next_groupbox = QGroupBox()NEWLINE self.vlayout_next= QtWidgets.QVBoxLayout()NEWLINE self.nextbuttontoolDNA = QtWidgets.QPushButton()NEWLINE self.nextbuttontoolDNA.setGeometry(QtCore.QRect(635, 400, 45, 45))NEWLINE self.nextbuttontoolDNA.setObjectName("nextbuttontoolDNA")NEWLINE ###NEWLINE self.previousbuttontoolDNA = QtWidgets.QPushButton()NEWLINE self.previousbuttontoolDNA.setGeometry(QtCore.QRect(10, 400, 45, 45))NEWLINE self.previousbuttontoolDNA.setObjectName("previousbuttontoolDNA")NEWLINE NEWLINE self.hbox_next = QtWidgets.QHBoxLayout()NEWLINE self.hbox_next.addWidget(self.previousbuttontoolDNA, 0, alignment=QtCore.Qt.AlignLeft)NEWLINE self.hbox_next.addWidget(self.nextbuttontoolDNA, 0, alignment=QtCore.Qt.AlignRight)NEWLINE NEWLINE self.vlayout_next.addItem(self.hbox_next)NEWLINE self.next_groupbox.setLayout(self.vlayout_next)NEWLINE NEWLINE def create_aligner_groupbox_rna(self):NEWLINE font_label = QtGui.QFont()NEWLINE font_label.setPointSize(8.5)NEWLINE color = QtGui.QColor(233, 10, 150)NEWLINE self.aligner_groupbox_rna = QGroupBox("Aligner")NEWLINE self.vlayout_rna= QtWidgets.QVBoxLayout()NEWLINE self.hlayout0_aligner_rna = QtWidgets.QHBoxLayout()NEWLINE NEWLINE font_info = QtGui.QFont()NEWLINE font_info.setPointSize(8.5)NEWLINE self.Alignerninfoicon_rna = QtWidgets.QPushButton(self.aligner_groupbox_rna)NEWLINE self.Alignerninfoicon_rna.setFlat(True)NEWLINE self.Alignerninfoicon_rna.setGeometry(QtCore.QRect(48, 0, 20, 20))NEWLINE self.Alignerninfoicon_rna.setToolTip("Software for arranging sequences to identify regions of similarity")NEWLINE self.Alignerninfoicon_rna.setFont(font_info)NEWLINE self.Alignerninfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.Alignerninfoicon_rna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.AlignercomboBoxRNA = QtWidgets.QComboBox()NEWLINE self.AlignercomboBoxRNA.move(20, 10)NEWLINE self.AlignercomboBoxRNA.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)NEWLINE self.AlignercomboBoxRNA.setObjectName("AlignercomboBoxRNA")NEWLINE self.AlignercomboBoxRNA.addItem("")NEWLINE self.AlignercomboBoxRNA.addItem("")NEWLINE self.hlayout0_aligner_rna.addWidget(self.AlignercomboBoxRNA)NEWLINE self.hlayout0_aligner_rna.addStretch(0)NEWLINE self.vlayout_rna.addItem(self.hlayout0_aligner_rna)NEWLINE self.hlayout1_aligner_rna = QtWidgets.QHBoxLayout()NEWLINE self.hlayout1_aligner_rna.setSpacing(10)NEWLINE self.StarIndexlabel = QtWidgets.QLabel()NEWLINE self.StarIndexlabel.setObjectName("StarIndexlabel")NEWLINE self.StarIndexlineEdit = QtWidgets.QLineEdit()NEWLINE self.StarIndexpushButton = QtWidgets.QPushButton()NEWLINE self.StarIndexpushButton.setObjectName("StarIndexpushButton")NEWLINE NEWLINE self.hlayout1_aligner_rna.addWidget(self.StarIndexlabel)NEWLINE self.hlayout1_aligner_rna.addWidget(self.StarIndexlineEdit)NEWLINE self.hlayout1_aligner_rna.addWidget(self.StarIndexpushButton)NEWLINE self.vlayout_rna.addItem(self.hlayout1_aligner_rna)NEWLINE NEWLINE self.hlayout1_error_aligner_rna = QtWidgets.QHBoxLayout()NEWLINE self.StarIndexErrortext = QtWidgets.QLabel()NEWLINE self.StarIndexErrortext.setGeometry(QtCore.QRect(170, 116, 300, 15))NEWLINE self.StarIndexErrortext.setFont(font_label)NEWLINE self.StarIndexErrortext.setStyleSheet("color: red")NEWLINE self.StarIndexErrortext.hide()NEWLINE self.hlayout1_error_aligner_rna.addWidget(self.StarIndexErrortext, 0, alignment=QtCore.Qt.AlignCenter)NEWLINE self.vlayout_rna.addItem(self.hlayout1_error_aligner_rna)NEWLINE NEWLINE self.hlayout0_or_rna = QtWidgets.QHBoxLayout()NEWLINE self.OrLabel_rna = QtWidgets.QLabel()NEWLINE self.OrLabel_rna.setGeometry(QtCore.QRect(340, 130, 270, 23))NEWLINE self.OrLabel_rna.setObjectName("OrLabel_rna")NEWLINE self.hlayout0_or_rna.addWidget(self.OrLabel_rna, 0, alignment=QtCore.Qt.AlignCenter)NEWLINE self.vlayout_rna.addItem(self.hlayout0_or_rna)NEWLINE NEWLINE self.hlayout0_runindex_rna = QtWidgets.QHBoxLayout()NEWLINE self.RunIndexrnapushButton = QtWidgets.QPushButton()NEWLINE self.RunIndexrnapushButton.setObjectName("RunIndexrnapushButton")NEWLINE self.hlayout0_runindex_rna.addWidget(self.RunIndexrnapushButton, 0, alignment=QtCore.Qt.AlignCenter)NEWLINE self.RunIndexrnaButtonErroricon = QtWidgets.QPushButton()NEWLINE self.RunIndexrnaButtonErroricon.setGeometry(QtCore.QRect(480, 175, 20, 20))NEWLINE self.RunIndexrnaButtonErroricon.setToolTip("Check and Run Index Again!")NEWLINE self.RunIndexrnaButtonErroricon.setFont(font_label)NEWLINE self.RunIndexrnaButtonErroricon.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/warning.svg')))NEWLINE self.RunIndexrnaButtonErroricon.hide()NEWLINE self.hlayout0_runindex_rna.addWidget(self.RunIndexrnaButtonErroricon, 0, alignment=QtCore.Qt.AlignCenter)NEWLINE self.vlayout_rna.addItem(self.hlayout0_runindex_rna)NEWLINE NEWLINE self.hlayout0_pb_rna = QtWidgets.QHBoxLayout()NEWLINE self.progressBar_sub2_rna = QtWidgets.QProgressBar()NEWLINE self.progressBar_sub2_rna.setGeometry(QtCore.QRect(10, 230, 665, 17))NEWLINE self.progressBar_sub2_rna.setProperty("value", 0)NEWLINE self.progressBar_sub2_rna.setObjectName("progressBar_sub2_rna")NEWLINE self.hlayout0_pb_rna.addWidget(self.progressBar_sub2_rna)NEWLINE self.vlayout_rna.addItem(self.hlayout0_pb_rna)NEWLINE NEWLINE self.param1_label_rna_1 = QtWidgets.QLabel()NEWLINE self.param1_label_rna_1.setGeometry(QtCore.QRect(20, 40, 91, 18))NEWLINE self.param1_lineEdit_rna_1 = QtWidgets.QLineEdit()NEWLINE self.param1_lineEdit_rna_1.setGeometry(QtCore.QRect(120, 40, 70, 18))NEWLINE self.param1_label_rna_3 = QtWidgets.QLabel()NEWLINE self.param1_label_rna_3.setGeometry(QtCore.QRect(200, 40, 91, 18))NEWLINE self.param1_lineEdit_rna_3 = QtWidgets.QLineEdit()NEWLINE self.param1_lineEdit_rna_3.setGeometry(QtCore.QRect(280, 40, 70, 18))NEWLINE self.param1_label_rna_5 = QtWidgets.QLabel()NEWLINE self.param1_label_rna_5.setGeometry(QtCore.QRect(360, 40, 91, 18))NEWLINE self.param1_lineEdit_rna_5 = QtWidgets.QLineEdit()NEWLINE self.param1_lineEdit_rna_5.setGeometry(QtCore.QRect(440, 40, 70, 18))NEWLINENEWLINE NEWLINE self.param1_label_rna_2 = QtWidgets.QLabel()NEWLINE self.param1_label_rna_2.setGeometry(QtCore.QRect(20, 65, 91, 18))NEWLINE self.param1_lineEdit_rna_2 = QtWidgets.QLineEdit()NEWLINE self.param1_lineEdit_rna_2.setGeometry(QtCore.QRect(120, 65, 70, 18))NEWLINE self.param1_label_rna_4 = QtWidgets.QLabel()NEWLINE self.param1_label_rna_4.setGeometry(QtCore.QRect(200, 65, 91, 18))NEWLINE self.param1_lineEdit_rna_4 = QtWidgets.QLineEdit()NEWLINE self.param1_lineEdit_rna_4.setGeometry(QtCore.QRect(280, 65, 70, 18))NEWLINE self.param1_label_rna_6 = QtWidgets.QLabel()NEWLINE self.param1_label_rna_6.setGeometry(QtCore.QRect(360, 65, 91, 18))NEWLINE self.param1_lineEdit_rna_6 = QtWidgets.QLineEdit()NEWLINE self.param1_lineEdit_rna_6.setGeometry(QtCore.QRect(440, 65, 70, 18))NEWLINE NEWLINE self.grid_aligner_rna = QtWidgets.QGridLayout()NEWLINE self.grid_aligner_rna.setSpacing(10)NEWLINE self.grid_aligner_rna.addWidget(self.param1_label_rna_1, 0, 0)NEWLINE self.grid_aligner_rna.addWidget(self.param1_lineEdit_rna_1, 0, 1)NEWLINE self.grid_aligner_rna.addWidget(self.param1_label_rna_3, 0, 2)NEWLINE self.grid_aligner_rna.addWidget(self.param1_lineEdit_rna_3, 0, 3)NEWLINE self.grid_aligner_rna.addWidget(self.param1_label_rna_5, 0, 4)NEWLINE self.grid_aligner_rna.addWidget(self.param1_lineEdit_rna_5, 0, 5)NEWLINE self.grid_aligner_rna.addWidget(self.param1_label_rna_2, 1,0)NEWLINE self.grid_aligner_rna.addWidget(self.param1_lineEdit_rna_2, 1,1)NEWLINE self.grid_aligner_rna.addWidget(self.param1_label_rna_4, 1,2)NEWLINE self.grid_aligner_rna.addWidget(self.param1_lineEdit_rna_4, 1, 3)NEWLINE self.grid_aligner_rna.addWidget(self.param1_label_rna_6, 1,4)NEWLINE self.grid_aligner_rna.addWidget(self.param1_lineEdit_rna_6, 1,5)NEWLINE NEWLINE self.vlayout_rna.addItem(self.grid_aligner_rna)NEWLINE NEWLINE NEWLINE self.hlayout4_aligner_rna = QtWidgets.QHBoxLayout()NEWLINE self.hlayout4_aligner_rna.addStretch(1)NEWLINE self.aligner_add_rna = QtWidgets.QPushButton()NEWLINE self.aligner_add_rna.setGeometry(QtCore.QRect(530, 45, 70, 30))NEWLINE self.aligner_add_rna.setText("Advanced")NEWLINE self.aligner_add_rna.setStyleSheet("background-color: #704214")NEWLINE self.hlayout4_aligner_rna.addWidget(self.aligner_add_rna)NEWLINE self.vlayout_rna.addItem(self.hlayout4_aligner_rna)NEWLINE NEWLINE self.aligner_groupbox_rna.setLayout(self.vlayout_rna)NEWLINE NEWLINE font_param = QtGui.QFont()NEWLINE font_param.setBold(True)NEWLINENEWLINE NEWLINE ##set of lbels and lineedits for params##NEWLINE NEWLINE self.param1_label_rna_1.hide()NEWLINE self.param1_label_rna_2.hide()NEWLINE self.param1_label_rna_3.hide()NEWLINE self.param1_label_rna_4.hide()NEWLINE self.param1_label_rna_5.hide()NEWLINE self.param1_label_rna_6.hide()NEWLINE self.param1_lineEdit_rna_1.hide()NEWLINE self.param1_lineEdit_rna_2.hide()NEWLINE self.param1_lineEdit_rna_3.hide()NEWLINE self.param1_lineEdit_rna_4.hide()NEWLINE self.param1_lineEdit_rna_5.hide()NEWLINE self.param1_lineEdit_rna_6.hide()NEWLINE NEWLINE NEWLINE NEWLINE NEWLINE def create_em_groupbox(self):NEWLINE self.em_groupbox = QGroupBox("Expression Modeller")NEWLINE self.vlayout_em= QtWidgets.QVBoxLayout()NEWLINE self.hlayout0_em = QtWidgets.QHBoxLayout()NEWLINE NEWLINE font_info = QtGui.QFont()NEWLINE font_info.setPointSize(8.5)NEWLINE self.eminfoicon_rna = QtWidgets.QPushButton(self.em_groupbox)NEWLINE self.eminfoicon_rna.setFlat(True)NEWLINE self.eminfoicon_rna.setGeometry(QtCore.QRect(125, 0, 20, 20))NEWLINE self.eminfoicon_rna.setToolTip("Expression modelling refers to count the reads mapped \n to individual genes from the aligned the file")NEWLINE self.eminfoicon_rna.setFont(font_info)NEWLINE self.eminfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.eminfoicon_rna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.EMcomboBoxRNA = QtWidgets.QComboBox()NEWLINE self.EMcomboBoxRNA.setObjectName("EMcomboBoxRNA")NEWLINE self.EMcomboBoxRNA.addItem("")NEWLINE self.EMcomboBoxRNA.addItem("")NEWLINE self.hlayout0_em.addWidget(self.EMcomboBoxRNA)NEWLINE self.hlayout0_em.addStretch(0)NEWLINE self.vlayout_em.addItem(self.hlayout0_em)NEWLINE NEWLINE NEWLINE self.param2_label_rna_1 = QtWidgets.QLabel()NEWLINE self.param2_label_rna_1.setGeometry(QtCore.QRect(20, 40, 91, 18))NEWLINE self.param2_lineEdit_rna_1 = QtWidgets.QLineEdit()NEWLINE self.param2_lineEdit_rna_1.setGeometry(QtCore.QRect(120, 40, 70, 18))NEWLINE self.param2_label_rna_3 = QtWidgets.QLabel()NEWLINE self.param2_label_rna_3.setGeometry(QtCore.QRect(200, 40, 91, 18))NEWLINE self.param2_lineEdit_rna_3 = QtWidgets.QLineEdit()NEWLINE self.param2_lineEdit_rna_3.setGeometry(QtCore.QRect(280, 40, 70, 18))NEWLINE self.param2_label_rna_5 = QtWidgets.QLabel()NEWLINE self.param2_label_rna_5.setGeometry(QtCore.QRect(360, 40, 91, 18))NEWLINE self.param2_lineEdit_rna_5 = QtWidgets.QLineEdit()NEWLINE self.param2_lineEdit_rna_5.setGeometry(QtCore.QRect(440, 40, 70, 18))NEWLINE NEWLINE self.param2_label_rna_2 = QtWidgets.QLabel()NEWLINE self.param2_label_rna_2.setGeometry(QtCore.QRect(20, 65, 91, 18))NEWLINE self.param2_lineEdit_rna_2 = QtWidgets.QLineEdit()NEWLINE self.param2_lineEdit_rna_2.setGeometry(QtCore.QRect(120, 65, 70, 18))NEWLINE self.param2_label_rna_4 = QtWidgets.QLabel()NEWLINE self.param2_label_rna_4.setGeometry(QtCore.QRect(200, 65, 91, 18))NEWLINE self.param2_lineEdit_rna_4 = QtWidgets.QLineEdit()NEWLINE self.param2_lineEdit_rna_4.setGeometry(QtCore.QRect(280, 65, 70, 18))NEWLINE self.param2_label_rna_6 = QtWidgets.QLabel()NEWLINE self.param2_label_rna_6.setGeometry(QtCore.QRect(360, 65, 91, 18))NEWLINE self.param2_lineEdit_rna_6 = QtWidgets.QLineEdit()NEWLINE self.param2_lineEdit_rna_6.setGeometry(QtCore.QRect(440, 65, 70, 18))NEWLINE NEWLINE self.grid_em = QtWidgets.QGridLayout()NEWLINE self.grid_em.setSpacing(10)NEWLINE self.grid_em.addWidget(self.param2_label_rna_1, 0, 0)NEWLINE self.grid_em.addWidget(self.param2_lineEdit_rna_1, 0, 1)NEWLINE self.grid_em.addWidget(self.param2_label_rna_3, 0, 2)NEWLINE self.grid_em.addWidget(self.param2_lineEdit_rna_3, 0, 3)NEWLINE self.grid_em.addWidget(self.param2_label_rna_5, 0, 4)NEWLINE self.grid_em.addWidget(self.param2_lineEdit_rna_5, 0, 5)NEWLINE self.grid_em.addWidget(self.param2_label_rna_2, 1,0)NEWLINE self.grid_em.addWidget(self.param2_lineEdit_rna_2, 1,1)NEWLINE self.grid_em.addWidget(self.param2_label_rna_4, 1,2)NEWLINE self.grid_em.addWidget(self.param2_lineEdit_rna_4, 1, 3)NEWLINE self.grid_em.addWidget(self.param2_label_rna_6, 1,4)NEWLINE self.grid_em.addWidget(self.param2_lineEdit_rna_6, 1,5)NEWLINE NEWLINE self.vlayout_em.addItem(self.grid_em)NEWLINE self.param2_label_rna_1.hide()NEWLINE self.param2_label_rna_2.hide()NEWLINE self.param2_label_rna_3.hide()NEWLINE self.param2_label_rna_4.hide()NEWLINE self.param2_label_rna_5.hide()NEWLINE self.param2_label_rna_6.hide()NEWLINE self.param2_lineEdit_rna_1.hide()NEWLINE self.param2_lineEdit_rna_2.hide()NEWLINE self.param2_lineEdit_rna_3.hide()NEWLINE self.param2_lineEdit_rna_4.hide()NEWLINE self.param2_lineEdit_rna_5.hide()NEWLINE self.param2_lineEdit_rna_6.hide()NEWLINE NEWLINE self.hlayout4_em = QtWidgets.QHBoxLayout()NEWLINE self.hlayout4_em.addStretch(1)NEWLINE self.em_add_rna = QtWidgets.QPushButton()NEWLINE self.em_add_rna.setGeometry(QtCore.QRect(530, 45, 70, 30))NEWLINE self.em_add_rna.setText("Advanced")NEWLINE self.em_add_rna.setStyleSheet("background-color: #704214")NEWLINE self.hlayout4_em.addWidget(self.em_add_rna)NEWLINE self.vlayout_em.addItem(self.hlayout4_em)NEWLINE NEWLINE self.em_groupbox.setLayout(self.vlayout_em)NEWLINE NEWLINE def create_de_groupbox(self):NEWLINE self.de_groupbox = QGroupBox("Differential Expression")NEWLINE self.vlayout_de= QtWidgets.QVBoxLayout()NEWLINE self.vlayout_de.setSpacing(20)NEWLINE self.hlayout0_de = QtWidgets.QHBoxLayout()NEWLINE NEWLINE font_info = QtGui.QFont()NEWLINE font_info.setPointSize(8.5)NEWLINE self.deninfoicon_rna = QtWidgets.QPushButton(self.de_groupbox)NEWLINE self.deninfoicon_rna.setFlat(True)NEWLINE self.deninfoicon_rna.setGeometry(QtCore.QRect(140, 0, 20, 20))NEWLINE self.deninfoicon_rna.setToolTip("Differential expression analysis referes to the normalization of read count data \n and employing statistical methods to discover quantitative changes\n in expression levels between different data groups")NEWLINE self.deninfoicon_rna.setFont(font_info)NEWLINE self.deninfoicon_rna.setIcon(QtGui.QIcon(os.path.join(module_dir,'./icons/info.svg')))NEWLINE self.deninfoicon_rna.setIconSize(QtCore.QSize(13, 13)) NEWLINE NEWLINE self.DEcomboBoxRNA = QtWidgets.QComboBox()NEWLINE self.DEcomboBoxRNA.setObjectName("DEcomboBoxRNA")NEWLINE self.DEcomboBoxRNA.addItem("")NEWLINE self.DEcomboBoxRNA.addItem("")NEWLINE self.hlayout0_de.addWidget(self.DEcomboBoxRNA)NEWLINE self.hlayout0_de.addStretch(0)NEWLINE self.vlayout_de.addItem(self.hlayout0_de)NEWLINE NEWLINENEWLINE NEWLINE NEWLINE self.param3_label_rna_1 = QtWidgets.QLabel()NEWLINE self.param3_label_rna_1.setGeometry(QtCore.QRect(20, 40, 91, 18))NEWLINE self.param3_lineEdit_rna_1 = QtWidgets.QLineEdit()NEWLINE self.param3_lineEdit_rna_1.setGeometry(QtCore.QRect(120, 40, 70, 18))NEWLINE self.param3_label_rna_3 = QtWidgets.QLabel()NEWLINE self.param3_label_rna_3.setGeometry(QtCore.QRect(200, 40, 91, 18))NEWLINE self.param3_lineEdit_rna_3 = QtWidgets.QLineEdit()NEWLINE self.param3_lineEdit_rna_3.setGeometry(QtCore.QRect(280, 40, 70, 18))NEWLINE self.param3_label_rna_5 = QtWidgets.QLabel()NEWLINE self.param3_label_rna_5.setGeometry(QtCore.QRect(360, 40, 91, 18))NEWLINE self.param3_lineEdit_rna_5 = QtWidgets.QLineEdit()NEWLINE self.param3_lineEdit_rna_5.setGeometry(QtCore.QRect(440, 40, 70, 18))NEWLINE NEWLINE self.param3_label_rna_2 = QtWidgets.QLabel()NEWLINE self.param3_label_rna_2.setGeometry(QtCore.QRect(20, 65, 91, 18))NEWLINE self.param3_lineEdit_rna_2 = QtWidgets.QLineEdit()NEWLINE self.param3_lineEdit_rna_2.setGeometry(QtCore.QRect(120, 65, 70, 18))NEWLINE self.param3_label_rna_4 = QtWidgets.QLabel()NEWLINE self.param3_label_rna_4.setGeometry(QtCore.QRect(200, 65, 91, 18))NEWLINE self.param3_lineEdit_rna_4 = QtWidgets.QLineEdit()NEWLINE self.param3_lineEdit_rna_4.setGeometry(QtCore.QRect(280, 65, 70, 18))NEWLINE self.param3_label_rna_6 = QtWidgets.QLabel()NEWLINE self.param3_label_rna_6.setGeometry(QtCore.QRect(360, 65, 91, 18))NEWLINE self.param3_lineEdit_rna_6 = QtWidgets.QLineEdit()NEWLINE self.param3_lineEdit_rna_6.setGeometry(QtCore.QRect(440, 65, 70, 18))NEWLINE NEWLINE self.grid_de = QtWidgets.QGridLayout()NEWLINE self.grid_de.setSpacing(10)NEWLINE self.grid_de.addWidget(self.param3_label_rna_1, 0, 0)NEWLINE self.grid_de.addWidget(self.param3_lineEdit_rna_1, 0, 1)NEWLINE self.grid_de.addWidget(self.param3_label_rna_3, 0, 2)NEWLINE self.grid_de.addWidget(self.param3_lineEdit_rna_3, 0, 3)NEWLINE self.grid_de.addWidget(self.param3_label_rna_5, 0, 4)NEWLINE self.grid_de.addWidget(self.param3_lineEdit_rna_5, 0, 5)NEWLINE self.grid_de.addWidget(self.param3_label_rna_2, 1,0)NEWLINE self.grid_de.addWidget(self.param3_lineEdit_rna_2, 1,1)NEWLINE self.grid_de.addWidget(self.param3_label_rna_4, 1,2)NEWLINE self.grid_de.addWidget(self.param3_lineEdit_rna_4, 1, 3)NEWLINE self.grid_de.addWidget(self.param3_label_rna_6, 1,4)NEWLINE self.grid_de.addWidget(self.param3_lineEdit_rna_6, 1,5)NEWLINE NEWLINE self.param3_label_rna_1.hide()NEWLINE self.param3_label_rna_2.hide()NEWLINE self.param3_label_rna_3.hide()NEWLINE self.param3_label_rna_4.hide()NEWLINE self.param3_label_rna_5.hide()NEWLINE self.param3_label_rna_6.hide()NEWLINE self.param3_lineEdit_rna_1.hide()NEWLINE self.param3_lineEdit_rna_2.hide()NEWLINE self.param3_lineEdit_rna_3.hide()NEWLINE self.param3_lineEdit_rna_4.hide()NEWLINE self.param3_lineEdit_rna_5.hide()NEWLINE self.param3_lineEdit_rna_6.hide()NEWLINE NEWLINE self.vlayout_de.addItem(self.grid_de)NEWLINE NEWLINE self.hlayout4_de = QtWidgets.QHBoxLayout()NEWLINE self.hlayout4_de.addStretch(1)NEWLINE self.de_add_rna = QtWidgets.QPushButton()NEWLINE self.de_add_rna.setGeometry(QtCore.QRect(530, 45, 70, 30))NEWLINE self.de_add_rna.setText("Advanced")NEWLINE self.de_add_rna.setStyleSheet("background-color: #704214")NEWLINE self.hlayout4_de.addWidget(self.de_add_rna)NEWLINE self.vlayout_de.addItem(self.hlayout4_de)NEWLINE self.de_groupbox.setLayout(self.vlayout_de)NEWLINE NEWLINE def create_group_next_rna(self):NEWLINE self.next_groupbox_rna = QGroupBox()NEWLINE self.vlayout_next_rna= QtWidgets.QVBoxLayout()NEWLINE self.nextbuttontoolRNA = QtWidgets.QPushButton()NEWLINE self.nextbuttontoolRNA.setGeometry(QtCore.QRect(635, 400, 45, 45))NEWLINE self.nextbuttontoolRNA.setObjectName("nextbuttontoolRNA")NEWLINE ###NEWLINE self.previousbuttontoolRNA = QtWidgets.QPushButton()NEWLINE self.previousbuttontoolRNA.setGeometry(QtCore.QRect(10, 400, 45, 45))NEWLINE self.previousbuttontoolRNA.setObjectName("previousbuttontoolRNA")NEWLINE NEWLINE self.hbox_next_rna = QtWidgets.QHBoxLayout()NEWLINE self.hbox_next_rna.addWidget(self.previousbuttontoolRNA, 0, alignment=QtCore.Qt.AlignLeft)NEWLINE self.hbox_next_rna.addWidget(self.nextbuttontoolRNA, 0, alignment=QtCore.Qt.AlignRight)NEWLINE NEWLINE self.vlayout_next_rna.addItem(self.hbox_next_rna)NEWLINE self.next_groupbox_rna.setLayout(self.vlayout_next_rna)NEWLINE NEWLINE def get_essential(self, path, essential_line_edit_array):NEWLINE dataframe = pd.read_csv(path, header =0)NEWLINE self.essential = dataframe[dataframe["Essential"] == "yes"]NEWLINE self.new_essential = [essential_line_edit_array[i].text() for i in range(len(self.essential))]NEWLINE self.essential['New_value'] = self.new_essentialNEWLINE self.essential['New_value'] = self.essential['New_value'].astype('str')NEWLINE self.essential = self.essential.reset_index()NEWLINE self.essential_dict = dict()NEWLINE for row in self.essential.itertuples():NEWLINE if row[6] != row[8]:NEWLINE self.essential_dict[row[2]] = row[8]NEWLINE return self.essential_dictNEWLINE NEWLINE def get_additional_int(self, path):NEWLINE dataframe = pd.read_csv(path, header =0)NEWLINE self.additional_int = dataframe[(dataframe["Value"] == 'INT') & (dataframe["Essential"] == 'no')]NEWLINE self.new_values_int = [j.text() for j in self.adv_dialog.line_edit_list_int]NEWLINE self.additional_int['New Value'] = self.new_values_intNEWLINE self.additional_int['New Value'] = self.additional_int['New Value'].astype('str')NEWLINE self.additional_int = self.additional_int.reset_index()NEWLINE self.snakefile_dict_int = dict()NEWLINE for row in self.additional_int.itertuples():NEWLINE if row[6] != row[8]:NEWLINE self.snakefile_dict_int[row[2]] = row[8]NEWLINE return self.snakefile_dict_intNEWLINE NEWLINE def get_additional_float(self, path):NEWLINE dataframe = pd.read_csv(path, header =0)NEWLINE self.additional_float = dataframe[(dataframe["Value"] == 'FLOAT') & (dataframe["Essential"] == 'no')]NEWLINE self.new_values_float = [j.text() for j in self.adv_dialog.line_edit_list_float]NEWLINE self.additional_float['New Value'] = self.new_values_floatNEWLINE self.additional_float['New Value'] = self.additional_float['New Value'].astype('str')NEWLINE self.additional_float = self.additional_float.reset_index()NEWLINE self.snakefile_dict_float = dict()NEWLINE for row in self.additional_float.itertuples():NEWLINE if row[6] != row[8]:NEWLINE self.snakefile_dict_float[row[2]] = row[8]NEWLINE return self.snakefile_dict_floatNEWLINE NEWLINE def get_additional_str(self, path):NEWLINE dataframe = pd.read_csv(path, header =0)NEWLINE self.additional_str = dataframe[(dataframe["Value"] == 'STR') & (dataframe["Essential"] == 'no')]NEWLINE self.new_values_str = [j.text() for j in self.adv_dialog.line_edit_list_str]NEWLINE self.additional_str['New Value'] = self.new_values_strNEWLINE self.additional_str['New Value'] = self.additional_str['New Value'].astype('str')NEWLINE self.additional_str = self.additional_str.reset_index()NEWLINE self.snakefile_dict_str = dict()NEWLINE for j in self.adv_dialog.label_list_str:NEWLINE if j.isChecked() == True:NEWLINE self.new_values_str.append("TRUE")NEWLINE else:NEWLINE self.new_values_str.append("FALSE")NEWLINE self.additional_str['New Value'] = self.new_values_strNEWLINE self.additional_str['New Value'] = self.additional_str['New Value'].astype('str')NEWLINE self.additional_str = self.additional_str.reset_index()NEWLINE self.snakefile_dict_str = dict()NEWLINE for row in self.additional_str.itertuples():NEWLINE if row[6] != row[8]:NEWLINE self.snakefile_dict_str[row[2]] = row[8]NEWLINE return self.snakefile_dict_strNEWLINE NEWLINE def get_additional_na(self, path):NEWLINE dataframe = pd.read_csv(path, header =0)NEWLINE self.additional_na = dataframe[(dataframe["Value"] == 'na') & (dataframe["Essential"] == 'no')]NEWLINE self.new_values_na=[]NEWLINE for j in self.adv_dialog.radio_label_list_na:NEWLINE if j.isChecked() == True:NEWLINE self.new_values_na.append("yes")NEWLINE else:NEWLINE self.new_values_na.append("na")NEWLINE self.additional_na['New Value'] = self.new_values_naNEWLINE self.additional_na['New Value'] = self.additional_na['New Value'].astype('str')NEWLINE self.additional_na = self.additional_na.reset_index()NEWLINE self.snakefile_dict_na = dict()NEWLINE for row in self.additional_na.itertuples():NEWLINE if row[6] != row[8]:NEWLINE self.snakefile_dict_na[row[2]] = row[8]NEWLINE return self.snakefile_dict_naNEWLINE NEWLINE NEWLINE def on_clicked_nextbuttoninputDNA(self):NEWLINE if self.SamplesYesradioButton.isChecked() == True:NEWLINE if self.SampleslineEditDNA.text() == '':NEWLINE self.SamplesErrortextDNA.show()NEWLINE self.SamplesErrortextDNA.setText("Input Samples folder path!")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif not os.path.exists(self.SampleslineEditDNA.text()):NEWLINE self.SamplesErrortextDNA.show()NEWLINE self.SamplesErrortextDNA.setText("File doesn't exist! Check the path!")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE else:NEWLINE inputfile = fileinput.input("check_for_correct_filename_check.py", inplace = 1)NEWLINE for l in inputfile:NEWLINE if "test_dir =" in l:NEWLINE print(l.replace(l, "test_dir = '"+self.SampleslineEditDNA.text()+"/'"))NEWLINE else:NEWLINE print(l.rstrip())NEWLINE inputfile.close()NEWLINE subprocess.run(["python", "check_for_correct_filename_check.py"])NEWLINE if os.path.exists('name_check.txt'):NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE with open('name_check.txt') as errorcheck:NEWLINE content = errorcheck.readline()NEWLINE self.SamplesErrortextDNA.show()NEWLINE self.SamplesErrortextDNA.setText(content.rstrip())NEWLINE else:NEWLINE file = fileinput.input("write_tsv.py", inplace = 1)NEWLINE for l in file:NEWLINE if "test_dir =" in l:NEWLINE print(l.replace(l, "test_dir = '"+self.SampleslineEditDNA.text()+"/'"))NEWLINE else:NEWLINE print(l.rstrip())NEWLINE file.close()NEWLINE subprocess.run(["python", "write_tsv.py"])NEWLINE unitsdf =pd.read_table('units.tsv', header=0)NEWLINE self.UnitslineEditDNA.setText("units.tsv")NEWLINE Row_list =[]NEWLINE for index, rows in unitsdf.iterrows():NEWLINE my_list =[rows.condition]NEWLINE Row_list.append(my_list)NEWLINE if ['tumor'] in Row_list:NEWLINE self.VCcomboBoxDNA.setItemText(0, "Mutect2")NEWLINENEWLINE else:NEWLINE self.VCcomboBoxDNA.addItem("")NEWLINE self.VCcomboBoxDNA.addItem("")NEWLINE self.VCcomboBoxDNA.setItemText(0, "GATK_HC")NEWLINE self.VCcomboBoxDNA.setItemText(1, "bcftools_call")NEWLINE self.VCcomboBoxDNA.setItemText(2, "freebayes")NEWLINE NEWLINE NEWLINE NEWLINE if self.RefGenomelineEditDNA.text() == '':NEWLINE self.RefGenomeErrortextDNA.show()NEWLINE self.RefGenomeErrortextDNA.setText("Input reference genome file!")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif not os.path.exists(self.RefGenomelineEditDNA.text()):NEWLINE self.RefGenomeErrortextDNA.show()NEWLINE self.RefGenomeErrortextDNA.setText("File doesn't exist! Check the path!")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif os.path.splitext(self.RefGenomelineEditDNA.text())[-1] != ".fa":NEWLINE self.RefGenomeErrortextDNA.show()NEWLINE self.RefGenomeErrortextDNA.setText("File should have extension '.fa'")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINENEWLINE NEWLINE if self.RefVariantlineEditDNA.text()== '':NEWLINE self.RefVariantErrortextDNA.show()NEWLINE self.RefVariantErrortextDNA.setText("Input reference known variants file!")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif not os.path.exists(self.RefVariantlineEditDNA.text()):NEWLINE self.RefVariantErrortextDNA.show()NEWLINE self.RefVariantErrortextDNA.setText("File doesn't exist! Check the path!")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif os.path.splitext(self.RefVariantlineEditDNA.text())[-1] != ".gz":NEWLINE self.RefVariantErrortextDNA.show()NEWLINE self.RefVariantErrortextDNA.setText("File should have extension '.gz'")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif (self.RefVariantlineEditDNA.text()).split(".")[-2] != "vcf":NEWLINE self.RefVariantErrortextDNA.show()NEWLINE self.RefVariantErrortextDNA.setText("File should be compressed 'vcf'")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE if self.CorelineEditDNA.text()=='':NEWLINE self.CoreErrortextDNA.show()NEWLINE self.CoreErrortextDNA.setText("Input number of threads available")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif not self.CorelineEditDNA.text().isnumeric():NEWLINE self.CoreErrortextDNA.show()NEWLINE self.CoreErrortextDNA.setText("Number of threads should be an integer")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif (os.path.splitext(self.RefGenomelineEditDNA.text())[-1] == ".fa" and not os.path.exists('name_check.txt') and os.path.splitext(self.RefVariantlineEditDNA.text())[-1] == ".gz" and (self.RefVariantlineEditDNA.text().split(".")[-2]) == 'vcf' and self.CorelineEditDNA.text().isnumeric()):NEWLINE self.SamplesErrortextDNA.hide()NEWLINE self.UnitsErrortextDNA.hide()NEWLINE self.RefGenomeErrortextDNA.hide()NEWLINE self.RefVariantErrortextDNA.hide()NEWLINE self.DNAtabWidget.setCurrentIndex(1)NEWLINE self.DNAtabWidget.setTabEnabled(1, True)NEWLINE self.textBrowser.setTextColor(self._colors['blue'])NEWLINE self.textBrowser.append("Click on the 'View Quality control Results' button to view the FastQC report \n")NEWLINE else:NEWLINE if self.UnitslineEditDNA.text() == '':NEWLINE self.UnitsErrortextDNA.show()NEWLINE self.UnitsErrortextDNA.setText("Input Units table!")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif not os.path.exists(self.UnitslineEditDNA.text()):NEWLINE self.UnitsErrortextDNA.show()NEWLINE self.UnitsErrortextDNA.setText("File doesn't exist! Check the path!")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif os.path.splitext(self.UnitslineEditDNA.text())[-1] != ".tsv":NEWLINE self.UnitsErrortextDNA.show()NEWLINE self.UnitsErrortextDNA.setText("File should have extension '.tsv'")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE else:NEWLINE list_tsv_col = ['sample', 'unit', 'condition', 'fq1', 'fq2']NEWLINE unitsdf =pd.read_table(self.UnitslineEditDNA.text(), header=0)NEWLINE if list(unitsdf) != list_tsv_col:NEWLINE self.UnitsErrortextDNA.show()NEWLINE self.UnitsErrortextDNA.setText("Table not in given format! Check!")NEWLINE else:NEWLINE arr = []NEWLINE for item in unitsdf["sample"]:NEWLINE arr.append(item)NEWLINE sample_df = pd.DataFrame({'sample': np.unique(arr)})NEWLINE sample_df.to_csv('samples.tsv', sep = '\t', index=False)NEWLINE Row_list =[]NEWLINE for index, rows in unitsdf.iterrows():NEWLINE my_list =[rows.condition]NEWLINE Row_list.append(my_list)NEWLINE if ['tumor'] in Row_list:NEWLINE self.VCcomboBoxDNA.setItemText(0, "Mutect2")NEWLINENEWLINE else:NEWLINE self.VCcomboBoxDNA.addItem("")NEWLINE self.VCcomboBoxDNA.addItem("")NEWLINE self.VCcomboBoxDNA.setItemText(0, "GATK_HC")NEWLINE self.VCcomboBoxDNA.setItemText(1, "bcftools_call")NEWLINE self.VCcomboBoxDNA.setItemText(2, "freebayes")NEWLINE if self.RefGenomelineEditDNA.text() == '':NEWLINE self.RefGenomeErrortextDNA.show()NEWLINE self.RefGenomeErrortextDNA.setText("Input reference genome file!")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif not os.path.exists(self.RefGenomelineEditDNA.text()):NEWLINE self.RefGenomeErrortextDNA.show()NEWLINE self.RefGenomeErrortextDNA.setText("File doesn't exist! Check the path!")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif os.path.splitext(self.RefGenomelineEditDNA.text())[-1] != ".fa":NEWLINE self.RefGenomeErrortextDNA.show()NEWLINE self.RefGenomeErrortextDNA.setText("File should have extension '.fa'")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINENEWLINE if self.RefVariantlineEditDNA.text()== '':NEWLINE self.RefVariantErrortextDNA.show()NEWLINE self.RefVariantErrortextDNA.setText("Input reference known variants file!")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif not os.path.exists(self.RefVariantlineEditDNA.text()):NEWLINE self.RefVariantErrortextDNA.show()NEWLINE self.RefVariantErrortextDNA.setText("File doesn't exist! Check the path!")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif os.path.splitext(self.RefVariantlineEditDNA.text())[-1] != ".gz":NEWLINE self.RefVariantErrortextDNA.show()NEWLINE self.RefVariantErrortextDNA.setText("File should have extension '.gz'")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif (self.RefVariantlineEditDNA.text()).split(".")[-2] != "vcf":NEWLINE self.RefVariantErrortextDNA.show()NEWLINE self.RefVariantErrortextDNA.setText("File should be compressed 'vcf'")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE if self.CorelineEditDNA.text()=='':NEWLINE self.CoreErrortextDNA.show()NEWLINE self.CoreErrortextDNA.setText("Input number of threads available")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif not self.CorelineEditDNA.text().isnumeric():NEWLINE self.CoreErrortextDNA.show()NEWLINE self.CoreErrortextDNA.setText("Number of threads should be an integer")NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(1, False)NEWLINE elif (list(unitsdf) == list_tsv_col and os.path.splitext(self.RefGenomelineEditDNA.text())[-1] == ".fa" and os.path.splitext(self.RefVariantlineEditDNA.text())[-1] == ".gz" and (self.RefVariantlineEditDNA.text().split(".")[-2]) == 'vcf' and self.CorelineEditDNA.text().isnumeric()):NEWLINE self.SamplesErrortextDNA.hide()NEWLINE self.UnitsErrortextDNA.hide()NEWLINE self.RefGenomeErrortextDNA.hide()NEWLINE self.RefVariantErrortextDNA.hide()NEWLINE self.DNAtabWidget.setCurrentIndex(1)NEWLINE self.DNAtabWidget.setTabEnabled(1, True)NEWLINE self.textBrowser.setTextColor(self._colors['blue'])NEWLINE self.textBrowser.append("Click on the 'View Quality control Results' button to view the FastQC report \n")NEWLINENEWLINE NEWLINE def param_display(self):NEWLINE _translate = QtCore.QCoreApplication.translateNEWLINE path_aligner = './params/'+self.AlignercomboBoxDNA.currentText()+'.csv'NEWLINE path_vc = './params/'+self.VCcomboBoxDNA.currentText()+'.csv'NEWLINE path_annotator = './params/'+self.AnnotatorcomboBoxDNA.currentText()+'.csv'NEWLINENEWLINE dataframe = pd.read_csv(path_aligner, header=0) # specifying that the table has column namesNEWLINE essential = dataframe[dataframe["Essential"] == "yes"]NEWLINE NEWLINE number_of_essential = len(essential) # returns number of essential parametersNEWLINE label_array_param1 = [self.param1_label_dna_1, self.param1_label_dna_2, self.param1_label_dna_3, self.param1_label_dna_4, self.param1_label_dna_5, self.param1_label_dna_6]NEWLINE line_edit_array_param1 = [self.param1_lineEdit_dna_1,self.param1_lineEdit_dna_2, self.param1_lineEdit_dna_3, self.param1_lineEdit_dna_4, self.param1_lineEdit_dna_5, self.param1_lineEdit_dna_6]NEWLINE for i, j, k in zip(range(number_of_essential), label_array_param1, line_edit_array_param1): NEWLINE j.show()NEWLINE j.setText(essential.iloc[i, 2])NEWLINE k.show()NEWLINE k.setText(str(essential.iloc[i, 4]))NEWLINE NEWLINE NEWLINE NEWLINE dataframe_vc = pd.read_csv(path_vc, header=0) # specifying that the table has column namesNEWLINE essential_vc = dataframe_vc[dataframe_vc["Essential"] == "yes"]NEWLINE NEWLINE number_of_essential_vc = len(essential_vc) # returns number of essential parametersNEWLINE label_array_param2 = [self.param2_label_dna_1, self.param2_label_dna_2, self.param2_label_dna_3, self.param2_label_dna_4, self.param2_label_dna_5, self.param2_label_dna_6]NEWLINE line_edit_array_param2 = [self.param2_lineEdit_dna_1,self.param2_lineEdit_dna_2, self.param2_lineEdit_dna_3, self.param2_lineEdit_dna_4, self.param2_lineEdit_dna_5, self.param2_lineEdit_dna_6]NEWLINE for i, j, k in zip(range(number_of_essential_vc), label_array_param2, line_edit_array_param2): NEWLINE j.show()NEWLINE j.setText(essential_vc.iloc[i, 2])NEWLINE k.show()NEWLINE k.setText(str(essential_vc.iloc[i, 4]))NEWLINE NEWLINE dataframe_annotator = pd.read_csv(path_annotator, header=0) # specifying that the table has column namesNEWLINE essential_annotator = dataframe_annotator[dataframe_annotator["Essential"] == "yes"]NEWLINE NEWLINE number_of_essential_annotator = len(essential_annotator) # returns number of essential parametersNEWLINE label_array_param3 = [self.param3_label_dna_1, self.param3_label_dna_2, self.param3_label_dna_3, self.param3_label_dna_4, self.param3_label_dna_5, self.param3_label_dna_6]NEWLINE line_edit_array_param3 = [self.param3_lineEdit_dna_1,self.param3_lineEdit_dna_2, self.param3_lineEdit_dna_3, self.param3_lineEdit_dna_4, self.param3_lineEdit_dna_5, self.param3_lineEdit_dna_6]NEWLINE for i, j, k in zip(range(number_of_essential_annotator), label_array_param3, line_edit_array_param3): NEWLINE j.show()NEWLINE j.setText(essential_annotator.iloc[i, 2])NEWLINE k.show()NEWLINE k.setText(str(essential_annotator.iloc[i, 4]))NEWLINE NEWLINE self.BWAIndexlabel.setText(_translate("MainWindow", "Index for " + self.AlignercomboBoxDNA.currentText()))NEWLINE self.BWAIndexlineEdit.setToolTip(_translate("MainWindow", "Input the path of the Index for" + self.AlignercomboBoxDNA.currentText()))NEWLINE NEWLINE def on_clicking_browse_samples(self):NEWLINE self.SamplesErrortextDNA.hide()NEWLINE NEWLINE def on_clicked_nextbuttonqcDNA(self):NEWLINE self.param_display()NEWLINE if os.path.exists("results_dna/qc"):NEWLINE self.DNAtabWidget.setCurrentIndex(2)NEWLINE self.DNAtabWidget.setTabEnabled(2, True)NEWLINE else:NEWLINE self.qc_warning = showQCDialog()NEWLINE if self.qc_warning.returnValue==QMessageBox.Yes:NEWLINE self.DNAtabWidget.setCurrentIndex(2)NEWLINE self.DNAtabWidget.setTabEnabled(2, True)NEWLINE NEWLINE if self.qc_warning.returnValue== QMessageBox.Cancel:NEWLINE self.DNAtabWidget.setCurrentIndex(1)NEWLINE self.DNAtabWidget.setTabEnabled(2, False)NEWLINE self.DNAtabWidget.setTabEnabled(2, True)NEWLINE def on_clicked_nextbuttontoolDNA(self):NEWLINE self.index_warning()NEWLINE self.DNAtabWidget.setCurrentIndex(3)NEWLINE self.DNAtabWidget.setTabEnabled(3, True)NEWLINE NEWLINE self.create_config_dna()NEWLINE self.create_snakefile_dna()NEWLINE self.if_annovar()NEWLINE self.textBrowser.setTextColor(self._colors['blue'])NEWLINE self.textBrowser.append("Click on the 'Run' button below to start your analysis \n")NEWLINENEWLINE def index_warning(self):NEWLINE if self.BWAIndexlineEdit.text()=='':NEWLINE self.BWAIndexErrortext.show()NEWLINE self.BWAIndexErrortext.setText("Please input index path!")NEWLINE self.DNAtabWidget.setCurrentIndex(3)NEWLINE self.DNAtabWidget.setTabEnabled(4, False)NEWLINE else:NEWLINE self.DNAtabWidget.setCurrentIndex(4)NEWLINE self.DNAtabWidget.setTabEnabled(4, True)NEWLINE NEWLINE def on_clicked_nextbuttonparamsDNA(self):NEWLINENEWLINE self.essential_dict_aligner = self.get_essential(path ='./params/'+self.AlignercomboBoxDNA.currentText()+'.csv', essential_line_edit_array= [self.param1_lineEdit_dna_1,self.param1_lineEdit_dna_2, self.param1_lineEdit_dna_3, self.param1_lineEdit_dna_4, self.param1_lineEdit_dna_5, self.param1_lineEdit_dna_6] )NEWLINE with open('aligner_params.txt', 'w') as aligner_params:NEWLINE aligner_params.write(self.AlignercomboBoxDNA.currentText() + " : '")NEWLINE for k, v in self.essential_dict_aligner.items():NEWLINE aligner_params.write(k +' '+ str(v) + " ")NEWLINE aligner_params.write("'")NEWLINE aligner_params.close()NEWLINE self.essential_dict_vc = self.get_essential(path ='./params/'+self.VCcomboBoxDNA.currentText()+'.csv', essential_line_edit_array =[self.param2_lineEdit_dna_1,self.param2_lineEdit_dna_2, self.param2_lineEdit_dna_3, self.param2_lineEdit_dna_4, self.param2_lineEdit_dna_5, self.param2_lineEdit_dna_6])NEWLINE with open('vc_params.txt', 'w') as vc_params:NEWLINE vc_params.write(self.VCcomboBoxDNA.currentText() + " : '")NEWLINE for k, v in self.essential_dict_vc.items():NEWLINE vc_params.write(k +' '+ str(v) + " ")NEWLINE vc_params.write("'")NEWLINE vc_params.close()NEWLINE self.essential_dict_annotator = self.get_essential(path ='./params/'+self.AnnotatorcomboBoxDNA.currentText()+'.csv', essential_line_edit_array=[self.param3_lineEdit_dna_1,self.param3_lineEdit_dna_2, self.param3_lineEdit_dna_3, self.param3_lineEdit_dna_4, self.param3_lineEdit_dna_5, self.param3_lineEdit_dna_6] )NEWLINE with open('annotator_params.txt', 'w') as annotator_params:NEWLINE if self.AnnotatorcomboBoxDNA.currentText() == "SnpEff":NEWLINE annotator_params.write(self.AnnotatorcomboBoxDNA.currentText() + " : '-Xmx4g ")NEWLINE else:NEWLINE annotator_params.write(self.AnnotatorcomboBoxDNA.currentText() + " : '")NEWLINE for k, v in self.essential_dict_annotator.items():NEWLINE annotator_params.write(k +' '+ str(v) + " ")NEWLINE annotator_params.write("'")NEWLINE annotator_params.close()NEWLINE NEWLINENEWLINE NEWLINE NEWLINE NEWLINE def on_clicked_previousbuttonqcDNA(self):NEWLINE self.DNAtabWidget.setCurrentIndex(0)NEWLINE self.DNAtabWidget.setTabEnabled(0, True)NEWLINE def on_clicked_previousbuttontoolDNA(self):NEWLINE self.DNAtabWidget.setCurrentIndex(1)NEWLINE self.DNAtabWidget.setTabEnabled(1, True)NEWLINE def on_clicked_previousbuttonindexDNA(self):NEWLINE self.DNAtabWidget.setCurrentIndex(2)NEWLINE self.DNAtabWidget.setTabEnabled(2, True)NEWLINE def on_clicked_previousbuttonparamsDNA(self):NEWLINE self.DNAtabWidget.setCurrentIndex(3) NEWLINE self.DNAtabWidget.setTabEnabled(3, True)NEWLINE NEWLINE def on_clicked_previousbuttonrunDNA(self):NEWLINE self.DNAtabWidget.setCurrentIndex(2) NEWLINE self.DNAtabWidget.setTabEnabled(2, True)NEWLINE NEWLINE def on_clicked_previousbuttonresultDNA(self):NEWLINE self.DNAtabWidget.setCurrentIndex(3) NEWLINE self.DNAtabWidget.setTabEnabled(3, True)NEWLINE NEWLINE def on_clicked_nextbuttoninputRNA(self):NEWLINENEWLINE if self.SamplesYesradioButton_rna.isChecked() == True:NEWLINE if self.SampleFolderLineEdit.text() == '':NEWLINE self.SampleFolderErrortextRNA.show()NEWLINE self.SampleFolderErrortextRNA.setText("Input Samples folder path!")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif not os.path.exists(self.SampleFolderLineEdit.text()):NEWLINE self.SampleFolderErrortextRNA.show()NEWLINE self.SampleFolderErrortextRNA.setText("File doesn't exist! Check the path!")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE else :NEWLINE inputfile = fileinput.input("check_for_correct_filename_check.py", inplace = 1)NEWLINE for l in inputfile:NEWLINE if "test_dir =" in l:NEWLINE print(l.replace(l, "test_dir = '"+self.SampleFolderLineEdit.text()+"'"))NEWLINE else:NEWLINE print(l.rstrip())NEWLINE inputfile.close()NEWLINE subprocess.run(["python", "check_for_correct_filename_check.py"])NEWLINE if os.path.exists('name_check.txt'):NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE with open('name_check.txt') as errorcheck:NEWLINE content = errorcheck.readline()NEWLINE self.SampleFolderErrortextRNA.show()NEWLINE self.SampleFolderErrortextRNA.setText(content.rstrip())NEWLINE else:NEWLINE# passNEWLINE file = fileinput.input("write_tsv_rna.py", inplace = 1)NEWLINE for l in file:NEWLINE if "test_dir =" in l:NEWLINE print(l.replace(l, "test_dir = '"+self.SampleFolderLineEdit.text()+"/'"))NEWLINE else:NEWLINE print(l.rstrip())NEWLINE file.close()NEWLINE subprocess.run(["python", "write_tsv_rna.py"])NEWLINE unitsdf =pd.read_table('units.tsv', header=0)NEWLINE self.UnitslineEditDNA.setText("units.tsv")NEWLINE Row_list =[]NEWLINE for index, rows in unitsdf.iterrows():NEWLINE my_list =[rows.condition]NEWLINE Row_list.append(my_list)NEWLINENEWLINE if self.FastalineEdit.text() == '':NEWLINE self.FastaErrortextRNA.show()NEWLINE self.FastaErrortextRNA.setText("Input Fasta file!")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif not os.path.exists(self.FastalineEdit.text()):NEWLINE self.FastaErrortextRNA.show()NEWLINE self.FastaErrortextRNA.setText("File doesn't exist! Check the path!")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif os.path.splitext(self.FastalineEdit.text())[-1] != ".fa":NEWLINE self.FastaErrortextRNA.show()NEWLINE self.FastaErrortextRNA.setText("File should have extension '.fa'")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINENEWLINE if self.AnnotatedlineEditRNA.text()== '':NEWLINE self.AnnotatedErrortextRNA.show()NEWLINE self.AnnotatedErrortextRNA.setText("Input Annotated file!")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif not os.path.exists(self.AnnotatedlineEditRNA.text()):NEWLINE self.AnnotatedErrortextRNA.show()NEWLINE self.AnnotatedErrortextRNA.setText("File doesn't exist! Check the path!")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif os.path.splitext(self.AnnotatedlineEditRNA.text())[-1] != ".gtf":NEWLINE self.AnnotatedErrortextRNA.show()NEWLINE self.AnnotatedErrortextRNA.setText("File should have extension '.gtf'")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINENEWLINE if self.CorelineEditRNA.text()=='':NEWLINE self.CoreErrortextRNA.show()NEWLINE self.CoreErrortextRNA.setText("Input number of threads available")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif not self.CorelineEditRNA.text().isnumeric():NEWLINE# print("File doesn't exist! Check the path!")NEWLINE self.CoreErrortextRNA.show()NEWLINE self.CoreErrortextRNA.setText("Number of threads should be an integer")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif (os.path.splitext(self.FastalineEdit.text())[-1] == ".fa" and not os.path.exists('name_check.txt') and os.path.splitext(self.AnnotatedlineEditRNA.text())[-1] == ".gtf" and self.CorelineEditRNA.text().isnumeric()): NEWLINE self.FastaErrortextRNA.hide()NEWLINE self.SampleFolderErrortextRNA.hide()NEWLINE self.AnnotatedErrortextRNA.hide()NEWLINE self.RNAtabWidget.setCurrentIndex(1)NEWLINE self.RNAtabWidget.setTabEnabled(1, True)NEWLINE self.textBrowser.setTextColor(self._colors['blue'])NEWLINE self.textBrowser.append("Click on the 'View Quality control Results' button below to view the FastQC report \n")NEWLINENEWLINE else:NEWLINE if self.SampleFolderLineEdit.text() == '':NEWLINE self.SampleFolderErrortextRNA.show()NEWLINE self.SampleFolderErrortextRNA.setText("Input Samples folder path!")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif not os.path.exists(self.SampleFolderLineEdit.text()):NEWLINE self.SampleFolderErrortextRNA.show()NEWLINE self.SampleFolderErrortextRNA.setText("File doesn't exist! Check the path!")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINENEWLINE if self.SampletablelineEdit.text() == '':NEWLINE self.SampletableErrortextRNA.show()NEWLINE self.SampletableErrortextRNA.setText("Input Sample Table!")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif not os.path.exists(self.SampletablelineEdit.text()):NEWLINE self.SampletableErrortextRNA.show()NEWLINE self.SampletableErrortextRNA.setText("File doesn't exist! Check the path!")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif os.path.splitext(self.SampletablelineEdit.text())[-1] != ".tsv":NEWLINE self.SampletableErrortextRNA.show()NEWLINE self.SampletableErrortextRNA.setText("File should have extension '.tsv'")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE else:NEWLINE list_tsv_col = ['sample', 'unit', 'condition', 'fq1', 'fq2']NEWLINE unitsdf =pd.read_table(self.SampletablelineEdit.text(), header=0)NEWLINE if list(unitsdf) != list_tsv_col:NEWLINE self.SampletableErrortextRNA.show()NEWLINE self.SampletableErrortextRNA.setText("Table not in given format! Check!")NEWLINE else:NEWLINE subprocess.run(["python", "rename.py"])NEWLINE if os.path.exists("rename_check.txt"):NEWLINE with open('rename_check.txt') as errorcheck:NEWLINE content = errorcheck.readline()NEWLINE self.SampletableErrortextRNA.show()NEWLINE self.SampletableErrortextRNA.setText(content.rstrip())NEWLINE NEWLINE else:NEWLINE passNEWLINENEWLINE if self.FastalineEdit.text() == '':NEWLINE self.FastaErrortextRNA.show()NEWLINE self.FastaErrortextRNA.setText("Input Fasta file!")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif not os.path.exists(self.FastalineEdit.text()):NEWLINE self.FastaErrortextRNA.show()NEWLINE self.FastaErrortextRNA.setText("File doesn't exist! Check the path!")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif os.path.splitext(self.FastalineEdit.text())[-1] != ".fa":NEWLINE self.FastaErrortextRNA.show()NEWLINE self.FastaErrortextRNA.setText("File should have extension '.fa'")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINENEWLINE if self.AnnotatedlineEditRNA.text()== '':NEWLINE self.AnnotatedErrortextRNA.show()NEWLINE self.AnnotatedErrortextRNA.setText("Input Annotated file!")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif not os.path.exists(self.AnnotatedlineEditRNA.text()):NEWLINE self.AnnotatedErrortextRNA.show()NEWLINE self.AnnotatedErrortextRNA.setText("File doesn't exist! Check the path!")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif os.path.splitext(self.AnnotatedlineEditRNA.text())[-1] != ".gtf":NEWLINE self.AnnotatedErrortextRNA.show()NEWLINE self.AnnotatedErrortextRNA.setText("File should have extension '.gtf'")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINENEWLINE if self.CorelineEditRNA.text()=='':NEWLINE self.CoreErrortextRNA.show()NEWLINE self.CoreErrortextRNA.setText("Input number of threads available")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif not self.CorelineEditRNA.text().isnumeric():NEWLINE# print("File doesn't exist! Check the path!")NEWLINE self.CoreErrortextRNA.show()NEWLINE self.CoreErrortextRNA.setText("Number of threads should be an integer")NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(1, False)NEWLINE elif (os.path.splitext(self.FastalineEdit.text())[-1] == ".fa" and list(unitsdf) == list_tsv_col and not os.path.exists('name_check.txt') and not os.path.exists('rename_check.txt') and os.path.splitext(self.AnnotatedlineEditRNA.text())[-1] == ".gtf" and self.CorelineEditDNA.text().isnumeric()):NEWLINE self.FastaErrortextRNA.hide()NEWLINE self.SampleFolderErrortextRNA.hide()NEWLINE self.SampletableErrortextRNA.hide()NEWLINE self.AnnotatedErrortextRNA.hide()NEWLINE self.RNAtabWidget.setCurrentIndex(1)NEWLINE self.RNAtabWidget.setTabEnabled(1, True)NEWLINE self.textBrowser.setTextColor(self._colors['blue'])NEWLINE self.textBrowser.append("Click on the 'View Quality control Results' button below to view the FastQC report \n")NEWLINENEWLINE NEWLINE def on_clicked_nextbuttonqcRNA(self):NEWLINE self.param_display_rna()NEWLINE if os.path.exists("results/fastqc"):NEWLINE self.RNAtabWidget.setCurrentIndex(2)NEWLINE self.RNAtabWidget.setTabEnabled(2, True)NEWLINE else:NEWLINE self.qc_warning = showQCDialog()NEWLINE if self.qc_warning.returnValue==QMessageBox.Yes:NEWLINE self.RNAtabWidget.setCurrentIndex(2)NEWLINE self.RNAtabWidget.setTabEnabled(2, True)NEWLINE NEWLINE if self.qc_warning.returnValue== QMessageBox.Cancel:NEWLINE self.RNAtabWidget.setCurrentIndex(1)NEWLINE self.RNAtabWidget.setTabEnabled(2, False)NEWLINE NEWLINE self.RNAtabWidget.setTabEnabled(2, True)NEWLINE def on_clicked_nextbuttontoolRNA(self):NEWLINE self.index_warning_rna()NEWLINE self.create_snakefile_rna()NEWLINE self.create_config_rna()NEWLINE self.textBrowser.setTextColor(self._colors['blue'])NEWLINE self.textBrowser.append("Click on the 'Run' button below to start your analysis \n")NEWLINE NEWLINE self.RNAtabWidget.setCurrentIndex(3)NEWLINE self.RNAtabWidget.setTabEnabled(3, True)NEWLINE NEWLINE def param_display_rna(self):NEWLINE _translate = QtCore.QCoreApplication.translateNEWLINE self.StarIndexlabel.setText(_translate("MainWindow", "Index for " + self.AlignercomboBoxRNA.currentText()))NEWLINE self.StarIndexlineEdit.setToolTip(_translate("MainWindow", "Input the path of the Index for" + self.AlignercomboBoxRNA.currentText()))NEWLINE path_aligner_rna = './params/'+self.AlignercomboBoxRNA.currentText()+'.csv'NEWLINE path_em = './params/'+self.EMcomboBoxRNA.currentText()+'.csv'NEWLINE path_de = './params/'+self.DEcomboBoxRNA.currentText()+'.csv'NEWLINENEWLINE dataframe = pd.read_csv(path_aligner_rna, header=0) # specifying that the table has column namesNEWLINE essential = dataframe[dataframe["Essential"] == "yes"]NEWLINE NEWLINE number_of_essential = len(essential) # returns number of essential parametersNEWLINE label_array_param1 = [self.param1_label_rna_1, self.param1_label_rna_2, self.param1_label_rna_3, self.param1_label_rna_4, self.param1_label_rna_5, self.param1_label_rna_6]NEWLINE line_edit_array_param1 = [self.param1_lineEdit_rna_1,self.param1_lineEdit_rna_2, self.param1_lineEdit_rna_3, self.param1_lineEdit_rna_4, self.param1_lineEdit_rna_5, self.param1_lineEdit_rna_6]NEWLINE for i, j, k in zip(range(number_of_essential), label_array_param1, line_edit_array_param1): NEWLINE j.show()NEWLINE j.setText(essential.iloc[i, 2])NEWLINE k.show()NEWLINE k.setText(str(essential.iloc[i, 4]))NEWLINE NEWLINE dataframe_em = pd.read_csv(path_em, header=0) # specifying that the table has column namesNEWLINE essential_em = dataframe_em[dataframe_em["Essential"] == "yes"]NEWLINE NEWLINE number_of_essential_em = len(essential_em) # returns number of essential parametersNEWLINE label_array_param2 = [self.param2_label_rna_1, self.param2_label_rna_2, self.param2_label_rna_3, self.param2_label_rna_4, self.param2_label_rna_5, self.param2_label_rna_6]NEWLINE line_edit_array_param2 = [self.param2_lineEdit_rna_1,self.param2_lineEdit_rna_2, self.param2_lineEdit_rna_3, self.param2_lineEdit_rna_4, self.param2_lineEdit_rna_5, self.param2_lineEdit_rna_6]NEWLINE for i, j, k in zip(range(number_of_essential_em), label_array_param2, line_edit_array_param2): NEWLINE j.show()NEWLINE j.setText(essential_em.iloc[i, 2])NEWLINE k.show()NEWLINE k.setText(str(essential_em.iloc[i, 4]))NEWLINE NEWLINE dataframe_de = pd.read_csv(path_de, header=0) # specifying that the table has column namesNEWLINE essential_de = dataframe_de[dataframe_de["Essential"] == "yes"]NEWLINE NEWLINE number_of_essential_de = len(essential_de) # returns number of essential parametersNEWLINE label_array_param3 = [self.param3_label_rna_1, self.param3_label_rna_2, self.param3_label_rna_3, self.param3_label_rna_4, self.param3_label_rna_5, self.param3_label_rna_6]NEWLINE line_edit_array_param3 = [self.param3_lineEdit_rna_1,self.param3_lineEdit_rna_2, self.param3_lineEdit_rna_3, self.param3_lineEdit_rna_4, self.param3_lineEdit_rna_5, self.param3_lineEdit_rna_6]NEWLINE for i, j, k in zip(range(number_of_essential_de), label_array_param3, line_edit_array_param3): NEWLINE j.show()NEWLINE j.setText(essential_de.iloc[i, 2])NEWLINE k.show()NEWLINE k.setText(str(essential_de.iloc[i, 4]))NEWLINE NEWLINE NEWLINE NEWLINE def index_warning_rna(self):NEWLINE if self.StarIndexlineEdit.text()=='':NEWLINE self.StarIndexErrortext.show()NEWLINE self.StarIndexErrortext.setText("Please input index path!")NEWLINE self.RNAtabWidget.setCurrentIndex(3)NEWLINE self.RNAtabWidget.setTabEnabled(4, False)NEWLINE elif not os.path.exists(self.StarIndexlineEdit.text()):NEWLINE self.StarIndexErrortext.show()NEWLINE self.StarIndexErrortext.setText("File doesn't exist! Please check the path!")NEWLINE self.RNAtabWidget.setCurrentIndex(3)NEWLINE self.RNAtabWidget.setTabEnabled(4, False)NEWLINENEWLINE else:NEWLINE self.RNAtabWidget.setCurrentIndex(4)NEWLINE self.RNAtabWidget.setTabEnabled(4, True)NEWLINENEWLINE def on_clicked_nextbuttonparamsRNA(self):NEWLINENEWLINE NEWLINE self.essential_dict_aligner_rna = self.get_essential(path ='./params/'+self.AlignercomboBoxRNA.currentText()+'.csv', essential_line_edit_array= [self.param1_lineEdit_rna_1,self.param1_lineEdit_rna_2, self.param1_lineEdit_rna_3, self.param1_lineEdit_rna_4, self.param1_lineEdit_rna_5, self.param1_lineEdit_rna_6] )NEWLINE with open('aligner_params_rna.txt', 'w') as aligner_params_rna:NEWLINE aligner_params_rna.write(self.AlignercomboBoxRNA.currentText() + " : '")NEWLINE for k, v in self.essential_dict_aligner_rna.items():NEWLINE aligner_params_rna.write(k +' '+ str(v) + " ")NEWLINE aligner_params_rna.write("'")NEWLINE aligner_params_rna.close()NEWLINE self.essential_dict_em = self.get_essential(path ='./params/'+self.EMcomboBoxRNA.currentText()+'.csv', essential_line_edit_array =[self.param2_lineEdit_rna_1,self.param2_lineEdit_rna_2, self.param2_lineEdit_rna_3, self.param2_lineEdit_rna_4, self.param2_lineEdit_rna_5, self.param2_lineEdit_rna_6])NEWLINE with open('em_params.txt', 'w') as em_params:NEWLINE em_params.write(self.EMcomboBoxRNA.currentText() + " : '")NEWLINE for k, v in self.essential_dict_em.items():NEWLINE em_params.write(k +' '+ str(v) + " ")NEWLINE em_params.write("'")NEWLINE em_params.close()NEWLINE self.essential_dict_de = self.get_essential(path ='./params/'+self.DEcomboBoxRNA.currentText()+'.csv', essential_line_edit_array=[self.param3_lineEdit_rna_1,self.param3_lineEdit_rna_2, self.param3_lineEdit_rna_3, self.param3_lineEdit_rna_4, self.param3_lineEdit_rna_5, self.param3_lineEdit_rna_6] )NEWLINE with open('de_params.txt', 'w') as de_params:NEWLINE de_params.write(self.DEcomboBoxRNA.currentText() + " : '")NEWLINE for k, v in self.essential_dict_de.items():NEWLINE de_params.write(k +' '+ str(v) + " ")NEWLINE de_params.write("'")NEWLINE de_params.close()NEWLINE def on_clicked_previousbuttonqcRNA(self):NEWLINE self.RNAtabWidget.setCurrentIndex(0)NEWLINE self.RNAtabWidget.setTabEnabled(6, True)NEWLINE def on_clicked_previousbuttontoolRNA(self):NEWLINE self.RNAtabWidget.setCurrentIndex(1)NEWLINE self.RNAtabWidget.setTabEnabled(1, True)NEWLINE def on_clicked_previousbuttonindexRNA(self):NEWLINE self.RNAtabWidget.setCurrentIndex(2)NEWLINE self.RNAtabWidget.setTabEnabled(2, True)NEWLINE def on_clicked_previousbuttonparamsRNA(self):NEWLINE self.RNAtabWidget.setCurrentIndex(3)NEWLINE self.RNAtabWidget.setTabEnabled(3, True)NEWLINE NEWLINE def on_clicked_previousbuttonrunRNA(self):NEWLINE self.RNAtabWidget.setCurrentIndex(2) NEWLINE self.RNAtabWidget.setTabEnabled(2, True)NEWLINE NEWLINE def on_clicked_previousbuttonresultRNA(self):NEWLINE self.RNAtabWidget.setCurrentIndex(3) NEWLINE self.RNAtabWidget.setTabEnabled(3, True)NEWLINE NEWLINENEWLINE NEWLINE def show_dag(self):NEWLINE with open("Snakefile", "r+") as snake:NEWLINE line= snake.readline()NEWLINE if '"rules/common_dna.smk"' in line:NEWLINE svg_filename = self.AlignercomboBoxDNA.currentText() + self.VCcomboBoxDNA.currentText() + self.AnnotatorcomboBoxDNA.currentText() + ".svg"NEWLINE else:NEWLINE svg_filename = self.AlignercomboBoxRNA.currentText() + self.EMcomboBoxRNA.currentText() + self.DEcomboBoxRNA.currentText() + ".svg"NEWLINE if os.path.exists(svg_filename):NEWLINE self.diag = SVGDialog(svg_filename)NEWLINE self.diag.show()NEWLINE else:NEWLINE self.textBrowser.setTextColor(self._colors['red'])NEWLINE self.textBrowser.append("Error creating DAG!")NEWLINE NEWLINE NEWLINENEWLINE NEWLINE NEWLINE def advanced_aligner(self):NEWLINE path = './params/'+self.AlignercomboBoxDNA.currentText()+'.csv'NEWLINE self.adv_dialog = AdvancedDialog(path)NEWLINE self.adv_dialog.show()NEWLINE retval = self.adv_dialog.exec_NEWLINE self.adv_dialog.button.accepted.connect(self.close_and_write_aligner)NEWLINE NEWLINE NEWLINE NEWLINE def close_and_write_aligner(self):NEWLINENEWLINE self.snakefile_dict_aligner_int = self.get_additional_int(path='./params/'+self.AlignercomboBoxDNA.currentText()+'.csv')NEWLINE self.snakefile_dict_aligner_float = self.get_additional_float(path='./params/'+self.AlignercomboBoxDNA.currentText()+'.csv')NEWLINE self.snakefile_dict_aligner_str = self.get_additional_str(path='./params/'+self.AlignercomboBoxDNA.currentText()+'.csv')NEWLINE self.snakefile_dict_aligner_na = self.get_additional_na(path='./params/'+self.AlignercomboBoxDNA.currentText()+'.csv')NEWLINE self.essential_dict_aligner = self.get_essential(path ='./params/'+self.AlignercomboBoxDNA.currentText()+'.csv', essential_line_edit_array= [self.param1_lineEdit_dna_1,self.param1_lineEdit_dna_2, self.param1_lineEdit_dna_3, self.param1_lineEdit_dna_4, self.param1_lineEdit_dna_5, self.param1_lineEdit_dna_6])NEWLINE with open('aligner_params.txt', 'w') as aligner_params:NEWLINE aligner_params.write(self.AlignercomboBoxDNA.currentText() + " : '")NEWLINE for k, v in self.snakefile_dict_aligner_int.items():NEWLINE aligner_params.write( k +''+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_aligner_float.items():NEWLINE aligner_params.write( k +''+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_aligner_str.items():NEWLINE aligner_params.write( k +''+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_aligner_na.items():NEWLINE aligner_params.write( k +' ')NEWLINE for k, v in self.essential_dict_aligner.items():NEWLINE aligner_params.write(k +''+ str(v) + " ")NEWLINE aligner_params.write("'")NEWLINE aligner_params.close()NEWLINE NEWLINE self.adv_dialog.close()NEWLINE NEWLINE def advanced_vc(self):NEWLINE path = './params/'+self.VCcomboBoxDNA.currentText()+'.csv'NEWLINE self.adv_dialog = AdvancedDialog(path)NEWLINE self.adv_dialog.show()NEWLINE retval = self.adv_dialog.exec_NEWLINE self.adv_dialog.button.accepted.connect(self.close_and_write_vc)NEWLINE NEWLINE def close_and_write_vc(self):NEWLINENEWLINE self.snakefile_dict_vc_int = self.get_additional_int(path='./params/'+self.VCcomboBoxDNA.currentText()+'.csv')NEWLINE self.snakefile_dict_vc_float = self.get_additional_float(path='./params/'+self.VCcomboBoxDNA.currentText()+'.csv')NEWLINE self.snakefile_dict_vc_str = self.get_additional_str(path='./params/'+self.VCcomboBoxDNA.currentText()+'.csv')NEWLINE self.snakefile_dict_vc_na = self.get_additional_na(path='./params/'+self.VCcomboBoxDNA.currentText()+'.csv')NEWLINE self.essential_dict_vc = self.get_essential(path ='./params/'+self.VCcomboBoxDNA.currentText()+'.csv', essential_line_edit_array= [self.param2_lineEdit_dna_1,self.param2_lineEdit_dna_2, self.param2_lineEdit_dna_3, self.param2_lineEdit_dna_4, self.param2_lineEdit_dna_5, self.param2_lineEdit_dna_6])NEWLINE with open('vc_params.txt', 'w') as vc_params:NEWLINE vc_params.write(self.VCcomboBoxDNA.currentText() + " : '")NEWLINE for k, v in self.snakefile_dict_vc_int.items():NEWLINE vc_params.write( k +''+ str(v) +" " )NEWLINE for k,v in self.snakefile_dict_vc_float.items():NEWLINE vc_params.write( k +''+ str(v) +" " )NEWLINE for k,v in self.snakefile_dict_vc_str.items():NEWLINE vc_params.write( k +''+ str(v) +" " )NEWLINE for k,v in self.snakefile_dict_vc_na.items():NEWLINE vc_params.write( k +' ')NEWLINE for k, v in self.essential_dict_vc.items():NEWLINE vc_params.write(k +''+ str(v) + " ")NEWLINE vc_params.write("'")NEWLINE vc_params.close()NEWLINE NEWLINE self.adv_dialog.close()NEWLINE NEWLINE def advanced_annotator(self):NEWLINE path = './params/'+self.AnnotatorcomboBoxDNA.currentText()+'.csv'NEWLINE self.adv_dialog = AdvancedDialog(path)NEWLINE self.adv_dialog.show()NEWLINE retval = self.adv_dialog.exec_NEWLINE self.adv_dialog.button.accepted.connect(self.close_and_write_annotator)NEWLINE NEWLINE def close_and_write_annotator(self):NEWLINENEWLINE self.snakefile_dict_annotator_int = self.get_additional_int(path='./params/'+self.AnnotatorcomboBoxDNA.currentText()+'.csv')NEWLINE self.snakefile_dict_annotator_float = self.get_additional_float(path='./params/'+self.AnnotatorcomboBoxDNA.currentText()+'.csv')NEWLINE self.snakefile_dict_annotator_str = self.get_additional_str(path='./params/'+self.AnnotatorcomboBoxDNA.currentText()+'.csv')NEWLINE self.snakefile_dict_annotator_na = self.get_additional_na(path='./params/'+self.AnnotatorcomboBoxDNA.currentText()+'.csv')NEWLINE self.essential_dict_annotator = self.get_essential(path ='./params/'+self.AnnotatorcomboBoxDNA.currentText()+'.csv', essential_line_edit_array= [self.param3_lineEdit_dna_1,self.param3_lineEdit_dna_2, self.param3_lineEdit_dna_3, self.param3_lineEdit_dna_4, self.param3_lineEdit_dna_5, self.param3_lineEdit_dna_6])NEWLINE with open('annotator_params.txt', 'w') as annotator_params:NEWLINE if self.AnnotatorcomboBoxDNA.currentText() == "SnpEff":NEWLINE annotator_params.write(self.AnnotatorcomboBoxDNA.currentText() + " : '-Xmx4g ")NEWLINE else:NEWLINE annotator_params.write(self.AnnotatorcomboBoxDNA.currentText() + " : '")NEWLINE for k, v in self.snakefile_dict_annotator_int.items():NEWLINE annotator_params.write( k +' '+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_annotator_float.items():NEWLINE annotator_params.write( k +' '+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_annotator_str.items():NEWLINE annotator_params.write( k +' '+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_annotator_na.items():NEWLINE annotator_params.write( k +' ' )NEWLINE for k, v in self.essential_dict_annotator.items():NEWLINE annotator_params.write(k +''+ str(v) + " ")NEWLINE annotator_params.write("'")NEWLINE annotator_params.close()NEWLINE NEWLINE self.adv_dialog.close()NEWLINE NEWLINE def advanced_aligner_rna(self):NEWLINE path = './params/'+self.AlignercomboBoxRNA.currentText()+'.csv'NEWLINE self.adv_dialog = AdvancedDialog(path)NEWLINE self.adv_dialog.show()NEWLINE retval = self.adv_dialog.exec_NEWLINE self.adv_dialog.button.accepted.connect(self.close_and_write_aligner_rna)NEWLINE NEWLINE def close_and_write_aligner_rna(self):NEWLINENEWLINE self.snakefile_dict_aligner_rna_int = self.get_additional_int(path='./params/'+self.AlignercomboBoxRNA.currentText()+'.csv')NEWLINE self.snakefile_dict_aligner_rna_float = self.get_additional_float(path='./params/'+self.AlignercomboBoxRNA.currentText()+'.csv')NEWLINE self.snakefile_dict_aligner_rna_str = self.get_additional_str(path='./params/'+self.AlignercomboBoxRNA.currentText()+'.csv')NEWLINE self.snakefile_dict_aligner_rna_na = self.get_additional_na(path='./params/'+self.AlignercomboBoxRNA.currentText()+'.csv')NEWLINE self.essential_dict_aligner_rna = self.get_essential(path ='./params/'+self.AlignercomboBoxRNA.currentText()+'.csv', essential_line_edit_array= [self.param1_lineEdit_rna_1,self.param1_lineEdit_rna_2, self.param1_lineEdit_rna_3, self.param1_lineEdit_rna_4, self.param1_lineEdit_rna_5, self.param1_lineEdit_rna_6])NEWLINE with open('aligner_params_rna.txt', 'w') as aligner_params_rna:NEWLINE aligner_params_rna.write(self.AlignercomboBoxRNA.currentText() + " : '")NEWLINE for k, v in self.snakefile_dict_aligner_rna_int.items():NEWLINE aligner_params_rna.write( k +''+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_aligner_rna_float.items():NEWLINE aligner_params_rna.write( k +''+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_aligner_rna_str.items():NEWLINE aligner_params_rna.write( k +''+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_aligner_rna_na.items():NEWLINE aligner_params_rna.write( k +' ')NEWLINE for k, v in self.essential_dict_aligner_rna.items():NEWLINE aligner_params_rna.write(k +''+ str(v) + " ")NEWLINE aligner_params_rna.write("'")NEWLINE aligner_params_rna.close()NEWLINE NEWLINENEWLINE NEWLINE self.adv_dialog.close()NEWLINE NEWLINE def advanced_em(self):NEWLINE path = './params/'+self.EMcomboBoxRNA.currentText()+'.csv'NEWLINE self.adv_dialog = AdvancedDialog(path)NEWLINE self.adv_dialog.show()NEWLINE retval = self.adv_dialog.exec_NEWLINE self.adv_dialog.button.accepted.connect(self.close_and_write_em)NEWLINE NEWLINE def close_and_write_em(self):NEWLINENEWLINE self.snakefile_dict_em_int = self.get_additional_int(path='./params/'+self.EMcomboBoxRNA.currentText()+'.csv')NEWLINE self.snakefile_dict_em_float = self.get_additional_float(path='./params/'+self.EMcomboBoxRNA.currentText()+'.csv')NEWLINE self.snakefile_dict_em_str = self.get_additional_str(path='./params/'+self.EMcomboBoxRNA.currentText()+'.csv')NEWLINE self.snakefile_dict_em_na = self.get_additional_na(path='./params/'+self.EMcomboBoxRNA.currentText()+'.csv')NEWLINE self.essential_dict_em = self.get_essential(path ='./params/'+self.EMcomboBoxRNA.currentText()+'.csv', essential_line_edit_array= [self.param2_lineEdit_rna_1,self.param2_lineEdit_rna_2, self.param2_lineEdit_rna_3, self.param2_lineEdit_rna_4, self.param2_lineEdit_rna_5, self.param2_lineEdit_rna_6])NEWLINE with open('em_params.txt', 'w') as em_params:NEWLINE em_params.write(self.EMcomboBoxRNA.currentText() + " : '")NEWLINE for k, v in self.snakefile_dict_em_int.items():NEWLINE em_params.write( k +''+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_em_float.items():NEWLINE em_params.write( k +''+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_em_str.items():NEWLINE em_params.write( k +''+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_em_na.items():NEWLINE em_params.write( k +' ')NEWLINE for k, v in self.essential_dict_em.items():NEWLINE em_params.write(k +''+ str(v) + " ")NEWLINE em_params.write("'")NEWLINE em_params.close()NEWLINE NEWLINE self.adv_dialog.close()NEWLINE NEWLINE def advanced_de(self):NEWLINE path = './params/'+self.DEcomboBoxRNA.currentText()+'.csv'NEWLINE self.adv_dialog = AdvancedDialog(path)NEWLINE self.adv_dialog.show()NEWLINE retval = self.adv_dialog.exec_NEWLINE self.adv_dialog.button.accepted.connect(self.close_and_write_de)NEWLINE NEWLINE def close_and_write_de(self):NEWLINENEWLINE self.snakefile_dict_de_int = self.get_additional_int(path='./params/'+self.DEcomboBoxRNA.currentText()+'.csv')NEWLINE self.snakefile_dict_de_float = self.get_additional_float(path='./params/'+self.DEcomboBoxRNA.currentText()+'.csv')NEWLINE self.snakefile_dict_de_str = self.get_additional_str(path='./params/'+self.DEcomboBoxRNA.currentText()+'.csv')NEWLINE self.snakefile_dict_de_na = self.get_additional_na(path='./params/'+self.DEcomboBoxRNA.currentText()+'.csv')NEWLINE self.essential_dict_de = self.get_essential(path ='./params/'+self.DEcomboBoxRNA.currentText()+'.csv', essential_line_edit_array= [self.param3_lineEdit_rna_1,self.param3_lineEdit_rna_2, self.param3_lineEdit_rna_3, self.param3_lineEdit_rna_4, self.param3_lineEdit_rna_5, self.param3_lineEdit_rna_6])NEWLINE with open('de_params.txt', 'w') as de_params:NEWLINE de_params.write(self.DEcomboBoxRNA.currentText() + " : '")NEWLINE for k, v in self.snakefile_dict_de_int.items():NEWLINE de_params.write( k +''+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_de_float.items():NEWLINE de_params.write( k +''+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_de_str.items():NEWLINE de_params.write( k +''+ str(v) +" " )NEWLINE for k, v in self.snakefile_dict_de_na.items():NEWLINE de_params.write( k +' ')NEWLINE for k, v in self.essential_dict_de.items():NEWLINE de_params.write(k +''+ str(v) + " ")NEWLINE de_params.write("'")NEWLINE de_params.close()NEWLINE NEWLINE self.adv_dialog.close()NEWLINE NEWLINE def check_run_button(self):NEWLINE if self.one_passed == self.two_passed is True:NEWLINE self.RunButton.setEnabled(True)NEWLINE self.RunLabel.setEnabled(True)NEWLINE NEWLINENEWLINE def on_check_SamplesNo_dna(self,is_toggle):NEWLINE if is_toggle:NEWLINE self.UnitsFilelabelDNA.setEnabled(True)NEWLINE self.UnitslineEditDNA.setEnabled(True)NEWLINE self.UnitsBrowseButtonDNA.setEnabled(True)NEWLINE self.SampleFilelabelDNA.setEnabled(False)NEWLINE self.SampleslineEditDNA.setEnabled(False)NEWLINE self.SamplesBrowseButtonDNA.setEnabled(False)NEWLINE else:NEWLINE self.UnitsFilelabelDNA.setEnabled(False)NEWLINE self.UnitslineEditDNA.setEnabled(False)NEWLINE self.UnitsBrowseButtonDNA.setEnabled(False)NEWLINE self.SampleFilelabelDNA.setEnabled(True)NEWLINE self.SampleslineEditDNA.setEnabled(True)NEWLINE self.SamplesBrowseButtonDNA.setEnabled(True)NEWLINE NEWLINE def on_check_SamplesNo_rna(self,is_toggle):NEWLINE if is_toggle:NEWLINE self.Sampletablelabel.setEnabled(True)NEWLINE self.SampletablelineEdit.setEnabled(True)NEWLINE self.SampletableBrowseButton.setEnabled(True)NEWLINE#==============================================================================NEWLINE self.SampleFolderlabel.setEnabled(False)NEWLINE self.SampleFolderLineEdit.setEnabled(False)NEWLINE self.SampleFolderBrowseButton.setEnabled(False)NEWLINE#==============================================================================NEWLINE else:NEWLINE self.Sampletablelabel.setEnabled(False)NEWLINE self.SampletablelineEdit.setEnabled(False)NEWLINE self.SampletableBrowseButton.setEnabled(False)NEWLINE#==============================================================================NEWLINE self.SampleFolderlabel.setEnabled(True)NEWLINE self.SampleFolderLineEdit.setEnabled(True)NEWLINE self.SampleFolderBrowseButton.setEnabled(True)NEWLINE#==============================================================================NEWLINENEWLINE def on_check_QC_dna(self,is_toggle):NEWLINE if is_toggle:NEWLINE self.InputParamslabel.setEnabled(True)NEWLINE self.Cutadaptlabel.setEnabled(True)NEWLINE self.CutadaptlineEdit.setEnabled(True)NEWLINE self.RunQCpushButton.setEnabled(True)NEWLINE else:NEWLINE self.InputParamslabel.setEnabled(False)NEWLINE self.Cutadaptlabel.setEnabled(False)NEWLINE self.CutadaptlineEdit.setEnabled(False)NEWLINE self.RunQCpushButton.setEnabled(False)NEWLINENEWLINE def on_check_QC_rna(self,is_toggle):NEWLINE if is_toggle:NEWLINE self.InputParamslabel_rna.setEnabled(True)NEWLINE self.Cutadaptlabel_rna.setEnabled(True) NEWLINE self.CutadaptlineEdit_rna.setEnabled(True)NEWLINE self.RunQCpushButton_rna.setEnabled(True)NEWLINE else:NEWLINE self.InputParamslabel_rna.setEnabled(False)NEWLINE self.Cutadaptlabel_rna.setEnabled(False)NEWLINE self.CutadaptlineEdit_rna.setEnabled(False)NEWLINENEWLINE self.RunQCpushButton_rna.setEnabled(False)NEWLINENEWLINENEWLINE def browse_data_sampletable(self):NEWLINE if os.path.exists('rename_check.txt'):NEWLINE os.remove('rename_check.txt')NEWLINE else:NEWLINE passNEWLINE self.SampletableErrortextRNA.hide()NEWLINE data_path_sampletable, _ =QtWidgets.QFileDialog.getOpenFileName(None,'Open File',r"",'*.tsv')NEWLINE self.SampletablelineEdit.setText(data_path_sampletable)NEWLINE with open('data_path_sampletable.pickle', 'wb') as handle:NEWLINE pickle.dump(data_path_sampletable,handle,protocol=pickle.HIGHEST_PROTOCOL)NEWLINENEWLINE def browse_data_fasta(self):NEWLINE self.FastaErrortextRNA.hide()NEWLINE data_path_fasta, _ =QtWidgets.QFileDialog.getOpenFileName(None,'Open File',r"",'*.fa *.fa.gz')NEWLINE self.FastalineEdit.setText(data_path_fasta)NEWLINE with open('data_path_fasta.pickle', 'wb') as handle:NEWLINE pickle.dump(data_path_fasta,handle,protocol=pickle.HIGHEST_PROTOCOL)NEWLINENEWLINE def browse_data_annotated(self):NEWLINE self.AnnotatedErrortextRNA.hide()NEWLINE data_path_annotated, _ =QtWidgets.QFileDialog.getOpenFileName(None,'Open File',r"",'*.gtf *.gtf.gz')NEWLINE self.AnnotatedlineEditRNA.setText(data_path_annotated)NEWLINE with open('data_path_annotated.pickle', 'wb') as handle:NEWLINE pickle.dump(data_path_annotated,handle,protocol=pickle.HIGHEST_PROTOCOL)NEWLINENEWLINENEWLINE NEWLINE def browse_samples_folder(self):NEWLINE self.SampleFolderErrortextRNA.hide()NEWLINE if os.path.exists("name_check.txt"):NEWLINE os.remove("name_check.txt")NEWLINE else:NEWLINE passNEWLINE my_dir_sample = QtWidgets.QFileDialog.getExistingDirectory(NEWLINE None,NEWLINE "Open a folder")NEWLINE self.SampleFolderLineEdit.setText(my_dir_sample)NEWLINE NEWLINENEWLINE def browse_data_samples(self):NEWLINENEWLINE self.SamplesErrortextDNA.hide()NEWLINE if os.path.exists("name_check.txt"):NEWLINE os.remove("name_check.txt")NEWLINE else:NEWLINE passNEWLINE my_dir_sample = QtWidgets.QFileDialog.getExistingDirectory(NEWLINE None,NEWLINE "Open a folder")NEWLINE self.SampleslineEditDNA.setText(my_dir_sample)NEWLINENEWLINE def browse_data_units(self):NEWLINE self.UnitsErrortextDNA.hide()NEWLINE data_path_units, _ =QtWidgets.QFileDialog.getOpenFileName(None,'Open File',r"",'*.tsv')NEWLINE self.UnitslineEditDNA.setText(data_path_units)NEWLINE with open('data_path_units.pickle', 'wb') as handle:NEWLINE pickle.dump(data_path_units,handle,protocol=pickle.HIGHEST_PROTOCOL)NEWLINENEWLINENEWLINE NEWLINE def browse_data_ref(self):NEWLINENEWLINE self.RefGenomeErrortextDNA.hide()NEWLINE data_path_ref, _ =QtWidgets.QFileDialog.getOpenFileName(None,'Open File',r"",'*.fa *.fa.gz')NEWLINE self.RefGenomelineEditDNA.setText(data_path_ref)NEWLINE with open('data_path_ref.pickle', 'wb') as handle:NEWLINE pickle.dump(data_path_ref,handle,protocol=pickle.HIGHEST_PROTOCOL)NEWLINENEWLINE def browse_data_kv(self):NEWLINE self.RefVariantErrortextDNA.hide()NEWLINE data_path_kv, _ =QtWidgets.QFileDialog.getOpenFileName(None,'Open File',r"",'*.gz')NEWLINE self.RefVariantlineEditDNA.setText(data_path_kv)NEWLINE with open('data_path_kv.pickle', 'wb') as handle:NEWLINE pickle.dump(data_path_kv,handle,protocol=pickle.HIGHEST_PROTOCOL)NEWLINENEWLINE def browse_bwaindex_dna(self):NEWLINE self.BWAIndexErrortext.hide()NEWLINE self._set_color(self._colors['blue'].name(),pb =self.progressBar_sub2_dna)NEWLINE data_path_bwadna, _ =QtWidgets.QFileDialog.getOpenFileName(None,'Open File')NEWLINE self.BWAIndexlineEdit.setText(data_path_bwadna)NEWLINE with open('data_path_bwadna.pickle', 'wb') as handle:NEWLINE pickle.dump(data_path_bwadna,handle,protocol=pickle.HIGHEST_PROTOCOL)NEWLINENEWLINENEWLINE def browse_data_maf(self):NEWLINE data_path_maf, _ =QtWidgets.QFileDialog.getOpenFileName(None,'Open File',r"",'*.maf *.maf.gz')NEWLINE self.maflineEdit.setText(data_path_maf)NEWLINE with open('data_path_maf.pickle', 'wb') as handle:NEWLINE pickle.dump(data_path_maf,handle,protocol=pickle.HIGHEST_PROTOCOL)NEWLINENEWLINE def browse_data_vcf(self):NEWLINE data_path_vcf, _ =QtWidgets.QFileDialog.getOpenFileName(None,'Open File','./NBDriver_ICOMIC/vcf/','*.vcf *.vcf.gz')NEWLINE self.vcflineEdit.setText(data_path_vcf)NEWLINE with open('data_path_vcf.pickle', 'wb') as handle:NEWLINE pickle.dump(data_path_vcf,handle,protocol=pickle.HIGHEST_PROTOCOL)NEWLINENEWLINE def browse_star_rna(self):NEWLINE self.StarIndexErrortext.hide()NEWLINE self._set_color(self._colors['blue'].name(),pb =self.progressBar_sub2_rna)NEWLINE my_dir_star = QtWidgets.QFileDialog.getExistingDirectory(NEWLINE None,NEWLINE "Open a folder")NEWLINE self.StarIndexlineEdit.setText(my_dir_star)NEWLINENEWLINENEWLINE NEWLINE def _set_color(self, color, pb):NEWLINE pb.setStyleSheet("""NEWLINE QProgressBar {{NEWLINE color: black;NEWLINE border: 2px solid grey;NEWLINE margin: 2px;NEWLINE border-radius: 5px;NEWLINE text-align: center;NEWLINE }}NEWLINE QProgressBar::chunk {{NEWLINE background: {};NEWLINE }}""".format(color))NEWLINE def _set_pb_color_sub(self, color, pb):NEWLINE self._set_color(self, color, pb )NEWLINE def _set_pb2_color_dna(self, color):NEWLINE self._set_color(self, color, pb = self.progressBar_sub2_dna)NEWLINE def _set_pb1_color_rna(self, color):NEWLINE self._set_color(self, color, pb=self.progressBar_sub1_rna)NEWLINE def _set_pb2_color_rna(self, color):NEWLINE self._set_color(self, color, pb=self.progressBar_sub2_rna)NEWLINE NEWLINE def func_pb_update(self, sub_pb, sub_pb_frac, initial_sub, initial_main, error_icon):NEWLINE time.sleep(2)NEWLINE files = glob.glob('.snakemake/log/*.log')NEWLINE filename_=max(files , key = os.path.getctime)NEWLINE f = open(filename_, 'r')NEWLINE while True:NEWLINE line = ''NEWLINE while len(line) == 0 or line[-1] != '\n':NEWLINE tail = f.readline()NEWLINE if tail == '':NEWLINE breakNEWLINE line += tailNEWLINE self.textBrowser.append(line)NEWLINE if '%' in line:NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE per = line.split('(', 1)[1].split(')')[0]NEWLINE percent = per[:-1]NEWLINE sub_pb.setValue(initial_sub + int(percent)/sub_pb_frac)NEWLINE elif 'Error: Directory cannot be locked' in line:NEWLINE self._set_color(self._colors['red'].name(),pb =sub_pb)NEWLINE self.textBrowser.setTextColor(self._colors['red'])NEWLINE self.textBrowser.append(line)NEWLINE breakNEWLINE subprocess.run(["snakemake", "--unlock"])NEWLINENEWLINE elif 'CalledProcessError' in line:NEWLINE self._set_color(self._colors['red'].name(),pb =sub_pb)NEWLINE self.textBrowser.setTextColor(self._colors['red'])NEWLINE breakNEWLINE elif 'WorkflowError' in line:NEWLINE self._set_color(self._colors['red'].name(),pb =sub_pb)NEWLINE self.textBrowser.setTextColor(self._colors['red'])NEWLINE breakNEWLINE elif 'Error' in line:NEWLINE self._set_color(self._colors['red'].name(),pb =sub_pb)NEWLINE self.textBrowser.setTextColor(self._colors['red'])NEWLINE breakNEWLINE elif 'Missing' in line:NEWLINE print(line)NEWLINE self._set_color(self._colors['red'].name(),pb =sub_pb)NEWLINE self.textBrowser.setTextColor(self._colors['red'])NEWLINE error_icon.show()NEWLINE error_icon.setToolTip("Missing input file! Check the inputs")NEWLINE breakNEWLINE elif '(100%) done' in line:NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE sub_pb.setValue(initial_sub + 100/sub_pb_frac)NEWLINE elif 'Nothing to be done' in line:NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE sub_pb.setValue(initial_sub + 100/sub_pb_frac)NEWLINE breakNEWLINE else:NEWLINE passNEWLINE if ('Complete log' in line):NEWLINE breakNEWLINE elif 'Missing' in line:NEWLINE self._set_color(self._colors['red'].name(),pb =sub_pb)NEWLINE breakNEWLINE elif 'Exiting' in line:NEWLINE self._set_color(self._colors['red'].name(),pb =sub_pb)NEWLINE breakNEWLINE NEWLINE def show_qc_textbox(self):NEWLINE subprocess.run(["snakemake", "--unlock", "-j", "1"])NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("QC Results being generated. Please wait! \n")NEWLINENEWLINE def show_qc_results(self):NEWLINE self.progressBar_sub1_dna.setValue(1)NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.nextbuttonqcDNA.setEnabled(True)NEWLINE self._set_color(self._colors['blue'].name(),pb =self.progressBar_sub1_dna)NEWLINE conf = open('config.yaml', 'w')NEWLINE conf.write('samples: samples.tsv \n')NEWLINE conf.write('units: '+ self.UnitslineEditDNA.text() + '\n'+'ref: \n')NEWLINE conf.write(' genome: '+ self.RefGenomelineEditDNA.text() + '\n')NEWLINE conf.write("processing: \n")NEWLINE conf.write(" remove-duplicates: true\n")NEWLINE conf.write('threads: ' + self.CorelineEditDNA.text() + '\n')NEWLINE conf.close()NEWLINE time.sleep(0.1)NEWLINENEWLINE NEWLINE snake = open('Snakefile', "w")NEWLINE snake.write('include: "rules/common_dna.smk"\n')NEWLINE snake.write('rule all:\n')NEWLINE snake.write(' input:\n')NEWLINE snake.write(' expand("results_dna/qc/fastqc/{u.sample}-{u.unit}-{u.condition}.html", u = units.itertuples()),\n')NEWLINE snake.write(' expand("results_dna/qc/fastqc/{u.sample}-{u.unit}-{u.condition}.zip", u = units.itertuples()),\n')NEWLINE snake.write('include: "rules/qc_dna.smk"\n')NEWLINE snake.close()NEWLINE NEWLINENEWLINE NEWLINE NEWLINE def func_qc():NEWLINE subprocess.run(["snakemake", "--use-conda", "--cores", self.CorelineEditDNA.text()])NEWLINE NEWLINE def multi_qc():NEWLINE subprocess.run(["snakemake", "--use-conda", "-s", "Snakefile_multiqc", "--cores", self.CorelineEditDNA.text()])NEWLINENEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE p1 = Process(target=func_qc)NEWLINE p1.start()NEWLINE NEWLINE p2 = Process(target=self.func_pb_update( sub_pb=self.progressBar_sub1_dna, sub_pb_frac=4, initial_sub = 0, initial_main=0, error_icon=self.QCresultsButtonErroricon))NEWLINE p2.start()NEWLINE NEWLINE if self.progressBar_sub1_dna.value()==100/4:NEWLINE p3 = Process(target=multi_qc)NEWLINE self.progressBar_sub1_dna.setValue(26)NEWLINE NEWLINE p3.start()NEWLINE NEWLINE p4 = Process(target= self.func_pb_update( sub_pb=self.progressBar_sub1_dna, sub_pb_frac=4, initial_sub = 25, initial_main=0, error_icon=self.QCresultsButtonErroricon))NEWLINE p4.start()NEWLINE NEWLINE if os.path.exists("results_dna/qc/multiqc.html"):NEWLINE self.textBrowser.setTextColor(self._colors['blue'])NEWLINE self.textBrowser.append("MultiQC results generated! Wait till the result is dispalyed and then proceed to the next tab \n\n")NEWLINE filename = "results_dna/qc/multiqc.html"NEWLINE webbrowser.get('google-chrome').open(filename, new=0, autoraise=True)NEWLINE else:NEWLINE passNEWLINENEWLINENEWLINE def show_qc_results_rna(self):NEWLINE self.progressBar_sub1_rna.setValue(1)NEWLINE self.nextbuttonqcRNA.setEnabled(True)NEWLINE self._set_color(self._colors['blue'].name(),pb =self.progressBar_sub1_rna)NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("QC Results being generated. Please wait! \n")NEWLINE time.sleep(0.1)NEWLINE conf = open('config.yaml', 'w')NEWLINE conf.write('units: units.tsv \n')NEWLINE conf.write('ref: \n')NEWLINE conf.write(' annotation: '+ self.AnnotatedlineEditRNA.text() + '\n')NEWLINE conf.write(' fasta: '+self.FastalineEdit.text() + '\n')NEWLINE conf.write('params: \n')NEWLINE conf.write("sample: " + self.SampleFolderLineEdit.text() + "\n")NEWLINE conf.write('threads: ' + self.CorelineEditRNA.text() + '\n')NEWLINE conf.close()NEWLINE time.sleep(0.1)NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Snakefile created for Quality Check!! \nPlease refer to the file: Snakefile in your working directory. \n\n")NEWLINE snakef = open('Snakefile', "w")NEWLINE snakef.write('include: "rules/common_rna.smk"\n')NEWLINE snakef.write('rule all:\n')NEWLINE snakef.write(' input:\n')NEWLINE snakef.write(" expand('results/fastqc/{sample}_{condition}_Rep{rep}.html', sample=samples, condition=type, rep=reps),\n")NEWLINE snakef.write(" expand('results/fastqc/{sample}_{condition}_Rep{rep}.zip', sample=samples, condition=type, rep=reps),\n")NEWLINE snakef.write('include: "rules/qc_rna.smk"\n')NEWLINE snakef.close()NEWLINE NEWLINE time.sleep(0.1)NEWLINE NEWLINE def func_qc():NEWLINE process1 = subprocess.Popen(["snakemake", "--use-conda", "--cores", self.CorelineEditRNA.text()], shell =True, stdout=subprocess.PIPE)NEWLINE output1 = process1.communicate()NEWLINENEWLINE def multi_qc():NEWLINE subprocess.run(["snakemake", "--use-conda", "-s", "Snakefile_multiqc_rna", "--cores", self.CorelineEditRNA.text()])NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE p1 = Process(target=func_qc)NEWLINE p1.start()NEWLINE NEWLINE p2 = Process(target=self.func_pb_update( sub_pb=self.progressBar_sub1_rna, sub_pb_frac=4, initial_sub = 0, initial_main=0, error_icon=self.QCresultsButtonErroricon_rna))NEWLINE p2.start()NEWLINE NEWLINE if self.progressBar_sub1_rna.value()==100/4:NEWLINE p3 = Process(target=multi_qc)NEWLINE self.progressBar_sub1_rna.setValue(26)NEWLINE p3.start()NEWLINE NEWLINE p4 = Process(target= self.func_pb_update( sub_pb=self.progressBar_sub1_rna, sub_pb_frac=4, initial_sub = 25, initial_main=0, error_icon=self.QCresultsButtonErroricon_rna))NEWLINE p4.start()NEWLINE else:NEWLINE passNEWLINE NEWLINE if os.path.exists("results/fastqc/multiqc.html"):NEWLINE self.textBrowser.setTextColor(self._colors['blue'])NEWLINE self.textBrowser.append("MultiQC results generated! Proceed to the next tab \n\n")NEWLINE filename = "results/fastqc/multiqc.html"NEWLINE webbrowser.get('google-chrome').open(filename, new=0, autoraise=True)NEWLINE else:NEWLINE passNEWLINENEWLINE def run_qc_textbox(self):NEWLINE subprocess.run(["snakemake", "--unlock", "-j", "1"])NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Running Quality Check!! \n\n") NEWLINE NEWLINE NEWLINE def run_qc_dna(self, line):NEWLINE self.progressBar_sub1_dna.setValue(51)NEWLINE self._set_color(self._colors['blue'].name(),pb =self.progressBar_sub1_dna)NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Config file created for Quality Check!! \nPlease refer to the file: config.yaml in your working directory. \n\n")NEWLINE conf = open('config.yaml', 'w')NEWLINE conf.write('samples: ./samples.tsv \n')NEWLINE conf.write('units: '+ self.UnitslineEditDNA.text() + '\n'+'ref: \n')NEWLINE conf.write(" name: " + self.RefNamecomboBoxDNA.currentText() + "\n")NEWLINE conf.write(' genome: '+ self.RefGenomelineEditDNA.text() + '\n')NEWLINE conf.write(' genome-name: '+ os.path.basename(self.RefGenomelineEditDNA.text()) + '\n')NEWLINE conf.write(' known-variants: '+ self.RefVariantlineEditDNA.text() + '\n')NEWLINE conf.write("processing: \n")NEWLINE conf.write(" remove-duplicates: true\n")NEWLINE conf.write('threads: ' + self.CorelineEditDNA.text() + '\n')NEWLINE conf.write('params: \n')NEWLINE conf.write(" cutadapt: '" + self.CutadaptlineEdit.text() + "' \n")NEWLINE conf.close()NEWLINE NEWLINE time.sleep(0.1)NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Snakefile created for Quality Check!! \nPlease refer to the file: Snakefile in your working directory. \n\n")NEWLINE snake = open('Snakefile', "w")NEWLINE snake.write('include: "rules/common_dna.smk"\n')NEWLINE snake.write('rule all:\n')NEWLINE snake.write(' input:\n')NEWLINE snake.write(' expand("results_dna/trimmed/fastqc_after/{u.sample}-{u.unit}-{u.condition}.aftertrim.html", u = units.itertuples()),\n')NEWLINE snake.write(' expand("results_dna/trimmed/fastqc_after/{u.sample}-{u.unit}-{u.condition}.aftertrim.zip", u = units.itertuples()) \n')NEWLINE snake.write('include: "rules/cutadapt_dna.smk"\n')NEWLINE snake.write('include: "rules/fastqc_after_dna.smk"\n')NEWLINE snake.close()NEWLINE NEWLINE time.sleep(0.1)NEWLINE NEWLINE def func1():NEWLINE NEWLINE process1 = subprocess.run(["snakemake", "--use-conda", "--cores", self.CorelineEditDNA.text()])NEWLINE p1 = Process(target=func1)NEWLINE p1.start()NEWLINE p2 = Process(target=self.func_pb_update( sub_pb=self.progressBar_sub1_dna, sub_pb_frac=4, initial_sub = 50, initial_main=0, error_icon=self.RunQCButtonErroricon))NEWLINE p2.start()NEWLINE NEWLINE def multi_qc():NEWLINE subprocess.run(["snakemake", "--use-conda", "-s", "Snakefile_after", "--cores", self.CorelineEditDNA.text()])NEWLINE NEWLINE if self.progressBar_sub1_dna.value()==75:NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Running Quality Check!! \n\n")NEWLINE p3 = Process(target=multi_qc)NEWLINE self.progressBar_sub1_dna.setValue(76)NEWLINE p3.start()NEWLINE NEWLINE p4 = Process(target= self.func_pb_update( sub_pb=self.progressBar_sub1_dna, sub_pb_frac=4, initial_sub = 75, initial_main=0, error_icon=self.QCresultsButtonErroricon))NEWLINE p4.start()NEWLINE else:NEWLINE passNEWLINE NEWLINE if os.path.exists("results_dna/qc/multiqc_after.html"):NEWLINE filename = "results_dna/qc/multiqc_after.html"NEWLINE webbrowser.get('google-chrome').open(filename, new=0, autoraise=True)NEWLINE else:NEWLINE passNEWLINE NEWLINE NEWLINENEWLINE def run_qc_rna_textbox(self):NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Running Quality Check!! \n\n")NEWLINE subprocess.run(["snakemake", "--unlock", "-j", "1"])NEWLINENEWLINE def run_qc_rna(self, line):NEWLINE self.progressBar_sub1_rna.setValue(51)NEWLINE self._set_color(self._colors['blue'].name(),pb =self.progressBar_sub1_rna)NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Config file created for Quality Check!! \nPlease refer to the file: config.yaml in your working directory. \n\n")NEWLINE conf = open('config.yaml', 'w')NEWLINE conf.write('units: units.tsv \n')NEWLINE conf.write('ref: \n')NEWLINE conf.write(' annotation: '+ self.AnnotatedlineEditRNA.text() + '\n')NEWLINE conf.write(' fasta: '+self.FastalineEdit.text() + '\n')NEWLINE conf.write('threads: ' + self.CorelineEditRNA.text() + '\n')NEWLINE conf.write('params: \n')NEWLINE conf.write(" cutadapt: '" + self.CutadaptlineEdit_rna.text() + "' \n")NEWLINE conf.write("sample: " + self.SampleFolderLineEdit.text() + "\n")NEWLINE conf.close()NEWLINE time.sleep(0.1)NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Snakefile created for Quality Check!! \nPlease refer to the file: Snakefile in your working directory. \n\n")NEWLINE snakef = open('Snakefile', "w")NEWLINE snakef.write('include: "rules/common_rna.smk"\n')NEWLINE snakef.write('rule all:\n')NEWLINE snakef.write(' input:\n')NEWLINE snakef.write(" expand('results/cutadapt/fastqc_after/{sample}_{condition}_Rep{rep}.aftertrim.html', sample=samples, condition=type, rep=reps),\n")NEWLINE snakef.write(" expand('results/cutadapt/fastqc_after/{sample}_{condition}_Rep{rep}.aftertrim.zip', sample=samples, condition=type, rep=reps),\n")NEWLINE snakef.write('include: "rules/cutadapt_rna.smk"\n')NEWLINE snakef.write('include: "rules/fastqc_after_rna.smk"\n')NEWLINE snakef.close()NEWLINE time.sleep(0.1)NEWLINE def func_qc_rna():NEWLINE NEWLINE process2 = subprocess.run(["snakemake", "--use-conda", "--cores", self.CorelineEditRNA.text()])NEWLINE output2 = process2.communicate()NEWLINE NEWLINE p1 = Process(target=func_qc_rna)NEWLINE p1.start()NEWLINE p2 = Process(target=self.func_pb_update( sub_pb=self.progressBar_sub1_rna, sub_pb_frac=4, initial_sub = 50, initial_main=0, error_icon=self.RunQCButtonErroricon_rna))NEWLINE p2.start() NEWLINE NEWLINE def multi_qc_rna():NEWLINE subprocess.run(["snakemake", "--use-conda", "-s", "Snakefile_after_rna", "--cores", self.CorelineEditRNA.text()])NEWLINE NEWLINE if self.progressBar_sub1_rna.value()==75:NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Running Quality Check!! \n\n")NEWLINE p3 = Process(target=multi_qc_rna)NEWLINE self.progressBar_sub1_rna.setValue(76)NEWLINE p3.start()NEWLINE NEWLINE p4 = Process(target= self.func_pb_update( sub_pb=self.progressBar_sub1_rna, sub_pb_frac=4, initial_sub = 75, initial_main=0, error_icon=self.QCresultsButtonErroricon_rna))NEWLINE p4.start()NEWLINE else:NEWLINE passNEWLINE NEWLINE if os.path.exists("results/cutadapt/fastqc_after/multiqc_after.html"):NEWLINE filename = "results/cutadapt/fastqc_after/multiqc_after.html"NEWLINE webbrowser.get('google-chrome').open(filename, new=0, autoraise=True)NEWLINE else:NEWLINE passNEWLINE NEWLINE def run_index_text(self):NEWLINE subprocess.run(["snakemake", "--unlock", "-j", "1"])NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Creating Index for "+self.AlignercomboBoxDNA.currentText()+ "!! \n\n")NEWLINE NEWLINE def run_index_dna(self):NEWLINE self.progressBar_sub2_dna.setValue(1)NEWLINE self._set_color(self._colors['blue'].name(),pb =self.progressBar_sub2_dna)NEWLINE conf = open('config.yaml', 'w')NEWLINE conf.write('samples: ./samples.tsv \n')NEWLINE conf.write('units: '+ self.UnitslineEditDNA.text() + '\n'+'ref: \n')NEWLINE conf.write(" name: " + self.RefNamecomboBoxDNA.currentText() + "\n")NEWLINE conf.write(' genome: '+ self.RefGenomelineEditDNA.text() + '\n')NEWLINE conf.write(' genome-name: '+ os.path.basename(self.RefGenomelineEditDNA.text()) + '\n')NEWLINE conf.write(' genome-dict: '+ os.path.splitext(self.RefGenomelineEditDNA.text())[0] + '\n')NEWLINE conf.write(' known-variants: '+ self.RefVariantlineEditDNA.text() + '\n')NEWLINE conf.write('threads: ' + self.CorelineEditRNA.text() + '\n')NEWLINE conf.write("processing: \n")NEWLINE conf.write(" remove-duplicates: true\n")NEWLINE conf.write("threads: " + self.CorelineEditDNA.text() + "\n")NEWLINE conf.write('params: \n')NEWLINE conf.write(" cutadapt: '" + self.CutadaptlineEdit.text() + "' \n")NEWLINE conf.close()NEWLINE time.sleep(0.1)NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Config file created for generating index!! \nPlease refer to the file: config.yaml in your working directory. \n\n")NEWLINE rule = open('rule_all_index.txt', 'r')NEWLINE snakef = open('Snakefile', "w")NEWLINE snakef.write('include: "rules/common_dna.smk"\n')NEWLINE snakef.write('rule all:\n')NEWLINE snakef.write(' input:\n')NEWLINE for line in rule:NEWLINE if self.AlignercomboBoxDNA.currentText() in line:NEWLINE snakef.write(line)NEWLINE else:NEWLINE passNEWLINE rule.close()NEWLINE snakef.write('\ninclude: "rules/' + self.AlignercomboBoxDNA.currentText() + '_index.smk" \n')NEWLINE snakef.close()NEWLINE time.sleep(0.1)NEWLINENEWLINE def func_index_dna():NEWLINE NEWLINE process3 = subprocess.run(["snakemake", "--use-conda", "-s", "Snakefile", "--cores", self.CorelineEditDNA.text()])NEWLINE p1 = Process(target=func_index_dna)NEWLINE p1.start()NEWLINE p2 = Process(target=self.func_pb_update( sub_pb=self.progressBar_sub2_dna, sub_pb_frac=1, initial_sub = 0, initial_main=0, error_icon=self.RunIndexdnaButtonErroricon))NEWLINE p2.start()NEWLINE# self.textBrowser.insertPlainText("Creating Index for "+self.AlignercomboBoxDNA.currentText()+ "!! \n\n")NEWLINE if self.AlignercomboBoxDNA.currentText() == "BWA_MEM":NEWLINE self.BWAIndexlineEdit.setText("results_dna/index/BWA_MEM/" +os.path.basename(self.RefGenomelineEditDNA.text()))NEWLINE elif self.AlignercomboBoxDNA.currentText() == 'GEM3':NEWLINE self.BWAIndexlineEdit.setText("results_dna/index/"+self.AlignercomboBoxDNA.currentText()+ "/"+os.path.basename(self.RefGenomelineEditDNA.text())+".gem")NEWLINE else:NEWLINE self.BWAIndexlineEdit.setText("results_dna/index/"+self.AlignercomboBoxDNA.currentText()+ "/"+os.path.basename(self.RefGenomelineEditDNA.text()))NEWLINE# self.BWAIndexlineEdit.setText(os.getcwd()+"/results_dna/index/"+self.AlignercomboBoxDNA.currentText()+ "/"+os.path.basename(self.RefGenomelineEditDNA.text())+".gem")NEWLINE if self.progressBar_sub2_dna.value() == 100:NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Index created in results_dna/index/" +self.AlignercomboBoxDNA.currentText() +"/ !! \n\n")NEWLINE else:NEWLINE passNEWLINE NEWLINE def run_index_rna(self):NEWLINE self.progressBar_sub2_dna.setValue(1)NEWLINE self._set_color(self._colors['blue'].name(),pb =self.progressBar_sub2_dna)NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Config file created for generating index!! \nPlease refer to the file: config.yaml in your working directory. \n\n")NEWLINE conf = open('config.yaml', 'w')NEWLINE conf.write('units: units.tsv \n')NEWLINE conf.write('ref: \n')NEWLINE conf.write(' annotation: '+ self.AnnotatedlineEditRNA.text() + '\n')NEWLINE conf.write(' fasta: '+self.FastalineEdit.text() + '\n')NEWLINE conf.write('threads: ' + self.CorelineEditRNA.text() + '\n')NEWLINE conf.write('params: \n')NEWLINE conf.write(" cutadapt: '" + self.CutadaptlineEdit_rna.text() + "' \n")NEWLINE conf.write("sample: " + self.SampleFolderLineEdit.text() + "\n")NEWLINE conf.close()NEWLINE NEWLINE time.sleep(0.1)NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Snakefilefile created for generating index!! \nPlease refer to the file: Snakefile_index in your working directory. \n\n")NEWLINE rule = open('rule_all_index.txt', 'r')NEWLINE snakef = open('Snakefile', "w")NEWLINE snakef.write('configfile: "config.yaml"\n')NEWLINE snakef.write('rule all:\n')NEWLINE snakef.write(' input:\n')NEWLINE for line in rule:NEWLINE if self.AlignercomboBoxRNA.currentText() in line:NEWLINE snakef.write(line)NEWLINE snakef.write('\ninclude: "rules/' + self.AlignercomboBoxRNA.currentText() + '_index.smk" \n')NEWLINE rule.close()NEWLINE snakef.close()NEWLINE NEWLINE time.sleep(0.1)NEWLINE def func_index_rna():NEWLINE NEWLINE process4 = subprocess.run(["snakemake", "--use-conda", "-s", "Snakefile", "--cores", self.CorelineEditDNA.text()])NEWLINE output4 = process4.communicate()NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Creating Index for "+self.AlignercomboBoxRNA.currentText()+ "!! \n\n")NEWLINE p1 = Process(target=func_index_rna)NEWLINE p1.start()NEWLINE p2 = Process(target=self.func_pb_update( sub_pb=self.progressBar_sub2_rna, sub_pb_frac=1, initial_sub = 0, initial_main=0, error_icon=self.RunIndexrnaButtonErroricon))NEWLINE p2.start()NEWLINE self.StarIndexlineEdit.setText(os.getcwd()+"/results/index/"+self.AlignercomboBoxRNA.currentText())NEWLINE if self.progressBar_sub2_dna.value() == 100:NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Index created in results/index/" +self.AlignercomboBoxRNA.currentText() +"/ !! \n\n")NEWLINE else:NEWLINE passNEWLINENEWLINE def create_config_dna(self):NEWLINE conf = open('config.yaml', 'w')NEWLINE conf.write('samples: ./samples.tsv \n')NEWLINE conf.write('units: '+ self.UnitslineEditDNA.text() + '\n'+'ref: \n')NEWLINE conf.write(" name: " + self.RefNamecomboBoxDNA.currentText() + "\n")NEWLINE conf.write(' genome: '+ self.RefGenomelineEditDNA.text() + '\n')NEWLINE conf.write(' genome-name: '+ os.path.basename(self.RefGenomelineEditDNA.text()) + '\n')NEWLINE conf.write(' genome-dict: '+ os.path.splitext(self.RefGenomelineEditDNA.text())[0] + '\n')NEWLINE conf.write(' known-variants: '+ self.RefVariantlineEditDNA.text() + '\n')NEWLINE conf.write("processing: \n")NEWLINE conf.write(" remove-duplicates: true\n")NEWLINE conf.write('index: \n')NEWLINE conf.write(' '+ self.AlignercomboBoxDNA.currentText() + ': ' + self.BWAIndexlineEdit.text() + '\n')NEWLINE conf.write('threads: ' + self.CorelineEditDNA.text() + '\n')NEWLINE conf.write('params: \n')NEWLINE conf.write(" cutadapt: '" + self.CutadaptlineEdit.text() + "' \n")NEWLINE aligner_params = open("aligner_params.txt", 'r').read().replace('\n', '')NEWLINE conf.write(" " + aligner_params + '\n')NEWLINE vc_params = open("vc_params.txt", 'r').read().replace('\n', '')NEWLINE conf.write(" " + vc_params + '\n')NEWLINE annotator_params = open("annotator_params.txt", 'r').read().replace('\n', '')NEWLINE conf.write(" " + annotator_params + '\n')NEWLINENEWLINE conf.write(" picard: \n")NEWLINE conf.write(" MarkDuplicates: REMOVE_DUPLICATES=true VALIDATION_STRINGENCY=SILENT \n")NEWLINE conf.write("filtering:\n")NEWLINE conf.write(" vqsr: false\n")NEWLINE conf.write(" hard:\n")NEWLINE conf.write(" snvs:\n")NEWLINE conf.write(" " + '"QD < 2.0 || FS > 60.0 || MQ < 40.0 || MQRankSum < -12.5 || ReadPosRankSum < -8.0"\n')NEWLINE conf.write(" "+"indels:\n")NEWLINE conf.write(" "+'"QD < 2.0 || FS > 200.0 || ReadPosRankSum < -20.0"\n')NEWLINE conf.close()NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Config file created for DNA Seq analysis!! \nPlease refer to the file: config.yaml in your working directory. \n\n")NEWLINENEWLINENEWLINE def create_snakefile_dna(self):NEWLINE snake = open('Snakefile', "w")NEWLINE snake.write('include: "rules/common_dna.smk"\n')NEWLINE snake.write('rule all:\n')NEWLINE snake.write(' input:\n')NEWLINE snake.write(' expand("results_dna/mapped/{u.sample}-{u.unit}-{u.condition}.sorted.bam", u = units.itertuples()),\n')NEWLINE snake.write(' expand("results_dna/dedup/{u.sample}-{u.unit}-{u.condition}.bam", u = units.itertuples()),\n')NEWLINE snake.write(' "results_dna/filtered/all.vcf.gz",\n')NEWLINE snake.write(' "results_dna/multiqc/multiqc.html",\n')NEWLINE snake.write(' config["ref"]["genome-dict"]+ ".dict",\n')NEWLINE snake.write(' config["ref"]["genome"]+ ".fai",\n')NEWLINE snake.write('\ninclude: "rules/' + self.AlignercomboBoxDNA.currentText() + '.smk" \n')NEWLINE snake.write('include: "rules/' + self.VCcomboBoxDNA.currentText() + '.smk" \n')NEWLINE snake.write('include: "rules/' + self.AnnotatorcomboBoxDNA.currentText() + '.smk" \n')NEWLINE snake.close()NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Snakefile created for DNA Seq analysis!! \nPlease refer to the file: Snakefile in your working directory. \n\n")NEWLINENEWLINE def not_snpeff(self):NEWLINE self.param_display()NEWLINE if self.AnnotatorcomboBoxDNA.currentText() == 'SnpEff':NEWLINE self.RefNamelabelDNA.show()NEWLINE self.RefNamecomboBoxDNA.show()NEWLINE else:NEWLINE self.RefNamelabelDNA.setText("Reference name (as in Annovar database)")NEWLINE self.RefNamelabelDNA.show()NEWLINE self.RefNamecomboBoxDNA.show()NEWLINENEWLINE def if_annovar(self):NEWLINE with open('Snakefile', 'r+') as fd:NEWLINE contents = fd.readlines()NEWLINE if self.AnnotatorcomboBoxDNA.currentText() == 'Annovar':NEWLINE self.RefNamelabelDNA.setText("Reference name (as in Annovar database)")NEWLINE contents.insert(7, ' "results_dna/filtered/all.avinput",\n')NEWLINE contents.insert(10, ' "results_dna/annotated/all." + config["ref"]["name"] + "_multianno.vcf", \n')NEWLINE fd.seek(0) # readlines consumes the iterator, so we need to start overNEWLINE fd.writelines(contents)NEWLINE else:NEWLINE contents.insert(8, ' "results_dna/annotated/all.vcf", \n')NEWLINE fd.seek(0) # readlines consumes the iterator, so we need to start overNEWLINE fd.writelines(contents)NEWLINE fd.close()NEWLINENEWLINE def create_config_rna(self):NEWLINE conf = open('config.yaml', 'w')NEWLINE conf.write('units: units.tsv \n')NEWLINE conf.write('ref: \n')NEWLINE if self.AlignercomboBoxRNA.currentText() == 'HISAT2':NEWLINE conf.write(' index-'+self.AlignercomboBoxRNA.currentText() + ': ' + self.StarIndexlineEdit.text() + '/ \n')NEWLINE elif self.AlignercomboBoxRNA.currentText() == 'bowtie2':NEWLINE conf.write(' index-'+ self.AlignercomboBoxRNA.currentText() + ': ' + self.StarIndexlineEdit.text() + '/bowtie2-index \n')NEWLINE else:NEWLINE conf.write(' index-'+ self.AlignercomboBoxRNA.currentText() + ': ' + self.StarIndexlineEdit.text() + '\n')NEWLINE conf.write(' annotation: '+ self.AnnotatedlineEditRNA.text() + '\n')NEWLINE conf.write(' fasta: '+self.FastalineEdit.text() + '\n')NEWLINE conf.write('threads: ' + self.CorelineEditRNA.text() + '\n')NEWLINE conf.write('params: \n')NEWLINE conf.write(" cutadapt: '" + self.CutadaptlineEdit_rna.text() + "' \n")NEWLINE aligner_params_rna = open("aligner_params_rna.txt", 'r').read().replace('\n', '')NEWLINE conf.write(" " + aligner_params_rna + '\n')NEWLINE em_params = open("em_params.txt", 'r').read().replace('\n', '')NEWLINE conf.write(" " + em_params + '\n')NEWLINE de_params = open("de_params.txt", 'r').read().replace('\n', '')NEWLINE conf.write(" " + de_params + '\n')NEWLINE NEWLINE conf.write("sample: " + self.SampleFolderLineEdit.text() + "\n")NEWLINE conf.close()NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Config file created for RNA Seq analysis!! \nPlease refer to the file: config.yaml in your working directory. \n\n")NEWLINENEWLINENEWLINE def create_snakefile_rna(self):NEWLINE snakef = open('Snakefile', 'w')NEWLINE snakef.write('include: "rules/common_rna.smk"\n')NEWLINE snakef.write('rule all:\n')NEWLINE snakef.write(' input:\n')NEWLINE if self.AlignercomboBoxRNA.currentText() == 'HISAT2':NEWLINE snakef.write(" expand('results/aligner_results/{sample}_{condition}_Rep{rep}.sam', sample=samples, condition=type, rep=reps),\n")NEWLINE snakef.write(" expand('results/aligner_results/{sample}_{condition}_Rep{rep}.bam', sample=samples, condition=type, rep=reps),\n")NEWLINE elif self.AlignercomboBoxRNA.currentText() == 'STAR':NEWLINE snakef.write(" expand('results/aligner_results/{sample}_{condition}_Rep{rep}/Aligned.out.sam', sample=samples, condition=type, rep=reps),\n")NEWLINE snakef.write(" expand('results/aligner_results/{sample}_{condition}_Rep{rep}.bam', sample=samples, condition=type, rep=reps),\n")NEWLINE if self.EMcomboBoxRNA.currentText() == 'StringTie':NEWLINE snakef.write(" expand('results/em_results/{sample}_{condition}_Rep{rep}/{sample}_{condition}_Rep{rep}_transcript.gtf', sample=samples, condition=type, rep=reps),\n")NEWLINE snakef.write(" expand('results/em_results/{sample}_{condition}_Rep{rep}/{sample}_{condition}_Rep{rep}_gene_abundances.tsv', sample=samples, condition=type, rep=reps),\n")NEWLINE snakef.write(" expand('results/em_results/{sample}_{condition}_Rep{rep}/{sample}_{condition}_Rep{rep}_cov_ref.gtf', sample=samples, condition=type, rep=reps),\n")NEWLINE elif self.EMcomboBoxRNA.currentText() == 'HTSeq':NEWLINE snakef.write(" expand('results/em_results/{sample}_{condition}_Rep{rep}.counts', sample=samples, condition=type, rep=reps),\n")NEWLINE snakef.write(' "results/em_results/emtable.tsv",\n')NEWLINE if self.DEcomboBoxRNA.currentText() == 'ballgown':NEWLINE snakef.write(" expand('results/de_results/SigDE.txt'),\n")NEWLINE elif self.DEcomboBoxRNA.currentText() == 'DESeq2':NEWLINE snakef.write(" expand('results/de_results/DESeq2_normalized_counts.txt'),\n")NEWLINE snakef.write(' "results/multiqc/multiqc.html",\n')NEWLINE snakef.write('include: "rules/' + self.AlignercomboBoxRNA.currentText() + '.smk" \n')NEWLINE snakef.write('include: "rules/' + self.EMcomboBoxRNA.currentText() + '.smk" \n')NEWLINE snakef.write('include: "rules/' + self.DEcomboBoxRNA.currentText() + '.smk" \n')NEWLINE snakef.close()NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Snakefile created for RNA Seq analysis!! \nPlease refer to the file: Snakefile in your working directory. \n\n")NEWLINENEWLINE def create_dag(self):NEWLINE with open("Snakefile", "r+") as snake:NEWLINE line= snake.readline()NEWLINE if '"rules/common_dna.smk"' in line:NEWLINE svg_filename = self.AlignercomboBoxDNA.currentText() + self.VCcomboBoxDNA.currentText() + self.AnnotatorcomboBoxDNA.currentText() + ".svg"NEWLINE else:NEWLINE svg_filename = self.AlignercomboBoxRNA.currentText() + self.EMcomboBoxRNA.currentText() + self.DEcomboBoxRNA.currentText() + ".svg"NEWLINE print(svg_filename)NEWLINE subprocess.run(["snakemake", "--rulegraph", "|", "dot", "-Tsvg", "-o", '"'+ svg_filename+ '"'], shell =True, stdout=subprocess.PIPE)NEWLINENEWLINENEWLINE def about(self):NEWLINE url = 'icomic.readthedocs.io'NEWLINE widget = About()NEWLINE widget.setText("iCOMIC version 0.1")NEWLINE widget.setInformativeText("""NEWLINE Online documentation on %(url)sNEWLINE
NEWLINE
NEWLINE Authors: Anjana Anilkumar Sithara, Devi Priyanka Maripuri, Keerthika Moorthy, Sai Sruthi Amirtha Ganesh, Philge Philip, Shayantan Banerjee, Malvika Sudhakar, Karthik Raman NEWLINE """ % {"url": url})NEWLINE widget.setWindowTitle("iCOMIC")NEWLINE retval = widget.exec_()NEWLINE if retval == QtWidgets.QMessageBox.Ok:NEWLINE widget.close()NEWLINENEWLINE def quick_start(self):NEWLINE url = 'iCOMIC.readthedocs.io'NEWLINE pipelines_text = "
    \n"NEWLINE msg = HelpDialog(pipelines=pipelines_text)NEWLINE retval = msg.exec_()NEWLINE if retval == QtWidgets.QMessageBox.Ok:NEWLINE msg.close()NEWLINENEWLINENEWLINE NEWLINE def run_action_textbox(self):NEWLINE subprocess.run(["snakemake", "--unlock", "-j", "1"])NEWLINE self.textBrowser.setTextColor(self._colors['black'])NEWLINE self.textBrowser.append("Please be patient, while we analyze your data... \n\n")NEWLINENEWLINE def run_action_dna(self):NEWLINE self._set_color(self._colors['blue'].name(),pb =self.progressBar_dna)NEWLINE self.progressBar_dna.setValue(1)NEWLINE NEWLINE def func_run_action():NEWLINE process5 = subprocess.run(["snakemake", "--use-conda", "-j", self.CorelineEditDNA.text()])NEWLINE NEWLINE NEWLINE p1 = Process(target=func_run_action)NEWLINE p1.start()NEWLINE p2 = Process(target=self.func_pb_update( sub_pb=self.progressBar_dna, sub_pb_frac=1, initial_sub = 0, initial_main=0, error_icon=self.RunButtonErroricon_dna))NEWLINE p2.start()NEWLINE NEWLINE if self.progressBar_dna.value() == 100:NEWLINE self._set_color(self._colors['green'].name(),pb =self.progressBar_dna)NEWLINE self.nextbuttonrunDNA.setEnabled(True)NEWLINE self.DNAtabWidget.setCurrentIndex(4)NEWLINE self.DNAtabWidget.setTabEnabled(4, True)NEWLINE else:NEWLINE passNEWLINE NEWLINENEWLINE def run_action_rna(self):NEWLINE self.progressBar.setValue(1)NEWLINE self._set_color(self._colors['blue'].name(),pb =self.progressBar)NEWLINE def func_run_action():NEWLINE process5 = subprocess.run(["snakemake", "--use-conda", "--cores", self.CorelineEditDNA.text()])NEWLINE NEWLINE NEWLINE p1 = Process(target=func_run_action)NEWLINE p1.start()NEWLINE p2 = Process(target=self.func_pb_update( sub_pb=self.progressBar, sub_pb_frac=1, initial_sub = 0, initial_main=0, error_icon=self.RunButtonErroricon))NEWLINE p2.start()NEWLINE if self.progressBar.value() == 100:NEWLINE self._set_color(self._colors['green'].name(),pb =self.progressBar)NEWLINE self.nextbuttonrunRNA.setEnabled(True)NEWLINE self.RNAtabWidget.setCurrentIndex(4)NEWLINE self.RNAtabWidget.setTabEnabled(4, True)NEWLINE else:NEWLINE passNEWLINE NEWLINE NEWLINE def on_check_proceed(self,is_toggle):NEWLINE if is_toggle:NEWLINE self.ctagradioButton.setEnabled(True)NEWLINE self.nbradioButton.setEnabled(True)NEWLINE self.nextbuttonresult.setEnabled(True)NEWLINE self.nbinfoiconradio.setEnabled(True)NEWLINE else:NEWLINE self.ctagradioButton.setEnabled(False)NEWLINE self.nbradioButton.setEnabled(False)NEWLINE self.nextbuttonresult.setEnabled(False)NEWLINE self.nbinfoiconradio.setEnabled(False)NEWLINENEWLINENEWLINENEWLINEclass About(QtWidgets.QMessageBox):NEWLINE """A resizable QMessageBox for the About dialog"""NEWLINENEWLINE def __init__(self, *args, **kwargs):NEWLINE super(About, self).__init__(*args, **kwargs)NEWLINE self.setSizeGripEnabled(True)NEWLINE self.setIcon(QtWidgets.QMessageBox.Information)NEWLINE self.setWindowTitle("iCOMIC")NEWLINE self.setStandardButtons(QtWidgets.QMessageBox.Ok)NEWLINENEWLINE def event(self, e):NEWLINE result = super(About, self).event(e)NEWLINENEWLINE self.setMinimumHeight(0)NEWLINE self.setMaximumHeight(16777215)NEWLINE self.setMinimumWidth(500)NEWLINE self.setMaximumWidth(16777215)NEWLINE self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)NEWLINENEWLINE return resultNEWLINENEWLINEclass Ui_Help(object):NEWLINE def setupUi(self, Help):NEWLINE Help.setObjectName("Help")NEWLINE Help.resize(456, 582)NEWLINE self.gridLayout = QtWidgets.QGridLayout(Help)NEWLINE self.gridLayout.setObjectName("gridLayout")NEWLINE self.verticalLayout = QtWidgets.QVBoxLayout()NEWLINE self.verticalLayout.setObjectName("verticalLayout")NEWLINE self.textBrowser = QtWidgets.QTextBrowser(Help)NEWLINE self.textBrowser.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)NEWLINE self.textBrowser.setOpenExternalLinks(True)NEWLINE self.textBrowser.setObjectName("textBrowser")NEWLINE self.verticalLayout.addWidget(self.textBrowser)NEWLINE self.buttonBox = QtWidgets.QDialogButtonBox(Help)NEWLINE self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok)NEWLINE self.buttonBox.setObjectName("buttonBox")NEWLINE self.verticalLayout.addWidget(self.buttonBox)NEWLINE self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)NEWLINENEWLINE self.retranslateUi(Help)NEWLINE QtCore.QMetaObject.connectSlotsByName(Help)NEWLINENEWLINE def retranslateUi(self, Help):NEWLINE _translate = QtCore.QCoreApplication.translateNEWLINE Help.setWindowTitle(_translate("Help", "iCOMIC Help"))NEWLINENEWLINEhelptxt = """NEWLINE
    NEWLINE

    NEWLINEiCOMIC pipeline enables the ready analysis of RNA-Seq and Whole Genome Sequencing data.NEWLINE ICOMIC has an inbuilt library of tools with predefined valid combinations.NEWLINE

    NEWLINE

    NEWLINE The user will have the freedom to choose any possible combination of tools,NEWLINE however a benchmarked list of pipelines is provided (seeNEWLINEiCOMIC.readthedocs.io for details).NEWLINE

    NEWLINENEWLINE

    NEWLINE Here is a typical set of actions to run iCOMIC pipelines:NEWLINE

      NEWLINE
    1. Select a pipeline.
    2. NEWLINE
    3. Input the required data files.
    4. NEWLINE
    5. Check 'yes' for Quality Control if you want to do quality check andNEWLINE trimming and also mention the additional parameters if required.
    6. NEWLINE
        NEWLINE
      • Tool for Quality Control: FastQC
      • NEWLINE
      • Tool for trimming the reads: Cutadapt
      • NEWLINE
      NEWLINE
    7. Click on 'Create snakefile for QC Analysis' button for creatingNEWLINE the Snakefile and 'Create config file for QC Analysis' button forNEWLINE config file.
    8. NEWLINE
    9. Click on 'Run Quality Control' to perform Quality check.
    10. NEWLINE
    11. Select the tools for analysis.
    12. NEWLINE
    13. Input the index files.
    14. NEWLINE
    15. Enter additional parameters for each tool if required.
    16. NEWLINE
    17. Click on 'Create snakefile' button for creating the Snakefile andNEWLINE 'Create config file' button for config file.
    18. NEWLINE
    19. Click 'Run' to run the pipeline.
    20. NEWLINE
    NEWLINE"""NEWLINENEWLINENEWLINEclass HelpDialog(QtWidgets.QDialog):NEWLINE """todo"""NEWLINE def __init__(self, parent=None, pipelines=""):NEWLINE super().__init__(parent=parent)NEWLINE self.ui = Ui_Help()NEWLINE self.ui.setupUi(self)NEWLINE self.ui.textBrowser.setText(helptxt % {"pipelines": pipelines})NEWLINE self.ui.buttonBox.accepted.connect(self.close)NEWLINENEWLINE NEWLINENEWLINEclass SVGDialog(QtWidgets.QDialog):NEWLINE """Dialog to show a SVG image"""NEWLINE def __init__(self, filename):NEWLINE super().__init__()NEWLINE self.main_layout = QtWidgets.QVBoxLayout(self)NEWLINE self.setWindowTitle("DAG")NEWLINENEWLINE if os.path.exists(filename):NEWLINE widget = QSvgWidget(filename)NEWLINE self.main_layout.addWidget(widget)NEWLINENEWLINEclass QCResultsDialog(QtWidgets.QWidget):NEWLINE """Dialog to show a SVG image"""NEWLINE def __init__(self, filename):NEWLINE super().__init__()NEWLINE self.initUI()NEWLINE NEWLINE def initUI(self):NEWLINE self.closeButton = QtWidgets.QPushButton("Close")NEWLINE self.main_layout = QtWidgets.QHBoxLayout(self)NEWLINE self.main_layout.addStretch(1)NEWLINE self.main_layout.addWidget(self.closeButton)NEWLINE self.vbox = QtWidgets.QVBoxLayout(self)NEWLINE self.vbox.addStretch(2)NEWLINE self.vbox.addLayout(self.main_layout)NEWLINE self.setLayout(self.vbox) NEWLINE self.setGeometry(300, 300, 300, 150)NEWLINE self.setWindowTitle("FastQC Results")NEWLINE NEWLINEclass AdvancedDialog(QtWidgets.QDialog):NEWLINE def __init__(self, path):NEWLINE super().__init__()NEWLINE self.setWindowTitle("Advanced Options")NEWLINE self.setStyleSheet("background-color: #C3E7B5")NEWLINE self.top = 200NEWLINE self.left = 500NEWLINE self.width = 600NEWLINE self.height = 550NEWLINE self.setGeometry(self.left, self.top, self.width, self.height)NEWLINE formLayout =QFormLayout()NEWLINE groupBox = QGroupBox()NEWLINE groupBox.setStyleSheet("background-color: #F0F9EC")NEWLINE dataframe = pd.read_csv(path, header=0) # specifying that the table has column namesNEWLINE add_int_param = dataframe[(dataframe["Value"] == 'INT') & (dataframe["Essential"] == 'no')]NEWLINE num_add_int_param = len(add_int_param)NEWLINE add_float_param = dataframe[(dataframe["Value"] == 'FLOAT') & (dataframe["Essential"] == 'no')]NEWLINE num_add_float_param=len(add_float_param)NEWLINE add_na_param = dataframe[(dataframe["Value"] == 'na') & (dataframe["Essential"] == 'no')]NEWLINE num_add_na_param=len(add_na_param)NEWLINE add_str_param = dataframe[(dataframe["Value"] == 'STR') & (dataframe["Essential"] == 'no')]NEWLINE num_add_str_param=len(add_str_param)NEWLINE NEWLINE self.button = QtWidgets.QDialogButtonBox(self)NEWLINE self.button.setStandardButtons(QtWidgets.QDialogButtonBox.Ok)NEWLINE self.button.move(450,510)NEWLINE NEWLINE self.label_list_int = []NEWLINE self.line_edit_list_int = []NEWLINE self.label_list_float = []NEWLINE self.line_edit_list_float = []NEWLINE self.radio_label_list_na = []NEWLINE self.line_edit_list_str = []NEWLINE self.label_list_str = []NEWLINE for y in range(num_add_int_param):NEWLINE label_name = str(add_int_param.iloc[y, 2])NEWLINE self.label_name = QtWidgets.QLabel(label_name)NEWLINE self.label_list_int.append(self.label_name)NEWLINE default_value = str(add_int_param.iloc[y, 4])NEWLINE self.line_edit = QtWidgets.QLineEdit(default_value)NEWLINE self.line_edit_list_int.append(self.line_edit)NEWLINE formLayout.addRow(self.label_list_int[y], self.line_edit_list_int[y])NEWLINE for x in range(num_add_float_param):NEWLINE label_name = str(add_float_param.iloc[x, 2])NEWLINE self.label_name = QtWidgets.QLabel(label_name)NEWLINE self.label_list_float.append(self.label_name)NEWLINE default_value = str(add_float_param.iloc[x, 4])NEWLINE self.line_edit = QtWidgets.QLineEdit(default_value)NEWLINE self.line_edit_list_float.append(self.line_edit)NEWLINE formLayout.addRow(self.label_list_float[x], self.line_edit_list_float[x])NEWLINE for p in range(num_add_str_param):NEWLINE label_name = str(add_str_param.iloc[p, 2])NEWLINE self.label_name = QtWidgets.QLabel(label_name)NEWLINE self.label_list_str.append(self.label_name)NEWLINE default_value = str(add_str_param.iloc[p, 4])NEWLINE self.line_edit = QtWidgets.QLineEdit(default_value)NEWLINE self.line_edit_list_str.append(self.line_edit)NEWLINE formLayout.addRow(self.label_list_str[p], self.line_edit_list_str[p])NEWLINE formLayout.addRow(self.label_list_str[p])NEWLINE for z in range(num_add_na_param):NEWLINE radio_name = str(add_na_param.iloc[z, 2])NEWLINE self.radio_name = QtWidgets.QCheckBox(radio_name)NEWLINE self.radio_name.setChecked(False)NEWLINE self.radio_label_list_na.append(self.radio_name)NEWLINE formLayout.addRow(self.radio_label_list_na[z])NEWLINE NEWLINENEWLINE NEWLINE groupBox.setLayout(formLayout)NEWLINE scroll = QScrollArea()NEWLINE scroll.setWidget(groupBox)NEWLINE scroll.setWidgetResizable(True)NEWLINE scroll.setFixedHeight(450)NEWLINE layout = QtWidgets.QVBoxLayout(self)NEWLINE layout.addWidget(scroll)NEWLINE NEWLINEclass AdvancedDialog_old(QtWidgets.QDialog):NEWLINE def __init__(self, path):NEWLINE super().__init__()NEWLINE self.setWindowTitle("Advanced Options")NEWLINE self.top = 200NEWLINE self.left = 500NEWLINE self.width = 600NEWLINE self.height = 550NEWLINE self.setGeometry(self.left, self.top, self.width, self.height)NEWLINE formLayout =QFormLayout()NEWLINE groupBox = QGroupBox()NEWLINE dataframe = pd.read_csv(path, header=0) # specifying that the table has column namesNEWLINE additional = dataframe[dataframe["Essential"] == "no"]NEWLINE number_of_additional = len(additional)NEWLINE NEWLINE self.button = QtWidgets.QDialogButtonBox(self)NEWLINE self.button.setStandardButtons(QtWidgets.QDialogButtonBox.Ok)NEWLINE self.button.move(450,510)NEWLINE self.label_list = []NEWLINE self.line_edit_list = []NEWLINE for x in range(number_of_additional):NEWLINE label_name = str(additional.iloc[x, 2])NEWLINE self.label_name = QtWidgets.QLabel(label_name)NEWLINE self.label_list.append(self.label_name)NEWLINE default_value = str(additional.iloc[x, 4])NEWLINE self.line_edit = QtWidgets.QLineEdit(default_value)NEWLINE self.line_edit_list.append(self.line_edit)NEWLINE formLayout.addRow(self.label_list[x], self.line_edit_list[x])NEWLINE groupBox.setLayout(formLayout)NEWLINE scroll = QScrollArea()NEWLINE scroll.setWidget(groupBox)NEWLINE scroll.setWidgetResizable(True)NEWLINE scroll.setFixedHeight(450)NEWLINE layout = QtWidgets.QVBoxLayout(self)NEWLINE layout.addWidget(scroll)NEWLINEclass showQCDialog():NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINE msgBox = QMessageBox()NEWLINE msgBox.setIcon(QMessageBox.Question)NEWLINE self.left = 700NEWLINE self.top = 450NEWLINE self.width = 320NEWLINE self.height = 400NEWLINE msgBox.setGeometry(self.left, self.top, self.width, self.height)NEWLINE msgBox.setText("Are you sure you want to proceed without Quality control of your data?")NEWLINE msgBox.setWindowTitle("WARNING")NEWLINE msgBox.resize(200,64)NEWLINE msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)NEWLINENEWLINE self.returnValue = msgBox.exec()NEWLINE NEWLINEclass ResultsDialog(QtWidgets.QMainWindow):NEWLINE def __init__(self, path):NEWLINE super().__init__() NEWLINENEWLINE self.textEdit = QtWidgets.QTextEdit()NEWLINE self.setCentralWidget(self.textEdit)NEWLINE self.statusBar()NEWLINE self.setGeometry(300, 300, 350, 300)NEWLINE self.setWindowTitle(os.path.basename(path))NEWLINE self.show()NEWLINE if os.path.splitext(path)[-1] == ".gz":NEWLINE with gzip.open(path, 'rb') as f:NEWLINE data = f.read()NEWLINE self.textEdit.setText(data.decode("utf-8"))NEWLINE else:NEWLINE with open(path, 'r') as f:NEWLINE data = f.read()NEWLINE self.textEdit.setText(data)NEWLINENEWLINEclass ResultsDialog_old(QtWidgets.QMainWindow):NEWLINENEWLINE def __init__(self, path):NEWLINE super().__init__()NEWLINE NEWLINE self.initUI()NEWLINENEWLINENEWLINE def initUI(self): NEWLINENEWLINE self.textEdit = QtWidgets.QTextEdit()NEWLINE self.setCentralWidget(self.textEdit)NEWLINE self.statusBar()NEWLINENEWLINE self.showDialog()NEWLINE self.setGeometry(300, 300, 350, 300)NEWLINE self.setWindowTitle("filtered vcf")NEWLINE self.show()NEWLINE def showDialog(self):NEWLINE with gzip.open(path, 'rb') as f:NEWLINE data = f.read()NEWLINE self.textEdit.setText(data.decode("utf-8"))NEWLINENEWLINE NEWLINENEWLINENEWLINENEWLINENEWLINEdef main():NEWLINE NEWLINE app = QtWidgets.QApplication(sys.argv)NEWLINE MainWindow = QtWidgets.QMainWindow()NEWLINE ui = Ui_MainWindow()NEWLINE ui.setupUi(MainWindow)NEWLINE MainWindow.show()NEWLINE sys.exit(app.exec_())NEWLINENEWLINEmain() import rlpNEWLINENEWLINEfrom bxutils.logging.log_level import LogLevelNEWLINENEWLINEfrom bxgateway.messages.eth.protocol.eth_protocol_message import EthProtocolMessageNEWLINEfrom bxgateway.messages.eth.protocol.eth_protocol_message_type import EthProtocolMessageTypeNEWLINEfrom bxgateway.messages.eth.serializers.block_header import BlockHeaderNEWLINEfrom bxgateway.utils.eth import rlp_utilsNEWLINENEWLINENEWLINEclass BlockHeadersEthProtocolMessage(EthProtocolMessage):NEWLINE msg_type = EthProtocolMessageType.BLOCK_HEADERSNEWLINENEWLINE fields = [("block_headers", rlp.sedes.CountableList(BlockHeader))]NEWLINENEWLINE def __repr__(self):NEWLINE headers = self.get_block_headers()NEWLINE headers_repr = list(headers[:1])NEWLINE if len(headers) > 1:NEWLINE headers_repr.append(headers[-1])NEWLINE return f"BlockHeadersEthProtocolMessage"NEWLINENEWLINE def get_block_headers(self):NEWLINE return self.get_field_value("block_headers")NEWLINENEWLINE def get_block_headers_bytes(self):NEWLINE if self._memory_view is None:NEWLINE self.serialize()NEWLINENEWLINE return rlp_utils.get_first_list_field_items_bytes(self._memory_view)NEWLINENEWLINE @classmethodNEWLINE def from_header_bytes(cls, header_bytes: memoryview) -> "BlockHeadersEthProtocolMessage":NEWLINE headers_list_prefix = rlp_utils.get_length_prefix_list(len(header_bytes))NEWLINENEWLINE msg_bytes = bytearray(len(headers_list_prefix) + len(header_bytes))NEWLINE msg_bytes[:len(headers_list_prefix)] = headers_list_prefixNEWLINE msg_bytes[len(headers_list_prefix):] = header_bytesNEWLINENEWLINE return cls(msg_bytes)NEWLINENEWLINE def log_level(self):NEWLINE return LogLevel.DEBUGNEWLINE from panda3d.core import DepthOffsetAttrib, NodePath, Vec3, Vec4, TextNodeNEWLINEfrom direct.directnotify import DirectNotifyGlobalNEWLINEfrom direct.fsm.FSM import FSMNEWLINEfrom direct.interval.FunctionInterval import WaitNEWLINEfrom direct.interval.IntervalGlobal import Func, LerpHprInterval, LerpScaleInterval, LerpFunctionIntervalNEWLINEfrom direct.interval.MetaInterval import Sequence, ParallelNEWLINEfrom direct.distributed.ClockDelta import globalClockDeltaNEWLINEfrom toontown.toonbase import ToontownGlobalsNEWLINEfrom toontown.effects import DustCloudNEWLINEimport CogdoFlyingGameGlobals as Globals, CogdoUtilNEWLINEfrom CogdoFlyingObjects import CogdoFlyingGatherableNEWLINEfrom CogdoFlyingUtil import swapAvatarShadowPlacerNEWLINENEWLINEclass CogdoFlyingPlayer(FSM):NEWLINE notify = DirectNotifyGlobal.directNotify.newCategory('CogdoFlyingPlayer')NEWLINENEWLINE def __init__(self, toon):NEWLINE FSM.__init__(self, 'CogdoFlyingPlayer')NEWLINE self.toon = toonNEWLINE self.toon.reparentTo(render)NEWLINE self.legalEaglesTargeting = []NEWLINE self.activeBuffs = []NEWLINE self.initModels()NEWLINE self.initIntervals()NEWLINE self.netTimeSentToStartDeath = 0NEWLINE self.backpackState = -1NEWLINE self.lastBackpackState = -1NEWLINE self.lastPropellerSpinRate = Globals.Gameplay.NormalPropSpeedNEWLINE self.propellerSpinRate = Globals.Gameplay.NormalPropSpeedNEWLINE self.setFuelState(Globals.Gameplay.FuelStates.FuelNoPropeller)NEWLINE self.setOldFuelState(self.fuelState)NEWLINE CogdoFlyingPlayer.setBlades(self, Globals.Gameplay.FuelStates.FuelNoPropeller)NEWLINE self.setBackpackState(Globals.Gameplay.BackpackStates.Normal)NEWLINENEWLINE def initModels(self):NEWLINE self.createPropeller()NEWLINE self.createRedTapeRing()NEWLINENEWLINE def createPropeller(self):NEWLINE self.propellerSmoke = DustCloud.DustCloud(self.toon, wantSound=False)NEWLINE self.propellerSmoke.setBillboardPointEye()NEWLINE self.propellerSmoke.setBin('fixed', 5002)NEWLINE self.backpack = CogdoUtil.loadFlyingModel('propellerPack')NEWLINE self.backpack.setScale(1.3)NEWLINE self.backpack.setHpr(180.0, 0.0, 0.0)NEWLINE self.backpackInstances = []NEWLINE self.backpackTextureCard = CogdoUtil.loadFlyingModel('propellerPack_card')NEWLINE parts = self.toon.getTorsoParts()NEWLINE for part in parts:NEWLINE backpackInstance = part.attachNewNode('backpackInstance')NEWLINE animal = self.toon.style.getAnimal()NEWLINE bodyScale = ToontownGlobals.toonBodyScales[animal]NEWLINE backpackHeight = ToontownGlobals.torsoHeightDict[self.toon.style.torso] * bodyScale - 0.5NEWLINE backpackInstance.setPos(0.0, -0.325, backpackHeight)NEWLINE self.backpackInstances.append(backpackInstance)NEWLINE self.backpack.instanceTo(backpackInstance)NEWLINENEWLINE self.propInstances = []NEWLINE self.propeller = CogdoUtil.loadFlyingModel('toonPropeller')NEWLINE for part in self.backpackInstances:NEWLINE propInstance = part.attachNewNode('propInstance')NEWLINE propInstance.setPos(0.0, -0.275, 0.0)NEWLINE propInstance.setHpr(0.0, 20.0, 0.0)NEWLINE propInstance.setScale(1.0, 1.0, 1.25)NEWLINE self.propInstances.append(propInstance)NEWLINE self.propeller.instanceTo(propInstance)NEWLINENEWLINE self.blades = []NEWLINE self.activeBlades = []NEWLINE index = 1NEWLINE blade = self.propeller.find('**/propeller%d' % index)NEWLINE while not blade.isEmpty():NEWLINE self.blades.append(blade)NEWLINE index += 1NEWLINE blade = self.propeller.find('**/propeller%d' % index)NEWLINENEWLINE for blade in self.blades:NEWLINE self.activeBlades.append(blade)NEWLINENEWLINE def createRedTapeRing(self):NEWLINE self.redTapeRing = CogdoUtil.loadFlyingModel('redTapeRing')NEWLINE self.redTapeRing.setTwoSided(True)NEWLINE self.redTapeRing.reparentTo(self.toon)NEWLINE self.redTapeRing.hide()NEWLINE self.redTapeRing.setScale(1.25)NEWLINE self.redTapeRing.setZ(self.toon.getHeight() / 2.0)NEWLINENEWLINE def initIntervals(self):NEWLINE self.baseSpinDuration = 1.0NEWLINE self.propellerSpinLerp = LerpFunctionInterval(self.propeller.setH, fromData=0.0, toData=360.0, duration=self.baseSpinDuration, name='%s.propellerSpinLerp-%s' % (self.__class__.__name__, self.toon.doId))NEWLINE singleBlinkTime = Globals.Gameplay.TargetedWarningSingleBlinkTimeNEWLINE blinkTime = Globals.Gameplay.TargetedWarningBlinkTimeNEWLINE self.blinkLoop = Sequence(Wait(singleBlinkTime / 2.0), Func(self.setBackpackTexture, Globals.Gameplay.BackpackStates.Attacked), Wait(singleBlinkTime / 2.0), Func(self.setBackpackTexture, Globals.Gameplay.BackpackStates.Targeted), name='%s.blinkLoop-%s' % (self.__class__.__name__, self.toon.doId))NEWLINE self.blinkWarningSeq = Sequence(Func(self.blinkLoop.loop), Wait(blinkTime), Func(self.blinkLoop.clearToInitial), name='%s.blinkWarningSeq-%s' % (self.__class__.__name__, self.toon.doId))NEWLINE dur = Globals.Gameplay.BackpackRefuelDurationNEWLINE self.refuelSeq = Sequence(Func(self.setPropellerSpinRate, Globals.Gameplay.RefuelPropSpeed), Wait(dur), Func(self.returnBackpackToLastStateFunc), name='%s.refuelSeq-%s' % (self.__class__.__name__, self.toon.doId))NEWLINE scale = self.redTapeRing.getScale()NEWLINE pulseTime = 1.0NEWLINE self.pulseBubbleSeq = Parallel(Sequence(LerpFunctionInterval(self.redTapeRing.setScale, fromData=scale, toData=scale * 1.1, duration=pulseTime / 2.0, blendType='easeInOut'), LerpFunctionInterval(self.redTapeRing.setScale, fromData=scale * 1.1, toData=scale, duration=pulseTime / 2.0, blendType='easeInOut')), LerpHprInterval(self.redTapeRing, pulseTime, Vec3(360, 0, 0), startHpr=Vec3(0, 0, 0)), name='%s.pulseBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))NEWLINE bouncePercent = 1.2NEWLINE scaleTime = 0.5NEWLINE scaleBounceTime = 0.25NEWLINE self.popUpBubbleLerp = LerpScaleInterval(self.redTapeRing, scaleTime, scale * bouncePercent, startScale=0.0, blendType='easeInOut')NEWLINE self.popUpBubbleSeq = Sequence(Func(self.updateLerpStartScale, self.popUpBubbleLerp, self.redTapeRing), Func(self.redTapeRing.show), self.popUpBubbleLerp, LerpScaleInterval(self.redTapeRing, scaleBounceTime, scale, startScale=scale * bouncePercent, blendType='easeInOut'), Func(self.pulseBubbleSeq.loop), name='%s.popUpBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))NEWLINE self.removeBubbleLerp = LerpScaleInterval(self.redTapeRing, scaleBounceTime, scale * bouncePercent, startScale=scale, blendType='easeInOut')NEWLINE self.removeBubbleSeq = Sequence(Func(self.pulseBubbleSeq.clearToInitial), Func(self.updateLerpStartScale, self.removeBubbleLerp, self.redTapeRing), self.removeBubbleLerp, LerpScaleInterval(self.redTapeRing, scaleTime, 0.0, startScale=scale * bouncePercent, blendType='easeInOut'), Func(self.redTapeRing.hide), name='%s.removeBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))NEWLINE self.redTapeRing.setScale(0.0)NEWLINE self.deathInterval = Sequence(Parallel(LerpHprInterval(self.toon, 1.0, Vec3(720, 0, 0)), LerpFunctionInterval(self.toon.setScale, fromData=1.0, toData=0.1, duration=1.0)), Func(self.toon.stash), name='%s.deathInterval-%s' % (self.__class__.__name__, self.toon.doId))NEWLINE self.spawnInterval = Sequence(Func(self.toon.stash), Func(self.resetToon), Wait(1.0), Func(self.toon.setAnimState, 'TeleportIn'), Func(self.toon.unstash), name='%s.spawnInterval-%s' % (self.__class__.__name__, self.toon.doId))NEWLINE singleBlinkTime = Globals.Gameplay.InvulSingleBlinkTimeNEWLINE blinkTime = Globals.Gameplay.InvulBlinkTimeNEWLINE invulBuffTime = Globals.Gameplay.InvulBuffTimeNEWLINE self.blinkBubbleLoop = Sequence(LerpFunctionInterval(self.redTapeRing.setAlphaScale, fromData=1.0, toData=0.0, duration=singleBlinkTime / 2.0, blendType='easeInOut'), LerpFunctionInterval(self.redTapeRing.setAlphaScale, fromData=0.0, toData=1.0, duration=singleBlinkTime / 2.0, blendType='easeInOut'), name='%s.blinkBubbleLoop-%s' % (self.__class__.__name__, self.toon.doId))NEWLINE self.blinkBubbleSeq = Sequence(Wait(invulBuffTime - blinkTime), Func(self.blinkBubbleLoop.loop), Wait(blinkTime), Func(self.blinkBubbleLoop.finish), name='%s.blinkBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))NEWLINENEWLINE def returnBackpackToLastStateFunc(self):NEWLINE if self.backpackState == Globals.Gameplay.BackpackStates.Refuel:NEWLINE self.returnBackpackToLastState()NEWLINENEWLINE def setPropellerSpinRateFunc(self):NEWLINE if self.propellerSpinRate == Globals.Gameplay.RefuelPropSpeed:NEWLINE self.setPropellerSpinRate(self.lastPropellerSpinRate)NEWLINENEWLINE def returnBackpackToLastState(self):NEWLINE self.setBackpackState(self.lastBackpackState)NEWLINENEWLINE def setBackpackState(self, state):NEWLINE if state == self.backpackState:NEWLINE returnNEWLINE self.lastBackpackState = self.backpackStateNEWLINE self.backpackState = stateNEWLINE self.blinkWarningSeq.clearToInitial()NEWLINE self.refuelSeq.clearToInitial()NEWLINE self.blinkLoop.clearToInitial()NEWLINE if self.lastBackpackState == Globals.Gameplay.BackpackStates.Refuel:NEWLINE self.setPropellerSpinRateFunc()NEWLINE if state in Globals.Gameplay.BackpackStates:NEWLINE if state == Globals.Gameplay.BackpackStates.Normal:NEWLINE passNEWLINE else:NEWLINE if state == Globals.Gameplay.BackpackStates.Targeted:NEWLINE passNEWLINE else:NEWLINE if state == Globals.Gameplay.BackpackStates.Refuel:NEWLINE self.refuelSeq.start()NEWLINE else:NEWLINE if state == Globals.Gameplay.BackpackStates.Attacked:NEWLINE self.blinkWarningSeq.start()NEWLINE self.setBackpackTexture(state)NEWLINENEWLINE def setBackpackTexture(self, state):NEWLINE texName = Globals.Gameplay.BackpackState2TextureName[state]NEWLINE tex = self.backpackTextureCard.findTexture(texName)NEWLINE self.backpack.setTexture(tex, 1)NEWLINENEWLINE def updateLerpStartScale(self, lerp, nodepath):NEWLINE lerp.setStartScale(nodepath.getScale())NEWLINENEWLINE def handleEnterGatherable(self, gatherable, elapsedTime):NEWLINE if gatherable.type == Globals.Level.GatherableTypes.InvulPowerup:NEWLINE self.blinkBubbleSeq.clearToInitial()NEWLINE self.blinkBubbleSeq.start(elapsedTime)NEWLINE self.removeBubbleSeq.clearToInitial()NEWLINE self.popUpBubbleSeq.start()NEWLINE if gatherable.type not in self.activeBuffs:NEWLINE self.activeBuffs.append(gatherable.type)NEWLINE else:NEWLINE if gatherable.type == Globals.Level.GatherableTypes.Propeller:NEWLINE self.setBackpackState(Globals.Gameplay.BackpackStates.Refuel)NEWLINENEWLINE def handleDebuffPowerup(self, pickupType, elapsedTime):NEWLINE if pickupType == Globals.Level.GatherableTypes.InvulPowerup:NEWLINE self.blinkBubbleSeq.finish()NEWLINE self.popUpBubbleSeq.clearToInitial()NEWLINE self.removeBubbleSeq.start()NEWLINE if pickupType in self.activeBuffs:NEWLINE self.activeBuffs.remove(pickupType)NEWLINENEWLINE def isBuffActive(self, pickupType):NEWLINE if pickupType in self.activeBuffs:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINE def isInvulnerable(self):NEWLINE if Globals.Level.GatherableTypes.InvulPowerup in self.activeBuffs:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINE def setFuelState(self, fuelState):NEWLINE self.fuelState = fuelStateNEWLINENEWLINE def setOldFuelState(self, fuelState):NEWLINE self.oldFuelState = fuelStateNEWLINENEWLINE def hasFuelStateChanged(self):NEWLINE if self.fuelState != self.oldFuelState:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINE def updatePropellerSmoke(self):NEWLINE if not self.hasFuelStateChanged():NEWLINE returnNEWLINE if self.fuelState in [Globals.Gameplay.FuelStates.FuelNoPropeller, Globals.Gameplay.FuelStates.FuelNormal]:NEWLINE self.propellerSmoke.stop()NEWLINE else:NEWLINE if self.fuelState in [Globals.Gameplay.FuelStates.FuelVeryLow, Globals.Gameplay.FuelStates.FuelEmpty]:NEWLINE self.propellerSmoke.stop()NEWLINE self.propellerSmoke.setScale(0.25)NEWLINE self.propellerSmoke.setZ(self.toon.getHeight() + 2.5)NEWLINE self.propellerSmoke.loop(rate=48)NEWLINE else:NEWLINE if self.fuelState in [Globals.Gameplay.FuelStates.FuelLow]:NEWLINE self.propellerSmoke.stop()NEWLINE self.propellerSmoke.setScale(0.0825)NEWLINE self.propellerSmoke.setZ(self.toon.getHeight() + 2.0)NEWLINE self.propellerSmoke.loop(rate=24)NEWLINENEWLINE def resetBlades(self):NEWLINE self.setBlades(len(self.blades))NEWLINENEWLINE def setAsLegalEagleTarget(self, legalEagle):NEWLINE if legalEagle not in self.legalEaglesTargeting:NEWLINE self.legalEaglesTargeting.append(legalEagle)NEWLINENEWLINE def removeAsLegalEagleTarget(self, legalEagle):NEWLINE if legalEagle in self.legalEaglesTargeting:NEWLINE self.legalEaglesTargeting.remove(legalEagle)NEWLINENEWLINE def isLegalEagleTarget(self):NEWLINE if len(self.legalEaglesTargeting) > 0:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINE def setBlades(self, fuelState):NEWLINE if fuelState not in Globals.Gameplay.FuelStates:NEWLINE returnNEWLINE numBlades = fuelState - 1NEWLINE if len(self.activeBlades) != numBlades:NEWLINE for i in xrange(len(self.activeBlades)):NEWLINE blade = self.activeBlades.pop()NEWLINE blade.stash()NEWLINENEWLINE if numBlades > len(self.blades):NEWLINE numBlades = len(self.blades)NEWLINE if numBlades > 0:NEWLINE for i in xrange(numBlades):NEWLINE blade = self.blades[i]NEWLINE self.activeBlades.append(blade)NEWLINE blade.unstash()NEWLINENEWLINE if fuelState == Globals.Gameplay.FuelStates.FuelNoPropeller:NEWLINE for prop in self.propInstances:NEWLINE prop.hide()NEWLINENEWLINE else:NEWLINE for prop in self.propInstances:NEWLINE prop.show()NEWLINENEWLINE self.setFuelState(fuelState)NEWLINE self.updatePropellerSmoke()NEWLINE self.setOldFuelState(self.fuelState)NEWLINENEWLINE def bladeLost(self):NEWLINE if len(self.activeBlades) > 0:NEWLINE blade = self.activeBlades.pop()NEWLINE blade.stash()NEWLINE self.setFuelState(len(self.activeBlades) + 1)NEWLINE self.updatePropellerSmoke()NEWLINE self.setOldFuelState(self.fuelState)NEWLINENEWLINE def setPropellerSpinRate(self, newRate):NEWLINE self.lastPropellerSpinRate = self.propellerSpinRateNEWLINE self.propellerSpinRate = newRateNEWLINE self.notify.debug('(%s) New propeller speed:%s, old propeller speed:%s' % (self.toon.doId, self.propellerSpinRate, self.lastPropellerSpinRate))NEWLINE self.propellerSpinLerp.setPlayRate(newRate)NEWLINENEWLINE def died(self, elapsedTime):NEWLINE self.deathInterval.start(elapsedTime)NEWLINE self.propellerSmoke.stop()NEWLINENEWLINE def spawn(self, elapsedTime):NEWLINE self.spawnInterval.start(elapsedTime)NEWLINENEWLINE def resetToon(self):NEWLINE self.toon.setScale(1.0)NEWLINENEWLINE def enable(self):NEWLINE self.toon.setAnimState('Happy', 1.0)NEWLINE self.toon.setForceJumpIdle(True)NEWLINE self.toon.setSpeed(0, 0)NEWLINE self.setPropellerSpinRate(Globals.Gameplay.NormalPropSpeed)NEWLINE self.propellerSpinLerp.loop()NEWLINENEWLINE def disable(self):NEWLINE passNEWLINENEWLINE def unload(self):NEWLINE self.ignoreAll()NEWLINE if self.toon:NEWLINE self.toon.showName()NEWLINE self.backpackTextureCard.removeNode()NEWLINE del self.backpackTextureCardNEWLINE self.refuelSeq.clearToInitial()NEWLINE del self.refuelSeqNEWLINE self.pulseBubbleSeq.clearToInitial()NEWLINE del self.pulseBubbleSeqNEWLINE self.blinkBubbleLoop.clearToInitial()NEWLINE del self.blinkBubbleLoopNEWLINE self.blinkBubbleSeq.clearToInitial()NEWLINE del self.blinkBubbleSeqNEWLINE self.popUpBubbleLerp.clearToInitial()NEWLINE del self.popUpBubbleLerpNEWLINE self.popUpBubbleSeq.clearToInitial()NEWLINE del self.popUpBubbleSeqNEWLINE self.removeBubbleLerp.clearToInitial()NEWLINE del self.removeBubbleLerpNEWLINE self.removeBubbleSeq.clearToInitial()NEWLINE del self.removeBubbleSeqNEWLINE self.propellerSmoke.destroy()NEWLINE del self.propellerSmokeNEWLINE self.blinkWarningSeq.clearToInitial()NEWLINE del self.blinkWarningSeqNEWLINE self.blinkLoop.clearToInitial()NEWLINE del self.blinkLoopNEWLINE self.redTapeRing.removeNode()NEWLINE del self.redTapeRingNEWLINE self.propellerSpinLerp.clearToInitial()NEWLINE del self.propellerSpinLerpNEWLINE for prop in self.propInstances:NEWLINE prop.removeNode()NEWLINENEWLINE del self.propInstances[:]NEWLINE self.propeller.removeNode()NEWLINE del self.propellerNEWLINE for backpack in self.backpackInstances:NEWLINE backpack.removeNode()NEWLINENEWLINE del self.backpackInstances[:]NEWLINE self.backpack.removeNode()NEWLINE del self.backpackNEWLINE del self.activeBuffs[:]NEWLINE del self.legalEaglesTargeting[:]NEWLINE del self.toonNEWLINE self.toon = NoneNEWLINE if self.deathInterval:NEWLINE self.deathInterval.clearToInitial()NEWLINE self.deathInterval = NoneNEWLINE if self.spawnInterval:NEWLINE self.spawnInterval.clearToInitial()NEWLINE self.spawnInterval = NoneNEWLINE returnNEWLINENEWLINE def start(self):NEWLINE swapAvatarShadowPlacer(self.toon, self.toon.uniqueName('toonShadowPlacer'))NEWLINE self.toon.startSmooth()NEWLINENEWLINE def exit(self):NEWLINE self.toon.setForceJumpIdle(False)NEWLINE self.propellerSmoke.reparentTo(hidden)NEWLINE self.propellerSmoke.stop()NEWLINE if self.toon:NEWLINE CogdoFlyingPlayer.resetToon(self)NEWLINE self.toon.setActiveShadow(0)NEWLINE self.toon.deleteDropShadow()NEWLINE self.toon.initializeDropShadow()NEWLINE self.toon.setActiveShadow(1)NEWLINE else:NEWLINE self.notify.warning("There's no toon in offstage, this is bad!") """JSON Web Encryption utilities."""NEWLINENEWLINEimport binasciiNEWLINEimport jsonNEWLINENEWLINEfrom collections import OrderedDictNEWLINEfrom typing import Any, Dict, Iterable, List, Mapping, Optional, UnionNEWLINENEWLINEfrom marshmallow import fields, Schema, ValidationErrorNEWLINENEWLINEfrom ..wallet.util import b64_to_bytes, bytes_to_b64NEWLINENEWLINEIDENT_ENC_KEY = "encrypted_key"NEWLINEIDENT_HEADER = "header"NEWLINEIDENT_PROTECTED = "protected"NEWLINEIDENT_RECIPIENTS = "recipients"NEWLINENEWLINENEWLINEdef b64url(value: Union[bytes, str]) -> str:NEWLINE """Encode a string or bytes value as unpadded base64-URL."""NEWLINE if isinstance(value, str):NEWLINE value = value.encode("utf-8")NEWLINE return bytes_to_b64(value, urlsafe=True, pad=False)NEWLINENEWLINENEWLINEdef from_b64url(value: str) -> bytes:NEWLINE """Decode an unpadded base64-URL value."""NEWLINE try:NEWLINE return b64_to_bytes(value, urlsafe=True)NEWLINE except binascii.Error:NEWLINE raise ValidationError("Error decoding base64 value")NEWLINENEWLINENEWLINEclass B64Value(fields.Str):NEWLINE """A marshmallow-compatible wrapper for base64-URL values."""NEWLINENEWLINE def _serialize(self, value, attr, obj, **kwargs) -> Optional[str]:NEWLINE if value is None:NEWLINE return NoneNEWLINE if not isinstance(value, bytes):NEWLINE return TypeError("Expected bytes")NEWLINE return b64url(value)NEWLINENEWLINE def _deserialize(self, value, attr, data, **kwargs) -> Any:NEWLINE value = super()._deserialize(value, attr, data, **kwargs)NEWLINE return from_b64url(value)NEWLINENEWLINENEWLINEclass JweSchema(Schema):NEWLINE """JWE envelope schema."""NEWLINENEWLINE protected = fields.Str(required=True)NEWLINE unprotected = fields.Dict(required=False)NEWLINE recipients = fields.List(fields.Dict(), required=False)NEWLINE ciphertext = B64Value(required=True)NEWLINE iv = B64Value(required=True)NEWLINE tag = B64Value(required=True)NEWLINE aad = B64Value(required=False)NEWLINE # flattened:NEWLINE header = fields.Dict(required=False)NEWLINE encrypted_key = B64Value(required=False)NEWLINENEWLINENEWLINEclass JweRecipientSchema(Schema):NEWLINE """JWE recipient schema."""NEWLINENEWLINE encrypted_key = B64Value(required=True)NEWLINE header = fields.Dict(many=True, required=False)NEWLINENEWLINENEWLINEclass JweRecipient:NEWLINE """A single message recipient."""NEWLINENEWLINE def __init__(self, *, encrypted_key: bytes, header: dict = None) -> "JweRecipient":NEWLINE """Initialize the JWE recipient."""NEWLINE self.encrypted_key = encrypted_keyNEWLINE self.header = header or {}NEWLINENEWLINE @classmethodNEWLINE def deserialize(cls, entry: Mapping[str, Any]) -> "JweRecipient":NEWLINE """Deserialize a JWE recipient from a mapping."""NEWLINE vals = JweRecipientSchema().load(entry)NEWLINE return cls(**vals)NEWLINENEWLINE def serialize(self) -> dict:NEWLINE """Serialize the JWE recipient to a mapping."""NEWLINE ret = OrderedDict([("encrypted_key", b64url(self.encrypted_key))])NEWLINE if self.header:NEWLINE ret["header"] = self.headerNEWLINE return retNEWLINENEWLINENEWLINEclass JweEnvelope:NEWLINE """JWE envelope instance."""NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE protected: dict = None,NEWLINE protected_b64: bytes = None,NEWLINE unprotected: dict = None,NEWLINE ciphertext: bytes = None,NEWLINE iv: bytes = None,NEWLINE tag: bytes = None,NEWLINE aad: bytes = None,NEWLINE with_protected_recipients: bool = False,NEWLINE with_flatten_recipients: bool = True,NEWLINE ):NEWLINE """Initialize a new JWE envelope instance."""NEWLINE self.protected = protectedNEWLINE self.protected_b64 = protected_b64NEWLINE self.unprotected = unprotected or OrderedDict()NEWLINE self.ciphertext = ciphertextNEWLINE self.iv = ivNEWLINE self.tag = tagNEWLINE self.aad = aadNEWLINE self.with_protected_recipients = with_protected_recipientsNEWLINE self.with_flatten_recipients = with_flatten_recipientsNEWLINE self._recipients: List[JweRecipient] = []NEWLINENEWLINE @classmethodNEWLINE def from_json(cls, message: Union[bytes, str]) -> "JweEnvelope":NEWLINE """Decode a JWE envelope from a JSON string or bytes value."""NEWLINE try:NEWLINE return cls._deserialize(JweSchema().loads(message))NEWLINE except json.JSONDecodeError:NEWLINE raise ValidationError("Invalid JWE: not JSON")NEWLINENEWLINE @classmethodNEWLINE def deserialize(cls, message: Mapping[str, Any]) -> "JweEnvelope":NEWLINE """Deserialize a JWE envelope from a mapping."""NEWLINE return cls._deserialize(JweSchema().load(message))NEWLINENEWLINE @classmethodNEWLINE def _deserialize(cls, parsed: Mapping[str, Any]) -> "JweEnvelope":NEWLINE protected_b64 = parsed[IDENT_PROTECTED]NEWLINE try:NEWLINE protected: dict = json.loads(from_b64url(protected_b64))NEWLINE except json.JSONDecodeError:NEWLINE raise ValidationError(NEWLINE "Invalid JWE: invalid JSON for protected headers"NEWLINE ) from NoneNEWLINE unprotected = parsed.get("unprotected") or dict()NEWLINE if protected.keys() & unprotected.keys():NEWLINE raise ValidationError("Invalid JWE: duplicate header")NEWLINENEWLINE encrypted_key = protected.get(IDENT_ENC_KEY) or parsed.get(IDENT_ENC_KEY)NEWLINE recipients = NoneNEWLINE protected_recipients = FalseNEWLINE flat_recipients = FalseNEWLINENEWLINE if IDENT_RECIPIENTS in protected:NEWLINE recipients = protected.pop(IDENT_RECIPIENTS)NEWLINE if IDENT_RECIPIENTS in parsed:NEWLINE raise ValidationError("Invalid JWE: duplicate recipients block")NEWLINE protected_recipients = TrueNEWLINE elif IDENT_RECIPIENTS in parsed:NEWLINE recipients = parsed[IDENT_RECIPIENTS]NEWLINENEWLINE if IDENT_ENC_KEY in protected:NEWLINE encrypted_key = from_b64url(protected.pop(IDENT_ENC_KEY))NEWLINE header = protected.pop(IDENT_HEADER) if IDENT_HEADER in protected else NoneNEWLINE protected_recipients = TrueNEWLINE elif IDENT_ENC_KEY in parsed:NEWLINE encrypted_key = parsed[IDENT_ENC_KEY]NEWLINE header = parsed.get(IDENT_HEADER)NEWLINENEWLINE if recipients:NEWLINE if encrypted_key:NEWLINE raise ValidationError("Invalid JWE: flattened form with 'recipients'")NEWLINE recipients = [JweRecipient.deserialize(recip) for recip in recipients]NEWLINE elif encrypted_key:NEWLINE recipients = [NEWLINE JweRecipient(NEWLINE encrypted_key=encrypted_key,NEWLINE header=header,NEWLINE )NEWLINE ]NEWLINE flat_recipients = TrueNEWLINE else:NEWLINE raise ValidationError("Invalid JWE: no recipients")NEWLINENEWLINE inst = cls(NEWLINE protected=protected,NEWLINE protected_b64=protected_b64,NEWLINE unprotected=unprotected,NEWLINE ciphertext=parsed["ciphertext"],NEWLINE iv=parsed.get("iv"),NEWLINE tag=parsed["tag"],NEWLINE aad=parsed.get("aad"),NEWLINE with_protected_recipients=protected_recipients,NEWLINE with_flatten_recipients=flat_recipients,NEWLINE )NEWLINE all_h = protected.keys() | unprotected.keys()NEWLINE for recip in recipients:NEWLINE if recip.header and recip.header.keys() & all_h:NEWLINE raise ValidationError("Invalid JWE: duplicate header")NEWLINE inst.add_recipient(recip)NEWLINENEWLINE return instNEWLINENEWLINE def serialize(self) -> dict:NEWLINE """Serialize the JWE envelope to a mapping."""NEWLINE if self.protected_b64 is None:NEWLINE raise ValidationError("Missing protected: use set_protected")NEWLINE if self.ciphertext is None:NEWLINE raise ValidationError("Missing ciphertext for JWE")NEWLINE if self.iv is None:NEWLINE raise ValidationError("Missing iv (nonce) for JWE")NEWLINE if self.tag is None:NEWLINE raise ValidationError("Missing tag for JWE")NEWLINE env = OrderedDict()NEWLINE env["protected"] = self.protected_b64NEWLINE if self.unprotected:NEWLINE env["unprotected"] = self.unprotected.copy()NEWLINE if not self.with_protected_recipients:NEWLINE recipients = self.recipients_jsonNEWLINE if self.with_flatten_recipients and len(recipients) == 1:NEWLINE for k in recipients[0]:NEWLINE env[k] = recipients[0][k]NEWLINE elif recipients:NEWLINE env[IDENT_RECIPIENTS] = recipientsNEWLINE else:NEWLINE raise ValidationError("Missing message recipients")NEWLINE env["iv"] = b64url(self.iv)NEWLINE env["ciphertext"] = b64url(self.ciphertext)NEWLINE env["tag"] = b64url(self.tag)NEWLINE if self.aad:NEWLINE env["aad"] = b64url(self.aad)NEWLINE return envNEWLINENEWLINE def to_json(self) -> str:NEWLINE """Serialize the JWE envelope to a JSON string."""NEWLINE return json.dumps(self.serialize())NEWLINENEWLINE def add_recipient(self, recip: JweRecipient):NEWLINE """Add a recipient to the JWE envelope."""NEWLINE self._recipients.append(recip)NEWLINENEWLINE def set_protected(NEWLINE self,NEWLINE protected: Mapping[str, Any],NEWLINE ):NEWLINE """Set the protected headers of the JWE envelope."""NEWLINE protected = OrderedDict(protected.items())NEWLINE if self.with_protected_recipients:NEWLINE recipients = self.recipients_jsonNEWLINE if self.with_flatten_recipients and len(recipients) == 1:NEWLINE protected.update(recipients[0])NEWLINE elif recipients:NEWLINE protected[IDENT_RECIPIENTS] = recipientsNEWLINE else:NEWLINE raise ValidationError("Missing message recipients")NEWLINE self.protected_b64 = b64url(json.dumps(protected))NEWLINENEWLINE @propertyNEWLINE def protected_bytes(self) -> bytes:NEWLINE """Access the protected data encoded as bytes.NEWLINENEWLINE This value is used in the additional authenticated data when encrypting.NEWLINE """NEWLINE return (NEWLINE self.protected_b64.encode("utf-8")NEWLINE if self.protected_b64 is not NoneNEWLINE else NoneNEWLINE )NEWLINENEWLINE def set_payload(self, ciphertext: bytes, iv: bytes, tag: bytes, aad: bytes = None):NEWLINE """Set the payload of the JWE envelope."""NEWLINE self.ciphertext = ciphertextNEWLINE self.iv = ivNEWLINE self.tag = tagNEWLINE self.aad = aadNEWLINENEWLINE @propertyNEWLINE def recipients(self) -> Iterable[JweRecipient]:NEWLINE """Accessor for an iterator over the JWE recipients.NEWLINENEWLINE The headers for each recipient include protected and unprotected headers from theNEWLINE outer envelope.NEWLINE """NEWLINE header = self.protected.copy()NEWLINE header.update(self.unprotected)NEWLINE for recip in self._recipients:NEWLINE if recip.header:NEWLINE recip_h = header.copy()NEWLINE recip_h.update(recip.header)NEWLINE yield JweRecipient(encrypted_key=recip.encrypted_key, header=recip_h)NEWLINE else:NEWLINE yield JweRecipient(encrypted_key=recip.encrypted_key, header=header)NEWLINENEWLINE @propertyNEWLINE def recipients_json(self) -> List[Dict[str, Any]]:NEWLINE """Encode the current recipients for JSON."""NEWLINE return [recip.serialize() for recip in self._recipients]NEWLINENEWLINE @propertyNEWLINE def recipient_key_ids(self) -> Iterable[JweRecipient]:NEWLINE """Accessor for an iterator over the JWE recipient key identifiers."""NEWLINE for recip in self._recipients:NEWLINE if recip.header and "kid" in recip.header:NEWLINE yield recip.header["kid"]NEWLINENEWLINE def get_recipient(self, kid: str) -> JweRecipient:NEWLINE """Find a recipient by key ID."""NEWLINE for recip in self._recipients:NEWLINE if recip.header and recip.header.get("kid") == kid:NEWLINE header = self.protected.copy()NEWLINE header.update(self.unprotected)NEWLINE header.update(recip.header)NEWLINE return JweRecipient(encrypted_key=recip.encrypted_key, header=header)NEWLINENEWLINE @propertyNEWLINE def combined_aad(self) -> bytes:NEWLINE """Accessor for the additional authenticated data."""NEWLINE aad = self.protected_bytesNEWLINE if self.aad:NEWLINE aad += b"." + b64url(self.aad).encode("utf-8")NEWLINE return aadNEWLINE #NEWLINE# Copyright 2019 The FATE Authors. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE#NEWLINENEWLINEimport argparseNEWLINENEWLINEfrom pipeline.backend.pipeline import PipeLineNEWLINEfrom pipeline.component import DataTransformNEWLINEfrom pipeline.component import HeteroPoissonNEWLINEfrom pipeline.component import IntersectionNEWLINEfrom pipeline.component import ReaderNEWLINEfrom pipeline.interface import DataNEWLINENEWLINEfrom pipeline.utils.tools import load_job_configNEWLINENEWLINENEWLINEdef main(config="../../config.yaml", namespace=""):NEWLINE # obtain configNEWLINE if isinstance(config, str):NEWLINE config = load_job_config(config)NEWLINE parties = config.partiesNEWLINE guest = parties.guest[0]NEWLINE host = parties.host[0]NEWLINE arbiter = parties.arbiter[0]NEWLINENEWLINE guest_train_data = {"name": "dvisits_hetero_guest", "namespace": f"experiment{namespace}"}NEWLINE host_train_data = {"name": "dvisits_hetero_host", "namespace": f"experiment{namespace}"}NEWLINENEWLINE pipeline = PipeLine().set_initiator(role='guest', party_id=guest).set_roles(guest=guest, host=host, arbiter=arbiter)NEWLINENEWLINE reader_0 = Reader(name="reader_0")NEWLINE reader_0.get_party_instance(role='guest', party_id=guest).component_param(table=guest_train_data)NEWLINE reader_0.get_party_instance(role='host', party_id=host).component_param(table=host_train_data)NEWLINENEWLINE data_transform_0 = DataTransform(name="data_transform_0")NEWLINE data_transform_0.get_party_instance(role='guest', party_id=guest).component_param(with_label=True, output_format="dense",NEWLINE label_name="doctorco", label_type="float",)NEWLINE data_transform_0.get_party_instance(role='host', party_id=host).component_param(with_label=False)NEWLINENEWLINE intersection_0 = Intersection(name="intersection_0")NEWLINE hetero_poisson_0 = HeteroPoisson(name="hetero_poisson_0", early_stop="diff", max_iter=5,NEWLINE penalty="None", optimizer="sgd", tol=0.001,NEWLINE batch_size=-1, learning_rate=0.15, decay=0.0,NEWLINE decay_sqrt=False, alpha=0.01,NEWLINE init_param={"init_method": "zeros"},NEWLINE stepwise_param={"score_name": "AIC", "direction": "both",NEWLINE "need_stepwise": True, "max_step": 1, "nvmin": 2NEWLINE })NEWLINE pipeline.add_component(reader_0)NEWLINE pipeline.add_component(data_transform_0, data=Data(data=reader_0.output.data))NEWLINE pipeline.add_component(intersection_0, data=Data(data=data_transform_0.output.data))NEWLINE pipeline.add_component(hetero_poisson_0, data=Data(train_data=intersection_0.output.data))NEWLINENEWLINE pipeline.compile()NEWLINENEWLINE pipeline.fit()NEWLINENEWLINE # print(pipeline.get_component("hetero_poisson_0").get_summary())NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE parser = argparse.ArgumentParser("PIPELINE DEMO")NEWLINE parser.add_argument("-config", type=str,NEWLINE help="config file")NEWLINE args = parser.parse_args()NEWLINE if args.config is not None:NEWLINE main(args.config)NEWLINE else:NEWLINE main() # -*- coding: utf-8 -*-NEWLINE#NEWLINE# Copyright (C) 2005-2007 Christopher Lenz NEWLINE# Copyright (C) 2007-2010 Edgewall SoftwareNEWLINE# All rights reserved.NEWLINE#NEWLINE# This software is licensed as described in the file COPYING, whichNEWLINE# you should have received as part of this distribution. The termsNEWLINE# are also available at http://bitten.edgewall.org/wiki/License.NEWLINENEWLINE"""Implementation of the Bitten web interface."""NEWLINENEWLINEimport posixpathNEWLINEimport reNEWLINEimport timeNEWLINEfrom StringIO import StringIONEWLINEfrom datetime import datetimeNEWLINENEWLINEimport pkg_resourcesNEWLINEfrom genshi.builder import tagNEWLINEfrom trac.attachment import AttachmentModule, AttachmentNEWLINEfrom trac.core import *NEWLINEfrom trac.config import OptionNEWLINEfrom trac.mimeview.api import ContextNEWLINEfrom trac.perm import PermissionErrorNEWLINEfrom trac.resource import Resource, get_resource_urlNEWLINEfrom trac.timeline import ITimelineEventProviderNEWLINEfrom trac.util import escape, pretty_timedelta, format_datetime, shorten_line, \NEWLINE Markup, arityNEWLINEfrom trac.util.datefmt import to_timestamp, to_datetime, utcNEWLINEfrom trac.util.html import htmlNEWLINEfrom trac.web import IRequestHandler, IRequestFilter, HTTPNotFoundNEWLINEfrom trac.web.chrome import INavigationContributor, ITemplateProvider, \NEWLINE add_link, add_stylesheet, add_ctxtnav, \NEWLINE prevnext_nav, add_script, add_warningNEWLINEfrom trac.versioncontrol import NoSuchChangeset, NoSuchNodeNEWLINEfrom trac.wiki import wiki_to_html, wiki_to_onelinerNEWLINEfrom bitten.api import ILogFormatter, IReportChartGenerator, IReportSummarizerNEWLINEfrom bitten.master import BuildMasterNEWLINEfrom bitten.model import BuildConfig, TargetPlatform, Build, BuildStep, \NEWLINE BuildLog, ReportNEWLINEfrom bitten.queue import collect_changesNEWLINEfrom bitten.util.repository import get_repos, get_chgset_resource, display_revNEWLINEfrom bitten.util import jsonNEWLINENEWLINE_status_label = {Build.PENDING: 'pending',NEWLINE Build.IN_PROGRESS: 'in progress',NEWLINE Build.SUCCESS: 'completed',NEWLINE Build.FAILURE: 'failed'}NEWLINE_status_title = {Build.PENDING: 'Pending',NEWLINE Build.IN_PROGRESS: 'In Progress',NEWLINE Build.SUCCESS: 'Success',NEWLINE Build.FAILURE: 'Failure'}NEWLINE_step_status_label = {BuildStep.SUCCESS: 'success',NEWLINE BuildStep.FAILURE: 'failed',NEWLINE BuildStep.IN_PROGRESS: 'in progress'}NEWLINENEWLINEdef _get_build_data(env, req, build, repos_name=None):NEWLINE chgset_url = ''NEWLINE if repos_name:NEWLINE chgset_resource = get_chgset_resource(env, repos_name, build.rev)NEWLINE chgset_url = get_resource_url(env, chgset_resource, req.href)NEWLINE platform = TargetPlatform.fetch(env, build.platform)NEWLINE data = {'id': build.id, 'name': build.slave, 'rev': build.rev,NEWLINE 'status': _status_label[build.status],NEWLINE 'platform': getattr(platform, 'name', 'unknown'),NEWLINE 'cls': _status_label[build.status].replace(' ', '-'),NEWLINE 'href': req.href.build(build.config, build.id),NEWLINE 'chgset_href': chgset_url}NEWLINE if build.started:NEWLINE data['started'] = format_datetime(build.started)NEWLINE data['started_delta'] = pretty_timedelta(build.started)NEWLINE data['duration'] = pretty_timedelta(build.started)NEWLINE if build.stopped:NEWLINE data['stopped'] = format_datetime(build.stopped)NEWLINE data['stopped_delta'] = pretty_timedelta(build.stopped)NEWLINE data['duration'] = pretty_timedelta(build.stopped, build.started)NEWLINE data['slave'] = {NEWLINE 'name': build.slave,NEWLINE 'ipnr': build.slave_info.get(Build.IP_ADDRESS),NEWLINE 'os_name': build.slave_info.get(Build.OS_NAME),NEWLINE 'os_family': build.slave_info.get(Build.OS_FAMILY),NEWLINE 'os_version': build.slave_info.get(Build.OS_VERSION),NEWLINE 'machine': build.slave_info.get(Build.MACHINE),NEWLINE 'processor': build.slave_info.get(Build.PROCESSOR)NEWLINE }NEWLINE return dataNEWLINENEWLINEdef _has_permission(perm, repos, path, rev=None, raise_error=False):NEWLINE if hasattr(repos, 'authz'):NEWLINE if not repos.authz.has_permission(path):NEWLINE if not raise_error:NEWLINE return FalseNEWLINE repos.authz.assert_permission(path)NEWLINE else:NEWLINE node = repos.get_node(path, rev)NEWLINE if not node.can_view(perm):NEWLINE if not raise_error:NEWLINE return FalseNEWLINE raise PermissionError('BROWSER_VIEW', node.resource)NEWLINE return TrueNEWLINENEWLINEclass BittenChrome(Component):NEWLINE """Provides the Bitten templates and static resources."""NEWLINENEWLINE implements(INavigationContributor, ITemplateProvider)NEWLINENEWLINE # INavigationContributor methodsNEWLINENEWLINE def get_active_navigation_item(self, req):NEWLINE passNEWLINENEWLINE def get_navigation_items(self, req):NEWLINE """Return the navigation item for access the build status overview fromNEWLINE the Trac navigation bar."""NEWLINE if 'BUILD_VIEW' in req.perm:NEWLINE status = ''NEWLINE if BuildMaster(self.env).quick_status:NEWLINE for config in BuildConfig.select(self.env,NEWLINE include_inactive=False):NEWLINE prev_rev = NoneNEWLINE for platform, rev, build in collect_changes(config, req.authname):NEWLINE if rev != prev_rev:NEWLINE if prev_rev is not None:NEWLINE breakNEWLINE prev_rev = revNEWLINE if build:NEWLINE build_data = _get_build_data(self.env, req, build)NEWLINE if build_data['status'] == 'failed':NEWLINE status='bittenfailed'NEWLINE breakNEWLINE if build_data['status'] == 'in progress':NEWLINE status='bitteninprogress'NEWLINE elif not status:NEWLINE if (build_data['status'] == 'completed'):NEWLINE status='bittencompleted'NEWLINE if not status:NEWLINE status='bittenpending'NEWLINE yield ('mainnav', 'build',NEWLINE tag.a('Build Status', href=req.href.build(), accesskey=5,NEWLINE class_=status))NEWLINENEWLINE # ITemplatesProvider methodsNEWLINENEWLINE def get_htdocs_dirs(self):NEWLINE """Return the directories containing static resources."""NEWLINE return [('bitten', pkg_resources.resource_filename(__name__, 'htdocs'))]NEWLINENEWLINE def get_templates_dirs(self):NEWLINE """Return the directories containing templates."""NEWLINE return [pkg_resources.resource_filename(__name__, 'templates')]NEWLINENEWLINENEWLINEclass BuildConfigController(Component):NEWLINE """Implements the web interface for build configurations."""NEWLINENEWLINE implements(IRequestHandler, IRequestFilter, INavigationContributor)NEWLINENEWLINE # Configuration optionsNEWLINENEWLINE chart_style = Option('bitten', 'chart_style', 'height: 220px; width: 220px;', doc=NEWLINE """Style attribute for charts. Mostly useful for setting the height and width.""")NEWLINENEWLINE # INavigationContributor methodsNEWLINENEWLINE def get_active_navigation_item(self, req):NEWLINE return 'build'NEWLINENEWLINE def get_navigation_items(self, req):NEWLINE return []NEWLINENEWLINE # IRequestHandler methodsNEWLINENEWLINE def match_request(self, req):NEWLINE match = re.match(r'/build(?:/([\w.-]+))?/?$', req.path_info)NEWLINE if match:NEWLINE if match.group(1):NEWLINE req.args['config'] = match.group(1)NEWLINE return TrueNEWLINENEWLINE def process_request(self, req):NEWLINE req.perm.require('BUILD_VIEW')NEWLINENEWLINE action = req.args.get('action')NEWLINE view = req.args.get('view')NEWLINE config = req.args.get('config')NEWLINENEWLINE if config:NEWLINE data = self._render_config(req, config)NEWLINE elif view == 'inprogress':NEWLINE data = self._render_inprogress(req)NEWLINE else:NEWLINE data = self._render_overview(req)NEWLINENEWLINE add_stylesheet(req, 'bitten/bitten.css')NEWLINE return 'bitten_config.html', data, NoneNEWLINENEWLINE # IRequestHandler methodsNEWLINENEWLINE def pre_process_request(self, req, handler):NEWLINE return handlerNEWLINENEWLINE def post_process_request(self, req, template, data, content_type):NEWLINE if template:NEWLINE add_stylesheet(req, 'bitten/bitten.css')NEWLINENEWLINE return template, data, content_typeNEWLINENEWLINE # Internal methodsNEWLINENEWLINE def _render_overview(self, req):NEWLINE data = {'title': 'Build Status'}NEWLINE show_all = FalseNEWLINE if req.args.get('show') == 'all':NEWLINE show_all = TrueNEWLINE data['show_all'] = show_allNEWLINENEWLINE configs = []NEWLINE for config in BuildConfig.select(self.env, include_inactive=show_all):NEWLINE repos_name, repos, repos_path = get_repos(self.env, config.path,NEWLINE req.authname)NEWLINE rev = config.max_rev or repos.youngest_revNEWLINE try:NEWLINE if not _has_permission(req.perm, repos, repos_path, rev=rev):NEWLINE continueNEWLINE except NoSuchNode:NEWLINE add_warning(req, "Configuration '%s' points to non-existing "NEWLINE "path '/%s' at revision '%s'. Configuration skipped." \NEWLINE % (config.name, config.path, rev))NEWLINE continueNEWLINENEWLINE description = config.descriptionNEWLINE if description:NEWLINE description = wiki_to_html(description, self.env, req)NEWLINENEWLINE platforms_data = []NEWLINE for platform in TargetPlatform.select(self.env, config=config.name):NEWLINE pd = { 'name': platform.name,NEWLINE 'id': platform.id,NEWLINE 'builds_pending': len(list(Build.select(self.env,NEWLINE config=config.name, status=Build.PENDING,NEWLINE platform=platform.id))),NEWLINE 'builds_inprogress': len(list(Build.select(self.env,NEWLINE config=config.name, status=Build.IN_PROGRESS,NEWLINE platform=platform.id)))NEWLINE }NEWLINE platforms_data.append(pd)NEWLINENEWLINE config_data = {NEWLINE 'name': config.name, 'label': config.label or config.name,NEWLINE 'active': config.active, 'path': config.path,NEWLINE 'description': description,NEWLINE 'builds_pending' : len(list(Build.select(self.env,NEWLINE config=config.name,NEWLINE status=Build.PENDING))),NEWLINE 'builds_inprogress' : len(list(Build.select(self.env,NEWLINE config=config.name,NEWLINE status=Build.IN_PROGRESS))),NEWLINE 'href': req.href.build(config.name),NEWLINE 'builds': [],NEWLINE 'platforms': platforms_dataNEWLINE }NEWLINE configs.append(config_data)NEWLINE if not config.active:NEWLINE continueNEWLINENEWLINE prev_rev = NoneNEWLINE for platform, rev, build in collect_changes(config, req.authname):NEWLINE if rev != prev_rev:NEWLINE if prev_rev is None:NEWLINE chgset = repos.get_changeset(rev)NEWLINE chgset_resource = get_chgset_resource(self.env, NEWLINE repos_name, rev)NEWLINE config_data['youngest_rev'] = {NEWLINE 'id': rev,NEWLINE 'href': get_resource_url(self.env, chgset_resource,NEWLINE req.href),NEWLINE 'display_rev': display_rev(repos, rev),NEWLINE 'author': chgset.author or 'anonymous',NEWLINE 'date': format_datetime(chgset.date),NEWLINE 'message': wiki_to_oneliner(NEWLINE shorten_line(chgset.message), self.env, req=req)NEWLINE }NEWLINE else:NEWLINE breakNEWLINE prev_rev = revNEWLINE if build:NEWLINE build_data = _get_build_data(self.env, req, build, repos_name)NEWLINE build_data['platform'] = platform.nameNEWLINE config_data['builds'].append(build_data)NEWLINE else:NEWLINE config_data['builds'].append({NEWLINE 'platform': platform.name, 'status': 'pending'NEWLINE })NEWLINENEWLINE data['configs'] = sorted(configs, key=lambda x:x['label'].lower())NEWLINE data['page_mode'] = 'overview'NEWLINENEWLINE in_progress_builds = Build.select(self.env, status=Build.IN_PROGRESS)NEWLINE pending_builds = Build.select(self.env, status=Build.PENDING)NEWLINENEWLINE data['builds_pending'] = len(list(pending_builds))NEWLINE data['builds_inprogress'] = len(list(in_progress_builds))NEWLINENEWLINE add_link(req, 'views', req.href.build(view='inprogress'),NEWLINE 'In Progress Builds')NEWLINE add_ctxtnav(req, 'In Progress Builds',NEWLINE req.href.build(view='inprogress'))NEWLINE return dataNEWLINENEWLINE def _render_inprogress(self, req):NEWLINE data = {'title': 'In Progress Builds',NEWLINE 'page_mode': 'view-inprogress'}NEWLINENEWLINE configs = []NEWLINE for config in BuildConfig.select(self.env, include_inactive=False):NEWLINE repos_name, repos, repos_path = get_repos(self.env, config.path,NEWLINE req.authname)NEWLINE rev = config.max_rev or repos.youngest_revNEWLINE try:NEWLINE if not _has_permission(req.perm, repos, repos_path, rev=rev):NEWLINE continueNEWLINE except NoSuchNode:NEWLINE add_warning(req, "Configuration '%s' points to non-existing "NEWLINE "path '/%s' at revision '%s'. Configuration skipped." \NEWLINE % (config.name, config.path, rev))NEWLINE continueNEWLINENEWLINE self.log.debug(config.name)NEWLINE if not config.active:NEWLINE continueNEWLINENEWLINE in_progress_builds = Build.select(self.env, config=config.name,NEWLINE status=Build.IN_PROGRESS)NEWLINENEWLINE current_builds = 0NEWLINE builds = []NEWLINE # sort correctly by revision.NEWLINE for build in sorted(in_progress_builds,NEWLINE cmp=lambda x, y: int(y.rev_time) - int(x.rev_time)):NEWLINE rev = build.revNEWLINE build_data = _get_build_data(self.env, req, build, repos_name)NEWLINE build_data['rev'] = revNEWLINE build_data['rev_href'] = build_data['chgset_href']NEWLINE platform = TargetPlatform.fetch(self.env, build.platform)NEWLINE build_data['platform'] = platform.nameNEWLINE build_data['steps'] = []NEWLINENEWLINE for step in BuildStep.select(self.env, build=build.id):NEWLINE build_data['steps'].append({NEWLINE 'name': step.name,NEWLINE 'description': step.description,NEWLINE 'duration': to_datetime(step.stopped or int(time.time()), utc) - \NEWLINE to_datetime(step.started, utc),NEWLINE 'status': _step_status_label[step.status],NEWLINE 'cls': _step_status_label[step.status].replace(' ', '-'),NEWLINE 'errors': step.errors,NEWLINE 'href': build_data['href'] + '#step_' + step.nameNEWLINE })NEWLINENEWLINE builds.append(build_data)NEWLINE current_builds += 1NEWLINENEWLINE if current_builds == 0:NEWLINE continueNEWLINENEWLINE description = config.descriptionNEWLINE if description:NEWLINE description = wiki_to_html(description, self.env, req)NEWLINE configs.append({NEWLINE 'name': config.name, 'label': config.label or config.name,NEWLINE 'active': config.active, 'path': config.path,NEWLINE 'description': description,NEWLINE 'href': req.href.build(config.name),NEWLINE 'builds': buildsNEWLINE })NEWLINENEWLINE data['configs'] = sorted(configs, key=lambda x:x['label'].lower())NEWLINE return dataNEWLINENEWLINE def _render_config(self, req, config_name):NEWLINENEWLINE config = BuildConfig.fetch(self.env, config_name)NEWLINE if not config:NEWLINE raise HTTPNotFound("Build configuration '%s' does not exist." \NEWLINE % config_name)NEWLINENEWLINE repos_name, repos, repos_path = get_repos(self.env, config.path,NEWLINE req.authname)NEWLINENEWLINE rev = config.max_rev or repos.youngest_revNEWLINE try:NEWLINE _has_permission(req.perm, repos, repos_path, rev=rev,NEWLINE raise_error=True)NEWLINE except NoSuchNode:NEWLINE raise TracError("Permission checking against repository path %s "NEWLINE "at revision %s failed." % (config.path, rev))NEWLINENEWLINE data = {'title': 'Build Configuration "%s"' \NEWLINE % config.label or config.name,NEWLINE 'page_mode': 'view_config'}NEWLINE add_link(req, 'up', req.href.build(), 'Build Status')NEWLINE description = config.descriptionNEWLINE if description:NEWLINE description = wiki_to_html(description, self.env, req)NEWLINENEWLINE pending_builds = list(Build.select(self.env,NEWLINE config=config.name, status=Build.PENDING))NEWLINE inprogress_builds = list(Build.select(self.env,NEWLINE config=config.name, status=Build.IN_PROGRESS))NEWLINENEWLINE min_chgset_url = ''NEWLINE if config.min_rev:NEWLINE min_chgset_resource = get_chgset_resource(self.env, repos_name,NEWLINE config.min_rev)NEWLINE min_chgset_url = get_resource_url(self.env, min_chgset_resource,NEWLINE req.href),NEWLINE max_chgset_url = ''NEWLINE if config.max_rev:NEWLINE max_chgset_resource = get_chgset_resource(self.env, repos_name,NEWLINE config.max_rev)NEWLINE max_chgset_url = get_resource_url(self.env, max_chgset_resource,NEWLINE req.href),NEWLINENEWLINE data['config'] = {NEWLINE 'name': config.name, 'label': config.label, 'path': config.path,NEWLINE 'min_rev': config.min_rev,NEWLINE 'min_rev_href': min_chgset_url,NEWLINE 'max_rev': config.max_rev,NEWLINE 'max_rev_href': max_chgset_url,NEWLINE 'active': config.active, 'description': description,NEWLINE 'browser_href': req.href.browser(config.path),NEWLINE 'builds_pending' : len(pending_builds),NEWLINE 'builds_inprogress' : len(inprogress_builds)NEWLINE }NEWLINENEWLINE context = Context.from_request(req, config.resource)NEWLINE data['context'] = contextNEWLINE data['config']['attachments'] = AttachmentModule(self.env).attachment_data(context)NEWLINENEWLINE platforms = list(TargetPlatform.select(self.env, config=config_name))NEWLINE data['config']['platforms'] = [NEWLINE { 'name': platform.name,NEWLINE 'id': platform.id,NEWLINE 'builds_pending': len(list(Build.select(self.env,NEWLINE config=config.name,NEWLINE status=Build.PENDING,NEWLINE platform=platform.id))),NEWLINE 'builds_inprogress': len(list(Build.select(self.env,NEWLINE config=config.name,NEWLINE status=Build.IN_PROGRESS,NEWLINE platform=platform.id)))NEWLINE }NEWLINE for platform in platformsNEWLINE ]NEWLINENEWLINE has_reports = FalseNEWLINE for report in Report.select(self.env, config=config.name):NEWLINE has_reports = TrueNEWLINE breakNEWLINENEWLINE if has_reports:NEWLINE chart_generators = []NEWLINE report_categories = list(self._report_categories_for_config(config))NEWLINE for generator in ReportChartController(self.env).generators:NEWLINE for category in generator.get_supported_categories():NEWLINE if category in report_categories:NEWLINE chart_generators.append({NEWLINE 'href': req.href.build(config.name, 'chart/' + category),NEWLINE 'category': category,NEWLINE 'style': self.config.get('bitten', 'chart_style'),NEWLINE })NEWLINE data['config']['charts'] = chart_generatorsNEWLINENEWLINE page = max(1, int(req.args.get('page', 1)))NEWLINE more = FalseNEWLINE data['page_number'] = pageNEWLINENEWLINE builds_per_page = 12 * len(platforms)NEWLINE idx = 0NEWLINE builds = {}NEWLINE revisions = []NEWLINE build_order = []NEWLINE for platform, rev, build in collect_changes(config,authname=req.authname):NEWLINE if idx >= page * builds_per_page:NEWLINE more = TrueNEWLINE breakNEWLINE elif idx >= (page - 1) * builds_per_page:NEWLINE if rev not in builds:NEWLINE revisions.append(rev)NEWLINE builds.setdefault(rev, {})NEWLINE chgset_resource = get_chgset_resource(self.env, repos_name, rev)NEWLINE builds[rev].setdefault('href', get_resource_url(self.env,NEWLINE chgset_resource, req.href))NEWLINE build_order.append((rev, repos.get_changeset(rev).date))NEWLINE builds[rev].setdefault('display_rev', display_rev(repos, rev))NEWLINE if build and build.status != Build.PENDING:NEWLINE build_data = _get_build_data(self.env, req, build)NEWLINE build_data['steps'] = []NEWLINE for step in BuildStep.select(self.env, build=build.id):NEWLINE build_data['steps'].append({NEWLINE 'name': step.name,NEWLINE 'description': step.description,NEWLINE 'duration': to_datetime(step.stopped or int(time.time()), utc) - \NEWLINE to_datetime(step.started, utc),NEWLINE 'status': _step_status_label[step.status],NEWLINE 'cls': _step_status_label[step.status].replace(' ', '-'),NEWLINENEWLINE 'errors': step.errors,NEWLINE 'href': build_data['href'] + '#step_' + step.nameNEWLINE })NEWLINE builds[rev][platform.id] = build_dataNEWLINE idx += 1NEWLINE data['config']['build_order'] = [r[0] for r in sorted(build_order,NEWLINE key=lambda x: x[1],NEWLINE reverse=True)]NEWLINE data['config']['builds'] = buildsNEWLINE data['config']['revisions'] = revisionsNEWLINENEWLINE if page > 1:NEWLINE if page == 2:NEWLINE prev_href = req.href.build(config.name)NEWLINE else:NEWLINE prev_href = req.href.build(config.name, page=page - 1)NEWLINE add_link(req, 'prev', prev_href, 'Previous Page')NEWLINE if more:NEWLINE next_href = req.href.build(config.name, page=page + 1)NEWLINE add_link(req, 'next', next_href, 'Next Page')NEWLINE if arity(prevnext_nav) == 4: # Trac 0.12 compat, see #450NEWLINE prevnext_nav(req, 'Previous Page', 'Next Page')NEWLINE else:NEWLINE prevnext_nav (req, 'Page')NEWLINE return dataNEWLINENEWLINE def _report_categories_for_config(self, config):NEWLINE """Yields the categories of reports that exist for active buildsNEWLINE of this configuration.NEWLINE """NEWLINENEWLINENEWLINE for (category, ) in self.env.db_query("""SELECT DISTINCT report.category as categoryNEWLINEFROM bitten_build AS buildNEWLINEJOIN bitten_report AS report ON (report.build=build.id)NEWLINEWHERE build.config=%s AND build.rev_time >= %s AND build.rev_time <= %s""",NEWLINE (config.name,NEWLINE config.min_rev_time(self.env),NEWLINE config.max_rev_time(self.env))):NEWLINE yield categoryNEWLINENEWLINENEWLINEclass BuildController(Component):NEWLINE """Renders the build page."""NEWLINE implements(INavigationContributor, IRequestHandler, ITimelineEventProvider)NEWLINENEWLINE log_formatters = ExtensionPoint(ILogFormatter)NEWLINE report_summarizers = ExtensionPoint(IReportSummarizer)NEWLINENEWLINE # INavigationContributor methodsNEWLINENEWLINE def get_active_navigation_item(self, req):NEWLINE return 'build'NEWLINENEWLINE def get_navigation_items(self, req):NEWLINE return []NEWLINENEWLINE # IRequestHandler methodsNEWLINENEWLINE def match_request(self, req):NEWLINE match = re.match(r'/build/([\w.-]+)/(\d+)', req.path_info)NEWLINE if match:NEWLINE if match.group(1):NEWLINE req.args['config'] = match.group(1)NEWLINE if match.group(2):NEWLINE req.args['id'] = match.group(2)NEWLINE return TrueNEWLINENEWLINE def process_request(self, req):NEWLINE req.perm.require('BUILD_VIEW')NEWLINENEWLINE build_id = int(req.args.get('id'))NEWLINE build = Build.fetch(self.env, build_id)NEWLINE if not build:NEWLINE raise HTTPNotFound("Build '%s' does not exist." \NEWLINE % build_id)NEWLINENEWLINE if req.method == 'POST':NEWLINE if req.args.get('action') == 'invalidate':NEWLINE self._do_invalidate(req, build)NEWLINE req.redirect(req.href.build(build.config, build.id))NEWLINENEWLINE add_link(req, 'up', req.href.build(build.config),NEWLINE 'Build Configuration')NEWLINE data = {'title': 'Build %s - %s' % (build_id,NEWLINE _status_title[build.status]),NEWLINE 'page_mode': 'view_build',NEWLINE 'build': {}}NEWLINE config = BuildConfig.fetch(self.env, build.config)NEWLINE data['build']['config'] = {NEWLINE 'name': config.label or config.name,NEWLINE 'href': req.href.build(config.name)NEWLINE }NEWLINENEWLINE context = Context.from_request(req, build.resource)NEWLINE data['context'] = contextNEWLINE data['build']['attachments'] = AttachmentModule(self.env).attachment_data(context)NEWLINENEWLINE formatters = []NEWLINE for formatter in self.log_formatters:NEWLINE formatters.append(formatter.get_formatter(req, build))NEWLINENEWLINE summarizers = {} # keyed by report typeNEWLINE for summarizer in self.report_summarizers:NEWLINE categories = summarizer.get_supported_categories()NEWLINE summarizers.update(dict([(cat, summarizer) for cat in categories]))NEWLINENEWLINE repos_name, repos, repos_path = get_repos(self.env, config.path,NEWLINE req.authname)NEWLINENEWLINE _has_permission(req.perm, repos, repos_path, rev=build.rev, raise_error=True)NEWLINENEWLINE data['build'].update(_get_build_data(self.env, req, build, repos_name))NEWLINE steps = []NEWLINE for step in BuildStep.select(self.env, build=build.id):NEWLINE steps.append({NEWLINE 'name': step.name, 'description': step.description,NEWLINE 'duration': pretty_timedelta(step.started, step.stopped or int(time.time())),NEWLINE 'status': _step_status_label[step.status],NEWLINE 'cls': _step_status_label[step.status].replace(' ', '-'),NEWLINE 'errors': step.errors,NEWLINE 'log': self._render_log(req, build, formatters, step),NEWLINE 'reports': self._render_reports(req, config, build, summarizers,NEWLINE step)NEWLINE })NEWLINE data['build']['steps'] = stepsNEWLINE data['build']['can_delete'] = ('BUILD_DELETE' in req.perm \NEWLINE and build.status != build.PENDING)NEWLINENEWLINE chgset = repos.get_changeset(build.rev)NEWLINE data['build']['chgset_author'] = chgset.authorNEWLINE data['build']['display_rev'] = display_rev(repos, build.rev)NEWLINENEWLINE add_script(req, 'common/js/folding.js')NEWLINE add_script(req, 'bitten/tabset.js')NEWLINE add_script(req, 'bitten/jquery.flot.js')NEWLINE add_stylesheet(req, 'bitten/bitten.css')NEWLINE return 'bitten_build.html', data, NoneNEWLINENEWLINE # ITimelineEventProvider methodsNEWLINENEWLINE def get_timeline_filters(self, req):NEWLINE if 'BUILD_VIEW' in req.perm:NEWLINE yield ('build', 'Builds')NEWLINENEWLINE def get_timeline_events(self, req, start, stop, filters):NEWLINE if 'build' not in filters:NEWLINE returnNEWLINENEWLINE # Attachments (will be rendered by attachment module)NEWLINE for event in AttachmentModule(self.env).get_timeline_events(NEWLINE req, Resource('build'), start, stop):NEWLINE yield eventNEWLINENEWLINE start = to_timestamp(start)NEWLINE stop = to_timestamp(stop)NEWLINENEWLINE add_stylesheet(req, 'bitten/bitten.css')NEWLINENEWLINE with self.env.db_query as db:NEWLINE cursor = db.cursor()NEWLINE cursor.execute("SELECT b.id,b.config,c.label,c.path, b.rev,p.name,"NEWLINE "b.stopped,b.status FROM bitten_build AS b"NEWLINE " INNER JOIN bitten_config AS c ON (c.name=b.config) "NEWLINE " INNER JOIN bitten_platform AS p ON (p.id=b.platform) "NEWLINE "WHERE b.stopped>=%s AND b.stopped<=%s "NEWLINE "AND b.status IN (%s, %s) ORDER BY b.stopped",NEWLINE (start, stop, Build.SUCCESS, Build.FAILURE))NEWLINENEWLINE event_kinds = {Build.SUCCESS: 'successbuild',NEWLINE Build.FAILURE: 'failedbuild'}NEWLINENEWLINE for id_, config, label, path, rev, platform, stopped, status in cursor:NEWLINE config_object = BuildConfig.fetch(self.env, config)NEWLINE repos_name, repos, repos_path = get_repos(self.env,NEWLINE config_object.path,NEWLINE req.authname)NEWLINE if not _has_permission(req.perm, repos, repos_path, rev=rev):NEWLINE continueNEWLINE errors = []NEWLINE if status == Build.FAILURE:NEWLINE for step in BuildStep.select(self.env, build=id_,NEWLINE status=BuildStep.FAILURE):NEWLINE errors += [(step.name, error) for errorNEWLINE in step.errors]NEWLINE yield (event_kinds[status], to_datetime(stopped, utc), None,NEWLINE (id_, config, label, display_rev(repos, rev), platform,NEWLINE status, errors))NEWLINENEWLINE def render_timeline_event(self, context, field, event):NEWLINE id_, config, label, rev, platform, status, errors = event[3]NEWLINENEWLINE if field == 'url':NEWLINE return context.href.build(config, id_)NEWLINENEWLINE elif field == 'title':NEWLINE return tag('Build of ', tag.em('%s [%s]' % (label, rev)),NEWLINE ' on %s %s' % (platform, _status_label[status]))NEWLINENEWLINE elif field == 'description':NEWLINE message = ''NEWLINE if context.req.args.get('format') == 'rss':NEWLINE if errors:NEWLINE buf = StringIO()NEWLINE prev_step = NoneNEWLINE for step, error in errors:NEWLINE if step != prev_step:NEWLINE if prev_step is not None:NEWLINE buf.write('
')NEWLINE buf.write('

Step %s failed:

    ' \NEWLINE % escape(step))NEWLINE prev_step = stepNEWLINE buf.write('
  • %s
  • ' % escape(error))NEWLINE buf.write('
')NEWLINE message = Markup(buf.getvalue())NEWLINE else:NEWLINE if errors:NEWLINE steps = []NEWLINE for step, error in errors:NEWLINE if step not in steps:NEWLINE steps.append(step)NEWLINE steps = [Markup('%s') % step for step in steps]NEWLINE if len(steps) < 2:NEWLINE message = steps[0]NEWLINE elif len(steps) == 2:NEWLINE message = Markup(' and ').join(steps)NEWLINE elif len(steps) > 2:NEWLINE message = Markup(', ').join(steps[:-1]) + ', and ' + \NEWLINE steps[-1]NEWLINE message = Markup('Step%s %s failed') % (NEWLINE len(steps) != 1 and 's' or '', message)NEWLINE return messageNEWLINENEWLINE # Internal methodsNEWLINENEWLINE def _do_invalidate(self, req, build):NEWLINE self.log.info('Invalidating build %d', build.id)NEWLINENEWLINE with self.env.db_transaction as db:NEWLINE for step in BuildStep.select(self.env, build=build.id):NEWLINE step.delete()NEWLINENEWLINE build.slave = NoneNEWLINE build.started = 0NEWLINE build.stopped = 0NEWLINE build.last_activity = 0NEWLINE build.status = Build.PENDINGNEWLINE build.slave_info = {}NEWLINE build.update()NEWLINENEWLINE Attachment.delete_all(self.env, 'build', build.resource.id)NEWLINENEWLINE #commitNEWLINENEWLINE req.redirect(req.href.build(build.config))NEWLINENEWLINE def _render_log(self, req, build, formatters, step):NEWLINE items = []NEWLINE for log in BuildLog.select(self.env, build=build.id, step=step.name):NEWLINE for level, message in log.messages:NEWLINE for format in formatters:NEWLINE message = format(step, log.generator, level, message)NEWLINE items.append({'level': level, 'message': message})NEWLINE return itemsNEWLINENEWLINE def _render_reports(self, req, config, build, summarizers, step):NEWLINE reports = []NEWLINE for report in Report.select(self.env, build=build.id, step=step.name):NEWLINE summarizer = summarizers.get(report.category)NEWLINE if summarizer:NEWLINE tmpl, data = summarizer.render_summary(req, config, build,NEWLINE step, report.category)NEWLINE reports.append({'category': report.category,NEWLINE 'template': tmpl, 'data': data})NEWLINE else:NEWLINE tmpl = data = NoneNEWLINE return reportsNEWLINENEWLINENEWLINEclass ReportChartController(Component):NEWLINE implements(IRequestHandler)NEWLINENEWLINE generators = ExtensionPoint(IReportChartGenerator)NEWLINENEWLINE # IRequestHandler methodsNEWLINE def match_request(self, req):NEWLINE match = re.match(r'/build/([\w.-]+)/chart/(\w+)', req.path_info)NEWLINE if match:NEWLINE req.args['config'] = match.group(1)NEWLINE req.args['category'] = match.group(2)NEWLINE return TrueNEWLINENEWLINE def process_request(self, req):NEWLINE category = req.args.get('category')NEWLINE config = BuildConfig.fetch(self.env, name=req.args.get('config'))NEWLINENEWLINE for generator in self.generators:NEWLINE if category in generator.get_supported_categories():NEWLINE tmpl, data = generator.generate_chart_data(req, config,NEWLINE category)NEWLINE breakNEWLINE else:NEWLINE raise TracError('Unknown report category "%s"' % category)NEWLINENEWLINE data['dumps'] = json.to_jsonNEWLINENEWLINE return tmpl, data, 'text/plain'NEWLINENEWLINENEWLINEclass SourceFileLinkFormatter(Component):NEWLINE """Detects references to files in the build log and renders them as linksNEWLINE to the repository browser.NEWLINE """NEWLINENEWLINE implements(ILogFormatter)NEWLINENEWLINE _fileref_re = re.compile(r'(?P-[A-Za-z])?(?P[\w.-]+(?:[\\/][\w.-]+)+)(?P:\d+)?')NEWLINENEWLINE def get_formatter(self, req, build):NEWLINE """Return the log message formatter function."""NEWLINE config = BuildConfig.fetch(self.env, name=build.config)NEWLINE repos_name, repos, repos_path = get_repos(self.env, config.path,NEWLINE req.authname)NEWLINE href = req.href.browserNEWLINE cache = {}NEWLINENEWLINE def _replace(m):NEWLINE filepath = posixpath.normpath(m.group('path').replace('\\', '/'))NEWLINE if not cache.get(filepath) is True:NEWLINE parts = filepath.split('/')NEWLINE path = ''NEWLINE for part in parts:NEWLINE path = posixpath.join(path, part)NEWLINE if path not in cache:NEWLINE try:NEWLINE full_path = posixpath.join(config.path, path)NEWLINE full_path = posixpath.normpath(full_path)NEWLINE if full_path.startswith(config.path + "/") \NEWLINE or full_path == config.path:NEWLINE repos.get_node(full_path,NEWLINE build.rev)NEWLINE cache[path] = TrueNEWLINE else:NEWLINE cache[path] = FalseNEWLINE except TracError:NEWLINE cache[path] = FalseNEWLINE if cache[path] is False:NEWLINE return m.group(0)NEWLINE link = href(config.path, filepath)NEWLINE if m.group('line'):NEWLINE link += '#L' + m.group('line')[1:]NEWLINE return Markup(tag.a(m.group(0), href=link))NEWLINENEWLINE def _formatter(step, type, level, message):NEWLINE buf = []NEWLINE offset = 0NEWLINE for mo in self._fileref_re.finditer(message):NEWLINE start, end = mo.span()NEWLINE if start > offset:NEWLINE buf.append(message[offset:start])NEWLINE buf.append(_replace(mo))NEWLINE offset = endNEWLINE if offset < len(message):NEWLINE buf.append(message[offset:])NEWLINE return Markup("").join(buf)NEWLINENEWLINE return _formatterNEWLINE # Copyright (C) 2021 Intel CorporationNEWLINE#NEWLINE# SPDX-License-Identifier: MITNEWLINENEWLINEimport osNEWLINEimport base64NEWLINEimport uuidNEWLINENEWLINEfrom django.conf import settingsNEWLINEfrom django.core.cache import cacheNEWLINEfrom rest_framework import statusNEWLINEfrom rest_framework.response import ResponseNEWLINENEWLINEfrom cvat.apps.engine.serializers import DataSerializerNEWLINENEWLINEclass TusFile:NEWLINE _tus_cache_timeout = 3600NEWLINE def __init__(self, file_id, upload_dir):NEWLINE self.file_id = file_idNEWLINE self.upload_dir = upload_dirNEWLINE self.file_path = os.path.join(self.upload_dir, self.file_id)NEWLINE self.filename = cache.get("tus-uploads/{}/filename".format(file_id))NEWLINE self.file_size = int(cache.get("tus-uploads/{}/file_size".format(file_id)))NEWLINE self.metadata = cache.get("tus-uploads/{}/metadata".format(file_id))NEWLINE self.offset = cache.get("tus-uploads/{}/offset".format(file_id))NEWLINENEWLINE def init_file(self):NEWLINE os.makedirs(self.upload_dir, exist_ok=True)NEWLINE file_path = os.path.join(self.upload_dir, self.file_id)NEWLINE with open(file_path, 'wb') as file:NEWLINE file.seek(self.file_size - 1)NEWLINE file.write(b'\0')NEWLINENEWLINE def write_chunk(self, chunk):NEWLINE with open(self.file_path, 'r+b') as file:NEWLINE file.seek(chunk.offset)NEWLINE file.write(chunk.content)NEWLINE self.offset = cache.incr("tus-uploads/{}/offset".format(self.file_id), chunk.size)NEWLINENEWLINE def is_complete(self):NEWLINE return self.offset == self.file_sizeNEWLINENEWLINE def rename(self):NEWLINE file_id_path = os.path.join(self.upload_dir, self.file_id)NEWLINE file_path = os.path.join(self.upload_dir, self.filename)NEWLINE file_exists = os.path.lexists(os.path.join(self.upload_dir, self.filename))NEWLINE if file_exists:NEWLINE raise FileExistsError("File {} is already uploaded".format(self.filename))NEWLINE os.rename(file_id_path, file_path)NEWLINENEWLINE def clean(self):NEWLINE cache.delete_many([NEWLINE "tus-uploads/{}/file_size".format(self.file_id),NEWLINE "tus-uploads/{}/filename".format(self.file_id),NEWLINE "tus-uploads/{}/offset".format(self.file_id),NEWLINE "tus-uploads/{}/metadata".format(self.file_id),NEWLINE ])NEWLINENEWLINE @staticmethodNEWLINE def get_tusfile(file_id, upload_dir):NEWLINE file_exists = cache.get("tus-uploads/{}/filename".format(file_id), None) is not NoneNEWLINE if file_exists:NEWLINE return TusFile(file_id, upload_dir)NEWLINE return NoneNEWLINENEWLINE @staticmethodNEWLINE def create_file(metadata, file_size, upload_dir):NEWLINE file_id = str(uuid.uuid4())NEWLINE cache.add("tus-uploads/{}/filename".format(file_id), "{}".format(metadata.get("filename")), TusFile._tus_cache_timeout)NEWLINE cache.add("tus-uploads/{}/file_size".format(file_id), file_size, TusFile._tus_cache_timeout)NEWLINE cache.add("tus-uploads/{}/offset".format(file_id), 0, TusFile._tus_cache_timeout)NEWLINE cache.add("tus-uploads/{}/metadata".format(file_id), metadata, TusFile._tus_cache_timeout)NEWLINENEWLINE tus_file = TusFile(file_id, upload_dir)NEWLINE tus_file.init_file()NEWLINE return tus_fileNEWLINENEWLINEclass TusChunk:NEWLINE def __init__(self, request):NEWLINE self.META = request.METANEWLINE self.offset = int(request.META.get("HTTP_UPLOAD_OFFSET", 0))NEWLINE self.size = int(request.META.get("CONTENT_LENGTH", settings.TUS_DEFAULT_CHUNK_SIZE))NEWLINE self.content = request.bodyNEWLINENEWLINE# This upload mixin is implemented using tusNEWLINE# tus is open protocol for file uploads (see more https://tus.io/)NEWLINEclass UploadMixin(object):NEWLINE _tus_api_version = '1.0.0'NEWLINE _tus_api_version_supported = ['1.0.0']NEWLINE _tus_api_extensions = []NEWLINE _tus_max_file_size = str(settings.TUS_MAX_FILE_SIZE)NEWLINE _base_tus_headers = {NEWLINE 'Tus-Resumable': _tus_api_version,NEWLINE 'Tus-Version': ",".join(_tus_api_version_supported),NEWLINE 'Tus-Extension': ",".join(_tus_api_extensions),NEWLINE 'Tus-Max-Size': _tus_max_file_size,NEWLINE 'Access-Control-Allow-Origin': "*",NEWLINE 'Access-Control-Allow-Methods': "PATCH,HEAD,GET,POST,OPTIONS",NEWLINE 'Access-Control-Expose-Headers': "Tus-Resumable,upload-length,upload-metadata,Location,Upload-Offset",NEWLINE 'Access-Control-Allow-Headers': "Tus-Resumable,upload-length,upload-metadata,Location,Upload-Offset,content-type",NEWLINE 'Cache-Control': 'no-store'NEWLINE }NEWLINE file_id_regex = r'(?P\b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b)'NEWLINENEWLINE def _tus_response(self, status, data=None, extra_headers=None):NEWLINE response = Response(data, status)NEWLINE for key, value in self._base_tus_headers.items():NEWLINE response.__setitem__(key, value)NEWLINE if extra_headers:NEWLINE for key, value in extra_headers.items():NEWLINE response.__setitem__(key, value)NEWLINE return responseNEWLINENEWLINE def _get_metadata(self, request):NEWLINE metadata = {}NEWLINE if request.META.get("HTTP_UPLOAD_METADATA"):NEWLINE for kv in request.META.get("HTTP_UPLOAD_METADATA").split(","):NEWLINE splited_metadata = kv.split(" ")NEWLINE if len(splited_metadata) == 2:NEWLINE key, value = splited_metadataNEWLINE value = base64.b64decode(value)NEWLINE if isinstance(value, bytes):NEWLINE value = value.decode()NEWLINE metadata[key] = valueNEWLINE else:NEWLINE metadata[splited_metadata[0]] = ""NEWLINE return metadataNEWLINENEWLINE def upload_data(self, request):NEWLINE tus_request = request.headers.get('Upload-Length', None) is not None or request.method == 'OPTIONS'NEWLINE bulk_file_upload = request.headers.get('Upload-Multiple', None) is not NoneNEWLINE start_upload = request.headers.get('Upload-Start', None) is not NoneNEWLINE finish_upload = request.headers.get('Upload-Finish', None) is not NoneNEWLINE one_request_upload = start_upload and finish_uploadNEWLINE if one_request_upload or finish_upload:NEWLINE return self.upload_finished(request)NEWLINE elif start_upload:NEWLINE return Response(status=status.HTTP_202_ACCEPTED)NEWLINE elif tus_request:NEWLINE return self.init_tus_upload(request)NEWLINE elif bulk_file_upload:NEWLINE return self.append(request)NEWLINE else: # backward compatibility case - no upload headers were foundNEWLINE return self.upload_finished(request)NEWLINENEWLINE def init_tus_upload(self, request):NEWLINE if request.method == 'OPTIONS':NEWLINE return self._tus_response(status=status.HTTP_204)NEWLINE else:NEWLINE metadata = self._get_metadata(request)NEWLINE filename = metadata.get('filename', '')NEWLINE if not self.validate_filename(filename):NEWLINE return self._tus_response(status=status.HTTP_400_BAD_REQUEST,NEWLINE data="File name {} is not allowed".format(filename))NEWLINENEWLINENEWLINE message_id = request.META.get("HTTP_MESSAGE_ID")NEWLINE if message_id:NEWLINE metadata["message_id"] = base64.b64decode(message_id)NEWLINENEWLINE file_exists = os.path.lexists(os.path.join(self.get_upload_dir(), filename))NEWLINE if file_exists:NEWLINE return self._tus_response(status=status.HTTP_409_CONFLICT,NEWLINE data="File with same name already exists")NEWLINENEWLINE file_size = int(request.META.get("HTTP_UPLOAD_LENGTH", "0"))NEWLINE if file_size > int(self._tus_max_file_size):NEWLINE return self._tus_response(status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,NEWLINE data="File size exceeds max limit of {} bytes".format(self._tus_max_file_size))NEWLINENEWLINE tus_file = TusFile.create_file(metadata, file_size, self.get_upload_dir())NEWLINENEWLINE location = request.build_absolute_uri()NEWLINE if 'HTTP_X_FORWARDED_HOST' not in request.META:NEWLINE location = request.META.get('HTTP_ORIGIN') + request.META.get('PATH_INFO')NEWLINE return self._tus_response(NEWLINE status=status.HTTP_201_CREATED,NEWLINE extra_headers={'Location': '{}{}'.format(location, tus_file.file_id)})NEWLINENEWLINE def append_tus_chunk(self, request, file_id):NEWLINE if request.method == 'HEAD':NEWLINE tus_file = TusFile.get_tusfile(str(file_id), self.get_upload_dir())NEWLINE if tus_file:NEWLINE return self._tus_response(status=status.HTTP_200_OK, extra_headers={NEWLINE 'Upload-Offset': tus_file.offset,NEWLINE 'Upload-Length': tus_file.file_size})NEWLINE return self._tus_response(status=status.HTTP_404_NOT_FOUND)NEWLINE else:NEWLINE tus_file = TusFile.get_tusfile(str(file_id), self.get_upload_dir())NEWLINE chunk = TusChunk(request)NEWLINENEWLINE if chunk.offset != tus_file.offset:NEWLINE return self._tus_response(status=status.HTTP_409_CONFLICT)NEWLINENEWLINE if chunk.offset > tus_file.file_size:NEWLINE return self._tus_response(status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)NEWLINENEWLINE tus_file.write_chunk(chunk)NEWLINENEWLINE if tus_file.is_complete():NEWLINE tus_file.rename()NEWLINE tus_file.clean()NEWLINENEWLINE return self._tus_response(status=status.HTTP_204_NO_CONTENT,NEWLINE extra_headers={'Upload-Offset': tus_file.offset})NEWLINENEWLINE def validate_filename(self, filename):NEWLINE upload_dir = self.get_upload_dir()NEWLINE file_path = os.path.join(upload_dir, filename)NEWLINE return os.path.commonprefix((os.path.realpath(file_path), upload_dir)) == upload_dirNEWLINENEWLINE def get_upload_dir(self):NEWLINE return self._object.data.get_upload_dirname()NEWLINENEWLINE def get_request_client_files(self, request):NEWLINE serializer = DataSerializer(self._object, data=request.data)NEWLINE serializer.is_valid(raise_exception=True)NEWLINE data = {k: v for k, v in serializer.validated_data.items()}NEWLINE return data.get('client_files', None)NEWLINENEWLINE def append(self, request):NEWLINE client_files = self.get_request_client_files(request)NEWLINE if client_files:NEWLINE upload_dir = self.get_upload_dir()NEWLINE for client_file in client_files:NEWLINE with open(os.path.join(upload_dir, client_file['file'].name), 'ab+') as destination:NEWLINE destination.write(client_file['file'].read())NEWLINE return Response(status=status.HTTP_200_OK)NEWLINENEWLINE # override this to do stuff after uploadNEWLINE def upload_finished(self, request):NEWLINE raise NotImplementedError('You need to implement upload_finished in UploadMixin')NEWLINE # Licensed to Elasticsearch B.V. under one or more contributorNEWLINE# license agreements. See the NOTICE file distributed withNEWLINE# this work for additional information regarding copyrightNEWLINE# ownership. Elasticsearch B.V. licenses this file to you underNEWLINE# the Apache License, Version 2.0 (the "License"); you mayNEWLINE# not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing,NEWLINE# software distributed under the License is distributed on anNEWLINE# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANYNEWLINE# KIND, either express or implied. See the License for theNEWLINE# specific language governing permissions and limitationsNEWLINE# under the License.NEWLINENEWLINE# File called _pytest for PyCharm compatabilityNEWLINENEWLINEimport pytestNEWLINENEWLINEfrom tests.common import TestDataNEWLINENEWLINENEWLINEclass TestDataFrameFilter(TestData):NEWLINE def test_filter_arguments_mutually_exclusive(self, df):NEWLINE with pytest.raises(TypeError):NEWLINE df.filter(items=[], like="!", regex="!")NEWLINE with pytest.raises(TypeError):NEWLINE df.filter(items=[], regex="!")NEWLINE with pytest.raises(TypeError):NEWLINE df.filter(items=[], like="!")NEWLINE with pytest.raises(TypeError):NEWLINE df.filter(like="!", regex="!")NEWLINE with pytest.raises(TypeError):NEWLINE df.filter()NEWLINENEWLINE @pytest.mark.parametrize(NEWLINE "items",NEWLINE [NEWLINE ["DestCountry", "Cancelled", "AvgTicketPrice"],NEWLINE [],NEWLINE ["notfound", "AvgTicketPrice"],NEWLINE ],NEWLINE )NEWLINE def test_filter_columns_items(self, df, items):NEWLINE df.filter(items=items)NEWLINENEWLINE @pytest.mark.parametrize("like", ["Flight", "Nope"])NEWLINE def test_filter_columns_like(self, df, like):NEWLINE df.filter(like=like)NEWLINENEWLINE @pytest.mark.parametrize("regex", ["^Flig", "^Flight.*r$", ".*", "^[^C]"])NEWLINE def test_filter_columns_regex(self, df, regex):NEWLINE df.filter(regex=regex)NEWLINENEWLINE @pytest.mark.parametrize("items", [[], ["20"], [str(x) for x in range(30)]])NEWLINE def test_filter_index_items(self, df, items):NEWLINE df.filter(items=items, axis=0)NEWLINENEWLINE def test_filter_index_like_and_regex(self):NEWLINE ed_flights_small = self.ed_flights_small()NEWLINENEWLINE with pytest.raises(NotImplementedError):NEWLINE ed_flights_small.filter(like="2", axis=0)NEWLINE with pytest.raises(NotImplementedError):NEWLINE ed_flights_small.filter(regex="^2", axis=0)NEWLINENEWLINE def test_filter_index_order(self):NEWLINE # Filtering dataframe should retain order of itemsNEWLINE ed_flights = self.ed_flights()NEWLINENEWLINE items = ["4", "2", "3", "1", "0"]NEWLINENEWLINE assert [NEWLINE i for i in ed_flights.filter(axis="index", items=items).to_pandas().indexNEWLINE ] == itemsNEWLINE # Copyright 2017 AT&T Intellectual Property. All other rights reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE"""Noop driver for manually executing OOB tasks."""NEWLINENEWLINEimport timeNEWLINEimport loggingNEWLINENEWLINEfrom oslo_config import cfgNEWLINENEWLINEimport drydock_provisioner.error as errorsNEWLINENEWLINEimport drydock_provisioner.objects.fields as hd_fieldsNEWLINENEWLINEimport drydock_provisioner.drivers.oob.driver as oobNEWLINENEWLINENEWLINEclass ManualDriver(oob.OobDriver):NEWLINENEWLINE oob_types_supported = ['manual']NEWLINENEWLINE def __init__(self, **kwargs):NEWLINE super(ManualDriver, self).__init__(**kwargs)NEWLINENEWLINE self.driver_name = "manual_driver"NEWLINE self.driver_key = "manual_driver"NEWLINE self.driver_desc = "Manual (Noop) OOB Driver"NEWLINENEWLINE self.logger = logging.getLogger(cfg.CONF.logging.oobdriver_logger_name)NEWLINENEWLINE def execute_task(self, task_id):NEWLINE task = self.state_manager.get_task(task_id)NEWLINENEWLINE if task is None:NEWLINE self.logger.error("Invalid task %s" % (task_id))NEWLINE raise errors.DriverError("Invalid task %s" % (task_id))NEWLINENEWLINE if task.action not in self.supported_actions:NEWLINE self.logger.error("Driver %s doesn't support task action %s" %NEWLINE (self.driver_desc, task.action))NEWLINE raise errors.DriverError("Driver %s doesn't support task action %s"NEWLINE % (self.driver_desc, task.action))NEWLINENEWLINE design_ref = task.design_refNEWLINENEWLINE if design_ref is None:NEWLINE raise errors.DriverError(NEWLINE "No design ID specified in task %s" % (task_id))NEWLINENEWLINE self.orchestrator.task_field_update(NEWLINE task.get_id(), status=hd_fields.TaskStatus.Running)NEWLINENEWLINE self.logger.info("Sleeping 60s to allow time for manual OOB %s action"NEWLINE % task.action)NEWLINENEWLINE time.sleep(60)NEWLINENEWLINE task.set_status(hd_fields.TaskStatus.Complete)NEWLINE task.success()NEWLINE task.save()NEWLINENEWLINE returnNEWLINE def define_targets(rules):NEWLINE rules.py_library(NEWLINE name = "torchgen",NEWLINE srcs = rules.glob(["**/*.py"]),NEWLINE deps = [NEWLINE rules.requirement("PyYAML"),NEWLINE rules.requirement("typing-extensions"),NEWLINE ],NEWLINE visibility = ["//visibility:public"],NEWLINE )NEWLINENEWLINE rules.py_binary(NEWLINE name = "gen",NEWLINE srcs = [":torchgen"],NEWLINE visibility = ["//visibility:public"],NEWLINE )NEWLINE version = '0.0.7'NEWLINEtime = '2021-10-22 16:08:00'NEWLINE from django.db import modelsNEWLINEimport django.contrib.auth.modelsNEWLINENEWLINENEWLINE# class Admin(models.Model):NEWLINE# password = models.CharField(max_length=128)NEWLINE# last_login = models.DateTimeField()NEWLINE# is_superuser = models.BooleanField()NEWLINE# first_name = models.CharField(max_length=30)NEWLINE# last_name = models.CharField(max_length=30)NEWLINE# email = models.EmailField(max_length=254)NEWLINE# is_staff = models.BooleanField()NEWLINE# is_active = models.BooleanField()NEWLINE# date_joined = models.DateTimeField()NEWLINE# username = models.CharField(max_length=30)NEWLINE#NEWLINE# class Meta:NEWLINE# db_table = "auth_user"NEWLINENEWLINENEWLINEclass Statistics(models.Model):NEWLINE new_order = models.IntegerField()NEWLINE new_visitors = models.IntegerField()NEWLINE new_user = models.IntegerField()NEWLINE profit_today = models.IntegerField()NEWLINENEWLINE class Meta:NEWLINE db_table = "admin_site_statistics"NEWLINENEWLINENEWLINEclass EmailEntity(models.Model):NEWLINE user = models.ForeignKey(django.contrib.auth.models.User, related_name='email_owner')NEWLINE #MIME headerNEWLINE mime_from = models.EmailField(max_length=128)NEWLINE mime_to = models.CharField(max_length=128)NEWLINE mime_cc = models.CharField(max_length=128)NEWLINE mime_bcc = models.CharField(max_length=128)NEWLINE mime_date = models.DateTimeField()NEWLINE mime_subject = models.CharField(max_length=128)NEWLINE mime_transfer_encoding = models.CharField(max_length=8)NEWLINE #MIME contentNEWLINE content_type = models.CharField(max_length=8)NEWLINENEWLINE #local statusNEWLINE readed = models.BooleanField()NEWLINENEWLINE class Meta:NEWLINE db_table = "admin_email_inbox"NEWLINE from typing import List, Dict, SetNEWLINEfrom itertools import chainNEWLINEimport reNEWLINEfrom collections import defaultdict, CounterNEWLINENEWLINENEWLINEclass BytePairEncoding(object):NEWLINE """ Byte Pair Encoding classNEWLINE We aren't gonna use this class for encoding. Because it is too slow......NEWLINE We will use sentence piece Google have made.NEWLINE Thus, this class is just for special token index reference.NEWLINE """NEWLINE PAD_token = ''NEWLINE PAD_token_idx = 0NEWLINE UNK_token = ''NEWLINE UNK_token_idx = 1NEWLINE CLS_token = ''NEWLINE CLS_token_idx = 2NEWLINE SEP_token = ''NEWLINE SEP_token_idx = 3NEWLINE MSK_token = ''NEWLINE MSK_token_idx = 4NEWLINENEWLINE WORD_END = '_'NEWLINENEWLINE def __init__(self, corpus: List[List[str]], max_vocab_size: int) -> None:NEWLINE self.idx2word = build_bpe(corpus, max_vocab_size)NEWLINENEWLINE def encode(self, sentence: List[str]) -> List[int]:NEWLINE return encode(sentence, self.idx2word)NEWLINENEWLINE def decoder(self, tokens: List[int]) -> List[str]:NEWLINE return decode(tokens, self.idx2word)NEWLINENEWLINENEWLINEdef build_bpe(NEWLINE corpus: List[str],NEWLINE max_vocab_size: intNEWLINE) -> List[int]:NEWLINE """ BPE Vocabulary BuilderNEWLINE Implement vocabulary builder for byte pair encoding.NEWLINE Please sort your idx2word by subword length in descending manner.NEWLINENEWLINE Hint: Counter in collection library would be helpfulNEWLINENEWLINE Note: If you convert sentences list to word frequence dictionary,NEWLINE building speed is enhanced significantly because duplicated words areNEWLINE preprocessed togetherNEWLINENEWLINE Arguments:NEWLINE corpus -- List of words to build vocabNEWLINE max_vocab_size -- The maximum size of vocabNEWLINENEWLINE Return:NEWLINE idx2word -- Subword listNEWLINE """NEWLINE # Special tokensNEWLINE PAD = BytePairEncoding.PAD_token # Index of must be 0NEWLINE UNK = BytePairEncoding.UNK_token # Index of must be 1NEWLINE CLS = BytePairEncoding.CLS_token # Index of must be 2NEWLINE SEP = BytePairEncoding.SEP_token # Index of must be 3NEWLINE MSK = BytePairEncoding.MSK_token # Index of must be 4NEWLINE SPECIAL = [PAD, UNK, CLS, SEP, MSK]NEWLINENEWLINE WORD_END = BytePairEncoding.WORD_END # Use this token as the end of a wordNEWLINE # YOUR CODE HERENEWLINE # 1. character vocabulary로 symbol vocab 초기화하고 단어를 sequence of chars로 표현NEWLINE vocab = {" ".join(list(word) + [WORD_END]): ct for word, ct in Counter(corpus).items()}NEWLINE chars = list(set([char for word in corpus for char in word]))NEWLINE num_merges = max_vocab_size - len(SPECIAL) - 1 - len(chars)NEWLINE # 2. number of merge operation에 도달할 때 까지 아래 두 과정을 반복한다NEWLINE for _ in range(num_merges):NEWLINE # 2-a. symbol pair를 센다. 합칠 pair가 없다면 loop을 종료한다.NEWLINE pairs = defaultdict(int)NEWLINE for word, freq in vocab.items():NEWLINE symbols = word.split()NEWLINE for i in range(len(symbols)-1):NEWLINE pairs[symbols[i],symbols[i+1]] += freqNEWLINE if not pairs:NEWLINE breakNEWLINE # 2-b. 가장 빈번히 등장하는 pairs를 합쳐 새로운 symbol로 대체한다NEWLINE best = max(pairs, key=pairs.get)NEWLINE new_vocab = {}NEWLINE bigram = re.escape(' '.join(best))NEWLINE p = re.compile(r'(? List:NEWLINE return [{"value": invoice_profile} for invoice_profile in self.invoice_profiles]NEWLINE # vim: tabstop=4 shiftwidth=4 softtabstop=4NEWLINENEWLINE# Copyright 2011 OpenStack FoundationNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License"); you mayNEWLINE# not use this file except in compliance with the License. You may obtainNEWLINE# a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS, WITHOUTNEWLINE# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See theNEWLINE# License for the specific language governing permissions and limitationsNEWLINE# under the License.NEWLINE"""NEWLINEA module where we define some basic units for use across Cinder.NEWLINE"""NEWLINENEWLINEKiB = 1024NEWLINEMiB = KiB * 1024NEWLINEGiB = MiB * 1024NEWLINE from django.db import modelsNEWLINEfrom django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \NEWLINE PermissionsMixinNEWLINENEWLINEclass UserManager(BaseUserManager):NEWLINE def create_user(self, email, password=None, **extra_fields):NEWLINE """creates and saves a new user"""NEWLINE if not email:NEWLINE raise ValueError('Users must have an email address')NEWLINE user = self.model(email=self.normalize_email(email), **extra_fields)NEWLINE user.set_password(password)NEWLINE user.save(using=self._db)NEWLINE return userNEWLINENEWLINE def create_superuser(self, email, password):NEWLINE """Creates and saves a new super user"""NEWLINE user = self.create_user(email, password)NEWLINE user.is_staff = TrueNEWLINE user.is_superuser = TrueNEWLINE user.save(using= self._db)NEWLINE return user NEWLINENEWLINENEWLINEclass User(AbstractBaseUser,PermissionsMixin):NEWLINE """custom user model that supports using email insteadof username"""NEWLINE email = models.EmailField(max_length=255, unique=True)NEWLINE name = models.CharField(max_length=255)NEWLINE is_active = models.BooleanField(default=True)NEWLINE is_staff = models.BooleanField(default=False)NEWLINENEWLINE objects = UserManager()NEWLINENEWLINE USERNAME_FIELD = 'email' # -*- coding: utf-8 -*-NEWLINE# Generated by Django 1.10.5 on 2017-06-25 16:40NEWLINEfrom __future__ import unicode_literalsNEWLINENEWLINEfrom django.db import migrations, modelsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ('websites', '0005_auto_20170625_1840'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.AlterField(NEWLINE model_name='websitedirective',NEWLINE name='name',NEWLINE field=models.CharField(choices=[(None, '-------'), ('SSL', [('ssl-ca', 'SSL CA'), ('ssl-cert', 'SSL cert'), ('ssl-key', 'SSL key')]), ('HTTPD', [('redirect', 'Redirection'), ('proxy', 'Proxy'), ('error-document', 'ErrorDocumentRoot')]), ('ModSecurity', [('sec-rule-remove', 'SecRuleRemoveById'), ('sec-engine', 'SecRuleEngine Off')]), ('SaaS', [('wordpress-saas', 'WordPress SaaS'), ('dokuwiki-saas', 'DokuWiki SaaS'), ('drupal-saas', 'Drupdal SaaS'), ('moodle-saas', 'Moodle SaaS')])], db_index=True, max_length=128, verbose_name='name'),NEWLINE ),NEWLINE ]NEWLINE import numpy as npNEWLINEfrom gym.envs.registration import registerNEWLINENEWLINEfrom onpolicy.envs.highway.highway_env import utilsNEWLINEfrom onpolicy.envs.highway.highway_env.envs.common.abstract import AbstractEnvNEWLINEfrom onpolicy.envs.highway.highway_env.road.lane import LineType, StraightLaneNEWLINEfrom onpolicy.envs.highway.highway_env.road.road import Road, RoadNetworkNEWLINEfrom onpolicy.envs.highway.highway_env.vehicle.controller import MDPVehicleNEWLINENEWLINENEWLINEclass TwoWayEnv(AbstractEnv):NEWLINENEWLINE """NEWLINE A risk management task: the agent is driving on a two-way lane with icoming traffic.NEWLINENEWLINE It must balance making progress by overtaking and ensuring safety.NEWLINENEWLINE These conflicting objectives are implemented by a reward signal and a constraint signal,NEWLINE in the CMDP/BMDP framework.NEWLINE """NEWLINENEWLINE COLLISION_REWARD: float = 0NEWLINE LEFT_LANE_CONSTRAINT: float = 1NEWLINE LEFT_LANE_REWARD: float = 0.2NEWLINE HIGH_SPEED_REWARD: float = 0.8NEWLINENEWLINE @classmethodNEWLINE def default_config(cls) -> dict:NEWLINE config = super().default_config()NEWLINE config.update({NEWLINE "observation": {NEWLINE "type": "TimeToCollision",NEWLINE "horizon": 5NEWLINE },NEWLINE "action": {NEWLINE "type": "DiscreteMetaAction",NEWLINE },NEWLINE })NEWLINE return configNEWLINENEWLINE def _reward(self, action: int) -> float:NEWLINE """NEWLINE The vehicle is rewarded for driving with high speedNEWLINE :param action: the action performedNEWLINE :return: the reward of the state-action transitionNEWLINE """NEWLINE neighbours = self.road.network.all_side_lanes(self.vehicle.lane_index)NEWLINENEWLINE reward = self.HIGH_SPEED_REWARD * self.vehicle.speed_index / (self.vehicle.SPEED_COUNT - 1) \NEWLINE + self.LEFT_LANE_REWARD * (len(neighbours) - 1 - self.vehicle.target_lane_index[2]) / (len(neighbours) - 1)NEWLINE return rewardNEWLINENEWLINE def _is_terminal(self) -> bool:NEWLINE """The episode is over if the ego vehicle crashed or the time is out."""NEWLINE return self.vehicle.crashedNEWLINENEWLINE def _cost(self, action: int) -> float:NEWLINE """The constraint signal is the time spent driving on the opposite lane, and occurrence of collisions."""NEWLINE return float(self.vehicle.crashed) + float(self.vehicle.lane_index[2] == 0)/15NEWLINENEWLINE def _reset(self) -> np.ndarray:NEWLINE self._make_road()NEWLINE self._make_vehicles()NEWLINENEWLINE def _make_road(self, length=800):NEWLINE """NEWLINE Make a road composed of a two-way road.NEWLINENEWLINE :return: the roadNEWLINE """NEWLINE net = RoadNetwork()NEWLINENEWLINE # LanesNEWLINE net.add_lane("a", "b", StraightLane([0, 0], [length, 0],NEWLINE line_types=(LineType.CONTINUOUS_LINE, LineType.STRIPED)))NEWLINE net.add_lane("a", "b", StraightLane([0, StraightLane.DEFAULT_WIDTH], [length, StraightLane.DEFAULT_WIDTH],NEWLINE line_types=(LineType.NONE, LineType.CONTINUOUS_LINE)))NEWLINE net.add_lane("b", "a", StraightLane([length, 0], [0, 0],NEWLINE line_types=(LineType.NONE, LineType.NONE)))NEWLINENEWLINE road = Road(network=net, np_random=self.np_random, record_history=self.config["show_trajectories"])NEWLINE self.road = roadNEWLINENEWLINE def _make_vehicles(self) -> None:NEWLINE """NEWLINE Populate a road with several vehicles on the roadNEWLINENEWLINE :return: the ego-vehicleNEWLINE """NEWLINE road = self.roadNEWLINE ego_vehicle = self.action_type.vehicle_class(road,NEWLINE road.network.get_lane(("a", "b", 1)).position(30, 0),NEWLINE speed=30)NEWLINE road.vehicles.append(ego_vehicle)NEWLINE self.vehicle = ego_vehicleNEWLINENEWLINE vehicles_type = utils.class_from_path(self.config["npc_vehicles_type"])NEWLINE for i in range(3):NEWLINE self.road.vehicles.append(NEWLINE vehicles_type(road,NEWLINE position=road.network.get_lane(("a", "b", 1))NEWLINE .position(70+40*i + 10*self.np_random.randn(), 0),NEWLINE heading=road.network.get_lane(("a", "b", 1)).heading_at(70+40*i),NEWLINE speed=24 + 2*self.np_random.randn(),NEWLINE enable_lane_change=False)NEWLINE )NEWLINE for i in range(2):NEWLINE v = vehicles_type(road,NEWLINE position=road.network.get_lane(("b", "a", 0))NEWLINE .position(200+100*i + 10*self.np_random.randn(), 0),NEWLINE heading=road.network.get_lane(("b", "a", 0)).heading_at(200+100*i),NEWLINE speed=20 + 5*self.np_random.randn(),NEWLINE enable_lane_change=False)NEWLINE v.target_lane_index = ("b", "a", 0)NEWLINE self.road.vehicles.append(v)NEWLINENEWLINENEWLINEregister(NEWLINE id='two-way-v0',NEWLINE entry_point='highway_env.envs:TwoWayEnv',NEWLINE max_episode_steps=15NEWLINE)NEWLINE '''NEWLINECreated by auto_sdk on 2020.11.17NEWLINE'''NEWLINEfrom dingtalk.api.base import RestApiNEWLINEclass OapiKacDatavDingGetRequest(RestApi):NEWLINE def __init__(self,url=None):NEWLINE RestApi.__init__(self,url)NEWLINE self.ding_usage_summary_request = NoneNEWLINENEWLINE def getHttpMethod(self):NEWLINE return 'POST'NEWLINENEWLINE def getapiname(self):NEWLINE return 'dingtalk.oapi.kac.datav.ding.get'NEWLINE from datetime import datetime, dateNEWLINEfrom marqeta.response_models.transaction_model import TransactionModelNEWLINEfrom marqeta.response_models import datetime_objectNEWLINEimport jsonNEWLINEimport reNEWLINENEWLINEclass AdvancedSimulationResponseModel(object):NEWLINENEWLINE def __init__(self, json_response):NEWLINE self.json_response = json_responseNEWLINENEWLINE def __str__(self):NEWLINE return json.dumps(self.json_response, default=self.json_serial)NEWLINENEWLINE @staticmethodNEWLINE def json_serial(o):NEWLINE if isinstance(o, datetime) or isinstance(o, date):NEWLINE return o.__str__()NEWLINENEWLINE @propertyNEWLINE def transaction(self):NEWLINE if 'transaction' in self.json_response:NEWLINE return TransactionModel(self.json_response['transaction'])NEWLINENEWLINE @propertyNEWLINE def raw_iso8583(self):NEWLINE return self.json_response.get('raw_iso8583', None)NEWLINENEWLINE def __repr__(self):NEWLINE return '' + self.__str__()NEWLINE import unittestNEWLINENEWLINEfrom tests.mapreduce import MapReduceTestCaseNEWLINENEWLINENEWLINEdef all_tests():NEWLINE suite = unittest.TestSuite()NEWLINE suite.addTest(unittest.makeSuite(MapReduceTestCase))NEWLINE return suiteNEWLINE #NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINEfrom neutron_lib import exceptions as q_excNEWLINENEWLINENEWLINEclass ArrayLBaaSv2DriverException(q_exc.NeutronException):NEWLINE """General Array LBaaSv2 Driver Exception."""NEWLINENEWLINE def __init__(self, message=None):NEWLINE if message:NEWLINE self.message = messageNEWLINENEWLINENEWLINEclass ArrayNoAttachedLoadbalancerException(ArrayLBaaSv2DriverException):NEWLINE """Exception thrown when an LBaaSv2 object has not parent Loadbalancer."""NEWLINENEWLINE message = "Entity has no associated loadbalancer"NEWLINENEWLINE def __str__(self):NEWLINE return self.messageNEWLINE #NEWLINE# Copyright 2019 The FATE Authors. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE#NEWLINEimport ioNEWLINEimport osNEWLINEfrom typing import IterableNEWLINENEWLINEfrom pyarrow import fsNEWLINENEWLINEfrom fate_arch.common import hdfs_utilsNEWLINEfrom fate_arch.common.log import getLoggerNEWLINEfrom fate_arch.storage import StorageEngine, HDFSStorageTypeNEWLINEfrom fate_arch.storage import StorageTableBaseNEWLINENEWLINELOGGER = getLogger()NEWLINENEWLINENEWLINEclass StorageTable(StorageTableBase):NEWLINE def __init__(self,NEWLINE address=None,NEWLINE name: str = None,NEWLINE namespace: str = None,NEWLINE partitions: int = None,NEWLINE storage_type: HDFSStorageType = None,NEWLINE options=None):NEWLINE super(StorageTable, self).__init__(name=name, namespace=namespace)NEWLINE self._address = addressNEWLINE self._name = nameNEWLINE self._namespace = namespaceNEWLINE self._partitions = partitions if partitions else 1NEWLINE self._type = storage_type if storage_type else HDFSStorageType.DISKNEWLINE self._options = options if options else {}NEWLINE self._engine = StorageEngine.HDFSNEWLINENEWLINE # tricky way to load libhdfsNEWLINE try:NEWLINE from pyarrow import HadoopFileSystemNEWLINE HadoopFileSystem(self._path)NEWLINE except Exception as e:NEWLINE LOGGER.warning(f"load libhdfs failed: {e}")NEWLINE self._hdfs_client = fs.HadoopFileSystem.from_uri(self._path)NEWLINENEWLINE def get_name(self):NEWLINE return self._nameNEWLINENEWLINE def get_namespace(self):NEWLINE return self._namespaceNEWLINENEWLINE def get_address(self):NEWLINE return self._addressNEWLINENEWLINE def get_engine(self):NEWLINE return self._engineNEWLINENEWLINE def get_type(self):NEWLINE return self._typeNEWLINENEWLINE def get_partitions(self):NEWLINE return self._partitionsNEWLINENEWLINE def get_options(self):NEWLINE return self._optionsNEWLINENEWLINE def put_all(self, kv_list: Iterable, append=True, assume_file_exist=False, **kwargs):NEWLINE LOGGER.info(f"put in hdfs file: {self._path}")NEWLINE if append and (assume_file_exist or self._exist()):NEWLINE stream = self._hdfs_client.open_append_stream(path=self._path, compression=None)NEWLINE else:NEWLINE stream = self._hdfs_client.open_output_stream(path=self._path, compression=None)NEWLINENEWLINE counter = 0NEWLINE with io.TextIOWrapper(stream) as writer:NEWLINE for k, v in kv_list:NEWLINE writer.write(hdfs_utils.serialize(k, v))NEWLINE writer.write(hdfs_utils.NEWLINE)NEWLINE counter = counter + 1NEWLINE self._meta.update_metas(count=counter)NEWLINENEWLINE def collect(self, **kwargs) -> list:NEWLINE for line in self._as_generator():NEWLINE yield hdfs_utils.deserialize(line.rstrip())NEWLINENEWLINE def read(self) -> list:NEWLINE for line in self._as_generator():NEWLINE yield lineNEWLINENEWLINE def destroy(self):NEWLINE super().destroy()NEWLINE self._hdfs_client.delete_file(self._path)NEWLINENEWLINE def count(self):NEWLINE count = 0NEWLINE for _ in self._as_generator():NEWLINE count += 1NEWLINE self.get_meta().update_metas(count=count)NEWLINE return countNEWLINENEWLINE def save_as(self, address, partitions=None, name=None, namespace=None, schema=None, **kwargs):NEWLINE super().save_as(name, namespace, partitions=partitions, schema=schema)NEWLINE self._hdfs_client.copy_file(src=self._path, dst=address.path)NEWLINE return StorageTable(address=address, partitions=partitions, name=name, namespace=namespace, **kwargs)NEWLINENEWLINE def close(self):NEWLINE passNEWLINENEWLINE @propertyNEWLINE def _path(self) -> str:NEWLINE return f"{self._address.name_node}/{self._address.path}"NEWLINENEWLINE def _exist(self):NEWLINE info = self._hdfs_client.get_file_info([self._path])[0]NEWLINE return info.type != fs.FileType.NotFoundNEWLINENEWLINE def _as_generator(self):NEWLINE info = self._hdfs_client.get_file_info([self._path])[0]NEWLINE if info.type == fs.FileType.NotFound:NEWLINE raise FileNotFoundError(f"file {self._path} not found")NEWLINENEWLINE elif info.type == fs.FileType.File:NEWLINE with io.TextIOWrapper(buffer=self._hdfs_client.open_input_stream(self._path),NEWLINE encoding="utf-8") as reader:NEWLINE for line in reader:NEWLINE yield lineNEWLINENEWLINE else:NEWLINE selector = fs.FileSelector(os.path.join("/", self._address.path))NEWLINE file_infos = self._hdfs_client.get_file_info(selector)NEWLINE for file_info in file_infos:NEWLINE if file_info.base_name == "_SUCCESS":NEWLINE continueNEWLINE assert file_info.is_file, f"{self._path} is directory contains a subdirectory: {file_info.path}"NEWLINE with io.TextIOWrapper(NEWLINE buffer=self._hdfs_client.open_input_stream(f"{self._address.name_node}/{file_info.path}"),NEWLINE encoding="utf-8") as reader:NEWLINE for line in reader:NEWLINE yield lineNEWLINE # coding=utf-8NEWLINE# --------------------------------------------------------------------------NEWLINE# Copyright (c) Microsoft Corporation. All rights reserved.NEWLINE# Licensed under the MIT License. See License.txt in the project root forNEWLINE# license information.NEWLINE#NEWLINE# Code generated by Microsoft (R) AutoRest Code Generator.NEWLINE# Changes may cause incorrect behavior and will be lost if the code isNEWLINE# regenerated.NEWLINE# --------------------------------------------------------------------------NEWLINENEWLINEfrom .azure_entity_resource import AzureEntityResourceNEWLINENEWLINENEWLINEclass ImmutabilityPolicy(AzureEntityResource):NEWLINE """The ImmutabilityPolicy property of a blob container, including Id, resourceNEWLINE name, resource type, Etag.NEWLINENEWLINE Variables are only populated by the server, and will be ignored whenNEWLINE sending a request.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar id: Fully qualified resource Id for the resource. Ex -NEWLINE /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}NEWLINE :vartype id: strNEWLINE :ivar name: The name of the resourceNEWLINE :vartype name: strNEWLINE :ivar type: The type of the resource. Ex-NEWLINE Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts.NEWLINE :vartype type: strNEWLINE :ivar etag: Resource Etag.NEWLINE :vartype etag: strNEWLINE :param immutability_period_since_creation_in_days: Required. TheNEWLINE immutability period for the blobs in the container since the policyNEWLINE creation, in days.NEWLINE :type immutability_period_since_creation_in_days: intNEWLINE :ivar state: The ImmutabilityPolicy state of a blob container, possibleNEWLINE values include: Locked and Unlocked. Possible values include: 'Locked',NEWLINE 'Unlocked'NEWLINE :vartype state: str orNEWLINE ~azure.mgmt.storage.v2018_11_01.models.ImmutabilityPolicyStateNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'id': {'readonly': True},NEWLINE 'name': {'readonly': True},NEWLINE 'type': {'readonly': True},NEWLINE 'etag': {'readonly': True},NEWLINE 'immutability_period_since_creation_in_days': {'required': True},NEWLINE 'state': {'readonly': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'id': {'key': 'id', 'type': 'str'},NEWLINE 'name': {'key': 'name', 'type': 'str'},NEWLINE 'type': {'key': 'type', 'type': 'str'},NEWLINE 'etag': {'key': 'etag', 'type': 'str'},NEWLINE 'immutability_period_since_creation_in_days': {'key': 'properties.immutabilityPeriodSinceCreationInDays', 'type': 'int'},NEWLINE 'state': {'key': 'properties.state', 'type': 'str'},NEWLINE }NEWLINENEWLINE def __init__(self, **kwargs):NEWLINE super(ImmutabilityPolicy, self).__init__(**kwargs)NEWLINE self.immutability_period_since_creation_in_days = kwargs.get('immutability_period_since_creation_in_days', None)NEWLINE self.state = NoneNEWLINE import FWCore.ParameterSet.Config as cmsNEWLINENEWLINEL1GtRunSettingsViewer = cms.EDAnalyzer("L1GtRunSettingsViewer",NEWLINE prescalesKey = cms.string(""),NEWLINE maskAlgoKey = cms.string(""),NEWLINE maskTechKey = cms.string(""),NEWLINE maskVetoAlgoKey = cms.string(""),NEWLINE maskVetoTechKey = cms.string("")NEWLINE )NEWLINE # -*- coding: utf-8 -*-NEWLINENEWLINE# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:NEWLINE# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-codeNEWLINENEWLINEfrom ccxt.async_support.base.exchange import ExchangeNEWLINEimport base64NEWLINEimport hashlibNEWLINEfrom ccxt.base.errors import ArgumentsRequiredNEWLINENEWLINENEWLINEclass negociecoins (Exchange):NEWLINENEWLINE def describe(self):NEWLINE return self.deep_extend(super(negociecoins, self).describe(), {NEWLINE 'id': 'negociecoins',NEWLINE 'name': 'NegocieCoins',NEWLINE 'countries': ['BR'],NEWLINE 'rateLimit': 1000,NEWLINE 'version': 'v3',NEWLINE 'has': {NEWLINE 'createMarketOrder': False,NEWLINE 'fetchOrder': True,NEWLINE 'fetchOrders': True,NEWLINE 'fetchOpenOrders': True,NEWLINE 'fetchClosedOrders': True,NEWLINE },NEWLINE 'urls': {NEWLINE 'logo': 'https://user-images.githubusercontent.com/1294454/38008571-25a6246e-3258-11e8-969b-aeb691049245.jpg',NEWLINE 'api': {NEWLINE 'public': 'https://broker.negociecoins.com.br/api/v3',NEWLINE 'private': 'https://broker.negociecoins.com.br/tradeapi/v1',NEWLINE },NEWLINE 'www': 'https://www.negociecoins.com.br',NEWLINE 'doc': [NEWLINE 'https://www.negociecoins.com.br/documentacao-tradeapi',NEWLINE 'https://www.negociecoins.com.br/documentacao-api',NEWLINE ],NEWLINE 'fees': 'https://www.negociecoins.com.br/comissoes',NEWLINE },NEWLINE 'api': {NEWLINE 'public': {NEWLINE 'get': [NEWLINE '{PAR}/ticker',NEWLINE '{PAR}/orderbook',NEWLINE '{PAR}/trades',NEWLINE '{PAR}/trades/{timestamp_inicial}',NEWLINE '{PAR}/trades/{timestamp_inicial}/{timestamp_final}',NEWLINE ],NEWLINE },NEWLINE 'private': {NEWLINE 'get': [NEWLINE 'user/balance',NEWLINE 'user/order/{orderId}',NEWLINE ],NEWLINE 'post': [NEWLINE 'user/order',NEWLINE 'user/orders',NEWLINE ],NEWLINE 'delete': [NEWLINE 'user/order/{orderId}',NEWLINE ],NEWLINE },NEWLINE },NEWLINE 'markets': {NEWLINE 'B2X/BRL': {'id': 'b2xbrl', 'symbol': 'B2X/BRL', 'base': 'B2X', 'quote': 'BRL'},NEWLINE 'BCH/BRL': {'id': 'bchbrl', 'symbol': 'BCH/BRL', 'base': 'BCH', 'quote': 'BRL'},NEWLINE 'BTC/BRL': {'id': 'btcbrl', 'symbol': 'BTC/BRL', 'base': 'BTC', 'quote': 'BRL'},NEWLINE 'BTG/BRL': {'id': 'btgbrl', 'symbol': 'BTG/BRL', 'base': 'BTG', 'quote': 'BRL'},NEWLINE 'DASH/BRL': {'id': 'dashbrl', 'symbol': 'DASH/BRL', 'base': 'DASH', 'quote': 'BRL'},NEWLINE 'LTC/BRL': {'id': 'ltcbrl', 'symbol': 'LTC/BRL', 'base': 'LTC', 'quote': 'BRL'},NEWLINE },NEWLINE 'fees': {NEWLINE 'trading': {NEWLINE 'maker': 0.003,NEWLINE 'taker': 0.004,NEWLINE },NEWLINE 'funding': {NEWLINE 'withdraw': {NEWLINE 'BTC': 0.001,NEWLINE 'BCH': 0.00003,NEWLINE 'BTG': 0.00009,NEWLINE 'LTC': 0.005,NEWLINE },NEWLINE },NEWLINE },NEWLINE 'limits': {NEWLINE 'amount': {NEWLINE 'min': 0.001,NEWLINE 'max': None,NEWLINE },NEWLINE },NEWLINE 'precision': {NEWLINE 'amount': 8,NEWLINE 'price': 8,NEWLINE },NEWLINE })NEWLINENEWLINE def parse_ticker(self, ticker, market=None):NEWLINE timestamp = ticker['date'] * 1000NEWLINE symbol = market['symbol'] if (market is not None) else NoneNEWLINE last = self.safe_float(ticker, 'last')NEWLINE return {NEWLINE 'symbol': symbol,NEWLINE 'timestamp': timestamp,NEWLINE 'datetime': self.iso8601(timestamp),NEWLINE 'high': self.safe_float(ticker, 'high'),NEWLINE 'low': self.safe_float(ticker, 'low'),NEWLINE 'bid': self.safe_float(ticker, 'buy'),NEWLINE 'bidVolume': None,NEWLINE 'ask': self.safe_float(ticker, 'sell'),NEWLINE 'askVolume': None,NEWLINE 'vwap': None,NEWLINE 'open': None,NEWLINE 'close': last,NEWLINE 'last': last,NEWLINE 'previousClose': None,NEWLINE 'change': None,NEWLINE 'percentage': None,NEWLINE 'average': None,NEWLINE 'baseVolume': self.safe_float(ticker, 'vol'),NEWLINE 'quoteVolume': None,NEWLINE 'info': ticker,NEWLINE }NEWLINENEWLINE async def fetch_ticker(self, symbol, params={}):NEWLINE await self.load_markets()NEWLINE market = self.market(symbol)NEWLINE request = {NEWLINE 'PAR': market['id'],NEWLINE }NEWLINE ticker = await self.publicGetPARTicker(self.extend(request, params))NEWLINE return self.parse_ticker(ticker, market)NEWLINENEWLINE async def fetch_order_book(self, symbol, limit=None, params={}):NEWLINE await self.load_markets()NEWLINE request = {NEWLINE 'PAR': self.market_id(symbol),NEWLINE }NEWLINE response = await self.publicGetPAROrderbook(self.extend(request, params))NEWLINE return self.parse_order_book(response, None, 'bid', 'ask', 'price', 'quantity')NEWLINENEWLINE def parse_trade(self, trade, market=None):NEWLINE timestamp = trade['date'] * 1000NEWLINE price = self.safe_float(trade, 'price')NEWLINE amount = self.safe_float(trade, 'amount')NEWLINE cost = NoneNEWLINE if price is not None:NEWLINE if amount is not None:NEWLINE cost = price * amountNEWLINE symbol = NoneNEWLINE if market is not None:NEWLINE symbol = market['symbol']NEWLINE id = self.safe_string(trade, 'tid')NEWLINE type = 'limit'NEWLINE side = self.safe_string_lower(trade, 'type')NEWLINE return {NEWLINE 'timestamp': timestamp,NEWLINE 'datetime': self.iso8601(timestamp),NEWLINE 'symbol': symbol,NEWLINE 'id': id,NEWLINE 'order': None,NEWLINE 'type': type,NEWLINE 'side': side,NEWLINE 'price': price,NEWLINE 'amount': amount,NEWLINE 'cost': cost,NEWLINE 'fee': None,NEWLINE 'info': trade,NEWLINE }NEWLINENEWLINE async def fetch_trades(self, symbol, since=None, limit=None, params={}):NEWLINE await self.load_markets()NEWLINE market = self.market(symbol)NEWLINE if since is None:NEWLINE since = 0NEWLINE request = {NEWLINE 'PAR': market['id'],NEWLINE 'timestamp_inicial': int(since / 1000),NEWLINE }NEWLINE response = await self.publicGetPARTradesTimestampInicial(self.extend(request, params))NEWLINE return self.parse_trades(response, market, since, limit)NEWLINENEWLINE async def fetch_balance(self, params={}):NEWLINE await self.load_markets()NEWLINE response = await self.privateGetUserBalance(params)NEWLINE #NEWLINE # {NEWLINE # "coins": [NEWLINE # {"name":"BRL","available":0.0,"openOrders":0.0,"withdraw":0.0,"total":0.0},NEWLINE # {"name":"BTC","available":0.0,"openOrders":0.0,"withdraw":0.0,"total":0.0},NEWLINE # ],NEWLINE # }NEWLINE #NEWLINE result = {'info': response}NEWLINE balances = self.safe_value(response, 'coins')NEWLINE for i in range(0, len(balances)):NEWLINE balance = balances[i]NEWLINE currencyId = self.safe_string(balance, 'name')NEWLINE code = self.safe_currency_code(currencyId)NEWLINE openOrders = self.safe_float(balance, 'openOrders')NEWLINE withdraw = self.safe_float(balance, 'withdraw')NEWLINE account = {NEWLINE 'free': self.safe_float(balance, 'total'),NEWLINE 'used': self.sum(openOrders, withdraw),NEWLINE 'total': self.safe_float(balance, 'available'),NEWLINE }NEWLINE result[code] = accountNEWLINE return self.parse_balance(result)NEWLINENEWLINE def parse_order_status(self, status):NEWLINE statuses = {NEWLINE 'filled': 'closed',NEWLINE 'cancelled': 'canceled',NEWLINE 'partially filled': 'open',NEWLINE 'pending': 'open',NEWLINE 'rejected': 'rejected',NEWLINE }NEWLINE return self.safe_string(statuses, status, status)NEWLINENEWLINE def parse_order(self, order, market=None):NEWLINE symbol = NoneNEWLINE if market is None:NEWLINE marketId = self.safe_string(order, 'pair')NEWLINE market = self.safe_value(self.marketsById, marketId)NEWLINE if market:NEWLINE symbol = market['symbol']NEWLINE timestamp = self.parse8601(self.safe_string(order, 'created'))NEWLINE price = self.safe_float(order, 'price')NEWLINE amount = self.safe_float(order, 'quantity')NEWLINE cost = self.safe_float(order, 'total')NEWLINE remaining = self.safe_float(order, 'pending_quantity')NEWLINE filled = self.safe_float(order, 'executed_quantity')NEWLINE status = self.parse_order_status(self.safe_string(order, 'status'))NEWLINE trades = NoneNEWLINE # if order['operations']:NEWLINE # trades = self.parse_trades(order['operations'])NEWLINE return {NEWLINE 'id': str(order['id']),NEWLINE 'datetime': self.iso8601(timestamp),NEWLINE 'timestamp': timestamp,NEWLINE 'lastTradeTimestamp': None,NEWLINE 'status': status,NEWLINE 'symbol': symbol,NEWLINE 'type': 'limit',NEWLINE 'side': order['type'],NEWLINE 'price': price,NEWLINE 'cost': cost,NEWLINE 'amount': amount,NEWLINE 'filled': filled,NEWLINE 'remaining': remaining,NEWLINE 'trades': trades,NEWLINE 'fee': {NEWLINE 'currency': market['quote'],NEWLINE 'cost': self.safe_float(order, 'fee'),NEWLINE },NEWLINE 'info': order,NEWLINE }NEWLINENEWLINE async def create_order(self, symbol, type, side, amount, price=None, params={}):NEWLINE await self.load_markets()NEWLINE market = self.market(symbol)NEWLINE request = {NEWLINE 'pair': market['id'],NEWLINE 'price': self.price_to_precision(symbol, price),NEWLINE 'volume': self.amount_to_precision(symbol, amount),NEWLINE 'type': side,NEWLINE }NEWLINE response = await self.privatePostUserOrder(self.extend(request, params))NEWLINE order = self.parse_order(response[0], market)NEWLINE id = order['id']NEWLINE self.orders[id] = orderNEWLINE return orderNEWLINENEWLINE async def cancel_order(self, id, symbol=None, params={}):NEWLINE await self.load_markets()NEWLINE market = self.markets[symbol]NEWLINE request = {NEWLINE 'orderId': id,NEWLINE }NEWLINE response = await self.privateDeleteUserOrderOrderId(self.extend(request, params))NEWLINE return self.parse_order(response[0], market)NEWLINENEWLINE async def fetch_order(self, id, symbol=None, params={}):NEWLINE await self.load_markets()NEWLINE request = {NEWLINE 'orderId': id,NEWLINE }NEWLINE order = await self.privateGetUserOrderOrderId(self.extend(request, params))NEWLINE return self.parse_order(order[0])NEWLINENEWLINE async def fetch_orders(self, symbol=None, since=None, limit=None, params={}):NEWLINE await self.load_markets()NEWLINE if symbol is None:NEWLINE raise ArgumentsRequired(self.id + ' fetchOrders() requires a symbol argument')NEWLINE market = self.market(symbol)NEWLINE request = {NEWLINE 'pair': market['id'],NEWLINE # type: buy, sellNEWLINE # status: cancelled, filled, partially filled, pending, rejectedNEWLINE # startIdNEWLINE # endIdNEWLINE # startDate yyyy-MM-ddNEWLINE # endDate: yyyy-MM-ddNEWLINE }NEWLINE if since is not None:NEWLINE request['startDate'] = self.ymd(since)NEWLINE if limit is not None:NEWLINE request['pageSize'] = limitNEWLINE orders = await self.privatePostUserOrders(self.extend(request, params))NEWLINE return self.parse_orders(orders, market)NEWLINENEWLINE async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):NEWLINE request = {NEWLINE 'status': 'pending',NEWLINE }NEWLINE return await self.fetch_orders(symbol, since, limit, self.extend(request, params))NEWLINENEWLINE async def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):NEWLINE request = {NEWLINE 'status': 'filled',NEWLINE }NEWLINE return await self.fetch_orders(symbol, since, limit, self.extend(request, params))NEWLINENEWLINE def nonce(self):NEWLINE return self.milliseconds()NEWLINENEWLINE def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):NEWLINE url = self.urls['api'][api] + '/' + self.implode_params(path, params)NEWLINE query = self.omit(params, self.extract_params(path))NEWLINE queryString = self.urlencode(query)NEWLINE if api == 'public':NEWLINE if len(queryString):NEWLINE url += '?' + queryStringNEWLINE else:NEWLINE self.check_required_credentials()NEWLINE timestamp = str(self.seconds())NEWLINE nonce = str(self.nonce())NEWLINE content = ''NEWLINE if len(queryString):NEWLINE body = self.json(query)NEWLINE content = self.hash(self.encode(body), 'md5', 'base64')NEWLINE else:NEWLINE body = ''NEWLINE uri = self.encode_uri_component(url).lower()NEWLINE payload = ''.join([self.apiKey, method, uri, timestamp, nonce, content])NEWLINE secret = base64.b64decode(self.secret)NEWLINE signature = self.hmac(self.encode(payload), secret, hashlib.sha256, 'base64')NEWLINE signature = self.decode(signature)NEWLINE auth = ':'.join([self.apiKey, signature, nonce, timestamp])NEWLINE headers = {NEWLINE 'Authorization': 'amx ' + auth,NEWLINE }NEWLINE if method == 'POST':NEWLINE headers['Content-Type'] = 'application/json; charset=UTF-8'NEWLINE headers['Content-Length'] = len(body)NEWLINE elif len(queryString):NEWLINE url += '?' + queryStringNEWLINE body = NoneNEWLINE return {'url': url, 'method': method, 'body': body, 'headers': headers}NEWLINE # import numpyNEWLINEimport numpy as npNEWLINENEWLINE# importing qiskitNEWLINEimport qiskitNEWLINEfrom qiskit import QuantumCircuit, ClassicalRegister, QuantumRegisterNEWLINEfrom qiskit.compiler import schedule, transpileNEWLINENEWLINEfrom qiskit.test.mock.backends.almaden import FakeAlmadenNEWLINEbackend = FakeAlmaden()NEWLINENEWLINEfrom qiskit.pulse.instructions.play import PlayNEWLINENEWLINE# importing audio utilsNEWLINEfrom scipy.io.wavfile import writeNEWLINENEWLINE# CONSTANTSNEWLINEsampling_rate = 44100 * 3NEWLINENEWLINEdef test_qiskit(): return qiskit.__qiskit_version__NEWLINENEWLINEdef char_to_qc(char_str):NEWLINE char_bin = '0'+' '.join(format(ord(x), 'b') for x in char_str)NEWLINENEWLINE char = QuantumRegister(8, name='char')NEWLINE output = QuantumRegister(1, name='output')NEWLINE meas = ClassicalRegister(8, name='meas')NEWLINE char_qc = QuantumCircuit(char, output, meas)NEWLINENEWLINE char_qc.h(char[:])NEWLINE char_qc.h(output)NEWLINE char_qc.z(output)NEWLINE char_qc.barrier()NEWLINENEWLINE for i, bit in enumerate(char_bin):NEWLINE if int(bit): char_qc.cx(char[i], output[0])NEWLINE char_qc.barrier()NEWLINENEWLINE char_qc.h(char[:])NEWLINE char_qc.barrier()NEWLINENEWLINE return char_qc.reverse_bits()NEWLINENEWLINEdef pulse_schedule_to_complex_waveform(pulse_schedule):NEWLINE instructions = pulse_schedule.instructionsNEWLINE waveform = [instruction[1].pulse.samples for instruction in instructions if type(instruction[1]) == Play]NEWLINE waveform = np.concatenate(waveform).ravel()NEWLINE return waveformNEWLINENEWLINEdef complex_waveform_to_amplitude_waveform(waveform): return np.asarray([np.absolute(z) for z in waveform])NEWLINENEWLINEdef get_audio_waveform(string):NEWLINE words = string.split(" ")NEWLINE audio_waveform = np.array([])NEWLINE for word in words:NEWLINE word_waveforms = [ pulse_schedule_to_complex_waveform(schedule(transpile(char_to_qc(char), backend), backend)) for char in word ]NEWLINE waveform_size = max([waveform.size for waveform in word_waveforms])NEWLINE word_waveform = np.zeros(waveform_size)NEWLINE for waveform in word_waveforms: NEWLINE word_waveform = word_waveform + np.pad(waveform, (0, waveform_size - waveform.size), mode='constant')NEWLINE audio_waveform = np.concatenate((audio_waveform, complex_waveform_to_amplitude_waveform(waveform)))NEWLINE return audio_waveformNEWLINENEWLINEdef generate_wav(string):NEWLINE data = get_audio_waveform(string)NEWLINE scaled = np.int16(data/np.max(np.abs(data)) * 32767)NEWLINE write('/tmp/output.wav', sampling_rate, scaled) # Author: Steven J. Bethard .NEWLINENEWLINE"""Command-line parsing libraryNEWLINENEWLINEThis module is an optparse-inspired command-line parsing library that:NEWLINENEWLINE - handles both optional and positional argumentsNEWLINE - produces highly informative usage messagesNEWLINE - supports parsers that dispatch to sub-parsersNEWLINENEWLINEThe following is a simple usage example that sums integers from theNEWLINEcommand-line and writes the result to a file::NEWLINENEWLINE parser = argparse.ArgumentParser(NEWLINE description='sum the integers at the command line')NEWLINE parser.add_argument(NEWLINE 'integers', metavar='int', nargs='+', type=int,NEWLINE help='an integer to be summed')NEWLINE parser.add_argument(NEWLINE '--log', default=sys.stdout, type=argparse.FileType('w'),NEWLINE help='the file where the sum should be written')NEWLINE args = parser.parse_args()NEWLINE args.log.write('%s' % sum(args.integers))NEWLINE args.log.close()NEWLINENEWLINEThe module contains the following public classes:NEWLINENEWLINE - ArgumentParser -- The main entry point for command-line parsing. As theNEWLINE example above shows, the add_argument() method is used to populateNEWLINE the parser with actions for optional and positional arguments. ThenNEWLINE the parse_args() method is invoked to convert the args at theNEWLINE command-line into an object with attributes.NEWLINENEWLINE - ArgumentError -- The exception raised by ArgumentParser objects whenNEWLINE there are errors with the parser's actions. Errors raised whileNEWLINE parsing the command-line are caught by ArgumentParser and emittedNEWLINE as command-line messages.NEWLINENEWLINE - FileType -- A factory for defining types of files to be created. As theNEWLINE example above shows, instances of FileType are typically passed asNEWLINE the type= argument of add_argument() calls.NEWLINENEWLINE - Action -- The base class for parser actions. Typically actions areNEWLINE selected by passing strings like 'store_true' or 'append_const' toNEWLINE the action= argument of add_argument(). However, for greaterNEWLINE customization of ArgumentParser actions, subclasses of Action mayNEWLINE be defined and passed as the action= argument.NEWLINENEWLINE - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,NEWLINE ArgumentDefaultsHelpFormatter -- Formatter classes whichNEWLINE may be passed as the formatter_class= argument to theNEWLINE ArgumentParser constructor. HelpFormatter is the default,NEWLINE RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parserNEWLINE not to change the formatting for help text, andNEWLINE ArgumentDefaultsHelpFormatter adds information about argument defaultsNEWLINE to the help.NEWLINENEWLINEAll other classes in this module are considered implementation details.NEWLINE(Also note that HelpFormatter and RawDescriptionHelpFormatter are onlyNEWLINEconsidered public as object names -- the API of the formatter objects isNEWLINEstill considered an implementation detail.)NEWLINE"""NEWLINENEWLINE__version__ = '1.1'NEWLINE__all__ = [NEWLINE 'ArgumentParser',NEWLINE 'ArgumentError',NEWLINE 'ArgumentTypeError',NEWLINE 'FileType',NEWLINE 'HelpFormatter',NEWLINE 'ArgumentDefaultsHelpFormatter',NEWLINE 'RawDescriptionHelpFormatter',NEWLINE 'RawTextHelpFormatter',NEWLINE 'Namespace',NEWLINE 'Action',NEWLINE 'ONE_OR_MORE',NEWLINE 'OPTIONAL',NEWLINE 'PARSER',NEWLINE 'REMAINDER',NEWLINE 'SUPPRESS',NEWLINE 'ZERO_OR_MORE',NEWLINE]NEWLINENEWLINENEWLINEimport collections as _collectionsNEWLINEimport copy as _copyNEWLINEimport os as _osNEWLINEimport re as _reNEWLINEimport sys as _sysNEWLINEimport textwrap as _textwrapNEWLINENEWLINEfrom gettext import gettext as _NEWLINENEWLINENEWLINEdef _callable(obj):NEWLINE return hasattr(obj, '__call__') or hasattr(obj, '__bases__')NEWLINENEWLINENEWLINESUPPRESS = '==SUPPRESS=='NEWLINENEWLINEOPTIONAL = '?'NEWLINEZERO_OR_MORE = '*'NEWLINEONE_OR_MORE = '+'NEWLINEPARSER = 'A...'NEWLINEREMAINDER = '...'NEWLINE_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'NEWLINENEWLINE# =============================NEWLINE# Utility functions and classesNEWLINE# =============================NEWLINENEWLINEclass _AttributeHolder(object):NEWLINE """Abstract base class that provides __repr__.NEWLINENEWLINE The __repr__ method returns a string in the format::NEWLINE ClassName(attr=name, attr=name, ...)NEWLINE The attributes are determined either by a class-level attribute,NEWLINE '_kwarg_names', or by inspecting the instance __dict__.NEWLINE """NEWLINENEWLINE def __repr__(self):NEWLINE type_name = type(self).__name__NEWLINE arg_strings = []NEWLINE for arg in self._get_args():NEWLINE arg_strings.append(repr(arg))NEWLINE for name, value in self._get_kwargs():NEWLINE arg_strings.append('%s=%r' % (name, value))NEWLINE return '%s(%s)' % (type_name, ', '.join(arg_strings))NEWLINENEWLINE def _get_kwargs(self):NEWLINE return sorted(self.__dict__.items())NEWLINENEWLINE def _get_args(self):NEWLINE return []NEWLINENEWLINENEWLINEdef _ensure_value(namespace, name, value):NEWLINE if getattr(namespace, name, None) is None:NEWLINE setattr(namespace, name, value)NEWLINE return getattr(namespace, name)NEWLINENEWLINENEWLINE# ===============NEWLINE# Formatting HelpNEWLINE# ===============NEWLINENEWLINEclass HelpFormatter(object):NEWLINE """Formatter for generating usage messages and argument help strings.NEWLINENEWLINE Only the name of this class is considered a public API. All the methodsNEWLINE provided by the class are considered an implementation detail.NEWLINE """NEWLINENEWLINE def __init__(self,NEWLINE prog,NEWLINE indent_increment=2,NEWLINE max_help_position=24,NEWLINE width=None):NEWLINENEWLINE # default setting for widthNEWLINE if width is None:NEWLINE try:NEWLINE width = int(_os.environ['COLUMNS'])NEWLINE except (KeyError, ValueError):NEWLINE width = 80NEWLINE width -= 2NEWLINENEWLINE self._prog = progNEWLINE self._indent_increment = indent_incrementNEWLINE self._max_help_position = max_help_positionNEWLINE self._max_help_position = min(max_help_position,NEWLINE max(width - 20, indent_increment * 2))NEWLINE self._width = widthNEWLINENEWLINE self._current_indent = 0NEWLINE self._level = 0NEWLINE self._action_max_length = 0NEWLINENEWLINE self._root_section = self._Section(self, None)NEWLINE self._current_section = self._root_sectionNEWLINENEWLINE self._whitespace_matcher = _re.compile(r'\s+')NEWLINE self._long_break_matcher = _re.compile(r'\n\n\n+')NEWLINENEWLINE # ===============================NEWLINE # Section and indentation methodsNEWLINE # ===============================NEWLINE def _indent(self):NEWLINE self._current_indent += self._indent_incrementNEWLINE self._level += 1NEWLINENEWLINE def _dedent(self):NEWLINE self._current_indent -= self._indent_incrementNEWLINE assert self._current_indent >= 0, 'Indent decreased below 0.'NEWLINE self._level -= 1NEWLINENEWLINE class _Section(object):NEWLINENEWLINE def __init__(self, formatter, parent, heading=None):NEWLINE self.formatter = formatterNEWLINE self.parent = parentNEWLINE self.heading = headingNEWLINE self.items = []NEWLINENEWLINE def format_help(self):NEWLINE # format the indented sectionNEWLINE if self.parent is not None:NEWLINE self.formatter._indent()NEWLINE join = self.formatter._join_partsNEWLINE for func, args in self.items:NEWLINE func(*args)NEWLINE item_help = join([func(*args) for func, args in self.items])NEWLINE if self.parent is not None:NEWLINE self.formatter._dedent()NEWLINENEWLINE # return nothing if the section was emptyNEWLINE if not item_help:NEWLINE return ''NEWLINENEWLINE # add the heading if the section was non-emptyNEWLINE if self.heading is not SUPPRESS and self.heading is not None:NEWLINE current_indent = self.formatter._current_indentNEWLINE heading = '%*s%s:\n' % (current_indent, '', self.heading)NEWLINE else:NEWLINE heading = ''NEWLINENEWLINE # join the section-initial newline, the heading and the helpNEWLINE return join(['\n', heading, item_help, '\n'])NEWLINENEWLINE def _add_item(self, func, args):NEWLINE self._current_section.items.append((func, args))NEWLINENEWLINE # ========================NEWLINE # Message building methodsNEWLINE # ========================NEWLINE def start_section(self, heading):NEWLINE self._indent()NEWLINE section = self._Section(self, self._current_section, heading)NEWLINE self._add_item(section.format_help, [])NEWLINE self._current_section = sectionNEWLINENEWLINE def end_section(self):NEWLINE self._current_section = self._current_section.parentNEWLINE self._dedent()NEWLINENEWLINE def add_text(self, text):NEWLINE if text is not SUPPRESS and text is not None:NEWLINE self._add_item(self._format_text, [text])NEWLINENEWLINE def add_usage(self, usage, actions, groups, prefix=None):NEWLINE if usage is not SUPPRESS:NEWLINE args = usage, actions, groups, prefixNEWLINE self._add_item(self._format_usage, args)NEWLINENEWLINE def add_argument(self, action):NEWLINE if action.help is not SUPPRESS:NEWLINENEWLINE # find all invocationsNEWLINE get_invocation = self._format_action_invocationNEWLINE invocations = [get_invocation(action)]NEWLINE for subaction in self._iter_indented_subactions(action):NEWLINE invocations.append(get_invocation(subaction))NEWLINENEWLINE # update the maximum item lengthNEWLINE invocation_length = max([len(s) for s in invocations])NEWLINE action_length = invocation_length + self._current_indentNEWLINE self._action_max_length = max(self._action_max_length,NEWLINE action_length)NEWLINENEWLINE # add the item to the listNEWLINE self._add_item(self._format_action, [action])NEWLINENEWLINE def add_arguments(self, actions):NEWLINE for action in actions:NEWLINE self.add_argument(action)NEWLINENEWLINE # =======================NEWLINE # Help-formatting methodsNEWLINE # =======================NEWLINE def format_help(self):NEWLINE help = self._root_section.format_help()NEWLINE if help:NEWLINE help = self._long_break_matcher.sub('\n\n', help)NEWLINE help = help.strip('\n') + '\n'NEWLINE return helpNEWLINENEWLINE def _join_parts(self, part_strings):NEWLINE return ''.join([partNEWLINE for part in part_stringsNEWLINE if part and part is not SUPPRESS])NEWLINENEWLINE def _format_usage(self, usage, actions, groups, prefix):NEWLINE if prefix is None:NEWLINE prefix = _('usage: ')NEWLINENEWLINE # if usage is specified, use thatNEWLINE if usage is not None:NEWLINE usage = usage % dict(prog=self._prog)NEWLINENEWLINE # if no optionals or positionals are available, usage is just progNEWLINE elif usage is None and not actions:NEWLINE usage = '%(prog)s' % dict(prog=self._prog)NEWLINENEWLINE # if optionals and positionals are available, calculate usageNEWLINE elif usage is None:NEWLINE prog = '%(prog)s' % dict(prog=self._prog)NEWLINENEWLINE # split optionals from positionalsNEWLINE optionals = []NEWLINE positionals = []NEWLINE for action in actions:NEWLINE if action.option_strings:NEWLINE optionals.append(action)NEWLINE else:NEWLINE positionals.append(action)NEWLINENEWLINE # build full usage stringNEWLINE format = self._format_actions_usageNEWLINE action_usage = format(optionals + positionals, groups)NEWLINE usage = ' '.join([s for s in [prog, action_usage] if s])NEWLINENEWLINE # wrap the usage parts if it's too longNEWLINE text_width = self._width - self._current_indentNEWLINE if len(prefix) + len(usage) > text_width:NEWLINENEWLINE # break usage into wrappable partsNEWLINE part_regexp = (NEWLINE r'\(.*?\)+(?=\s|$)|'NEWLINE r'\[.*?\]+(?=\s|$)|'NEWLINE r'\S+'NEWLINE )NEWLINE opt_usage = format(optionals, groups)NEWLINE pos_usage = format(positionals, groups)NEWLINE opt_parts = _re.findall(part_regexp, opt_usage)NEWLINE pos_parts = _re.findall(part_regexp, pos_usage)NEWLINE assert ' '.join(opt_parts) == opt_usageNEWLINE assert ' '.join(pos_parts) == pos_usageNEWLINENEWLINE # helper for wrapping linesNEWLINE def get_lines(parts, indent, prefix=None):NEWLINE lines = []NEWLINE line = []NEWLINE if prefix is not None:NEWLINE line_len = len(prefix) - 1NEWLINE else:NEWLINE line_len = len(indent) - 1NEWLINE for part in parts:NEWLINE if line_len + 1 + len(part) > text_width and line:NEWLINE lines.append(indent + ' '.join(line))NEWLINE line = []NEWLINE line_len = len(indent) - 1NEWLINE line.append(part)NEWLINE line_len += len(part) + 1NEWLINE if line:NEWLINE lines.append(indent + ' '.join(line))NEWLINE if prefix is not None:NEWLINE lines[0] = lines[0][len(indent):]NEWLINE return linesNEWLINENEWLINE # if prog is short, follow it with optionals or positionalsNEWLINE if len(prefix) + len(prog) <= 0.75 * text_width:NEWLINE indent = ' ' * (len(prefix) + len(prog) + 1)NEWLINE if opt_parts:NEWLINE lines = get_lines([prog] + opt_parts, indent, prefix)NEWLINE lines.extend(get_lines(pos_parts, indent))NEWLINE elif pos_parts:NEWLINE lines = get_lines([prog] + pos_parts, indent, prefix)NEWLINE else:NEWLINE lines = [prog]NEWLINENEWLINE # if prog is long, put it on its own lineNEWLINE else:NEWLINE indent = ' ' * len(prefix)NEWLINE parts = opt_parts + pos_partsNEWLINE lines = get_lines(parts, indent)NEWLINE if len(lines) > 1:NEWLINE lines = []NEWLINE lines.extend(get_lines(opt_parts, indent))NEWLINE lines.extend(get_lines(pos_parts, indent))NEWLINE lines = [prog] + linesNEWLINENEWLINE # join lines into usageNEWLINE usage = '\n'.join(lines)NEWLINENEWLINE # prefix with 'usage:'NEWLINE return '%s%s\n\n' % (prefix, usage)NEWLINENEWLINE def _format_actions_usage(self, actions, groups):NEWLINE # find group indices and identify actions in groupsNEWLINE group_actions = set()NEWLINE inserts = {}NEWLINE for group in groups:NEWLINE try:NEWLINE start = actions.index(group._group_actions[0])NEWLINE except ValueError:NEWLINE continueNEWLINE else:NEWLINE end = start + len(group._group_actions)NEWLINE if actions[start:end] == group._group_actions:NEWLINE for action in group._group_actions:NEWLINE group_actions.add(action)NEWLINE if not group.required:NEWLINE if start in inserts:NEWLINE inserts[start] += ' ['NEWLINE else:NEWLINE inserts[start] = '['NEWLINE inserts[end] = ']'NEWLINE else:NEWLINE if start in inserts:NEWLINE inserts[start] += ' ('NEWLINE else:NEWLINE inserts[start] = '('NEWLINE inserts[end] = ')'NEWLINE for i in range(start + 1, end):NEWLINE inserts[i] = '|'NEWLINENEWLINE # collect all actions format stringsNEWLINE parts = []NEWLINE for i, action in enumerate(actions):NEWLINENEWLINE # suppressed arguments are marked with NoneNEWLINE # remove | separators for suppressed argumentsNEWLINE if action.help is SUPPRESS:NEWLINE parts.append(None)NEWLINE if inserts.get(i) == '|':NEWLINE inserts.pop(i)NEWLINE elif inserts.get(i + 1) == '|':NEWLINE inserts.pop(i + 1)NEWLINENEWLINE # produce all arg stringsNEWLINE elif not action.option_strings:NEWLINE part = self._format_args(action, action.dest)NEWLINENEWLINE # if it's in a group, strip the outer []NEWLINE if action in group_actions:NEWLINE if part[0] == '[' and part[-1] == ']':NEWLINE part = part[1:-1]NEWLINENEWLINE # add the action string to the listNEWLINE parts.append(part)NEWLINENEWLINE # produce the first way to invoke the option in bracketsNEWLINE else:NEWLINE option_string = action.option_strings[0]NEWLINENEWLINE # if the Optional doesn't take a value, format is:NEWLINE # -s or --longNEWLINE if action.nargs == 0:NEWLINE part = '%s' % option_stringNEWLINENEWLINE # if the Optional takes a value, format is:NEWLINE # -s ARGS or --long ARGSNEWLINE else:NEWLINE default = action.dest.upper()NEWLINE args_string = self._format_args(action, default)NEWLINE part = '%s %s' % (option_string, args_string)NEWLINENEWLINE # make it look optional if it's not required or in a groupNEWLINE if not action.required and action not in group_actions:NEWLINE part = '[%s]' % partNEWLINENEWLINE # add the action string to the listNEWLINE parts.append(part)NEWLINENEWLINE # insert things at the necessary indicesNEWLINE for i in sorted(inserts, reverse=True):NEWLINE parts[i:i] = [inserts[i]]NEWLINENEWLINE # join all the action items with spacesNEWLINE text = ' '.join([item for item in parts if item is not None])NEWLINENEWLINE # clean up separators for mutually exclusive groupsNEWLINE open = r'[\[(]'NEWLINE close = r'[\])]'NEWLINE text = _re.sub(r'(%s) ' % open, r'\1', text)NEWLINE text = _re.sub(r' (%s)' % close, r'\1', text)NEWLINE text = _re.sub(r'%s *%s' % (open, close), r'', text)NEWLINE text = _re.sub(r'\(([^|]*)\)', r'\1', text)NEWLINE text = text.strip()NEWLINENEWLINE # return the textNEWLINE return textNEWLINENEWLINE def _format_text(self, text):NEWLINE if '%(prog)' in text:NEWLINE text = text % dict(prog=self._prog)NEWLINE text_width = max(self._width - self._current_indent, 11)NEWLINE indent = ' ' * self._current_indentNEWLINE return self._fill_text(text, text_width, indent) + '\n\n'NEWLINENEWLINE def _format_action(self, action):NEWLINE # determine the required width and the entry labelNEWLINE help_position = min(self._action_max_length + 2,NEWLINE self._max_help_position)NEWLINE help_width = max(self._width - help_position, 11)NEWLINE action_width = help_position - self._current_indent - 2NEWLINE action_header = self._format_action_invocation(action)NEWLINENEWLINE # ho nelp; start on same line and add a final newlineNEWLINE if not action.help:NEWLINE tup = self._current_indent, '', action_headerNEWLINE action_header = '%*s%s\n' % tupNEWLINENEWLINE # short action name; start on the same line and pad two spacesNEWLINE elif len(action_header) <= action_width:NEWLINE tup = self._current_indent, '', action_width, action_headerNEWLINE action_header = '%*s%-*s ' % tupNEWLINE indent_first = 0NEWLINENEWLINE # long action name; start on the next lineNEWLINE else:NEWLINE tup = self._current_indent, '', action_headerNEWLINE action_header = '%*s%s\n' % tupNEWLINE indent_first = help_positionNEWLINENEWLINE # collect the pieces of the action helpNEWLINE parts = [action_header]NEWLINENEWLINE # if there was help for the action, add lines of help textNEWLINE if action.help:NEWLINE help_text = self._expand_help(action)NEWLINE help_lines = self._split_lines(help_text, help_width)NEWLINE parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))NEWLINE for line in help_lines[1:]:NEWLINE parts.append('%*s%s\n' % (help_position, '', line))NEWLINENEWLINE # or add a newline if the description doesn't end with oneNEWLINE elif not action_header.endswith('\n'):NEWLINE parts.append('\n')NEWLINENEWLINE # if there are any sub-actions, add their help as wellNEWLINE for subaction in self._iter_indented_subactions(action):NEWLINE parts.append(self._format_action(subaction))NEWLINENEWLINE # return a single stringNEWLINE return self._join_parts(parts)NEWLINENEWLINE def _format_action_invocation(self, action):NEWLINE if not action.option_strings:NEWLINE metavar, = self._metavar_formatter(action, action.dest)(1)NEWLINE return metavarNEWLINENEWLINE else:NEWLINE parts = []NEWLINENEWLINE # if the Optional doesn't take a value, format is:NEWLINE # -s, --longNEWLINE if action.nargs == 0:NEWLINE parts.extend(action.option_strings)NEWLINENEWLINE # if the Optional takes a value, format is:NEWLINE # -s ARGS, --long ARGSNEWLINE else:NEWLINE default = action.dest.upper()NEWLINE args_string = self._format_args(action, default)NEWLINE for option_string in action.option_strings:NEWLINE parts.append('%s %s' % (option_string, args_string))NEWLINENEWLINE return ', '.join(parts)NEWLINENEWLINE def _metavar_formatter(self, action, default_metavar):NEWLINE if action.metavar is not None:NEWLINE result = action.metavarNEWLINE elif action.choices is not None:NEWLINE choice_strs = [str(choice) for choice in action.choices]NEWLINE result = '{%s}' % ','.join(choice_strs)NEWLINE else:NEWLINE result = default_metavarNEWLINENEWLINE def format(tuple_size):NEWLINE if isinstance(result, tuple):NEWLINE return resultNEWLINE else:NEWLINE return (result, ) * tuple_sizeNEWLINE return formatNEWLINENEWLINE def _format_args(self, action, default_metavar):NEWLINE get_metavar = self._metavar_formatter(action, default_metavar)NEWLINE if action.nargs is None:NEWLINE result = '%s' % get_metavar(1)NEWLINE elif action.nargs == OPTIONAL:NEWLINE result = '[%s]' % get_metavar(1)NEWLINE elif action.nargs == ZERO_OR_MORE:NEWLINE result = '[%s [%s ...]]' % get_metavar(2)NEWLINE elif action.nargs == ONE_OR_MORE:NEWLINE result = '%s [%s ...]' % get_metavar(2)NEWLINE elif action.nargs == REMAINDER:NEWLINE result = '...'NEWLINE elif action.nargs == PARSER:NEWLINE result = '%s ...' % get_metavar(1)NEWLINE else:NEWLINE formats = ['%s' for _ in range(action.nargs)]NEWLINE result = ' '.join(formats) % get_metavar(action.nargs)NEWLINE return resultNEWLINENEWLINE def _expand_help(self, action):NEWLINE params = dict(vars(action), prog=self._prog)NEWLINE for name in list(params):NEWLINE if params[name] is SUPPRESS:NEWLINE del params[name]NEWLINE for name in list(params):NEWLINE if hasattr(params[name], '__name__'):NEWLINE params[name] = params[name].__name__NEWLINE if params.get('choices') is not None:NEWLINE choices_str = ', '.join([str(c) for c in params['choices']])NEWLINE params['choices'] = choices_strNEWLINE return self._get_help_string(action) % paramsNEWLINENEWLINE def _iter_indented_subactions(self, action):NEWLINE try:NEWLINE get_subactions = action._get_subactionsNEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE self._indent()NEWLINE for subaction in get_subactions():NEWLINE yield subactionNEWLINE self._dedent()NEWLINENEWLINE def _split_lines(self, text, width):NEWLINE text = self._whitespace_matcher.sub(' ', text).strip()NEWLINE return _textwrap.wrap(text, width)NEWLINENEWLINE def _fill_text(self, text, width, indent):NEWLINE text = self._whitespace_matcher.sub(' ', text).strip()NEWLINE return _textwrap.fill(text, width, initial_indent=indent,NEWLINE subsequent_indent=indent)NEWLINENEWLINE def _get_help_string(self, action):NEWLINE return action.helpNEWLINENEWLINENEWLINEclass RawDescriptionHelpFormatter(HelpFormatter):NEWLINE """Help message formatter which retains any formatting in descriptions.NEWLINENEWLINE Only the name of this class is considered a public API. All the methodsNEWLINE provided by the class are considered an implementation detail.NEWLINE """NEWLINENEWLINE def _fill_text(self, text, width, indent):NEWLINE return ''.join([indent + line for line in text.splitlines(True)])NEWLINENEWLINENEWLINEclass RawTextHelpFormatter(RawDescriptionHelpFormatter):NEWLINE """Help message formatter which retains formatting of all help text.NEWLINENEWLINE Only the name of this class is considered a public API. All the methodsNEWLINE provided by the class are considered an implementation detail.NEWLINE """NEWLINENEWLINE def _split_lines(self, text, width):NEWLINE return text.splitlines()NEWLINENEWLINENEWLINEclass ArgumentDefaultsHelpFormatter(HelpFormatter):NEWLINE """Help message formatter which adds default values to argument help.NEWLINENEWLINE Only the name of this class is considered a public API. All the methodsNEWLINE provided by the class are considered an implementation detail.NEWLINE """NEWLINENEWLINE def _get_help_string(self, action):NEWLINE help = action.helpNEWLINE if '%(default)' not in action.help:NEWLINE if action.default is not SUPPRESS:NEWLINE defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]NEWLINE if action.option_strings or action.nargs in defaulting_nargs:NEWLINE help += ' (default: %(default)s)'NEWLINE return helpNEWLINENEWLINENEWLINE# =====================NEWLINE# Options and ArgumentsNEWLINE# =====================NEWLINENEWLINEdef _get_action_name(argument):NEWLINE if argument is None:NEWLINE return NoneNEWLINE elif argument.option_strings:NEWLINE return '/'.join(argument.option_strings)NEWLINE elif argument.metavar not in (None, SUPPRESS):NEWLINE return argument.metavarNEWLINE elif argument.dest not in (None, SUPPRESS):NEWLINE return argument.destNEWLINE else:NEWLINE return NoneNEWLINENEWLINENEWLINEclass ArgumentError(Exception):NEWLINE """An error from creating or using an argument (optional or positional).NEWLINENEWLINE The string value of this exception is the message, augmented withNEWLINE information about the argument that caused it.NEWLINE """NEWLINENEWLINE def __init__(self, argument, message):NEWLINE self.argument_name = _get_action_name(argument)NEWLINE self.message = messageNEWLINENEWLINE def __str__(self):NEWLINE if self.argument_name is None:NEWLINE format = '%(message)s'NEWLINE else:NEWLINE format = 'argument %(argument_name)s: %(message)s'NEWLINE return format % dict(message=self.message,NEWLINE argument_name=self.argument_name)NEWLINENEWLINENEWLINEclass ArgumentTypeError(Exception):NEWLINE """An error from trying to convert a command line string to a type."""NEWLINE passNEWLINENEWLINENEWLINE# ==============NEWLINE# Action classesNEWLINE# ==============NEWLINENEWLINEclass Action(_AttributeHolder):NEWLINE """Information about how to convert command line strings to Python objects.NEWLINENEWLINE Action objects are used by an ArgumentParser to represent the informationNEWLINE needed to parse a single argument from one or more strings from theNEWLINE command line. The keyword arguments to the Action constructor are alsoNEWLINE all attributes of Action instances.NEWLINENEWLINE Keyword Arguments:NEWLINENEWLINE - option_strings -- A list of command-line option strings whichNEWLINE should be associated with this action.NEWLINENEWLINE - dest -- The name of the attribute to hold the created object(s)NEWLINENEWLINE - nargs -- The number of command-line arguments that should beNEWLINE consumed. By default, one argument will be consumed and a singleNEWLINE value will be produced. Other values include:NEWLINE - N (an integer) consumes N arguments (and produces a list)NEWLINE - '?' consumes zero or one argumentsNEWLINE - '*' consumes zero or more arguments (and produces a list)NEWLINE - '+' consumes one or more arguments (and produces a list)NEWLINE Note that the difference between the default and nargs=1 is thatNEWLINE with the default, a single value will be produced, while withNEWLINE nargs=1, a list containing a single value will be produced.NEWLINENEWLINE - const -- The value to be produced if the option is specified and theNEWLINE option uses an action that takes no values.NEWLINENEWLINE - default -- The value to be produced if the option is not specified.NEWLINENEWLINE - type -- A callable that accepts a single string argument, andNEWLINE returns the converted value. The standard Python types str, int,NEWLINE float, and complex are useful examples of such callables. If None,NEWLINE str is used.NEWLINENEWLINE - choices -- A container of values that should be allowed. If not None,NEWLINE after a command-line argument has been converted to the appropriateNEWLINE type, an exception will be raised if it is not a member of thisNEWLINE collection.NEWLINENEWLINE - required -- True if the action must always be specified at theNEWLINE command line. This is only meaningful for optional command-lineNEWLINE arguments.NEWLINENEWLINE - help -- The help string describing the argument.NEWLINENEWLINE - metavar -- The name to be used for the option's argument with theNEWLINE help string. If None, the 'dest' value will be used as the name.NEWLINE """NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE nargs=None,NEWLINE const=None,NEWLINE default=None,NEWLINE type=None,NEWLINE choices=None,NEWLINE required=False,NEWLINE help=None,NEWLINE metavar=None):NEWLINE self.option_strings = option_stringsNEWLINE self.dest = destNEWLINE self.nargs = nargsNEWLINE self.const = constNEWLINE self.default = defaultNEWLINE self.type = typeNEWLINE self.choices = choicesNEWLINE self.required = requiredNEWLINE self.help = helpNEWLINE self.metavar = metavarNEWLINENEWLINE def _get_kwargs(self):NEWLINE names = [NEWLINE 'option_strings',NEWLINE 'dest',NEWLINE 'nargs',NEWLINE 'const',NEWLINE 'default',NEWLINE 'type',NEWLINE 'choices',NEWLINE 'help',NEWLINE 'metavar',NEWLINE ]NEWLINE return [(name, getattr(self, name)) for name in names]NEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE raise NotImplementedError(_('.__call__() not defined'))NEWLINENEWLINENEWLINEclass _StoreAction(Action):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE nargs=None,NEWLINE const=None,NEWLINE default=None,NEWLINE type=None,NEWLINE choices=None,NEWLINE required=False,NEWLINE help=None,NEWLINE metavar=None):NEWLINE if nargs == 0:NEWLINE raise ValueError('nargs for store actions must be > 0; if you 'NEWLINE 'have nothing to store, actions such as store 'NEWLINE 'true or store const may be more appropriate')NEWLINE if const is not None and nargs != OPTIONAL:NEWLINE raise ValueError('nargs must be %r to supply const' % OPTIONAL)NEWLINE super(_StoreAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE nargs=nargs,NEWLINE const=const,NEWLINE default=default,NEWLINE type=type,NEWLINE choices=choices,NEWLINE required=required,NEWLINE help=help,NEWLINE metavar=metavar)NEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE setattr(namespace, self.dest, values)NEWLINENEWLINENEWLINEclass _StoreConstAction(Action):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE const,NEWLINE default=None,NEWLINE required=False,NEWLINE help=None,NEWLINE metavar=None):NEWLINE super(_StoreConstAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE nargs=0,NEWLINE const=const,NEWLINE default=default,NEWLINE required=required,NEWLINE help=help)NEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE setattr(namespace, self.dest, self.const)NEWLINENEWLINENEWLINEclass _StoreTrueAction(_StoreConstAction):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE default=False,NEWLINE required=False,NEWLINE help=None):NEWLINE super(_StoreTrueAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE const=True,NEWLINE default=default,NEWLINE required=required,NEWLINE help=help)NEWLINENEWLINENEWLINEclass _StoreFalseAction(_StoreConstAction):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE default=True,NEWLINE required=False,NEWLINE help=None):NEWLINE super(_StoreFalseAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE const=False,NEWLINE default=default,NEWLINE required=required,NEWLINE help=help)NEWLINENEWLINENEWLINEclass _AppendAction(Action):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE nargs=None,NEWLINE const=None,NEWLINE default=None,NEWLINE type=None,NEWLINE choices=None,NEWLINE required=False,NEWLINE help=None,NEWLINE metavar=None):NEWLINE if nargs == 0:NEWLINE raise ValueError('nargs for append actions must be > 0; if arg 'NEWLINE 'strings are not supplying the value to append, 'NEWLINE 'the append const action may be more appropriate')NEWLINE if const is not None and nargs != OPTIONAL:NEWLINE raise ValueError('nargs must be %r to supply const' % OPTIONAL)NEWLINE super(_AppendAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE nargs=nargs,NEWLINE const=const,NEWLINE default=default,NEWLINE type=type,NEWLINE choices=choices,NEWLINE required=required,NEWLINE help=help,NEWLINE metavar=metavar)NEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE items = _copy.copy(_ensure_value(namespace, self.dest, []))NEWLINE items.append(values)NEWLINE setattr(namespace, self.dest, items)NEWLINENEWLINENEWLINEclass _AppendConstAction(Action):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE const,NEWLINE default=None,NEWLINE required=False,NEWLINE help=None,NEWLINE metavar=None):NEWLINE super(_AppendConstAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE nargs=0,NEWLINE const=const,NEWLINE default=default,NEWLINE required=required,NEWLINE help=help,NEWLINE metavar=metavar)NEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE items = _copy.copy(_ensure_value(namespace, self.dest, []))NEWLINE items.append(self.const)NEWLINE setattr(namespace, self.dest, items)NEWLINENEWLINENEWLINEclass _CountAction(Action):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE default=None,NEWLINE required=False,NEWLINE help=None):NEWLINE super(_CountAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE nargs=0,NEWLINE default=default,NEWLINE required=required,NEWLINE help=help)NEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE new_count = _ensure_value(namespace, self.dest, 0) + 1NEWLINE setattr(namespace, self.dest, new_count)NEWLINENEWLINENEWLINEclass _HelpAction(Action):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest=SUPPRESS,NEWLINE default=SUPPRESS,NEWLINE help=None):NEWLINE super(_HelpAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE default=default,NEWLINE nargs=0,NEWLINE help=help)NEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE parser.print_help()NEWLINE parser.exit()NEWLINENEWLINENEWLINEclass _VersionAction(Action):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE version=None,NEWLINE dest=SUPPRESS,NEWLINE default=SUPPRESS,NEWLINE help="show program's version number and exit"):NEWLINE super(_VersionAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE default=default,NEWLINE nargs=0,NEWLINE help=help)NEWLINE self.version = versionNEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE version = self.versionNEWLINE if version is None:NEWLINE version = parser.versionNEWLINE formatter = parser._get_formatter()NEWLINE formatter.add_text(version)NEWLINE parser.exit(message=formatter.format_help())NEWLINENEWLINENEWLINEclass _SubParsersAction(Action):NEWLINENEWLINE class _ChoicesPseudoAction(Action):NEWLINENEWLINE def __init__(self, name, help):NEWLINE sup = super(_SubParsersAction._ChoicesPseudoAction, self)NEWLINE sup.__init__(option_strings=[], dest=name, help=help)NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE prog,NEWLINE parser_class,NEWLINE dest=SUPPRESS,NEWLINE help=None,NEWLINE metavar=None):NEWLINENEWLINE self._prog_prefix = progNEWLINE self._parser_class = parser_classNEWLINE self._name_parser_map = _collections.OrderedDict()NEWLINE self._choices_actions = []NEWLINENEWLINE super(_SubParsersAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE nargs=PARSER,NEWLINE choices=self._name_parser_map,NEWLINE help=help,NEWLINE metavar=metavar)NEWLINENEWLINE def add_parser(self, name, **kwargs):NEWLINE # set prog from the existing prefixNEWLINE if kwargs.get('prog') is None:NEWLINE kwargs['prog'] = '%s %s' % (self._prog_prefix, name)NEWLINENEWLINE # create a pseudo-action to hold the choice helpNEWLINE if 'help' in kwargs:NEWLINE help = kwargs.pop('help')NEWLINE choice_action = self._ChoicesPseudoAction(name, help)NEWLINE self._choices_actions.append(choice_action)NEWLINENEWLINE # create the parser and add it to the mapNEWLINE parser = self._parser_class(**kwargs)NEWLINE self._name_parser_map[name] = parserNEWLINE return parserNEWLINENEWLINE def _get_subactions(self):NEWLINE return self._choices_actionsNEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE parser_name = values[0]NEWLINE arg_strings = values[1:]NEWLINENEWLINE # set the parser name if requestedNEWLINE if self.dest is not SUPPRESS:NEWLINE setattr(namespace, self.dest, parser_name)NEWLINENEWLINE # select the parserNEWLINE try:NEWLINE parser = self._name_parser_map[parser_name]NEWLINE except KeyError:NEWLINE tup = parser_name, ', '.join(self._name_parser_map)NEWLINE msg = _('unknown parser %r (choices: %s)') % tupNEWLINE raise ArgumentError(self, msg)NEWLINENEWLINE # parse all the remaining options into the namespaceNEWLINE # store any unrecognized options on the object, so that the topNEWLINE # level parser can decide what to do with themNEWLINENEWLINE # In case this subparser defines new defaults, we parse themNEWLINE # in a new namespace object and then update the originalNEWLINE # namespace for the relevant parts.NEWLINE subnamespace, arg_strings = parser.parse_known_args(arg_strings, None)NEWLINE for key, value in vars(subnamespace).items():NEWLINE setattr(namespace, key, value)NEWLINENEWLINE if arg_strings:NEWLINE vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])NEWLINE getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)NEWLINENEWLINENEWLINE# ==============NEWLINE# Type classesNEWLINE# ==============NEWLINENEWLINEclass FileType(object):NEWLINE """Factory for creating file object typesNEWLINENEWLINE Instances of FileType are typically passed as type= arguments to theNEWLINE ArgumentParser add_argument() method.NEWLINENEWLINE Keyword Arguments:NEWLINE - mode -- A string indicating how the file is to be opened. Accepts theNEWLINE same values as the builtin open() function.NEWLINE - bufsize -- The file's desired buffer size. Accepts the same values asNEWLINE the builtin open() function.NEWLINE """NEWLINENEWLINE def __init__(self, mode='r', bufsize=-1):NEWLINE self._mode = modeNEWLINE self._bufsize = bufsizeNEWLINENEWLINE def __call__(self, string):NEWLINE # the special argument "-" means sys.std{in,out}NEWLINE if string == '-':NEWLINE if 'r' in self._mode:NEWLINE return _sys.stdinNEWLINE elif 'w' in self._mode:NEWLINE return _sys.stdoutNEWLINE else:NEWLINE msg = _('argument "-" with mode %r') % self._modeNEWLINE raise ValueError(msg)NEWLINENEWLINE # all other arguments are used as file namesNEWLINE try:NEWLINE return open(string, self._mode, self._bufsize)NEWLINE except IOError as e:NEWLINE message = _("can't open '%s': %s")NEWLINE raise ArgumentTypeError(message % (string, e))NEWLINENEWLINE def __repr__(self):NEWLINE args = self._mode, self._bufsizeNEWLINE args_str = ', '.join(repr(arg) for arg in args if arg != -1)NEWLINE return '%s(%s)' % (type(self).__name__, args_str)NEWLINENEWLINE# ===========================NEWLINE# Optional and Positional ParsingNEWLINE# ===========================NEWLINENEWLINEclass Namespace(_AttributeHolder):NEWLINE """Simple object for storing attributes.NEWLINENEWLINE Implements equality by attribute names and values, and provides a simpleNEWLINE string representation.NEWLINE """NEWLINENEWLINE def __init__(self, **kwargs):NEWLINE for name in kwargs:NEWLINE setattr(self, name, kwargs[name])NEWLINENEWLINE __hash__ = NoneNEWLINENEWLINE def __eq__(self, other):NEWLINE if not isinstance(other, Namespace):NEWLINE return NotImplementedNEWLINE return vars(self) == vars(other)NEWLINENEWLINE def __ne__(self, other):NEWLINE if not isinstance(other, Namespace):NEWLINE return NotImplementedNEWLINE return not (self == other)NEWLINENEWLINE def __contains__(self, key):NEWLINE return key in self.__dict__NEWLINENEWLINENEWLINEclass _ActionsContainer(object):NEWLINENEWLINE def __init__(self,NEWLINE description,NEWLINE prefix_chars,NEWLINE argument_default,NEWLINE conflict_handler):NEWLINE super(_ActionsContainer, self).__init__()NEWLINENEWLINE self.description = descriptionNEWLINE self.argument_default = argument_defaultNEWLINE self.prefix_chars = prefix_charsNEWLINE self.conflict_handler = conflict_handlerNEWLINENEWLINE # set up registriesNEWLINE self._registries = {}NEWLINENEWLINE # register actionsNEWLINE self.register('action', None, _StoreAction)NEWLINE self.register('action', 'store', _StoreAction)NEWLINE self.register('action', 'store_const', _StoreConstAction)NEWLINE self.register('action', 'store_true', _StoreTrueAction)NEWLINE self.register('action', 'store_false', _StoreFalseAction)NEWLINE self.register('action', 'append', _AppendAction)NEWLINE self.register('action', 'append_const', _AppendConstAction)NEWLINE self.register('action', 'count', _CountAction)NEWLINE self.register('action', 'help', _HelpAction)NEWLINE self.register('action', 'version', _VersionAction)NEWLINE self.register('action', 'parsers', _SubParsersAction)NEWLINENEWLINE # raise an exception if the conflict handler is invalidNEWLINE self._get_handler()NEWLINENEWLINE # action storageNEWLINE self._actions = []NEWLINE self._option_string_actions = {}NEWLINENEWLINE # groupsNEWLINE self._action_groups = []NEWLINE self._mutually_exclusive_groups = []NEWLINENEWLINE # defaults storageNEWLINE self._defaults = {}NEWLINENEWLINE # determines whether an "option" looks like a negative numberNEWLINE self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')NEWLINENEWLINE # whether or not there are any optionals that look like negativeNEWLINE # numbers -- uses a list so it can be shared and editedNEWLINE self._has_negative_number_optionals = []NEWLINENEWLINE # ====================NEWLINE # Registration methodsNEWLINE # ====================NEWLINE def register(self, registry_name, value, object):NEWLINE registry = self._registries.setdefault(registry_name, {})NEWLINE registry[value] = objectNEWLINENEWLINE def _registry_get(self, registry_name, value, default=None):NEWLINE return self._registries[registry_name].get(value, default)NEWLINENEWLINE # ==================================NEWLINE # Namespace default accessor methodsNEWLINE # ==================================NEWLINE def set_defaults(self, **kwargs):NEWLINE self._defaults.update(kwargs)NEWLINENEWLINE # if these defaults match any existing arguments, replaceNEWLINE # the previous default on the object with the new oneNEWLINE for action in self._actions:NEWLINE if action.dest in kwargs:NEWLINE action.default = kwargs[action.dest]NEWLINENEWLINE def get_default(self, dest):NEWLINE for action in self._actions:NEWLINE if action.dest == dest and action.default is not None:NEWLINE return action.defaultNEWLINE return self._defaults.get(dest, None)NEWLINENEWLINENEWLINE # =======================NEWLINE # Adding argument actionsNEWLINE # =======================NEWLINE def add_argument(self, *args, **kwargs):NEWLINE """NEWLINE add_argument(dest, ..., name=value, ...)NEWLINE add_argument(option_string, option_string, ..., name=value, ...)NEWLINE """NEWLINENEWLINE # if no positional args are supplied or only one is supplied andNEWLINE # it doesn't look like an option string, parse a positionalNEWLINE # argumentNEWLINE chars = self.prefix_charsNEWLINE if not args or len(args) == 1 and args[0][0] not in chars:NEWLINE if args and 'dest' in kwargs:NEWLINE raise ValueError('dest supplied twice for positional argument')NEWLINE kwargs = self._get_positional_kwargs(*args, **kwargs)NEWLINENEWLINE # otherwise, we're adding an optional argumentNEWLINE else:NEWLINE kwargs = self._get_optional_kwargs(*args, **kwargs)NEWLINENEWLINE # if no default was supplied, use the parser-level defaultNEWLINE if 'default' not in kwargs:NEWLINE dest = kwargs['dest']NEWLINE if dest in self._defaults:NEWLINE kwargs['default'] = self._defaults[dest]NEWLINE elif self.argument_default is not None:NEWLINE kwargs['default'] = self.argument_defaultNEWLINENEWLINE # create the action object, and add it to the parserNEWLINE action_class = self._pop_action_class(kwargs)NEWLINE if not _callable(action_class):NEWLINE raise ValueError('unknown action "%s"' % (action_class,))NEWLINE action = action_class(**kwargs)NEWLINENEWLINE # raise an error if the action type is not callableNEWLINE type_func = self._registry_get('type', action.type, action.type)NEWLINE if not _callable(type_func):NEWLINE raise ValueError('%r is not callable' % (type_func,))NEWLINENEWLINE # raise an error if the metavar does not match the typeNEWLINE if hasattr(self, "_get_formatter"):NEWLINE try:NEWLINE self._get_formatter()._format_args(action, None)NEWLINE except TypeError:NEWLINE raise ValueError("length of metavar tuple does not match nargs")NEWLINENEWLINE return self._add_action(action)NEWLINENEWLINE def add_argument_group(self, *args, **kwargs):NEWLINE group = _ArgumentGroup(self, *args, **kwargs)NEWLINE self._action_groups.append(group)NEWLINE return groupNEWLINENEWLINE def add_mutually_exclusive_group(self, **kwargs):NEWLINE group = _MutuallyExclusiveGroup(self, **kwargs)NEWLINE self._mutually_exclusive_groups.append(group)NEWLINE return groupNEWLINENEWLINE def _add_action(self, action):NEWLINE # resolve any conflictsNEWLINE self._check_conflict(action)NEWLINENEWLINE # add to actions listNEWLINE self._actions.append(action)NEWLINE action.container = selfNEWLINENEWLINE # index the action by any option strings it hasNEWLINE for option_string in action.option_strings:NEWLINE self._option_string_actions[option_string] = actionNEWLINENEWLINE # set the flag if any option strings look like negative numbersNEWLINE for option_string in action.option_strings:NEWLINE if self._negative_number_matcher.match(option_string):NEWLINE if not self._has_negative_number_optionals:NEWLINE self._has_negative_number_optionals.append(True)NEWLINENEWLINE # return the created actionNEWLINE return actionNEWLINENEWLINE def _remove_action(self, action):NEWLINE self._actions.remove(action)NEWLINENEWLINE def _add_container_actions(self, container):NEWLINE # collect groups by titlesNEWLINE title_group_map = {}NEWLINE for group in self._action_groups:NEWLINE if group.title in title_group_map:NEWLINE msg = _('cannot merge actions - two groups are named %r')NEWLINE raise ValueError(msg % (group.title))NEWLINE title_group_map[group.title] = groupNEWLINENEWLINE # map each action to its groupNEWLINE group_map = {}NEWLINE for group in container._action_groups:NEWLINENEWLINE # if a group with the title exists, use that, otherwiseNEWLINE # create a new group matching the container's groupNEWLINE if group.title not in title_group_map:NEWLINE title_group_map[group.title] = self.add_argument_group(NEWLINE title=group.title,NEWLINE description=group.description,NEWLINE conflict_handler=group.conflict_handler)NEWLINENEWLINE # map the actions to their new groupNEWLINE for action in group._group_actions:NEWLINE group_map[action] = title_group_map[group.title]NEWLINENEWLINE # add container's mutually exclusive groupsNEWLINE # NOTE: if add_mutually_exclusive_group ever gains title= andNEWLINE # description= then this code will need to be expanded as aboveNEWLINE for group in container._mutually_exclusive_groups:NEWLINE mutex_group = self.add_mutually_exclusive_group(NEWLINE required=group.required)NEWLINENEWLINE # map the actions to their new mutex groupNEWLINE for action in group._group_actions:NEWLINE group_map[action] = mutex_groupNEWLINENEWLINE # add all actions to this container or their groupNEWLINE for action in container._actions:NEWLINE group_map.get(action, self)._add_action(action)NEWLINENEWLINE def _get_positional_kwargs(self, dest, **kwargs):NEWLINE # make sure required is not specifiedNEWLINE if 'required' in kwargs:NEWLINE msg = _("'required' is an invalid argument for positionals")NEWLINE raise TypeError(msg)NEWLINENEWLINE # mark positional arguments as required if at least one isNEWLINE # always requiredNEWLINE if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:NEWLINE kwargs['required'] = TrueNEWLINE if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:NEWLINE kwargs['required'] = TrueNEWLINENEWLINE # return the keyword arguments with no option stringsNEWLINE return dict(kwargs, dest=dest, option_strings=[])NEWLINENEWLINE def _get_optional_kwargs(self, *args, **kwargs):NEWLINE # determine short and long option stringsNEWLINE option_strings = []NEWLINE long_option_strings = []NEWLINE for option_string in args:NEWLINE # error on strings that don't start with an appropriate prefixNEWLINE if not option_string[0] in self.prefix_chars:NEWLINE msg = _('invalid option string %r: 'NEWLINE 'must start with a character %r')NEWLINE tup = option_string, self.prefix_charsNEWLINE raise ValueError(msg % tup)NEWLINENEWLINE # strings starting with two prefix characters are long optionsNEWLINE option_strings.append(option_string)NEWLINE if option_string[0] in self.prefix_chars:NEWLINE if len(option_string) > 1:NEWLINE if option_string[1] in self.prefix_chars:NEWLINE long_option_strings.append(option_string)NEWLINENEWLINE # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'NEWLINE dest = kwargs.pop('dest', None)NEWLINE if dest is None:NEWLINE if long_option_strings:NEWLINE dest_option_string = long_option_strings[0]NEWLINE else:NEWLINE dest_option_string = option_strings[0]NEWLINE dest = dest_option_string.lstrip(self.prefix_chars)NEWLINE if not dest:NEWLINE msg = _('dest= is required for options like %r')NEWLINE raise ValueError(msg % option_string)NEWLINE dest = dest.replace('-', '_')NEWLINENEWLINE # return the updated keyword argumentsNEWLINE return dict(kwargs, dest=dest, option_strings=option_strings)NEWLINENEWLINE def _pop_action_class(self, kwargs, default=None):NEWLINE action = kwargs.pop('action', default)NEWLINE return self._registry_get('action', action, action)NEWLINENEWLINE def _get_handler(self):NEWLINE # determine function from conflict handler stringNEWLINE handler_func_name = '_handle_conflict_%s' % self.conflict_handlerNEWLINE try:NEWLINE return getattr(self, handler_func_name)NEWLINE except AttributeError:NEWLINE msg = _('invalid conflict_resolution value: %r')NEWLINE raise ValueError(msg % self.conflict_handler)NEWLINENEWLINE def _check_conflict(self, action):NEWLINENEWLINE # find all options that conflict with this optionNEWLINE confl_optionals = []NEWLINE for option_string in action.option_strings:NEWLINE if option_string in self._option_string_actions:NEWLINE confl_optional = self._option_string_actions[option_string]NEWLINE confl_optionals.append((option_string, confl_optional))NEWLINENEWLINE # resolve any conflictsNEWLINE if confl_optionals:NEWLINE conflict_handler = self._get_handler()NEWLINE conflict_handler(action, confl_optionals)NEWLINENEWLINE def _handle_conflict_error(self, action, conflicting_actions):NEWLINE message = _('conflicting option string(s): %s')NEWLINE conflict_string = ', '.join([option_stringNEWLINE for option_string, actionNEWLINE in conflicting_actions])NEWLINE raise ArgumentError(action, message % conflict_string)NEWLINENEWLINE def _handle_conflict_resolve(self, action, conflicting_actions):NEWLINENEWLINE # remove all conflicting optionsNEWLINE for option_string, action in conflicting_actions:NEWLINENEWLINE # remove the conflicting optionNEWLINE action.option_strings.remove(option_string)NEWLINE self._option_string_actions.pop(option_string, None)NEWLINENEWLINE # if the option now has no option string, remove it from theNEWLINE # container holding itNEWLINE if not action.option_strings:NEWLINE action.container._remove_action(action)NEWLINENEWLINENEWLINEclass _ArgumentGroup(_ActionsContainer):NEWLINENEWLINE def __init__(self, container, title=None, description=None, **kwargs):NEWLINE # add any missing keyword arguments by checking the containerNEWLINE update = kwargs.setdefaultNEWLINE update('conflict_handler', container.conflict_handler)NEWLINE update('prefix_chars', container.prefix_chars)NEWLINE update('argument_default', container.argument_default)NEWLINE super_init = super(_ArgumentGroup, self).__init__NEWLINE super_init(description=description, **kwargs)NEWLINENEWLINE # group attributesNEWLINE self.title = titleNEWLINE self._group_actions = []NEWLINENEWLINE # share most attributes with the containerNEWLINE self._registries = container._registriesNEWLINE self._actions = container._actionsNEWLINE self._option_string_actions = container._option_string_actionsNEWLINE self._defaults = container._defaultsNEWLINE self._has_negative_number_optionals = \NEWLINE container._has_negative_number_optionalsNEWLINE self._mutually_exclusive_groups = container._mutually_exclusive_groupsNEWLINENEWLINE def _add_action(self, action):NEWLINE action = super(_ArgumentGroup, self)._add_action(action)NEWLINE self._group_actions.append(action)NEWLINE return actionNEWLINENEWLINE def _remove_action(self, action):NEWLINE super(_ArgumentGroup, self)._remove_action(action)NEWLINE self._group_actions.remove(action)NEWLINENEWLINENEWLINEclass _MutuallyExclusiveGroup(_ArgumentGroup):NEWLINENEWLINE def __init__(self, container, required=False):NEWLINE super(_MutuallyExclusiveGroup, self).__init__(container)NEWLINE self.required = requiredNEWLINE self._container = containerNEWLINENEWLINE def _add_action(self, action):NEWLINE if action.required:NEWLINE msg = _('mutually exclusive arguments must be optional')NEWLINE raise ValueError(msg)NEWLINE action = self._container._add_action(action)NEWLINE self._group_actions.append(action)NEWLINE return actionNEWLINENEWLINE def _remove_action(self, action):NEWLINE self._container._remove_action(action)NEWLINE self._group_actions.remove(action)NEWLINENEWLINENEWLINEclass ArgumentParser(_AttributeHolder, _ActionsContainer):NEWLINE """Object for parsing command line strings into Python objects.NEWLINENEWLINE Keyword Arguments:NEWLINE - prog -- The name of the program (default: sys.argv[0])NEWLINE - usage -- A usage message (default: auto-generated from arguments)NEWLINE - description -- A description of what the program doesNEWLINE - epilog -- Text following the argument descriptionsNEWLINE - parents -- Parsers whose arguments should be copied into this oneNEWLINE - formatter_class -- HelpFormatter class for printing help messagesNEWLINE - prefix_chars -- Characters that prefix optional argumentsNEWLINE - fromfile_prefix_chars -- Characters that prefix files containingNEWLINE additional argumentsNEWLINE - argument_default -- The default value for all argumentsNEWLINE - conflict_handler -- String indicating how to handle conflictsNEWLINE - add_help -- Add a -h/-help optionNEWLINE """NEWLINENEWLINE def __init__(self,NEWLINE prog=None,NEWLINE usage=None,NEWLINE description=None,NEWLINE epilog=None,NEWLINE version=None,NEWLINE parents=[],NEWLINE formatter_class=HelpFormatter,NEWLINE prefix_chars='-',NEWLINE fromfile_prefix_chars=None,NEWLINE argument_default=None,NEWLINE conflict_handler='error',NEWLINE add_help=True):NEWLINENEWLINE if version is not None:NEWLINE import warningsNEWLINE warnings.warn(NEWLINE """The "version" argument to ArgumentParser is deprecated. """NEWLINE """Please use """NEWLINE """"add_argument(..., action='version', version="N", ...)" """NEWLINE """instead""", DeprecationWarning)NEWLINENEWLINE superinit = super(ArgumentParser, self).__init__NEWLINE superinit(description=description,NEWLINE prefix_chars=prefix_chars,NEWLINE argument_default=argument_default,NEWLINE conflict_handler=conflict_handler)NEWLINENEWLINE # default setting for progNEWLINE if prog is None:NEWLINE prog = _os.path.basename(_sys.argv[0])NEWLINENEWLINE self.prog = progNEWLINE self.usage = usageNEWLINE self.epilog = epilogNEWLINE self.version = versionNEWLINE self.formatter_class = formatter_classNEWLINE self.fromfile_prefix_chars = fromfile_prefix_charsNEWLINE self.add_help = add_helpNEWLINENEWLINE add_group = self.add_argument_groupNEWLINE self._positionals = add_group(_('positional arguments'))NEWLINE self._optionals = add_group(_('optional arguments'))NEWLINE self._subparsers = NoneNEWLINENEWLINE # register typesNEWLINE def identity(string):NEWLINE return stringNEWLINE self.register('type', None, identity)NEWLINENEWLINE # add help and version arguments if necessaryNEWLINE # (using explicit default to override global argument_default)NEWLINE default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]NEWLINE if self.add_help:NEWLINE self.add_argument(NEWLINE default_prefix+'h', default_prefix*2+'help',NEWLINE action='help', default=SUPPRESS,NEWLINE help=_('show this help message and exit'))NEWLINE if self.version:NEWLINE self.add_argument(NEWLINE default_prefix+'v', default_prefix*2+'version',NEWLINE action='version', default=SUPPRESS,NEWLINE version=self.version,NEWLINE help=_("show program's version number and exit"))NEWLINENEWLINE # add parent arguments and defaultsNEWLINE for parent in parents:NEWLINE self._add_container_actions(parent)NEWLINE try:NEWLINE defaults = parent._defaultsNEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE self._defaults.update(defaults)NEWLINENEWLINE # =======================NEWLINE # Pretty __repr__ methodsNEWLINE # =======================NEWLINE def _get_kwargs(self):NEWLINE names = [NEWLINE 'prog',NEWLINE 'usage',NEWLINE 'description',NEWLINE 'version',NEWLINE 'formatter_class',NEWLINE 'conflict_handler',NEWLINE 'add_help',NEWLINE ]NEWLINE return [(name, getattr(self, name)) for name in names]NEWLINENEWLINE # ==================================NEWLINE # Optional/Positional adding methodsNEWLINE # ==================================NEWLINE def add_subparsers(self, **kwargs):NEWLINE if self._subparsers is not None:NEWLINE self.error(_('cannot have multiple subparser arguments'))NEWLINENEWLINE # add the parser class to the arguments if it's not presentNEWLINE kwargs.setdefault('parser_class', type(self))NEWLINENEWLINE if 'title' in kwargs or 'description' in kwargs:NEWLINE title = _(kwargs.pop('title', 'subcommands'))NEWLINE description = _(kwargs.pop('description', None))NEWLINE self._subparsers = self.add_argument_group(title, description)NEWLINE else:NEWLINE self._subparsers = self._positionalsNEWLINENEWLINE # prog defaults to the usage message of this parser, skippingNEWLINE # optional arguments and with no "usage:" prefixNEWLINE if kwargs.get('prog') is None:NEWLINE formatter = self._get_formatter()NEWLINE positionals = self._get_positional_actions()NEWLINE groups = self._mutually_exclusive_groupsNEWLINE formatter.add_usage(self.usage, positionals, groups, '')NEWLINE kwargs['prog'] = formatter.format_help().strip()NEWLINENEWLINE # create the parsers action and add it to the positionals listNEWLINE parsers_class = self._pop_action_class(kwargs, 'parsers')NEWLINE action = parsers_class(option_strings=[], **kwargs)NEWLINE self._subparsers._add_action(action)NEWLINENEWLINE # return the created parsers actionNEWLINE return actionNEWLINENEWLINE def _add_action(self, action):NEWLINE if action.option_strings:NEWLINE self._optionals._add_action(action)NEWLINE else:NEWLINE self._positionals._add_action(action)NEWLINE return actionNEWLINENEWLINE def _get_optional_actions(self):NEWLINE return [actionNEWLINE for action in self._actionsNEWLINE if action.option_strings]NEWLINENEWLINE def _get_positional_actions(self):NEWLINE return [actionNEWLINE for action in self._actionsNEWLINE if not action.option_strings]NEWLINENEWLINE # =====================================NEWLINE # Command line argument parsing methodsNEWLINE # =====================================NEWLINE def parse_args(self, args=None, namespace=None):NEWLINE args, argv = self.parse_known_args(args, namespace)NEWLINE if argv:NEWLINE msg = _('unrecognized arguments: %s')NEWLINE self.error(msg % ' '.join(argv))NEWLINE return argsNEWLINENEWLINE def parse_known_args(self, args=None, namespace=None):NEWLINE if args is None:NEWLINE # args default to the system argsNEWLINE args = _sys.argv[1:]NEWLINE else:NEWLINE # make sure that args are mutableNEWLINE args = list(args)NEWLINENEWLINE # default Namespace built from parser defaultsNEWLINE if namespace is None:NEWLINE namespace = Namespace()NEWLINENEWLINE # add any action defaults that aren't presentNEWLINE for action in self._actions:NEWLINE if action.dest is not SUPPRESS:NEWLINE if not hasattr(namespace, action.dest):NEWLINE if action.default is not SUPPRESS:NEWLINE setattr(namespace, action.dest, action.default)NEWLINENEWLINE # add any parser defaults that aren't presentNEWLINE for dest in self._defaults:NEWLINE if not hasattr(namespace, dest):NEWLINE setattr(namespace, dest, self._defaults[dest])NEWLINENEWLINE # parse the arguments and exit if there are any errorsNEWLINE try:NEWLINE namespace, args = self._parse_known_args(args, namespace)NEWLINE if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):NEWLINE args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))NEWLINE delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)NEWLINE return namespace, argsNEWLINE except ArgumentError:NEWLINE err = _sys.exc_info()[1]NEWLINE self.error(str(err))NEWLINENEWLINE def _parse_known_args(self, arg_strings, namespace):NEWLINE # replace arg strings that are file referencesNEWLINE if self.fromfile_prefix_chars is not None:NEWLINE arg_strings = self._read_args_from_files(arg_strings)NEWLINENEWLINE # map all mutually exclusive arguments to the other argumentsNEWLINE # they can't occur withNEWLINE action_conflicts = {}NEWLINE for mutex_group in self._mutually_exclusive_groups:NEWLINE group_actions = mutex_group._group_actionsNEWLINE for i, mutex_action in enumerate(mutex_group._group_actions):NEWLINE conflicts = action_conflicts.setdefault(mutex_action, [])NEWLINE conflicts.extend(group_actions[:i])NEWLINE conflicts.extend(group_actions[i + 1:])NEWLINENEWLINE # find all option indices, and determine the arg_string_patternNEWLINE # which has an 'O' if there is an option at an index,NEWLINE # an 'A' if there is an argument, or a '-' if there is a '--'NEWLINE option_string_indices = {}NEWLINE arg_string_pattern_parts = []NEWLINE arg_strings_iter = iter(arg_strings)NEWLINE for i, arg_string in enumerate(arg_strings_iter):NEWLINENEWLINE # all args after -- are non-optionsNEWLINE if arg_string == '--':NEWLINE arg_string_pattern_parts.append('-')NEWLINE for arg_string in arg_strings_iter:NEWLINE arg_string_pattern_parts.append('A')NEWLINENEWLINE # otherwise, add the arg to the arg stringsNEWLINE # and note the index if it was an optionNEWLINE else:NEWLINE option_tuple = self._parse_optional(arg_string)NEWLINE if option_tuple is None:NEWLINE pattern = 'A'NEWLINE else:NEWLINE option_string_indices[i] = option_tupleNEWLINE pattern = 'O'NEWLINE arg_string_pattern_parts.append(pattern)NEWLINENEWLINE # join the pieces together to form the patternNEWLINE arg_strings_pattern = ''.join(arg_string_pattern_parts)NEWLINENEWLINE # converts arg strings to the appropriate and then takes the actionNEWLINE seen_actions = set()NEWLINE seen_non_default_actions = set()NEWLINENEWLINE def take_action(action, argument_strings, option_string=None):NEWLINE seen_actions.add(action)NEWLINE argument_values = self._get_values(action, argument_strings)NEWLINENEWLINE # error if this argument is not allowed with other previouslyNEWLINE # seen arguments, assuming that actions that use the defaultNEWLINE # value don't really count as "present"NEWLINE if argument_values is not action.default:NEWLINE seen_non_default_actions.add(action)NEWLINE for conflict_action in action_conflicts.get(action, []):NEWLINE if conflict_action in seen_non_default_actions:NEWLINE msg = _('not allowed with argument %s')NEWLINE action_name = _get_action_name(conflict_action)NEWLINE raise ArgumentError(action, msg % action_name)NEWLINENEWLINE # take the action if we didn't receive a SUPPRESS valueNEWLINE # (e.g. from a default)NEWLINE if argument_values is not SUPPRESS:NEWLINE action(self, namespace, argument_values, option_string)NEWLINENEWLINE # function to convert arg_strings into an optional actionNEWLINE def consume_optional(start_index):NEWLINENEWLINE # get the optional identified at this indexNEWLINE option_tuple = option_string_indices[start_index]NEWLINE action, option_string, explicit_arg = option_tupleNEWLINENEWLINE # identify additional optionals in the same arg stringNEWLINE # (e.g. -xyz is the same as -x -y -z if no args are required)NEWLINE match_argument = self._match_argumentNEWLINE action_tuples = []NEWLINE while True:NEWLINENEWLINE # if we found no optional action, skip itNEWLINE if action is None:NEWLINE extras.append(arg_strings[start_index])NEWLINE return start_index + 1NEWLINENEWLINE # if there is an explicit argument, try to match theNEWLINE # optional's string arguments to only thisNEWLINE if explicit_arg is not None:NEWLINE arg_count = match_argument(action, 'A')NEWLINENEWLINE # if the action is a single-dash option and takes noNEWLINE # arguments, try to parse more single-dash options outNEWLINE # of the tail of the option stringNEWLINE chars = self.prefix_charsNEWLINE if arg_count == 0 and option_string[1] not in chars:NEWLINE action_tuples.append((action, [], option_string))NEWLINE char = option_string[0]NEWLINE option_string = char + explicit_arg[0]NEWLINE new_explicit_arg = explicit_arg[1:] or NoneNEWLINE optionals_map = self._option_string_actionsNEWLINE if option_string in optionals_map:NEWLINE action = optionals_map[option_string]NEWLINE explicit_arg = new_explicit_argNEWLINE else:NEWLINE msg = _('ignored explicit argument %r')NEWLINE raise ArgumentError(action, msg % explicit_arg)NEWLINENEWLINE # if the action expect exactly one argument, we'veNEWLINE # successfully matched the option; exit the loopNEWLINE elif arg_count == 1:NEWLINE stop = start_index + 1NEWLINE args = [explicit_arg]NEWLINE action_tuples.append((action, args, option_string))NEWLINE breakNEWLINENEWLINE # error if a double-dash option did not use theNEWLINE # explicit argumentNEWLINE else:NEWLINE msg = _('ignored explicit argument %r')NEWLINE raise ArgumentError(action, msg % explicit_arg)NEWLINENEWLINE # if there is no explicit argument, try to match theNEWLINE # optional's string arguments with the following stringsNEWLINE # if successful, exit the loopNEWLINE else:NEWLINE start = start_index + 1NEWLINE selected_patterns = arg_strings_pattern[start:]NEWLINE arg_count = match_argument(action, selected_patterns)NEWLINE stop = start + arg_countNEWLINE args = arg_strings[start:stop]NEWLINE action_tuples.append((action, args, option_string))NEWLINE breakNEWLINENEWLINE # add the Optional to the list and return the index at whichNEWLINE # the Optional's string args stoppedNEWLINE assert action_tuplesNEWLINE for action, args, option_string in action_tuples:NEWLINE take_action(action, args, option_string)NEWLINE return stopNEWLINENEWLINE # the list of Positionals left to be parsed; this is modifiedNEWLINE # by consume_positionals()NEWLINE positionals = self._get_positional_actions()NEWLINENEWLINE # function to convert arg_strings into positional actionsNEWLINE def consume_positionals(start_index):NEWLINE # match as many Positionals as possibleNEWLINE match_partial = self._match_arguments_partialNEWLINE selected_pattern = arg_strings_pattern[start_index:]NEWLINE arg_counts = match_partial(positionals, selected_pattern)NEWLINENEWLINE # slice off the appropriate arg strings for each PositionalNEWLINE # and add the Positional and its args to the listNEWLINE for action, arg_count in zip(positionals, arg_counts):NEWLINE args = arg_strings[start_index: start_index + arg_count]NEWLINE start_index += arg_countNEWLINE take_action(action, args)NEWLINENEWLINE # slice off the Positionals that we just parsed and return theNEWLINE # index at which the Positionals' string args stoppedNEWLINE positionals[:] = positionals[len(arg_counts):]NEWLINE return start_indexNEWLINENEWLINE # consume Positionals and Optionals alternately, until we haveNEWLINE # passed the last option stringNEWLINE extras = []NEWLINE start_index = 0NEWLINE if option_string_indices:NEWLINE max_option_string_index = max(option_string_indices)NEWLINE else:NEWLINE max_option_string_index = -1NEWLINE while start_index <= max_option_string_index:NEWLINENEWLINE # consume any Positionals preceding the next optionNEWLINE next_option_string_index = min([NEWLINE indexNEWLINE for index in option_string_indicesNEWLINE if index >= start_index])NEWLINE if start_index != next_option_string_index:NEWLINE positionals_end_index = consume_positionals(start_index)NEWLINENEWLINE # only try to parse the next optional if we didn't consumeNEWLINE # the option string during the positionals parsingNEWLINE if positionals_end_index > start_index:NEWLINE start_index = positionals_end_indexNEWLINE continueNEWLINE else:NEWLINE start_index = positionals_end_indexNEWLINENEWLINE # if we consumed all the positionals we could and we're notNEWLINE # at the index of an option string, there were extra argumentsNEWLINE if start_index not in option_string_indices:NEWLINE strings = arg_strings[start_index:next_option_string_index]NEWLINE extras.extend(strings)NEWLINE start_index = next_option_string_indexNEWLINENEWLINE # consume the next optional and any arguments for itNEWLINE start_index = consume_optional(start_index)NEWLINENEWLINE # consume any positionals following the last OptionalNEWLINE stop_index = consume_positionals(start_index)NEWLINENEWLINE # if we didn't consume all the argument strings, there were extrasNEWLINE extras.extend(arg_strings[stop_index:])NEWLINENEWLINE # if we didn't use all the Positional objects, there were too fewNEWLINE # arg strings supplied.NEWLINE if positionals:NEWLINE self.error(_('too few arguments'))NEWLINENEWLINE # make sure all required actions were present, and convert defaults.NEWLINE for action in self._actions:NEWLINE if action not in seen_actions:NEWLINE if action.required:NEWLINE name = _get_action_name(action)NEWLINE self.error(_('argument %s is required') % name)NEWLINE else:NEWLINE # Convert action default now instead of doing it beforeNEWLINE # parsing arguments to avoid calling convert functionsNEWLINE # twice (which may fail) if the argument was given, butNEWLINE # only if it was defined already in the namespaceNEWLINE if (action.default is not None andNEWLINE isinstance(action.default, basestring) andNEWLINE hasattr(namespace, action.dest) andNEWLINE action.default is getattr(namespace, action.dest)):NEWLINE setattr(namespace, action.dest,NEWLINE self._get_value(action, action.default))NEWLINENEWLINE # make sure all required groups had one option presentNEWLINE for group in self._mutually_exclusive_groups:NEWLINE if group.required:NEWLINE for action in group._group_actions:NEWLINE if action in seen_non_default_actions:NEWLINE breakNEWLINENEWLINE # if no actions were used, report the errorNEWLINE else:NEWLINE names = [_get_action_name(action)NEWLINE for action in group._group_actionsNEWLINE if action.help is not SUPPRESS]NEWLINE msg = _('one of the arguments %s is required')NEWLINE self.error(msg % ' '.join(names))NEWLINENEWLINE # return the updated namespace and the extra argumentsNEWLINE return namespace, extrasNEWLINENEWLINE def _read_args_from_files(self, arg_strings):NEWLINE # expand arguments referencing filesNEWLINE new_arg_strings = []NEWLINE for arg_string in arg_strings:NEWLINENEWLINE # for regular arguments, just add them back into the listNEWLINE if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:NEWLINE new_arg_strings.append(arg_string)NEWLINENEWLINE # replace arguments referencing files with the file contentNEWLINE else:NEWLINE try:NEWLINE args_file = open(arg_string[1:])NEWLINE try:NEWLINE arg_strings = []NEWLINE for arg_line in args_file.read().splitlines():NEWLINE for arg in self.convert_arg_line_to_args(arg_line):NEWLINE arg_strings.append(arg)NEWLINE arg_strings = self._read_args_from_files(arg_strings)NEWLINE new_arg_strings.extend(arg_strings)NEWLINE finally:NEWLINE args_file.close()NEWLINE except IOError:NEWLINE err = _sys.exc_info()[1]NEWLINE self.error(str(err))NEWLINENEWLINE # return the modified argument listNEWLINE return new_arg_stringsNEWLINENEWLINE def convert_arg_line_to_args(self, arg_line):NEWLINE return [arg_line]NEWLINENEWLINE def _match_argument(self, action, arg_strings_pattern):NEWLINE # match the pattern for this action to the arg stringsNEWLINE nargs_pattern = self._get_nargs_pattern(action)NEWLINE match = _re.match(nargs_pattern, arg_strings_pattern)NEWLINENEWLINE # raise an exception if we weren't able to find a matchNEWLINE if match is None:NEWLINE nargs_errors = {NEWLINE None: _('expected one argument'),NEWLINE OPTIONAL: _('expected at most one argument'),NEWLINE ONE_OR_MORE: _('expected at least one argument'),NEWLINE }NEWLINE default = _('expected %s argument(s)') % action.nargsNEWLINE msg = nargs_errors.get(action.nargs, default)NEWLINE raise ArgumentError(action, msg)NEWLINENEWLINE # return the number of arguments matchedNEWLINE return len(match.group(1))NEWLINENEWLINE def _match_arguments_partial(self, actions, arg_strings_pattern):NEWLINE # progressively shorten the actions list by slicing off theNEWLINE # final actions until we find a matchNEWLINE result = []NEWLINE for i in range(len(actions), 0, -1):NEWLINE actions_slice = actions[:i]NEWLINE pattern = ''.join([self._get_nargs_pattern(action)NEWLINE for action in actions_slice])NEWLINE match = _re.match(pattern, arg_strings_pattern)NEWLINE if match is not None:NEWLINE result.extend([len(string) for string in match.groups()])NEWLINE breakNEWLINENEWLINE # return the list of arg string countsNEWLINE return resultNEWLINENEWLINE def _parse_optional(self, arg_string):NEWLINE # if it's an empty string, it was meant to be a positionalNEWLINE if not arg_string:NEWLINE return NoneNEWLINENEWLINE # if it doesn't start with a prefix, it was meant to be positionalNEWLINE if not arg_string[0] in self.prefix_chars:NEWLINE return NoneNEWLINENEWLINE # if the option string is present in the parser, return the actionNEWLINE if arg_string in self._option_string_actions:NEWLINE action = self._option_string_actions[arg_string]NEWLINE return action, arg_string, NoneNEWLINENEWLINE # if it's just a single character, it was meant to be positionalNEWLINE if len(arg_string) == 1:NEWLINE return NoneNEWLINENEWLINE # if the option string before the "=" is present, return the actionNEWLINE if '=' in arg_string:NEWLINE option_string, explicit_arg = arg_string.split('=', 1)NEWLINE if option_string in self._option_string_actions:NEWLINE action = self._option_string_actions[option_string]NEWLINE return action, option_string, explicit_argNEWLINENEWLINE # search through all possible prefixes of the option stringNEWLINE # and all actions in the parser for possible interpretationsNEWLINE option_tuples = self._get_option_tuples(arg_string)NEWLINENEWLINE # if multiple actions match, the option string was ambiguousNEWLINE if len(option_tuples) > 1:NEWLINE options = ', '.join([option_stringNEWLINE for action, option_string, explicit_arg in option_tuples])NEWLINE tup = arg_string, optionsNEWLINE self.error(_('ambiguous option: %s could match %s') % tup)NEWLINENEWLINE # if exactly one action matched, this segmentation is good,NEWLINE # so return the parsed actionNEWLINE elif len(option_tuples) == 1:NEWLINE option_tuple, = option_tuplesNEWLINE return option_tupleNEWLINENEWLINE # if it was not found as an option, but it looks like a negativeNEWLINE # number, it was meant to be positionalNEWLINE # unless there are negative-number-like optionsNEWLINE if self._negative_number_matcher.match(arg_string):NEWLINE if not self._has_negative_number_optionals:NEWLINE return NoneNEWLINENEWLINE # if it contains a space, it was meant to be a positionalNEWLINE if ' ' in arg_string:NEWLINE return NoneNEWLINENEWLINE # it was meant to be an optional but there is no such optionNEWLINE # in this parser (though it might be a valid option in a subparser)NEWLINE return None, arg_string, NoneNEWLINENEWLINE def _get_option_tuples(self, option_string):NEWLINE result = []NEWLINENEWLINE # option strings starting with two prefix characters are onlyNEWLINE # split at the '='NEWLINE chars = self.prefix_charsNEWLINE if option_string[0] in chars and option_string[1] in chars:NEWLINE if '=' in option_string:NEWLINE option_prefix, explicit_arg = option_string.split('=', 1)NEWLINE else:NEWLINE option_prefix = option_stringNEWLINE explicit_arg = NoneNEWLINE for option_string in self._option_string_actions:NEWLINE if option_string.startswith(option_prefix):NEWLINE action = self._option_string_actions[option_string]NEWLINE tup = action, option_string, explicit_argNEWLINE result.append(tup)NEWLINENEWLINE # single character options can be concatenated with their argumentsNEWLINE # but multiple character options always have to have their argumentNEWLINE # separateNEWLINE elif option_string[0] in chars and option_string[1] not in chars:NEWLINE option_prefix = option_stringNEWLINE explicit_arg = NoneNEWLINE short_option_prefix = option_string[:2]NEWLINE short_explicit_arg = option_string[2:]NEWLINENEWLINE for option_string in self._option_string_actions:NEWLINE if option_string == short_option_prefix:NEWLINE action = self._option_string_actions[option_string]NEWLINE tup = action, option_string, short_explicit_argNEWLINE result.append(tup)NEWLINE elif option_string.startswith(option_prefix):NEWLINE action = self._option_string_actions[option_string]NEWLINE tup = action, option_string, explicit_argNEWLINE result.append(tup)NEWLINENEWLINE # shouldn't ever get hereNEWLINE else:NEWLINE self.error(_('unexpected option string: %s') % option_string)NEWLINENEWLINE # return the collected option tuplesNEWLINE return resultNEWLINENEWLINE def _get_nargs_pattern(self, action):NEWLINE # in all examples below, we have to allow for '--' argsNEWLINE # which are represented as '-' in the patternNEWLINE nargs = action.nargsNEWLINENEWLINE # the default (None) is assumed to be a single argumentNEWLINE if nargs is None:NEWLINE nargs_pattern = '(-*A-*)'NEWLINENEWLINE # allow zero or one argumentsNEWLINE elif nargs == OPTIONAL:NEWLINE nargs_pattern = '(-*A?-*)'NEWLINENEWLINE # allow zero or more argumentsNEWLINE elif nargs == ZERO_OR_MORE:NEWLINE nargs_pattern = '(-*[A-]*)'NEWLINENEWLINE # allow one or more argumentsNEWLINE elif nargs == ONE_OR_MORE:NEWLINE nargs_pattern = '(-*A[A-]*)'NEWLINENEWLINE # allow any number of options or argumentsNEWLINE elif nargs == REMAINDER:NEWLINE nargs_pattern = '([-AO]*)'NEWLINENEWLINE # allow one argument followed by any number of options or argumentsNEWLINE elif nargs == PARSER:NEWLINE nargs_pattern = '(-*A[-AO]*)'NEWLINENEWLINE # all others should be integersNEWLINE else:NEWLINE nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)NEWLINENEWLINE # if this is an optional action, -- is not allowedNEWLINE if action.option_strings:NEWLINE nargs_pattern = nargs_pattern.replace('-*', '')NEWLINE nargs_pattern = nargs_pattern.replace('-', '')NEWLINENEWLINE # return the patternNEWLINE return nargs_patternNEWLINENEWLINE # ========================NEWLINE # Value conversion methodsNEWLINE # ========================NEWLINE def _get_values(self, action, arg_strings):NEWLINE # for everything but PARSER, REMAINDER args, strip out first '--'NEWLINE if action.nargs not in [PARSER, REMAINDER]:NEWLINE try:NEWLINE arg_strings.remove('--')NEWLINE except ValueError:NEWLINE passNEWLINENEWLINE # optional argument produces a default when not presentNEWLINE if not arg_strings and action.nargs == OPTIONAL:NEWLINE if action.option_strings:NEWLINE value = action.constNEWLINE else:NEWLINE value = action.defaultNEWLINE if isinstance(value, basestring):NEWLINE value = self._get_value(action, value)NEWLINE self._check_value(action, value)NEWLINENEWLINE # when nargs='*' on a positional, if there were no command-lineNEWLINE # args, use the default if it is anything other than NoneNEWLINE elif (not arg_strings and action.nargs == ZERO_OR_MORE andNEWLINE not action.option_strings):NEWLINE if action.default is not None:NEWLINE value = action.defaultNEWLINE else:NEWLINE value = arg_stringsNEWLINE self._check_value(action, value)NEWLINENEWLINE # single argument or optional argument produces a single valueNEWLINE elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:NEWLINE arg_string, = arg_stringsNEWLINE value = self._get_value(action, arg_string)NEWLINE self._check_value(action, value)NEWLINENEWLINE # REMAINDER arguments convert all values, checking noneNEWLINE elif action.nargs == REMAINDER:NEWLINE value = [self._get_value(action, v) for v in arg_strings]NEWLINENEWLINE # PARSER arguments convert all values, but check only the firstNEWLINE elif action.nargs == PARSER:NEWLINE value = [self._get_value(action, v) for v in arg_strings]NEWLINE self._check_value(action, value[0])NEWLINENEWLINE # all other types of nargs produce a listNEWLINE else:NEWLINE value = [self._get_value(action, v) for v in arg_strings]NEWLINE for v in value:NEWLINE self._check_value(action, v)NEWLINENEWLINE # return the converted valueNEWLINE return valueNEWLINENEWLINE def _get_value(self, action, arg_string):NEWLINE type_func = self._registry_get('type', action.type, action.type)NEWLINE if not _callable(type_func):NEWLINE msg = _('%r is not callable')NEWLINE raise ArgumentError(action, msg % type_func)NEWLINENEWLINE # convert the value to the appropriate typeNEWLINE try:NEWLINE result = type_func(arg_string)NEWLINENEWLINE # ArgumentTypeErrors indicate errorsNEWLINE except ArgumentTypeError:NEWLINE name = getattr(action.type, '__name__', repr(action.type))NEWLINE msg = str(_sys.exc_info()[1])NEWLINE raise ArgumentError(action, msg)NEWLINENEWLINE # TypeErrors or ValueErrors also indicate errorsNEWLINE except (TypeError, ValueError):NEWLINE name = getattr(action.type, '__name__', repr(action.type))NEWLINE msg = _('invalid %s value: %r')NEWLINE raise ArgumentError(action, msg % (name, arg_string))NEWLINENEWLINE # return the converted valueNEWLINE return resultNEWLINENEWLINE def _check_value(self, action, value):NEWLINE # converted value must be one of the choices (if specified)NEWLINE if action.choices is not None and value not in action.choices:NEWLINE tup = value, ', '.join(map(repr, action.choices))NEWLINE msg = _('invalid choice: %r (choose from %s)') % tupNEWLINE raise ArgumentError(action, msg)NEWLINENEWLINE # =======================NEWLINE # Help-formatting methodsNEWLINE # =======================NEWLINE def format_usage(self):NEWLINE formatter = self._get_formatter()NEWLINE formatter.add_usage(self.usage, self._actions,NEWLINE self._mutually_exclusive_groups)NEWLINE return formatter.format_help()NEWLINENEWLINE def format_help(self):NEWLINE formatter = self._get_formatter()NEWLINENEWLINE # usageNEWLINE formatter.add_usage(self.usage, self._actions,NEWLINE self._mutually_exclusive_groups)NEWLINENEWLINE # descriptionNEWLINE formatter.add_text(self.description)NEWLINENEWLINE # positionals, optionals and user-defined groupsNEWLINE for action_group in self._action_groups:NEWLINE formatter.start_section(action_group.title)NEWLINE formatter.add_text(action_group.description)NEWLINE formatter.add_arguments(action_group._group_actions)NEWLINE formatter.end_section()NEWLINENEWLINE # epilogNEWLINE formatter.add_text(self.epilog)NEWLINENEWLINE # determine help from format aboveNEWLINE return formatter.format_help()NEWLINENEWLINE def format_version(self):NEWLINE import warningsNEWLINE warnings.warn(NEWLINE 'The format_version method is deprecated -- the "version" 'NEWLINE 'argument to ArgumentParser is no longer supported.',NEWLINE DeprecationWarning)NEWLINE formatter = self._get_formatter()NEWLINE formatter.add_text(self.version)NEWLINE return formatter.format_help()NEWLINENEWLINE def _get_formatter(self):NEWLINE return self.formatter_class(prog=self.prog)NEWLINENEWLINE # =====================NEWLINE # Help-printing methodsNEWLINE # =====================NEWLINE def print_usage(self, file=None):NEWLINE if file is None:NEWLINE file = _sys.stdoutNEWLINE self._print_message(self.format_usage(), file)NEWLINENEWLINE def print_help(self, file=None):NEWLINE if file is None:NEWLINE file = _sys.stdoutNEWLINE self._print_message(self.format_help(), file)NEWLINENEWLINE def print_version(self, file=None):NEWLINE import warningsNEWLINE warnings.warn(NEWLINE 'The print_version method is deprecated -- the "version" 'NEWLINE 'argument to ArgumentParser is no longer supported.',NEWLINE DeprecationWarning)NEWLINE self._print_message(self.format_version(), file)NEWLINENEWLINE def _print_message(self, message, file=None):NEWLINE if message:NEWLINE if file is None:NEWLINE file = _sys.stderrNEWLINE file.write(message)NEWLINENEWLINE # ===============NEWLINE # Exiting methodsNEWLINE # ===============NEWLINE def exit(self, status=0, message=None):NEWLINE if message:NEWLINE self._print_message(message, _sys.stderr)NEWLINE _sys.exit(status)NEWLINENEWLINE def error(self, message):NEWLINE """error(message: string)NEWLINENEWLINE Prints a usage message incorporating the message to stderr andNEWLINE exits.NEWLINENEWLINE If you override this in a subclass, it should not return -- itNEWLINE should either exit or raise an exception.NEWLINE """NEWLINE self.print_usage(_sys.stderr)NEWLINE self.exit(2, _('%s: error: %s\n') % (self.prog, message))NEWLINE #!/usr/bin/env pythonNEWLINENEWLINE# Copyright (c) 2013 Intel Corporation. All rights reserved.NEWLINE# Use of this source code is governed by a BSD-style license that can beNEWLINE# found in the LICENSE file.NEWLINE# pylint: disable=F0401NEWLINENEWLINEimport osNEWLINEimport shutilNEWLINEimport sysNEWLINEfrom common_function import RemoveUnusedFilesInReleaseModeNEWLINENEWLINEdef Clean(dir_to_clean):NEWLINE if os.path.isdir(dir_to_clean):NEWLINE shutil.rmtree(dir_to_clean)NEWLINENEWLINENEWLINEdef PrepareFromChromium(target_dir):NEWLINE gyp_dir = os.path.join(target_dir, 'scripts', 'gyp')NEWLINE if not os.path.exists(gyp_dir):NEWLINE os.makedirs(gyp_dir)NEWLINE shutil.copytree('../build/android/gyp/util', os.path.join(gyp_dir, 'util'))NEWLINE shutil.copy('../build/android/gyp/ant.py', gyp_dir)NEWLINENEWLINENEWLINEdef PrepareFromXwalk(src_dir, target_dir):NEWLINE '''Prepare different files for app packaging tools. All resources are used byNEWLINE make_apk.py.NEWLINE '''NEWLINE # Get the dir of source code from src_dir: ../../.NEWLINE source_code_dir = os.path.dirname(os.path.dirname(src_dir))NEWLINENEWLINE # The directories for source and target .jar files.NEWLINE jar_src_dir = os.path.join(src_dir, 'lib.java')NEWLINE jar_target_dir = os.path.join(target_dir, 'libs')NEWLINENEWLINE # The directories for generated resources.NEWLINE gen_res_src_dir = os.path.join(src_dir, 'gen')NEWLINE gen_res_target_dir = os.path.join(target_dir, 'gen')NEWLINENEWLINE # The directory for source packaging tools.NEWLINE tools_src_dir = os.path.join(source_code_dir, 'xwalk/app/tools/android')NEWLINENEWLINE # The directories for source and target gyp.NEWLINE gyp_src_dir = os.path.join(tools_src_dir, 'gyp')NEWLINE gyp_target_dir = os.path.join(target_dir, 'scripts/gyp')NEWLINENEWLINE # The source file/directory list to be copied and the target directory list.NEWLINE source_target_list = [NEWLINE (os.path.join(source_code_dir, 'xwalk/VERSION'), target_dir),NEWLINENEWLINE # This jar is needed for 'javac' compile.NEWLINE (os.path.join(jar_src_dir, 'xwalk_app_runtime_java.jar'), jar_target_dir),NEWLINE (os.path.join(jar_src_dir, 'xwalk_core_embedded.dex.jar'), jar_target_dir),NEWLINENEWLINE # Native library, like libxwalkcore.so.NEWLINE (os.path.join(src_dir, 'xwalk_runtime_lib_apk/libs/x86'),NEWLINE os.path.join(target_dir, 'native_libs/x86/libs/x86')),NEWLINE (os.path.join(src_dir, 'xwalk_runtime_lib_apk/libs/armeabi-v7a'),NEWLINE os.path.join(target_dir, 'native_libs/armeabi-v7a/libs/armeabi-v7a')),NEWLINENEWLINE # Native source package(xwalk.pak) and related js files for extension.NEWLINE (os.path.join(src_dir, 'xwalk_runtime_lib/assets'),NEWLINE os.path.join(target_dir, 'native_libs_res')),NEWLINENEWLINE # Various Java resources.NEWLINE (os.path.join(source_code_dir, 'content/public/android/java/res'),NEWLINE os.path.join(target_dir, 'libs_res/content')),NEWLINE (os.path.join(source_code_dir, 'ui/android/java/res'),NEWLINE os.path.join(target_dir, 'libs_res/ui')),NEWLINE (os.path.join(source_code_dir, 'xwalk/runtime/android/java/res'),NEWLINE os.path.join(target_dir, 'libs_res/runtime')),NEWLINENEWLINE (os.path.join(gen_res_src_dir, 'ui_java/java_R'),NEWLINE os.path.join(gen_res_target_dir, 'ui_java/java_R')),NEWLINE (os.path.join(gen_res_src_dir, 'ui_java/res_crunched'),NEWLINE os.path.join(gen_res_target_dir, 'ui_java/res_crunched')),NEWLINE (os.path.join(gen_res_src_dir, 'ui_java/res_grit'),NEWLINE os.path.join(gen_res_target_dir, 'ui_java/res_grit')),NEWLINE (os.path.join(gen_res_src_dir, 'ui_java/res_v14_compatibility'),NEWLINE os.path.join(gen_res_target_dir, 'ui_java/res_v14_compatibility')),NEWLINENEWLINE (os.path.join(gen_res_src_dir, 'content_java/java_R'),NEWLINE os.path.join(gen_res_target_dir, 'content_java/java_R')),NEWLINE (os.path.join(gen_res_src_dir, 'content_java/res_crunched'),NEWLINE os.path.join(gen_res_target_dir, 'content_java/res_crunched')),NEWLINE (os.path.join(gen_res_src_dir, 'content_java/res_grit'),NEWLINE os.path.join(gen_res_target_dir, 'content_java/res_grit')),NEWLINE (os.path.join(gen_res_src_dir, 'content_java/res_v14_compatibility'),NEWLINE os.path.join(gen_res_target_dir, 'content_java/res_v14_compatibility')),NEWLINENEWLINE (os.path.join(gen_res_src_dir, 'xwalk_core_java/java_R'),NEWLINE os.path.join(gen_res_target_dir, 'xwalk_core_java/java_R')),NEWLINE (os.path.join(gen_res_src_dir, 'xwalk_core_java/res_crunched'),NEWLINE os.path.join(gen_res_target_dir, 'xwalk_core_java/res_crunched')),NEWLINE (os.path.join(gen_res_src_dir, 'xwalk_core_java/res_grit'),NEWLINE os.path.join(gen_res_target_dir, 'xwalk_core_java/res_grit')),NEWLINE (os.path.join(gen_res_src_dir, 'xwalk_core_java/res_v14_compatibility'),NEWLINE os.path.join(gen_res_target_dir, 'xwalk_core_java/res_v14_compatibility')),NEWLINENEWLINE # The app wrapper code. It's the template Java code.NEWLINE (os.path.join(source_code_dir, 'xwalk/app/android/app_template'),NEWLINE os.path.join(target_dir, 'app_src')),NEWLINENEWLINE # Copy below 5 files to overwrite the existing ones from Chromium.NEWLINE (os.path.join(gyp_src_dir, 'util/build_utils.py'),NEWLINE os.path.join(gyp_target_dir, 'util')),NEWLINE (os.path.join(gyp_src_dir, 'dex.py'), gyp_target_dir),NEWLINE (os.path.join(gyp_src_dir, 'finalize_apk.py'), gyp_target_dir),NEWLINE (os.path.join(gyp_src_dir, 'jar.py'), gyp_target_dir),NEWLINE (os.path.join(gyp_src_dir, 'javac.py'), gyp_target_dir),NEWLINENEWLINE # Build and python tools.NEWLINE (os.path.join(tools_src_dir, 'ant'),NEWLINE os.path.join(target_dir, 'scripts/ant')),NEWLINE (os.path.join(tools_src_dir, 'customize.py'), target_dir),NEWLINE (os.path.join(tools_src_dir, 'handle_permissions.py'), target_dir),NEWLINE (os.path.join(tools_src_dir, 'handle_xml.py'), target_dir),NEWLINE (os.path.join(tools_src_dir, 'make_apk.py'), target_dir),NEWLINE (os.path.join(tools_src_dir, 'manifest_json_parser.py'), target_dir),NEWLINE (os.path.join(tools_src_dir, 'parse_xpk.py'), target_dir)NEWLINE ]NEWLINENEWLINE for index in range(len(source_target_list)):NEWLINE source_path, target_path = source_target_list[index]NEWLINENEWLINE # Process source.NEWLINE if not os.path.exists(source_path):NEWLINE print ('The source path "%s" does not exist.' % source_path)NEWLINE continueNEWLINENEWLINE source_is_file = os.path.isfile(source_path)NEWLINENEWLINE # Process target.NEWLINE if source_is_file and not os.path.exists(target_path):NEWLINE os.makedirs(target_path)NEWLINENEWLINE # Do copy.NEWLINE if source_is_file:NEWLINE shutil.copy(source_path, target_path)NEWLINE else:NEWLINE shutil.copytree(source_path, target_path)NEWLINENEWLINE # Remove unused files.NEWLINE mode = os.path.basename(os.path.dirname(target_dir))NEWLINE RemoveUnusedFilesInReleaseMode(mode, os.path.join(target_dir, 'native_libs'))NEWLINENEWLINENEWLINEdef main(args):NEWLINE if len(args) != 1:NEWLINE print 'You must provide only one argument: folder to update'NEWLINE return 1NEWLINE target_dir = args[0]NEWLINE src_dir = os.path.dirname(target_dir)NEWLINE Clean(target_dir)NEWLINE PrepareFromChromium(target_dir)NEWLINE PrepareFromXwalk(src_dir, target_dir)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE sys.exit(main(sys.argv[1:]))NEWLINE """NEWLINEMetric Learning for Kernel Regression (MLKR), Weinberger et al.,NEWLINENEWLINEMLKR is an algorithm for supervised metric learning, which learns a distanceNEWLINEfunction by directly minimising the leave-one-out regression error. ThisNEWLINEalgorithm can also be viewed as a supervised variation of PCA and can be usedNEWLINEfor dimensionality reduction and high dimensional data visualization.NEWLINE"""NEWLINEfrom __future__ import division, print_functionNEWLINEimport numpy as npNEWLINEfrom scipy.optimize import minimizeNEWLINEfrom scipy.spatial.distance import pdist, squareformNEWLINEfrom sklearn.decomposition import PCANEWLINEfrom sklearn.utils.validation import check_X_yNEWLINENEWLINEfrom .base_metric import BaseMetricLearnerNEWLINENEWLINEEPS = np.finfo(float).epsNEWLINENEWLINENEWLINEclass MLKR(BaseMetricLearner):NEWLINE """Metric Learning for Kernel Regression (MLKR)"""NEWLINE def __init__(self, num_dims=None, A0=None, epsilon=0.01, alpha=0.0001,NEWLINE max_iter=1000):NEWLINE """NEWLINE Initialize MLKR.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE num_dims : int, optionalNEWLINE Dimensionality of reduced space (defaults to dimension of X)NEWLINENEWLINE A0: array-like, optionalNEWLINE Initialization of transformation matrix. Defaults to PCA loadings.NEWLINENEWLINE epsilon: float, optionalNEWLINE Step size for congujate gradient descent.NEWLINENEWLINE alpha: float, optionalNEWLINE Stopping criterion for congujate gradient descent.NEWLINENEWLINE max_iter: int, optionalNEWLINE Cap on number of congugate gradient iterations.NEWLINE """NEWLINE self.num_dims = num_dimsNEWLINE self.A0 = A0NEWLINE self.epsilon = epsilonNEWLINE self.alpha = alphaNEWLINE self.max_iter = max_iterNEWLINENEWLINE def _process_inputs(self, X, y):NEWLINE self.X_, y = check_X_y(X, y)NEWLINE n, d = self.X_.shapeNEWLINE if y.shape[0] != n:NEWLINE raise ValueError('Data and label lengths mismatch: %d != %d'NEWLINE % (n, y.shape[0]))NEWLINENEWLINE A = self.A0NEWLINE m = self.num_dimsNEWLINE if m is None:NEWLINE m = dNEWLINE if A is None:NEWLINE # initialize to PCA transformation matrixNEWLINE # note: not the same as n_components=m !NEWLINE A = PCA().fit(X).components_.T[:m]NEWLINE elif A.shape != (m, d):NEWLINE raise ValueError('A0 needs shape (%d,%d) but got %s' % (NEWLINE m, d, A.shape))NEWLINE return self.X_, y, ANEWLINENEWLINE def fit(self, X, y):NEWLINE """NEWLINE Fit MLKR modelNEWLINENEWLINE Parameters:NEWLINE ----------NEWLINE X : (n x d) array of samplesNEWLINE y : (n) data labelsNEWLINE """NEWLINE X, y, A = self._process_inputs(X, y)NEWLINENEWLINE # note: this line takes (n*n*d) memory!NEWLINE # for larger datasets, we'll need to compute dX as we goNEWLINE dX = (X[None] - X[:, None]).reshape((-1, X.shape[1]))NEWLINENEWLINE res = minimize(_loss, A.ravel(), (X, y, dX), method='CG', jac=True,NEWLINE tol=self.alpha,NEWLINE options=dict(maxiter=self.max_iter, eps=self.epsilon))NEWLINE self.transformer_ = res.x.reshape(A.shape)NEWLINE self.n_iter_ = res.nitNEWLINE return selfNEWLINENEWLINE def transformer(self):NEWLINE return self.transformer_NEWLINENEWLINENEWLINEdef _loss(flatA, X, y, dX):NEWLINE A = flatA.reshape((-1, X.shape[1]))NEWLINE dist = pdist(X, metric='mahalanobis', VI=A.T.dot(A))NEWLINE K = squareform(np.exp(-dist**2))NEWLINE denom = np.maximum(K.sum(axis=0), EPS)NEWLINE yhat = K.dot(y) / denomNEWLINE ydiff = yhat - yNEWLINE cost = (ydiff**2).sum()NEWLINENEWLINE # also compute the gradientNEWLINE np.fill_diagonal(K, 1)NEWLINE W = 2 * K * (np.outer(ydiff, ydiff) / denom)NEWLINE # note: this is the part that the matlab impl drops to C forNEWLINE M = (dX.T * W.ravel()).dot(dX)NEWLINE grad = 2 * A.dot(M)NEWLINE return cost, grad.ravel()NEWLINE # coding: utf-8NEWLINE"""NEWLINE Cisco IntersightNEWLINENEWLINE Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advanced ways than the prior generations of tools. Cisco Intersight provides an integrated and intuitive management experience for resources in the traditional data center as well as at the edge. With flexible deployment options to address complex security needs, getting started with Intersight is quick and easy. Cisco Intersight has deep integration with Cisco UCS and HyperFlex systems allowing for remote deployment, configuration, and ongoing maintenance. The model-based deployment works for a single system in a remote location or hundreds of systems in a data center and enables rapid, standardized configuration and deployment. It also streamlines maintaining those systems whether you are working with small or very large configurations. # noqa: E501NEWLINENEWLINE The version of the OpenAPI document: 1.0.9-1295NEWLINE Contact: intersight@cisco.comNEWLINE Generated by: https://openapi-generator.techNEWLINE"""NEWLINENEWLINEfrom __future__ import absolute_importNEWLINENEWLINEimport unittestNEWLINENEWLINEimport intersightNEWLINEfrom intersight.models.syslog_policy_list import SyslogPolicyList # noqa: E501NEWLINEfrom intersight.rest import ApiExceptionNEWLINENEWLINENEWLINEclass TestSyslogPolicyList(unittest.TestCase):NEWLINE """SyslogPolicyList unit test stubs"""NEWLINE def setUp(self):NEWLINE passNEWLINENEWLINE def tearDown(self):NEWLINE passNEWLINENEWLINE def testSyslogPolicyList(self):NEWLINE """Test SyslogPolicyList"""NEWLINE # FIXME: construct object with mandatory attributes with example valuesNEWLINE # model = intersight.models.syslog_policy_list.SyslogPolicyList() # noqa: E501NEWLINE passNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE unittest.main()NEWLINE #!/usr/bin/env python3NEWLINE# -*- coding: utf-8 -*-NEWLINENEWLINENEWLINEdef test_list():NEWLINE L1 = ['Hello', 'World', 18, 'Apple', None]NEWLINE L2 = [i.lower() for i in L1 if isinstance(i, str)]NEWLINE print(L1)NEWLINE print(L2)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE print('list comprehensions:')NEWLINE print('range 1~10:', [i for i in range(1, 11)])NEWLINE print('square 1~10:', [i * i for i in range(1, 11)])NEWLINE print('square odd 1~10:', [i * i for i in range(1, 11) if i % 2 == 0])NEWLINE print('combine alpha:', [i + j for i in 'ABC' for j in 'XYZ'])NEWLINE test_list()NEWLINE from django.conf import settingsNEWLINEfrom hashids import HashidsNEWLINENEWLINENEWLINEdef get_hashids():NEWLINE return Hashids(NEWLINE salt=settings.SECRET_KEY, min_length=4, alphabet="abcdefghijklmnopqrstuvwxyz"NEWLINE )NEWLINENEWLINENEWLINEdef decode_hashid(hashid):NEWLINE hashids = get_hashids()NEWLINENEWLINE return hashids.decode(hashid)[0]NEWLINENEWLINENEWLINEdef encode_hashid(value):NEWLINE hashids = get_hashids()NEWLINENEWLINE return hashids.encode(value)NEWLINE # Copyright 2016 Confluent Inc.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINENEWLINEimport datetimeNEWLINEimport jsonNEWLINEimport osNEWLINEimport reNEWLINEimport signalNEWLINEimport socketNEWLINEimport sysNEWLINEimport timeNEWLINENEWLINENEWLINEclass VerifiableClient(object):NEWLINE """NEWLINE Generic base class for a kafkatest verifiable client.NEWLINE Implements the common kafkatest protocol and semantics.NEWLINE """NEWLINE def __init__(self, conf):NEWLINE """NEWLINE """NEWLINE super(VerifiableClient, self).__init__()NEWLINE self.conf = confNEWLINE self.conf['client.id'] = 'python@' + socket.gethostname()NEWLINE self.run = TrueNEWLINE signal.signal(signal.SIGTERM, self.sig_term)NEWLINE self.dbg('Pid is %d' % os.getpid())NEWLINENEWLINE def sig_term(self, sig, frame):NEWLINE self.dbg('SIGTERM')NEWLINE self.run = FalseNEWLINENEWLINE @staticmethodNEWLINE def _timestamp():NEWLINE return time.strftime('%H:%M:%S', time.localtime())NEWLINENEWLINE def dbg(self, s):NEWLINE """ Debugging printout """NEWLINE sys.stderr.write('%% %s DEBUG: %s\n' % (self._timestamp(), s))NEWLINENEWLINE def err(self, s, term=False):NEWLINE """ Error printout, if term=True the process will terminate immediately. """NEWLINE sys.stderr.write('%% %s ERROR: %s\n' % (self._timestamp(), s))NEWLINE if term:NEWLINE sys.stderr.write('%% FATAL ERROR ^\n')NEWLINE sys.exit(1)NEWLINENEWLINE def send(self, d):NEWLINE """ Send dict as JSON to stdout for consumtion by kafkatest handler """NEWLINE d['_time'] = str(datetime.datetime.now())NEWLINE self.dbg('SEND: %s' % json.dumps(d))NEWLINE sys.stdout.write('%s\n' % json.dumps(d))NEWLINE sys.stdout.flush()NEWLINENEWLINE @staticmethodNEWLINE def set_config(conf, args):NEWLINE """ Set client config properties using args dict. """NEWLINE for n, v in args.iteritems():NEWLINE if v is None:NEWLINE continueNEWLINE # Things to ignoreNEWLINE if '.' not in n:NEWLINE # App config, skipNEWLINE continueNEWLINE if n.startswith('topic.'):NEWLINE # Set "topic.<...>" properties on default topic conf dictNEWLINE conf['default.topic.config'][n[6:]] = vNEWLINE elif n == 'partition.assignment.strategy':NEWLINE # Convert Java class name to config value.NEWLINE # "org.apache.kafka.clients.consumer.RangeAssignor" -> "range"NEWLINE conf[n] = re.sub(r'org.apache.kafka.clients.consumer.(\w+)Assignor',NEWLINE lambda x: x.group(1).lower(), v)NEWLINE else:NEWLINE conf[n] = vNEWLINE #!/usr/bin/env pythonNEWLINE# -*- coding: utf-8 -*-NEWLINE# @Time : 2018/12/24 10:05 AMNEWLINE# @Author : zhangzhenNEWLINE# @Site : NEWLINE# @File : torch_lstm_classification.pyNEWLINE# @Software: PyCharmNEWLINEimport torchNEWLINEimport torchvisionNEWLINEfrom torch import nnNEWLINEimport torch.utils.data as DataNEWLINEfrom torch.autograd import VariableNEWLINEimport torchvision.datasets as dsNEWLINEimport torchvision.transforms as transformsNEWLINEimport matplotlib.pyplot as pltNEWLINENEWLINEtorch.manual_seed(1) # reproducibleNEWLINENEWLINE# hyper ParametersNEWLINEEPOCH = 1NEWLINEBATCH_SIZE = 128NEWLINETIME_STEP = 28NEWLINEINPUT_SIZE = 28NEWLINELR = 0.01NEWLINEDOWNLOAD_MNIST = FalseNEWLINEROOT = '/Users/zhangzhen/gitRepository/AnalyticsVidhya/data/mnist'NEWLINEtrain_data = torchvision.datasets.MNIST(NEWLINE root=ROOT,NEWLINE train=True,NEWLINE transform=torchvision.transforms.ToTensor(),NEWLINE download=DOWNLOAD_MNIST,NEWLINE)NEWLINENEWLINE# plt.imshow(train_data.train_data[0], cmap='gray')NEWLINE# plt.show()NEWLINEtest_data = torchvision.datasets.MNIST(NEWLINE root=ROOT,NEWLINE train=False,NEWLINE)NEWLINENEWLINE# batch settingNEWLINEtrain_loader = Data.DataLoader(NEWLINE dataset=train_data,NEWLINE batch_size=BATCH_SIZE,NEWLINE shuffle=TrueNEWLINE)NEWLINE# simplify data setNEWLINEtest_x = Variable(test_data.test_data, volatile=True).type(torch.FloatTensor)[: 2000]/255.NEWLINEtest_y = test_data.test_labels.numpy().squeeze()[: 2000]NEWLINENEWLINEprint(test_x.shape, test_y.shape)NEWLINENEWLINENEWLINEclass RNN(nn.Module):NEWLINENEWLINE def __init__(self):NEWLINE super(RNN, self).__init__()NEWLINENEWLINE self.rnn = nn.LSTM(NEWLINE input_size=INPUT_SIZE,NEWLINE hidden_size=64,NEWLINE num_layers=2,NEWLINE batch_first=True, # False -> (time_step, batch, input) True -> (batch, time_step, input)NEWLINE )NEWLINE self.out = nn.Linear(64, 10)NEWLINENEWLINE def forward(self, *input):NEWLINE r_out, h_state = self.rnn(input[0], None) # x-> (batch, time_step, input_size)NEWLINE out = self.out(r_out[:, -1, :]) # (batch, time_step, input)NEWLINE return outNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINENEWLINE rnn = RNN()NEWLINE # print(rnn)NEWLINE optimizer = torch.optim.Adam(rnn.parameters(), lr=LR)NEWLINE loss_func = nn.CrossEntropyLoss()NEWLINENEWLINE for epoch in range(EPOCH):NEWLINE for step, (x, y) in enumerate(train_loader):NEWLINE b_x = Variable(x.view(-1, 28, 28))NEWLINE b_y = Variable(y)NEWLINE output = rnn(b_x)NEWLINE loss = loss_func(output, b_y)NEWLINENEWLINE optimizer.zero_grad()NEWLINE loss.backward()NEWLINE optimizer.step()NEWLINENEWLINE if step % 50 == 0:NEWLINE test_out = rnn(test_x)NEWLINE pred_y = torch.max(test_out, 1)[1].data.numpy().squeeze()NEWLINE acc = sum(pred_y==test_y)/test_y.sizeNEWLINE print('Epoch:', epoch, '| train loss: %.4f' % loss.item(), 'test acc: %.4f' % acc)NEWLINENEWLINE # print 10 predictions from test dataNEWLINE test_output = rnn(test_x[:10])NEWLINE pred_y = torch.max(test_output, 1)[1].data.numpy().squeeze()NEWLINE print(pred_y, 'prediction number')NEWLINE print(test_y[:10], 'real number')NEWLINE # Generated by Django 2.0 on 2019-12-22 18:26NEWLINENEWLINEfrom django.db import migrations, modelsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ('products', '0012_auto_20191222_2354'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.AlterField(NEWLINE model_name='product',NEWLINE name='slug',NEWLINE field=models.SlugField(blank=True, unique=True),NEWLINE ),NEWLINE ]NEWLINE # coding: utf-8NEWLINENEWLINE"""NEWLINE HyperOneNEWLINENEWLINE HyperOne API # noqa: E501NEWLINENEWLINE The version of the OpenAPI document: 0.1.0NEWLINE Generated by: https://openapi-generator.techNEWLINE"""NEWLINENEWLINENEWLINEimport pprintNEWLINEimport re # noqa: F401NEWLINENEWLINEimport sixNEWLINENEWLINEfrom h1.configuration import ConfigurationNEWLINENEWLINENEWLINEclass Vault(object):NEWLINE """NOTE: This class is auto generated by OpenAPI Generator.NEWLINE Ref: https://openapi-generator.techNEWLINENEWLINE Do not edit the class manually.NEWLINE """NEWLINENEWLINE """NEWLINE Attributes:NEWLINE openapi_types (dict): The key is attribute nameNEWLINE and the value is attribute type.NEWLINE attribute_map (dict): The key is attribute nameNEWLINE and the value is json key in definition.NEWLINE """NEWLINE openapi_types = {NEWLINE 'id': 'str',NEWLINE 'name': 'str',NEWLINE 'flavour': 'str',NEWLINE 'modified_on': 'datetime',NEWLINE 'modified_by': 'str',NEWLINE 'created_on': 'datetime',NEWLINE 'created_by': 'str',NEWLINE 'state': 'str',NEWLINE 'project': 'str',NEWLINE 'uri': 'str',NEWLINE 'size_used': 'float',NEWLINE 'size': 'float',NEWLINE 'fqdn': 'str',NEWLINE 'tag': 'list[Tag]'NEWLINE }NEWLINENEWLINE attribute_map = {NEWLINE 'id': 'id',NEWLINE 'name': 'name',NEWLINE 'flavour': 'flavour',NEWLINE 'modified_on': 'modifiedOn',NEWLINE 'modified_by': 'modifiedBy',NEWLINE 'created_on': 'createdOn',NEWLINE 'created_by': 'createdBy',NEWLINE 'state': 'state',NEWLINE 'project': 'project',NEWLINE 'uri': 'uri',NEWLINE 'size_used': 'sizeUsed',NEWLINE 'size': 'size',NEWLINE 'fqdn': 'fqdn',NEWLINE 'tag': 'tag'NEWLINE }NEWLINENEWLINE def __init__(self, id=None, name=None, flavour=None, modified_on=None, modified_by=None, created_on=None, created_by=None, state=None, project=None, uri=None, size_used=None, size=None, fqdn=None, tag=None, local_vars_configuration=None): # noqa: E501NEWLINE """Vault - a model defined in OpenAPI""" # noqa: E501NEWLINE if local_vars_configuration is None:NEWLINE local_vars_configuration = Configuration()NEWLINE self.local_vars_configuration = local_vars_configurationNEWLINENEWLINE self._id = NoneNEWLINE self._name = NoneNEWLINE self._flavour = NoneNEWLINE self._modified_on = NoneNEWLINE self._modified_by = NoneNEWLINE self._created_on = NoneNEWLINE self._created_by = NoneNEWLINE self._state = NoneNEWLINE self._project = NoneNEWLINE self._uri = NoneNEWLINE self._size_used = NoneNEWLINE self._size = NoneNEWLINE self._fqdn = NoneNEWLINE self._tag = NoneNEWLINE self.discriminator = NoneNEWLINENEWLINE if id is not None:NEWLINE self.id = idNEWLINE if name is not None:NEWLINE self.name = nameNEWLINE if flavour is not None:NEWLINE self.flavour = flavourNEWLINE if modified_on is not None:NEWLINE self.modified_on = modified_onNEWLINE if modified_by is not None:NEWLINE self.modified_by = modified_byNEWLINE if created_on is not None:NEWLINE self.created_on = created_onNEWLINE if created_by is not None:NEWLINE self.created_by = created_byNEWLINE if state is not None:NEWLINE self.state = stateNEWLINE if project is not None:NEWLINE self.project = projectNEWLINE if uri is not None:NEWLINE self.uri = uriNEWLINE if size_used is not None:NEWLINE self.size_used = size_usedNEWLINE if size is not None:NEWLINE self.size = sizeNEWLINE if fqdn is not None:NEWLINE self.fqdn = fqdnNEWLINE if tag is not None:NEWLINE self.tag = tagNEWLINENEWLINE @propertyNEWLINE def id(self):NEWLINE """Gets the id of this Vault. # noqa: E501NEWLINENEWLINENEWLINE :return: The id of this Vault. # noqa: E501NEWLINE :rtype: strNEWLINE """NEWLINE return self._idNEWLINENEWLINE @id.setterNEWLINE def id(self, id):NEWLINE """Sets the id of this Vault.NEWLINENEWLINENEWLINE :param id: The id of this Vault. # noqa: E501NEWLINE :type: strNEWLINE """NEWLINENEWLINE self._id = idNEWLINENEWLINE @propertyNEWLINE def name(self):NEWLINE """Gets the name of this Vault. # noqa: E501NEWLINENEWLINENEWLINE :return: The name of this Vault. # noqa: E501NEWLINE :rtype: strNEWLINE """NEWLINE return self._nameNEWLINENEWLINE @name.setterNEWLINE def name(self, name):NEWLINE """Sets the name of this Vault.NEWLINENEWLINENEWLINE :param name: The name of this Vault. # noqa: E501NEWLINE :type: strNEWLINE """NEWLINENEWLINE self._name = nameNEWLINENEWLINE @propertyNEWLINE def flavour(self):NEWLINE """Gets the flavour of this Vault. # noqa: E501NEWLINENEWLINENEWLINE :return: The flavour of this Vault. # noqa: E501NEWLINE :rtype: strNEWLINE """NEWLINE return self._flavourNEWLINENEWLINE @flavour.setterNEWLINE def flavour(self, flavour):NEWLINE """Sets the flavour of this Vault.NEWLINENEWLINENEWLINE :param flavour: The flavour of this Vault. # noqa: E501NEWLINE :type: strNEWLINE """NEWLINENEWLINE self._flavour = flavourNEWLINENEWLINE @propertyNEWLINE def modified_on(self):NEWLINE """Gets the modified_on of this Vault. # noqa: E501NEWLINENEWLINENEWLINE :return: The modified_on of this Vault. # noqa: E501NEWLINE :rtype: datetimeNEWLINE """NEWLINE return self._modified_onNEWLINENEWLINE @modified_on.setterNEWLINE def modified_on(self, modified_on):NEWLINE """Sets the modified_on of this Vault.NEWLINENEWLINENEWLINE :param modified_on: The modified_on of this Vault. # noqa: E501NEWLINE :type: datetimeNEWLINE """NEWLINENEWLINE self._modified_on = modified_onNEWLINENEWLINE @propertyNEWLINE def modified_by(self):NEWLINE """Gets the modified_by of this Vault. # noqa: E501NEWLINENEWLINENEWLINE :return: The modified_by of this Vault. # noqa: E501NEWLINE :rtype: strNEWLINE """NEWLINE return self._modified_byNEWLINENEWLINE @modified_by.setterNEWLINE def modified_by(self, modified_by):NEWLINE """Sets the modified_by of this Vault.NEWLINENEWLINENEWLINE :param modified_by: The modified_by of this Vault. # noqa: E501NEWLINE :type: strNEWLINE """NEWLINENEWLINE self._modified_by = modified_byNEWLINENEWLINE @propertyNEWLINE def created_on(self):NEWLINE """Gets the created_on of this Vault. # noqa: E501NEWLINENEWLINENEWLINE :return: The created_on of this Vault. # noqa: E501NEWLINE :rtype: datetimeNEWLINE """NEWLINE return self._created_onNEWLINENEWLINE @created_on.setterNEWLINE def created_on(self, created_on):NEWLINE """Sets the created_on of this Vault.NEWLINENEWLINENEWLINE :param created_on: The created_on of this Vault. # noqa: E501NEWLINE :type: datetimeNEWLINE """NEWLINENEWLINE self._created_on = created_onNEWLINENEWLINE @propertyNEWLINE def created_by(self):NEWLINE """Gets the created_by of this Vault. # noqa: E501NEWLINENEWLINENEWLINE :return: The created_by of this Vault. # noqa: E501NEWLINE :rtype: strNEWLINE """NEWLINE return self._created_byNEWLINENEWLINE @created_by.setterNEWLINE def created_by(self, created_by):NEWLINE """Sets the created_by of this Vault.NEWLINENEWLINENEWLINE :param created_by: The created_by of this Vault. # noqa: E501NEWLINE :type: strNEWLINE """NEWLINENEWLINE self._created_by = created_byNEWLINENEWLINE @propertyNEWLINE def state(self):NEWLINE """Gets the state of this Vault. # noqa: E501NEWLINENEWLINENEWLINE :return: The state of this Vault. # noqa: E501NEWLINE :rtype: strNEWLINE """NEWLINE return self._stateNEWLINENEWLINE @state.setterNEWLINE def state(self, state):NEWLINE """Sets the state of this Vault.NEWLINENEWLINENEWLINE :param state: The state of this Vault. # noqa: E501NEWLINE :type: strNEWLINE """NEWLINE allowed_values = ["Online", "Off", "Unknown", "Processing", "NotCreated"] # noqa: E501NEWLINE if self.local_vars_configuration.client_side_validation and state not in allowed_values: # noqa: E501NEWLINE raise ValueError(NEWLINE "Invalid value for `state` ({0}), must be one of {1}" # noqa: E501NEWLINE .format(state, allowed_values)NEWLINE )NEWLINENEWLINE self._state = stateNEWLINENEWLINE @propertyNEWLINE def project(self):NEWLINE """Gets the project of this Vault. # noqa: E501NEWLINENEWLINENEWLINE :return: The project of this Vault. # noqa: E501NEWLINE :rtype: strNEWLINE """NEWLINE return self._projectNEWLINENEWLINE @project.setterNEWLINE def project(self, project):NEWLINE """Sets the project of this Vault.NEWLINENEWLINENEWLINE :param project: The project of this Vault. # noqa: E501NEWLINE :type: strNEWLINE """NEWLINENEWLINE self._project = projectNEWLINENEWLINE @propertyNEWLINE def uri(self):NEWLINE """Gets the uri of this Vault. # noqa: E501NEWLINENEWLINENEWLINE :return: The uri of this Vault. # noqa: E501NEWLINE :rtype: strNEWLINE """NEWLINE return self._uriNEWLINENEWLINE @uri.setterNEWLINE def uri(self, uri):NEWLINE """Sets the uri of this Vault.NEWLINENEWLINENEWLINE :param uri: The uri of this Vault. # noqa: E501NEWLINE :type: strNEWLINE """NEWLINENEWLINE self._uri = uriNEWLINENEWLINE @propertyNEWLINE def size_used(self):NEWLINE """Gets the size_used of this Vault. # noqa: E501NEWLINENEWLINENEWLINE :return: The size_used of this Vault. # noqa: E501NEWLINE :rtype: floatNEWLINE """NEWLINE return self._size_usedNEWLINENEWLINE @size_used.setterNEWLINE def size_used(self, size_used):NEWLINE """Sets the size_used of this Vault.NEWLINENEWLINENEWLINE :param size_used: The size_used of this Vault. # noqa: E501NEWLINE :type: floatNEWLINE """NEWLINENEWLINE self._size_used = size_usedNEWLINENEWLINE @propertyNEWLINE def size(self):NEWLINE """Gets the size of this Vault. # noqa: E501NEWLINENEWLINENEWLINE :return: The size of this Vault. # noqa: E501NEWLINE :rtype: floatNEWLINE """NEWLINE return self._sizeNEWLINENEWLINE @size.setterNEWLINE def size(self, size):NEWLINE """Sets the size of this Vault.NEWLINENEWLINENEWLINE :param size: The size of this Vault. # noqa: E501NEWLINE :type: floatNEWLINE """NEWLINENEWLINE self._size = sizeNEWLINENEWLINE @propertyNEWLINE def fqdn(self):NEWLINE """Gets the fqdn of this Vault. # noqa: E501NEWLINENEWLINENEWLINE :return: The fqdn of this Vault. # noqa: E501NEWLINE :rtype: strNEWLINE """NEWLINE return self._fqdnNEWLINENEWLINE @fqdn.setterNEWLINE def fqdn(self, fqdn):NEWLINE """Sets the fqdn of this Vault.NEWLINENEWLINENEWLINE :param fqdn: The fqdn of this Vault. # noqa: E501NEWLINE :type: strNEWLINE """NEWLINENEWLINE self._fqdn = fqdnNEWLINENEWLINE @propertyNEWLINE def tag(self):NEWLINE """Gets the tag of this Vault. # noqa: E501NEWLINENEWLINENEWLINE :return: The tag of this Vault. # noqa: E501NEWLINE :rtype: list[Tag]NEWLINE """NEWLINE return self._tagNEWLINENEWLINE @tag.setterNEWLINE def tag(self, tag):NEWLINE """Sets the tag of this Vault.NEWLINENEWLINENEWLINE :param tag: The tag of this Vault. # noqa: E501NEWLINE :type: list[Tag]NEWLINE """NEWLINENEWLINE self._tag = tagNEWLINENEWLINE def to_dict(self):NEWLINE """Returns the model properties as a dict"""NEWLINE result = {}NEWLINENEWLINE for attr, _ in six.iteritems(self.openapi_types):NEWLINE value = getattr(self, attr)NEWLINE if isinstance(value, list):NEWLINE result[attr] = list(map(NEWLINE lambda x: x.to_dict() if hasattr(x, "to_dict") else x,NEWLINE valueNEWLINE ))NEWLINE elif hasattr(value, "to_dict"):NEWLINE result[attr] = value.to_dict()NEWLINE elif isinstance(value, dict):NEWLINE result[attr] = dict(map(NEWLINE lambda item: (item[0], item[1].to_dict())NEWLINE if hasattr(item[1], "to_dict") else item,NEWLINE value.items()NEWLINE ))NEWLINE else:NEWLINE result[attr] = valueNEWLINENEWLINE return resultNEWLINENEWLINE def to_str(self):NEWLINE """Returns the string representation of the model"""NEWLINE return pprint.pformat(self.to_dict())NEWLINENEWLINE def __repr__(self):NEWLINE """For `print` and `pprint`"""NEWLINE return self.to_str()NEWLINENEWLINE def __eq__(self, other):NEWLINE """Returns true if both objects are equal"""NEWLINE if not isinstance(other, Vault):NEWLINE return FalseNEWLINENEWLINE return self.to_dict() == other.to_dict()NEWLINENEWLINE def __ne__(self, other):NEWLINE """Returns true if both objects are not equal"""NEWLINE if not isinstance(other, Vault):NEWLINE return TrueNEWLINENEWLINE return self.to_dict() != other.to_dict()NEWLINE # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINEimport argparseNEWLINEimport osNEWLINEimport randomNEWLINEimport timeNEWLINEimport mathNEWLINEimport sysNEWLINEfrom functools import partialNEWLINENEWLINEimport numpy as npNEWLINEimport paddleNEWLINENEWLINEimport paddlenlp as ppnlpNEWLINEfrom paddlenlp.transformers import LinearDecayWithWarmupNEWLINEfrom paddlenlp.metrics import ChunkEvaluatorNEWLINEfrom paddlenlp.datasets import load_datasetNEWLINEfrom paddlenlp.data import Stack, Tuple, PadNEWLINEfrom paddlenlp.utils.log import loggerNEWLINENEWLINE# from paddlenlp.trainer.trainer_base import TrainerBaseNEWLINEsys.path.insert(0, os.path.abspath("."))NEWLINEfrom utils import DictNEWLINENEWLINENEWLINEdef tokenize_and_align_labels(example, tokenizer, no_entity_id,NEWLINE max_seq_len=512):NEWLINE labels = example['labels']NEWLINE example = example['tokens']NEWLINE tokenized_input = tokenizer(NEWLINE example,NEWLINE is_split_into_words=True,NEWLINE max_seq_len=max_seq_len, )NEWLINENEWLINE # -2 for [CLS] and [SEP]NEWLINE if len(tokenized_input['input_ids']) - 2 < len(labels):NEWLINE labels = labels[:len(tokenized_input['input_ids']) - 2]NEWLINE tokenized_input['labels'] = [no_entity_id] + labels + [no_entity_id]NEWLINE tokenized_input['labels'] += [no_entity_id] * (NEWLINE len(tokenized_input['input_ids']) - len(tokenized_input['labels']))NEWLINENEWLINE return tokenized_inputNEWLINENEWLINENEWLINEdef ner_collator(tokenizer, args):NEWLINE batchify_fn = lambda samples, fn=Dict({NEWLINE 'input_ids': Pad(axis=0, pad_val=tokenizer.pad_token_id, dtype='int32'), # inputNEWLINE 'token_type_ids': Pad(axis=0, pad_val=tokenizer.pad_token_type_id, dtype='int32'), # segmentNEWLINE 'labels': Pad(axis=0, pad_val=args.ignore_label, dtype='int64') # labelNEWLINE }): fn(samples)NEWLINENEWLINE return batchify_fnNEWLINENEWLINENEWLINEdef ner_trans_fn(example, tokenizer, args):NEWLINE return tokenize_and_align_labels(NEWLINE example,NEWLINE tokenizer=tokenizer,NEWLINE no_entity_id=args.no_entity_id,NEWLINE max_seq_len=args.max_seq_length)NEWLINE #!/usr/bin/env pythonNEWLINE## -*- coding: utf-8 -*-NEWLINE# Licensed to Cloudera, Inc. under oneNEWLINE# or more contributor license agreements. See the NOTICE fileNEWLINE# distributed with this work for additional informationNEWLINE# regarding copyright ownership. Cloudera, Inc. licenses this fileNEWLINE# to you under the Apache License, Version 2.0 (theNEWLINE# "License"); you may not use this file except in complianceNEWLINE# with the License. You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINEimport jsonNEWLINEimport sysNEWLINEimport unittestNEWLINENEWLINEfrom django.urls import reverseNEWLINEfrom nose.plugins.skip import SkipTestNEWLINEfrom nose.tools import assert_equal, assert_true, assert_falseNEWLINENEWLINEfrom desktop.auth.backend import rewrite_user, is_adminNEWLINEfrom desktop.conf import ENABLE_CONNECTORS, ENABLE_ORGANIZATIONSNEWLINEfrom desktop.lib.connectors.api import _get_installed_connectorsNEWLINEfrom desktop.lib.django_test_util import make_logged_in_clientNEWLINENEWLINEfrom useradmin.models import User, update_app_permissions, get_default_user_group, ConnectorNEWLINEfrom useradmin.permissions import HuePermission, GroupPermissionNEWLINENEWLINEif sys.version_info[0] > 2:NEWLINE from unittest.mock import patch, MockNEWLINEelse:NEWLINE from mock import patch, MockNEWLINENEWLINENEWLINEclass TestApi(object):NEWLINENEWLINE def setUp(self):NEWLINE self.client = make_logged_in_client(username="admin_test_connector", recreate=True, is_superuser=False, is_admin=True)NEWLINE self.user = User.objects.get(username="admin_test_connector")NEWLINENEWLINE @classmethodNEWLINE def setUpClass(cls):NEWLINE cls._class_resets = [NEWLINE ENABLE_CONNECTORS.set_for_testing(True),NEWLINE ]NEWLINENEWLINE @classmethodNEWLINE def tearDownClass(cls):NEWLINE for reset in cls._class_resets:NEWLINE reset()NEWLINENEWLINENEWLINE def test_install_connector_examples(self):NEWLINENEWLINE with patch('desktop.lib.connectors.api._create_connector_examples') as _create_connector_examples:NEWLINE with patch('desktop.lib.connectors.api.update_app_permissions') as update_app_permissions:NEWLINE _create_connector_examples.return_value = ['Connector 1'], ['Connector 2']NEWLINENEWLINE response = self.client.post(NEWLINE reverse('connectors.api.install_connector_examples')NEWLINE )NEWLINE data = json.loads(response.content)NEWLINENEWLINE assert_equal(200, response.status_code)NEWLINE assert_equal(NEWLINE 'Added connectors: Connector 1. 'NEWLINE 'Already installed connectors: Connector 2',NEWLINE data['message'],NEWLINE dataNEWLINE )NEWLINE #!/usr/bin/pythonNEWLINE# -*- coding: utf-8 -*-NEWLINE#NEWLINE# Copyright: (c) 2018, F5 Networks Inc.NEWLINE# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)NEWLINENEWLINEfrom __future__ import absolute_import, division, print_functionNEWLINE__metaclass__ = typeNEWLINENEWLINEDOCUMENTATION = r'''NEWLINE---NEWLINEmodule: bigip_gtm_globalNEWLINEshort_description: Manages global GTM settingsNEWLINEdescription:NEWLINE - Manages global BIG-IP GTM (now BIG-IP DNS) settings. These settings include general, load balancing, and metricsNEWLINE related settings.NEWLINEversion_added: "1.0.0"NEWLINEoptions:NEWLINE synchronization:NEWLINE description:NEWLINE - Specifies whether this system is a member of a synchronization group.NEWLINE - When you enable synchronization, the system periodically queries other systems inNEWLINE the synchronization group to obtain and distribute configuration and metrics collectionNEWLINE updates.NEWLINE - The synchronization group may contain systems configured as Global Traffic Manager (DNS) andNEWLINE Link Controller systems.NEWLINE type: boolNEWLINE synchronization_group_name:NEWLINE description:NEWLINE - Specifies the name of the synchronization group to which the system belongs.NEWLINE type: strNEWLINE synchronize_zone_files:NEWLINE description:NEWLINE - Specifies the system synchronizes Domain Name System (DNS) zone files among theNEWLINE synchronization group members.NEWLINE type: boolNEWLINEextends_documentation_fragment: f5networks.f5_modules.f5NEWLINEauthor:NEWLINE - Tim Rupp (@caphrim007)NEWLINE - Wojciech Wypior (@wojtek0806)NEWLINE'''NEWLINENEWLINEEXAMPLES = r'''NEWLINE- name: Configure synchronization settingsNEWLINE bigip_gtm_global:NEWLINE synchronization: yesNEWLINE synchronization_group_name: my-groupNEWLINE synchronize_zone_files: yesNEWLINE state: presentNEWLINE provider:NEWLINE user: adminNEWLINE password: secretNEWLINE server: lb.mydomain.comNEWLINE delegate_to: localhostNEWLINE'''NEWLINENEWLINERETURN = r'''NEWLINEsynchronization:NEWLINE description: The synchronization setting on the system.NEWLINE returned: changedNEWLINE type: boolNEWLINE sample: trueNEWLINEsynchronization_group_name:NEWLINE description: The synchronization group name.NEWLINE returned: changedNEWLINE type: strNEWLINE sample: my-groupNEWLINEsynchronize_zone_files:NEWLINE description: Whether or not the system will synchronize zone files.NEWLINE returned: changedNEWLINE type: strNEWLINE sample: my-groupNEWLINE'''NEWLINEfrom datetime import datetimeNEWLINEfrom ansible.module_utils.basic import AnsibleModuleNEWLINENEWLINEfrom ..module_utils.bigip import F5RestClientNEWLINEfrom ..module_utils.common import (NEWLINE F5ModuleError, AnsibleF5Parameters, f5_argument_specNEWLINE)NEWLINEfrom ..module_utils.icontrol import (NEWLINE module_provisioned, tmos_versionNEWLINE)NEWLINEfrom ..module_utils.teem import send_teemNEWLINENEWLINENEWLINEclass Parameters(AnsibleF5Parameters):NEWLINE api_map = {NEWLINE 'synchronizationGroupName': 'synchronization_group_name',NEWLINE 'synchronizeZoneFiles': 'synchronize_zone_files',NEWLINE }NEWLINENEWLINE api_attributes = [NEWLINE 'synchronizeZoneFiles',NEWLINE 'synchronizationGroupName',NEWLINE 'synchronization',NEWLINE ]NEWLINENEWLINE returnables = [NEWLINE 'synchronization',NEWLINE 'synchronization_group_name',NEWLINE 'synchronize_zone_files',NEWLINE ]NEWLINENEWLINE updatables = [NEWLINE 'synchronization',NEWLINE 'synchronization_group_name',NEWLINE 'synchronize_zone_files',NEWLINE ]NEWLINENEWLINENEWLINEclass ApiParameters(Parameters):NEWLINE @propertyNEWLINE def synchronization(self):NEWLINE if self._values['synchronization'] is None:NEWLINE return NoneNEWLINE elif self._values['synchronization'] == 'no':NEWLINE return FalseNEWLINE else:NEWLINE return TrueNEWLINENEWLINE @propertyNEWLINE def synchronize_zone_files(self):NEWLINE if self._values['synchronize_zone_files'] is None:NEWLINE return NoneNEWLINE elif self._values['synchronize_zone_files'] == 'no':NEWLINE return FalseNEWLINE else:NEWLINE return TrueNEWLINENEWLINE @propertyNEWLINE def synchronization_group_name(self):NEWLINE if self._values['synchronization_group_name'] is None:NEWLINE return NoneNEWLINE return str(self._values['synchronization_group_name'])NEWLINENEWLINENEWLINEclass ModuleParameters(Parameters):NEWLINE passNEWLINENEWLINENEWLINEclass Changes(Parameters):NEWLINE def to_return(self):NEWLINE result = {}NEWLINE try:NEWLINE for returnable in self.returnables:NEWLINE result[returnable] = getattr(self, returnable)NEWLINE result = self._filter_params(result)NEWLINE except Exception:NEWLINE raiseNEWLINE return resultNEWLINENEWLINENEWLINEclass UsableChanges(Changes):NEWLINE @propertyNEWLINE def synchronization(self):NEWLINE if self._values['synchronization'] is None:NEWLINE return NoneNEWLINE elif self._values['synchronization'] is False:NEWLINE return 'no'NEWLINE else:NEWLINE return 'yes'NEWLINENEWLINE @propertyNEWLINE def synchronize_zone_files(self):NEWLINE if self._values['synchronize_zone_files'] is None:NEWLINE return NoneNEWLINE elif self._values['synchronize_zone_files'] is False:NEWLINE return 'no'NEWLINE else:NEWLINE return 'yes'NEWLINENEWLINENEWLINEclass ReportableChanges(Changes):NEWLINE passNEWLINENEWLINENEWLINEclass Difference(object):NEWLINE def __init__(self, want, have=None):NEWLINE self.want = wantNEWLINE self.have = haveNEWLINENEWLINE def compare(self, param):NEWLINE try:NEWLINE result = getattr(self, param)NEWLINE return resultNEWLINE except AttributeError:NEWLINE return self.__default(param)NEWLINENEWLINE def __default(self, param):NEWLINE attr1 = getattr(self.want, param)NEWLINE try:NEWLINE attr2 = getattr(self.have, param)NEWLINE if attr1 != attr2:NEWLINE return attr1NEWLINE except AttributeError:NEWLINE return attr1NEWLINENEWLINE @propertyNEWLINE def synchronization_group_name(self):NEWLINE if self.want.synchronization_group_name is None:NEWLINE return NoneNEWLINE if self.want.synchronization_group_name == '' and self.have.synchronization_group_name is None:NEWLINE return NoneNEWLINE if self.want.synchronization_group_name != self.have.synchronization_group_name:NEWLINE return self.want.synchronization_group_nameNEWLINENEWLINENEWLINEclass ModuleManager(object):NEWLINE def __init__(self, *args, **kwargs):NEWLINE self.module = kwargs.get('module', None)NEWLINE self.client = F5RestClient(**self.module.params)NEWLINE self.want = ModuleParameters(params=self.module.params)NEWLINE self.have = ApiParameters()NEWLINE self.changes = UsableChanges()NEWLINENEWLINE def _update_changed_options(self):NEWLINE diff = Difference(self.want, self.have)NEWLINE updatables = Parameters.updatablesNEWLINE changed = dict()NEWLINE for k in updatables:NEWLINE change = diff.compare(k)NEWLINE if change is None:NEWLINE continueNEWLINE else:NEWLINE if isinstance(change, dict):NEWLINE changed.update(change)NEWLINE else:NEWLINE changed[k] = changeNEWLINE if changed:NEWLINE self.changes = UsableChanges(params=changed)NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINE def _announce_deprecations(self, result):NEWLINE warnings = result.pop('__warnings', [])NEWLINE for warning in warnings:NEWLINE self.client.module.deprecate(NEWLINE msg=warning['msg'],NEWLINE version=warning['version']NEWLINE )NEWLINENEWLINE def exec_module(self):NEWLINE start = datetime.now().isoformat()NEWLINE version = tmos_version(self.client)NEWLINE if not module_provisioned(self.client, 'gtm'):NEWLINE raise F5ModuleError(NEWLINE "GTM must be provisioned to use this module."NEWLINE )NEWLINE result = dict()NEWLINENEWLINE changed = self.present()NEWLINENEWLINE reportable = ReportableChanges(params=self.changes.to_return())NEWLINE changes = reportable.to_return()NEWLINE result.update(**changes)NEWLINE result.update(dict(changed=changed))NEWLINE self._announce_deprecations(result)NEWLINE send_teem(start, self.client, self.module, version)NEWLINE return resultNEWLINENEWLINE def present(self):NEWLINE return self.update()NEWLINENEWLINE def update(self):NEWLINE self.have = self.read_current_from_device()NEWLINE if not self.should_update():NEWLINE return FalseNEWLINE if self.module.check_mode:NEWLINE return TrueNEWLINE self.update_on_device()NEWLINE return TrueNEWLINENEWLINE def should_update(self):NEWLINE result = self._update_changed_options()NEWLINE if result:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINE def update_on_device(self):NEWLINE params = self.changes.api_params()NEWLINE uri = "https://{0}:{1}/mgmt/tm/gtm/global-settings/general/".format(NEWLINE self.client.provider['server'],NEWLINE self.client.provider['server_port'],NEWLINE )NEWLINE resp = self.client.api.patch(uri, json=params)NEWLINE try:NEWLINE response = resp.json()NEWLINE except ValueError as ex:NEWLINE raise F5ModuleError(str(ex))NEWLINENEWLINE if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:NEWLINE return TrueNEWLINE raise F5ModuleError(resp.content)NEWLINENEWLINE def read_current_from_device(self):NEWLINE uri = "https://{0}:{1}/mgmt/tm/gtm/global-settings/general/".format(NEWLINE self.client.provider['server'],NEWLINE self.client.provider['server_port'],NEWLINE )NEWLINE resp = self.client.api.get(uri)NEWLINE try:NEWLINE response = resp.json()NEWLINE except ValueError as ex:NEWLINE raise F5ModuleError(str(ex))NEWLINENEWLINE if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:NEWLINE return ApiParameters(params=response)NEWLINE raise F5ModuleError(resp.content)NEWLINENEWLINENEWLINEclass ArgumentSpec(object):NEWLINE def __init__(self):NEWLINE self.supports_check_mode = TrueNEWLINE argument_spec = dict(NEWLINE synchronization=dict(type='bool'),NEWLINE synchronization_group_name=dict(),NEWLINE synchronize_zone_files=dict(type='bool')NEWLINE )NEWLINE self.argument_spec = {}NEWLINE self.argument_spec.update(f5_argument_spec)NEWLINE self.argument_spec.update(argument_spec)NEWLINENEWLINENEWLINEdef main():NEWLINE spec = ArgumentSpec()NEWLINENEWLINE module = AnsibleModule(NEWLINE argument_spec=spec.argument_spec,NEWLINE supports_check_mode=spec.supports_check_mode,NEWLINE )NEWLINENEWLINE try:NEWLINE mm = ModuleManager(module=module)NEWLINE results = mm.exec_module()NEWLINE module.exit_json(**results)NEWLINE except F5ModuleError as ex:NEWLINE module.fail_json(msg=str(ex))NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE main()NEWLINE # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINEfrom __future__ import print_functionNEWLINEimport copyNEWLINEimport warningsNEWLINEimport paddleNEWLINEimport osNEWLINEimport numpy as npNEWLINEfrom paddle.fluid.framework import dygraph_onlyNEWLINEfrom paddle.fluid import compilerNEWLINEfrom .role_maker import UserDefinedRoleMaker, PaddleCloudRoleMaker, RoleMakerBaseNEWLINEfrom .strategy_compiler import StrategyCompilerNEWLINEfrom .distributed_strategy import DistributedStrategyNEWLINEfrom .meta_optimizer_factory import MetaOptimizerFactoryNEWLINEfrom .runtime_factory import RuntimeFactoryNEWLINEfrom paddle.fluid.wrapped_decorator import wrap_decoratorNEWLINEfrom paddle.fluid.dygraph import parallel_helperNEWLINEfrom . import topology as tpNEWLINEfrom .topology import ParallelModeNEWLINEfrom ..meta_parallel import TensorParallel, model_parallel_random_seedNEWLINEfrom ..meta_parallel import PipelineParallel, ShardingParallelNEWLINEfrom ..meta_optimizers import HybridParallelOptimizerNEWLINEfrom ..meta_optimizers import HybridParallelGradScalerNEWLINENEWLINE__all__ = []NEWLINENEWLINENEWLINEdef _inited_runtime_handler_(func):NEWLINE def __impl__(*args, **kwargs):NEWLINE cls = args[0]NEWLINENEWLINE if cls._runtime_handle is None:NEWLINE raise ValueError("Fleet can not find suitable runtime handler")NEWLINENEWLINE return func(*args, **kwargs)NEWLINENEWLINE return __impl__NEWLINENEWLINENEWLINEdef _is_non_distributed_check_(func):NEWLINE def __impl__(*args, **kwargs):NEWLINE cls = args[0]NEWLINENEWLINE if cls._role_maker is not None and cls._role_maker._is_non_distributed(NEWLINE ) is True:NEWLINE warnings.warn(NEWLINE "%s() function doesn't work when use non_distributed fleet." %NEWLINE (func.__name__))NEWLINE returnNEWLINENEWLINE return func(*args, **kwargs)NEWLINENEWLINE return __impl__NEWLINENEWLINENEWLINEinited_runtime_handler = wrap_decorator(_inited_runtime_handler_)NEWLINEis_non_distributed_check = wrap_decorator(_is_non_distributed_check_)NEWLINENEWLINENEWLINEclass Fleet(object):NEWLINE """NEWLINE Unified API for distributed training of PaddlePaddleNEWLINE Please reference the https://github.com/PaddlePaddle/FleetX for detailsNEWLINENEWLINENEWLINE Returns:NEWLINE Fleet: A Fleet instanceNEWLINENEWLINE Example for collective training:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddleNEWLINE paddle.enable_static()NEWLINE import paddle.distributed.fleet as fleetNEWLINENEWLINE fleet.init(is_collective=True)NEWLINENEWLINE strategy = fleet.DistributedStrategy()NEWLINE optimizer = paddle.optimizer.SGD(learning_rate=0.001)NEWLINE optimizer = fleet.distributed_optimizer(optimizer, strategy=strategy)NEWLINENEWLINE # do distributed trainingNEWLINENEWLINENEWLINE Example for parameter server training:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddleNEWLINE paddle.enable_static()NEWLINE import paddle.distributed.fleet as fleetNEWLINE strategy = fleet.DistributedStrategy()NEWLINE fleet.init(strategy=strategy)NEWLINENEWLINE optimizer = paddle.optimizer.SGD(learning_rate=0.001)NEWLINE optimizer = fleet.distributed_optimizer(optimizer)NEWLINENEWLINE if fleet.is_first_worker():NEWLINE print("this is first worker")NEWLINENEWLINE print("current node index: {}".format(fleet.worker_index()))NEWLINE print("total number of worker num: {}".format(fleet.worker_num()))NEWLINENEWLINE if fleet.is_worker():NEWLINE print("this is worker")NEWLINE print("worker endpoints: {}".format(fleet.worker_endpoints(to_string=True)))NEWLINENEWLINE print("server num: {}".format(fleet.server_num()))NEWLINE print("server endpoints: {}".format(fleet.server_endpoints(to_string=True)))NEWLINENEWLINE if fleet.is_server():NEWLINE print("this is server")NEWLINE fleet.stop_worker()NEWLINENEWLINENEWLINE """NEWLINENEWLINE def __init__(self):NEWLINE self._role_maker = NoneNEWLINE self.strategy_compiler = NoneNEWLINE self._is_collective = FalseNEWLINE self._runtime_handle = NoneNEWLINE self._util = NoneNEWLINE self._context = {}NEWLINENEWLINE def init(self, role_maker=None, is_collective=False, strategy=None):NEWLINE """NEWLINE Initialize role_maker in Fleet.NEWLINENEWLINE This function is responsible for the distributed architectureNEWLINE what you want to run your code behind.NEWLINENEWLINE Args:NEWLINE role_maker (RoleMakerBase, optional): A ``RoleMakerBase`` containing the configurationNEWLINE of environment variables related to distributed training.If you did not initialize NEWLINE the rolemaker by yourself, it will be automatically initialized to PaddleRoleMaker.NEWLINE The default value is None.NEWLINE is_collective (Boolean, optional): A ``Boolean`` variable determines whether the program NEWLINE runs on the CPU or GPU. False means set distributed training using CPU, and True meansNEWLINE GPU.The default value is False.The default value is False.NEWLINE strategy (DistributedStrategy): Extra properties for distributed training. NEWLINE For details, please refer to paddle.distributed.fleet.DistributedStrategy. Default: None.NEWLINENEWLINENEWLINE Returns:NEWLINE NoneNEWLINENEWLINE Examples1:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINENEWLINE Examples2:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init(is_collective=True)NEWLINENEWLINE Examples3:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE role = fleet.PaddleCloudRoleMaker()NEWLINE fleet.init(role)NEWLINENEWLINE Examples4:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE strategy = fleet.DistributedStrategy()NEWLINE fleet.init(strategy=strategy)NEWLINENEWLINE """NEWLINE if strategy is None:NEWLINE strategy = DistributedStrategy()NEWLINE self._user_defined_strategy = copy.deepcopy(strategy)NEWLINENEWLINE if role_maker is None:NEWLINE if isinstance(is_collective, bool):NEWLINE self._is_collective = is_collectiveNEWLINE self._role_maker = PaddleCloudRoleMaker(NEWLINE is_collective=self._is_collective)NEWLINE else:NEWLINE raise ValueError(NEWLINE "`is_collective` should be instance of `bool`, but got {}".NEWLINE format(type(is_collective)))NEWLINE else:NEWLINE if isinstance(role_maker, RoleMakerBase):NEWLINE self._role_maker = role_makerNEWLINE self._is_collective = role_maker._is_collectiveNEWLINE else:NEWLINE raise ValueError(NEWLINE "`role_maker` should be subclass of `RoleMakerBase`, but got {}".NEWLINE format(type(role_maker)))NEWLINE self._role_maker._generate_role()NEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.util._set_role_maker(self._role_maker)NEWLINENEWLINE self.strategy_compiler = StrategyCompiler()NEWLINENEWLINE if self._role_maker._is_non_distributed() and self._is_collective:NEWLINE if paddle.fluid.core.is_compiled_with_cuda():NEWLINE gpus_num = paddle.fluid.core.get_cuda_device_count()NEWLINE if gpus_num != 1:NEWLINE raise ValueError(NEWLINE "CUDA_VISIBLE_DEVICES shoule be set only 1 card if you use `python` to launch fleet program."NEWLINE )NEWLINENEWLINE if paddle.fluid.framework.in_dygraph_mode():NEWLINE if self.worker_num() == 1:NEWLINE # if worker_num is 1, should construct default topology & hcgNEWLINE self._topology = tp.CommunicateTopology()NEWLINE self._hcg = tp.HybridCommunicateGroup(self._topology)NEWLINE returnNEWLINE if parallel_helper._is_parallel_ctx_initialized():NEWLINE warnings.warn(NEWLINE "The dygraph parallel environment has been initialized.")NEWLINE else:NEWLINE # FLAGS_nccl_nrings is used for dynamic graph multi-stream communicationNEWLINE if "FLAGS_nccl_nrings" in os.environ:NEWLINE warnings.warn(NEWLINE "You have set the environment variable FLAGS_nccl_nrings "NEWLINE "outside the program, so the nccl_comm_num in "NEWLINE "DistributedStrategy will not take effect here.")NEWLINE else:NEWLINE os.environ["FLAGS_nccl_nrings"] = str(NEWLINE self._user_defined_strategy.nccl_comm_num)NEWLINE paddle.distributed.init_parallel_env()NEWLINENEWLINE # init hybrid parallel environment in dygraphNEWLINE if tp._HYBRID_PARALLEL_GROUP is None:NEWLINE self._init_hybrid_parallel_env()NEWLINE else:NEWLINE warnings.warn(NEWLINE "The dygraph hybrid parallel environment has been initialized."NEWLINE )NEWLINE elif self._is_collective:NEWLINE use_sharding = self._user_defined_strategy.shardingNEWLINENEWLINE # global groupNEWLINE global_rank = self.worker_index()NEWLINE global_world_size = self.worker_num()NEWLINE # NOTE(wangxi): see sharding_optimizerNEWLINE global_ring_id = 3 if use_sharding else 0NEWLINE global_ranks = list(range(global_world_size))NEWLINENEWLINE if tp._HYBRID_PARALLEL_GROUP is None: tp._CommunicateGroup()NEWLINE cg = tp._HYBRID_PARALLEL_GROUPNEWLINE self._hcg = cgNEWLINE cg.set_comm_group('global', global_rank, global_world_size,NEWLINE global_ring_id, global_ranks)NEWLINENEWLINE use_tensor_parallel = self._user_defined_strategy.tensor_parallelNEWLINE use_mp = use_sharding or use_tensor_parallelNEWLINENEWLINE # hybrid groupNEWLINE if use_mp is False: returnNEWLINENEWLINE mp_degree_sharding = 1NEWLINE mp_degree_tensor_parallel = 1NEWLINE if use_sharding:NEWLINE sharding_configs = self._user_defined_strategy.sharding_configsNEWLINE mp_degree_sharding = int(sharding_configs['mp_degree'])NEWLINENEWLINE if use_tensor_parallel:NEWLINE tensor_parallel_configs = self._user_defined_strategy.tensor_parallel_configsNEWLINE mp_degree_tensor_parallel = int(tensor_parallel_configs[NEWLINE 'tensor_parallel_degree'])NEWLINENEWLINE if use_sharding and use_tensor_parallel:NEWLINE assert mp_degree_sharding == mp_degree_tensor_parallelNEWLINENEWLINE mp_degree = mp_degree_sharding if use_sharding else mp_degree_tensor_parallelNEWLINENEWLINE if mp_degree > 1:NEWLINE assert global_world_size % mp_degree == 0NEWLINE # NOTE(wangxi): mp_ring_id sync with sharding_optimizer.py _build_groupsNEWLINE mp_ring_id = 0NEWLINE mp_rank = global_rank % mp_degreeNEWLINE mp_group_id = global_rank // mp_degreeNEWLINE mp_group_ranks = [NEWLINE idx for idx in global_ranksNEWLINE if idx // mp_degree == mp_group_idNEWLINE ]NEWLINE cg.set_comm_group('model', mp_rank, mp_degree, mp_ring_id,NEWLINE mp_group_ranks)NEWLINENEWLINE def _init_hybrid_parallel_env(self):NEWLINE """initialize the hybrid environmentNEWLINE """NEWLINE self.hybrid_configs = self._user_defined_strategy.hybrid_configsNEWLINE self.dp_degree = self.hybrid_configs["dp_degree"]NEWLINE self.mp_degree = self.hybrid_configs["mp_degree"]NEWLINE self.pp_degree = self.hybrid_configs["pp_degree"]NEWLINE self.sharding_degree = self.hybrid_configs["sharding_degree"]NEWLINENEWLINE assert self.mp_degree >= 0, "mp_degree should be greater or equal to 0"NEWLINE assert self.pp_degree >= 0, "pp_degree should be greater or equal to 0"NEWLINE assert self.sharding_degree >= 0, "sharding_degree should be greater or equal to 0"NEWLINENEWLINE self.mp_degree = max(self.mp_degree, 1)NEWLINE self.pp_degree = max(self.pp_degree, 1)NEWLINENEWLINE if self.dp_degree < 0:NEWLINE nranks = paddle.distributed.get_world_size()NEWLINE self.dp_degree = nranks // (self.mp_degree * self.pp_degree)NEWLINENEWLINE self.dp_degree = max(self.dp_degree, 1)NEWLINENEWLINE self._topology = tp.CommunicateTopology(NEWLINE hybrid_group_names=["data", "pipe", "sharding", "model"],NEWLINE dims=[NEWLINE self.dp_degree, self.pp_degree, self.sharding_degree,NEWLINE self.mp_degreeNEWLINE ])NEWLINENEWLINE self._hcg = tp.HybridCommunicateGroup(self._topology)NEWLINENEWLINE if self.mp_degree > 1:NEWLINE tensor_parallel_configs = self._user_defined_strategy.tensor_parallel_configsNEWLINE tensor_init_seed = tensor_parallel_configs["tensor_init_seed"]NEWLINE if tensor_init_seed == -1:NEWLINE model_parallel_random_seed()NEWLINE else:NEWLINE model_parallel_random_seed(tensor_init_seed)NEWLINENEWLINE def get_hybrid_communicate_group(self):NEWLINE assert self._hcg is not NoneNEWLINE return self._hcgNEWLINENEWLINE def get_hybrid_parallel_topology(self):NEWLINE assert self._topology is not NoneNEWLINE return self._topologyNEWLINENEWLINE def is_first_worker(self):NEWLINE """NEWLINE Check whether the node is the first instance of worker.NEWLINENEWLINE Returns:NEWLINE bool: True if this is the first node of worker,NEWLINE False if not.NEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINE fleet.is_first_worker()NEWLINENEWLINE """NEWLINE return self._role_maker._is_first_worker()NEWLINENEWLINE def worker_index(self):NEWLINE """NEWLINE Get current worker index.NEWLINENEWLINE Returns:NEWLINE int: node idNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINE fleet.worker_index()NEWLINENEWLINE """NEWLINE return self._role_maker._worker_index()NEWLINENEWLINE def worker_num(self):NEWLINE """NEWLINE Get current total worker number.NEWLINENEWLINE Returns:NEWLINE int: worker numbersNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINE fleet.worker_num()NEWLINENEWLINE """NEWLINE return self._role_maker._worker_num()NEWLINENEWLINE def node_num(self):NEWLINE return self._role_maker._get_node_num()NEWLINENEWLINE def local_rank(self):NEWLINE return self._role_maker._get_local_rank()NEWLINENEWLINE def local_device_ids(self):NEWLINE return self._role_maker._get_local_device_ids()NEWLINENEWLINE def world_device_ids(self):NEWLINE return self._role_maker._get_world_device_ids()NEWLINENEWLINE def is_worker(self):NEWLINE """NEWLINE Check whether the node is an instance of worker.NEWLINENEWLINE Returns:NEWLINE bool: True if this is a node of worker,NEWLINE False if not.NEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINE fleet.is_worker()NEWLINENEWLINE """NEWLINE return self._role_maker._is_worker()NEWLINENEWLINE def worker_endpoints(self, to_string=False):NEWLINE """NEWLINE Get current worker endpoints, such as ["127.0.0.1:1001", "127.0.0.1:1002"].NEWLINENEWLINE Returns:NEWLINE list/string: server endpointsNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINE fleet.worker_endpoints()NEWLINENEWLINE """NEWLINE if to_string:NEWLINE return ",".join(self._role_maker._get_trainer_endpoints())NEWLINE else:NEWLINE return self._role_maker._get_trainer_endpoints()NEWLINENEWLINE def server_num(self):NEWLINE """NEWLINE Get current total worker number.NEWLINENEWLINE Returns:NEWLINE int: server numberNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINE fleet.server_num()NEWLINE """NEWLINE return len(self._role_maker._get_pserver_endpoints())NEWLINENEWLINE def server_index(self):NEWLINE """NEWLINE Get current server index.NEWLINENEWLINE Returns:NEWLINE int: node idNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINE fleet.server_index()NEWLINENEWLINE """NEWLINE return self._role_maker._server_index()NEWLINENEWLINE def server_endpoints(self, to_string=False):NEWLINE """NEWLINE Get current server endpoints, such as ["127.0.0.1:1001", "127.0.0.1:1002"].NEWLINENEWLINE Returns:NEWLINE list/string: server endpointsNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINE fleet.server_endpoints()NEWLINENEWLINE """NEWLINENEWLINE if to_string:NEWLINE return ",".join(self._role_maker._get_pserver_endpoints())NEWLINE else:NEWLINE return self._role_maker._get_pserver_endpoints()NEWLINENEWLINE def is_server(self):NEWLINE """NEWLINE Check whether the node is an instance of server.NEWLINENEWLINE Returns:NEWLINE bool: True if this is a node of server,NEWLINE False if not.NEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINE fleet.is_server()NEWLINENEWLINE """NEWLINE return self._role_maker._is_server(NEWLINE ) or self._role_maker._is_heter_worker()NEWLINENEWLINE def barrier_worker(self):NEWLINE """NEWLINE barrier all workersNEWLINENEWLINE Returns:NEWLINE NoneNEWLINE """NEWLINE self._role_maker._barrier("worker")NEWLINENEWLINE @is_non_distributed_checkNEWLINE @inited_runtime_handlerNEWLINE def init_worker(self):NEWLINE """NEWLINE initialize `Communicator` for parameter server training.NEWLINENEWLINENEWLINE Returns:NEWLINE NoneNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINENEWLINE # build netNEWLINE # fleet.distributed_optimizer(...)NEWLINENEWLINE fleet.init_worker()NEWLINENEWLINE """NEWLINE self._runtime_handle._init_worker()NEWLINENEWLINE @is_non_distributed_checkNEWLINE @inited_runtime_handlerNEWLINE def init_server(self, *args, **kwargs):NEWLINE """NEWLINE init_server executor to initialize startup program,NEWLINE if the `args` is not empty, it will run load_persistables for increment training.NEWLINENEWLINENEWLINE Returns:NEWLINE NoneNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINENEWLINE # build netNEWLINE # fleet.distributed_optimizer(...)NEWLINENEWLINE fleet.init_server()NEWLINENEWLINE """NEWLINE self._runtime_handle._init_server(*args, **kwargs)NEWLINENEWLINE def load_model(self, path, mode):NEWLINE """NEWLINE load fleet model from pathNEWLINENEWLINENEWLINE Returns:NEWLINE NoneNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINENEWLINE # build netNEWLINE # fleet.distributed_optimizer(...)NEWLINENEWLINE fleet.load_model("path", "mode")NEWLINENEWLINE """NEWLINE self._runtime_handle.load_model(path, mode)NEWLINENEWLINE @is_non_distributed_checkNEWLINE @inited_runtime_handlerNEWLINE def run_server(self):NEWLINE """NEWLINE run server will run pserver main program with executor.NEWLINENEWLINE Returns:NEWLINE NoneNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINENEWLINE # build netNEWLINE # fleet.distributed_optimizer(...)NEWLINENEWLINE if fleet.is_server():NEWLINE fleet.init_server()NEWLINENEWLINE """NEWLINE self._runtime_handle._run_server()NEWLINENEWLINE @is_non_distributed_checkNEWLINE @inited_runtime_handlerNEWLINE def stop_worker(self):NEWLINE """NEWLINE stop `Communicator` and give training complete notice to parameter server.NEWLINENEWLINE Returns:NEWLINE NoneNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINENEWLINE # build netNEWLINE # fleet.distributed_optimizer(...)NEWLINENEWLINE fleet.init_server()NEWLINENEWLINE """NEWLINE self._runtime_handle._stop_worker()NEWLINENEWLINE def save(self, dirname, feed=[], fetch=[], **configs):NEWLINE inference = TrueNEWLINENEWLINE if not feed and not fetch:NEWLINE inference = FalseNEWLINENEWLINE place = paddle.CPUPlace()NEWLINE executor = paddle.static.Executor(place)NEWLINENEWLINE if inference:NEWLINE feeded_var_names = []NEWLINE fetch_var_names = []NEWLINENEWLINE for var in feed:NEWLINE if isinstance(var, str):NEWLINE feeded_var_names.append(var)NEWLINE elif isinstance(var, paddle.static.Variable):NEWLINE feeded_var_names.append(var.name)NEWLINE else:NEWLINE raise ValueError("feed must be [str|Variable]")NEWLINENEWLINE for var in fetch:NEWLINE if isinstance(var, str):NEWLINE fetch_var_names.append(var)NEWLINE elif isinstance(var, paddle.static.Variable):NEWLINE fetch_var_names.append(var.name)NEWLINE else:NEWLINE raise ValueError("feed must be [str|Variable]")NEWLINENEWLINE fetch_vars = [NEWLINE paddle.static.default_main_program().global_block().var(name)NEWLINE for name in fetch_var_namesNEWLINE ]NEWLINENEWLINE self._runtime_handle._save_inference_model(NEWLINE executor, dirname, feeded_var_names, fetch_vars, None, True, 0)NEWLINE else:NEWLINE increment_mode = 0NEWLINE if "mode" in configs:NEWLINE increment_mode = int(configs["mode"])NEWLINE self._runtime_handle._save_persistables(NEWLINE executor, dirname, main_program=None, mode=increment_mode)NEWLINENEWLINE def save_inference_model(self,NEWLINE executor,NEWLINE dirname,NEWLINE feeded_var_names,NEWLINE target_vars,NEWLINE main_program=None,NEWLINE export_for_deployment=True,NEWLINE mode=0):NEWLINE """NEWLINE save inference model for inference.NEWLINENEWLINE Returns:NEWLINE NoneNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init()NEWLINENEWLINE # build netNEWLINE # fleet.distributed_optimizer(...)NEWLINENEWLINE fleet.init_server()NEWLINENEWLINE """NEWLINE # warnings.warn(NEWLINE # "'save_inference_model' is a deprecated, will be deleted after v2.2.0, Please use fleet.save instead."NEWLINE # )NEWLINENEWLINE self._runtime_handle._save_inference_model(NEWLINE executor, dirname, feeded_var_names, target_vars, main_program,NEWLINE export_for_deployment, mode)NEWLINENEWLINE def save_persistables(self, executor, dirname, main_program=None, mode=0):NEWLINE """NEWLINENEWLINE saves all persistable tensors from :code:`main_program` toNEWLINE the folder :code:`dirname`. You can refer toNEWLINENEWLINE The :code:`dirname` is used to specify the folder where persistable tensorsNEWLINE are going to be saved. If you would like to save tensors in separateNEWLINE files, set :code:`filename` None.NEWLINENEWLINE Args:NEWLINE executor(Executor): The executor to run for saving persistable tensors.NEWLINE You can refer to :ref:`api_guide_executor_en` forNEWLINE more details.NEWLINENEWLINE dirname(str, optional): The saving directory path.NEWLINE When you need to save the parameter to the memory, set it to None.NEWLINE main_program(Program, optional): The program whose persistbale tensors willNEWLINE be saved. Default: None.NEWLINENEWLINENEWLINE Returns:NEWLINE NoneNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: textNEWLINENEWLINE import paddleNEWLINE paddle.enable_static()NEWLINE import paddle.distributed.fleet as fleetNEWLINENEWLINE fleet.init()NEWLINENEWLINE # build netNEWLINE # fleet.distributed_optimizer(...)NEWLINENEWLINE exe = paddle.static.Executor(paddle.CPUPlace())NEWLINE fleet.save_persistables(exe, "dirname", paddle.static.default_main_program())NEWLINENEWLINE """NEWLINE # warnings.warn(NEWLINE # "'save_persistables' is a deprecated, will be deleted after v2.2.0, Please use fleet.save instead."NEWLINE # )NEWLINENEWLINE self._runtime_handle._save_persistables(executor, dirname, main_program,NEWLINE mode)NEWLINENEWLINE def shrink(self, threshold):NEWLINE self._runtime_handle._shrink(threshold)NEWLINENEWLINE def distributed_optimizer(self, optimizer, strategy=None):NEWLINE """NEWLINE Optimizer for distributed training.NEWLINENEWLINE For the distributed training, this method would rebuild a new instance of DistributedOptimizer.NEWLINE Which has basic Optimizer function and special features for distributed training.NEWLINENEWLINE Args:NEWLINE optimizer(Optimizer): The executor to run for init server.NEWLINE strategy(DistributedStrategy): Extra properties for distributed optimizer. NEWLINE It is recommended to use DistributedStrategy in fleet.init(). The strategyNEWLINE here is for compatibility. If the strategy in fleet.distributed_optimizer() NEWLINE is not None, then it will overwrite the DistributedStrategy in fleet.init(), NEWLINE which will take effect in distributed training.NEWLINENEWLINE Returns:NEWLINE Fleet: instance of fleet.NEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddleNEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.init(is_collective=True)NEWLINE strategy = fleet.DistributedStrategy()NEWLINE optimizer = paddle.optimizer.SGD(learning_rate=0.001)NEWLINE optimizer = fleet.distributed_optimizer(optimizer, strategy=strategy)NEWLINENEWLINE """NEWLINE self.user_defined_optimizer = optimizerNEWLINENEWLINE if strategy is not None:NEWLINE if self._is_collective:NEWLINE warnings.warn(NEWLINE "It is recommended to use DistributedStrategy "NEWLINE "in fleet.init(). The strategy here is only for compatibility. "NEWLINE "If the strategy in fleet.distributed_optimizer() is "NEWLINE "not None, then it will overwrite the DistributedStrategy in fleet.init(), "NEWLINE "which will take effect in distributed training.")NEWLINE self._user_defined_strategy = copy.deepcopy(strategy)NEWLINENEWLINE self._context = {}NEWLINENEWLINE if paddle.fluid.framework.in_dygraph_mode():NEWLINE if self.worker_num() > 1:NEWLINE return HybridParallelOptimizer(optimizer, self._hcg,NEWLINE self._user_defined_strategy)NEWLINE else:NEWLINE return optimizerNEWLINE return selfNEWLINENEWLINE @dygraph_onlyNEWLINE def distributed_model(self, model):NEWLINE """NEWLINE Return distributed data parallel model (Only work in dygraph mode)NEWLINENEWLINE Args:NEWLINE model (Layer): the user-defind model which inherits Layer.NEWLINENEWLINE Returns:NEWLINE distributed data parallel model which inherits Layer.NEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddleNEWLINE import paddle.nn as nnNEWLINE from paddle.distributed import fleetNEWLINENEWLINE class LinearNet(nn.Layer):NEWLINE def __init__(self):NEWLINE super(LinearNet, self).__init__()NEWLINE self._linear1 = nn.Linear(10, 10)NEWLINE self._linear2 = nn.Linear(10, 1)NEWLINENEWLINE def forward(self, x):NEWLINE return self._linear2(self._linear1(x))NEWLINENEWLINE # 1. initialize fleet environmentNEWLINE fleet.init(is_collective=True)NEWLINENEWLINE # 2. create layer & optimizerNEWLINE layer = LinearNet()NEWLINE loss_fn = nn.MSELoss()NEWLINE adam = paddle.optimizer.Adam(NEWLINE learning_rate=0.001, parameters=layer.parameters())NEWLINENEWLINE # 3. get data_parallel model using fleetNEWLINE adam = fleet.distributed_optimizer(adam)NEWLINE dp_layer = fleet.distributed_model(layer)NEWLINENEWLINE # 4. run layerNEWLINE inputs = paddle.randn([10, 10], 'float32')NEWLINE outputs = dp_layer(inputs)NEWLINE labels = paddle.randn([10, 1], 'float32')NEWLINE loss = loss_fn(outputs, labels)NEWLINENEWLINE print("loss:", loss.numpy())NEWLINENEWLINE loss.backward()NEWLINENEWLINE adam.step()NEWLINE adam.clear_grad()NEWLINENEWLINENEWLINE """NEWLINE assert model is not None, "model should not be None"NEWLINE if self.worker_num() <= 1:NEWLINE return modelNEWLINENEWLINE if self._hcg.get_parallel_mode() == ParallelMode.SHARDING_PARALLEL:NEWLINE distributed_model = ShardingParallel(NEWLINE model, self._hcg, strategy=self._user_defined_strategy)NEWLINE elif self._hcg.get_parallel_mode() == ParallelMode.DATA_PARALLEL:NEWLINE distributed_model = paddle.DataParallel(NEWLINE model,NEWLINE comm_buffer_size=self._user_defined_strategy.NEWLINE fuse_grad_size_in_MB,NEWLINE last_comm_buffer_size=self._user_defined_strategy.NEWLINE last_comm_group_size_MB,NEWLINE find_unused_parameters=self._user_defined_strategy.NEWLINE find_unused_parameters)NEWLINE elif self._hcg.get_parallel_mode() == ParallelMode.TENSOR_PARALLEL:NEWLINE distributed_model = TensorParallel(NEWLINE model, self._hcg, strategy=self._user_defined_strategy)NEWLINE elif self._hcg.get_parallel_mode() == ParallelMode.PIPELINE_PARALLEL:NEWLINE distributed_model = PipelineParallel(NEWLINE model, self._hcg, strategy=self._user_defined_strategy)NEWLINENEWLINE return distributed_modelNEWLINENEWLINE @dygraph_onlyNEWLINE def state_dict(self):NEWLINE """NEWLINE Get state dict information from optimizer.NEWLINE (Only work in dygraph mode)NEWLINENEWLINE Returns: NEWLINE state_dict(dict) : dict contains all the Tensor used by optimizerNEWLINENEWLINE Examples:NEWLINE .. code-block:: pythonNEWLINENEWLINE import numpy as npNEWLINE import paddleNEWLINE from paddle.distributed import fleetNEWLINENEWLINE fleet.init(is_collective=True)NEWLINENEWLINE value = np.arange(26).reshape(2, 13).astype("float32")NEWLINE a = paddle.to_tensor(value)NEWLINENEWLINE layer = paddle.nn.Linear(13, 5)NEWLINE adam = paddle.optimizer.Adam(learning_rate=0.01, parameters=layer.parameters())NEWLINENEWLINE adam = fleet.distributed_optimizer(adam)NEWLINE dp_layer = fleet.distributed_model(layer)NEWLINE state_dict = adam.state_dict()NEWLINE """NEWLINE # imitate target optimizer retrievalNEWLINE return self.user_defined_optimizer.state_dict()NEWLINENEWLINE @dygraph_onlyNEWLINE def set_state_dict(self, state_dict):NEWLINE """NEWLINE Load optimizer state dict.NEWLINE (Only work in dygraph mode)NEWLINENEWLINE Args: NEWLINE state_dict(dict) : Dict contains all the Tensor needed by optimizerNEWLINENEWLINE Returns:NEWLINE NoneNEWLINENEWLINE Examples:NEWLINE .. code-block:: pythonNEWLINENEWLINE import numpy as npNEWLINE import paddleNEWLINE from paddle.distributed import fleetNEWLINENEWLINE fleet.init(is_collective=True)NEWLINENEWLINE value = np.arange(26).reshape(2, 13).astype("float32")NEWLINE a = paddle.to_tensor(value)NEWLINENEWLINE layer = paddle.nn.Linear(13, 5)NEWLINE adam = paddle.optimizer.Adam(learning_rate=0.01, parameters=layer.parameters())NEWLINENEWLINE adam = fleet.distributed_optimizer(adam)NEWLINE dp_layer = fleet.distributed_model(layer)NEWLINE state_dict = adam.state_dict()NEWLINE paddle.save(state_dict, "paddle_dy")NEWLINE para_state_dict = paddle.load("paddle_dy")NEWLINE adam.set_state_dict(para_state_dict)NEWLINE """NEWLINE # imitate target optimizer retrievalNEWLINE return self.user_defined_optimizer.set_state_dict(state_dict)NEWLINENEWLINE @dygraph_onlyNEWLINE def set_lr(self, value):NEWLINE """NEWLINE Set the value of the learning rate manually in the optimizer. NEWLINE (Only work in dygraph mode)NEWLINENEWLINE Args:NEWLINE value (float|Tensor): the value of learning rateNEWLINENEWLINE Returns: NEWLINE None NEWLINENEWLINE Examples:NEWLINE .. code-block:: pythonNEWLINENEWLINE import numpy as npNEWLINE import paddleNEWLINE from paddle.distributed import fleetNEWLINENEWLINE fleet.init(is_collective=True)NEWLINENEWLINE value = np.arange(26).reshape(2, 13).astype("float32")NEWLINE a = paddle.to_tensor(value)NEWLINENEWLINE layer = paddle.nn.Linear(13, 5)NEWLINE adam = paddle.optimizer.Adam(learning_rate=0.01, parameters=layer.parameters())NEWLINENEWLINE adam = fleet.distributed_optimizer(adam)NEWLINE dp_layer = fleet.distributed_model(layer)NEWLINENEWLINE lr_list = [0.2, 0.3, 0.4, 0.5, 0.6]NEWLINE for i in range(5):NEWLINE adam.set_lr(lr_list[i])NEWLINE lr = adam.get_lr()NEWLINE print("current lr is {}".format(lr))NEWLINE # Print:NEWLINE # current lr is 0.2NEWLINE # current lr is 0.3NEWLINE # current lr is 0.4NEWLINE # current lr is 0.5NEWLINE # current lr is 0.6NEWLINE """NEWLINE # imitate target optimizer retrievalNEWLINE return self.user_defined_optimizer.set_lr(value)NEWLINENEWLINE @dygraph_onlyNEWLINE def get_lr(self):NEWLINE """NEWLINE Get current step learning rate.NEWLINE (Only work in dygraph mode)NEWLINENEWLINE Returns:NEWLINE float: The learning rate of the current step.NEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import numpy as npNEWLINE import paddleNEWLINE from paddle.distributed import fleetNEWLINENEWLINE fleet.init(is_collective=True)NEWLINENEWLINE value = np.arange(26).reshape(2, 13).astype("float32")NEWLINE a = paddle.to_tensor(value)NEWLINENEWLINE layer = paddle.nn.Linear(13, 5)NEWLINE adam = paddle.optimizer.Adam(learning_rate=0.01, parameters=layer.parameters())NEWLINENEWLINE adam = fleet.distributed_optimizer(adam)NEWLINE dp_layer = fleet.distributed_model(layer)NEWLINENEWLINE lr = adam.get_lr()NEWLINE print(lr) # 0.01NEWLINE """NEWLINE # imitate target optimizer retrievalNEWLINE return self.user_defined_optimizer.get_lr()NEWLINENEWLINE @dygraph_onlyNEWLINE def step(self):NEWLINE """NEWLINE Execute the optimizer once.NEWLINE (Only work in dygraph mode)NEWLINENEWLINE Returns:NEWLINE NoneNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddleNEWLINE import paddle.nn as nnNEWLINE from paddle.distributed import fleetNEWLINENEWLINE class LinearNet(nn.Layer):NEWLINE def __init__(self):NEWLINE super(LinearNet, self).__init__()NEWLINE self._linear1 = nn.Linear(10, 10)NEWLINE self._linear2 = nn.Linear(10, 1)NEWLINENEWLINE def forward(self, x):NEWLINE return self._linear2(self._linear1(x))NEWLINENEWLINE # 1. initialize fleet environmentNEWLINE fleet.init(is_collective=True)NEWLINENEWLINE # 2. create layer & optimizerNEWLINE layer = LinearNet()NEWLINE loss_fn = nn.MSELoss()NEWLINE adam = paddle.optimizer.Adam(NEWLINE learning_rate=0.001, parameters=layer.parameters())NEWLINENEWLINE # 3. get data_parallel model using fleetNEWLINE adam = fleet.distributed_optimizer(adam)NEWLINE dp_layer = fleet.distributed_model(layer)NEWLINENEWLINE # 4. run layerNEWLINE inputs = paddle.randn([10, 10], 'float32')NEWLINE outputs = dp_layer(inputs)NEWLINE labels = paddle.randn([10, 1], 'float32')NEWLINE loss = loss_fn(outputs, labels)NEWLINENEWLINE print("loss:", loss.numpy())NEWLINENEWLINE loss.backward()NEWLINENEWLINE adam.step()NEWLINE adam.clear_grad()NEWLINENEWLINENEWLINE """NEWLINE # imitate target optimizer retrievalNEWLINE return self.user_defined_optimizer.step()NEWLINENEWLINE @dygraph_onlyNEWLINE def clear_grad(self):NEWLINE """NEWLINE Clear the gradients of all optimized parameters for model.NEWLINE (Only work in dygraph mode)NEWLINENEWLINE Returns: NEWLINE NoneNEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddleNEWLINE import paddle.nn as nnNEWLINE from paddle.distributed import fleetNEWLINENEWLINE class LinearNet(nn.Layer):NEWLINE def __init__(self):NEWLINE super(LinearNet, self).__init__()NEWLINE self._linear1 = nn.Linear(10, 10)NEWLINE self._linear2 = nn.Linear(10, 1)NEWLINENEWLINE def forward(self, x):NEWLINE return self._linear2(self._linear1(x))NEWLINENEWLINE # 1. initialize fleet environmentNEWLINE fleet.init(is_collective=True)NEWLINENEWLINE # 2. create layer & optimizerNEWLINE layer = LinearNet()NEWLINE loss_fn = nn.MSELoss()NEWLINE adam = paddle.optimizer.Adam(NEWLINE learning_rate=0.001, parameters=layer.parameters())NEWLINENEWLINE # 3. get data_parallel model using fleetNEWLINE adam = fleet.distributed_optimizer(adam)NEWLINE dp_layer = fleet.distributed_model(layer)NEWLINENEWLINE # 4. run layerNEWLINE inputs = paddle.randn([10, 10], 'float32')NEWLINE outputs = dp_layer(inputs)NEWLINE labels = paddle.randn([10, 1], 'float32')NEWLINE loss = loss_fn(outputs, labels)NEWLINENEWLINE print("loss:", loss.numpy())NEWLINENEWLINE loss.backward()NEWLINENEWLINE adam.step()NEWLINE adam.clear_grad()NEWLINENEWLINE """NEWLINE # imitate target optimizer retrievalNEWLINE return self.user_defined_optimizer.clear_grad()NEWLINENEWLINE def _get_amp_optimizer(self):NEWLINE # imitate target optimizer retrievalNEWLINE amp_optimizer = NoneNEWLINE for optimizer in self.strategy_compiler._get_applied_meta_optimizer():NEWLINE if hasattr(optimizer, 'amp_init'):NEWLINE amp_optimizer = optimizerNEWLINE breakNEWLINENEWLINE if amp_optimizer is None:NEWLINE if hasattr(self.user_defined_optimizer, 'amp_init'):NEWLINE amp_optimizer = self.user_defined_optimizerNEWLINENEWLINE assert amp_optimizer is not None, \NEWLINE "amp_init can only be used when the amp(auto mixed precision) strategy is turned on."NEWLINE return amp_optimizerNEWLINENEWLINE def get_loss_scaling(self):NEWLINE """Return the real-time loss scaling factor.NEWLINE """NEWLINE amp_optimizer = self._get_amp_optimizer()NEWLINE return amp_optimizer.get_loss_scaling()NEWLINENEWLINE def amp_init(self,NEWLINE place,NEWLINE scope=None,NEWLINE test_program=None,NEWLINE use_fp16_test=False):NEWLINE """NEWLINE Init the amp training, such as cast fp32 parameters to fp16 type.NEWLINE NEWLINE Args:NEWLINE place(CUDAPlace): place is used to initialize NEWLINE fp16 parameters with fp32 values.NEWLINE scope(Scope): The scope is used to find fp32 parameters.NEWLINE test_program(Program): The program is used for testing.NEWLINE use_fp16_test(bool): Whether to use fp16 testing.NEWLINE NEWLINE Examples:NEWLINE .. code-block:: pythonNEWLINENEWLINE import numpy as npNEWLINE import paddleNEWLINE import paddle.nn.functional as FNEWLINE paddle.enable_static()NEWLINENEWLINE def run_example_code():NEWLINE place = paddle.CUDAPlace(0)NEWLINE exe = paddle.static.Executor(place)NEWLINE data = paddle.static.data(name='X', shape=[None, 1, 28, 28], dtype='float32')NEWLINE conv2d = paddle.static.nn.conv2d(input=data, num_filters=6, filter_size=3)NEWLINE # 1) Use fp16_guard to control the range of fp16 kernels used.NEWLINE with paddle.static.amp.fp16_guard():NEWLINE bn = paddle.static.nn.batch_norm(input=conv2d, act="relu")NEWLINE pool = F.max_pool2d(bn, kernel_size=2, stride=2)NEWLINE hidden = paddle.static.nn.fc(pool, size=10)NEWLINE loss = paddle.mean(hidden)NEWLINE # 2) Create the optimizer and set `multi_precision` to True.NEWLINE # Setting `multi_precision` to True can avoid the poor accuracyNEWLINE # or the slow convergence in a way. NEWLINE optimizer = paddle.optimizer.Momentum(learning_rate=0.01, multi_precision=True)NEWLINE # 3) These ops in `custom_black_list` will keep in the float32 computation type.NEWLINE amp_list = paddle.static.amp.CustomOpLists(NEWLINE custom_black_list=['pool2d'])NEWLINE # 4) The entry of Paddle AMP.NEWLINE # Enable pure fp16 training by setting `use_pure_fp16` to True.NEWLINE optimizer = paddle.static.amp.decorate(NEWLINE optimizer,NEWLINE amp_list,NEWLINE init_loss_scaling=128.0,NEWLINE use_dynamic_loss_scaling=True,NEWLINE use_pure_fp16=True)NEWLINE # If you don't use the default_startup_program(), you sholud passNEWLINE # your defined `startup_program` into `minimize`.NEWLINE optimizer.minimize(loss)NEWLINE exe.run(paddle.static.default_startup_program())NEWLINE # 5) Use `amp_init` after FP32 parameters initialization(such as `exe.run(startup_program)`).NEWLINE # If you want to perform the testing process, you should pass `test_program` into `amp_init`.NEWLINE optimizer.amp_init(place, scope=paddle.static.global_scope())NEWLINE NEWLINE if paddle.is_compiled_with_cuda() and len(paddle.static.cuda_places()) > 0:NEWLINE run_example_code() NEWLINE """NEWLINE amp_optimizer = self._get_amp_optimizer()NEWLINE return amp_optimizer.amp_init(place, scope, test_program, use_fp16_test)NEWLINENEWLINE def _final_strategy(self):NEWLINE if "valid_strategy" not in self._context:NEWLINE print(NEWLINE "WARNING: You may need to call minimize function before this function is called"NEWLINE )NEWLINE return {}NEWLINE else:NEWLINE return self._context["valid_strategy"]NEWLINENEWLINE def _get_applied_meta_list(self):NEWLINE if "applied_meta_list" not in self._context:NEWLINE print(NEWLINE "WARNING: You may need to call minimize function before _get_applied_meta_list called"NEWLINE )NEWLINE return []NEWLINE else:NEWLINE return self._context["applied_meta_list"]NEWLINENEWLINE def _get_applied_graph_list(self):NEWLINE if "applied_graph_list" not in self._context:NEWLINE print(NEWLINE "WARNING: You may need to call minimize function before _get_applied_graph_list called"NEWLINE )NEWLINE return []NEWLINE else:NEWLINE return self._context["applied_graph_list"]NEWLINENEWLINE def minimize(self,NEWLINE loss,NEWLINE startup_program=None,NEWLINE parameter_list=None,NEWLINE no_grad_set=None):NEWLINE """NEWLINE Add distributed operations to minimize ``loss`` by updating ``parameter_list``.NEWLINENEWLINE Args:NEWLINE loss (Tensor): A ``Tensor`` containing the value to minimize.NEWLINE startup_program (Program, optional): :ref:`api_fluid_Program` forNEWLINE initializing parameters in ``parameter_list``. The default valueNEWLINE is None, at this time :ref:`api_fluid_default_startup_program` will be used.NEWLINE parameter_list (Iterable, optional): Iterable of ``Tensor`` or ``Tensor.name`` to updateNEWLINE to minimize ``loss``. The default value is None, at this time all parametersNEWLINE will be updated.NEWLINE no_grad_set (set, optional): Set of ``Tensor`` or ``Tensor.name`` that don't needNEWLINE to be updated. The default value is None.NEWLINENEWLINE Returns:NEWLINE tuple: tuple (optimize_ops, params_grads), A list of operators appendedNEWLINE by minimize and a list of (param, grad) tensor pairs, param isNEWLINE ``Parameter``, grad is the gradient value corresponding to the parameter.NEWLINE The returned tuple can be passed to ``fetch_list`` in ``Executor.run()`` toNEWLINE indicate program pruning. If so, the program will be pruned by ``feed`` andNEWLINE ``fetch_list`` before run, see details in ``Executor``.NEWLINENEWLINE Examples:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE import paddleNEWLINE paddle.enable_static()NEWLINE import paddle.distributed.fleet as fleetNEWLINE import paddle.nn.functional as FNEWLINENEWLINE hid_dim = 10NEWLINE label_dim = 2NEWLINE input_x = paddle.static.data(name='x', shape=[None, 13], dtype='float32')NEWLINE input_y = paddle.static.data(name='y', shape=[None, 1], dtype='int64')NEWLINE fc_1 = paddle.static.nn.fc(x=input_x, size=hid_dim, activation='tanh')NEWLINE fc_2 = paddle.static.nn.fc(x=fc_1, size=hid_dim, activation='tanh')NEWLINE prediction = paddle.static.nn.fc(x=[fc_2], size=label_dim, activation='softmax')NEWLINE cost = F.cross_entropy(input=prediction, label=input_y)NEWLINE avg_cost = paddle.mean(x=cost)NEWLINENEWLINE fleet.init(is_collective=True)NEWLINE strategy = fleet.DistributedStrategy()NEWLINE optimizer = paddle.optimizer.SGD(learning_rate=0.001)NEWLINE optimizer = fleet.distributed_optimizer(optimizer, strategy=strategy)NEWLINE optimizer.minimize(avg_cost)NEWLINENEWLINE # for more examples, please reference https://github.com/PaddlePaddle/FleetXNEWLINENEWLINE """NEWLINE context = {}NEWLINE context["user_defined_strategy"] = copy.deepcopy(NEWLINE self._user_defined_strategy)NEWLINE if paddle.fluid.framework.in_dygraph_mode():NEWLINE # imitate target optimizer retrievalNEWLINE target_opt = self.user_defined_optimizerNEWLINE self._context = contextNEWLINE return target_opt.minimize(loss)NEWLINENEWLINE # cache original feed forward programNEWLINE self.origin_main_program = loss.block.programNEWLINE context["origin_main_program"] = self.origin_main_programNEWLINE context["loss"] = lossNEWLINE if startup_program == None:NEWLINE self.origin_startup_program = \NEWLINE paddle.static.default_startup_program().clone(for_test=False)NEWLINE startup_program = paddle.static.default_startup_program()NEWLINE else:NEWLINE self.origin_startup_program = \NEWLINE startup_program.clone(for_test=False)NEWLINENEWLINE context["origin_startup_program"] = startup_programNEWLINE context["role_maker"] = self._role_makerNEWLINENEWLINE # compile timeNEWLINE distributed_optimizer_list = \NEWLINE MetaOptimizerFactory()._get_valid_meta_optimizers(NEWLINE self.user_defined_optimizer)NEWLINENEWLINE context["user_defined_strategy"] = copy.deepcopy(NEWLINE self._user_defined_strategy)NEWLINE copy_user_defined_strategy = copy.deepcopy(self._user_defined_strategy)NEWLINENEWLINE # trigger the auto-parallel in very strict conditionNEWLINE # strategy = DistributedStrategy()NEWLINE # strategy.auto = TrueNEWLINE # optimizer = paddle.optimizer.SGD(learning_rate=0.1)NEWLINE # optimizer = fleet.distributed_optimizer(optimizer, strategy)NEWLINE if copy_user_defined_strategy._is_strict_auto():NEWLINE # turn on all the strategy for each optimizerNEWLINE for opt in distributed_optimizer_list:NEWLINE opt._enable_strategy(copy_user_defined_strategy, context)NEWLINENEWLINE valid_optimizer_list = []NEWLINE valid_graph_optimizer_list = []NEWLINE can_not_apply_optimizer_list = []NEWLINE # recall meta optimizers for rankingNEWLINE for opt in distributed_optimizer_list:NEWLINE opt._set_basic_info(loss, self._role_maker,NEWLINE self.user_defined_optimizer,NEWLINE copy_user_defined_strategy)NEWLINE if opt._can_apply() and not opt._is_graph_out():NEWLINE valid_optimizer_list.append(opt)NEWLINE elif opt._can_apply() and opt._is_graph_out():NEWLINE valid_graph_optimizer_list.append(opt)NEWLINE else:NEWLINE can_not_apply_optimizer_list.append(opt)NEWLINE # combine recalled meta optimizers to be a valid meta optimizerNEWLINE meta_optimizer, graph_optimizer = \NEWLINE self.strategy_compiler.generate_optimizer(NEWLINE loss, self._role_maker, self.user_defined_optimizer,NEWLINE copy_user_defined_strategy, valid_optimizer_list,NEWLINE valid_graph_optimizer_list)NEWLINENEWLINE valid_strategy = self.strategy_compiler._get_valid_strategy(NEWLINE copy_user_defined_strategy, can_not_apply_optimizer_list)NEWLINENEWLINE context["valid_strategy"] = copy.deepcopy(valid_strategy)NEWLINENEWLINE applied_meta_list = self.strategy_compiler._get_applied_meta_list()NEWLINE applied_graph_list = self.strategy_compiler._get_applied_graph_list()NEWLINENEWLINE context['applied_meta_list'] = applied_meta_listNEWLINE context['applied_graph_list'] = applied_graph_listNEWLINENEWLINE self._context = contextNEWLINENEWLINE self.valid_strategy = valid_strategyNEWLINE self.valid_strategy._enable_env()NEWLINENEWLINE optimize_ops = []NEWLINE params_grads = []NEWLINENEWLINE if self._role_maker._is_non_distributed() and not self._is_collective:NEWLINE if self._runtime_handle is None:NEWLINE self._runtime_handle = RuntimeFactory()._create_runtime(context)NEWLINENEWLINE compiled_program = compiler.CompiledProgram(NEWLINE self.origin_main_program).with_data_parallel(NEWLINE loss_name=loss.name, share_vars_from=None)NEWLINE loss.block.program._graph = compiled_programNEWLINE return self.user_defined_optimizer.minimize(NEWLINE loss, startup_program, parameter_list, no_grad_set=no_grad_set)NEWLINENEWLINE if meta_optimizer:NEWLINE optimize_ops, params_grads = meta_optimizer.minimize(NEWLINE loss, startup_program, parameter_list, no_grad_set=no_grad_set)NEWLINENEWLINE default_program = paddle.static.default_main_program()NEWLINENEWLINE if id(default_program) != id(loss.block.program):NEWLINE paddle.fluid.framework.switch_main_program(loss.block.program)NEWLINENEWLINE else:NEWLINE optimize_ops, params_grads = self.user_defined_optimizer.minimize(NEWLINE loss, startup_program, parameter_list, no_grad_set=no_grad_set)NEWLINENEWLINE context["program_optimize_ops"] = optimize_opsNEWLINE context["program_params_grads"] = params_gradsNEWLINENEWLINE if graph_optimizer:NEWLINE optimize_ops, params_grads = graph_optimizer.minimize(NEWLINE loss, startup_program, parameter_list, no_grad_set=no_grad_set)NEWLINE # since we do not encourage users to use graph operationsNEWLINE # if a graph optimizer takes effect, mostlyNEWLINE # optimizers_ops and params_grads are NoneNEWLINE # i.e. users can not modify current computation graph anymoreNEWLINE context["graph_optimize_ops"] = optimize_opsNEWLINE context["graph_optimize_grads"] = params_gradsNEWLINENEWLINE if self._runtime_handle is None:NEWLINE self._runtime_handle = RuntimeFactory()._create_runtime(context)NEWLINENEWLINE import paddle.distributed.fleet as fleetNEWLINE fleet.util._set_strategy(context["valid_strategy"])NEWLINENEWLINE return optimize_ops, params_gradsNEWLINENEWLINE @dygraph_onlyNEWLINE def distributed_scaler(self, scaler):NEWLINE return HybridParallelGradScaler(scaler, self._hcg)NEWLINE #MenuTitle: Build Circled GlyphsNEWLINE# -*- coding: utf-8 -*-NEWLINEfrom __future__ import division, print_function, unicode_literalsNEWLINE__doc__="""NEWLINEBuilds circled numbers and letters (U+24B6...24EA and U+2460...2473) from _part.circle and the letters and figures.NEWLINE"""NEWLINENEWLINEfrom Foundation import NSPointNEWLINEimport mathNEWLINENEWLINEminDistanceBetweenFigures = 90.0NEWLINENEWLINEthisFont = Glyphs.font # frontmost fontNEWLINEthisFontMaster = thisFont.selectedFontMaster # active masterNEWLINEselectedLayers = thisFont.selectedLayers # active layers of selected glyphsNEWLINEcircledGlyphNames = ["one.circled", "two.circled", "three.circled", "four.circled", "five.circled", "six.circled", "seven.circled", "eight.circled", "nine.circled", "one_zero.circled", "one_one.circled", "one_two.circled", "one_three.circled", "one_four.circled", "one_five.circled", "one_six.circled", "one_seven.circled", "one_eight.circled", "one_nine.circled", "two_zero.circled", "A.circled", "B.circled", "C.circled", "D.circled", "E.circled", "F.circled", "G.circled", "H.circled", "I.circled", "J.circled", "K.circled", "L.circled", "M.circled", "N.circled", "O.circled", "P.circled", "Q.circled", "R.circled", "S.circled", "T.circled", "U.circled", "V.circled", "W.circled", "X.circled", "Y.circled", "Z.circled", "a.circled", "b.circled", "c.circled", "d.circled", "e.circled", "f.circled", "g.circled", "h.circled", "i.circled", "j.circled", "k.circled", "l.circled", "m.circled", "n.circled", "o.circled", "p.circled", "q.circled", "r.circled", "s.circled", "t.circled", "u.circled", "v.circled", "w.circled", "x.circled", "y.circled", "z.circled", "zero.circled"]NEWLINENEWLINENEWLINENEWLINEdef offsetLayer( thisLayer, offset, makeStroke=False, position=0.5, autoStroke=False ):NEWLINE offsetFilter = NSClassFromString("GlyphsFilterOffsetCurve")NEWLINE offsetFilter.offsetLayer_offsetX_offsetY_makeStroke_autoStroke_position_error_shadow_(NEWLINE thisLayer,NEWLINE offset, offset, # horizontal and vertical offsetNEWLINE makeStroke, # if True, creates a strokeNEWLINE autoStroke, # if True, distorts resulting shape to vertical metricsNEWLINE position, # stroke distribution to the left and right, 0.5 = middleNEWLINE None, None )NEWLINENEWLINEdef transform(shiftX=0.0, shiftY=0.0, rotate=0.0, skew=0.0, scale=1.0):NEWLINE """NEWLINE Returns an NSAffineTransform object for transforming layers.NEWLINE Apply an NSAffineTransform t object like this:NEWLINE Layer.transform_checkForSelection_doComponents_(t,False,True)NEWLINE Access its transformation matrix like this:NEWLINE tMatrix = t.transformStruct() # returns the 6-float tupleNEWLINE Apply the matrix tuple like this:NEWLINE Layer.applyTransform(tMatrix)NEWLINE Component.applyTransform(tMatrix)NEWLINE Path.applyTransform(tMatrix)NEWLINE Chain multiple NSAffineTransform objects t1, t2 like this:NEWLINE t1.appendTransform_(t2)NEWLINE """NEWLINE myTransform = NSAffineTransform.transform()NEWLINE if rotate:NEWLINE myTransform.rotateByDegrees_(rotate)NEWLINE if scale != 1.0:NEWLINE myTransform.scaleBy_(scale)NEWLINE if not (shiftX == 0.0 and shiftY == 0.0):NEWLINE myTransform.translateXBy_yBy_(shiftX,shiftY)NEWLINE if skew:NEWLINE skewStruct = NSAffineTransformStruct()NEWLINE skewStruct.m11 = 1.0NEWLINE skewStruct.m22 = 1.0NEWLINE skewStruct.m21 = math.tan(math.radians(skew))NEWLINE skewTransform = NSAffineTransform.transform()NEWLINE skewTransform.setTransformStruct_(skewStruct)NEWLINE myTransform.appendTransform_(skewTransform)NEWLINE return myTransformNEWLINENEWLINEdef centerOfRect(rect):NEWLINE """NEWLINE Returns the center of NSRect rect as an NSPoint.NEWLINE """NEWLINE x = rect.origin.x + rect.size.width * 0.5NEWLINE y = rect.origin.y + rect.size.height * 0.5NEWLINE return NSPoint(x,y)NEWLINENEWLINEdef combinedBounds(rects):NEWLINE bottomLeft = NSPoint( 1000.0, 100.0 )NEWLINE topRight = NSPoint( 0.0, 0.0 )NEWLINE for thisRect in rects:NEWLINE bottomLeft.x = min( thisRect.origin.x, bottomLeft.x )NEWLINE bottomLeft.y = min( thisRect.origin.y, bottomLeft.y )NEWLINE topRight.x = max( topRight.x, thisRect.origin.x+thisRect.size.width )NEWLINE topRight.y = max( topRight.y, thisRect.origin.y+thisRect.size.height )NEWLINE combinedRect = NSRect()NEWLINE combinedRect.origin = bottomLeftNEWLINE combinedRect.size = NSSize( topRight.x-bottomLeft.x, topRight.y-bottomLeft.y )NEWLINE return combinedRectNEWLINENEWLINEdef measureLayerAtHeightFromLeftOrRight( thisLayer, height, leftSide=True ):NEWLINE leftX = thisLayer.bounds.origin.xNEWLINE rightX = leftX + thisLayer.bounds.size.widthNEWLINE y = heightNEWLINE returnIndex = 1NEWLINE if not leftSide:NEWLINE returnIndex = -2NEWLINE measurement = thisLayer.intersectionsBetweenPoints( NSPoint(leftX,y), NSPoint(rightX,y) )[returnIndex].pointValue().xNEWLINE if leftSide:NEWLINE distance = measurement - leftXNEWLINE else:NEWLINE distance = rightX - measurementNEWLINE return distanceNEWLINENEWLINEdef minDistanceBetweenTwoLayers( comp1, comp2, interval=5.0 ):NEWLINE topY = min( comp1.bounds.origin.y+comp1.bounds.size.height, comp2.bounds.origin.y+comp2.bounds.size.height )NEWLINE bottomY = max( comp1.bounds.origin.y, comp2.bounds.origin.y )NEWLINE distance = topY - bottomYNEWLINE minDist = NoneNEWLINE for i in range(int(distance/interval)):NEWLINE height = bottomY + i * intervalNEWLINE left = measureLayerAtHeightFromLeftOrRight( comp1, height, leftSide=False )NEWLINE right = measureLayerAtHeightFromLeftOrRight( comp2, height, leftSide=True )NEWLINE total = left+rightNEWLINE if minDist == None or minDist > total:NEWLINE minDist = totalNEWLINE return minDistNEWLINENEWLINEdef placeComponentsAtDistance( thisLayer, comp1, comp2, interval=5.0, distance=10.0 ):NEWLINE thisMaster = thisLayer.associatedFontMaster()NEWLINE masterID = thisMaster.idNEWLINE original1 = comp1.component.layers[masterID]NEWLINE original2 = comp2.component.layers[masterID]NEWLINE minDist = minDistanceBetweenTwoLayers( original1, original2, interval=interval )NEWLINE comp2shift = distance - minDistNEWLINE addedSBs = original1.RSB + original2.LSBNEWLINE comp2.x = comp1.x + original1.width - addedSBs + comp2shiftNEWLINENEWLINEdef process( thisLayer, compName1, compName2, distance=10.0, interval=5.0 ):NEWLINE if compName1 and compName2:NEWLINE compCount = len(thisLayer.components)NEWLINE for compName in (compName1,compName2):NEWLINE newComp = GSComponent(compName)NEWLINE thisLayer.components.append(newComp)NEWLINE newComp.disableAlignment = TrueNEWLINE placeComponentsAtDistance( thisLayer, thisLayer.components[compCount], thisLayer.components[compCount+1] )NEWLINE else:NEWLINE return FalseNEWLINENEWLINENEWLINEdef buildCircledGlyph( thisGlyph, circleName, scaleFactors ):NEWLINE thisFont = thisGlyph.font()NEWLINE thisGlyph.setWidthMetricsKey_( "=%i" % thisFont.upm )NEWLINE circleGlyph = thisFont.glyphs[circleName]NEWLINE NEWLINE for i, thisMaster in enumerate(thisFont.masters):NEWLINE figureHeight = NoneNEWLINE scaleFactor = scaleFactors[i]NEWLINE thisLayer = thisGlyph.layers[thisMaster.id]NEWLINE circleLayer = circleGlyph.layers[thisMaster.id]NEWLINE circleScaleFactor = thisFont.upm * 0.9 / ( circleLayer.bounds.size.width )NEWLINE thisLayer.clear()NEWLINE thisLayer.syncMetrics()NEWLINE NEWLINE # add circle:NEWLINE assumedCenter = NSPoint( thisFont.upm*0.5, thisFont.upm*0.3 ) # hardcodedNEWLINE circleComponent = GSComponent(circleName)NEWLINE thisLayer.components.append(circleComponent)NEWLINE NEWLINE # scale circle:NEWLINE circleScale = transform( scale=circleScaleFactor ).transformStruct()NEWLINE circleComponent.applyTransform( circleScale )NEWLINE NEWLINE # move circle:NEWLINE circleBounds = thisLayer.components[0].boundsNEWLINE circleCenter = centerOfRect(circleBounds)NEWLINE xShift = assumedCenter.x - circleCenter.xNEWLINE yShift = assumedCenter.y - circleCenter.yNEWLINE circleShift = transform( shiftX=xShift, shiftY=yShift ).transformStruct()NEWLINE circleComponent.applyTransform(circleShift)NEWLINE NEWLINE # find components to addNEWLINE suffixlessName = thisGlyph.nameNEWLINE if "." in suffixlessName:NEWLINE suffixlessName = thisGlyph.name[:thisGlyph.name.find(".")]NEWLINE componentNames = suffixlessName.split("_")NEWLINE NEWLINE # add one component in the center:NEWLINE if componentNames:NEWLINE advance = 0NEWLINE for j, compName in enumerate(componentNames):NEWLINE lfName = "%s.lf" % compNameNEWLINE osfName = "%s.osf" % compNameNEWLINE if thisFont.glyphs[lfName]:NEWLINE compName = lfNameNEWLINE elif thisFont.glyphs[osfName]:NEWLINE compName = osfNameNEWLINE NEWLINE innerComponent = GSComponent( compName )NEWLINE thisLayer.components.append( innerComponent )NEWLINE innerComponent.position = NSPoint( advance, 0.0 )NEWLINE NEWLINE if j > 0:NEWLINE innerComponent.disableAlignment = TrueNEWLINE placeComponentsAtDistance( NEWLINE thisLayer,NEWLINE thisLayer.components[-2], NEWLINE thisLayer.components[-1], # same as innerComponentNEWLINE distance = minDistanceBetweenFiguresNEWLINE )NEWLINE NEWLINE originalLayerWidth = thisFont.glyphs[compName].layers[thisMaster.id].widthNEWLINE advance += originalLayerWidthNEWLINE NEWLINE collectedBounds = [ c.bounds for c in thisLayer.components[1:] ]NEWLINE compCenter = centerOfRect( combinedBounds(collectedBounds) )NEWLINE circleCenter = centerOfRect( circleComponent.bounds )NEWLINE NEWLINE # scale and move it in place:NEWLINE shift = transform( shiftX=-compCenter.x, shiftY=-compCenter.y ).transformStruct()NEWLINE scaleToFit = transform( scale=scaleFactor*circleScaleFactor ).transformStruct()NEWLINE backshift = transform( shiftX=circleCenter.x, shiftY=circleCenter.y ).transformStruct()NEWLINE NEWLINE compensateStroke = []NEWLINE for innerComponent in thisLayer.components[1:]:NEWLINE NEWLINE # optically shift so top anchor is in center:NEWLINE originalLayer = topAnchor = innerComponent.component.layers[thisMaster.id]NEWLINE topAnchor = originalLayer.anchors["top"]NEWLINE if topAnchor:NEWLINE anchorCenter = topAnchor.xNEWLINE boundsCenter = centerOfRect(originalLayer.bounds).xNEWLINE opticalCorrection = boundsCenter-anchorCenterNEWLINE if opticalCorrection != 0.0:NEWLINE threshold = 35.0NEWLINE if abs(opticalCorrection) > threshold:NEWLINE posNeg = opticalCorrection/abs(opticalCorrection)NEWLINE rest = abs(opticalCorrection) - thresholdNEWLINE opticalCorrection = posNeg * ( threshold + rest * 1/rest**0.3 )NEWLINE print("--", opticalCorrection)NEWLINE opticalShift = transform( shiftX = opticalCorrection ).transformStruct()NEWLINE innerComponent.applyTransform( opticalShift )NEWLINE NEWLINE NEWLINE innerComponent.applyTransform( shift )NEWLINE innerComponent.applyTransform( scaleToFit )NEWLINE innerComponent.applyTransform( backshift )NEWLINE NEWLINE # move components closer to center:NEWLINE #move = 15.0NEWLINE #hOffset = circleCenter.x - centerOfRect(innerComponent.bounds).xNEWLINE #if abs(hOffset) > move:NEWLINE # hOffset = (hOffset/abs(hOffset))*moveNEWLINE #if hOffset != 0.0:NEWLINE # moveCloser = transform( shiftX=hOffset ).transformStruct()NEWLINE # innerComponent.applyTransform( moveCloser )NEWLINE NEWLINE # compensatory shift:NEWLINE if thisGlyph.name in ("two_zero.circled", "one_nine.circled", "one_zero.circled"):NEWLINE compensate = transform( shiftX=10.0 ).transformStruct()NEWLINE innerComponent.applyTransform( compensate )NEWLINE NEWLINE NEWLINE NEWLINE if innerComponent.component.glyphInfo.category == "Number":NEWLINE if figureHeight == None:NEWLINE figureHeight = innerComponent.position.yNEWLINE else:NEWLINE innerComponent.position.y = figureHeightNEWLINE NEWLINE compensateStroke.append(innerComponent)NEWLINE NEWLINE # auffetten:NEWLINE isNumber = FalseNEWLINE for i in range(len(compensateStroke))[::-1]:NEWLINE componentToDecompose = compensateStroke[i]NEWLINE if componentToDecompose.component.category == "Number":NEWLINE isNumber = TrueNEWLINE thisLayer.decomposeComponent_(componentToDecompose)NEWLINE NEWLINE offsetLayer( thisLayer, 4.0 ) #4.0 if isNumber else 3.0 )NEWLINE thisLayer.anchors = NoneNEWLINE NEWLINE NEWLINE NEWLINENEWLINENEWLINEdef buildCirclePart( thisFont, glyphName ):NEWLINE partCircle = (NEWLINE (NEWLINE (353.0, 0.0),NEWLINE ((152.0, 0.0),(0.0, 150.0),(0.0, 348.0)),NEWLINE ((0.0, 549.0),(152.0, 700.0),(353.0, 700.0)),NEWLINE ((556.0, 700.0),(708.0, 549.0),(708.0, 348.0)),NEWLINE ((708.0, 149.0),(556.0, 0.0),(353.0, 0.0))NEWLINE ),NEWLINE )NEWLINE NEWLINE thisGlyph = thisFont.glyphs[glyphName]NEWLINE if not thisGlyph:NEWLINE thisGlyph = GSGlyph()NEWLINE thisGlyph.name = glyphNameNEWLINE thisFont.glyphs.append( thisGlyph )NEWLINE print("Generated %s" % glyphName)NEWLINE NEWLINE thisGlyph.export = FalseNEWLINE NEWLINE # find zero for reference:NEWLINE zeroGlyph = thisFont.glyphs["zero.lf"]NEWLINE if not zeroGlyph:NEWLINE zeroGlyph = thisFont.glyphs["zero.tf"]NEWLINE if not zeroGlyph:NEWLINE zeroGlyph = thisFont.glyphs["zero"]NEWLINE NEWLINE # draw in every layer:NEWLINE for thisLayer in thisGlyph.layers:NEWLINE # make sure it is empty:NEWLINE thisLayer.clear()NEWLINE NEWLINE # draw outer circle:NEWLINE for thisPath in partCircle:NEWLINE pen = thisLayer.getPen()NEWLINE pen.moveTo( thisPath[0] )NEWLINE for thisSegment in thisPath[1:]:NEWLINE if len(thisSegment) == 2: # linetoNEWLINE pen.lineTo( thisSegment )NEWLINE elif len(thisSegment) == 3: # curvetoNEWLINE pen.curveTo(NEWLINE thisSegment[0],NEWLINE thisSegment[1],NEWLINE thisSegment[2]NEWLINE )NEWLINE else:NEWLINE print("%s: Path drawing error. Could not process this segment:\n" % (glyphName, thisSegment))NEWLINE pen.closePath()NEWLINE pen.endPath()NEWLINE NEWLINE # scale circle to match zero:NEWLINE if zeroGlyph:NEWLINE zeroBounds = zeroGlyph.layers[thisLayer.associatedMasterId].boundsNEWLINE zeroHeight = zeroBounds.size.heightNEWLINE if zeroHeight: # zero could be emptyNEWLINE zeroOvershoot = -zeroBounds.origin.yNEWLINE overshootDiff = zeroOvershoot - 5.0NEWLINE actualHeight = thisLayer.bounds.size.heightNEWLINE correctedHeight = zeroHeight - 2 * overshootDiffNEWLINE if correctedHeight != actualHeight:NEWLINE scaleFactor = correctedHeight/actualHeightNEWLINE correction = transform(shiftY=5.0)NEWLINE correction.appendTransform_( transform(scale=scaleFactor) )NEWLINE correction.appendTransform_( transform(-5.0) )NEWLINE thisLayer.applyTransform( correction.transformStruct() )NEWLINENEWLINE # inner circle, scaled down:NEWLINE currentHeight = thisLayer.bounds.size.heightNEWLINE outerCircle = thisLayer.paths[0]NEWLINE innerCircle = outerCircle.copy()NEWLINE thisLayer.paths.append(innerCircle)NEWLINE NEWLINE # scale down inner circle:NEWLINE stemSize = 50.0NEWLINE hstems = thisLayer.associatedFontMaster().horizontalStemsNEWLINE vstems = thisLayer.associatedFontMaster().verticalStemsNEWLINE if hstems and vstems:NEWLINE stemSize = (hstems[0] + vstems[0]) * 0.25NEWLINE NEWLINE maximumStemSize = currentHeight * 0.28NEWLINE stemSize = min(maximumStemSize,stemSize)NEWLINE smallerBy = stemSize * 2 * 1.06NEWLINE newHeight = currentHeight - smallerByNEWLINE scaleFactor = newHeight/currentHeightNEWLINE scale = transform(scale=scaleFactor).transformStruct()NEWLINE NEWLINE centerX = innerCircle.bounds.origin.x + innerCircle.bounds.size.width * 0.5NEWLINE centerY = innerCircle.bounds.origin.y + innerCircle.bounds.size.height * 0.5NEWLINE shift = transform(shiftX=-centerX, shiftY=-centerY).transformStruct()NEWLINE shiftBack = transform(shiftX=centerX, shiftY=centerY).transformStruct()NEWLINE NEWLINE innerCircle.applyTransform( shift )NEWLINE innerCircle.applyTransform( scale )NEWLINE innerCircle.applyTransform( shiftBack )NEWLINENEWLINE # tidy up paths and set width:NEWLINE thisLayer.correctPathDirection()NEWLINE thisLayer.cleanUpPaths()NEWLINE thisLayer.LSB = 40.0NEWLINE thisLayer.RSB = 40.0NEWLINE NEWLINE # add anchor:NEWLINE centerX = thisLayer.bounds.origin.x + thisLayer.bounds.size.width * 0.5NEWLINE centerY = thisLayer.bounds.origin.y + thisLayer.bounds.size.height * 0.5NEWLINE centerAnchor = GSAnchor()NEWLINE centerAnchor.name = "#center"NEWLINE centerAnchor.position = NSPoint( centerX, centerY )NEWLINE thisLayer.anchors.append(centerAnchor)NEWLINENEWLINEdef boxArea(thisLayer):NEWLINE return thisLayer.bounds.size.width * thisLayer.bounds.size.heightNEWLINENEWLINEthisFont.disableUpdateInterface() # suppresses UI updates in Font ViewNEWLINENEWLINENEWLINE# add circle if not present in font already:NEWLINEcircleName = "_part.circle"NEWLINEif not thisFont.glyphs[circleName]:NEWLINE buildCirclePart( thisFont, circleName )NEWLINEcircleGlyph = thisFont.glyphs[circleName]NEWLINENEWLINE# determining scale of inscribed letters:NEWLINEscaleFactors = []NEWLINEfor thisMaster in thisFont.masters:NEWLINE radius = circleGlyph.layers[thisMaster.id].paths[1].bounds.size.width * 0.5NEWLINE maxArea = 0.0NEWLINE biggestLayer = NoneNEWLINE for glyphName in circledGlyphNames:NEWLINE if "." in glyphName:NEWLINE glyphName = glyphName[:glyphName.find(".")]NEWLINE thisGlyph = thisFont.glyphs[glyphName]NEWLINE if thisGlyph:NEWLINE thisLayer = thisGlyph.layers[thisMaster.id]NEWLINE thisArea = boxArea(thisLayer)NEWLINE if thisArea > maxArea:NEWLINE maxArea = thisAreaNEWLINE biggestLayer = thisLayerNEWLINE NEWLINE angleInRadians = math.atan2( biggestLayer.bounds.size.height, biggestLayer.bounds.size.width )NEWLINE scaledHeight = math.sin(angleInRadians) * radius * 2 * 0.9NEWLINE scaleFactor = scaledHeight / biggestLayer.bounds.size.heightNEWLINE scaleFactors.append(scaleFactor)NEWLINE NEWLINENEWLINEfor glyphName in circledGlyphNames:NEWLINE thisGlyph = thisFont.glyphs[glyphName]NEWLINE if not thisGlyph:NEWLINE thisGlyph = GSGlyph()NEWLINE thisGlyph.name = glyphNameNEWLINE thisFont.glyphs.append(thisGlyph)NEWLINENEWLINE thisGlyph.beginUndo() # begin undo groupingNEWLINE print("Building %s" % thisGlyph.name)NEWLINE buildCircledGlyph( thisGlyph, circleName, scaleFactors )NEWLINE thisGlyph.endUndo() # end undo groupingNEWLINENEWLINEthisFont.enableUpdateInterface() # re-enables UI updates in Font ViewNEWLINE """NEWLINEAbstract agent for the gym-idsgame environmentNEWLINE"""NEWLINEfrom abc import ABCNEWLINE#from gym_idsgame.envs.dao.game_config import GameConfigNEWLINENEWLINEclass Agent(ABC):NEWLINE """NEWLINE Abstract class representing an agentNEWLINE """NEWLINENEWLINE def __init__(self, game_config):NEWLINE """NEWLINE Class constructorNEWLINENEWLINE :param game_config: the game configurationNEWLINE """NEWLINE self.game_config = game_configNEWLINE # if self.game_config is None:NEWLINE # self.game_config = GameConfig()NEWLINE import usocket as socketNEWLINEimport uselectNEWLINEfrom utime import ticks_add, ticks_ms, ticks_diffNEWLINENEWLINENEWLINEclass MQTTException(Exception):NEWLINE passNEWLINENEWLINENEWLINEdef pid_gen(pid=0):NEWLINE while True:NEWLINE pid = pid + 1 if pid < 65535 else 1NEWLINE yield pidNEWLINENEWLINENEWLINEclass MQTTClient:NEWLINENEWLINE def __init__(self, client_id, server, port=0, user=None, password=None, keepalive=0,NEWLINE ssl=False, ssl_params=None, socket_timeout=5, message_timeout=10):NEWLINE """NEWLINE Default constructor, initializes MQTTClient object.NEWLINE :param client_id: Unique MQTT ID attached to client.NEWLINE :type client_id: strNEWLINE :param server: MQTT host address.NEWLINE :type server strNEWLINE :param port: MQTT Port, typically 1883. If unset, the port number will default to 1883 of 8883 base on ssl.NEWLINE :type port: intNEWLINE :param user: Username if your server requires it.NEWLINE :type user: strNEWLINE :param password: Password if your server requires it.NEWLINE :type password: strNEWLINE :param keepalive: The Keep Alive is a time interval measured in seconds since the lastNEWLINE correct control packet was received.NEWLINE :type keepalive: intNEWLINE :param ssl: Require SSL for the connection.NEWLINE :type ssl: boolNEWLINE :param ssl_params: Required SSL parameters.NEWLINE :type ssl_params: dictNEWLINE :param socket_timeout: The time in seconds after which the socket interrupts the connection to the server whenNEWLINE no data exchange takes place. None - socket blocking, positive number - seconds to wait.NEWLINE :type socket_timeout: intNEWLINE :param message_timeout: The time in seconds after which the library recognizes that a message with QoS=1NEWLINE or topic subscription has not been received by the server.NEWLINE :type message_timeout: intNEWLINE """NEWLINE if port == 0:NEWLINE port = 8883 if ssl else 1883NEWLINE self.client_id = client_idNEWLINE self.sock = NoneNEWLINE self.poller_r = NoneNEWLINE self.poller_w = NoneNEWLINE self.server = serverNEWLINE self.port = portNEWLINE self.ssl = sslNEWLINE self.ssl_params = ssl_params if ssl_params else {}NEWLINE self.newpid = pid_gen()NEWLINE if not getattr(self, 'cb', None):NEWLINE self.cb = NoneNEWLINE if not getattr(self, 'cbstat', None):NEWLINE self.cbstat = lambda p, s: NoneNEWLINE self.user = userNEWLINE self.pswd = passwordNEWLINE self.keepalive = keepaliveNEWLINE self.lw_topic = NoneNEWLINE self.lw_msg = NoneNEWLINE self.lw_qos = 0NEWLINE self.lw_retain = FalseNEWLINE self.rcv_pids = {} # PUBACK and SUBACK pids awaiting ACK responseNEWLINENEWLINE self.last_ping = ticks_ms() # Time of the last PING sentNEWLINE self.last_cpacket = ticks_ms() # Time of last Control PacketNEWLINENEWLINE self.socket_timeout = socket_timeoutNEWLINE self.message_timeout = message_timeoutNEWLINENEWLINE def _read(self, n):NEWLINE """NEWLINE Private class method.NEWLINE :param n: Expected length of read bytesNEWLINE :type n: intNEWLINE :return:NEWLINE """NEWLINE # in non-blocking mode, may not download enough dataNEWLINE try:NEWLINE msg = b''NEWLINE for i in range(n):NEWLINE self._sock_timeout(self.poller_r, self.socket_timeout)NEWLINE msg += self.sock.read(1)NEWLINE except AttributeError:NEWLINE raise MQTTException(8)NEWLINE if msg == b'': # Connection closed by host (?)NEWLINE raise MQTTException(1)NEWLINE if len(msg) != n:NEWLINE raise MQTTException(2)NEWLINE return msgNEWLINENEWLINE def _write(self, bytes_wr, length=-1):NEWLINE """NEWLINE Private class method.NEWLINE :param bytes_wr: Bytes sequence for writingNEWLINE :type bytes_wr: bytesNEWLINE :param length: Expected length of write bytesNEWLINE :type length: intNEWLINE :return:NEWLINE """NEWLINE # In non-blocking socket mode, the entire block of data may not be sent.NEWLINE try:NEWLINE self._sock_timeout(self.poller_w, self.socket_timeout)NEWLINE out = self.sock.write(bytes_wr, length)NEWLINE except AttributeError:NEWLINE raise MQTTException(8)NEWLINE if length < 0:NEWLINE if out != len(bytes_wr):NEWLINE raise MQTTException(3)NEWLINE else:NEWLINE if out != length:NEWLINE raise MQTTException(3)NEWLINE return outNEWLINENEWLINE def _send_str(self, s):NEWLINE """NEWLINE Private class method.NEWLINE :param s:NEWLINE :type s: byteNEWLINE :return: NoneNEWLINE """NEWLINE assert len(s) < 65536NEWLINE self._write(len(s).to_bytes(2, 'big'))NEWLINE self._write(s)NEWLINENEWLINE def _recv_len(self):NEWLINE """NEWLINE Private class method.NEWLINE :return:NEWLINE :rtype intNEWLINE """NEWLINE n = 0NEWLINE sh = 0NEWLINE while 1:NEWLINE b = self._read(1)[0]NEWLINE n |= (b & 0x7f) << shNEWLINE if not b & 0x80:NEWLINE return nNEWLINE sh += 7NEWLINENEWLINE def _varlen_encode(self, value, buf, offset=0):NEWLINE assert value < 268435456 # 2**28, i.e. max. four 7-bit bytesNEWLINE while value > 0x7f:NEWLINE buf[offset] = (value & 0x7f) | 0x80NEWLINE value >>= 7NEWLINE offset += 1NEWLINE buf[offset] = valueNEWLINE return offset + 1NEWLINENEWLINE def _sock_timeout(self, poller, socket_timeout):NEWLINE if self.sock:NEWLINE res = poller.poll(-1 if socket_timeout is None else int(socket_timeout * 1000))NEWLINE if not res:NEWLINE raise MQTTException(30)NEWLINE else:NEWLINE raise MQTTException(28)NEWLINENEWLINE def set_callback(self, f):NEWLINE """NEWLINE Set callback for received subscription messages.NEWLINE :param f: callable(topic, msg, retained, duplicate)NEWLINE """NEWLINE self.cb = fNEWLINENEWLINE def set_callback_status(self, f):NEWLINE """NEWLINE Set the callback for information about whether the sent packet (QoS=1)NEWLINE or subscription was received or not by the server.NEWLINE :param f: callable(pid, status)NEWLINE Where:NEWLINE status = 0 - timeoutNEWLINE status = 1 - successfully deliveredNEWLINE status = 2 - Unknown PID. It is also possible that the PID is outdated,NEWLINE i.e. it came out of the message timeout.NEWLINE """NEWLINE self.cbstat = fNEWLINENEWLINE def set_last_will(self, topic, msg, retain=False, qos=0):NEWLINE """NEWLINE Sets the last will and testament of the client. This is used to perform an action by the brokerNEWLINE in the event that the client "dies".NEWLINE Learn more at https://www.hivemq.com/blog/mqtt-essentials-part-9-last-will-and-testament/NEWLINE :param topic: Topic of LWT. Takes the from "path/to/topic"NEWLINE :type topic: byteNEWLINE :param msg: Message to be published to LWT topic.NEWLINE :type msg: byteNEWLINE :param retain: Have the MQTT broker retain the message.NEWLINE :type retain: boolNEWLINE :param qos: Sets quality of service level. Accepts values 0 to 2. PLEASE NOTE qos=2 is not actually supported.NEWLINE :type qos: intNEWLINE :return: NoneNEWLINE """NEWLINE assert 0 <= qos <= 2NEWLINE assert topicNEWLINE self.lw_topic = topicNEWLINE self.lw_msg = msgNEWLINE self.lw_qos = qosNEWLINE self.lw_retain = retainNEWLINENEWLINE def connect(self, clean_session=True):NEWLINE """NEWLINE Establishes connection with the MQTT server.NEWLINE :param clean_session: Starts new session on true, resumes past session if false.NEWLINE :type clean_session: boolNEWLINE :return: Existing persistent session of the client from previous interactions.NEWLINE :rtype: boolNEWLINE """NEWLINE self.sock = socket.socket()NEWLINE addr = socket.getaddrinfo(self.server, self.port)[0][-1]NEWLINE self.sock.connect(addr)NEWLINE if self.ssl:NEWLINE import usslNEWLINE self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)NEWLINENEWLINE self.poller_r = uselect.poll()NEWLINE self.poller_r.register(self.sock, uselect.POLLIN)NEWLINE self.poller_w = uselect.poll()NEWLINE self.poller_w.register(self.sock, uselect.POLLOUT)NEWLINENEWLINE # Byte nr - descNEWLINE # 1 - \x10 0001 - Connect Command, 0000 - ReservedNEWLINE # 2 - Remaining LengthNEWLINE # PROTOCOL NAME (3.1.2.1 Protocol Name)NEWLINE # 3,4 - protocol name length len('MQTT')NEWLINE # 5-8 = 'MQTT'NEWLINE # PROTOCOL LEVEL (3.1.2.2 Protocol Level)NEWLINE # 9 - mqtt version 0x04NEWLINE # CONNECT FLAGSNEWLINE # 10 - connection flagsNEWLINE # X... .... = User Name FlagNEWLINE # .X.. .... = Password FlagNEWLINE # ..X. .... = Will RetainNEWLINE # ...X X... = QoS LevelNEWLINE # .... .X.. = Will FlagNEWLINE # .... ..X. = Clean Session FlagNEWLINE # .... ...0 = (Reserved) It must be 0!NEWLINE # KEEP ALIVENEWLINE # 11,12 - keepaliveNEWLINE # 13,14 - client ID lengthNEWLINE # 15-15+len(client_id) - byte(client_id)NEWLINE premsg = bytearray(b"\x10\0\0\0\0\0")NEWLINE msg = bytearray(b"\0\x04MQTT\x04\0\0\0")NEWLINENEWLINE sz = 10 + 2 + len(self.client_id)NEWLINENEWLINE msg[7] = bool(clean_session) << 1NEWLINE # Clean session = True, remove current sessionNEWLINE if bool(clean_session):NEWLINE self.rcv_pids.clear()NEWLINE if self.user is not None:NEWLINE sz += 2 + len(self.user)NEWLINE msg[7] |= 1 << 7 # User Name FlagNEWLINE if self.pswd is not None:NEWLINE sz += 2 + len(self.pswd)NEWLINE msg[7] |= 1 << 6 # # Password FlagNEWLINE if self.keepalive:NEWLINE assert self.keepalive < 65536NEWLINE msg[8] |= self.keepalive >> 8NEWLINE msg[9] |= self.keepalive & 0x00FFNEWLINE if self.lw_topic:NEWLINE sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)NEWLINE msg[7] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3NEWLINE msg[7] |= self.lw_retain << 5NEWLINENEWLINE plen = self._varlen_encode(sz, premsg, 1)NEWLINE self._write(premsg, plen)NEWLINE self._write(msg)NEWLINE self._send_str(self.client_id)NEWLINE if self.lw_topic:NEWLINE self._send_str(self.lw_topic)NEWLINE self._send_str(self.lw_msg)NEWLINE if self.user is not None:NEWLINE self._send_str(self.user)NEWLINE if self.pswd is not None:NEWLINE self._send_str(self.pswd)NEWLINE resp = self._read(4)NEWLINE if not (resp[0] == 0x20 and resp[1] == 0x02): # control packet type, Remaining Length == 2NEWLINE raise MQTTException(29)NEWLINE if resp[3] != 0:NEWLINE if 1 <= resp[3] <= 5:NEWLINE raise MQTTException(20 + resp[3])NEWLINE else:NEWLINE raise MQTTException(20, resp[3])NEWLINE self.last_cpacket = ticks_ms()NEWLINE return resp[2] & 1 # Is existing persistent session of the client from previous interactions.NEWLINENEWLINE def disconnect(self):NEWLINE """NEWLINE Disconnects from the MQTT server.NEWLINE :return: NoneNEWLINE """NEWLINE self._write(b"\xe0\0")NEWLINE self.poller_r.unregister(self.sock)NEWLINE self.poller_w.unregister(self.sock)NEWLINE self.poller_r = NoneNEWLINE self.poller_w = NoneNEWLINE self.sock.close()NEWLINE self.sock = NoneNEWLINENEWLINE def ping(self):NEWLINE """NEWLINE Pings the MQTT server.NEWLINE :return: NoneNEWLINE """NEWLINE self._write(b"\xc0\0")NEWLINE self.last_ping = ticks_ms()NEWLINENEWLINE def publish(self, topic, msg, retain=False, qos=0, dup=False):NEWLINE """NEWLINE Publishes a message to a specified topic.NEWLINE :param topic: Topic you wish to publish to. Takes the form "path/to/topic"NEWLINE :type topic: byteNEWLINE :param msg: Message to publish to topic.NEWLINE :type msg: byteNEWLINE :param retain: Have the MQTT broker retain the message.NEWLINE :type retain: boolNEWLINE :param qos: Sets quality of service level. Accepts values 0 to 2. PLEASE NOTE qos=2 is not actually supported.NEWLINE :type qos: intNEWLINE :param dup: Duplicate delivery of a PUBLISH Control PacketNEWLINE :type dup: boolNEWLINE :return: NoneNEWLINE """NEWLINE assert qos in (0, 1)NEWLINE pkt = bytearray(b"\x30\0\0\0\0")NEWLINE pkt[0] |= qos << 1 | retain | int(dup) << 3NEWLINE sz = 2 + len(topic) + len(msg)NEWLINE if qos > 0:NEWLINE sz += 2NEWLINE plen = self._varlen_encode(sz, pkt, 1)NEWLINE self._write(pkt, plen)NEWLINE self._send_str(topic)NEWLINE if qos > 0:NEWLINE pid = next(self.newpid)NEWLINE self._write(pid.to_bytes(2, 'big'))NEWLINE self._write(msg)NEWLINE if qos > 0:NEWLINE self.rcv_pids[pid] = ticks_add(ticks_ms(), self.message_timeout * 1000)NEWLINE return pidNEWLINENEWLINE def subscribe(self, topic, qos=0):NEWLINE """NEWLINE Subscribes to a given topic.NEWLINE :param topic: Topic you wish to publish to. Takes the form "path/to/topic"NEWLINE :type topic: byteNEWLINE :param qos: Sets quality of service level. Accepts values 0 to 1. This gives the maximum QoS level at whichNEWLINE the Server can send Application Messages to the Client.NEWLINE :type qos: intNEWLINE :return: NoneNEWLINE """NEWLINE assert qos in (0, 1)NEWLINE assert self.cb is not None, "Subscribe callback is not set"NEWLINE pkt = bytearray(b"\x82\0\0\0\0\0\0")NEWLINE pid = next(self.newpid)NEWLINE sz = 2 + 2 + len(topic) + 1NEWLINE plen = self._varlen_encode(sz, pkt, 1)NEWLINE pkt[plen:plen + 2] = pid.to_bytes(2, 'big')NEWLINE self._write(pkt, plen + 2)NEWLINE self._send_str(topic)NEWLINE self._write(qos.to_bytes(1, "little")) # maximum QOS value that can be given by the server to the clientNEWLINE self.rcv_pids[pid] = ticks_add(ticks_ms(), self.message_timeout * 1000)NEWLINE return pidNEWLINENEWLINE def _message_timeout(self):NEWLINE curr_tick = ticks_ms()NEWLINE for pid, timeout in self.rcv_pids.items():NEWLINE if ticks_diff(timeout, curr_tick) <= 0:NEWLINE self.rcv_pids.pop(pid)NEWLINE self.cbstat(pid, 0)NEWLINENEWLINE def check_msg(self):NEWLINE """NEWLINE Checks whether a pending message from server is available.NEWLINE If socket_timeout=None, this is the socket lock mode. That is, it waits until the data can be read.NEWLINE Otherwise it will return None, after the time set in the socket_timeout.NEWLINE It processes such messages:NEWLINE - response to PINGNEWLINE - messages from subscribed topics that are processed by functions set by the set_callback method.NEWLINE - reply from the server that he received a QoS=1 message or subscribed to a topicNEWLINE :return: NoneNEWLINE """NEWLINE if self.sock:NEWLINE if not self.poller_r.poll(-1 if self.socket_timeout is None else 1):NEWLINE self._message_timeout()NEWLINE return NoneNEWLINE try:NEWLINE res = self._read(1) # Throws OSError on WiFi failNEWLINE if not res:NEWLINE self._message_timeout()NEWLINE return NoneNEWLINE except OSError as e:NEWLINE if e.args[0] == 110: # Occurs when no incomming dataNEWLINE self._message_timeout()NEWLINE return NoneNEWLINE else:NEWLINE raise eNEWLINE else:NEWLINE raise MQTTException(28)NEWLINENEWLINE if res == b"\xd0": # PINGRESPNEWLINE if self._read(1)[0] != 0:NEWLINE MQTTException(-1)NEWLINE self.last_cpacket = ticks_ms()NEWLINE returnNEWLINENEWLINE op = res[0]NEWLINENEWLINE if op == 0x40: # PUBACKNEWLINE sz = self._read(1)NEWLINE if sz != b"\x02":NEWLINE raise MQTTException(-1)NEWLINE rcv_pid = int.from_bytes(self._read(2), 'big')NEWLINE if rcv_pid in self.rcv_pids:NEWLINE self.last_cpacket = ticks_ms()NEWLINE self.rcv_pids.pop(rcv_pid)NEWLINE self.cbstat(rcv_pid, 1)NEWLINE else:NEWLINE self.cbstat(rcv_pid, 2)NEWLINENEWLINE if op == 0x90: # SUBACK Packet fixed headerNEWLINE resp = self._read(4)NEWLINE # Byte - descNEWLINE # 1 - Remaining Length 2(varible header) + len(payload)=1NEWLINE # 2,3 - PIDNEWLINE # 4 - PayloadNEWLINE if resp[0] != 0x03:NEWLINE raise MQTTException(40, resp)NEWLINE if resp[3] == 0x80:NEWLINE raise MQTTException(44)NEWLINE if resp[3] not in (0, 1, 2):NEWLINE raise MQTTException(40, resp)NEWLINE pid = resp[2] | (resp[1] << 8)NEWLINE if pid in self.rcv_pids:NEWLINE self.last_cpacket = ticks_ms()NEWLINE self.rcv_pids.pop(pid)NEWLINE self.cbstat(pid, 1)NEWLINE else:NEWLINE raise MQTTException(5)NEWLINENEWLINE self._message_timeout()NEWLINENEWLINE if op & 0xf0 != 0x30: # 3.3 PUBLISH – Publish messageNEWLINE return opNEWLINE sz = self._recv_len()NEWLINE topic_len = int.from_bytes(self._read(2), 'big')NEWLINE topic = self._read(topic_len)NEWLINE sz -= topic_len + 2NEWLINE if op & 6: # QoS level > 0NEWLINE pid = int.from_bytes(self._read(2), 'big')NEWLINE sz -= 2NEWLINE msg = self._read(sz) if sz else b''NEWLINE retained = op & 0x01NEWLINE dup = op & 0x08NEWLINE self.cb(topic, msg)#, bool(retained), bool(dup))NEWLINE self.last_cpacket = ticks_ms()NEWLINE if op & 6 == 2: # QoS==1NEWLINE self._write(b"\x40\x02") # Send PUBACKNEWLINE self._write(pid.to_bytes(2, 'big'))NEWLINE elif op & 6 == 4: # QoS==2NEWLINE raise NotImplementedError()NEWLINE elif op & 6 == 6: # 3.3.1.2 QoS - Reserved – must not be usedNEWLINE raise MQTTException(-1)NEWLINENEWLINE def wait_msg(self):NEWLINE """NEWLINE This method waits for a message from the server.NEWLINE Compatibility with previous versions.NEWLINE It is recommended not to use this method. Set socket_time=None instead.NEWLINE """NEWLINE st_old = self.socket_timeoutNEWLINE self.socket_timeout = NoneNEWLINE out = self.check_msg()NEWLINE self.socket_timeout = st_oldNEWLINE return # pylint:disable=no-memberNEWLINEfrom time import sleepNEWLINEfrom typing import ListNEWLINENEWLINEfrom dagster import Field, Output, opNEWLINEfrom dagster.core.definitions.decorators.graph import graphNEWLINEfrom dagster.core.definitions.output import OutNEWLINENEWLINENEWLINE@opNEWLINEdef sleeper(context, units: List[int]) -> int:NEWLINE tot = 0NEWLINE for sec in units:NEWLINE context.log.info("Sleeping for {} seconds".format(sec))NEWLINE sleep(sec)NEWLINE tot += secNEWLINENEWLINE return totNEWLINENEWLINENEWLINE@op(NEWLINE config_schema=[int],NEWLINE out={NEWLINE "out_1": Out(List[int]),NEWLINE "out_2": Out(List[int]),NEWLINE "out_3": Out(List[int]),NEWLINE "out_4": Out(List[int]),NEWLINE },NEWLINE)NEWLINEdef giver(context):NEWLINE units = context.op_configNEWLINE queues: List[List[int]] = [[], [], [], []]NEWLINE for i, sec in enumerate(units):NEWLINE queues[i % 4].append(sec)NEWLINENEWLINE return queues[0], queues[1], queues[2], queues[3]NEWLINENEWLINENEWLINE@op(NEWLINE config_schema={"fail": Field(bool, is_required=False, default_value=False)},NEWLINE out=Out(int, is_required=False),NEWLINE)NEWLINEdef total(context, in_1, in_2, in_3, in_4):NEWLINE result = in_1 + in_2 + in_3 + in_4NEWLINE if context.op_config["fail"]:NEWLINE yield Output(result, "result")NEWLINE # skip the failing opNEWLINE context.log.info(str(result))NEWLINENEWLINENEWLINE@opNEWLINEdef will_fail(i):NEWLINE raise Exception(i)NEWLINENEWLINENEWLINE@graph(NEWLINE description=("Demo diamond-shaped graph that has four-path parallel structure of ops."),NEWLINE)NEWLINEdef sleepy():NEWLINE giver_res = giver()NEWLINENEWLINE will_fail(NEWLINE total(NEWLINE in_1=sleeper(units=giver_res.out_1),NEWLINE in_2=sleeper(units=giver_res.out_2),NEWLINE in_3=sleeper(units=giver_res.out_3),NEWLINE in_4=sleeper(units=giver_res.out_4),NEWLINE )NEWLINE )NEWLINENEWLINENEWLINEsleepy_job = sleepy.to_job(NEWLINE config={NEWLINE "ops": {"giver": {"config": [2, 2, 2, 2]}},NEWLINE },NEWLINE)NEWLINE #!/usr/bin/env pythonNEWLINEimport argparseNEWLINEimport networkx as nxNEWLINEimport numpy as npNEWLINEimport matplotlib as mplNEWLINEimport matplotlib.pyplot as pltNEWLINEfrom matplotlib import rcNEWLINEimport prmfNEWLINEimport prmf.plotNEWLINErc('text', usetex=True)NEWLINENEWLINEDPI = prmf.plot.DPINEWLINEEPSILON = np.finfo(np.float32).epsNEWLINENEWLINEdef project(w, G):NEWLINE inds = []NEWLINE for node in G:NEWLINE inds.append(node)NEWLINE inds = sorted(inds)NEWLINE return w[inds]NEWLINENEWLINEdef manifold_penalty(w, G):NEWLINE L = nx.laplacian_matrix(G).todense()NEWLINE w = project(w, G)NEWLINE return L.dot(w).dot(w)NEWLINENEWLINEdef ignore_penalty(w, G):NEWLINE # node identifiers are indexesNEWLINE rv = 0.0NEWLINE w = project(w, G)NEWLINE for i in range(w.shape[0]):NEWLINE rv += 1 / (w[i] + 1)NEWLINE return rvNEWLINENEWLINEif __name__ == "__main__":NEWLINE parser = argparse.ArgumentParser()NEWLINE parser.add_argument("--outfile")NEWLINE args = parser.parse_args()NEWLINENEWLINE fig = plt.figure()NEWLINE fig = plt.figure(figsize=(1000/DPI, 500/DPI), dpi=DPI)NEWLINENEWLINE gs = mpl.gridspec.GridSpec(1, 5, width_ratios=[1,5,1,1,5])NEWLINE ax1 = plt.subplot(gs[0,0])NEWLINE ax2 = plt.subplot(gs[0,1])NEWLINE #ax3 = plt.subplot(gs[0,2])NEWLINE ax4 = plt.subplot(gs[0,3])NEWLINE ax5 = plt.subplot(gs[0,4])NEWLINENEWLINE # graph defined on 2-NEWLINE order = 7NEWLINE nodelist = list(range(order))NEWLINE G = nx.path_graph(order)NEWLINE G.remove_node(0)NEWLINE G.remove_node(1)NEWLINE #G.add_edge(3,6)NEWLINENEWLINE # no penalty because smoothNEWLINE data1 = np.array([0.8, 0.9, 0.0, 0.0, 0.0, 0.0, 0.0])NEWLINE data1[data1 == 0] = EPSILONNEWLINE vmin = 0.0NEWLINE vmax = 1.0NEWLINE prmf.plot.plot_vec(data1, ax1, aspect=3, vmin=vmin, vmax=vmax)NEWLINENEWLINE man_pen = manifold_penalty(data1, G)[0,0]NEWLINE title1 = "$w^T L w = {:1.3f}$".format(man_pen)NEWLINENEWLINE # introduce penalty term for above dataNEWLINE man_pen = manifold_penalty(data1, G)[0,0]NEWLINE ign_pen = ignore_penalty(data1, G)NEWLINE title2 = r'$w^T L w + \sum_L \frac{1}{w_L + 1} = ' + '{:1.3f}'.format(man_pen + ign_pen) + r'$'NEWLINENEWLINE title = title1 + '\n' + title2NEWLINE pos = prmf.plot.plot_graph(G, ax2, title=title, title_fontsize=24, title_y=1.08)NEWLINE #prmf.plot.plot_graph(G, ax3, pos=pos, title=title)NEWLINENEWLINE # penalty because not smooth on 2-NEWLINE data2 = np.array([0.0, 0.1, 0.8, 0.9, 0.8, 0.9, 0.7])NEWLINE data2[data2 == 0] = EPSILONNEWLINE prmf.plot.plot_vec(data2, ax4, aspect=3, vmin=vmin, vmax=vmax)NEWLINENEWLINE man_pen = manifold_penalty(data2, G)[0,0]NEWLINE ign_pen = ignore_penalty(data2, G)NEWLINE title = r'$w^T L w + \sum_L \frac{1}{w_L + 1} = ' + '{:1.3f}'.format(man_pen + ign_pen) + '$'NEWLINE prmf.plot.plot_graph(G, ax5, pos=pos, title=title, title_fontsize=24, title_y=1.08)NEWLINENEWLINE plt.savefig(args.outfile, bbox_inches='tight')NEWLINE from Find_the_last_Fibonacci_digit_hardcore_version_6_kyu import last_fib_digitNEWLINEimport unittestNEWLINENEWLINEclass Fibonacci(unittest.TestCase):NEWLINE def test_1(self):NEWLINE n = 7000006NEWLINE result = 3NEWLINE self.assertEqual(last_fib_digit(n), result)NEWLINE def test_1(self):NEWLINE n = 9000000008NEWLINE result = 4NEWLINE self.assertEqual(last_fib_digit(n), result) NEWLINENEWLINEif __name__ == "__main__":NEWLINE unittest.main() #!/usr/bin/env pythonNEWLINENEWLINEimport scipy as spNEWLINEimport netCDF4 as ncNEWLINEfrom scipy import interpolateNEWLINENEWLINE#gi=nc.Dataset('/discover/nobackup/yvikhlia/coupled/Forcings/a288x181_o720x410/INPUT/grid_spec.nc')NEWLINE#loni=gi.variables['x_T'][:]; lati=gi.variables['y_T'][:]NEWLINE#jm,im=loni.shapeNEWLINENEWLINEloni,lati=sp.meshgrid(sp.arange(-179.875,180,0.25),sp.arange(-89.875,90,0.25))NEWLINEloni[loni>79.875]-=360.NEWLINEjm,im=720,1440NEWLINENEWLINEvlist=[]NEWLINEvlist.append(('head','f4',16))NEWLINEvlist.append(('h1','i4',1))NEWLINEvlist.append(('kpar','f4',(jm,im)))NEWLINEvlist.append(('h2','i4',1))NEWLINENEWLINE#a=sp.memmap('/discover/nobackup/yvikhlia/coupled/Forcings/a288x181_o720x410/SEAWIFS_KPAR_mon_clim.720x410',dtype=vlist,mode='r')NEWLINEa=sp.memmap('/discover/nobackup/projects/gmao/share/dao_ops/fvInput/g5gcm/bcs/realtime/SST/1440x720/SEAWIFS_KPAR_mon_clim.1440x720',dtype=vlist,mode='r')NEWLINENEWLINE#go=nc.Dataset('/home/yvikhlya/nobackup/coupled/4_0_beta10/GEOSagcm/src/GEOSgcs_GridComp/GEOSgcm_GridComp/GEOSagcm_GridComp/GEOSphysics_GridComp/GEOSsurface_GridComp/Shared/Raster/data/MOM/1440x1080/grid_spec.nc')NEWLINEgo=nc.Dataset('/home/yvikhlia/nobackup/coupled/Forcings/MOM6/CF0090x6C_TM0360xTM0210/INPUT/ocean_hgrid.nc')NEWLINE#lono=go.variables['x_T'][:]; lato=go.variables['y_T'][:]NEWLINElono=go.variables['x'][1::2,1::2]; lato=go.variables['y'][1::2,1::2]NEWLINEjm,im=lono.shapeNEWLINENEWLINEvlist=[]NEWLINEvlist.append(('head','f4',16))NEWLINEvlist.append(('h1','i4',1))NEWLINEvlist.append(('kpar','f4',(jm,im)))NEWLINEvlist.append(('h2','i4',1))NEWLINEb=sp.zeros(14,dtype=vlist)NEWLINENEWLINEfor i,x in enumerate(a):NEWLINE print iNEWLINE xx=x['kpar'][:]NEWLINE b[i]['head'][:]=x['head'][:]NEWLINE b[i]['h1']=im*jm*4NEWLINE b[i]['kpar'][:]=interpolate.griddata(zip(loni.flatten(),lati.flatten()),xx.flatten(),(lono,lato))NEWLINE b[i]['h2']=im*jm*4NEWLINENEWLINEb['head'][:,13]=im; b['head'][:,14]=jmNEWLINEb['kpar'][sp.isnan(b['kpar'])]=1.0NEWLINEb['kpar'][:,1060:,:]=1.0NEWLINEb.tofile('SEAWIFS_KPAR_mon_clim.360x210')NEWLINE from django.conf import settingsNEWLINEfrom rest_framework.routers import DefaultRouter, SimpleRouterNEWLINEfrom django.urls import pathNEWLINEfrom scrape_imdb.movies.views import MovieSerializerView, scrape_moviesNEWLINENEWLINEfrom scrape_imdb.users.api.views import UserViewSetNEWLINENEWLINEif settings.DEBUG:NEWLINE router = DefaultRouter()NEWLINEelse:NEWLINE router = SimpleRouter()NEWLINENEWLINErouter.register("users", UserViewSet)NEWLINErouter.register("movies", MovieSerializerView)NEWLINENEWLINEapp_name = "api"NEWLINEurlpatterns = router.urlsNEWLINENEWLINEurlpatterns += [path("utils/scrape_movies", scrape_movies)]NEWLINE import osNEWLINENEWLINEimport torchNEWLINEimport torch.nn as nnNEWLINEimport torch.nn.functional as FNEWLINEimport torchvisionNEWLINEimport torchvision.datasets as datasetsNEWLINEimport torchvision.transforms as transformsNEWLINEfrom pl_bolts.datamodules import CIFAR10DataModuleNEWLINEfrom pl_bolts.callbacks import PrintTableMetricsCallbackNEWLINEfrom pl_bolts.transforms.dataset_normalizations import cifar10_normalizationNEWLINEfrom pytorch_lightning import LightningModule, seed_everything, TrainerNEWLINEfrom pytorch_lightning.callbacks import LearningRateMonitorNEWLINEfrom pytorch_lightning.loggers import TensorBoardLogger, MLFlowLoggerNEWLINEfrom pytorch_lightning.callbacks import CallbackNEWLINEfrom pytorch_lightning.callbacks import EarlyStopping, ModelCheckpointNEWLINEfrom torch.optim.lr_scheduler import OneCycleLRNEWLINEfrom torch.optim.swa_utils import AveragedModel, update_bnNEWLINEfrom torchmetrics.functional import accuracyNEWLINEimport sysNEWLINEsys.path.append("../../")NEWLINEfrom autotorch.models.network import init_networkNEWLINEfrom autotorch.autoptl.custom_trainer import CustomTrainerNEWLINENEWLINEseed_everything(7)NEWLINENEWLINEPATH_DATASETS = os.environ.get(NEWLINE '/media/robin/DATA/datatsets/image_data/cifar10')NEWLINEAVAIL_GPUS = min(1, torch.cuda.device_count())NEWLINEBATCH_SIZE = 16 if AVAIL_GPUS else 32NEWLINENUM_WORKERS = int(os.cpu_count() / 2)NEWLINENEWLINEtrain_transforms = torchvision.transforms.Compose([NEWLINE torchvision.transforms.RandomResizedCrop(32),NEWLINE torchvision.transforms.RandomHorizontalFlip(),NEWLINE torchvision.transforms.ToTensor(),NEWLINE cifar10_normalization(),NEWLINE])NEWLINENEWLINEtest_transforms = torchvision.transforms.Compose([NEWLINE torchvision.transforms.RandomResizedCrop(32),NEWLINE torchvision.transforms.ToTensor(),NEWLINE cifar10_normalization(),NEWLINE])NEWLINENEWLINEcifar10_dm = CIFAR10DataModule(NEWLINE data_dir=PATH_DATASETS,NEWLINE batch_size=BATCH_SIZE,NEWLINE num_workers=NUM_WORKERS,NEWLINE train_transforms=train_transforms,NEWLINE test_transforms=test_transforms,NEWLINE val_transforms=test_transforms,NEWLINE)NEWLINENEWLINE# Data loading codeNEWLINEroot_dir = '/media/robin/DATA/datatsets/image_data/shopee-iet/images'NEWLINEtraindir = os.path.join(root_dir, 'train')NEWLINEvaldir = os.path.join(root_dir, 'val')NEWLINEnormalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],NEWLINE std=[0.229, 0.224, 0.225])NEWLINENEWLINEtrain_dataset = datasets.ImageFolder(NEWLINE traindir,NEWLINE transforms.Compose([NEWLINE transforms.RandomResizedCrop(224),NEWLINE transforms.RandomHorizontalFlip(),NEWLINE transforms.ToTensor(),NEWLINE normalize,NEWLINE ]))NEWLINENEWLINEtrain_sampler = NoneNEWLINEtrain_loader = torch.utils.data.DataLoader(train_dataset,NEWLINE batch_size=32,NEWLINE shuffle=(train_sampler is None),NEWLINE num_workers=0,NEWLINE pin_memory=True,NEWLINE sampler=train_sampler)NEWLINENEWLINEval_dataset = datasets.ImageFolder(NEWLINE valdir,NEWLINE transforms.Compose([NEWLINE transforms.Resize(256),NEWLINE transforms.CenterCrop(224),NEWLINE transforms.ToTensor(),NEWLINE normalize,NEWLINE ]))NEWLINENEWLINEval_loader = torch.utils.data.DataLoader(val_dataset,NEWLINE batch_size=32,NEWLINE shuffle=False,NEWLINE num_workers=0,NEWLINE pin_memory=True)NEWLINENEWLINENEWLINEdef create_model(model_name):NEWLINE model = torchvision.models.resnet18(pretrained=False, num_classes=4)NEWLINE # model = init_network(model_name, num_class=10, pretrained=True)NEWLINE # model.conv1 = nn.Conv2d(3,NEWLINE # 64,NEWLINE # kernel_size=(3, 3),NEWLINE # stride=(1, 1),NEWLINE # padding=(1, 1),NEWLINE # bias=False)NEWLINE # model.maxpool = nn.Identity()NEWLINE return modelNEWLINENEWLINENEWLINEclass LitResnet(LightningModule):NEWLINE def __init__(self, lr=0.05):NEWLINE super().__init__()NEWLINENEWLINE self.save_hyperparameters()NEWLINE self.model = create_model('resnet18')NEWLINENEWLINE def forward(self, x):NEWLINE out = self.model(x)NEWLINE return F.log_softmax(out, dim=1)NEWLINENEWLINE def training_step(self, batch, batch_idx):NEWLINE x, y = batchNEWLINE y_hat = self.model(x)NEWLINE loss = F.cross_entropy(y_hat, y)NEWLINENEWLINE # logs metrics for each training_step,NEWLINE # and the average across the epoch, to the progress bar and loggerNEWLINE self.log('train_loss',NEWLINE loss,NEWLINE on_step=True,NEWLINE on_epoch=True,NEWLINE prog_bar=True,NEWLINE logger=True,NEWLINE sync_dist=True)NEWLINE return lossNEWLINENEWLINE def evaluate(self, batch, stage=None):NEWLINE x, y = batchNEWLINE logits = self(x)NEWLINE loss = F.nll_loss(logits, y)NEWLINE preds = torch.argmax(logits, dim=1)NEWLINE acc = accuracy(preds, y)NEWLINENEWLINE if stage:NEWLINE self.log(f'{stage}_loss', loss, prog_bar=True)NEWLINE self.log(f'{stage}_acc', acc, prog_bar=True)NEWLINENEWLINE def validation_step(self, batch, batch_idx):NEWLINE self.evaluate(batch, 'val')NEWLINENEWLINE # def test_step(self, batch, batch_idx):NEWLINE # self.evaluate(batch, 'test')NEWLINENEWLINE def test_step(self, batch, batch_idx):NEWLINE x, y = batchNEWLINE # implement your ownNEWLINE logits = self(x)NEWLINE loss = F.nll_loss(logits, y)NEWLINE preds = torch.argmax(logits, dim=1)NEWLINE acc = accuracy(preds, y)NEWLINE # log the outputs!NEWLINE self.log_dict({'test_loss': loss, 'test_acc': acc})NEWLINENEWLINE def configure_optimizers(self):NEWLINE optimizer = torch.optim.SGD(NEWLINE self.parameters(),NEWLINE lr=self.hparams.lr,NEWLINE momentum=0.9,NEWLINE weight_decay=5e-4,NEWLINE )NEWLINE steps_per_epoch = 45000 // BATCH_SIZENEWLINE scheduler_dict = {NEWLINE 'scheduler':NEWLINE OneCycleLR(NEWLINE optimizer,NEWLINE 0.1,NEWLINE epochs=self.trainer.max_epochs,NEWLINE steps_per_epoch=steps_per_epoch,NEWLINE ),NEWLINE 'interval':NEWLINE 'step',NEWLINE }NEWLINENEWLINE return {NEWLINE 'optimizer': optimizer,NEWLINE 'lr_scheduler': scheduler_dict,NEWLINE }NEWLINENEWLINE def configure_callbacks(self):NEWLINE checkpoint = ModelCheckpoint(monitor="val_loss")NEWLINE return [checkpoint]NEWLINENEWLINENEWLINEclass PrintCallback(Callback):NEWLINE def on_train_start(self, trainer, pl_module):NEWLINE print("Training is started!")NEWLINENEWLINE def on_train_end(self, trainer, pl_module):NEWLINE print("Training is done.")NEWLINENEWLINENEWLINEearly_stop_callback = EarlyStopping(monitor='val_acc',NEWLINE min_delta=0.00,NEWLINE patience=3,NEWLINE verbose=False,NEWLINE mode='max')NEWLINENEWLINEmodel = LitResnet(lr=0.05)NEWLINEmodel.datamodule = cifar10_dmNEWLINEtrainer = CustomTrainer(NEWLINE progress_bar_refresh_rate=50,NEWLINE log_every_n_steps=1,NEWLINE log_gpu_memory='all',NEWLINE max_epochs=10,NEWLINE gpus=AVAIL_GPUS,NEWLINE sync_batchnorm=True,NEWLINE limit_train_batches=1.0,NEWLINE checkpoint_callback=True,NEWLINE check_val_every_n_epoch=1,NEWLINE precision=16,NEWLINE profiler="simple",NEWLINE val_check_interval=1.0,NEWLINE weights_summary='top',NEWLINE auto_scale_batch_size=True,NEWLINE benchmark=True,NEWLINE weights_save_path='lightning_logs/',NEWLINE default_root_dir=os.getcwd(),NEWLINE max_time={NEWLINE "days": 1,NEWLINE "hours": 5NEWLINE },NEWLINE logger=[NEWLINE TensorBoardLogger(save_dir='lightning_logs/',NEWLINE version="0",NEWLINE name='resnet'),NEWLINE MLFlowLogger(save_dir='mlflow_logs/')NEWLINE ],NEWLINE callbacks=[NEWLINE LearningRateMonitor(logging_interval='step'),NEWLINE PrintTableMetricsCallback(),NEWLINE early_stop_callback,NEWLINE ],NEWLINE)NEWLINENEWLINE# trainer.fit(model, cifar10_dm)NEWLINE# trainer.test(model, datamodule=cifar10_dm)NEWLINENEWLINEtrainer.fit(model, train_dataloader=train_loader, val_dataloaders=val_loader)NEWLINEtrainer.test(model, val_loader)NEWLINENEWLINE try:NEWLINE from django.conf.urls import url, includeNEWLINEexcept ImportError:NEWLINE from django.urls import url, includeNEWLINENEWLINEurlpatterns = [NEWLINE url(r'^', include('notify.urls', namespace='notifications')),NEWLINE]NEWLINE ## @fileNEWLINE# This file contained the parser for define sections in INF file NEWLINE#NEWLINE# Copyright (c) 2011, Intel Corporation. All rights reserved.
NEWLINE#NEWLINE# This program and the accompanying materials are licensed and made available NEWLINE# under the terms and conditions of the BSD License which accompanies this NEWLINE# distribution. The full text of the license may be found at NEWLINE# http://opensource.org/licenses/bsd-license.phpNEWLINE#NEWLINE# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.NEWLINE#NEWLINENEWLINE'''NEWLINEInfDefineSectionParserNEWLINE'''NEWLINE##NEWLINE# Import ModulesNEWLINE#NEWLINEimport reNEWLINENEWLINEfrom Library import DataType as DTNEWLINEfrom Library import GlobalDataNEWLINEfrom Library.Parsing import MacroParserNEWLINEfrom Library.Misc import GetSplitValueListNEWLINEfrom Library.ParserValidate import IsValidArchNEWLINEfrom Object.Parser.InfCommonObject import InfLineCommentObjectNEWLINEfrom Object.Parser.InfDefineObject import InfDefMemberNEWLINEfrom Parser.InfParserMisc import InfExpandMacroNEWLINEfrom Object.Parser.InfMisc import ErrorInInfNEWLINEfrom Logger import StringTable as STNEWLINEfrom Parser.InfParserMisc import InfParserSectionRootNEWLINENEWLINE## __GetValidateArchListNEWLINE# NEWLINE#NEWLINEdef GetValidateArchList(LineContent):NEWLINE NEWLINE TempArch = ''NEWLINE ArchList = []NEWLINE ValidateAcrhPatten = re.compile(r"^\s*#\s*VALID_ARCHITECTURES\s*=\s*.*$", re.DOTALL)NEWLINE NEWLINE if ValidateAcrhPatten.match(LineContent):NEWLINE TempArch = GetSplitValueList(LineContent, DT.TAB_EQUAL_SPLIT, 1)[1]NEWLINE NEWLINE TempArch = GetSplitValueList(TempArch, '(', 1)[0]NEWLINE NEWLINE ArchList = re.split('\s+', TempArch)NEWLINE NewArchList = []NEWLINE for Arch in ArchList:NEWLINE if IsValidArch(Arch):NEWLINE NewArchList.append(Arch)NEWLINE NEWLINE ArchList = NewArchListNEWLINE NEWLINE return ArchList NEWLINENEWLINEclass InfDefinSectionParser(InfParserSectionRoot):NEWLINE def InfDefineParser(self, SectionString, InfSectionObject, FileName, SectionComment):NEWLINE NEWLINE if SectionComment:NEWLINE passNEWLINE #NEWLINE # Parser Defines section content and fill self._ContentList dict.NEWLINE #NEWLINE StillCommentFalg = FalseNEWLINE HeaderComments = []NEWLINE SectionContent = ''NEWLINE ArchList = []NEWLINE _ContentList = []NEWLINE _ValueList = []NEWLINE #NEWLINE # Add WORKSPACE to global Marco dict.NEWLINE #NEWLINE self.FileLocalMacros['WORKSPACE'] = GlobalData.gWORKSPACENEWLINE NEWLINE for Line in SectionString:NEWLINE LineContent = Line[0]NEWLINE LineNo = Line[1]NEWLINE TailComments = ''NEWLINE LineComment = NoneNEWLINE NEWLINE LineInfo = ['', -1, '']NEWLINE LineInfo[0] = FileNameNEWLINE LineInfo[1] = LineNoNEWLINE LineInfo[2] = LineContentNEWLINE NEWLINE if LineContent.strip() == '':NEWLINE continueNEWLINE #NEWLINE # The first time encountered VALIDATE_ARCHITECHERS will be considered as support arch list.NEWLINE #NEWLINE if not ArchList:NEWLINE ArchList = GetValidateArchList(LineContent)NEWLINENEWLINE #NEWLINE # Parser CommentNEWLINE #NEWLINE if LineContent.strip().startswith(DT.TAB_COMMENT_SPLIT):NEWLINE #NEWLINE # Last line is comments, and this line go on.NEWLINE #NEWLINE if StillCommentFalg:NEWLINE HeaderComments.append(Line)NEWLINE SectionContent += LineContent + DT.END_OF_LINENEWLINE continueNEWLINE #NEWLINE # First time encounter comment NEWLINE #NEWLINE else:NEWLINE #NEWLINE # Clear original dataNEWLINE #NEWLINE HeaderComments = []NEWLINE HeaderComments.append(Line)NEWLINE StillCommentFalg = TrueNEWLINE SectionContent += LineContent + DT.END_OF_LINENEWLINE continueNEWLINE else:NEWLINE StillCommentFalg = FalseNEWLINE NEWLINE if len(HeaderComments) >= 1:NEWLINE LineComment = InfLineCommentObject()NEWLINE LineCommentContent = ''NEWLINE for Item in HeaderComments:NEWLINE LineCommentContent += Item[0] + DT.END_OF_LINENEWLINE LineComment.SetHeaderComments(LineCommentContent)NEWLINE NEWLINE #NEWLINE # Find Tail comment.NEWLINE #NEWLINE if LineContent.find(DT.TAB_COMMENT_SPLIT) > -1:NEWLINE TailComments = LineContent[LineContent.find(DT.TAB_COMMENT_SPLIT):]NEWLINE LineContent = LineContent[:LineContent.find(DT.TAB_COMMENT_SPLIT)]NEWLINE if LineComment == None:NEWLINE LineComment = InfLineCommentObject()NEWLINE LineComment.SetTailComments(TailComments)NEWLINE NEWLINE #NEWLINE # Find MacroNEWLINE #NEWLINE Name, Value = MacroParser((LineContent, LineNo), NEWLINE FileName, NEWLINE DT.MODEL_META_DATA_HEADER, NEWLINE self.FileLocalMacros)NEWLINE if Name != None:NEWLINE self.FileLocalMacros[Name] = ValueNEWLINE continue NEWLINENEWLINE #NEWLINE # Replace with [Defines] section MacroNEWLINE #NEWLINE LineContent = InfExpandMacro(LineContent, NEWLINE (FileName, LineContent, LineNo), NEWLINE self.FileLocalMacros, NEWLINE None, True)NEWLINE NEWLINE SectionContent += LineContent + DT.END_OF_LINENEWLINE NEWLINE TokenList = GetSplitValueList(LineContent, DT.TAB_EQUAL_SPLIT, 1)NEWLINE if len(TokenList) < 2:NEWLINE ErrorInInf(ST.ERR_INF_PARSER_DEFINE_ITEM_NO_VALUE,NEWLINE LineInfo=LineInfo) NEWLINE _ValueList[0:len(TokenList)] = TokenListNEWLINE if not _ValueList[0]:NEWLINE ErrorInInf(ST.ERR_INF_PARSER_DEFINE_ITEM_NO_NAME,NEWLINE LineInfo=LineInfo)NEWLINE if not _ValueList[1]:NEWLINE ErrorInInf(ST.ERR_INF_PARSER_DEFINE_ITEM_NO_VALUE,NEWLINE LineInfo=LineInfo) NEWLINE NEWLINE Name, Value = _ValueList[0], _ValueList[1] NEWLINE NEWLINE InfDefMemberObj = InfDefMember(Name, Value)NEWLINE if (LineComment != None):NEWLINE InfDefMemberObj.Comments.SetHeaderComments(LineComment.GetHeaderComments())NEWLINE InfDefMemberObj.Comments.SetTailComments(LineComment.GetTailComments())NEWLINE NEWLINE InfDefMemberObj.CurrentLine.SetFileName(self.FullPath)NEWLINE InfDefMemberObj.CurrentLine.SetLineString(LineContent)NEWLINE InfDefMemberObj.CurrentLine.SetLineNo(LineNo)NEWLINE NEWLINE _ContentList.append(InfDefMemberObj)NEWLINE HeaderComments = []NEWLINE TailComments = ''NEWLINE NEWLINE #NEWLINE # Current Define section archsNEWLINE #NEWLINE if not ArchList:NEWLINE ArchList = ['COMMON']NEWLINE NEWLINE InfSectionObject.SetAllContent(SectionContent) NEWLINE NEWLINE InfSectionObject.SetDefines(_ContentList, Arch=ArchList)NEWLINE # Copyright 2019 The Chromium Authors. All rights reserved.NEWLINE# Use of this source code is governed by a BSD-style license that can beNEWLINE# found in the LICENSE file.NEWLINENEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import print_functionNEWLINENEWLINEimport codecsNEWLINEimport csvNEWLINEimport gzipNEWLINEimport jsonNEWLINEimport loggingNEWLINENEWLINEfrom six.moves import map # pylint: disable=redefined-builtinNEWLINEfrom tracing_build import html2trace, trace2htmlNEWLINENEWLINEGZIP_FILENAME_SUFFIX = '.gz'NEWLINEHTML_FILENAME_SUFFIX = '.html'NEWLINEJSON_FILENAME_SUFFIX = '.json'NEWLINENEWLINETRACE_METADATA_ARG_NAME_MAP = {NEWLINE 'process_sort_index': 'sort_index',NEWLINE 'process_name': 'name'NEWLINE}NEWLINENEWLINENEWLINEdef LoadTraces(chrome_trace_filename):NEWLINE """Load traces from a file and return them as a python list.NEWLINENEWLINE There are several tools in tracing/bin that deal with reading traces from aNEWLINE file. None of them does exactly what we need here. In particular,NEWLINE merge_traces.LoadTrace will discard all traces but one if an HTML file hasNEWLINE several traces.NEWLINENEWLINE TODO(chiniforooshan): create a module for reading/writing different trace fileNEWLINE formats and make every other tool use that module.NEWLINE """NEWLINE traces = []NEWLINE if chrome_trace_filename.endswith(GZIP_FILENAME_SUFFIX):NEWLINE with gzip.open(chrome_trace_filename, 'rb') as f:NEWLINE traces.append(json.load(f))NEWLINE elif chrome_trace_filename.endswith(HTML_FILENAME_SUFFIX):NEWLINE with codecs.open(chrome_trace_filename, mode='r', encoding='utf-8') as f:NEWLINE traces = html2trace.ReadTracesFromHTMLFile(f)NEWLINE elif chrome_trace_filename.endswith(JSON_FILENAME_SUFFIX):NEWLINE with open(chrome_trace_filename, 'r') as f:NEWLINE traces.append(json.load(f))NEWLINE else:NEWLINE raise Exception('Unknown trace file suffix: %s', chrome_trace_filename)NEWLINE return list(map(_ConvertToDictIfNecessary, traces))NEWLINENEWLINENEWLINEdef WriteTraces(output_filename, traces):NEWLINE if output_filename.endswith(GZIP_FILENAME_SUFFIX):NEWLINE with gzip.open(output_filename, 'wb') as f:NEWLINE json.dump(_ConcatTraces(traces), f)NEWLINE elif output_filename.endswith(HTML_FILENAME_SUFFIX):NEWLINE with codecs.open(output_filename, mode='w', encoding='utf-8') as f:NEWLINE trace2html.WriteHTMLForTraceDataToFile(NEWLINE traces, 'Chrome trace with Snapdragon profiler data', f)NEWLINE elif output_filename.endswith(JSON_FILENAME_SUFFIX):NEWLINE with open(output_filename, 'w') as f:NEWLINE json.dump(_ConcatTraces(traces), f)NEWLINE else:NEWLINE raise Exception('Unknown trace file suffix: %s', output_filename)NEWLINENEWLINENEWLINEdef LoadCSV(csv_filename):NEWLINE with open(csv_filename, 'r') as csv_file:NEWLINE reader = csv.DictReader(csv_file, delimiter=',')NEWLINE for row in reader:NEWLINE yield rowNEWLINENEWLINENEWLINEdef AddSnapdragonProfilerData(traces, snapdragon_csv):NEWLINE clock_offset = NoneNEWLINE min_ts = NoneNEWLINE max_ts = 0NEWLINE max_pid = 0NEWLINE for trace in traces:NEWLINE should_use_timestamps_from_this_trace = FalseNEWLINE if 'metadata' in trace and 'clock-offset-since-epoch' in trace['metadata']:NEWLINE if clock_offset is not None:NEWLINE logging.warning('Found more than one clock offset')NEWLINE else:NEWLINE clock_offset = int(trace['metadata']['clock-offset-since-epoch'])NEWLINE should_use_timestamps_from_this_trace = TrueNEWLINE if 'traceEvents' in trace:NEWLINE for event in trace['traceEvents']:NEWLINE max_pid = max(max_pid, event['pid'], event['tid'])NEWLINE if should_use_timestamps_from_this_trace and event['ph'] != 'M':NEWLINE ts = event['ts']NEWLINE max_ts = max(ts + (event['dur'] if 'dur' in event else 0), max_ts)NEWLINE if min_ts is None or min_ts > ts:NEWLINE min_ts = tsNEWLINE if clock_offset is None:NEWLINE raise Exception('Cannot find clock offset in Chrome traces')NEWLINENEWLINE process_names = {}NEWLINE num_counter_events = 0NEWLINE events = []NEWLINE for row in snapdragon_csv:NEWLINE ts = int(row['TimestampRaw']) - clock_offsetNEWLINE if ts < min_ts or ts > max_ts:NEWLINE continueNEWLINE if row['Process'] not in process_names:NEWLINE max_pid += 1NEWLINE process_names[row['Process']] = max_pidNEWLINE events.append(_MetadataEvent(max_pid, 'process_sort_index', -7))NEWLINE events.append(_MetadataEvent(max_pid, 'process_name', row['Process']))NEWLINE pid = process_names[row['Process']]NEWLINE events.append(_CounterEvent(pid, ts, row['Metric'], row['Value']))NEWLINE num_counter_events += 1NEWLINE logging.info('Added %d counter events.', num_counter_events)NEWLINE traces.append({'traceEvents': events})NEWLINENEWLINENEWLINEdef _ConcatTraces(traces):NEWLINE # As long as at most one of the traces has a field with a non-list value, e.g.NEWLINE # a metadata field, we can trivially concat them.NEWLINE #NEWLINE # TODO(chiniforooshan): to support writing several traces with severalNEWLINE # metadata fields in a JSON file, we can write a simpleNEWLINE # trace_list_importer.html that treats each of them as a subtrace.NEWLINE #NEWLINE # Note: metadata fields should not be confused with metadata trace events.NEWLINE result = NoneNEWLINE for trace in traces:NEWLINE if result is None:NEWLINE result = trace.copy()NEWLINE continueNEWLINE for k, v in trace.items():NEWLINE if k in result:NEWLINE if not isinstance(v, list):NEWLINE raise Exception('Cannot concat two traces with non-list values 'NEWLINE '(e.g. two traces with metadata)')NEWLINE result[k].extend(v)NEWLINE else:NEWLINE result[k] = list(v) if isinstance(v, list) else vNEWLINE return resultNEWLINENEWLINENEWLINEdef _ConvertToDictIfNecessary(trace):NEWLINE return {'traceEvents': trace} if isinstance(trace, list) else traceNEWLINENEWLINENEWLINEdef _MetadataEvent(pid, name, value):NEWLINE if name not in TRACE_METADATA_ARG_NAME_MAP:NEWLINE raise Exception('Unknown metadata name: %s', name)NEWLINE arg_name = TRACE_METADATA_ARG_NAME_MAP[name]NEWLINE return {NEWLINE 'pid': pid,NEWLINE 'tid': pid,NEWLINE 'ts': 0,NEWLINE 'ph': 'M',NEWLINE 'cat': '__metadata',NEWLINE 'name': name,NEWLINE 'args': {arg_name: value}NEWLINE }NEWLINENEWLINENEWLINEdef _CounterEvent(pid, timestamp, name, value):NEWLINE if not isinstance(value, float):NEWLINE value = float(value)NEWLINE return {NEWLINE 'pid': pid,NEWLINE 'tid': pid,NEWLINE 'ts': timestamp,NEWLINE 'ph': 'C',NEWLINE 'name': name,NEWLINE 'args': {'Value': value}NEWLINE }NEWLINE import unittestNEWLINENEWLINEfrom cubes.sql.mapper import StarSchemaMapper, distill_namingNEWLINEfrom cubes.model import AttributeNEWLINENEWLINEfrom ..common import CubesTestCaseBase, create_providerNEWLINENEWLINEclass MapperTestCase(CubesTestCaseBase):NEWLINE def setUp(self):NEWLINE super(MapperTestCase, self).setUp()NEWLINENEWLINE self.provider = create_provider("mapper_test.json")NEWLINENEWLINE self.cube = self.provider.cube("sales")NEWLINE naming = {NEWLINE "dimension_prefix": "dim_",NEWLINE "dimension_suffix": "_dim"NEWLINE }NEWLINE self.naming = distill_naming(naming)NEWLINE self.mapper = StarSchemaMapper(self.cube, self.naming)NEWLINENEWLINE self.mapper.mappings = {NEWLINE "product.name": "product.product_name",NEWLINE "product.category": "product.category_id",NEWLINE "subcategory.name.en": "subcategory.subcategory_name_en",NEWLINE "subcategory.name.sk": "subcategory.subcategory_name_sk"NEWLINE }NEWLINENEWLINE def test_logical_reference(self):NEWLINENEWLINE dim = self.provider.dimension("date")NEWLINE attr = Attribute("month", dimension=dim)NEWLINE self.assertEqual("date.month", attr.ref)NEWLINENEWLINE dim = self.provider.dimension("product")NEWLINE attr = Attribute("category", dimension=dim)NEWLINE self.assertEqual("product.category", attr.ref)NEWLINENEWLINE dim = self.provider.dimension("flag")NEWLINE attr = Attribute("flag", dimension=dim)NEWLINE self.assertEqual("flag", attr.ref)NEWLINENEWLINE attr = Attribute("measure", dimension=None)NEWLINE self.assertEqual("measure", attr.ref)NEWLINENEWLINE def assertMapping(self, expected, logical_ref, mapper=None):NEWLINE """Create string reference by concatentanig table and column name.NEWLINE No schema is expected (is ignored)."""NEWLINENEWLINE attr = self.cube.attribute(logical_ref)NEWLINE mapper = mapper or self.mapperNEWLINE ref = mapper[attr]NEWLINE sref = ref[1] + "." + ref[2]NEWLINENEWLINE self.assertEqual(expected, sref)NEWLINENEWLINE def test_physical_refs_dimensions(self):NEWLINE """Testing correct default mappings of dimensions (with and withoutNEWLINE explicit default prefix) in physical references."""NEWLINENEWLINE # No dimension prefixNEWLINE self.mapper.naming.dimension_prefix = ""NEWLINE self.mapper.naming.dimension_suffix = ""NEWLINE self.assertMapping("date.year", "date.year")NEWLINE self.assertMapping("sales.flag", "flag")NEWLINE self.assertMapping("sales.amount", "amount")NEWLINENEWLINE # With prefixNEWLINE self.mapper.naming.dimension_prefix = "dm_"NEWLINE self.assertMapping("dm_date.year", "date.year")NEWLINE self.assertMapping("dm_date.month_name", "date.month_name")NEWLINE self.assertMapping("sales.flag", "flag")NEWLINE self.assertMapping("sales.amount", "amount")NEWLINENEWLINE def test_physical_refs_flat_dims(self):NEWLINE self.cube.fact = NoneNEWLINE self.assertMapping("sales.flag", "flag")NEWLINENEWLINE def test_physical_refs_facts(self):NEWLINE """Testing correct mappings of fact attributes in physical references"""NEWLINENEWLINE fact = self.cube.factNEWLINE self.cube.fact = NoneNEWLINE self.assertMapping("sales.amount", "amount")NEWLINE # self.assertEqual("sales.flag", sref("flag.flag"))NEWLINE self.cube.fact = factNEWLINENEWLINE def test_physical_refs_with_mappings_and_locales(self):NEWLINE """Testing mappings of mapped attributes and localized attributes inNEWLINE physical references"""NEWLINENEWLINE self.mapper.mappings = self.cube.mappingsNEWLINE # Test defaultsNEWLINE # Localized mapper is localizing to 'sk', non-localized mapper isNEWLINE # localizing to default 'en'NEWLINE #NEWLINE # Mapper with locale that we haveNEWLINE sk_mapper = StarSchemaMapper(self.cube, self.naming, locale="sk")NEWLINENEWLINE # Mapper with locale that we don't haveNEWLINE de_mapper = StarSchemaMapper(self.cube, self.naming, locale="de")NEWLINENEWLINE self.assertMapping("dim_date_dim.month_name", "date.month_name")NEWLINENEWLINE self.assertMapping("dim_category_dim.category_name_en",NEWLINE "product.category_name")NEWLINENEWLINE self.assertMapping("dim_category_dim.category_name_sk",NEWLINE "product.category_name", sk_mapper)NEWLINENEWLINE # This should default to 'en' since we don't have 'de' locale and theNEWLINE # 'en' locale is the default oneNEWLINE self.assertMapping("dim_category_dim.category_name_en",NEWLINE "product.category_name", de_mapper)NEWLINENEWLINE # Test with mappingNEWLINE self.assertMapping("dim_product_dim.product_name", "product.name")NEWLINE self.assertMapping("dim_product_dim.category_id", "product.category")NEWLINENEWLINE # The product name is not localized, we should get the same for anyNEWLINE # mapperNEWLINE self.assertMapping("dim_product_dim.product_name", "product.name",NEWLINE sk_mapper)NEWLINE self.assertMapping("dim_product_dim.product_name", "product.name",NEWLINE de_mapper)NEWLINENEWLINE self.assertMapping("dim_category_dim.subcategory_name_en",NEWLINE "product.subcategory_name")NEWLINE self.assertMapping("dim_category_dim.subcategory_name_sk",NEWLINE "product.subcategory_name",NEWLINE sk_mapper)NEWLINE self.assertMapping("dim_category_dim.subcategory_name_en",NEWLINE "product.subcategory_name",NEWLINE de_mapper)NEWLINENEWLINE from test_common import get_sample_layer, get_opsNEWLINEfrom nose.tools import assert_raisesNEWLINEimport tvmNEWLINENEWLINEdef test_set_tiling_wrong_inputs():NEWLINE layer = get_sample_layer()NEWLINE with assert_raises(Exception):NEWLINE # wrong iv nameNEWLINE layer.set_tiling("n", [4, 1, 1, 1])NEWLINENEWLINE with assert_raises(Exception):NEWLINE # wrong tiling lengthNEWLINE layer.set_tiling("N", [4, 1, 1, 1, 1])NEWLINENEWLINE with assert_raises(Exception):NEWLINE # wrong tiling valueNEWLINE layer.set_tiling("N", [4, 2, 1, 1])NEWLINENEWLINE # correct caseNEWLINE layer.set_tiling("N", [4, 1, 1, 1])NEWLINENEWLINENEWLINEdef test_set_tiling():NEWLINE layer = get_sample_layer()NEWLINE assert layer._loop_TCs["N_DRAM"] == 4NEWLINE assert layer._loop_TCs["N_SPM"] == 1NEWLINE assert layer._loop_TCs["N_RF"] == 1NEWLINE assert layer._loop_TCs["N_Spatial"] == 1NEWLINENEWLINE layer.set_tiling("N", [1, 1, 2, 2])NEWLINE assert layer._loop_TCs["N_DRAM"] == 1NEWLINE assert layer._loop_TCs["N_SPM"] == 1NEWLINE assert layer._loop_TCs["N_RF"] == 2NEWLINE assert layer._loop_TCs["N_Spatial"] == 2NEWLINENEWLINENEWLINEdef test_set_ordering():NEWLINE layer = get_sample_layer()NEWLINE new_order = ["M", "C", "Ox", "N", "Oy", "Fx", "Fy"]NEWLINE layer.set_ordering("DRAM", new_order)NEWLINE assert layer._loop_IVs["DRAM"] == [ x+"_DRAM" for x in new_order ]NEWLINENEWLINENEWLINEdef test_get_loop():NEWLINE layer = get_sample_layer()NEWLINE loop = layer._get_loop()NEWLINENEWLINENEWLINEdef test_get_stores():NEWLINE layer = get_sample_layer()NEWLINE stores = layer._get_stores()NEWLINE assert len(stores) == 1NEWLINE store = stores[0]NEWLINE assert isinstance(store, tvm.stmt.Store)NEWLINENEWLINE stores = layer._get_stores(pass_init=False)NEWLINE assert len(stores) == 2NEWLINE assert store in storesNEWLINE for store in stores:NEWLINE assert isinstance(store, tvm.stmt.Store)NEWLINENEWLINENEWLINEdef test_get_reads_writes():NEWLINE layer = get_sample_layer()NEWLINE reads, writes = layer._get_reads_writes()NEWLINE assert len(reads) == 3NEWLINE assert len(writes) == 1NEWLINE for read in reads:NEWLINE assert isinstance(read, tvm.expr.Load)NEWLINE for write in writes:NEWLINE assert isinstance(write, tvm.stmt.Store)NEWLINENEWLINENEWLINEdef test_get_reads_writes_of_operand():NEWLINE layer = get_sample_layer()NEWLINE reads, writes = layer._get_reads_writes_of_operand(layer._O.name)NEWLINE assert len(reads) == 1 and len(writes) == 1NEWLINE reads, writes = layer._get_reads_writes_of_operand(layer._W.name)NEWLINE assert len(reads) == 1 and len(writes) == 0NEWLINE reads, writes = layer._get_reads_writes_of_operand(layer._I.name)NEWLINE assert len(reads) == 1 and len(writes) == 0NEWLINENEWLINENEWLINEdef test_get_operands():NEWLINE layer = get_sample_layer()NEWLINE O_write, O_read, I, W = get_ops(layer)NEWLINE operands = layer._get_operands()NEWLINENEWLINE assert O_write in operands[layer._O.name]NEWLINE assert O_read in operands[layer._O.name]NEWLINE assert I in operands[layer._I.name]NEWLINE assert W in operands[layer._W.name]NEWLINENEWLINENEWLINEdef test_get_num_different_pixels():NEWLINE layer = get_sample_layer()NEWLINE reads, writes = layer._get_reads_writes_of_operand(layer._I.name)NEWLINE assert layer._get_num_different_pixels(reads[0], [1, 2, 2, 14, 14, 3, 3]) == 512NEWLINENEWLINENEWLINEdef test_get_index_vars():NEWLINE layer = get_sample_layer()NEWLINE O_write, O_read, I, W = get_ops(layer)NEWLINE assert layer._get_index_vars(O_write) == ["N", "M", "Ox", "Oy"]NEWLINE assert layer._get_index_vars(O_read) == ["N", "M", "Ox", "Oy"]NEWLINE assert set(layer._get_index_vars(I)) == set(["N", "C", "Ox", "Oy", "Fx", "Fy"])NEWLINE assert layer._get_index_vars(W) == ["M", "C", "Fx", "Fy"]NEWLINENEWLINENEWLINEdef test_get_index_exprs():NEWLINE layer = get_sample_layer()NEWLINE O_write, O_read, I, W = get_ops(layer)NEWLINE keys = ["n", "m", "c", "ox", "oy", "fx", "fy"]NEWLINE values = [ int(layer.get_TripCounts(key.title(), "loop") / layer.get_TripCounts(key.title(), "DRAM")) for key in layer.base_TCs ]NEWLINE local_vars = dict(zip(keys, values))NEWLINE assert layer._get_index_expr_evaluated(I, 0, local_vars) == 16NEWLINE assert layer._get_index_expr_evaluated(I, 1, local_vars) == 16NEWLINE assert layer._get_index_expr_evaluated(I, 2, local_vars) == 32NEWLINE assert layer._get_index_expr_evaluated(I, 3, local_vars) == 1NEWLINENEWLINENEWLINEdef test_get_tensor_from_name():NEWLINE layer = get_sample_layer()NEWLINE assert layer._get_tensor_from_name("I") == layer._INEWLINE assert layer._get_tensor_from_name("O") == layer._ONEWLINE assert layer._get_tensor_from_name("W") == layer._W """Builder class used to transform a mypy AST to the IR form.NEWLINENEWLINEThe IRBuilder class maintains transformation state and provides accessNEWLINEto various helpers used to implement the transform.NEWLINENEWLINEThe top-level transform control logic is in mypyc.irbuild.main.NEWLINENEWLINEmypyc.irbuild.visitor.IRBuilderVisitor is used to dispatch based on mypyNEWLINEAST node type to code that actually does the bulk of the work. ForNEWLINEexample, expressions are transformed in mypyc.irbuild.expression andNEWLINEfunctions are transformed in mypyc.irbuild.function.NEWLINE"""NEWLINENEWLINEfrom mypyc.irbuild.prepare import RegisterImplInfoNEWLINEfrom typing import Callable, Dict, List, Tuple, Optional, Union, Sequence, Set, AnyNEWLINEfrom typing_extensions import overloadNEWLINEfrom mypy.backports import OrderedDictNEWLINENEWLINEfrom mypy.build import GraphNEWLINEfrom mypy.nodes import (NEWLINE MypyFile, SymbolNode, Statement, OpExpr, IntExpr, NameExpr, LDEF, Var, UnaryExpr,NEWLINE CallExpr, IndexExpr, Expression, MemberExpr, RefExpr, Lvalue, TupleExpr,NEWLINE TypeInfo, Decorator, OverloadedFuncDef, StarExpr, ComparisonExpr, GDEF,NEWLINE ArgKind, ARG_POS, ARG_NAMED, FuncDef,NEWLINE)NEWLINEfrom mypy.types import (NEWLINE Type, Instance, TupleType, UninhabitedType, get_proper_typeNEWLINE)NEWLINEfrom mypy.maptype import map_instance_to_supertypeNEWLINEfrom mypy.visitor import ExpressionVisitor, StatementVisitorNEWLINEfrom mypy.util import split_targetNEWLINENEWLINEfrom mypyc.common import TEMP_ATTR_NAME, SELF_NAMENEWLINEfrom mypyc.irbuild.prebuildvisitor import PreBuildVisitorNEWLINEfrom mypyc.ir.ops import (NEWLINE BasicBlock, Integer, Value, Register, Op, Assign, Branch, Unreachable, TupleGet, GetAttr,NEWLINE SetAttr, LoadStatic, InitStatic, NAMESPACE_MODULE, RaiseStandardErrorNEWLINE)NEWLINEfrom mypyc.ir.rtypes import (NEWLINE RType, RTuple, RInstance, c_int_rprimitive, int_rprimitive, dict_rprimitive,NEWLINE none_rprimitive, is_none_rprimitive, object_rprimitive, is_object_rprimitive,NEWLINE str_rprimitive, is_tagged, is_list_rprimitive, is_tuple_rprimitive, c_pyssize_t_rprimitiveNEWLINE)NEWLINEfrom mypyc.ir.func_ir import FuncIR, INVALID_FUNC_DEF, RuntimeArg, FuncSignature, FuncDeclNEWLINEfrom mypyc.ir.class_ir import ClassIR, NonExtClassInfoNEWLINEfrom mypyc.primitives.registry import CFunctionDescription, function_opsNEWLINEfrom mypyc.primitives.list_ops import to_list, list_pop_last, list_get_item_unsafe_opNEWLINEfrom mypyc.primitives.dict_ops import dict_get_item_op, dict_set_item_opNEWLINEfrom mypyc.primitives.generic_ops import py_setattr_op, iter_op, next_opNEWLINEfrom mypyc.primitives.misc_ops import (NEWLINE import_op, check_unpack_count_op, get_module_dict_op, import_extra_args_opNEWLINE)NEWLINEfrom mypyc.crash import catch_errorsNEWLINEfrom mypyc.options import CompilerOptionsNEWLINEfrom mypyc.errors import ErrorsNEWLINEfrom mypyc.irbuild.nonlocalcontrol import (NEWLINE NonlocalControl, BaseNonlocalControl, LoopNonlocalControl, GeneratorNonlocalControlNEWLINE)NEWLINEfrom mypyc.irbuild.targets import (NEWLINE AssignmentTarget, AssignmentTargetRegister, AssignmentTargetIndex, AssignmentTargetAttr,NEWLINE AssignmentTargetTupleNEWLINE)NEWLINEfrom mypyc.irbuild.context import FuncInfo, ImplicitClassNEWLINEfrom mypyc.irbuild.mapper import MapperNEWLINEfrom mypyc.irbuild.ll_builder import LowLevelIRBuilderNEWLINEfrom mypyc.irbuild.util import is_constantNEWLINENEWLINENEWLINEclass IRVisitor(ExpressionVisitor[Value], StatementVisitor[None]):NEWLINE passNEWLINENEWLINENEWLINEclass UnsupportedException(Exception):NEWLINE passNEWLINENEWLINENEWLINESymbolTarget = Union[AssignmentTargetRegister, AssignmentTargetAttr]NEWLINENEWLINENEWLINEclass IRBuilder:NEWLINE def __init__(self,NEWLINE current_module: str,NEWLINE types: Dict[Expression, Type],NEWLINE graph: Graph,NEWLINE errors: Errors,NEWLINE mapper: Mapper,NEWLINE pbv: PreBuildVisitor,NEWLINE visitor: IRVisitor,NEWLINE options: CompilerOptions,NEWLINE singledispatch_impls: Dict[FuncDef, List[RegisterImplInfo]]) -> None:NEWLINE self.builder = LowLevelIRBuilder(current_module, mapper, options)NEWLINE self.builders = [self.builder]NEWLINE self.symtables: List[OrderedDict[SymbolNode, SymbolTarget]] = [OrderedDict()]NEWLINE self.runtime_args: List[List[RuntimeArg]] = [[]]NEWLINE self.function_name_stack: List[str] = []NEWLINE self.class_ir_stack: List[ClassIR] = []NEWLINENEWLINE self.current_module = current_moduleNEWLINE self.mapper = mapperNEWLINE self.types = typesNEWLINE self.graph = graphNEWLINE self.ret_types: List[RType] = []NEWLINE self.functions: List[FuncIR] = []NEWLINE self.classes: List[ClassIR] = []NEWLINE self.final_names: List[Tuple[str, RType]] = []NEWLINE self.callable_class_names: Set[str] = set()NEWLINE self.options = optionsNEWLINENEWLINE # These variables keep track of the number of lambdas, implicit indices, and implicitNEWLINE # iterators instantiated so we avoid name conflicts. The indices and iterators areNEWLINE # instantiated from for-loops.NEWLINE self.lambda_counter = 0NEWLINE self.temp_counter = 0NEWLINENEWLINE # These variables are populated from the first-pass PreBuildVisitor.NEWLINE self.free_variables = pbv.free_variablesNEWLINE self.prop_setters = pbv.prop_settersNEWLINE self.encapsulating_funcs = pbv.encapsulating_funcsNEWLINE self.nested_fitems = pbv.nested_funcs.keys()NEWLINE self.fdefs_to_decorators = pbv.funcs_to_decoratorsNEWLINE self.singledispatch_impls = singledispatch_implsNEWLINENEWLINE self.visitor = visitorNEWLINENEWLINE # This list operates similarly to a function call stack for nested functions. Whenever aNEWLINE # function definition begins to be generated, a FuncInfo instance is added to the stack,NEWLINE # and information about that function (e.g. whether it is nested, its environment class toNEWLINE # be generated) is stored in that FuncInfo instance. When the function is done beingNEWLINE # generated, its corresponding FuncInfo is popped off the stack.NEWLINE self.fn_info = FuncInfo(INVALID_FUNC_DEF, '', '')NEWLINE self.fn_infos: List[FuncInfo] = [self.fn_info]NEWLINENEWLINE # This list operates as a stack of constructs that modify theNEWLINE # behavior of nonlocal control flow constructs.NEWLINE self.nonlocal_control: List[NonlocalControl] = []NEWLINENEWLINE self.errors = errorsNEWLINE # Notionally a list of all of the modules imported by theNEWLINE # module being compiled, but stored as an OrderedDict so weNEWLINE # can also do quick lookups.NEWLINE self.imports: OrderedDict[str, None] = OrderedDict()NEWLINENEWLINE # High-level controlNEWLINENEWLINE def set_module(self, module_name: str, module_path: str) -> None:NEWLINE """Set the name and path of the current module.NEWLINENEWLINE This must be called before transforming any AST nodes.NEWLINE """NEWLINE self.module_name = module_nameNEWLINE self.module_path = module_pathNEWLINENEWLINE @overloadNEWLINE def accept(self, node: Expression) -> Value: ...NEWLINENEWLINE @overloadNEWLINE def accept(self, node: Statement) -> None: ...NEWLINENEWLINE def accept(self, node: Union[Statement, Expression]) -> Optional[Value]:NEWLINE """Transform an expression or a statement."""NEWLINE with self.catch_errors(node.line):NEWLINE if isinstance(node, Expression):NEWLINE try:NEWLINE res = node.accept(self.visitor)NEWLINE res = self.coerce(res, self.node_type(node), node.line)NEWLINE # If we hit an error during compilation, we want toNEWLINE # keep trying, so we can produce more errorNEWLINE # messages. Generate a temp of the right type to keepNEWLINE # from causing more downstream trouble.NEWLINE except UnsupportedException:NEWLINE res = Register(self.node_type(node))NEWLINE return resNEWLINE else:NEWLINE try:NEWLINE node.accept(self.visitor)NEWLINE except UnsupportedException:NEWLINE passNEWLINE return NoneNEWLINENEWLINE # Pass through methods for the most common low-level builder ops, for convenience.NEWLINENEWLINE def add(self, op: Op) -> Value:NEWLINE return self.builder.add(op)NEWLINENEWLINE def goto(self, target: BasicBlock) -> None:NEWLINE self.builder.goto(target)NEWLINENEWLINE def activate_block(self, block: BasicBlock) -> None:NEWLINE self.builder.activate_block(block)NEWLINENEWLINE def goto_and_activate(self, block: BasicBlock) -> None:NEWLINE self.builder.goto_and_activate(block)NEWLINENEWLINE def self(self) -> Register:NEWLINE return self.builder.self()NEWLINENEWLINE def py_get_attr(self, obj: Value, attr: str, line: int) -> Value:NEWLINE return self.builder.py_get_attr(obj, attr, line)NEWLINENEWLINE def load_str(self, value: str) -> Value:NEWLINE return self.builder.load_str(value)NEWLINENEWLINE def load_bytes_from_str_literal(self, value: str) -> Value:NEWLINE """Load bytes object from a string literal.NEWLINENEWLINE The literal characters of BytesExpr (the characters inside b'')NEWLINE are stored in BytesExpr.value, whose type is 'str' not 'bytes'.NEWLINE Thus we perform a special conversion here.NEWLINE """NEWLINE bytes_value = bytes(value, 'utf8').decode('unicode-escape').encode('raw-unicode-escape')NEWLINE return self.builder.load_bytes(bytes_value)NEWLINENEWLINE def load_int(self, value: int) -> Value:NEWLINE return self.builder.load_int(value)NEWLINENEWLINE def unary_op(self, lreg: Value, expr_op: str, line: int) -> Value:NEWLINE return self.builder.unary_op(lreg, expr_op, line)NEWLINENEWLINE def binary_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value:NEWLINE return self.builder.binary_op(lreg, rreg, expr_op, line)NEWLINENEWLINE def coerce(self, src: Value, target_type: RType, line: int, force: bool = False) -> Value:NEWLINE return self.builder.coerce(src, target_type, line, force)NEWLINENEWLINE def none_object(self) -> Value:NEWLINE return self.builder.none_object()NEWLINENEWLINE def none(self) -> Value:NEWLINE return self.builder.none()NEWLINENEWLINE def true(self) -> Value:NEWLINE return self.builder.true()NEWLINENEWLINE def false(self) -> Value:NEWLINE return self.builder.false()NEWLINENEWLINE def new_list_op(self, values: List[Value], line: int) -> Value:NEWLINE return self.builder.new_list_op(values, line)NEWLINENEWLINE def new_set_op(self, values: List[Value], line: int) -> Value:NEWLINE return self.builder.new_set_op(values, line)NEWLINENEWLINE def translate_is_op(self,NEWLINE lreg: Value,NEWLINE rreg: Value,NEWLINE expr_op: str,NEWLINE line: int) -> Value:NEWLINE return self.builder.translate_is_op(lreg, rreg, expr_op, line)NEWLINENEWLINE def py_call(self,NEWLINE function: Value,NEWLINE arg_values: List[Value],NEWLINE line: int,NEWLINE arg_kinds: Optional[List[ArgKind]] = None,NEWLINE arg_names: Optional[Sequence[Optional[str]]] = None) -> Value:NEWLINE return self.builder.py_call(function, arg_values, line, arg_kinds, arg_names)NEWLINENEWLINE def add_bool_branch(self, value: Value, true: BasicBlock, false: BasicBlock) -> None:NEWLINE self.builder.add_bool_branch(value, true, false)NEWLINENEWLINE def load_native_type_object(self, fullname: str) -> Value:NEWLINE return self.builder.load_native_type_object(fullname)NEWLINENEWLINE def gen_method_call(self,NEWLINE base: Value,NEWLINE name: str,NEWLINE arg_values: List[Value],NEWLINE result_type: Optional[RType],NEWLINE line: int,NEWLINE arg_kinds: Optional[List[ArgKind]] = None,NEWLINE arg_names: Optional[List[Optional[str]]] = None) -> Value:NEWLINE return self.builder.gen_method_call(NEWLINE base, name, arg_values, result_type, line, arg_kinds, arg_namesNEWLINE )NEWLINENEWLINE def load_module(self, name: str) -> Value:NEWLINE return self.builder.load_module(name)NEWLINENEWLINE def call_c(self, desc: CFunctionDescription, args: List[Value], line: int) -> Value:NEWLINE return self.builder.call_c(desc, args, line)NEWLINENEWLINE def int_op(self, type: RType, lhs: Value, rhs: Value, op: int, line: int) -> Value:NEWLINE return self.builder.int_op(type, lhs, rhs, op, line)NEWLINENEWLINE def compare_tagged(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:NEWLINE return self.builder.compare_tagged(lhs, rhs, op, line)NEWLINENEWLINE def compare_tuples(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:NEWLINE return self.builder.compare_tuples(lhs, rhs, op, line)NEWLINENEWLINE def builtin_len(self, val: Value, line: int) -> Value:NEWLINE return self.builder.builtin_len(val, line)NEWLINENEWLINE def new_tuple(self, items: List[Value], line: int) -> Value:NEWLINE return self.builder.new_tuple(items, line)NEWLINENEWLINE # Helpers for IR buildingNEWLINENEWLINE def add_to_non_ext_dict(self, non_ext: NonExtClassInfo,NEWLINE key: str, val: Value, line: int) -> None:NEWLINE # Add an attribute entry into the class dict of a non-extension class.NEWLINE key_unicode = self.load_str(key)NEWLINE self.call_c(dict_set_item_op, [non_ext.dict, key_unicode, val], line)NEWLINENEWLINE def gen_import_from(self, id: str, globals_dict: Value,NEWLINE imported: List[str], line: int) -> Value:NEWLINE self.imports[id] = NoneNEWLINENEWLINE null_dict = Integer(0, dict_rprimitive, line)NEWLINE names_to_import = self.new_list_op([self.load_str(name) for name in imported], line)NEWLINE zero_int = Integer(0, c_int_rprimitive, line)NEWLINE value = self.call_c(NEWLINE import_extra_args_op,NEWLINE [self.load_str(id), globals_dict, null_dict, names_to_import, zero_int],NEWLINE line,NEWLINE )NEWLINE self.add(InitStatic(value, id, namespace=NAMESPACE_MODULE))NEWLINE return valueNEWLINENEWLINE def gen_import(self, id: str, line: int) -> None:NEWLINE self.imports[id] = NoneNEWLINENEWLINE needs_import, out = BasicBlock(), BasicBlock()NEWLINE self.check_if_module_loaded(id, line, needs_import, out)NEWLINENEWLINE self.activate_block(needs_import)NEWLINE value = self.call_c(import_op, [self.load_str(id)], line)NEWLINE self.add(InitStatic(value, id, namespace=NAMESPACE_MODULE))NEWLINE self.goto_and_activate(out)NEWLINENEWLINE def check_if_module_loaded(self, id: str, line: int,NEWLINE needs_import: BasicBlock, out: BasicBlock) -> None:NEWLINE """Generate code that checks if the module `id` has been loaded yet.NEWLINENEWLINE Arguments:NEWLINE id: name of module to check if importedNEWLINE line: line number that the import occurs onNEWLINE needs_import: the BasicBlock that is run if the module has not been loaded yetNEWLINE out: the BasicBlock that is run if the module has already been loaded"""NEWLINE first_load = self.load_module(id)NEWLINE comparison = self.translate_is_op(first_load, self.none_object(), 'is not', line)NEWLINE self.add_bool_branch(comparison, out, needs_import)NEWLINENEWLINE def get_module(self, module: str, line: int) -> Value:NEWLINE # Python 3.7 has a nice 'PyImport_GetModule' function that we can't use :(NEWLINE mod_dict = self.call_c(get_module_dict_op, [], line)NEWLINE # Get module object from modules dict.NEWLINE return self.call_c(dict_get_item_op,NEWLINE [mod_dict, self.load_str(module)], line)NEWLINENEWLINE def get_module_attr(self, module: str, attr: str, line: int) -> Value:NEWLINE """Look up an attribute of a module without storing it in the local namespace.NEWLINENEWLINE For example, get_module_attr('typing', 'TypedDict', line) results inNEWLINE the value of 'typing.TypedDict'.NEWLINENEWLINE Import the module if needed.NEWLINE """NEWLINE self.gen_import(module, line)NEWLINE module_obj = self.get_module(module, line)NEWLINE return self.py_get_attr(module_obj, attr, line)NEWLINENEWLINE def assign_if_null(self, target: Register,NEWLINE get_val: Callable[[], Value], line: int) -> None:NEWLINE """If target is NULL, assign value produced by get_val to it."""NEWLINE error_block, body_block = BasicBlock(), BasicBlock()NEWLINE self.add(Branch(target, error_block, body_block, Branch.IS_ERROR))NEWLINE self.activate_block(error_block)NEWLINE self.add(Assign(target, self.coerce(get_val(), target.type, line)))NEWLINE self.goto(body_block)NEWLINE self.activate_block(body_block)NEWLINENEWLINE def maybe_add_implicit_return(self) -> None:NEWLINE if is_none_rprimitive(self.ret_types[-1]) or is_object_rprimitive(self.ret_types[-1]):NEWLINE self.add_implicit_return()NEWLINE else:NEWLINE self.add_implicit_unreachable()NEWLINENEWLINE def add_implicit_return(self) -> None:NEWLINE block = self.builder.blocks[-1]NEWLINE if not block.terminated:NEWLINE retval = self.coerce(self.builder.none(), self.ret_types[-1], -1)NEWLINE self.nonlocal_control[-1].gen_return(self, retval, self.fn_info.fitem.line)NEWLINENEWLINE def add_implicit_unreachable(self) -> None:NEWLINE block = self.builder.blocks[-1]NEWLINE if not block.terminated:NEWLINE self.add(Unreachable())NEWLINENEWLINE def disallow_class_assignments(self, lvalues: List[Lvalue], line: int) -> None:NEWLINE # Some best-effort attempts to disallow assigning to classNEWLINE # variables that aren't marked ClassVar, since we blatantlyNEWLINE # miscompile the interaction between instance and classNEWLINE # variables.NEWLINE for lvalue in lvalues:NEWLINE if (isinstance(lvalue, MemberExpr)NEWLINE and isinstance(lvalue.expr, RefExpr)NEWLINE and isinstance(lvalue.expr.node, TypeInfo)):NEWLINE var = lvalue.expr.node[lvalue.name].nodeNEWLINE if isinstance(var, Var) and not var.is_classvar:NEWLINE self.error(NEWLINE "Only class variables defined as ClassVar can be assigned to",NEWLINE line)NEWLINENEWLINE def non_function_scope(self) -> bool:NEWLINE # Currently the stack always has at least two items: dummy and top-level.NEWLINE return len(self.fn_infos) <= 2NEWLINENEWLINE def init_final_static(self,NEWLINE lvalue: Lvalue,NEWLINE rvalue_reg: Value,NEWLINE class_name: Optional[str] = None,NEWLINE *,NEWLINE type_override: Optional[RType] = None) -> None:NEWLINE assert isinstance(lvalue, NameExpr)NEWLINE assert isinstance(lvalue.node, Var)NEWLINE if lvalue.node.final_value is None:NEWLINE if class_name is None:NEWLINE name = lvalue.nameNEWLINE else:NEWLINE name = '{}.{}'.format(class_name, lvalue.name)NEWLINE assert name is not None, "Full name not set for variable"NEWLINE coerced = self.coerce(rvalue_reg, type_override or self.node_type(lvalue), lvalue.line)NEWLINE self.final_names.append((name, coerced.type))NEWLINE self.add(InitStatic(coerced, name, self.module_name))NEWLINENEWLINE def load_final_static(self, fullname: str, typ: RType, line: int,NEWLINE error_name: Optional[str] = None) -> Value:NEWLINE split_name = split_target(self.graph, fullname)NEWLINE assert split_name is not NoneNEWLINE module, name = split_nameNEWLINE return self.builder.load_static_checked(NEWLINE typ, name, module, line=line,NEWLINE error_msg='value for final name "{}" was not set'.format(error_name))NEWLINENEWLINE def load_final_literal_value(self, val: Union[int, str, bytes, float, bool],NEWLINE line: int) -> Value:NEWLINE """Load value of a final name or class-level attribute."""NEWLINE if isinstance(val, bool):NEWLINE if val:NEWLINE return self.true()NEWLINE else:NEWLINE return self.false()NEWLINE elif isinstance(val, int):NEWLINE # TODO: take care of negative integer initializersNEWLINE # (probably easier to fix this in mypy itself).NEWLINE return self.builder.load_int(val)NEWLINE elif isinstance(val, float):NEWLINE return self.builder.load_float(val)NEWLINE elif isinstance(val, str):NEWLINE return self.builder.load_str(val)NEWLINE elif isinstance(val, bytes):NEWLINE return self.builder.load_bytes(val)NEWLINE else:NEWLINE assert False, "Unsupported final literal value"NEWLINENEWLINE def get_assignment_target(self, lvalue: Lvalue,NEWLINE line: int = -1) -> AssignmentTarget:NEWLINE if isinstance(lvalue, NameExpr):NEWLINE # If we are visiting a decorator, then the SymbolNode we really want to be looking atNEWLINE # is the function that is decorated, not the entire Decorator node itself.NEWLINE symbol = lvalue.nodeNEWLINE if isinstance(symbol, Decorator):NEWLINE symbol = symbol.funcNEWLINE if symbol is None:NEWLINE # New semantic analyzer doesn't create ad-hoc Vars for special forms.NEWLINE assert lvalue.is_special_formNEWLINE symbol = Var(lvalue.name)NEWLINE if lvalue.kind == LDEF:NEWLINE if symbol not in self.symtables[-1]:NEWLINE # If the function is a generator function, then first define a new variableNEWLINE # in the current function's environment class. Next, define a target thatNEWLINE # refers to the newly defined variable in that environment class. Add theNEWLINE # target to the table containing class environment variables, as well as theNEWLINE # current environment.NEWLINE if self.fn_info.is_generator:NEWLINE return self.add_var_to_env_class(symbol, self.node_type(lvalue),NEWLINE self.fn_info.generator_class,NEWLINE reassign=False)NEWLINENEWLINE # Otherwise define a new local variable.NEWLINE return self.add_local_reg(symbol, self.node_type(lvalue))NEWLINE else:NEWLINE # Assign to a previously defined variable.NEWLINE return self.lookup(symbol)NEWLINE elif lvalue.kind == GDEF:NEWLINE globals_dict = self.load_globals_dict()NEWLINE name = self.load_str(lvalue.name)NEWLINE return AssignmentTargetIndex(globals_dict, name)NEWLINE else:NEWLINE assert False, lvalue.kindNEWLINE elif isinstance(lvalue, IndexExpr):NEWLINE # Indexed assignment x[y] = eNEWLINE base = self.accept(lvalue.base)NEWLINE index = self.accept(lvalue.index)NEWLINE return AssignmentTargetIndex(base, index)NEWLINE elif isinstance(lvalue, MemberExpr):NEWLINE # Attribute assignment x.y = eNEWLINE obj = self.accept(lvalue.expr)NEWLINE return AssignmentTargetAttr(obj, lvalue.name)NEWLINE elif isinstance(lvalue, TupleExpr):NEWLINE # Multiple assignment a, ..., b = eNEWLINE star_idx: Optional[int] = NoneNEWLINE lvalues = []NEWLINE for idx, item in enumerate(lvalue.items):NEWLINE targ = self.get_assignment_target(item)NEWLINE lvalues.append(targ)NEWLINE if isinstance(item, StarExpr):NEWLINE if star_idx is not None:NEWLINE self.error("Two starred expressions in assignment", line)NEWLINE star_idx = idxNEWLINENEWLINE return AssignmentTargetTuple(lvalues, star_idx)NEWLINENEWLINE elif isinstance(lvalue, StarExpr):NEWLINE return self.get_assignment_target(lvalue.expr)NEWLINENEWLINE assert False, 'Unsupported lvalue: %r' % lvalueNEWLINENEWLINE def read(self, target: Union[Value, AssignmentTarget], line: int = -1) -> Value:NEWLINE if isinstance(target, Value):NEWLINE return targetNEWLINE if isinstance(target, AssignmentTargetRegister):NEWLINE return target.registerNEWLINE if isinstance(target, AssignmentTargetIndex):NEWLINE reg = self.gen_method_call(NEWLINE target.base, '__getitem__', [target.index], target.type, line)NEWLINE if reg is not None:NEWLINE return regNEWLINE assert False, target.base.typeNEWLINE if isinstance(target, AssignmentTargetAttr):NEWLINE if isinstance(target.obj.type, RInstance) and target.obj.type.class_ir.is_ext_class:NEWLINE return self.add(GetAttr(target.obj, target.attr, line))NEWLINE else:NEWLINE return self.py_get_attr(target.obj, target.attr, line)NEWLINENEWLINE assert False, 'Unsupported lvalue: %r' % targetNEWLINENEWLINE def assign(self,NEWLINE target: Union[Register, AssignmentTarget],NEWLINE rvalue_reg: Value,NEWLINE line: int) -> None:NEWLINE if isinstance(target, Register):NEWLINE self.add(Assign(target, rvalue_reg))NEWLINE elif isinstance(target, AssignmentTargetRegister):NEWLINE rvalue_reg = self.coerce(rvalue_reg, target.type, line)NEWLINE self.add(Assign(target.register, rvalue_reg))NEWLINE elif isinstance(target, AssignmentTargetAttr):NEWLINE if isinstance(target.obj_type, RInstance):NEWLINE rvalue_reg = self.coerce(rvalue_reg, target.type, line)NEWLINE self.add(SetAttr(target.obj, target.attr, rvalue_reg, line))NEWLINE else:NEWLINE key = self.load_str(target.attr)NEWLINE boxed_reg = self.builder.box(rvalue_reg)NEWLINE self.call_c(py_setattr_op, [target.obj, key, boxed_reg], line)NEWLINE elif isinstance(target, AssignmentTargetIndex):NEWLINE target_reg2 = self.gen_method_call(NEWLINE target.base, '__setitem__', [target.index, rvalue_reg], None, line)NEWLINE assert target_reg2 is not None, target.base.typeNEWLINE elif isinstance(target, AssignmentTargetTuple):NEWLINE if isinstance(rvalue_reg.type, RTuple) and target.star_idx is None:NEWLINE rtypes = rvalue_reg.type.typesNEWLINE assert len(rtypes) == len(target.items)NEWLINE for i in range(len(rtypes)):NEWLINE item_value = self.add(TupleGet(rvalue_reg, i, line))NEWLINE self.assign(target.items[i], item_value, line)NEWLINE elif ((is_list_rprimitive(rvalue_reg.type) or is_tuple_rprimitive(rvalue_reg.type))NEWLINE and target.star_idx is None):NEWLINE self.process_sequence_assignment(target, rvalue_reg, line)NEWLINE else:NEWLINE self.process_iterator_tuple_assignment(target, rvalue_reg, line)NEWLINE else:NEWLINE assert False, 'Unsupported assignment target'NEWLINENEWLINE def process_sequence_assignment(self,NEWLINE target: AssignmentTargetTuple,NEWLINE rvalue: Value,NEWLINE line: int) -> None:NEWLINE """Process assignment like 'x, y = s', where s is a variable-length list or tuple."""NEWLINE # Check the length of sequence.NEWLINE expected_len = Integer(len(target.items), c_pyssize_t_rprimitive)NEWLINE self.builder.call_c(check_unpack_count_op, [rvalue, expected_len], line)NEWLINENEWLINE # Read sequence items.NEWLINE values = []NEWLINE for i in range(len(target.items)):NEWLINE item = target.items[i]NEWLINE index = self.builder.load_int(i)NEWLINE if is_list_rprimitive(rvalue.type):NEWLINE item_value = self.call_c(list_get_item_unsafe_op, [rvalue, index], line)NEWLINE else:NEWLINE item_value = self.builder.gen_method_call(NEWLINE rvalue, '__getitem__', [index], item.type, line)NEWLINE values.append(item_value)NEWLINENEWLINE # Assign sequence items to the target lvalues.NEWLINE for lvalue, value in zip(target.items, values):NEWLINE self.assign(lvalue, value, line)NEWLINENEWLINE def process_iterator_tuple_assignment_helper(self,NEWLINE litem: AssignmentTarget,NEWLINE ritem: Value, line: int) -> None:NEWLINE error_block, ok_block = BasicBlock(), BasicBlock()NEWLINE self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR))NEWLINENEWLINE self.activate_block(error_block)NEWLINE self.add(RaiseStandardError(RaiseStandardError.VALUE_ERROR,NEWLINE 'not enough values to unpack', line))NEWLINE self.add(Unreachable())NEWLINENEWLINE self.activate_block(ok_block)NEWLINE self.assign(litem, ritem, line)NEWLINENEWLINE def process_iterator_tuple_assignment(self,NEWLINE target: AssignmentTargetTuple,NEWLINE rvalue_reg: Value,NEWLINE line: int) -> None:NEWLINENEWLINE iterator = self.call_c(iter_op, [rvalue_reg], line)NEWLINENEWLINE # This may be the whole lvalue list if there is no starred valueNEWLINE split_idx = target.star_idx if target.star_idx is not None else len(target.items)NEWLINENEWLINE # Assign values before the first starred valueNEWLINE for litem in target.items[:split_idx]:NEWLINE ritem = self.call_c(next_op, [iterator], line)NEWLINE error_block, ok_block = BasicBlock(), BasicBlock()NEWLINE self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR))NEWLINENEWLINE self.activate_block(error_block)NEWLINE self.add(RaiseStandardError(RaiseStandardError.VALUE_ERROR,NEWLINE 'not enough values to unpack', line))NEWLINE self.add(Unreachable())NEWLINENEWLINE self.activate_block(ok_block)NEWLINENEWLINE self.assign(litem, ritem, line)NEWLINENEWLINE # Assign the starred value and all values after itNEWLINE if target.star_idx is not None:NEWLINE post_star_vals = target.items[split_idx + 1:]NEWLINE iter_list = self.call_c(to_list, [iterator], line)NEWLINE iter_list_len = self.builtin_len(iter_list, line)NEWLINE post_star_len = Integer(len(post_star_vals))NEWLINE condition = self.binary_op(post_star_len, iter_list_len, '<=', line)NEWLINENEWLINE error_block, ok_block = BasicBlock(), BasicBlock()NEWLINE self.add(Branch(condition, ok_block, error_block, Branch.BOOL))NEWLINENEWLINE self.activate_block(error_block)NEWLINE self.add(RaiseStandardError(RaiseStandardError.VALUE_ERROR,NEWLINE 'not enough values to unpack', line))NEWLINE self.add(Unreachable())NEWLINENEWLINE self.activate_block(ok_block)NEWLINENEWLINE for litem in reversed(post_star_vals):NEWLINE ritem = self.call_c(list_pop_last, [iter_list], line)NEWLINE self.assign(litem, ritem, line)NEWLINENEWLINE # Assign the starred valueNEWLINE self.assign(target.items[target.star_idx], iter_list, line)NEWLINENEWLINE # There is no starred value, so check if there are extra values in rhs thatNEWLINE # have not been assigned.NEWLINE else:NEWLINE extra = self.call_c(next_op, [iterator], line)NEWLINE error_block, ok_block = BasicBlock(), BasicBlock()NEWLINE self.add(Branch(extra, ok_block, error_block, Branch.IS_ERROR))NEWLINENEWLINE self.activate_block(error_block)NEWLINE self.add(RaiseStandardError(RaiseStandardError.VALUE_ERROR,NEWLINE 'too many values to unpack', line))NEWLINE self.add(Unreachable())NEWLINENEWLINE self.activate_block(ok_block)NEWLINENEWLINE def push_loop_stack(self, continue_block: BasicBlock, break_block: BasicBlock) -> None:NEWLINE self.nonlocal_control.append(NEWLINE LoopNonlocalControl(self.nonlocal_control[-1], continue_block, break_block))NEWLINENEWLINE def pop_loop_stack(self) -> None:NEWLINE self.nonlocal_control.pop()NEWLINENEWLINE def spill(self, value: Value) -> AssignmentTarget:NEWLINE """Moves a given Value instance into the generator class' environment class."""NEWLINE name = '{}{}'.format(TEMP_ATTR_NAME, self.temp_counter)NEWLINE self.temp_counter += 1NEWLINE target = self.add_var_to_env_class(Var(name), value.type, self.fn_info.generator_class)NEWLINE # Shouldn't be able to fail, so -1 for lineNEWLINE self.assign(target, value, -1)NEWLINE return targetNEWLINENEWLINE def maybe_spill(self, value: Value) -> Union[Value, AssignmentTarget]:NEWLINE """NEWLINE Moves a given Value instance into the environment class for generator functions. ForNEWLINE non-generator functions, leaves the Value instance as it is.NEWLINENEWLINE Returns an AssignmentTarget associated with the Value for generator functions and theNEWLINE original Value itself for non-generator functions.NEWLINE """NEWLINE if self.fn_info.is_generator:NEWLINE return self.spill(value)NEWLINE return valueNEWLINENEWLINE def maybe_spill_assignable(self, value: Value) -> Union[Register, AssignmentTarget]:NEWLINE """NEWLINE Moves a given Value instance into the environment class for generator functions. ForNEWLINE non-generator functions, allocate a temporary Register.NEWLINENEWLINE Returns an AssignmentTarget associated with the Value for generator functions and anNEWLINE assignable Register for non-generator functions.NEWLINE """NEWLINE if self.fn_info.is_generator:NEWLINE return self.spill(value)NEWLINENEWLINE if isinstance(value, Register):NEWLINE return valueNEWLINENEWLINE # Allocate a temporary register for the assignable value.NEWLINE reg = Register(value.type)NEWLINE self.assign(reg, value, -1)NEWLINE return regNEWLINENEWLINE def extract_int(self, e: Expression) -> Optional[int]:NEWLINE if isinstance(e, IntExpr):NEWLINE return e.valueNEWLINE elif isinstance(e, UnaryExpr) and e.op == '-' and isinstance(e.expr, IntExpr):NEWLINE return -e.expr.valueNEWLINE else:NEWLINE return NoneNEWLINENEWLINE def get_sequence_type(self, expr: Expression) -> RType:NEWLINE target_type = get_proper_type(self.types[expr])NEWLINE assert isinstance(target_type, Instance)NEWLINE if target_type.type.fullname == 'builtins.str':NEWLINE return str_rprimitiveNEWLINE else:NEWLINE return self.type_to_rtype(target_type.args[0])NEWLINENEWLINE def get_dict_base_type(self, expr: Expression) -> Instance:NEWLINE """Find dict type of a dict-like expression.NEWLINENEWLINE This is useful for dict subclasses like SymbolTable.NEWLINE """NEWLINE target_type = get_proper_type(self.types[expr])NEWLINE assert isinstance(target_type, Instance)NEWLINE dict_base = next(base for base in target_type.type.mroNEWLINE if base.fullname == 'builtins.dict')NEWLINE return map_instance_to_supertype(target_type, dict_base)NEWLINENEWLINE def get_dict_key_type(self, expr: Expression) -> RType:NEWLINE dict_base_type = self.get_dict_base_type(expr)NEWLINE return self.type_to_rtype(dict_base_type.args[0])NEWLINENEWLINE def get_dict_value_type(self, expr: Expression) -> RType:NEWLINE dict_base_type = self.get_dict_base_type(expr)NEWLINE return self.type_to_rtype(dict_base_type.args[1])NEWLINENEWLINE def get_dict_item_type(self, expr: Expression) -> RType:NEWLINE key_type = self.get_dict_key_type(expr)NEWLINE value_type = self.get_dict_value_type(expr)NEWLINE return RTuple([key_type, value_type])NEWLINENEWLINE def _analyze_iterable_item_type(self, expr: Expression) -> Type:NEWLINE """Return the item type given by 'expr' in an iterable context."""NEWLINE # This logic is copied from mypy's TypeChecker.analyze_iterable_item_type.NEWLINE iterable = get_proper_type(self.types[expr])NEWLINE echk = self.graph[self.module_name].type_checker().expr_checkerNEWLINE iterator = echk.check_method_call_by_name('__iter__', iterable, [], [], expr)[0]NEWLINENEWLINE from mypy.join import join_typesNEWLINE if isinstance(iterable, TupleType):NEWLINE joined: Type = UninhabitedType()NEWLINE for item in iterable.items:NEWLINE joined = join_types(joined, item)NEWLINE return joinedNEWLINE else:NEWLINE # Non-tuple iterable.NEWLINE return echk.check_method_call_by_name('__next__', iterator, [], [], expr)[0]NEWLINENEWLINE def is_native_module(self, module: str) -> bool:NEWLINE """Is the given module one compiled by mypyc?"""NEWLINE return module in self.mapper.group_mapNEWLINENEWLINE def is_native_ref_expr(self, expr: RefExpr) -> bool:NEWLINE if expr.node is None:NEWLINE return FalseNEWLINE if '.' in expr.node.fullname:NEWLINE return self.is_native_module(expr.node.fullname.rpartition('.')[0])NEWLINE return TrueNEWLINENEWLINE def is_native_module_ref_expr(self, expr: RefExpr) -> bool:NEWLINE return self.is_native_ref_expr(expr) and expr.kind == GDEFNEWLINENEWLINE def is_synthetic_type(self, typ: TypeInfo) -> bool:NEWLINE """Is a type something other than just a class we've created?"""NEWLINE return typ.is_named_tuple or typ.is_newtype or typ.typeddict_type is not NoneNEWLINENEWLINE def get_final_ref(self, expr: MemberExpr) -> Optional[Tuple[str, Var, bool]]:NEWLINE """Check if `expr` is a final attribute.NEWLINENEWLINE This needs to be done differently for class and module attributes toNEWLINE correctly determine fully qualified name. Return a tuple that consists ofNEWLINE the qualified name, the corresponding Var node, and a flag indicating whetherNEWLINE the final name was defined in a compiled module. Return None if `expr` does notNEWLINE refer to a final attribute.NEWLINE """NEWLINE final_var = NoneNEWLINE if isinstance(expr.expr, RefExpr) and isinstance(expr.expr.node, TypeInfo):NEWLINE # a class attributeNEWLINE sym = expr.expr.node.get(expr.name)NEWLINE if sym and isinstance(sym.node, Var):NEWLINE # Enum attribute are treated as final since they are added to the global cacheNEWLINE expr_fullname = expr.expr.node.bases[0].type.fullnameNEWLINE is_final = sym.node.is_final or expr_fullname == 'enum.Enum'NEWLINE if is_final:NEWLINE final_var = sym.nodeNEWLINE fullname = '{}.{}'.format(sym.node.info.fullname, final_var.name)NEWLINE native = self.is_native_module(expr.expr.node.module_name)NEWLINE elif self.is_module_member_expr(expr):NEWLINE # a module attributeNEWLINE if isinstance(expr.node, Var) and expr.node.is_final:NEWLINE final_var = expr.nodeNEWLINE fullname = expr.node.fullnameNEWLINE native = self.is_native_ref_expr(expr)NEWLINE if final_var is not None:NEWLINE return fullname, final_var, nativeNEWLINE return NoneNEWLINENEWLINE def emit_load_final(self, final_var: Var, fullname: str,NEWLINE name: str, native: bool, typ: Type, line: int) -> Optional[Value]:NEWLINE """Emit code for loading value of a final name (if possible).NEWLINENEWLINE Args:NEWLINE final_var: Var corresponding to the final nameNEWLINE fullname: its qualified nameNEWLINE name: shorter name to show in errorsNEWLINE native: whether the name was defined in a compiled moduleNEWLINE typ: its typeNEWLINE line: line number where loading occursNEWLINE """NEWLINE if final_var.final_value is not None: # this is safe even for non-native namesNEWLINE return self.load_final_literal_value(final_var.final_value, line)NEWLINE elif native:NEWLINE return self.load_final_static(fullname, self.mapper.type_to_rtype(typ),NEWLINE line, name)NEWLINE else:NEWLINE return NoneNEWLINENEWLINE def is_module_member_expr(self, expr: MemberExpr) -> bool:NEWLINE return isinstance(expr.expr, RefExpr) and isinstance(expr.expr.node, MypyFile)NEWLINENEWLINE def call_refexpr_with_args(NEWLINE self, expr: CallExpr, callee: RefExpr, arg_values: List[Value]) -> Value:NEWLINENEWLINE # Handle data-driven special-cased primitive call ops.NEWLINE if callee.fullname is not None and expr.arg_kinds == [ARG_POS] * len(arg_values):NEWLINE call_c_ops_candidates = function_ops.get(callee.fullname, [])NEWLINE target = self.builder.matching_call_c(call_c_ops_candidates, arg_values,NEWLINE expr.line, self.node_type(expr))NEWLINE if target:NEWLINE return targetNEWLINENEWLINE # Standard native call if signature and fullname are good and all arguments are positionalNEWLINE # or named.NEWLINE callee_node = callee.nodeNEWLINE if isinstance(callee_node, OverloadedFuncDef):NEWLINE callee_node = callee_node.implNEWLINE # TODO: use native calls for any decorated functions which have all their decoratorsNEWLINE # removed, not just singledispatch functions (which we don't do now just in case thoseNEWLINE # decorated functions are callable classes or cannot be called without the python API forNEWLINE # some other reason)NEWLINE if (NEWLINE isinstance(callee_node, Decorator)NEWLINE and callee_node.func not in self.fdefs_to_decoratorsNEWLINE and callee_node.func in self.singledispatch_implsNEWLINE ):NEWLINE callee_node = callee_node.funcNEWLINE if (callee_node is not NoneNEWLINE and callee.fullname is not NoneNEWLINE and callee_node in self.mapper.func_to_declNEWLINE and all(kind in (ARG_POS, ARG_NAMED) for kind in expr.arg_kinds)):NEWLINE decl = self.mapper.func_to_decl[callee_node]NEWLINE return self.builder.call(decl, arg_values, expr.arg_kinds, expr.arg_names, expr.line)NEWLINENEWLINE # Fall back to a Python callNEWLINE function = self.accept(callee)NEWLINE return self.py_call(function, arg_values, expr.line,NEWLINE arg_kinds=expr.arg_kinds, arg_names=expr.arg_names)NEWLINENEWLINE def shortcircuit_expr(self, expr: OpExpr) -> Value:NEWLINE return self.builder.shortcircuit_helper(NEWLINE expr.op, self.node_type(expr),NEWLINE lambda: self.accept(expr.left),NEWLINE lambda: self.accept(expr.right),NEWLINE expr.lineNEWLINE )NEWLINENEWLINE # Conditional expressionsNEWLINENEWLINE def process_conditional(self, e: Expression, true: BasicBlock, false: BasicBlock) -> None:NEWLINE if isinstance(e, OpExpr) and e.op in ['and', 'or']:NEWLINE if e.op == 'and':NEWLINE # Short circuit 'and' in a conditional context.NEWLINE new = BasicBlock()NEWLINE self.process_conditional(e.left, new, false)NEWLINE self.activate_block(new)NEWLINE self.process_conditional(e.right, true, false)NEWLINE else:NEWLINE # Short circuit 'or' in a conditional context.NEWLINE new = BasicBlock()NEWLINE self.process_conditional(e.left, true, new)NEWLINE self.activate_block(new)NEWLINE self.process_conditional(e.right, true, false)NEWLINE elif isinstance(e, UnaryExpr) and e.op == 'not':NEWLINE self.process_conditional(e.expr, false, true)NEWLINE else:NEWLINE res = self.maybe_process_conditional_comparison(e, true, false)NEWLINE if res:NEWLINE returnNEWLINE # Catch-all for arbitrary expressions.NEWLINE reg = self.accept(e)NEWLINE self.add_bool_branch(reg, true, false)NEWLINENEWLINE def maybe_process_conditional_comparison(self,NEWLINE e: Expression,NEWLINE true: BasicBlock,NEWLINE false: BasicBlock) -> bool:NEWLINE """Transform simple tagged integer comparisons in a conditional context.NEWLINENEWLINE Return True if the operation is supported (and was transformed). Otherwise,NEWLINE do nothing and return False.NEWLINENEWLINE Args:NEWLINE e: Arbitrary expressionNEWLINE true: Branch target if comparison is trueNEWLINE false: Branch target if comparison is falseNEWLINE """NEWLINE if not isinstance(e, ComparisonExpr) or len(e.operands) != 2:NEWLINE return FalseNEWLINE ltype = self.node_type(e.operands[0])NEWLINE rtype = self.node_type(e.operands[1])NEWLINE if not is_tagged(ltype) or not is_tagged(rtype):NEWLINE return FalseNEWLINE op = e.operators[0]NEWLINE if op not in ('==', '!=', '<', '<=', '>', '>='):NEWLINE return FalseNEWLINE left = self.accept(e.operands[0])NEWLINE right = self.accept(e.operands[1])NEWLINE # "left op right" for two tagged integersNEWLINE self.builder.compare_tagged_condition(left, right, op, true, false, e.line)NEWLINE return TrueNEWLINENEWLINE # Basic helpersNEWLINENEWLINE def flatten_classes(self, arg: Union[RefExpr, TupleExpr]) -> Optional[List[ClassIR]]:NEWLINE """Flatten classes in isinstance(obj, (A, (B, C))).NEWLINENEWLINE If at least one item is not a reference to a native class, return None.NEWLINE """NEWLINE if isinstance(arg, RefExpr):NEWLINE if isinstance(arg.node, TypeInfo) and self.is_native_module_ref_expr(arg):NEWLINE ir = self.mapper.type_to_ir.get(arg.node)NEWLINE if ir:NEWLINE return [ir]NEWLINE return NoneNEWLINE else:NEWLINE res: List[ClassIR] = []NEWLINE for item in arg.items:NEWLINE if isinstance(item, (RefExpr, TupleExpr)):NEWLINE item_part = self.flatten_classes(item)NEWLINE if item_part is None:NEWLINE return NoneNEWLINE res.extend(item_part)NEWLINE else:NEWLINE return NoneNEWLINE return resNEWLINENEWLINE def enter(self, fn_info: Union[FuncInfo, str] = '') -> None:NEWLINE if isinstance(fn_info, str):NEWLINE fn_info = FuncInfo(name=fn_info)NEWLINE self.builder = LowLevelIRBuilder(self.current_module, self.mapper, self.options)NEWLINE self.builders.append(self.builder)NEWLINE self.symtables.append(OrderedDict())NEWLINE self.runtime_args.append([])NEWLINE self.fn_info = fn_infoNEWLINE self.fn_infos.append(self.fn_info)NEWLINE self.ret_types.append(none_rprimitive)NEWLINE if fn_info.is_generator:NEWLINE self.nonlocal_control.append(GeneratorNonlocalControl())NEWLINE else:NEWLINE self.nonlocal_control.append(BaseNonlocalControl())NEWLINE self.activate_block(BasicBlock())NEWLINENEWLINE def leave(self) -> Tuple[List[Register], List[RuntimeArg], List[BasicBlock], RType, FuncInfo]:NEWLINE builder = self.builders.pop()NEWLINE self.symtables.pop()NEWLINE runtime_args = self.runtime_args.pop()NEWLINE ret_type = self.ret_types.pop()NEWLINE fn_info = self.fn_infos.pop()NEWLINE self.nonlocal_control.pop()NEWLINE self.builder = self.builders[-1]NEWLINE self.fn_info = self.fn_infos[-1]NEWLINE return builder.args, runtime_args, builder.blocks, ret_type, fn_infoNEWLINENEWLINE def enter_method(self,NEWLINE class_ir: ClassIR,NEWLINE name: str,NEWLINE ret_type: RType,NEWLINE fn_info: Union[FuncInfo, str] = '',NEWLINE self_type: Optional[RType] = None) -> None:NEWLINE """Begin generating IR for a method.NEWLINENEWLINE If the method takes arguments, you should immediately afterwards callNEWLINE add_argument() for each non-self argument (self is created implicitly).NEWLINENEWLINE Call leave_method() to finish the generation of the method.NEWLINENEWLINE You can enter multiple methods at a time. They are maintained in aNEWLINE stack, and leave_method() leaves the topmost one.NEWLINENEWLINE Args:NEWLINE class_ir: Add method to this classNEWLINE name: Short name of the methodNEWLINE ret_type: Return type of the methodNEWLINE fn_info: Optionally, additional information about the methodNEWLINE self_type: If not None, override default type of the implicit 'self'NEWLINE argument (by default, derive type from class_ir)NEWLINE """NEWLINE self.enter(fn_info)NEWLINE self.function_name_stack.append(name)NEWLINE self.class_ir_stack.append(class_ir)NEWLINE self.ret_types[-1] = ret_typeNEWLINE if self_type is None:NEWLINE self_type = RInstance(class_ir)NEWLINE self.add_argument(SELF_NAME, self_type)NEWLINENEWLINE def add_argument(self, var: Union[str, Var], typ: RType, kind: ArgKind = ARG_POS) -> Register:NEWLINE """Declare an argument in the current function.NEWLINENEWLINE You should use this instead of directly calling add_local() in new code.NEWLINE """NEWLINE if isinstance(var, str):NEWLINE var = Var(var)NEWLINE reg = self.add_local(var, typ, is_arg=True)NEWLINE self.runtime_args[-1].append(RuntimeArg(var.name, typ, kind))NEWLINE return regNEWLINENEWLINE def leave_method(self) -> None:NEWLINE """Finish the generation of IR for a method."""NEWLINE arg_regs, args, blocks, ret_type, fn_info = self.leave()NEWLINE sig = FuncSignature(args, ret_type)NEWLINE name = self.function_name_stack.pop()NEWLINE class_ir = self.class_ir_stack.pop()NEWLINE decl = FuncDecl(name, class_ir.name, self.module_name, sig)NEWLINE ir = FuncIR(decl, arg_regs, blocks)NEWLINE class_ir.methods[name] = irNEWLINE class_ir.method_decls[name] = ir.declNEWLINE self.functions.append(ir)NEWLINENEWLINE def lookup(self, symbol: SymbolNode) -> SymbolTarget:NEWLINE return self.symtables[-1][symbol]NEWLINENEWLINE def add_local(self, symbol: SymbolNode, typ: RType, is_arg: bool = False) -> 'Register':NEWLINE """Add register that represents a symbol to the symbol table.NEWLINENEWLINE Args:NEWLINE is_arg: is this a function argumentNEWLINE """NEWLINE assert isinstance(symbol, SymbolNode)NEWLINE reg = Register(typ, symbol.name, is_arg=is_arg, line=symbol.line)NEWLINE self.symtables[-1][symbol] = AssignmentTargetRegister(reg)NEWLINE if is_arg:NEWLINE self.builder.args.append(reg)NEWLINE return regNEWLINENEWLINE def add_local_reg(self,NEWLINE symbol: SymbolNode,NEWLINE typ: RType,NEWLINE is_arg: bool = False) -> AssignmentTargetRegister:NEWLINE """Like add_local, but return an assignment target instead of value."""NEWLINE self.add_local(symbol, typ, is_arg)NEWLINE target = self.symtables[-1][symbol]NEWLINE assert isinstance(target, AssignmentTargetRegister)NEWLINE return targetNEWLINENEWLINE def add_self_to_env(self, cls: ClassIR) -> AssignmentTargetRegister:NEWLINE """Low-level function that adds a 'self' argument.NEWLINENEWLINE This is only useful if using enter() instead of enter_method().NEWLINE """NEWLINE return self.add_local_reg(Var(SELF_NAME), RInstance(cls), is_arg=True)NEWLINENEWLINE def add_target(self, symbol: SymbolNode, target: SymbolTarget) -> SymbolTarget:NEWLINE self.symtables[-1][symbol] = targetNEWLINE return targetNEWLINENEWLINE def type_to_rtype(self, typ: Optional[Type]) -> RType:NEWLINE return self.mapper.type_to_rtype(typ)NEWLINENEWLINE def node_type(self, node: Expression) -> RType:NEWLINE if isinstance(node, IntExpr):NEWLINE # TODO: Don't special case IntExprNEWLINE return int_rprimitiveNEWLINE if node not in self.types:NEWLINE return object_rprimitiveNEWLINE mypy_type = self.types[node]NEWLINE return self.type_to_rtype(mypy_type)NEWLINENEWLINE def add_var_to_env_class(self,NEWLINE var: SymbolNode,NEWLINE rtype: RType,NEWLINE base: Union[FuncInfo, ImplicitClass],NEWLINE reassign: bool = False) -> AssignmentTarget:NEWLINE # First, define the variable name as an attribute of the environment class, and thenNEWLINE # construct a target for that attribute.NEWLINE self.fn_info.env_class.attributes[var.name] = rtypeNEWLINE attr_target = AssignmentTargetAttr(base.curr_env_reg, var.name)NEWLINENEWLINE if reassign:NEWLINE # Read the local definition of the variable, and set the corresponding attribute ofNEWLINE # the environment class' variable to be that value.NEWLINE reg = self.read(self.lookup(var), self.fn_info.fitem.line)NEWLINE self.add(SetAttr(base.curr_env_reg, var.name, reg, self.fn_info.fitem.line))NEWLINENEWLINE # Override the local definition of the variable to instead point at the variable inNEWLINE # the environment class.NEWLINE return self.add_target(var, attr_target)NEWLINENEWLINE def is_builtin_ref_expr(self, expr: RefExpr) -> bool:NEWLINE assert expr.node, "RefExpr not resolved"NEWLINE return '.' in expr.node.fullname and expr.node.fullname.split('.')[0] == 'builtins'NEWLINENEWLINE def load_global(self, expr: NameExpr) -> Value:NEWLINE """Loads a Python-level global.NEWLINENEWLINE This takes a NameExpr and uses its name as a key to retrieve the corresponding PyObject *NEWLINE from the _globals dictionary in the C-generated code.NEWLINE """NEWLINE # If the global is from 'builtins', turn it into a module attr load insteadNEWLINE if self.is_builtin_ref_expr(expr):NEWLINE assert expr.node, "RefExpr not resolved"NEWLINE return self.load_module_attr_by_fullname(expr.node.fullname, expr.line)NEWLINE if (self.is_native_module_ref_expr(expr) and isinstance(expr.node, TypeInfo)NEWLINE and not self.is_synthetic_type(expr.node)):NEWLINE assert expr.fullname is not NoneNEWLINE return self.load_native_type_object(expr.fullname)NEWLINE return self.load_global_str(expr.name, expr.line)NEWLINENEWLINE def load_global_str(self, name: str, line: int) -> Value:NEWLINE _globals = self.load_globals_dict()NEWLINE reg = self.load_str(name)NEWLINE return self.call_c(dict_get_item_op, [_globals, reg], line)NEWLINENEWLINE def load_globals_dict(self) -> Value:NEWLINE return self.add(LoadStatic(dict_rprimitive, 'globals', self.module_name))NEWLINENEWLINE def load_module_attr_by_fullname(self, fullname: str, line: int) -> Value:NEWLINE module, _, name = fullname.rpartition('.')NEWLINE left = self.load_module(module)NEWLINE return self.py_get_attr(left, name, line)NEWLINENEWLINE # Lacks a good type because there wasn't a reasonable type in 3.5 :(NEWLINE def catch_errors(self, line: int) -> Any:NEWLINE return catch_errors(self.module_path, line)NEWLINENEWLINE def warning(self, msg: str, line: int) -> None:NEWLINE self.errors.warning(msg, self.module_path, line)NEWLINENEWLINE def error(self, msg: str, line: int) -> None:NEWLINE self.errors.error(msg, self.module_path, line)NEWLINENEWLINE def note(self, msg: str, line: int) -> None:NEWLINE self.errors.note(msg, self.module_path, line)NEWLINENEWLINENEWLINEdef gen_arg_defaults(builder: IRBuilder) -> None:NEWLINE """Generate blocks for arguments that have default values.NEWLINENEWLINE If the passed value is an error value, then assign the defaultNEWLINE value to the argument.NEWLINE """NEWLINE fitem = builder.fn_info.fitemNEWLINE for arg in fitem.arguments:NEWLINE if arg.initializer:NEWLINE target = builder.lookup(arg.variable)NEWLINENEWLINE def get_default() -> Value:NEWLINE assert arg.initializer is not NoneNEWLINENEWLINE # If it is constant, don't bother storing itNEWLINE if is_constant(arg.initializer):NEWLINE return builder.accept(arg.initializer)NEWLINENEWLINE # Because gen_arg_defaults runs before calculate_arg_defaults, weNEWLINE # add the static/attribute to final_names/the class here.NEWLINE elif not builder.fn_info.is_nested:NEWLINE name = fitem.fullname + '.' + arg.variable.nameNEWLINE builder.final_names.append((name, target.type))NEWLINE return builder.add(LoadStatic(target.type, name, builder.module_name))NEWLINE else:NEWLINE name = arg.variable.nameNEWLINE builder.fn_info.callable_class.ir.attributes[name] = target.typeNEWLINE return builder.add(NEWLINE GetAttr(builder.fn_info.callable_class.self_reg, name, arg.line))NEWLINE assert isinstance(target, AssignmentTargetRegister)NEWLINE builder.assign_if_null(target.register, get_default, arg.initializer.line)NEWLINE import numpy as npNEWLINEimport picameraxNEWLINEimport picamerax.arrayNEWLINEfrom PIL import ImageNEWLINENEWLINEwith picamerax.PiCamera() as camera:NEWLINE with picamerax.array.PiMotionArray(camera) as stream:NEWLINE camera.resolution = (640, 480)NEWLINE camera.framerate = 30NEWLINE camera.start_recording('/dev/null', format='h264', motion_output=stream)NEWLINE camera.wait_recording(10)NEWLINE camera.stop_recording()NEWLINE for frame in range(stream.array.shape[0]):NEWLINE data = np.sqrt(NEWLINE np.square(stream.array[frame]['x'].astype(np.float)) +NEWLINE np.square(stream.array[frame]['y'].astype(np.float))NEWLINE ).clip(0, 255).astype(np.uint8)NEWLINE img = Image.fromarray(data)NEWLINE filename = 'frame%03d.png' % frameNEWLINE print('Writing %s' % filename)NEWLINE img.save(filename)NEWLINE from time import timeNEWLINEfrom base64 import b16encodeNEWLINEfrom functools import partialNEWLINEfrom operator import __eq__, __ne__, __lt__, __le__, __gt__, __ge__NEWLINENEWLINEfrom six import (NEWLINE integer_types as _integer_types,NEWLINE text_type as _text_type)NEWLINENEWLINEfrom OpenSSL._util import (NEWLINE ffi as _ffi,NEWLINE lib as _lib,NEWLINE exception_from_error_queue as _exception_from_error_queue,NEWLINE byte_string as _byte_string,NEWLINE native as _native)NEWLINENEWLINEFILETYPE_PEM = _lib.SSL_FILETYPE_PEMNEWLINEFILETYPE_ASN1 = _lib.SSL_FILETYPE_ASN1NEWLINENEWLINE# TODO This was an API mistake. OpenSSL has no such constant.NEWLINEFILETYPE_TEXT = 2 ** 16 - 1NEWLINENEWLINETYPE_RSA = _lib.EVP_PKEY_RSANEWLINETYPE_DSA = _lib.EVP_PKEY_DSANEWLINENEWLINENEWLINEclass Error(Exception):NEWLINE """NEWLINE An error occurred in an `OpenSSL.crypto` API.NEWLINE """NEWLINENEWLINENEWLINE_raise_current_error = partial(_exception_from_error_queue, Error)NEWLINENEWLINEdef _untested_error(where):NEWLINE """NEWLINE An OpenSSL API failed somehow. Additionally, the failure which wasNEWLINE encountered isn't one that's exercised by the test suite so future behaviorNEWLINE of pyOpenSSL is now somewhat less predictable.NEWLINE """NEWLINE raise RuntimeError("Unknown %s failure" % (where,))NEWLINENEWLINENEWLINENEWLINEdef _new_mem_buf(buffer=None):NEWLINE """NEWLINE Allocate a new OpenSSL memory BIO.NEWLINENEWLINE Arrange for the garbage collector to clean it up automatically.NEWLINENEWLINE :param buffer: None or some bytes to use to put into the BIO so that theyNEWLINE can be read out.NEWLINE """NEWLINE if buffer is None:NEWLINE bio = _lib.BIO_new(_lib.BIO_s_mem())NEWLINE free = _lib.BIO_freeNEWLINE else:NEWLINE data = _ffi.new("char[]", buffer)NEWLINE bio = _lib.BIO_new_mem_buf(data, len(buffer))NEWLINE # Keep the memory alive as long as the bio is alive!NEWLINE def free(bio, ref=data):NEWLINE return _lib.BIO_free(bio)NEWLINENEWLINE if bio == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE bio = _ffi.gc(bio, free)NEWLINE return bioNEWLINENEWLINENEWLINENEWLINEdef _bio_to_string(bio):NEWLINE """NEWLINE Copy the contents of an OpenSSL BIO object into a Python byte string.NEWLINE """NEWLINE result_buffer = _ffi.new('char**')NEWLINE buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)NEWLINE return _ffi.buffer(result_buffer[0], buffer_length)[:]NEWLINENEWLINENEWLINENEWLINEdef _set_asn1_time(boundary, when):NEWLINE """NEWLINE The the time value of an ASN1 time object.NEWLINENEWLINE @param boundary: An ASN1_GENERALIZEDTIME pointer (or an object safelyNEWLINE castable to that type) which will have its value set.NEWLINE @param when: A string representation of the desired time value.NEWLINENEWLINE @raise TypeError: If C{when} is not a L{bytes} string.NEWLINE @raise ValueError: If C{when} does not represent a time in the requiredNEWLINE format.NEWLINE @raise RuntimeError: If the time value cannot be set for some otherNEWLINE (unspecified) reason.NEWLINE """NEWLINE if not isinstance(when, bytes):NEWLINE raise TypeError("when must be a byte string")NEWLINENEWLINE set_result = _lib.ASN1_GENERALIZEDTIME_set_string(NEWLINE _ffi.cast('ASN1_GENERALIZEDTIME*', boundary), when)NEWLINE if set_result == 0:NEWLINE dummy = _ffi.gc(_lib.ASN1_STRING_new(), _lib.ASN1_STRING_free)NEWLINE _lib.ASN1_STRING_set(dummy, when, len(when))NEWLINE check_result = _lib.ASN1_GENERALIZEDTIME_check(NEWLINE _ffi.cast('ASN1_GENERALIZEDTIME*', dummy))NEWLINE if not check_result:NEWLINE raise ValueError("Invalid string")NEWLINE else:NEWLINE _untested_error()NEWLINENEWLINENEWLINENEWLINEdef _get_asn1_time(timestamp):NEWLINE """NEWLINE Retrieve the time value of an ASN1 time object.NEWLINENEWLINE @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable toNEWLINE that type) from which the time value will be retrieved.NEWLINENEWLINE @return: The time value from C{timestamp} as a L{bytes} string in a certainNEWLINE format. Or C{None} if the object contains no time value.NEWLINE """NEWLINE string_timestamp = _ffi.cast('ASN1_STRING*', timestamp)NEWLINE if _lib.ASN1_STRING_length(string_timestamp) == 0:NEWLINE return NoneNEWLINE elif _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME:NEWLINE return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))NEWLINE else:NEWLINE generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")NEWLINE _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)NEWLINE if generalized_timestamp[0] == _ffi.NULL:NEWLINE # This may happen:NEWLINE # - if timestamp was not an ASN1_TIMENEWLINE # - if allocating memory for the ASN1_GENERALIZEDTIME failedNEWLINE # - if a copy of the time data from timestamp cannot be made forNEWLINE # the newly allocated ASN1_GENERALIZEDTIMENEWLINE #NEWLINE # These are difficult to test. cffi enforces the ASN1_TIME type.NEWLINE # Memory allocation failures are a pain to triggerNEWLINE # deterministically.NEWLINE _untested_error("ASN1_TIME_to_generalizedtime")NEWLINE else:NEWLINE string_timestamp = _ffi.cast(NEWLINE "ASN1_STRING*", generalized_timestamp[0])NEWLINE string_data = _lib.ASN1_STRING_data(string_timestamp)NEWLINE string_result = _ffi.string(string_data)NEWLINE _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])NEWLINE return string_resultNEWLINENEWLINENEWLINENEWLINEclass PKey(object):NEWLINE _only_public = FalseNEWLINE _initialized = TrueNEWLINENEWLINE def __init__(self):NEWLINE pkey = _lib.EVP_PKEY_new()NEWLINE self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)NEWLINE self._initialized = FalseNEWLINENEWLINENEWLINE def generate_key(self, type, bits):NEWLINE """NEWLINE Generate a key of a given type, with a given number of a bitsNEWLINENEWLINE :param type: The key type (TYPE_RSA or TYPE_DSA)NEWLINE :param bits: The number of bitsNEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(type, int):NEWLINE raise TypeError("type must be an integer")NEWLINENEWLINE if not isinstance(bits, int):NEWLINE raise TypeError("bits must be an integer")NEWLINENEWLINE # TODO Check error returnNEWLINE exponent = _lib.BN_new()NEWLINE exponent = _ffi.gc(exponent, _lib.BN_free)NEWLINE _lib.BN_set_word(exponent, _lib.RSA_F4)NEWLINENEWLINE if type == TYPE_RSA:NEWLINE if bits <= 0:NEWLINE raise ValueError("Invalid number of bits")NEWLINENEWLINE rsa = _lib.RSA_new()NEWLINENEWLINE result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)NEWLINE if result == 0:NEWLINE # TODO: The test for this case is commented out. DifferentNEWLINE # builds of OpenSSL appear to have different failure modes thatNEWLINE # make it hard to test. Visual inspection of the OpenSSLNEWLINE # source reveals that a return value of 0 signals an error.NEWLINE # Manual testing on a particular build of OpenSSL suggests thatNEWLINE # this is probably the appropriate way to handle those errors.NEWLINE _raise_current_error()NEWLINENEWLINE result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)NEWLINE if not result:NEWLINE # TODO: It appears as though this can fail if an engine is inNEWLINE # use which does not support RSA.NEWLINE _raise_current_error()NEWLINENEWLINE elif type == TYPE_DSA:NEWLINE dsa = _lib.DSA_generate_parameters(NEWLINE bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE if dsa == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE if not _lib.DSA_generate_key(dsa):NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE if not _lib.EVP_PKEY_assign_DSA(self._pkey, dsa):NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE else:NEWLINE raise Error("No such key type")NEWLINENEWLINE self._initialized = TrueNEWLINENEWLINENEWLINE def check(self):NEWLINE """NEWLINE Check the consistency of an RSA private key.NEWLINENEWLINE :return: True if key is consistent.NEWLINE :raise Error: if the key is inconsistent.NEWLINE :raise TypeError: if the key is of a type which cannot be checked.NEWLINE Only RSA keys can currently be checked.NEWLINE """NEWLINE if self._only_public:NEWLINE raise TypeError("public key only")NEWLINENEWLINE if _lib.EVP_PKEY_type(self._pkey.type) != _lib.EVP_PKEY_RSA:NEWLINE raise TypeError("key type unsupported")NEWLINENEWLINE rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)NEWLINE rsa = _ffi.gc(rsa, _lib.RSA_free)NEWLINE result = _lib.RSA_check_key(rsa)NEWLINE if result:NEWLINE return TrueNEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def type(self):NEWLINE """NEWLINE Returns the type of the keyNEWLINENEWLINE :return: The type of the key.NEWLINE """NEWLINE return self._pkey.typeNEWLINENEWLINENEWLINE def bits(self):NEWLINE """NEWLINE Returns the number of bits of the keyNEWLINENEWLINE :return: The number of bits of the key.NEWLINE """NEWLINE return _lib.EVP_PKEY_bits(self._pkey)NEWLINEPKeyType = PKeyNEWLINENEWLINENEWLINENEWLINEclass X509Name(object):NEWLINE def __init__(self, name):NEWLINE """NEWLINE Create a new X509Name, copying the given X509Name instance.NEWLINENEWLINE :param name: An X509Name object to copyNEWLINE """NEWLINE name = _lib.X509_NAME_dup(name._name)NEWLINE self._name = _ffi.gc(name, _lib.X509_NAME_free)NEWLINENEWLINENEWLINE def __setattr__(self, name, value):NEWLINE if name.startswith('_'):NEWLINE return super(X509Name, self).__setattr__(name, value)NEWLINENEWLINE # Note: we really do not want str subclasses here, so we do not useNEWLINE # isinstance.NEWLINE if type(name) is not str:NEWLINE raise TypeError("attribute name must be string, not '%.200s'" % (NEWLINE type(value).__name__,))NEWLINENEWLINE nid = _lib.OBJ_txt2nid(_byte_string(name))NEWLINE if nid == _lib.NID_undef:NEWLINE try:NEWLINE _raise_current_error()NEWLINE except Error:NEWLINE passNEWLINE raise AttributeError("No such attribute")NEWLINENEWLINE # If there's an old entry for this NID, remove itNEWLINE for i in range(_lib.X509_NAME_entry_count(self._name)):NEWLINE ent = _lib.X509_NAME_get_entry(self._name, i)NEWLINE ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)NEWLINE ent_nid = _lib.OBJ_obj2nid(ent_obj)NEWLINE if nid == ent_nid:NEWLINE ent = _lib.X509_NAME_delete_entry(self._name, i)NEWLINE _lib.X509_NAME_ENTRY_free(ent)NEWLINE breakNEWLINENEWLINE if isinstance(value, _text_type):NEWLINE value = value.encode('utf-8')NEWLINENEWLINE add_result = _lib.X509_NAME_add_entry_by_NID(NEWLINE self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0)NEWLINE if not add_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def __getattr__(self, name):NEWLINE """NEWLINE Find attribute. An X509Name object has the following attributes:NEWLINE countryName (alias C), stateOrProvince (alias ST), locality (alias L),NEWLINE organization (alias O), organizationalUnit (alias OU), commonName (aliasNEWLINE CN) and more...NEWLINE """NEWLINE nid = _lib.OBJ_txt2nid(_byte_string(name))NEWLINE if nid == _lib.NID_undef:NEWLINE # This is a bit weird. OBJ_txt2nid indicated failure, but it seemsNEWLINE # a lower level function, a2d_ASN1_OBJECT, also feels the need toNEWLINE # push something onto the error queue. If we don't clean that upNEWLINE # now, someone else will bump into it later and be quite confused.NEWLINE # See lp#314814.NEWLINE try:NEWLINE _raise_current_error()NEWLINE except Error:NEWLINE passNEWLINE return super(X509Name, self).__getattr__(name)NEWLINENEWLINE entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)NEWLINE if entry_index == -1:NEWLINE return NoneNEWLINENEWLINE entry = _lib.X509_NAME_get_entry(self._name, entry_index)NEWLINE data = _lib.X509_NAME_ENTRY_get_data(entry)NEWLINENEWLINE result_buffer = _ffi.new("unsigned char**")NEWLINE data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)NEWLINE if data_length < 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE try:NEWLINE result = _ffi.buffer(result_buffer[0], data_length)[:].decode('utf-8')NEWLINE finally:NEWLINE # XXX untestedNEWLINE _lib.OPENSSL_free(result_buffer[0])NEWLINE return resultNEWLINENEWLINENEWLINE def _cmp(op):NEWLINE def f(self, other):NEWLINE if not isinstance(other, X509Name):NEWLINE return NotImplementedNEWLINE result = _lib.X509_NAME_cmp(self._name, other._name)NEWLINE return op(result, 0)NEWLINE return fNEWLINENEWLINE __eq__ = _cmp(__eq__)NEWLINE __ne__ = _cmp(__ne__)NEWLINENEWLINE __lt__ = _cmp(__lt__)NEWLINE __le__ = _cmp(__le__)NEWLINENEWLINE __gt__ = _cmp(__gt__)NEWLINE __ge__ = _cmp(__ge__)NEWLINENEWLINE def __repr__(self):NEWLINE """NEWLINE String representation of an X509NameNEWLINE """NEWLINE result_buffer = _ffi.new("char[]", 512);NEWLINE format_result = _lib.X509_NAME_oneline(NEWLINE self._name, result_buffer, len(result_buffer))NEWLINENEWLINE if format_result == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return "" % (NEWLINE _native(_ffi.string(result_buffer)),)NEWLINENEWLINENEWLINE def hash(self):NEWLINE """NEWLINE Return the hash value of this nameNEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return _lib.X509_NAME_hash(self._name)NEWLINENEWLINENEWLINE def der(self):NEWLINE """NEWLINE Return the DER encoding of this nameNEWLINENEWLINE :return: A :py:class:`bytes` instance giving the DER encoded form ofNEWLINE this name.NEWLINE """NEWLINE result_buffer = _ffi.new('unsigned char**')NEWLINE encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)NEWLINE if encode_result < 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE string_result = _ffi.buffer(result_buffer[0], encode_result)[:]NEWLINE _lib.OPENSSL_free(result_buffer[0])NEWLINE return string_resultNEWLINENEWLINENEWLINE def get_components(self):NEWLINE """NEWLINE Returns the split-up components of this name.NEWLINENEWLINE :return: List of tuples (name, value).NEWLINE """NEWLINE result = []NEWLINE for i in range(_lib.X509_NAME_entry_count(self._name)):NEWLINE ent = _lib.X509_NAME_get_entry(self._name, i)NEWLINENEWLINE fname = _lib.X509_NAME_ENTRY_get_object(ent)NEWLINE fval = _lib.X509_NAME_ENTRY_get_data(ent)NEWLINENEWLINE nid = _lib.OBJ_obj2nid(fname)NEWLINE name = _lib.OBJ_nid2sn(nid)NEWLINENEWLINE result.append((NEWLINE _ffi.string(name),NEWLINE _ffi.string(NEWLINE _lib.ASN1_STRING_data(fval),NEWLINE _lib.ASN1_STRING_length(fval))))NEWLINENEWLINE return resultNEWLINEX509NameType = X509NameNEWLINENEWLINENEWLINEclass X509Extension(object):NEWLINE def __init__(self, type_name, critical, value, subject=None, issuer=None):NEWLINE """NEWLINE :param typename: The name of the extension to create.NEWLINE :type typename: :py:data:`str`NEWLINENEWLINE :param critical: A flag indicating whether this is a critical extension.NEWLINENEWLINE :param value: The value of the extension.NEWLINE :type value: :py:data:`str`NEWLINENEWLINE :param subject: Optional X509 cert to use as subject.NEWLINE :type subject: :py:class:`X509`NEWLINENEWLINE :param issuer: Optional X509 cert to use as issuer.NEWLINE :type issuer: :py:class:`X509`NEWLINENEWLINE :return: The X509Extension objectNEWLINE """NEWLINE ctx = _ffi.new("X509V3_CTX*")NEWLINENEWLINE # A context is necessary for any extension which uses the r2i conversionNEWLINE # method. That is, X509V3_EXT_nconf may segfault if passed a NULL ctx.NEWLINE # Start off by initializing most of the fields to NULL.NEWLINE _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)NEWLINENEWLINE # We have no configuration database - but perhaps we should (someNEWLINE # extensions may require it).NEWLINE _lib.X509V3_set_ctx_nodb(ctx)NEWLINENEWLINE # Initialize the subject and issuer, if appropriate. ctx is a local,NEWLINE # and as far as I can tell none of the X509V3_* APIs invoked here stealNEWLINE # any references, so no need to mess with reference counts or duplicates.NEWLINE if issuer is not None:NEWLINE if not isinstance(issuer, X509):NEWLINE raise TypeError("issuer must be an X509 instance")NEWLINE ctx.issuer_cert = issuer._x509NEWLINE if subject is not None:NEWLINE if not isinstance(subject, X509):NEWLINE raise TypeError("subject must be an X509 instance")NEWLINE ctx.subject_cert = subject._x509NEWLINENEWLINE if critical:NEWLINE # There are other OpenSSL APIs which would let us pass in criticalNEWLINE # separately, but they're harder to use, and since value is alreadyNEWLINE # a pile of crappy junk smuggling a ton of utterly importantNEWLINE # structured data, what's the point of trying to avoid nasty stuffNEWLINE # with strings? (However, X509V3_EXT_i2d in particular seems like itNEWLINE # would be a better API to invoke. I do not know where to get theNEWLINE # ext_struc it desires for its last parameter, though.)NEWLINE value = b"critical," + valueNEWLINENEWLINE extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)NEWLINE if extension == _ffi.NULL:NEWLINE _raise_current_error()NEWLINE self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)NEWLINENEWLINENEWLINE @propertyNEWLINE def _nid(self):NEWLINE return _lib.OBJ_obj2nid(self._extension.object)NEWLINENEWLINE _prefixes = {NEWLINE _lib.GEN_EMAIL: "email",NEWLINE _lib.GEN_DNS: "DNS",NEWLINE _lib.GEN_URI: "URI",NEWLINE }NEWLINENEWLINE def _subjectAltNameString(self):NEWLINE method = _lib.X509V3_EXT_get(self._extension)NEWLINE if method == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE payload = self._extension.value.dataNEWLINE length = self._extension.value.lengthNEWLINENEWLINE payloadptr = _ffi.new("unsigned char**")NEWLINE payloadptr[0] = payloadNEWLINENEWLINE if method.it != _ffi.NULL:NEWLINE ptr = _lib.ASN1_ITEM_ptr(method.it)NEWLINE data = _lib.ASN1_item_d2i(_ffi.NULL, payloadptr, length, ptr)NEWLINE names = _ffi.cast("GENERAL_NAMES*", data)NEWLINE else:NEWLINE names = _ffi.cast(NEWLINE "GENERAL_NAMES*",NEWLINE method.d2i(_ffi.NULL, payloadptr, length))NEWLINENEWLINE parts = []NEWLINE for i in range(_lib.sk_GENERAL_NAME_num(names)):NEWLINE name = _lib.sk_GENERAL_NAME_value(names, i)NEWLINE try:NEWLINE label = self._prefixes[name.type]NEWLINE except KeyError:NEWLINE bio = _new_mem_buf()NEWLINE _lib.GENERAL_NAME_print(bio, name)NEWLINE parts.append(_native(_bio_to_string(bio)))NEWLINE else:NEWLINE value = _native(NEWLINE _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[:])NEWLINE parts.append(label + ":" + value)NEWLINE return ", ".join(parts)NEWLINENEWLINENEWLINE def __str__(self):NEWLINE """NEWLINE :return: a nice text representation of the extensionNEWLINE """NEWLINE if _lib.NID_subject_alt_name == self._nid:NEWLINE return self._subjectAltNameString()NEWLINENEWLINE bio = _new_mem_buf()NEWLINE print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)NEWLINE if not print_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _native(_bio_to_string(bio))NEWLINENEWLINENEWLINE def get_critical(self):NEWLINE """NEWLINE Returns the critical field of the X509ExtensionNEWLINENEWLINE :return: The critical field.NEWLINE """NEWLINE return _lib.X509_EXTENSION_get_critical(self._extension)NEWLINENEWLINENEWLINE def get_short_name(self):NEWLINE """NEWLINE Returns the short version of the type name of the X509ExtensionNEWLINENEWLINE :return: The short type name.NEWLINE """NEWLINE obj = _lib.X509_EXTENSION_get_object(self._extension)NEWLINE nid = _lib.OBJ_obj2nid(obj)NEWLINE return _ffi.string(_lib.OBJ_nid2sn(nid))NEWLINENEWLINENEWLINE def get_data(self):NEWLINE """NEWLINE Returns the data of the X509ExtensionNEWLINENEWLINE :return: A :py:data:`str` giving the X509Extension's ASN.1 encoded data.NEWLINE """NEWLINE octet_result = _lib.X509_EXTENSION_get_data(self._extension)NEWLINE string_result = _ffi.cast('ASN1_STRING*', octet_result)NEWLINE char_result = _lib.ASN1_STRING_data(string_result)NEWLINE result_length = _lib.ASN1_STRING_length(string_result)NEWLINE return _ffi.buffer(char_result, result_length)[:]NEWLINENEWLINEX509ExtensionType = X509ExtensionNEWLINENEWLINENEWLINEclass X509Req(object):NEWLINE def __init__(self):NEWLINE req = _lib.X509_REQ_new()NEWLINE self._req = _ffi.gc(req, _lib.X509_REQ_free)NEWLINENEWLINENEWLINE def set_pubkey(self, pkey):NEWLINE """NEWLINE Set the public key of the certificate requestNEWLINENEWLINE :param pkey: The public key to useNEWLINE :return: NoneNEWLINE """NEWLINE set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)NEWLINE if not set_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_pubkey(self):NEWLINE """NEWLINE Get the public key from the certificate requestNEWLINENEWLINE :return: The public keyNEWLINE """NEWLINE pkey = PKey.__new__(PKey)NEWLINE pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)NEWLINE if pkey._pkey == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)NEWLINE pkey._only_public = TrueNEWLINE return pkeyNEWLINENEWLINENEWLINE def set_version(self, version):NEWLINE """NEWLINE Set the version subfield (RFC 2459, section 4.1.2.1) of the certificateNEWLINE request.NEWLINENEWLINE :param version: The version numberNEWLINE :return: NoneNEWLINE """NEWLINE set_result = _lib.X509_REQ_set_version(self._req, version)NEWLINE if not set_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_version(self):NEWLINE """NEWLINE Get the version subfield (RFC 2459, section 4.1.2.1) of the certificateNEWLINE request.NEWLINENEWLINE :return: an integer giving the value of the version subfieldNEWLINE """NEWLINE return _lib.X509_REQ_get_version(self._req)NEWLINENEWLINENEWLINE def get_subject(self):NEWLINE """NEWLINE Create an X509Name object for the subject of the certificate requestNEWLINENEWLINE :return: An X509Name objectNEWLINE """NEWLINE name = X509Name.__new__(X509Name)NEWLINE name._name = _lib.X509_REQ_get_subject_name(self._req)NEWLINE if name._name == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE # The name is owned by the X509Req structure. As long as the X509NameNEWLINE # Python object is alive, keep the X509Req Python object alive.NEWLINE name._owner = selfNEWLINENEWLINE return nameNEWLINENEWLINENEWLINE def add_extensions(self, extensions):NEWLINE """NEWLINE Add extensions to the request.NEWLINENEWLINE :param extensions: a sequence of X509Extension objectsNEWLINE :return: NoneNEWLINE """NEWLINE stack = _lib.sk_X509_EXTENSION_new_null()NEWLINE if stack == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)NEWLINENEWLINE for ext in extensions:NEWLINE if not isinstance(ext, X509Extension):NEWLINE raise ValueError("One of the elements is not an X509Extension")NEWLINENEWLINE # TODO push can fail (here and elsewhere)NEWLINE _lib.sk_X509_EXTENSION_push(stack, ext._extension)NEWLINENEWLINE add_result = _lib.X509_REQ_add_extensions(self._req, stack)NEWLINE if not add_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def sign(self, pkey, digest):NEWLINE """NEWLINE Sign the certificate request using the supplied key and digestNEWLINENEWLINE :param pkey: The key to sign withNEWLINE :param digest: The message digest to useNEWLINE :return: NoneNEWLINE """NEWLINE if pkey._only_public:NEWLINE raise ValueError("Key has only public part")NEWLINENEWLINE if not pkey._initialized:NEWLINE raise ValueError("Key is uninitialized")NEWLINENEWLINE digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if digest_obj == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)NEWLINE if not sign_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def verify(self, pkey):NEWLINE """NEWLINE Verifies a certificate request using the supplied public keyNEWLINENEWLINE :param key: a public keyNEWLINE :return: True if the signature is correct.NEWLINENEWLINE :raise OpenSSL.crypto.Error: If the signature is invalid or there is aNEWLINE problem verifying the signature.NEWLINE """NEWLINE if not isinstance(pkey, PKey):NEWLINE raise TypeError("pkey must be a PKey instance")NEWLINENEWLINE result = _lib.X509_REQ_verify(self._req, pkey._pkey)NEWLINE if result <= 0:NEWLINE _raise_current_error()NEWLINENEWLINE return resultNEWLINENEWLINENEWLINEX509ReqType = X509ReqNEWLINENEWLINENEWLINENEWLINEclass X509(object):NEWLINE def __init__(self):NEWLINE # TODO Allocation failure? And why not __new__ instead of __init__?NEWLINE x509 = _lib.X509_new()NEWLINE self._x509 = _ffi.gc(x509, _lib.X509_free)NEWLINENEWLINENEWLINE def set_version(self, version):NEWLINE """NEWLINE Set version number of the certificateNEWLINENEWLINE :param version: The version numberNEWLINE :type version: :py:class:`int`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(version, int):NEWLINE raise TypeError("version must be an integer")NEWLINENEWLINE _lib.X509_set_version(self._x509, version)NEWLINENEWLINENEWLINE def get_version(self):NEWLINE """NEWLINE Return version number of the certificateNEWLINENEWLINE :return: Version number as a Python integerNEWLINE """NEWLINE return _lib.X509_get_version(self._x509)NEWLINENEWLINENEWLINE def get_pubkey(self):NEWLINE """NEWLINE Get the public key of the certificateNEWLINENEWLINE :return: The public keyNEWLINE """NEWLINE pkey = PKey.__new__(PKey)NEWLINE pkey._pkey = _lib.X509_get_pubkey(self._x509)NEWLINE if pkey._pkey == _ffi.NULL:NEWLINE _raise_current_error()NEWLINE pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)NEWLINE pkey._only_public = TrueNEWLINE return pkeyNEWLINENEWLINENEWLINE def set_pubkey(self, pkey):NEWLINE """NEWLINE Set the public key of the certificateNEWLINENEWLINE :param pkey: The public keyNEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(pkey, PKey):NEWLINE raise TypeError("pkey must be a PKey instance")NEWLINENEWLINE set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)NEWLINE if not set_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def sign(self, pkey, digest):NEWLINE """NEWLINE Sign the certificate using the supplied key and digestNEWLINENEWLINE :param pkey: The key to sign withNEWLINE :param digest: The message digest to useNEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(pkey, PKey):NEWLINE raise TypeError("pkey must be a PKey instance")NEWLINENEWLINE if pkey._only_public:NEWLINE raise ValueError("Key only has public part")NEWLINENEWLINE if not pkey._initialized:NEWLINE raise ValueError("Key is uninitialized")NEWLINENEWLINE evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if evp_md == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)NEWLINE if not sign_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_signature_algorithm(self):NEWLINE """NEWLINE Retrieve the signature algorithm used in the certificateNEWLINENEWLINE :return: A byte string giving the name of the signature algorithm used inNEWLINE the certificate.NEWLINE :raise ValueError: If the signature algorithm is undefined.NEWLINE """NEWLINE alg = self._x509.cert_info.signature.algorithmNEWLINE nid = _lib.OBJ_obj2nid(alg)NEWLINE if nid == _lib.NID_undef:NEWLINE raise ValueError("Undefined signature algorithm")NEWLINE return _ffi.string(_lib.OBJ_nid2ln(nid))NEWLINENEWLINENEWLINE def digest(self, digest_name):NEWLINE """NEWLINE Return the digest of the X509 object.NEWLINENEWLINE :param digest_name: The name of the digest algorithm to use.NEWLINE :type digest_name: :py:class:`bytes`NEWLINENEWLINE :return: The digest of the objectNEWLINE """NEWLINE digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))NEWLINE if digest == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE result_buffer = _ffi.new("char[]", _lib.EVP_MAX_MD_SIZE)NEWLINE result_length = _ffi.new("unsigned int[]", 1)NEWLINE result_length[0] = len(result_buffer)NEWLINENEWLINE digest_result = _lib.X509_digest(NEWLINE self._x509, digest, result_buffer, result_length)NEWLINENEWLINE if not digest_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return b":".join([NEWLINE b16encode(ch).upper() for chNEWLINE in _ffi.buffer(result_buffer, result_length[0])])NEWLINENEWLINENEWLINE def subject_name_hash(self):NEWLINE """NEWLINE Return the hash of the X509 subject.NEWLINENEWLINE :return: The hash of the subject.NEWLINE """NEWLINE return _lib.X509_subject_name_hash(self._x509)NEWLINENEWLINENEWLINE def set_serial_number(self, serial):NEWLINE """NEWLINE Set serial number of the certificateNEWLINENEWLINE :param serial: The serial numberNEWLINE :type serial: :py:class:`int`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(serial, _integer_types):NEWLINE raise TypeError("serial must be an integer")NEWLINENEWLINE hex_serial = hex(serial)[2:]NEWLINE if not isinstance(hex_serial, bytes):NEWLINE hex_serial = hex_serial.encode('ascii')NEWLINENEWLINE bignum_serial = _ffi.new("BIGNUM**")NEWLINENEWLINE # BN_hex2bn stores the result in &bignum. Unless it doesn't feel likeNEWLINE # it. If bignum is still NULL after this call, then the return value isNEWLINE # actually the result. I hope. -exarkunNEWLINE small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)NEWLINENEWLINE if bignum_serial[0] == _ffi.NULL:NEWLINE set_result = _lib.ASN1_INTEGER_set(NEWLINE _lib.X509_get_serialNumber(self._x509), small_serial)NEWLINE if set_result:NEWLINE # TODO Not testedNEWLINE _raise_current_error()NEWLINE else:NEWLINE asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)NEWLINE _lib.BN_free(bignum_serial[0])NEWLINE if asn1_serial == _ffi.NULL:NEWLINE # TODO Not testedNEWLINE _raise_current_error()NEWLINE asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)NEWLINE set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)NEWLINE if not set_result:NEWLINE # TODO Not testedNEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_serial_number(self):NEWLINE """NEWLINE Return serial number of the certificateNEWLINENEWLINE :return: Serial number as a Python integerNEWLINE """NEWLINE asn1_serial = _lib.X509_get_serialNumber(self._x509)NEWLINE bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)NEWLINE try:NEWLINE hex_serial = _lib.BN_bn2hex(bignum_serial)NEWLINE try:NEWLINE hexstring_serial = _ffi.string(hex_serial)NEWLINE serial = int(hexstring_serial, 16)NEWLINE return serialNEWLINE finally:NEWLINE _lib.OPENSSL_free(hex_serial)NEWLINE finally:NEWLINE _lib.BN_free(bignum_serial)NEWLINENEWLINENEWLINE def gmtime_adj_notAfter(self, amount):NEWLINE """NEWLINE Adjust the time stamp for when the certificate stops being validNEWLINENEWLINE :param amount: The number of seconds by which to adjust the endingNEWLINE validity time.NEWLINE :type amount: :py:class:`int`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(amount, int):NEWLINE raise TypeError("amount must be an integer")NEWLINENEWLINE notAfter = _lib.X509_get_notAfter(self._x509)NEWLINE _lib.X509_gmtime_adj(notAfter, amount)NEWLINENEWLINENEWLINE def gmtime_adj_notBefore(self, amount):NEWLINE """NEWLINE Change the timestamp for when the certificate starts being valid to the currentNEWLINE time plus an offset.NEWLINENEWLINE :param amount: The number of seconds by which to adjust the starting validityNEWLINE time.NEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(amount, int):NEWLINE raise TypeError("amount must be an integer")NEWLINENEWLINE notBefore = _lib.X509_get_notBefore(self._x509)NEWLINE _lib.X509_gmtime_adj(notBefore, amount)NEWLINENEWLINENEWLINE def has_expired(self):NEWLINE """NEWLINE Check whether the certificate has expired.NEWLINENEWLINE :return: True if the certificate has expired, false otherwiseNEWLINE """NEWLINE now = int(time())NEWLINE notAfter = _lib.X509_get_notAfter(self._x509)NEWLINE return _lib.ASN1_UTCTIME_cmp_time_t(NEWLINE _ffi.cast('ASN1_UTCTIME*', notAfter), now) < 0NEWLINENEWLINENEWLINE def _get_boundary_time(self, which):NEWLINE return _get_asn1_time(which(self._x509))NEWLINENEWLINENEWLINE def get_notBefore(self):NEWLINE """NEWLINE Retrieve the time stamp for when the certificate starts being validNEWLINENEWLINE :return: A string giving the timestamp, in the format::NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINENEWLINE or None if there is no value set.NEWLINE """NEWLINE return self._get_boundary_time(_lib.X509_get_notBefore)NEWLINENEWLINENEWLINE def _set_boundary_time(self, which, when):NEWLINE return _set_asn1_time(which(self._x509), when)NEWLINENEWLINENEWLINE def set_notBefore(self, when):NEWLINE """NEWLINE Set the time stamp for when the certificate starts being validNEWLINENEWLINE :param when: A string giving the timestamp, in the format:NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINE :type when: :py:class:`bytes`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return self._set_boundary_time(_lib.X509_get_notBefore, when)NEWLINENEWLINENEWLINE def get_notAfter(self):NEWLINE """NEWLINE Retrieve the time stamp for when the certificate stops being validNEWLINENEWLINE :return: A string giving the timestamp, in the format::NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINENEWLINE or None if there is no value set.NEWLINE """NEWLINE return self._get_boundary_time(_lib.X509_get_notAfter)NEWLINENEWLINENEWLINE def set_notAfter(self, when):NEWLINE """NEWLINE Set the time stamp for when the certificate stops being validNEWLINENEWLINE :param when: A string giving the timestamp, in the format:NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINE :type when: :py:class:`bytes`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return self._set_boundary_time(_lib.X509_get_notAfter, when)NEWLINENEWLINENEWLINE def _get_name(self, which):NEWLINE name = X509Name.__new__(X509Name)NEWLINE name._name = which(self._x509)NEWLINE if name._name == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE # The name is owned by the X509 structure. As long as the X509NameNEWLINE # Python object is alive, keep the X509 Python object alive.NEWLINE name._owner = selfNEWLINENEWLINE return nameNEWLINENEWLINENEWLINE def _set_name(self, which, name):NEWLINE if not isinstance(name, X509Name):NEWLINE raise TypeError("name must be an X509Name")NEWLINE set_result = which(self._x509, name._name)NEWLINE if not set_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_issuer(self):NEWLINE """NEWLINE Create an X509Name object for the issuer of the certificateNEWLINENEWLINE :return: An X509Name objectNEWLINE """NEWLINE return self._get_name(_lib.X509_get_issuer_name)NEWLINENEWLINENEWLINE def set_issuer(self, issuer):NEWLINE """NEWLINE Set the issuer of the certificateNEWLINENEWLINE :param issuer: The issuer nameNEWLINE :type issuer: :py:class:`X509Name`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return self._set_name(_lib.X509_set_issuer_name, issuer)NEWLINENEWLINENEWLINE def get_subject(self):NEWLINE """NEWLINE Create an X509Name object for the subject of the certificateNEWLINENEWLINE :return: An X509Name objectNEWLINE """NEWLINE return self._get_name(_lib.X509_get_subject_name)NEWLINENEWLINENEWLINE def set_subject(self, subject):NEWLINE """NEWLINE Set the subject of the certificateNEWLINENEWLINE :param subject: The subject nameNEWLINE :type subject: :py:class:`X509Name`NEWLINE :return: NoneNEWLINE """NEWLINE return self._set_name(_lib.X509_set_subject_name, subject)NEWLINENEWLINENEWLINE def get_extension_count(self):NEWLINE """NEWLINE Get the number of extensions on the certificate.NEWLINENEWLINE :return: The number of extensions as an integer.NEWLINE """NEWLINE return _lib.X509_get_ext_count(self._x509)NEWLINENEWLINENEWLINE def add_extensions(self, extensions):NEWLINE """NEWLINE Add extensions to the certificate.NEWLINENEWLINE :param extensions: a sequence of X509Extension objectsNEWLINE :return: NoneNEWLINE """NEWLINE for ext in extensions:NEWLINE if not isinstance(ext, X509Extension):NEWLINE raise ValueError("One of the elements is not an X509Extension")NEWLINENEWLINE add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)NEWLINE if not add_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_extension(self, index):NEWLINE """NEWLINE Get a specific extension of the certificate by index.NEWLINENEWLINE :param index: The index of the extension to retrieve.NEWLINE :return: The X509Extension object at the specified index.NEWLINE """NEWLINE ext = X509Extension.__new__(X509Extension)NEWLINE ext._extension = _lib.X509_get_ext(self._x509, index)NEWLINE if ext._extension == _ffi.NULL:NEWLINE raise IndexError("extension index out of bounds")NEWLINENEWLINE extension = _lib.X509_EXTENSION_dup(ext._extension)NEWLINE ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)NEWLINE return extNEWLINENEWLINEX509Type = X509NEWLINENEWLINENEWLINENEWLINEclass X509Store(object):NEWLINE def __init__(self):NEWLINE store = _lib.X509_STORE_new()NEWLINE self._store = _ffi.gc(store, _lib.X509_STORE_free)NEWLINENEWLINENEWLINE def add_cert(self, cert):NEWLINE if not isinstance(cert, X509):NEWLINE raise TypeError()NEWLINENEWLINE result = _lib.X509_STORE_add_cert(self._store, cert._x509)NEWLINE if not result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINEX509StoreType = X509StoreNEWLINENEWLINENEWLINENEWLINEdef load_certificate(type, buffer):NEWLINE """NEWLINE Load a certificate from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINENEWLINE :param buffer: The buffer the certificate is stored inNEWLINE :type buffer: :py:class:`bytes`NEWLINENEWLINE :return: The X509 objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE elif type == FILETYPE_ASN1:NEWLINE x509 = _lib.d2i_X509_bio(bio, _ffi.NULL);NEWLINE else:NEWLINE raise ValueError(NEWLINE "type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if x509 == _ffi.NULL:NEWLINE _raise_current_error()NEWLINENEWLINE cert = X509.__new__(X509)NEWLINE cert._x509 = _ffi.gc(x509, _lib.X509_free)NEWLINE return certNEWLINENEWLINENEWLINEdef dump_certificate(type, cert):NEWLINE """NEWLINE Dump a certificate to a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, orNEWLINE FILETYPE_TEXT)NEWLINE :param cert: The certificate to dumpNEWLINE :return: The buffer with the dumped certificate inNEWLINE """NEWLINE bio = _new_mem_buf()NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE result_code = _lib.PEM_write_bio_X509(bio, cert._x509)NEWLINE elif type == FILETYPE_ASN1:NEWLINE result_code = _lib.i2d_X509_bio(bio, cert._x509)NEWLINE elif type == FILETYPE_TEXT:NEWLINE result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)NEWLINE else:NEWLINE raise ValueError(NEWLINE "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "NEWLINE "FILETYPE_TEXT")NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINENEWLINEdef dump_privatekey(type, pkey, cipher=None, passphrase=None):NEWLINE """NEWLINE Dump a private key to a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, orNEWLINE FILETYPE_TEXT)NEWLINE :param pkey: The PKey to dumpNEWLINE :param cipher: (optional) if encrypted PEM format, the cipher toNEWLINE useNEWLINE :param passphrase: (optional) if encrypted PEM format, this can be eitherNEWLINE the passphrase to use, or a callback for providing theNEWLINE passphrase.NEWLINE :return: The buffer with the dumped key inNEWLINE :rtype: :py:data:`str`NEWLINE """NEWLINE bio = _new_mem_buf()NEWLINENEWLINE if cipher is not None:NEWLINE if passphrase is None:NEWLINE raise TypeError(NEWLINE "if a value is given for cipher "NEWLINE "one must also be given for passphrase")NEWLINE cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))NEWLINE if cipher_obj == _ffi.NULL:NEWLINE raise ValueError("Invalid cipher name")NEWLINE else:NEWLINE cipher_obj = _ffi.NULLNEWLINENEWLINE helper = _PassphraseHelper(type, passphrase)NEWLINE if type == FILETYPE_PEM:NEWLINE result_code = _lib.PEM_write_bio_PrivateKey(NEWLINE bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,NEWLINE helper.callback, helper.callback_args)NEWLINE helper.raise_if_problem()NEWLINE elif type == FILETYPE_ASN1:NEWLINE result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)NEWLINE elif type == FILETYPE_TEXT:NEWLINE rsa = _lib.EVP_PKEY_get1_RSA(pkey._pkey)NEWLINE result_code = _lib.RSA_print(bio, rsa, 0)NEWLINE # TODO RSA_free(rsa)?NEWLINE else:NEWLINE raise ValueError(NEWLINE "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "NEWLINE "FILETYPE_TEXT")NEWLINENEWLINE if result_code == 0:NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINENEWLINEdef _X509_REVOKED_dup(original):NEWLINE copy = _lib.X509_REVOKED_new()NEWLINE if copy == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE if original.serialNumber != _ffi.NULL:NEWLINE copy.serialNumber = _lib.ASN1_INTEGER_dup(original.serialNumber)NEWLINENEWLINE if original.revocationDate != _ffi.NULL:NEWLINE copy.revocationDate = _lib.M_ASN1_TIME_dup(original.revocationDate)NEWLINENEWLINE if original.extensions != _ffi.NULL:NEWLINE extension_stack = _lib.sk_X509_EXTENSION_new_null()NEWLINE for i in range(_lib.sk_X509_EXTENSION_num(original.extensions)):NEWLINE original_ext = _lib.sk_X509_EXTENSION_value(original.extensions, i)NEWLINE copy_ext = _lib.X509_EXTENSION_dup(original_ext)NEWLINE _lib.sk_X509_EXTENSION_push(extension_stack, copy_ext)NEWLINE copy.extensions = extension_stackNEWLINENEWLINE copy.sequence = original.sequenceNEWLINE return copyNEWLINENEWLINENEWLINENEWLINEclass Revoked(object):NEWLINE # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_NEWLINE # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matchesNEWLINE # OCSP_crl_reason_str. We use the latter, just like the command lineNEWLINE # program.NEWLINE _crl_reasons = [NEWLINE b"unspecified",NEWLINE b"keyCompromise",NEWLINE b"CACompromise",NEWLINE b"affiliationChanged",NEWLINE b"superseded",NEWLINE b"cessationOfOperation",NEWLINE b"certificateHold",NEWLINE # b"removeFromCRL",NEWLINE ]NEWLINENEWLINE def __init__(self):NEWLINE revoked = _lib.X509_REVOKED_new()NEWLINE self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)NEWLINENEWLINENEWLINE def set_serial(self, hex_str):NEWLINE """NEWLINE Set the serial number of a revoked Revoked structureNEWLINENEWLINE :param hex_str: The new serial number.NEWLINE :type hex_str: :py:data:`str`NEWLINE :return: NoneNEWLINE """NEWLINE bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)NEWLINE bignum_ptr = _ffi.new("BIGNUM**")NEWLINE bignum_ptr[0] = bignum_serialNEWLINE bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)NEWLINE if not bn_result:NEWLINE raise ValueError("bad hex string")NEWLINENEWLINE asn1_serial = _ffi.gc(NEWLINE _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),NEWLINE _lib.ASN1_INTEGER_free)NEWLINE _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)NEWLINENEWLINENEWLINE def get_serial(self):NEWLINE """NEWLINE Return the serial number of a Revoked structureNEWLINENEWLINE :return: The serial number as a stringNEWLINE """NEWLINE bio = _new_mem_buf()NEWLINENEWLINE result = _lib.i2a_ASN1_INTEGER(bio, self._revoked.serialNumber)NEWLINE if result < 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINE def _delete_reason(self):NEWLINE stack = self._revoked.extensionsNEWLINE for i in range(_lib.sk_X509_EXTENSION_num(stack)):NEWLINE ext = _lib.sk_X509_EXTENSION_value(stack, i)NEWLINE if _lib.OBJ_obj2nid(ext.object) == _lib.NID_crl_reason:NEWLINE _lib.X509_EXTENSION_free(ext)NEWLINE _lib.sk_X509_EXTENSION_delete(stack, i)NEWLINE breakNEWLINENEWLINENEWLINE def set_reason(self, reason):NEWLINE """NEWLINE Set the reason of a Revoked object.NEWLINENEWLINE If :py:data:`reason` is :py:data:`None`, delete the reason instead.NEWLINENEWLINE :param reason: The reason string.NEWLINE :type reason: :py:class:`str` or :py:class:`NoneType`NEWLINE :return: NoneNEWLINE """NEWLINE if reason is None:NEWLINE self._delete_reason()NEWLINE elif not isinstance(reason, bytes):NEWLINE raise TypeError("reason must be None or a byte string")NEWLINE else:NEWLINE reason = reason.lower().replace(b' ', b'')NEWLINE reason_code = [r.lower() for r in self._crl_reasons].index(reason)NEWLINENEWLINE new_reason_ext = _lib.ASN1_ENUMERATED_new()NEWLINE if new_reason_ext == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)NEWLINENEWLINE set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)NEWLINE if set_result == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE self._delete_reason()NEWLINE add_result = _lib.X509_REVOKED_add1_ext_i2d(NEWLINE self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)NEWLINENEWLINE if not add_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_reason(self):NEWLINE """NEWLINE Return the reason of a Revoked object.NEWLINENEWLINE :return: The reason as a stringNEWLINE """NEWLINE extensions = self._revoked.extensionsNEWLINE for i in range(_lib.sk_X509_EXTENSION_num(extensions)):NEWLINE ext = _lib.sk_X509_EXTENSION_value(extensions, i)NEWLINE if _lib.OBJ_obj2nid(ext.object) == _lib.NID_crl_reason:NEWLINE bio = _new_mem_buf()NEWLINENEWLINE print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)NEWLINE if not print_result:NEWLINE print_result = _lib.M_ASN1_OCTET_STRING_print(bio, ext.value)NEWLINE if print_result == 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINE def all_reasons(self):NEWLINE """NEWLINE Return a list of all the supported reason strings.NEWLINENEWLINE :return: A list of reason strings.NEWLINE """NEWLINE return self._crl_reasons[:]NEWLINENEWLINENEWLINE def set_rev_date(self, when):NEWLINE """NEWLINE Set the revocation timestampNEWLINENEWLINE :param when: A string giving the timestamp, in the format:NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return _set_asn1_time(self._revoked.revocationDate, when)NEWLINENEWLINENEWLINE def get_rev_date(self):NEWLINE """NEWLINE Retrieve the revocation dateNEWLINENEWLINE :return: A string giving the timestamp, in the format:NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINE """NEWLINE return _get_asn1_time(self._revoked.revocationDate)NEWLINENEWLINENEWLINENEWLINEclass CRL(object):NEWLINE def __init__(self):NEWLINE """NEWLINE Create a new empty CRL object.NEWLINE """NEWLINE crl = _lib.X509_CRL_new()NEWLINE self._crl = _ffi.gc(crl, _lib.X509_CRL_free)NEWLINENEWLINENEWLINE def get_revoked(self):NEWLINE """NEWLINE Return revoked portion of the CRL structure (by value not reference).NEWLINENEWLINE :return: A tuple of Revoked objects.NEWLINE """NEWLINE results = []NEWLINE revoked_stack = self._crl.crl.revokedNEWLINE for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):NEWLINE revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)NEWLINE revoked_copy = _X509_REVOKED_dup(revoked)NEWLINE pyrev = Revoked.__new__(Revoked)NEWLINE pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)NEWLINE results.append(pyrev)NEWLINE if results:NEWLINE return tuple(results)NEWLINENEWLINENEWLINE def add_revoked(self, revoked):NEWLINE """NEWLINE Add a revoked (by value not reference) to the CRL structureNEWLINENEWLINE :param revoked: The new revoked.NEWLINE :type revoked: :class:`X509`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE copy = _X509_REVOKED_dup(revoked._revoked)NEWLINE if copy == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)NEWLINE if add_result == 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def export(self, cert, key, type=FILETYPE_PEM, days=100):NEWLINE """NEWLINE export a CRL as a stringNEWLINENEWLINE :param cert: Used to sign CRL.NEWLINE :type cert: :class:`X509`NEWLINENEWLINE :param key: Used to sign CRL.NEWLINE :type key: :class:`PKey`NEWLINENEWLINE :param type: The export format, either :py:data:`FILETYPE_PEM`, :py:data:`FILETYPE_ASN1`, or :py:data:`FILETYPE_TEXT`.NEWLINENEWLINE :param days: The number of days until the next update of this CRL.NEWLINE :type days: :py:data:`int`NEWLINENEWLINE :return: :py:data:`str`NEWLINE """NEWLINE if not isinstance(cert, X509):NEWLINE raise TypeError("cert must be an X509 instance")NEWLINE if not isinstance(key, PKey):NEWLINE raise TypeError("key must be a PKey instance")NEWLINE if not isinstance(type, int):NEWLINE raise TypeError("type must be an integer")NEWLINENEWLINE bio = _lib.BIO_new(_lib.BIO_s_mem())NEWLINE if bio == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE # A scratch time object to give different values to different CRL fieldsNEWLINE sometime = _lib.ASN1_TIME_new()NEWLINE if sometime == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE _lib.X509_gmtime_adj(sometime, 0)NEWLINE _lib.X509_CRL_set_lastUpdate(self._crl, sometime)NEWLINENEWLINE _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)NEWLINE _lib.X509_CRL_set_nextUpdate(self._crl, sometime)NEWLINENEWLINE _lib.X509_CRL_set_issuer_name(self._crl, _lib.X509_get_subject_name(cert._x509))NEWLINENEWLINE sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, _lib.EVP_md5())NEWLINE if not sign_result:NEWLINE _raise_current_error()NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE ret = _lib.PEM_write_bio_X509_CRL(bio, self._crl)NEWLINE elif type == FILETYPE_ASN1:NEWLINE ret = _lib.i2d_X509_CRL_bio(bio, self._crl)NEWLINE elif type == FILETYPE_TEXT:NEWLINE ret = _lib.X509_CRL_print(bio, self._crl)NEWLINE else:NEWLINE raise ValueError(NEWLINE "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT")NEWLINENEWLINE if not ret:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINECRLType = CRLNEWLINENEWLINENEWLINENEWLINEclass PKCS7(object):NEWLINE def type_is_signed(self):NEWLINE """NEWLINE Check if this NID_pkcs7_signed objectNEWLINENEWLINE :return: True if the PKCS7 is of type signedNEWLINE """NEWLINE if _lib.PKCS7_type_is_signed(self._pkcs7):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE def type_is_enveloped(self):NEWLINE """NEWLINE Check if this NID_pkcs7_enveloped objectNEWLINENEWLINE :returns: True if the PKCS7 is of type envelopedNEWLINE """NEWLINE if _lib.PKCS7_type_is_enveloped(self._pkcs7):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE def type_is_signedAndEnveloped(self):NEWLINE """NEWLINE Check if this NID_pkcs7_signedAndEnveloped objectNEWLINENEWLINE :returns: True if the PKCS7 is of type signedAndEnvelopedNEWLINE """NEWLINE if _lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE def type_is_data(self):NEWLINE """NEWLINE Check if this NID_pkcs7_data objectNEWLINENEWLINE :return: True if the PKCS7 is of type dataNEWLINE """NEWLINE if _lib.PKCS7_type_is_data(self._pkcs7):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE def get_type_name(self):NEWLINE """NEWLINE Returns the type name of the PKCS7 structureNEWLINENEWLINE :return: A string with the typenameNEWLINE """NEWLINE nid = _lib.OBJ_obj2nid(self._pkcs7.type)NEWLINE string_type = _lib.OBJ_nid2sn(nid)NEWLINE return _ffi.string(string_type)NEWLINENEWLINEPKCS7Type = PKCS7NEWLINENEWLINENEWLINENEWLINEclass PKCS12(object):NEWLINE def __init__(self):NEWLINE self._pkey = NoneNEWLINE self._cert = NoneNEWLINE self._cacerts = NoneNEWLINE self._friendlyname = NoneNEWLINENEWLINENEWLINE def get_certificate(self):NEWLINE """NEWLINE Return certificate portion of the PKCS12 structureNEWLINENEWLINE :return: X509 object containing the certificateNEWLINE """NEWLINE return self._certNEWLINENEWLINENEWLINE def set_certificate(self, cert):NEWLINE """NEWLINE Replace the certificate portion of the PKCS12 structureNEWLINENEWLINE :param cert: The new certificate.NEWLINE :type cert: :py:class:`X509` or :py:data:`None`NEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(cert, X509):NEWLINE raise TypeError("cert must be an X509 instance")NEWLINE self._cert = certNEWLINENEWLINENEWLINE def get_privatekey(self):NEWLINE """NEWLINE Return private key portion of the PKCS12 structureNEWLINENEWLINE :returns: PKey object containing the private keyNEWLINE """NEWLINE return self._pkeyNEWLINENEWLINENEWLINE def set_privatekey(self, pkey):NEWLINE """NEWLINE Replace or set the certificate portion of the PKCS12 structureNEWLINENEWLINE :param pkey: The new private key.NEWLINE :type pkey: :py:class:`PKey`NEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(pkey, PKey):NEWLINE raise TypeError("pkey must be a PKey instance")NEWLINE self._pkey = pkeyNEWLINENEWLINENEWLINE def get_ca_certificates(self):NEWLINE """NEWLINE Return CA certificates within of the PKCS12 objectNEWLINENEWLINE :return: A newly created tuple containing the CA certificates in the chain,NEWLINE if any are present, or None if no CA certificates are present.NEWLINE """NEWLINE if self._cacerts is not None:NEWLINE return tuple(self._cacerts)NEWLINENEWLINENEWLINE def set_ca_certificates(self, cacerts):NEWLINE """NEWLINE Replace or set the CA certificates withing the PKCS12 object.NEWLINENEWLINE :param cacerts: The new CA certificates.NEWLINE :type cacerts: :py:data:`None` or an iterable of :py:class:`X509`NEWLINE :return: NoneNEWLINE """NEWLINE if cacerts is None:NEWLINE self._cacerts = NoneNEWLINE else:NEWLINE cacerts = list(cacerts)NEWLINE for cert in cacerts:NEWLINE if not isinstance(cert, X509):NEWLINE raise TypeError("iterable must only contain X509 instances")NEWLINE self._cacerts = cacertsNEWLINENEWLINENEWLINE def set_friendlyname(self, name):NEWLINE """NEWLINE Replace or set the certificate portion of the PKCS12 structureNEWLINENEWLINE :param name: The new friendly name.NEWLINE :type name: :py:class:`bytes`NEWLINE :return: NoneNEWLINE """NEWLINE if name is None:NEWLINE self._friendlyname = NoneNEWLINE elif not isinstance(name, bytes):NEWLINE raise TypeError("name must be a byte string or None (not %r)" % (name,))NEWLINE self._friendlyname = nameNEWLINENEWLINENEWLINE def get_friendlyname(self):NEWLINE """NEWLINE Return friendly name portion of the PKCS12 structureNEWLINENEWLINE :returns: String containing the friendlynameNEWLINE """NEWLINE return self._friendlynameNEWLINENEWLINENEWLINE def export(self, passphrase=None, iter=2048, maciter=1):NEWLINE """NEWLINE Dump a PKCS12 object as a string. See also "man PKCS12_create".NEWLINENEWLINE :param passphrase: used to encrypt the PKCS12NEWLINE :type passphrase: :py:data:`bytes`NEWLINENEWLINE :param iter: How many times to repeat the encryptionNEWLINE :type iter: :py:data:`int`NEWLINENEWLINE :param maciter: How many times to repeat the MACNEWLINE :type maciter: :py:data:`int`NEWLINENEWLINE :return: The string containing the PKCS12NEWLINE """NEWLINE if self._cacerts is None:NEWLINE cacerts = _ffi.NULLNEWLINE else:NEWLINE cacerts = _lib.sk_X509_new_null()NEWLINE cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)NEWLINE for cert in self._cacerts:NEWLINE _lib.sk_X509_push(cacerts, cert._x509)NEWLINENEWLINE if passphrase is None:NEWLINE passphrase = _ffi.NULLNEWLINENEWLINE friendlyname = self._friendlynameNEWLINE if friendlyname is None:NEWLINE friendlyname = _ffi.NULLNEWLINENEWLINE if self._pkey is None:NEWLINE pkey = _ffi.NULLNEWLINE else:NEWLINE pkey = self._pkey._pkeyNEWLINENEWLINE if self._cert is None:NEWLINE cert = _ffi.NULLNEWLINE else:NEWLINE cert = self._cert._x509NEWLINENEWLINE pkcs12 = _lib.PKCS12_create(NEWLINE passphrase, friendlyname, pkey, cert, cacerts,NEWLINE _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,NEWLINE _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,NEWLINE iter, maciter, 0)NEWLINE if pkcs12 == _ffi.NULL:NEWLINE _raise_current_error()NEWLINE pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)NEWLINENEWLINE bio = _new_mem_buf()NEWLINE _lib.i2d_PKCS12_bio(bio, pkcs12)NEWLINE return _bio_to_string(bio)NEWLINENEWLINEPKCS12Type = PKCS12NEWLINENEWLINENEWLINENEWLINEclass NetscapeSPKI(object):NEWLINE def __init__(self):NEWLINE spki = _lib.NETSCAPE_SPKI_new()NEWLINE self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)NEWLINENEWLINENEWLINE def sign(self, pkey, digest):NEWLINE """NEWLINE Sign the certificate request using the supplied key and digestNEWLINENEWLINE :param pkey: The key to sign withNEWLINE :param digest: The message digest to useNEWLINE :return: NoneNEWLINE """NEWLINE if pkey._only_public:NEWLINE raise ValueError("Key has only public part")NEWLINENEWLINE if not pkey._initialized:NEWLINE raise ValueError("Key is uninitialized")NEWLINENEWLINE digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if digest_obj == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE sign_result = _lib.NETSCAPE_SPKI_sign(self._spki, pkey._pkey, digest_obj)NEWLINE if not sign_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def verify(self, key):NEWLINE """NEWLINE Verifies a certificate request using the supplied public keyNEWLINENEWLINE :param key: a public keyNEWLINE :return: True if the signature is correct.NEWLINE :raise OpenSSL.crypto.Error: If the signature is invalid or there is aNEWLINE problem verifying the signature.NEWLINE """NEWLINE answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)NEWLINE if answer <= 0:NEWLINE _raise_current_error()NEWLINE return TrueNEWLINENEWLINENEWLINE def b64_encode(self):NEWLINE """NEWLINE Generate a base64 encoded string from an SPKINEWLINENEWLINE :return: The base64 encoded stringNEWLINE """NEWLINE encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)NEWLINE result = _ffi.string(encoded)NEWLINE _lib.CRYPTO_free(encoded)NEWLINE return resultNEWLINENEWLINENEWLINE def get_pubkey(self):NEWLINE """NEWLINE Get the public key of the certificateNEWLINENEWLINE :return: The public keyNEWLINE """NEWLINE pkey = PKey.__new__(PKey)NEWLINE pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)NEWLINE if pkey._pkey == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)NEWLINE pkey._only_public = TrueNEWLINE return pkeyNEWLINENEWLINENEWLINE def set_pubkey(self, pkey):NEWLINE """NEWLINE Set the public key of the certificateNEWLINENEWLINE :param pkey: The public keyNEWLINE :return: NoneNEWLINE """NEWLINE set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)NEWLINE if not set_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENetscapeSPKIType = NetscapeSPKINEWLINENEWLINENEWLINEclass _PassphraseHelper(object):NEWLINE def __init__(self, type, passphrase, more_args=False, truncate=False):NEWLINE if type != FILETYPE_PEM and passphrase is not None:NEWLINE raise ValueError("only FILETYPE_PEM key format supports encryption")NEWLINE self._passphrase = passphraseNEWLINE self._more_args = more_argsNEWLINE self._truncate = truncateNEWLINE self._problems = []NEWLINENEWLINENEWLINE @propertyNEWLINE def callback(self):NEWLINE if self._passphrase is None:NEWLINE return _ffi.NULLNEWLINE elif isinstance(self._passphrase, bytes):NEWLINE return _ffi.NULLNEWLINE elif callable(self._passphrase):NEWLINE return _ffi.callback("pem_password_cb", self._read_passphrase)NEWLINE else:NEWLINE raise TypeError("Last argument must be string or callable")NEWLINENEWLINENEWLINE @propertyNEWLINE def callback_args(self):NEWLINE if self._passphrase is None:NEWLINE return _ffi.NULLNEWLINE elif isinstance(self._passphrase, bytes):NEWLINE return self._passphraseNEWLINE elif callable(self._passphrase):NEWLINE return _ffi.NULLNEWLINE else:NEWLINE raise TypeError("Last argument must be string or callable")NEWLINENEWLINENEWLINE def raise_if_problem(self, exceptionType=Error):NEWLINE try:NEWLINE _exception_from_error_queue(exceptionType)NEWLINE except exceptionType as e:NEWLINE from_queue = eNEWLINE if self._problems:NEWLINE raise self._problems[0]NEWLINE return from_queueNEWLINENEWLINENEWLINE def _read_passphrase(self, buf, size, rwflag, userdata):NEWLINE try:NEWLINE if self._more_args:NEWLINE result = self._passphrase(size, rwflag, userdata)NEWLINE else:NEWLINE result = self._passphrase(rwflag)NEWLINE if not isinstance(result, bytes):NEWLINE raise ValueError("String expected")NEWLINE if len(result) > size:NEWLINE if self._truncate:NEWLINE result = result[:size]NEWLINE else:NEWLINE raise ValueError("passphrase returned by callback is too long")NEWLINE for i in range(len(result)):NEWLINE buf[i] = result[i:i + 1]NEWLINE return len(result)NEWLINE except Exception as e:NEWLINE self._problems.append(e)NEWLINE return 0NEWLINENEWLINENEWLINENEWLINEdef load_privatekey(type, buffer, passphrase=None):NEWLINE """NEWLINE Load a private key from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINE :param buffer: The buffer the key is stored inNEWLINE :param passphrase: (optional) if encrypted PEM format, this can beNEWLINE either the passphrase to use, or a callback forNEWLINE providing the passphrase.NEWLINENEWLINE :return: The PKey objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE helper = _PassphraseHelper(type, passphrase)NEWLINE if type == FILETYPE_PEM:NEWLINE evp_pkey = _lib.PEM_read_bio_PrivateKey(NEWLINE bio, _ffi.NULL, helper.callback, helper.callback_args)NEWLINE helper.raise_if_problem()NEWLINE elif type == FILETYPE_ASN1:NEWLINE evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)NEWLINE else:NEWLINE raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if evp_pkey == _ffi.NULL:NEWLINE _raise_current_error()NEWLINENEWLINE pkey = PKey.__new__(PKey)NEWLINE pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)NEWLINE return pkeyNEWLINENEWLINENEWLINENEWLINEdef dump_certificate_request(type, req):NEWLINE """NEWLINE Dump a certificate request to a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINE :param req: The certificate request to dumpNEWLINE :return: The buffer with the dumped certificate request inNEWLINE """NEWLINE bio = _new_mem_buf()NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)NEWLINE elif type == FILETYPE_ASN1:NEWLINE result_code = _lib.i2d_X509_REQ_bio(bio, req._req)NEWLINE elif type == FILETYPE_TEXT:NEWLINE result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)NEWLINE else:NEWLINE raise ValueError("type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT")NEWLINENEWLINE if result_code == 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINENEWLINEdef load_certificate_request(type, buffer):NEWLINE """NEWLINE Load a certificate request from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINE :param buffer: The buffer the certificate request is stored inNEWLINE :return: The X509Req objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE elif type == FILETYPE_ASN1:NEWLINE req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)NEWLINE else:NEWLINE raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if req == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE x509req = X509Req.__new__(X509Req)NEWLINE x509req._req = _ffi.gc(req, _lib.X509_REQ_free)NEWLINE return x509reqNEWLINENEWLINENEWLINENEWLINEdef sign(pkey, data, digest):NEWLINE """NEWLINE Sign data with a digestNEWLINENEWLINE :param pkey: Pkey to sign withNEWLINE :param data: data to be signedNEWLINE :param digest: message digest to useNEWLINE :return: signatureNEWLINE """NEWLINE digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if digest_obj == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE md_ctx = _ffi.new("EVP_MD_CTX*")NEWLINE md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup)NEWLINENEWLINE _lib.EVP_SignInit(md_ctx, digest_obj)NEWLINE _lib.EVP_SignUpdate(md_ctx, data, len(data))NEWLINENEWLINE signature_buffer = _ffi.new("unsigned char[]", 512)NEWLINE signature_length = _ffi.new("unsigned int*")NEWLINE signature_length[0] = len(signature_buffer)NEWLINE final_result = _lib.EVP_SignFinal(NEWLINE md_ctx, signature_buffer, signature_length, pkey._pkey)NEWLINENEWLINE if final_result != 1:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _ffi.buffer(signature_buffer, signature_length[0])[:]NEWLINENEWLINENEWLINENEWLINEdef verify(cert, signature, data, digest):NEWLINE """NEWLINE Verify a signatureNEWLINENEWLINE :param cert: signing certificate (X509 object)NEWLINE :param signature: signature returned by sign functionNEWLINE :param data: data to be verifiedNEWLINE :param digest: message digest to useNEWLINE :return: None if the signature is correct, raise exception otherwiseNEWLINE """NEWLINE digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if digest_obj == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE pkey = _lib.X509_get_pubkey(cert._x509)NEWLINE if pkey == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)NEWLINENEWLINE md_ctx = _ffi.new("EVP_MD_CTX*")NEWLINE md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup)NEWLINENEWLINE _lib.EVP_VerifyInit(md_ctx, digest_obj)NEWLINE _lib.EVP_VerifyUpdate(md_ctx, data, len(data))NEWLINE verify_result = _lib.EVP_VerifyFinal(md_ctx, signature, len(signature), pkey)NEWLINENEWLINE if verify_result != 1:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINENEWLINEdef load_crl(type, buffer):NEWLINE """NEWLINE Load a certificate revocation list from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINE :param buffer: The buffer the CRL is stored inNEWLINENEWLINE :return: The PKey objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE elif type == FILETYPE_ASN1:NEWLINE crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)NEWLINE else:NEWLINE raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if crl == _ffi.NULL:NEWLINE _raise_current_error()NEWLINENEWLINE result = CRL.__new__(CRL)NEWLINE result._crl = crlNEWLINE return resultNEWLINENEWLINENEWLINENEWLINEdef load_pkcs7_data(type, buffer):NEWLINE """NEWLINE Load pkcs7 data from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)NEWLINE :param buffer: The buffer with the pkcs7 data.NEWLINE :return: The PKCS7 objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE elif type == FILETYPE_ASN1:NEWLINE passNEWLINE else:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if pkcs7 == _ffi.NULL:NEWLINE _raise_current_error()NEWLINENEWLINE pypkcs7 = PKCS7.__new__(PKCS7)NEWLINE pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)NEWLINE return pypkcs7NEWLINENEWLINENEWLINENEWLINEdef load_pkcs12(buffer, passphrase):NEWLINE """NEWLINE Load a PKCS12 object from a bufferNEWLINENEWLINE :param buffer: The buffer the certificate is stored inNEWLINE :param passphrase: (Optional) The password to decrypt the PKCS12 lumpNEWLINE :returns: The PKCS12 objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)NEWLINE if p12 == _ffi.NULL:NEWLINE _raise_current_error()NEWLINE p12 = _ffi.gc(p12, _lib.PKCS12_free)NEWLINENEWLINE pkey = _ffi.new("EVP_PKEY**")NEWLINE cert = _ffi.new("X509**")NEWLINE cacerts = _ffi.new("Cryptography_STACK_OF_X509**")NEWLINENEWLINE parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)NEWLINE if not parse_result:NEWLINE _raise_current_error()NEWLINENEWLINE cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)NEWLINENEWLINE # openssl 1.0.0 sometimes leaves an X509_check_private_key error in theNEWLINE # queue for no particular reason. This error isn't interesting to anyoneNEWLINE # outside this function. It's not even interesting to us. Get rid of it.NEWLINE try:NEWLINE _raise_current_error()NEWLINE except Error:NEWLINE passNEWLINENEWLINE if pkey[0] == _ffi.NULL:NEWLINE pykey = NoneNEWLINE else:NEWLINE pykey = PKey.__new__(PKey)NEWLINE pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)NEWLINENEWLINE if cert[0] == _ffi.NULL:NEWLINE pycert = NoneNEWLINE friendlyname = NoneNEWLINE else:NEWLINE pycert = X509.__new__(X509)NEWLINE pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)NEWLINENEWLINE friendlyname_length = _ffi.new("int*")NEWLINE friendlyname_buffer = _lib.X509_alias_get0(cert[0], friendlyname_length)NEWLINE friendlyname = _ffi.buffer(friendlyname_buffer, friendlyname_length[0])[:]NEWLINE if friendlyname_buffer == _ffi.NULL:NEWLINE friendlyname = NoneNEWLINENEWLINE pycacerts = []NEWLINE for i in range(_lib.sk_X509_num(cacerts)):NEWLINE pycacert = X509.__new__(X509)NEWLINE pycacert._x509 = _lib.sk_X509_value(cacerts, i)NEWLINE pycacerts.append(pycacert)NEWLINE if not pycacerts:NEWLINE pycacerts = NoneNEWLINENEWLINE pkcs12 = PKCS12.__new__(PKCS12)NEWLINE pkcs12._pkey = pykeyNEWLINE pkcs12._cert = pycertNEWLINE pkcs12._cacerts = pycacertsNEWLINE pkcs12._friendlyname = friendlynameNEWLINE return pkcs12NEWLINENEWLINENEWLINEdef _initialize_openssl_threads(get_ident, Lock):NEWLINE import _sslNEWLINE returnNEWLINENEWLINE locks = list(Lock() for n in range(_lib.CRYPTO_num_locks()))NEWLINENEWLINE def locking_function(mode, index, filename, line):NEWLINE if mode & _lib.CRYPTO_LOCK:NEWLINE locks[index].acquire()NEWLINE else:NEWLINE locks[index].release()NEWLINENEWLINE _lib.CRYPTO_set_id_callback(NEWLINE _ffi.callback("unsigned long (*)(void)", get_ident))NEWLINENEWLINE _lib.CRYPTO_set_locking_callback(NEWLINE _ffi.callback(NEWLINE "void (*)(int, int, const char*, int)", locking_function))NEWLINENEWLINENEWLINEtry:NEWLINE from thread import get_identNEWLINE from threading import LockNEWLINEexcept ImportError:NEWLINE passNEWLINEelse:NEWLINE _initialize_openssl_threads(get_ident, Lock)NEWLINE del get_ident, LockNEWLINENEWLINE# There are no direct unit tests for this initialization. It is testedNEWLINE# indirectly since it is necessary for functions like dump_privatekey whenNEWLINE# using encryption.NEWLINE#NEWLINE# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphraseNEWLINE# and some other similar tests may fail without this (though they may not ifNEWLINE# the Python runtime has already done some initialization of the underlyingNEWLINE# OpenSSL library (and is linked against the same one that cryptography isNEWLINE# using)).NEWLINE_lib.OpenSSL_add_all_algorithms()NEWLINENEWLINE# This is similar but exercised mainly by exception_from_error_queue. It callsNEWLINE# both ERR_load_crypto_strings() and ERR_load_SSL_strings().NEWLINE_lib.SSL_load_error_strings()NEWLINE begin_unitNEWLINEcomment|'# Copyright 2011 Eldar Nugaev'NEWLINEnl|'\n'NEWLINEcomment|'# All Rights Reserved.'NEWLINEnl|'\n'NEWLINEcomment|'#'NEWLINEnl|'\n'NEWLINEcomment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'NEWLINEnl|'\n'NEWLINEcomment|'# not use this file except in compliance with the License. You may obtain'NEWLINEnl|'\n'NEWLINEcomment|'# a copy of the License at'NEWLINEnl|'\n'NEWLINEcomment|'#'NEWLINEnl|'\n'NEWLINEcomment|'# http://www.apache.org/licenses/LICENSE-2.0'NEWLINEnl|'\n'NEWLINEcomment|'#'NEWLINEnl|'\n'NEWLINEcomment|'# Unless required by applicable law or agreed to in writing, software'NEWLINEnl|'\n'NEWLINEcomment|'# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT'NEWLINEnl|'\n'NEWLINEcomment|'# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the'NEWLINEnl|'\n'NEWLINEcomment|'# License for the specific language governing permissions and limitations'NEWLINEnl|'\n'NEWLINEcomment|'# under the License.'NEWLINEnl|'\n'NEWLINEnl|'\n'NEWLINEname|'import'NEWLINEname|'string'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEname|'import'NEWLINEname|'mock'NEWLINEnewline|'\n'NEWLINEname|'import'NEWLINEname|'webob'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEname|'from'NEWLINEname|'nova'NEWLINEop|'.'NEWLINEname|'api'NEWLINEop|'.'NEWLINEname|'openstack'NEWLINEop|'.'NEWLINEname|'compute'NEWLINEname|'import'NEWLINEname|'console_output'NEWLINEname|'as'NEWLINEname|'console_output_v21'NEWLINEnewline|'\n'NEWLINEname|'from'NEWLINEname|'nova'NEWLINEop|'.'NEWLINEname|'compute'NEWLINEname|'import'NEWLINEname|'api'NEWLINEname|'as'NEWLINEname|'compute_api'NEWLINEnewline|'\n'NEWLINEname|'from'NEWLINEname|'nova'NEWLINEname|'import'NEWLINEname|'exception'NEWLINEnewline|'\n'NEWLINEname|'from'NEWLINEname|'nova'NEWLINEname|'import'NEWLINEname|'test'NEWLINEnewline|'\n'NEWLINEname|'from'NEWLINEname|'nova'NEWLINEop|'.'NEWLINEname|'tests'NEWLINEop|'.'NEWLINEname|'unit'NEWLINEop|'.'NEWLINEname|'api'NEWLINEop|'.'NEWLINEname|'openstack'NEWLINEname|'import'NEWLINEname|'fakes'NEWLINEnewline|'\n'NEWLINEname|'from'NEWLINEname|'nova'NEWLINEop|'.'NEWLINEname|'tests'NEWLINEop|'.'NEWLINEname|'unit'NEWLINEname|'import'NEWLINEname|'fake_instance'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEnl|'\n'NEWLINEDECL|function|fake_get_console_outputNEWLINEname|'def'NEWLINEname|'fake_get_console_output'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|','NEWLINEname|'_context'NEWLINEop|','NEWLINEname|'_instance'NEWLINEop|','NEWLINEname|'tail_length'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'fixture'NEWLINEop|'='NEWLINEop|'['NEWLINEname|'str'NEWLINEop|'('NEWLINEname|'i'NEWLINEop|')'NEWLINEname|'for'NEWLINEname|'i'NEWLINEname|'in'NEWLINEname|'range'NEWLINEop|'('NEWLINEnumber|'5'NEWLINEop|')'NEWLINEop|']'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEname|'if'NEWLINEname|'tail_length'NEWLINEname|'is'NEWLINEname|'None'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'pass'NEWLINEnewline|'\n'NEWLINEdedent|''NEWLINEname|'elif'NEWLINEname|'tail_length'NEWLINEop|'=='NEWLINEnumber|'0'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'fixture'NEWLINEop|'='NEWLINEop|'['NEWLINEop|']'NEWLINEnewline|'\n'NEWLINEdedent|''NEWLINEname|'else'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'fixture'NEWLINEop|'='NEWLINEname|'fixture'NEWLINEop|'['NEWLINEop|'-'NEWLINEname|'int'NEWLINEop|'('NEWLINEname|'tail_length'NEWLINEop|')'NEWLINEop|':'NEWLINEop|']'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEdedent|''NEWLINEname|'return'NEWLINEstring|"'\\n'"NEWLINEop|'.'NEWLINEname|'join'NEWLINEop|'('NEWLINEname|'fixture'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEnl|'\n'NEWLINEDECL|function|fake_get_console_output_not_readyNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'fake_get_console_output_not_ready'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|','NEWLINEname|'_context'NEWLINEop|','NEWLINEname|'_instance'NEWLINEop|','NEWLINEname|'tail_length'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'raise'NEWLINEname|'exception'NEWLINEop|'.'NEWLINEname|'InstanceNotReady'NEWLINEop|'('NEWLINEname|'instance_id'NEWLINEop|'='NEWLINEname|'_instance'NEWLINEop|'['NEWLINEstring|'"uuid"'NEWLINEop|']'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEnl|'\n'NEWLINEDECL|function|fake_get_console_output_all_charactersNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'fake_get_console_output_all_characters'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|','NEWLINEname|'_ctx'NEWLINEop|','NEWLINEname|'_instance'NEWLINEop|','NEWLINEname|'_tail_len'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'return'NEWLINEname|'string'NEWLINEop|'.'NEWLINEname|'printable'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEnl|'\n'NEWLINEDECL|function|fake_getNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'fake_get'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|','NEWLINEname|'context'NEWLINEop|','NEWLINEname|'instance_uuid'NEWLINEop|','NEWLINEname|'want_objects'NEWLINEop|'='NEWLINEname|'False'NEWLINEop|','NEWLINEnl|'\n'NEWLINEname|'expected_attrs'NEWLINEop|'='NEWLINEname|'None'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'return'NEWLINEname|'fake_instance'NEWLINEop|'.'NEWLINEname|'fake_instance_obj'NEWLINEop|'('NEWLINEname|'context'NEWLINEop|','NEWLINEop|'**'NEWLINEop|'{'NEWLINEstring|"'uuid'"NEWLINEop|':'NEWLINEname|'instance_uuid'NEWLINEop|'}'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEnl|'\n'NEWLINEDECL|function|fake_get_not_foundNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'fake_get_not_found'NEWLINEop|'('NEWLINEop|'*'NEWLINEname|'args'NEWLINEop|','NEWLINEop|'**'NEWLINEname|'kwargs'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'raise'NEWLINEname|'exception'NEWLINEop|'.'NEWLINEname|'InstanceNotFound'NEWLINEop|'('NEWLINEname|'instance_id'NEWLINEop|'='NEWLINEstring|"'fake'"NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEnl|'\n'NEWLINEDECL|class|ConsoleOutputExtensionTestV21NEWLINEdedent|''NEWLINEname|'class'NEWLINEname|'ConsoleOutputExtensionTestV21'NEWLINEop|'('NEWLINEname|'test'NEWLINEop|'.'NEWLINEname|'NoDBTestCase'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEDECL|variable|controller_classNEWLINEindent|' 'NEWLINEname|'controller_class'NEWLINEop|'='NEWLINEname|'console_output_v21'NEWLINEnewline|'\n'NEWLINEDECL|variable|validation_errorNEWLINEname|'validation_error'NEWLINEop|'='NEWLINEname|'exception'NEWLINEop|'.'NEWLINEname|'ValidationError'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|setUpNEWLINEname|'def'NEWLINEname|'setUp'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'super'NEWLINEop|'('NEWLINEname|'ConsoleOutputExtensionTestV21'NEWLINEop|','NEWLINEname|'self'NEWLINEop|')'NEWLINEop|'.'NEWLINEname|'setUp'NEWLINEop|'('NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'stubs'NEWLINEop|'.'NEWLINEname|'Set'NEWLINEop|'('NEWLINEname|'compute_api'NEWLINEop|'.'NEWLINEname|'API'NEWLINEop|','NEWLINEstring|"'get_console_output'"NEWLINEop|','NEWLINEnl|'\n'NEWLINEname|'fake_get_console_output'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'stubs'NEWLINEop|'.'NEWLINEname|'Set'NEWLINEop|'('NEWLINEname|'compute_api'NEWLINEop|'.'NEWLINEname|'API'NEWLINEop|','NEWLINEstring|"'get'"NEWLINEop|','NEWLINEname|'fake_get'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'controller'NEWLINEop|'='NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'controller_class'NEWLINEop|'.'NEWLINEname|'ConsoleOutputController'NEWLINEop|'('NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'req'NEWLINEop|'='NEWLINEname|'fakes'NEWLINEop|'.'NEWLINEname|'HTTPRequest'NEWLINEop|'.'NEWLINEname|'blank'NEWLINEop|'('NEWLINEstring|"''"NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|_get_console_outputNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'_get_console_output'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|','NEWLINEname|'length_dict'NEWLINEop|'='NEWLINEname|'None'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'length_dict'NEWLINEop|'='NEWLINEname|'length_dict'NEWLINEname|'or'NEWLINEop|'{'NEWLINEop|'}'NEWLINEnewline|'\n'NEWLINEname|'body'NEWLINEop|'='NEWLINEop|'{'NEWLINEstring|"'os-getConsoleOutput'"NEWLINEop|':'NEWLINEname|'length_dict'NEWLINEop|'}'NEWLINEnewline|'\n'NEWLINEname|'return'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'controller'NEWLINEop|'.'NEWLINEname|'get_console_output'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'req'NEWLINEop|','NEWLINEname|'fakes'NEWLINEop|'.'NEWLINEname|'FAKE_UUID'NEWLINEop|','NEWLINEnl|'\n'NEWLINEname|'body'NEWLINEop|'='NEWLINEname|'body'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|_check_console_output_failureNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'_check_console_output_failure'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|','NEWLINEname|'exception'NEWLINEop|','NEWLINEname|'body'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'assertRaises'NEWLINEop|'('NEWLINEname|'exception'NEWLINEop|','NEWLINEnl|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'controller'NEWLINEop|'.'NEWLINEname|'get_console_output'NEWLINEop|','NEWLINEnl|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'req'NEWLINEop|','NEWLINEname|'fakes'NEWLINEop|'.'NEWLINEname|'FAKE_UUID'NEWLINEop|','NEWLINEname|'body'NEWLINEop|'='NEWLINEname|'body'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|test_get_text_console_instance_actionNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'test_get_text_console_instance_action'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'output'NEWLINEop|'='NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'_get_console_output'NEWLINEop|'('NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'assertEqual'NEWLINEop|'('NEWLINEop|'{'NEWLINEstring|"'output'"NEWLINEop|':'NEWLINEstring|"'0\\n1\\n2\\n3\\n4'"NEWLINEop|'}'NEWLINEop|','NEWLINEname|'output'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|test_get_console_output_with_tailNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'test_get_console_output_with_tail'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'output'NEWLINEop|'='NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'_get_console_output'NEWLINEop|'('NEWLINEname|'length_dict'NEWLINEop|'='NEWLINEop|'{'NEWLINEstring|"'length'"NEWLINEop|':'NEWLINEnumber|'3'NEWLINEop|'}'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'assertEqual'NEWLINEop|'('NEWLINEop|'{'NEWLINEstring|"'output'"NEWLINEop|':'NEWLINEstring|"'2\\n3\\n4'"NEWLINEop|'}'NEWLINEop|','NEWLINEname|'output'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|test_get_console_output_with_none_lengthNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'test_get_console_output_with_none_length'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'output'NEWLINEop|'='NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'_get_console_output'NEWLINEop|'('NEWLINEname|'length_dict'NEWLINEop|'='NEWLINEop|'{'NEWLINEstring|"'length'"NEWLINEop|':'NEWLINEname|'None'NEWLINEop|'}'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'assertEqual'NEWLINEop|'('NEWLINEop|'{'NEWLINEstring|"'output'"NEWLINEop|':'NEWLINEstring|"'0\\n1\\n2\\n3\\n4'"NEWLINEop|'}'NEWLINEop|','NEWLINEname|'output'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|test_get_console_output_with_length_as_strNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'test_get_console_output_with_length_as_str'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'output'NEWLINEop|'='NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'_get_console_output'NEWLINEop|'('NEWLINEname|'length_dict'NEWLINEop|'='NEWLINEop|'{'NEWLINEstring|"'length'"NEWLINEop|':'NEWLINEstring|"'3'"NEWLINEop|'}'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'assertEqual'NEWLINEop|'('NEWLINEop|'{'NEWLINEstring|"'output'"NEWLINEop|':'NEWLINEstring|"'2\\n3\\n4'"NEWLINEop|'}'NEWLINEop|','NEWLINEname|'output'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|test_get_console_output_filtered_charactersNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'test_get_console_output_filtered_characters'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'stubs'NEWLINEop|'.'NEWLINEname|'Set'NEWLINEop|'('NEWLINEname|'compute_api'NEWLINEop|'.'NEWLINEname|'API'NEWLINEop|','NEWLINEstring|"'get_console_output'"NEWLINEop|','NEWLINEnl|'\n'NEWLINEname|'fake_get_console_output_all_characters'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'output'NEWLINEop|'='NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'_get_console_output'NEWLINEop|'('NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'expect'NEWLINEop|'='NEWLINEname|'string'NEWLINEop|'.'NEWLINEname|'digits'NEWLINEop|'+'NEWLINEname|'string'NEWLINEop|'.'NEWLINEname|'letters'NEWLINEop|'+'NEWLINEname|'string'NEWLINEop|'.'NEWLINEname|'punctuation'NEWLINEop|'+'NEWLINEstring|"' \\t\\n'"NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'assertEqual'NEWLINEop|'('NEWLINEop|'{'NEWLINEstring|"'output'"NEWLINEop|':'NEWLINEname|'expect'NEWLINEop|'}'NEWLINEop|','NEWLINEname|'output'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|test_get_text_console_no_instanceNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'test_get_text_console_no_instance'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'stubs'NEWLINEop|'.'NEWLINEname|'Set'NEWLINEop|'('NEWLINEname|'compute_api'NEWLINEop|'.'NEWLINEname|'API'NEWLINEop|','NEWLINEstring|"'get'"NEWLINEop|','NEWLINEname|'fake_get_not_found'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'body'NEWLINEop|'='NEWLINEop|'{'NEWLINEstring|"'os-getConsoleOutput'"NEWLINEop|':'NEWLINEop|'{'NEWLINEop|'}'NEWLINEop|'}'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'_check_console_output_failure'NEWLINEop|'('NEWLINEname|'webob'NEWLINEop|'.'NEWLINEname|'exc'NEWLINEop|'.'NEWLINEname|'HTTPNotFound'NEWLINEop|','NEWLINEname|'body'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|test_get_text_console_no_instance_on_get_outputNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'test_get_text_console_no_instance_on_get_output'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'stubs'NEWLINEop|'.'NEWLINEname|'Set'NEWLINEop|'('NEWLINEname|'compute_api'NEWLINEop|'.'NEWLINEname|'API'NEWLINEop|','NEWLINEnl|'\n'NEWLINEstring|"'get_console_output'"NEWLINEop|','NEWLINEnl|'\n'NEWLINEname|'fake_get_not_found'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'body'NEWLINEop|'='NEWLINEop|'{'NEWLINEstring|"'os-getConsoleOutput'"NEWLINEop|':'NEWLINEop|'{'NEWLINEop|'}'NEWLINEop|'}'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'_check_console_output_failure'NEWLINEop|'('NEWLINEname|'webob'NEWLINEop|'.'NEWLINEname|'exc'NEWLINEop|'.'NEWLINEname|'HTTPNotFound'NEWLINEop|','NEWLINEname|'body'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|test_get_console_output_with_non_integer_lengthNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'test_get_console_output_with_non_integer_length'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'body'NEWLINEop|'='NEWLINEop|'{'NEWLINEstring|"'os-getConsoleOutput'"NEWLINEop|':'NEWLINEop|'{'NEWLINEstring|"'length'"NEWLINEop|':'NEWLINEstring|"'NaN'"NEWLINEop|'}'NEWLINEop|'}'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'_check_console_output_failure'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'validation_error'NEWLINEop|','NEWLINEname|'body'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|test_get_text_console_bad_bodyNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'test_get_text_console_bad_body'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'body'NEWLINEop|'='NEWLINEop|'{'NEWLINEop|'}'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'_check_console_output_failure'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'validation_error'NEWLINEop|','NEWLINEname|'body'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|test_get_console_output_with_length_as_floatNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'test_get_console_output_with_length_as_float'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'body'NEWLINEop|'='NEWLINEop|'{'NEWLINEstring|"'os-getConsoleOutput'"NEWLINEop|':'NEWLINEop|'{'NEWLINEstring|"'length'"NEWLINEop|':'NEWLINEnumber|'2.5'NEWLINEop|'}'NEWLINEop|'}'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'_check_console_output_failure'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'validation_error'NEWLINEop|','NEWLINEname|'body'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|test_get_console_output_not_readyNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'test_get_console_output_not_ready'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'stubs'NEWLINEop|'.'NEWLINEname|'Set'NEWLINEop|'('NEWLINEname|'compute_api'NEWLINEop|'.'NEWLINEname|'API'NEWLINEop|','NEWLINEstring|"'get_console_output'"NEWLINEop|','NEWLINEnl|'\n'NEWLINEname|'fake_get_console_output_not_ready'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'body'NEWLINEop|'='NEWLINEop|'{'NEWLINEstring|"'os-getConsoleOutput'"NEWLINEop|':'NEWLINEop|'{'NEWLINEop|'}'NEWLINEop|'}'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'_check_console_output_failure'NEWLINEop|'('NEWLINEname|'webob'NEWLINEop|'.'NEWLINEname|'exc'NEWLINEop|'.'NEWLINEname|'HTTPConflict'NEWLINEop|','NEWLINEname|'body'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|test_not_implementedNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'test_not_implemented'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'stubs'NEWLINEop|'.'NEWLINEname|'Set'NEWLINEop|'('NEWLINEname|'compute_api'NEWLINEop|'.'NEWLINEname|'API'NEWLINEop|','NEWLINEstring|"'get_console_output'"NEWLINEop|','NEWLINEnl|'\n'NEWLINEname|'fakes'NEWLINEop|'.'NEWLINEname|'fake_not_implemented'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'body'NEWLINEop|'='NEWLINEop|'{'NEWLINEstring|"'os-getConsoleOutput'"NEWLINEop|':'NEWLINEop|'{'NEWLINEop|'}'NEWLINEop|'}'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'_check_console_output_failure'NEWLINEop|'('NEWLINEname|'webob'NEWLINEop|'.'NEWLINEname|'exc'NEWLINEop|'.'NEWLINEname|'HTTPNotImplemented'NEWLINEop|','NEWLINEname|'body'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|test_get_console_output_with_boolean_lengthNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'test_get_console_output_with_boolean_length'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'body'NEWLINEop|'='NEWLINEop|'{'NEWLINEstring|"'os-getConsoleOutput'"NEWLINEop|':'NEWLINEop|'{'NEWLINEstring|"'length'"NEWLINEop|':'NEWLINEname|'True'NEWLINEop|'}'NEWLINEop|'}'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'_check_console_output_failure'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'validation_error'NEWLINEop|','NEWLINEname|'body'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEdedent|''NEWLINEop|'@'NEWLINEname|'mock'NEWLINEop|'.'NEWLINEname|'patch'NEWLINEop|'.'NEWLINEname|'object'NEWLINEop|'('NEWLINEname|'compute_api'NEWLINEop|'.'NEWLINEname|'API'NEWLINEop|','NEWLINEstring|"'get_console_output'"NEWLINEop|','NEWLINEnl|'\n'NEWLINEname|'side_effect'NEWLINEop|'='NEWLINEname|'exception'NEWLINEop|'.'NEWLINEname|'ConsoleNotAvailable'NEWLINEop|'('NEWLINEnl|'\n'NEWLINEname|'instance_uuid'NEWLINEop|'='NEWLINEstring|"'fake_uuid'"NEWLINEop|')'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEDECL|member|test_get_console_output_not_availableNEWLINEname|'def'NEWLINEname|'test_get_console_output_not_available'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|','NEWLINEname|'mock_get_console_output'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'body'NEWLINEop|'='NEWLINEop|'{'NEWLINEstring|"'os-getConsoleOutput'"NEWLINEop|':'NEWLINEop|'{'NEWLINEop|'}'NEWLINEop|'}'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'_check_console_output_failure'NEWLINEop|'('NEWLINEname|'webob'NEWLINEop|'.'NEWLINEname|'exc'NEWLINEop|'.'NEWLINEname|'HTTPNotFound'NEWLINEop|','NEWLINEname|'body'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEnl|'\n'NEWLINEDECL|class|ConsoleOutpuPolicyEnforcementV21NEWLINEdedent|''NEWLINEdedent|''NEWLINEname|'class'NEWLINEname|'ConsoleOutpuPolicyEnforcementV21'NEWLINEop|'('NEWLINEname|'test'NEWLINEop|'.'NEWLINEname|'NoDBTestCase'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|setUpNEWLINEindent|' 'NEWLINEname|'def'NEWLINEname|'setUp'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'super'NEWLINEop|'('NEWLINEname|'ConsoleOutpuPolicyEnforcementV21'NEWLINEop|','NEWLINEname|'self'NEWLINEop|')'NEWLINEop|'.'NEWLINEname|'setUp'NEWLINEop|'('NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'controller'NEWLINEop|'='NEWLINEname|'console_output_v21'NEWLINEop|'.'NEWLINEname|'ConsoleOutputController'NEWLINEop|'('NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEnl|'\n'NEWLINEDECL|member|test_get_console_output_policy_failedNEWLINEdedent|''NEWLINEname|'def'NEWLINEname|'test_get_console_output_policy_failed'NEWLINEop|'('NEWLINEname|'self'NEWLINEop|')'NEWLINEop|':'NEWLINEnewline|'\n'NEWLINEindent|' 'NEWLINEname|'rule_name'NEWLINEop|'='NEWLINEstring|'"os_compute_api:os-console-output"'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'policy'NEWLINEop|'.'NEWLINEname|'set_rules'NEWLINEop|'('NEWLINEop|'{'NEWLINEname|'rule_name'NEWLINEop|':'NEWLINEstring|'"project:non_fake"'NEWLINEop|'}'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'req'NEWLINEop|'='NEWLINEname|'fakes'NEWLINEop|'.'NEWLINEname|'HTTPRequest'NEWLINEop|'.'NEWLINEname|'blank'NEWLINEop|'('NEWLINEstring|"''"NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'body'NEWLINEop|'='NEWLINEop|'{'NEWLINEstring|"'os-getConsoleOutput'"NEWLINEop|':'NEWLINEop|'{'NEWLINEop|'}'NEWLINEop|'}'NEWLINEnewline|'\n'NEWLINEname|'exc'NEWLINEop|'='NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'assertRaises'NEWLINEop|'('NEWLINEnl|'\n'NEWLINEname|'exception'NEWLINEop|'.'NEWLINEname|'PolicyNotAuthorized'NEWLINEop|','NEWLINEnl|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'controller'NEWLINEop|'.'NEWLINEname|'get_console_output'NEWLINEop|','NEWLINEname|'req'NEWLINEop|','NEWLINEname|'fakes'NEWLINEop|'.'NEWLINEname|'FAKE_UUID'NEWLINEop|','NEWLINEnl|'\n'NEWLINEname|'body'NEWLINEop|'='NEWLINEname|'body'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEname|'self'NEWLINEop|'.'NEWLINEname|'assertEqual'NEWLINEop|'('NEWLINEnl|'\n'NEWLINEstring|'"Policy doesn\'t allow %s to be performed."'NEWLINEop|'%'NEWLINEname|'rule_name'NEWLINEop|','NEWLINEnl|'\n'NEWLINEname|'exc'NEWLINEop|'.'NEWLINEname|'format_message'NEWLINEop|'('NEWLINEop|')'NEWLINEop|')'NEWLINEnewline|'\n'NEWLINEdedent|''NEWLINEdedent|''NEWLINEendmarker|''NEWLINEend_unitNEWLINE # Owner(s): ["oncall: quantization"]NEWLINENEWLINEimport torchNEWLINEimport torch.nn as nnNEWLINEimport torch.nn.intrinsic as nniNEWLINEimport torch.nn.intrinsic.quantized as nniqNEWLINEimport torch.nn.quantized as nnqNEWLINEimport torch.nn.quantized.dynamic as nnqdNEWLINEimport torch.nn.quantized._reference as nnqrNEWLINEimport torch.ao.quantizationNEWLINENEWLINEfrom torch.ao.quantization import (NEWLINE get_default_static_quant_module_mappings,NEWLINE default_float_qparams_observer,NEWLINE PerChannelMinMaxObserver,NEWLINE)NEWLINEfrom torch.package import PackageExporter, PackageImporterNEWLINEfrom torch.testing._internal.common_quantization import (NEWLINE QuantizationTestCase,NEWLINE prepare_dynamic,NEWLINE _make_conv_test_input,NEWLINE skipIfNoFBGEMM,NEWLINE lengths_to_offsetsNEWLINE)NEWLINEfrom torch.testing._internal.common_quantized import (NEWLINE _calculate_dynamic_qparams,NEWLINE override_quantized_engine,NEWLINE override_qengines,NEWLINE qengine_is_qnnpack,NEWLINE)NEWLINEfrom hypothesis import assume, givenNEWLINEfrom hypothesis import strategies as stNEWLINEimport torch.testing._internal.hypothesis_utils as huNEWLINEhu.assert_deadline_disabled()NEWLINENEWLINEimport copyNEWLINEimport ioNEWLINEimport numpy as npNEWLINEimport itertoolsNEWLINENEWLINE"""NEWLINENote that tests in this file are just API test, to make sure we wrapped theNEWLINEquantized operator implementations correctly in the user facing APIs, these areNEWLINEnot correctness test for the underlying quantized operators. For correctnessNEWLINEtest please see `test/quantization/test_quantized_op.py`.NEWLINE"""NEWLINENEWLINEclass TestStaticQuantizedModule(QuantizationTestCase):NEWLINE def test_relu(self):NEWLINE relu_module = nn.ReLU()NEWLINE relu6_module = nnq.ReLU6()NEWLINENEWLINE x = torch.arange(-10, 10, dtype=torch.float)NEWLINE y_ref = torch.relu(x)NEWLINE y6_ref = torch.nn.modules.ReLU6()(x)NEWLINENEWLINE qx = torch.quantize_per_tensor(x, 1.0, 0, dtype=torch.qint32)NEWLINE qy = relu_module(qx)NEWLINE qy6 = relu6_module(qx)NEWLINENEWLINE self.assertEqual(y_ref, qy.dequantize(),NEWLINE msg="ReLU module API failed")NEWLINE self.assertEqual(y6_ref, qy6.dequantize(),NEWLINE msg="ReLU6 module API failed")NEWLINENEWLINE @override_qenginesNEWLINE def test_linear_api(self):NEWLINE """test API functionality for nn.quantized.linear and nn.intrinsic.quantized.linear_relu"""NEWLINE options = itertools.product(NEWLINE [1, 5],NEWLINE [16, 32],NEWLINE [4, 8],NEWLINE [True, False],NEWLINE [True, False],NEWLINE [True, False])NEWLINE for (batch_size, in_features, out_features, use_bias,NEWLINE use_fused, per_channel) in options:NEWLINE self._test_linear_api_impl(NEWLINE batch_size, in_features, out_features, use_bias, use_fused,NEWLINE per_channel)NEWLINENEWLINE def _test_linear_api_impl(self, batch_size, in_features, out_features, use_bias, use_fused, per_channel):NEWLINE if torch.backends.quantized.engine == 'qnnpack':NEWLINE per_channel = FalseNEWLINENEWLINE # use_fused -> quantized classNEWLINE class_map = {NEWLINE True: nniq.LinearReLU,NEWLINE False: nnq.Linear,NEWLINE }NEWLINENEWLINE W = torch.rand(out_features, in_features).float()NEWLINE if per_channel:NEWLINE scale_tensor = torch.ones(out_features, dtype=torch.double)NEWLINE zero_point_tensor = torch.zeros(out_features, dtype=torch.long)NEWLINE for i in range(len(scale_tensor)):NEWLINE scale_tensor[i] = (i + 1.0) / 255.0NEWLINE W_q = torch.quantize_per_channel(W, scales=scale_tensor,NEWLINE zero_points=zero_point_tensor,NEWLINE axis=0, dtype=torch.qint8)NEWLINE else:NEWLINE W_q = torch.quantize_per_tensor(W, 0.1, 4, torch.qint8)NEWLINENEWLINE X = torch.rand(batch_size, in_features).float()NEWLINE X_q = torch.quantize_per_tensor(X, 0.2, 10, torch.quint8)NEWLINE B = torch.rand(out_features).float() if use_bias else NoneNEWLINE scale = 0.5NEWLINE zero_point = 3NEWLINE qlinear = class_map[use_fused](in_features, out_features)NEWLINENEWLINE qlinear_copy = copy.deepcopy(qlinear)NEWLINE # set random quantized weight and bias before test torch scriptableNEWLINE qlinear_copy.set_weight_bias(W_q, B)NEWLINE self.checkScriptable(qlinear_copy, [[X_q]], check_save_load=True)NEWLINE # Run module with default-initialized parameters.NEWLINE # This tests that the constructor is correct.NEWLINE qlinear(X_q)NEWLINENEWLINE qlinear.set_weight_bias(W_q, B)NEWLINE # Simple round-trip test to ensure weight()/set_weight() APINEWLINE self.assertEqual(qlinear.weight(), W_q, atol=1e-5, rtol=0)NEWLINENEWLINE # testing packed param implementationNEWLINE qlinear.scale = float(scale)NEWLINE qlinear.zero_point = int(zero_point)NEWLINE Z_q = qlinear(X_q)NEWLINENEWLINE # Check if the module implementation matches calling theNEWLINE # ops directlyNEWLINE W_pack = qlinear._packed_params._packed_paramsNEWLINE if use_fused:NEWLINE Z_ref = torch.ops.quantized.linear_relu(X_q, W_pack, scale, zero_point)NEWLINE else:NEWLINE Z_ref = torch.ops.quantized.linear(X_q, W_pack, scale, zero_point)NEWLINENEWLINE self.assertEqual(Z_ref, Z_q)NEWLINE self.assertTrue(NEWLINE ("QuantizedLinearReLU" if use_fused else "QuantizedLinear") in str(qlinear))NEWLINENEWLINE # Test serialization of quantized Linear Module using state_dictNEWLINE model_dict = qlinear.state_dict()NEWLINE b = io.BytesIO()NEWLINE torch.save(model_dict, b)NEWLINE b.seek(0)NEWLINE loaded_dict = torch.load(b)NEWLINE for key in model_dict:NEWLINE if isinstance(model_dict[key], torch._C.ScriptObject):NEWLINE assert isinstance(loaded_dict[key], torch._C.ScriptObject)NEWLINE w_model, b_model = torch.ops.quantized.linear_unpack(model_dict[key])NEWLINE w_loaded, b_loaded = torch.ops.quantized.linear_unpack(loaded_dict[key])NEWLINE self.assertEqual(w_model, w_loaded)NEWLINE self.assertEqual(b_model, b_loaded)NEWLINE else:NEWLINE self.assertEqual(model_dict[key], loaded_dict[key])NEWLINENEWLINE loaded_qlinear = class_map[use_fused](NEWLINE in_features, out_features)NEWLINE loaded_qlinear.load_state_dict(loaded_dict)NEWLINE linear_unpack = torch.ops.quantized.linear_unpackNEWLINE self.assertEqual(linear_unpack(qlinear._packed_params._packed_params),NEWLINE linear_unpack(loaded_qlinear._packed_params._packed_params))NEWLINE self.assertEqual(qlinear.scale, loaded_qlinear.scale)NEWLINE self.assertEqual(qlinear.zero_point, loaded_qlinear.zero_point)NEWLINE # scripting will add __overloads__ to __dict__, which is why we script a copyNEWLINE # to be able to do the check in the next lineNEWLINE self.checkScriptable(copy.deepcopy(loaded_qlinear), [[X_q]], check_save_load=True)NEWLINE self.assertTrue(dir(qlinear) == dir(loaded_qlinear))NEWLINE self.assertEqual(qlinear._weight_bias(), loaded_qlinear._weight_bias())NEWLINE self.assertEqual(qlinear._weight_bias(), torch.ops.quantized.linear_unpack(qlinear._packed_params._packed_params))NEWLINE Z_q2 = loaded_qlinear(X_q)NEWLINE self.assertEqual(Z_q, Z_q2)NEWLINENEWLINE # Test serializationNEWLINE b = io.BytesIO()NEWLINE torch.save(qlinear, b)NEWLINE b.seek(0)NEWLINE loaded = torch.load(b)NEWLINE self.assertEqual(qlinear.weight(), loaded.weight())NEWLINE self.assertEqual(qlinear.scale, loaded.scale)NEWLINE self.assertEqual(qlinear.zero_point, loaded.zero_point)NEWLINENEWLINE # Test torch.packageNEWLINE buffer = io.BytesIO()NEWLINE with PackageExporter(buffer) as pe:NEWLINE pe.save_pickle("module", "qlinear.pkl", qlinear)NEWLINE buffer.seek(0)NEWLINENEWLINE importer = PackageImporter(buffer)NEWLINE loaded_from_package = importer.load_pickle("module", "qlinear.pkl")NEWLINE self.assertEqual(qlinear.weight(), loaded_from_package.weight())NEWLINE self.assertEqual(qlinear.scale, loaded_from_package.scale)NEWLINE self.assertEqual(qlinear.zero_point, loaded_from_package.zero_point)NEWLINENEWLINE for name, module in loaded_from_package.named_modules():NEWLINE # noop, just make sure attribute "_modules" is restored correctly during torch.package importNEWLINE assert(name is not None)NEWLINENEWLINE # Test copy and deepcopyNEWLINE copied_linear = copy.copy(qlinear)NEWLINE self.assertEqual(copied_linear.bias(), qlinear.bias())NEWLINE self.assertEqual(copied_linear.scale, qlinear.scale)NEWLINE self.assertEqual(copied_linear.zero_point,NEWLINE qlinear.zero_point)NEWLINE Y_copied = copied_linear(X_q)NEWLINE np.testing.assert_array_almost_equal(NEWLINE Z_q.int_repr().numpy(), Y_copied.int_repr().numpy(), decimal=0)NEWLINENEWLINE deepcopied_linear = copy.deepcopy(qlinear)NEWLINE self.assertEqual(deepcopied_linear.bias(), qlinear.bias())NEWLINE self.assertEqual(deepcopied_linear.scale, qlinear.scale)NEWLINE self.assertEqual(deepcopied_linear.zero_point,NEWLINE qlinear.zero_point)NEWLINE Y_deepcopied = copied_linear(X_q)NEWLINE np.testing.assert_array_almost_equal(NEWLINE Z_q.int_repr().numpy(), Y_deepcopied.int_repr().numpy(), decimal=0)NEWLINENEWLINE # Test JITNEWLINE self.checkScriptable(qlinear, [[X_q]], check_save_load=True)NEWLINENEWLINE # Make sure `from_float` works for all linear variantsNEWLINE modules_under_test = [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear]NEWLINENEWLINE for mut in modules_under_test:NEWLINE # Test from_float.NEWLINE float_linear = mut(in_features, out_features).float()NEWLINE float_linear.qconfig = torch.ao.quantization.default_qconfigNEWLINE torch.ao.quantization.prepare(float_linear, inplace=True)NEWLINE float_linear(X.float())NEWLINE # Sequential allows swapping using "convert".NEWLINE quantized_float_linear = torch.nn.Sequential(float_linear)NEWLINE quantized_float_linear = torch.ao.quantization.convert(quantized_float_linear, inplace=True)NEWLINENEWLINE # Smoke test to make sure the module actually runsNEWLINE quantized_float_linear(X_q)NEWLINENEWLINE # Smoke test extra_reprNEWLINE self.assertTrue('QuantizedLinear' in str(quantized_float_linear))NEWLINENEWLINE def test_quant_dequant_api(self):NEWLINE r = torch.tensor([[1., -1.], [1., -1.]], dtype=torch.float)NEWLINE scale, zero_point, dtype = 1.0, 2, torch.qint8NEWLINE # testing Quantize APINEWLINE qr = torch.quantize_per_tensor(r, scale, zero_point, dtype)NEWLINE quant_m = nnq.Quantize(scale, zero_point, dtype)NEWLINE qr2 = quant_m(r)NEWLINE self.assertEqual(qr, qr2)NEWLINE # testing Dequantize APINEWLINE rqr = qr.dequantize()NEWLINE dequant_m = nnq.DeQuantize()NEWLINE rqr2 = dequant_m(qr2)NEWLINE self.assertEqual(rqr, rqr2)NEWLINENEWLINE def _test_conv_api_impl(NEWLINE self, module_name, qconv_module, conv_module, batch_size,NEWLINE in_channels_per_group, input_feature_map_size, out_channels_per_group,NEWLINE groups, kernel_size, stride, padding, padding_mode, dilation,NEWLINE X_scale, X_zero_point, W_scale, W_zero_point, Y_scale, Y_zero_point,NEWLINE use_bias, use_fused, use_channelwise):NEWLINE for i in range(len(kernel_size)):NEWLINE assume(input_feature_map_size[i] + 2 * padding[i]NEWLINE >= dilation[i] * (kernel_size[i] - 1) + 1)NEWLINENEWLINE in_channels = in_channels_per_group * groupsNEWLINE out_channels = out_channels_per_group * groupsNEWLINE (X, X_q, W, W_q, b) = _make_conv_test_input(NEWLINE batch_size, in_channels_per_group, input_feature_map_size,NEWLINE out_channels_per_group, groups, kernel_size, X_scale, X_zero_point,NEWLINE W_scale, W_zero_point, use_bias, use_channelwise)NEWLINE # Make sure the weight shape is correctNEWLINE self.assertTrue(qconv_module.weight().shape == W_q.shape)NEWLINENEWLINE qconv_module.set_weight_bias(W_q, b)NEWLINE qconv_module.scale = Y_scaleNEWLINE qconv_module.zero_point = Y_zero_pointNEWLINENEWLINE if use_fused:NEWLINE conv_module[0].weight.data = WNEWLINE if use_bias:NEWLINE conv_module[0].bias.data = bNEWLINE else:NEWLINE conv_module.weight.data = WNEWLINE if use_bias:NEWLINE conv_module.bias.data = bNEWLINENEWLINE # Test membersNEWLINE self.assertTrue(module_name == qconv_module._get_name(), module_name + " " + qconv_module._get_name())NEWLINE self.assertTrue(hasattr(qconv_module, '_packed_params'))NEWLINE self.assertTrue(hasattr(qconv_module, 'scale'))NEWLINE self.assertTrue(hasattr(qconv_module, 'zero_point'))NEWLINENEWLINE # Test propertiesNEWLINE self.assertEqual(W_q, qconv_module.weight())NEWLINE if use_bias:NEWLINE self.assertEqual(b, qconv_module.bias())NEWLINE self.assertEqual(Y_scale, qconv_module.scale)NEWLINE self.assertEqual(Y_zero_point, qconv_module.zero_point)NEWLINENEWLINE # Test forwardNEWLINE Y_exp = conv_module(X)NEWLINE Y_exp = torch.quantize_per_tensor(NEWLINE Y_exp, scale=Y_scale, zero_point=Y_zero_point, dtype=torch.quint8)NEWLINE Y_act = qconv_module(X_q)NEWLINENEWLINE # Make sure the results matchNEWLINE # assert_array_almost_equal compares using the following formula:NEWLINE # abs(desired-actual) < 1.5 * 10**(-decimal)NEWLINE # (https://docs.scipy.org/doc/numpy/reference/generated/numpy.testing.assert_almost_equal.html)NEWLINE # We use decimal = 0 to ignore off-by-1 differences between referenceNEWLINE # and test. Off-by-1 differences arise due to the order of round andNEWLINE # zero_point addition operation, i.e., if addition followed by round isNEWLINE # used by reference and round followed by addition is used by test, theNEWLINE # results may differ by 1.NEWLINE # For example, the result of round(2.5) + 1 is 3 while round(2.5 + 1) isNEWLINE # 4 assuming the rounding mode is round-to-nearest, ties-to-even.NEWLINE # skip numerics checking for reference moduleNEWLINE np.testing.assert_array_almost_equal(NEWLINE Y_exp.int_repr().numpy(), Y_act.int_repr().numpy(), decimal=0)NEWLINENEWLINE # Test serialization of quantized Conv Module using state_dictNEWLINE model_dict = qconv_module.state_dict()NEWLINE self.assertEqual(model_dict['weight'], W_q)NEWLINE if use_bias:NEWLINE self.assertEqual(model_dict['bias'], b)NEWLINE bytes_io = io.BytesIO()NEWLINE torch.save(model_dict, bytes_io)NEWLINE bytes_io.seek(0)NEWLINE loaded_dict = torch.load(bytes_io)NEWLINE for key in loaded_dict:NEWLINE self.assertEqual(model_dict[key], loaded_dict[key])NEWLINE loaded_qconv_module = type(qconv_module)(NEWLINE in_channels, out_channels, kernel_size, stride, padding, dilation,NEWLINE groups, use_bias, padding_mode=padding_mode)NEWLINE loaded_qconv_module.load_state_dict(loaded_dict)NEWLINENEWLINE self.assertTrue(dir(loaded_qconv_module) == dir(qconv_module))NEWLINE self.assertTrue(module_name == loaded_qconv_module._get_name())NEWLINE self.assertTrue(hasattr(loaded_qconv_module, '_packed_params'))NEWLINE self.assertTrue(hasattr(loaded_qconv_module, '_weight_bias'))NEWLINENEWLINE self.assertEqual(qconv_module.weight(), loaded_qconv_module.weight())NEWLINE if use_bias:NEWLINE self.assertEqual(qconv_module.bias(), loaded_qconv_module.bias())NEWLINE self.assertEqual(qconv_module.scale, loaded_qconv_module.scale)NEWLINE self.assertEqual(qconv_module.zero_point,NEWLINE loaded_qconv_module.zero_point)NEWLINE Y_loaded = loaded_qconv_module(X_q)NEWLINE np.testing.assert_array_almost_equal(NEWLINE Y_exp.int_repr().numpy(), Y_loaded.int_repr().numpy(), decimal=0)NEWLINENEWLINE # Test serializationNEWLINE b = io.BytesIO()NEWLINE torch.save(qconv_module, b)NEWLINE b.seek(0)NEWLINE loaded_conv = torch.load(b)NEWLINENEWLINE self.assertEqual(loaded_conv.bias(), qconv_module.bias())NEWLINE self.assertEqual(loaded_conv.scale, qconv_module.scale)NEWLINE self.assertEqual(loaded_conv.zero_point,NEWLINE qconv_module.zero_point)NEWLINENEWLINE # Test copy and deepcopyNEWLINE copied_conv = copy.copy(qconv_module)NEWLINE self.assertEqual(copied_conv.bias(), qconv_module.bias())NEWLINE self.assertEqual(copied_conv.scale, qconv_module.scale)NEWLINE self.assertEqual(copied_conv.zero_point,NEWLINE qconv_module.zero_point)NEWLINE Y_copied = copied_conv(X_q)NEWLINE np.testing.assert_array_almost_equal(NEWLINE Y_exp.int_repr().numpy(), Y_copied.int_repr().numpy(), decimal=0)NEWLINENEWLINE deepcopied_conv = copy.deepcopy(qconv_module)NEWLINE self.assertEqual(deepcopied_conv.bias(), qconv_module.bias())NEWLINE self.assertEqual(deepcopied_conv.scale, qconv_module.scale)NEWLINE self.assertEqual(deepcopied_conv.zero_point,NEWLINE qconv_module.zero_point)NEWLINE Y_deepcopied = copied_conv(X_q)NEWLINE np.testing.assert_array_almost_equal(NEWLINE Y_exp.int_repr().numpy(), Y_deepcopied.int_repr().numpy(), decimal=0)NEWLINENEWLINE # JIT testingNEWLINE self.checkScriptable(NEWLINE qconv_module, [[X_q]],NEWLINE check_save_load=True)NEWLINENEWLINE # Test from_floatNEWLINE fused_conv_module = torch.nn.intrinsic._FusedModule(conv_module)NEWLINE fused_conv_module.qconfig = torch.ao.quantization.default_qconfigNEWLINE torch.ao.quantization.prepare(fused_conv_module, inplace=True)NEWLINE fused_conv_module(X.float())NEWLINE converted_qconv_module = fused_conv_moduleNEWLINE reference_mapping = get_default_static_quant_module_mappings()NEWLINE reference_mapping[type(conv_module)] = type(qconv_module)NEWLINE torch.ao.quantization.convert(converted_qconv_module, mapping=reference_mapping, inplace=True)NEWLINENEWLINE # Smoke test to make sure the module actually runsNEWLINE if use_bias:NEWLINE if use_fused:NEWLINE self.assertEqual(conv_module[0].bias,NEWLINE converted_qconv_module[0].bias())NEWLINE else:NEWLINE self.assertEqual(conv_module.bias,NEWLINE converted_qconv_module[0].bias())NEWLINE # Smoke test extra_reprNEWLINE self.assertTrue(module_name == converted_qconv_module[0]._get_name())NEWLINENEWLINE @override_qenginesNEWLINE def test_conv1d_api(self):NEWLINE options = itertools.product(NEWLINE ["zeros", "reflect"], # pad_modeNEWLINE [True, False], # use_biasNEWLINE [True, False], # use_fusedNEWLINE [True, False], # use_channelwiseNEWLINE )NEWLINE for pad_mode, use_bias, use_fused, use_channelwise in options:NEWLINE if torch.backends.quantized.engine == "qnnpack":NEWLINE use_channelwise = FalseNEWLINE batch_size = 2NEWLINE in_channels_per_group = 2NEWLINE length = 8NEWLINE out_channels_per_group = 2NEWLINE groups = 3NEWLINE kernel = 3NEWLINE stride = 2NEWLINE pad = 1NEWLINE dilation = 1NEWLINE # Tests the correctness of the conv2d module.NEWLINE in_channels = in_channels_per_group * groupsNEWLINE out_channels = out_channels_per_group * groupsNEWLINE input_feature_map_size = (length,)NEWLINE kernel_size = (kernel, )NEWLINE stride = (stride, )NEWLINE pad = (pad, )NEWLINE dilation = (dilation, )NEWLINE X_scale = 1.3NEWLINE X_zero_point = 2NEWLINE W_scale = [0.5]NEWLINE W_zero_point = [3]NEWLINE Y_scale = 5.0NEWLINE Y_zero_point = 4NEWLINE if torch.backends.quantized.engine == 'qnnpack':NEWLINE use_channelwise = FalseNEWLINE # use_fused -> quantized classNEWLINE class_map = {NEWLINE True: (nniq.ConvReLU1d, "QuantizedConvReLU1d"),NEWLINE False: (nnq.Conv1d, "QuantizedConv1d")NEWLINE }NEWLINENEWLINE qconv_cls, module_name = class_map[use_fused]NEWLINE qconv_module = qconv_cls(NEWLINE in_channels, out_channels, kernel, stride, pad,NEWLINE dilation, groups, use_bias, padding_mode=pad_modeNEWLINE )NEWLINENEWLINE conv_module = nn.Conv1d(NEWLINE in_channels, out_channels, kernel, stride, pad,NEWLINE dilation, groups, use_bias, padding_mode=pad_mode)NEWLINE if use_fused:NEWLINE relu_module = nn.ReLU()NEWLINE conv_module = nni.ConvReLU1d(conv_module, relu_module)NEWLINE conv_module = conv_module.float()NEWLINENEWLINE self._test_conv_api_impl(NEWLINE module_name, qconv_module, conv_module, batch_size,NEWLINE in_channels_per_group, input_feature_map_size,NEWLINE out_channels_per_group, groups, kernel_size, stride, pad, pad_mode,NEWLINE dilation, X_scale, X_zero_point, W_scale, W_zero_point, Y_scale,NEWLINE Y_zero_point, use_bias, use_fused, use_channelwise)NEWLINENEWLINE @override_qenginesNEWLINE def test_conv2d_api(self):NEWLINE options = itertools.product(NEWLINE ["zeros", "reflect"], # pad_modeNEWLINE [True, False], # use_biasNEWLINE [True, False], # use_fusedNEWLINE [True, False], # use_channelwiseNEWLINE )NEWLINE for pad_mode, use_bias, use_fused, use_channelwise in options:NEWLINE if torch.backends.quantized.engine == "qnnpack":NEWLINE use_channelwise = FalseNEWLINE batch_size = 2NEWLINE in_channels_per_group = 2NEWLINE H = 8NEWLINE W = 8NEWLINE out_channels_per_group = 2NEWLINE groups = 3NEWLINE kernel_h = 3NEWLINE kernel_w = 3NEWLINE stride_h = 2NEWLINE stride_w = 2NEWLINE pad_h = 1NEWLINE pad_w = 1NEWLINE dilation = 1NEWLINE # Tests the correctness of the conv2d module.NEWLINE in_channels = in_channels_per_group * groupsNEWLINE out_channels = out_channels_per_group * groupsNEWLINE input_feature_map_size = (H, W)NEWLINE kernel_size = (kernel_h, kernel_w)NEWLINE stride = (stride_h, stride_w)NEWLINE padding = (pad_h, pad_w)NEWLINE dilation = (dilation, dilation)NEWLINE X_scale = 1.3NEWLINE X_zero_point = 2NEWLINE W_scale = [0.5]NEWLINE W_zero_point = [3]NEWLINE Y_scale = 5.0NEWLINE Y_zero_point = 4NEWLINE # use_fused -> quantized classNEWLINE class_map = {NEWLINE True: (nniq.ConvReLU2d, "QuantizedConvReLU2d"),NEWLINE False: (nnq.Conv2d, "QuantizedConv2d")NEWLINE }NEWLINENEWLINE qconv_cls, module_name = class_map[use_fused]NEWLINE qconv_module = qconv_cls(NEWLINE in_channels, out_channels, kernel_size, stride, padding,NEWLINE dilation, groups, use_bias, padding_mode=pad_modeNEWLINE )NEWLINENEWLINE conv_module = nn.Conv2d(NEWLINE in_channels, out_channels, kernel_size, stride, padding,NEWLINE dilation, groups, use_bias, padding_mode=pad_mode)NEWLINE if use_fused:NEWLINE relu_module = nn.ReLU()NEWLINE conv_module = nni.ConvReLU2d(conv_module, relu_module)NEWLINE conv_module = conv_module.float()NEWLINENEWLINE self._test_conv_api_impl(NEWLINE module_name, qconv_module, conv_module, batch_size,NEWLINE in_channels_per_group, input_feature_map_size,NEWLINE out_channels_per_group, groups, kernel_size, stride, padding,NEWLINE pad_mode, dilation, X_scale, X_zero_point, W_scale, W_zero_point,NEWLINE Y_scale, Y_zero_point, use_bias, use_fused, use_channelwise)NEWLINENEWLINE @skipIfNoFBGEMMNEWLINE def test_conv3d_api(self):NEWLINE options = itertools.product(NEWLINE [True, False], # use_biasNEWLINE [True, False], # use_fusedNEWLINE [True, False], # use_channelwiseNEWLINE )NEWLINE for use_bias, use_fused, use_channelwise in options:NEWLINE if torch.backends.quantized.engine == "qnnpack":NEWLINE use_channelwise = FalseNEWLINE batch_size = 2NEWLINE in_channels_per_group = 2NEWLINE H = 8NEWLINE W = 8NEWLINE D = 8NEWLINE out_channels_per_group = 2NEWLINE groups = 3NEWLINE kernel_h = 3NEWLINE kernel_w = 3NEWLINE kernel_d = 3NEWLINE stride_h = 2NEWLINE stride_w = 2NEWLINE stride_d = 2NEWLINE pad_mode = "zeros" # 3d doesn't support reflect paddingNEWLINE pad_h = 1NEWLINE pad_w = 1NEWLINE pad_d = 1NEWLINE dilation = 1NEWLINE # Tests the correctness of the conv3d module.NEWLINE in_channels = in_channels_per_group * groupsNEWLINE out_channels = out_channels_per_group * groupsNEWLINE input_feature_map_size = (D, H, W)NEWLINE kernel_size = (kernel_d, kernel_h, kernel_w)NEWLINE stride = (stride_d, stride_h, stride_w)NEWLINE padding = (pad_d, pad_h, pad_w)NEWLINE dilation = (dilation, dilation, dilation)NEWLINE X_scale = 1.3NEWLINE X_zero_point = 2NEWLINE W_scale = [0.5]NEWLINE W_zero_point = [3]NEWLINE Y_scale = 5.0NEWLINE Y_zero_point = 4NEWLINE # use_fused -> quantized classNEWLINE class_map = {NEWLINE True: (nniq.ConvReLU3d, "QuantizedConvReLU3d"),NEWLINE False: (nnq.Conv3d, "QuantizedConv3d")NEWLINE }NEWLINENEWLINE with override_quantized_engine('fbgemm'):NEWLINE qconv_cls, module_name = class_map[use_fused]NEWLINE qconv_module = qconv_cls(NEWLINE in_channels, out_channels, kernel_size, stride, padding,NEWLINE dilation, groups, use_bias, padding_mode=pad_modeNEWLINE )NEWLINENEWLINE conv_module = nn.Conv3d(NEWLINE in_channels, out_channels, kernel_size, stride, padding,NEWLINE dilation, groups, use_bias, padding_mode=pad_mode)NEWLINE if use_fused:NEWLINE relu_module = nn.ReLU()NEWLINE conv_module = nni.ConvReLU3d(conv_module, relu_module)NEWLINE conv_module = conv_module.float()NEWLINENEWLINE self._test_conv_api_impl(NEWLINE module_name, qconv_module, conv_module, batch_size,NEWLINE in_channels_per_group, input_feature_map_size,NEWLINE out_channels_per_group, groups, kernel_size, stride, padding,NEWLINE pad_mode, dilation, X_scale, X_zero_point, W_scale,NEWLINE W_zero_point, Y_scale, Y_zero_point, use_bias, use_fused,NEWLINE use_channelwise)NEWLINENEWLINE def test_pool_api(self):NEWLINE """Tests the correctness of the pool module.NEWLINE The correctness is defined against the functional implementation.NEWLINE """NEWLINE N, C, H, W = 10, 10, 10, 3NEWLINE kwargs = {NEWLINE 'kernel_size': 2,NEWLINE 'stride': None,NEWLINE 'padding': 0,NEWLINE 'dilation': 1NEWLINE }NEWLINENEWLINE scale, zero_point = 1.0 / 255, 128NEWLINENEWLINE X = torch.randn(N, C, H, W, dtype=torch.float32)NEWLINE qX = torch.quantize_per_tensor(X, scale=scale, zero_point=zero_point,NEWLINE dtype=torch.quint8)NEWLINE qX_expect = torch.nn.functional.max_pool2d(qX, **kwargs)NEWLINENEWLINE pool_under_test = torch.nn.quantized.MaxPool2d(**kwargs)NEWLINE qX_hat = pool_under_test(qX)NEWLINE self.assertEqual(qX_expect, qX_hat)NEWLINENEWLINE # JIT TestingNEWLINE self.checkScriptable(pool_under_test, [[X]])NEWLINENEWLINE def test_dropout(self):NEWLINE """Tests the correctness of the dropout module.NEWLINE The correctness is defined against the functional implementation.NEWLINE """NEWLINE x = torch.randn((2, 4, 6, 8), dtype=torch.float)NEWLINE float_mod = torch.nn.Dropout(p=0.5)NEWLINE float_mod.training = FalseNEWLINENEWLINE y_ref = float_mod(x)NEWLINE quant_ref = torch.quantize_per_tensor(y_ref, 1.0, 0, dtype=torch.quint8)NEWLINENEWLINE quant_mod = nnq.Dropout(p=0.5)NEWLINE qx = torch.quantize_per_tensor(x, 1.0, 0, dtype=torch.quint8)NEWLINE qy = quant_mod(qx)NEWLINENEWLINE self.assertEqual(quant_ref.int_repr().numpy(), qy.int_repr().numpy(),NEWLINE msg="Dropout module API failed")NEWLINENEWLINE def _test_dropout_serialization(self, get_model, data1, data2):NEWLINE m1 = get_model()NEWLINE m1.qconfig = torch.ao.quantization.default_qconfigNEWLINE mp1 = torch.ao.quantization.prepare(m1)NEWLINE mp1(data1)NEWLINE mq1 = torch.ao.quantization.convert(mp1)NEWLINE ref1 = mq1(data2)NEWLINENEWLINE m2 = get_model()NEWLINE m2.qconfig = torch.quantization.default_qconfigNEWLINE mp2 = torch.ao.quantization.prepare(m2)NEWLINE mq2 = torch.ao.quantization.convert(mp2)NEWLINENEWLINE mq2.load_state_dict(mq1.state_dict())NEWLINE ref2 = mq2(data2)NEWLINENEWLINE self.assertTrue(torch.allclose(ref1, ref2))NEWLINENEWLINE def test_dropout_serialization(self):NEWLINE data1 = torch.randn(2, 4, 6, 8)NEWLINE data2 = torch.randn(2, 4, 6, 8)NEWLINENEWLINE def _get_model():NEWLINE return nn.Sequential(NEWLINE torch.ao.quantization.QuantStub(),NEWLINE nn.Dropout(p=0.5),NEWLINE torch.ao.quantization.DeQuantStub()NEWLINE ).eval()NEWLINENEWLINE self._test_dropout_serialization(_get_model, data1, data2)NEWLINENEWLINENEWLINENEWLINE def test_batch_norm2d(self):NEWLINE """Tests the correctness of the batchnorm2d module.NEWLINE The correctness is defined against the functional implementation.NEWLINE """NEWLINE x = torch.randn((2, 4, 6, 8), dtype=torch.float)NEWLINE float_mod = torch.nn.BatchNorm2d(4)NEWLINE float_mod.training = FalseNEWLINENEWLINE y_ref = float_mod(x)NEWLINE quant_ref = torch.quantize_per_tensor(y_ref, 1.0, 0, dtype=torch.quint8)NEWLINENEWLINE quant_mod = nnq.BatchNorm2d(4)NEWLINE qx = torch.quantize_per_tensor(x, 1.0, 0, dtype=torch.quint8)NEWLINE qy = quant_mod(qx)NEWLINENEWLINE self.assertEqual(quant_ref.int_repr().numpy(), qy.int_repr().numpy(),NEWLINE msg="BatchNorm2d module API failed")NEWLINENEWLINE def test_batch_norm3d(self):NEWLINE """Tests the correctness of the batchnorm3d module.NEWLINE The correctness is defined against the functional implementation.NEWLINE """NEWLINE x = torch.randn((2, 4, 6, 8, 10), dtype=torch.float)NEWLINE float_mod = torch.nn.BatchNorm3d(4)NEWLINE float_mod.training = FalseNEWLINENEWLINE y_ref = float_mod(x)NEWLINE quant_ref = torch.quantize_per_tensor(y_ref, 1.0, 0, dtype=torch.quint8)NEWLINENEWLINE quant_mod = nnq.BatchNorm3d(4)NEWLINE qx = torch.quantize_per_tensor(x, 1.0, 0, dtype=torch.quint8)NEWLINE qy = quant_mod(qx)NEWLINENEWLINE self.assertEqual(quant_ref.int_repr().numpy(), qy.int_repr().numpy(),NEWLINE msg="BatchNorm3d module API failed")NEWLINENEWLINE def _test_batch_norm_serialization(self, get_model, data1, data2):NEWLINE m1 = get_model()NEWLINE m1.qconfig = torch.ao.quantization.default_qconfigNEWLINE mp1 = torch.ao.quantization.prepare(m1)NEWLINE mp1(data1)NEWLINE mq1 = torch.ao.quantization.convert(mp1)NEWLINE ref1 = mq1(data2)NEWLINENEWLINE m2 = get_model()NEWLINE m2.qconfig = torch.quantization.default_qconfigNEWLINE mp2 = torch.ao.quantization.prepare(m2)NEWLINE mq2 = torch.ao.quantization.convert(mp2)NEWLINENEWLINE mq2.load_state_dict(mq1.state_dict())NEWLINE ref2 = mq2(data2)NEWLINENEWLINE self.assertTrue(torch.allclose(ref1, ref2))NEWLINENEWLINE def test_batch_norm2d_serialization(self):NEWLINE data1 = torch.randn(2, 4, 6, 8)NEWLINE data2 = torch.randn(2, 4, 6, 8)NEWLINENEWLINE def _get_model():NEWLINE return nn.Sequential(NEWLINE torch.ao.quantization.QuantStub(),NEWLINE nn.BatchNorm2d(4),NEWLINE torch.ao.quantization.DeQuantStub()NEWLINE ).eval()NEWLINENEWLINE self._test_batch_norm_serialization(_get_model, data1, data2)NEWLINENEWLINE def test_batch_norm3d_serialization(self):NEWLINE data1 = torch.randn(2, 4, 6, 8, 1)NEWLINE data2 = torch.randn(2, 4, 6, 8, 1)NEWLINENEWLINE def _get_model():NEWLINE return nn.Sequential(NEWLINE torch.ao.quantization.QuantStub(),NEWLINE nn.BatchNorm3d(4),NEWLINE torch.ao.quantization.DeQuantStub()NEWLINE ).eval()NEWLINENEWLINE self._test_batch_norm_serialization(_get_model, data1, data2)NEWLINENEWLINE def test_layer_norm(self):NEWLINE """Tests the correctness of the layernorm module.NEWLINE The correctness is defined against the functional implementation.NEWLINE """NEWLINE x_scale = 10.0 / 256NEWLINE x_zero_point = 0NEWLINE y_scale = 5.0 / 256NEWLINE y_zero_point = 127NEWLINENEWLINE dims = (1, 4, 8)NEWLINENEWLINE X = (torch.randn(dims, dtype=torch.float) - 0.5) * 10NEWLINE qX = torch.quantize_per_tensor(X, x_scale, x_zero_point, dtype=torch.quint8)NEWLINE dqX = qX.dequantize()NEWLINENEWLINE float_mod = torch.nn.LayerNorm(dqX.size()[1:]).float()NEWLINE float_mod.weight = torch.nn.Parameter(torch.rand(*dims[1:]))NEWLINE float_mod.bias = torch.nn.Parameter(torch.rand(*dims[1:]))NEWLINENEWLINE dqY_ref = float_mod(dqX)NEWLINE qY_ref = torch.quantize_per_tensor(NEWLINE dqY_ref, y_scale, y_zero_point, dtype=torch.quint8)NEWLINENEWLINE quant_mod = nnq.LayerNorm(NEWLINE qX.size()[1:], float_mod.weight, float_mod.bias, y_scale, y_zero_point)NEWLINE qY = quant_mod(qX)NEWLINENEWLINE self.assertEqual(qY_ref.int_repr().numpy(), qY.int_repr().numpy(),NEWLINE msg="LayerNorm module API failed, qY_ref\n{} vs qY\n{}"NEWLINE .format(qY_ref, qY))NEWLINENEWLINE def test_group_norm(self):NEWLINE """Tests the correctness of the groupnorm module.NEWLINE The correctness is defined against the functional implementation.NEWLINE """NEWLINE x_scale = 10.0 / 256NEWLINE x_zero_point = 0NEWLINE y_scale = 5.0 / 256NEWLINE y_zero_point = 127NEWLINENEWLINE dims = (1, 4, 8)NEWLINENEWLINE X = (torch.randn(dims, dtype=torch.float) - 0.5) * 10NEWLINE qX = torch.quantize_per_tensor(X, x_scale, x_zero_point, dtype=torch.quint8)NEWLINE dqX = qX.dequantize()NEWLINENEWLINE float_mod = torch.nn.GroupNorm(2, 4).float()NEWLINE float_mod.weight = torch.nn.Parameter(torch.rand(dims[1]))NEWLINE float_mod.bias = torch.nn.Parameter(torch.rand(dims[1]))NEWLINENEWLINE dqY_ref = float_mod(dqX)NEWLINE qY_ref = torch.quantize_per_tensor(NEWLINE dqY_ref, y_scale, y_zero_point, dtype=torch.quint8)NEWLINENEWLINE quant_mod = nnq.GroupNorm(NEWLINE 2, 2, float_mod.weight, float_mod.bias, y_scale, y_zero_point)NEWLINE qY = quant_mod(qX)NEWLINENEWLINE self.assertEqual(qY_ref.int_repr().numpy(), qY.int_repr().numpy(),NEWLINE msg="GroupNorm module API failed, qY_ref\n{} vs qY\n{}"NEWLINE .format(qY_ref, qY))NEWLINENEWLINE def test_instance_norm(self):NEWLINE """Tests the correctness of the instancenorm{n}d modules.NEWLINE The correctness is defined against the functional implementation.NEWLINE """NEWLINE x_scale = 10.0 / 256NEWLINE x_zero_point = 0NEWLINE y_scale = 5.0 / 256NEWLINE y_zero_point = 127NEWLINENEWLINE dims_to_modules = [NEWLINE ((1, 4, 8), torch.nn.InstanceNorm1d, nnq.InstanceNorm1d),NEWLINE ((1, 4, 8, 1), torch.nn.InstanceNorm2d, nnq.InstanceNorm2d),NEWLINE ((1, 4, 8, 1, 1), torch.nn.InstanceNorm3d, nnq.InstanceNorm3d),NEWLINE ]NEWLINENEWLINE for dim_to_modules in dims_to_modules:NEWLINE dims, float_cls, q_cls = dim_to_modulesNEWLINENEWLINE X = (torch.randn(dims, dtype=torch.float) - 0.5) * 10NEWLINE qX = torch.quantize_per_tensor(NEWLINE X, x_scale, x_zero_point, dtype=torch.quint8)NEWLINE dqX = qX.dequantize()NEWLINENEWLINE float_mod = float_cls(dims[1]).float()NEWLINE float_mod.weight = torch.nn.Parameter(torch.rand(dims[1]))NEWLINE float_mod.bias = torch.nn.Parameter(torch.rand(dims[1]))NEWLINENEWLINE dqY_ref = float_mod(dqX)NEWLINE qY_ref = torch.quantize_per_tensor(NEWLINE dqY_ref, y_scale, y_zero_point, dtype=torch.quint8)NEWLINENEWLINE quant_mod = q_cls(NEWLINE dims[1], float_mod.weight, float_mod.bias, y_scale,NEWLINE y_zero_point)NEWLINE qY = quant_mod(qX)NEWLINENEWLINE self.assertEqual(NEWLINE qY_ref.int_repr().numpy(), qY.int_repr().numpy(),NEWLINE msg="InstanceNorm module API failed, qY_ref\n{} vs qY\n{}"NEWLINE .format(qY_ref, qY))NEWLINENEWLINE def _test_activation_module_impl(self, name, float_module_class, quantized_module_class, extra_kwargs):NEWLINE """Tests the correctness of the ELU module.NEWLINE The correctness is defined against the functional implementation.NEWLINE """NEWLINE x_scale = 10.0 / 256NEWLINE x_zero_point = 0NEWLINE y_scale = 5.0 / 256NEWLINE y_zero_point = 127NEWLINE alpha = 1.5NEWLINENEWLINE dims = (1, 4, 8)NEWLINENEWLINE X = (torch.randn(dims, dtype=torch.float) - 0.5) * 10NEWLINE qX = torch.quantize_per_tensor(X, x_scale, x_zero_point, dtype=torch.quint8)NEWLINE dqX = qX.dequantize()NEWLINENEWLINE float_mod = float_module_class(**extra_kwargs).float()NEWLINENEWLINE dqY_ref = float_mod(dqX)NEWLINE qY_ref = torch.quantize_per_tensor(NEWLINE dqY_ref, y_scale, y_zero_point, dtype=torch.quint8)NEWLINENEWLINE quant_mod = quantized_module_class(y_scale, y_zero_point, **extra_kwargs)NEWLINE qY = quant_mod(qX)NEWLINE self.assertEqual(qY_ref.int_repr().numpy(), qY.int_repr().numpy(),NEWLINE msg="{} module API failed, qY_ref\n{} vs qY\n{}"NEWLINE .format(name, qY_ref, qY))NEWLINENEWLINE def _test_leaky_relu_serialization(self):NEWLINE scale_original = 10.0 / 256NEWLINE zero_point_original = 1.0NEWLINENEWLINE quant_mod_original = nnq.LeakyReLU(scale_original, zero_point_original)NEWLINE state_dict = quant_mod_original.state_dict()NEWLINENEWLINE scale_new = 5.0 / 256NEWLINE zero_point_new = 2.0NEWLINE quant_mod_new = nnq.LeakyReLU(scale_new, zero_point_new)NEWLINE quant_mod_new.load_state_dict(state_dict)NEWLINENEWLINE self.assertEqual(quant_mod_original.scale, quant_mod_new.scale)NEWLINE self.assertEqual(quant_mod_original.zero_point, quant_mod_new.zero_point)NEWLINENEWLINE def test_elu(self):NEWLINE """Tests the correctness of the ELU module.NEWLINE The correctness is defined against the functional implementation.NEWLINE """NEWLINE self._test_activation_module_impl("ELU", nn.ELU, nnq.ELU, {"alpha": 1.5})NEWLINENEWLINE def test_leaky_relu(self):NEWLINE self._test_activation_module_impl("LeakyReLU", nn.LeakyReLU, nnq.LeakyReLU, {"negative_slope": 0.2})NEWLINE self._test_leaky_relu_serialization()NEWLINENEWLINE def test_sigmoid(self):NEWLINE self._test_activation_module_impl("Sigmoid", nn.Sigmoid, nnq.Sigmoid, {})NEWLINENEWLINE @given(NEWLINE num_embeddings=st.integers(10, 50),NEWLINE embedding_dim=st.integers(5, 50).filter(lambda x: x % 4 == 0),NEWLINE set_qconfig=st.booleans(),NEWLINE )NEWLINE @skipIfNoFBGEMMNEWLINE def test_embedding_api(self, num_embeddings, embedding_dim, set_qconfig):NEWLINE num_lengths = np.random.randint(1, 6)NEWLINE lengths = np.random.randint(0, 21, size=num_lengths).astype(np.int32)NEWLINE num_indices = np.sum(lengths)NEWLINE indices = torch.from_numpy(np.random.randint(low=0, high=num_embeddings, size=num_indices, dtype=np.int64))NEWLINE weights = torch.from_numpy((np.random.random_sample((num_embeddings, embedding_dim)) + 1).astype(np.float32))NEWLINENEWLINE obs = default_float_qparams_observer()NEWLINE obs(weights)NEWLINE qparams = obs.calculate_qparams()NEWLINENEWLINE dtypes = [torch.quint4x2, torch.quint8]NEWLINE embedding_funcs = [torch.ops.quantized.embedding_4bit, torch.ops.quantized.embedding_byte]NEWLINENEWLINE for dtype, embedding_func in zip(dtypes, embedding_funcs):NEWLINE # Quantize the weightsNEWLINE qweight = torch.quantize_per_channel(weights, qparams[0], qparams[1], axis=0, dtype=dtype)NEWLINE qemb = nnq.Embedding(num_embeddings=num_embeddings, embedding_dim=embedding_dim, dtype=dtype)NEWLINE qemb.set_weight(qweight)NEWLINE qemb(indices)NEWLINENEWLINE # Ensure the module has the correct weightsNEWLINE self.assertEqual(qweight, qemb.weight())NEWLINE w_packed = qemb._packed_params._packed_weightNEWLINE module_out = qemb(indices)NEWLINENEWLINE # Call the bit qembedding operator directlyNEWLINE ref = embedding_func(w_packed, indices, pruned_weights=False)NEWLINE self.assertEqual(module_out, ref)NEWLINE self.checkEmbeddingSerialization(qemb, num_embeddings, embedding_dim, indices, None, set_qconfig=False,NEWLINE is_emb_bag=False, dtype=dtype)NEWLINENEWLINE @given(NEWLINE num_embeddings=st.integers(10, 50),NEWLINE embedding_dim=st.integers(5, 50).filter(lambda x: x % 4 == 0),NEWLINE num_offsets=st.integers(1, 20),NEWLINE set_qconfig=st.booleans(),NEWLINE )NEWLINE @skipIfNoFBGEMMNEWLINE def test_embedding_bag_api(self, num_embeddings, embedding_dim, num_offsets, set_qconfig):NEWLINE r"""Test execution and serialization for dynamic quantized embedding_bag modules on int8NEWLINE """NEWLINENEWLINE num_lengths = np.random.randint(1, 6)NEWLINE lengths = np.random.randint(0, 21, size=num_lengths).astype(np.int32)NEWLINE num_indices = np.sum(lengths)NEWLINE indices = torch.from_numpy(np.random.randint(low=0, high=num_embeddings, size=num_indices, dtype=np.int64))NEWLINENEWLINE offsets = lengths_to_offsets(lengths)NEWLINE # include the last offsetNEWLINE offsets = torch.cat((offsets, torch.tensor([indices.size(0)], dtype=torch.long)), 0)NEWLINE weights = torch.from_numpy((np.random.random_sample((num_embeddings, embedding_dim)) + 1).astype(np.float32))NEWLINENEWLINE for qdtype in [torch.quint8, torch.quint4x2]:NEWLINE obs = PerChannelMinMaxObserver(dtype=qdtype, qscheme=torch.per_channel_affine_float_qparams, ch_axis=0)NEWLINE obs(weights)NEWLINE # Get the scale and zero point for the weight tensorNEWLINE qparams = obs.calculate_qparams()NEWLINE # Quantize the weights to 8bitsNEWLINE qweight = torch.quantize_per_channel(weights, qparams[0], qparams[1], axis=0, dtype=qdtype)NEWLINE qemb = nnq.EmbeddingBag(num_embeddings=num_embeddings, embedding_dim=embedding_dim,NEWLINE include_last_offset=True, mode='sum', _weight=qweight, dtype=qdtype)NEWLINE qemb(indices, offsets)NEWLINENEWLINE # Ensure the module has the correct weightsNEWLINE self.assertEqual(qweight, qemb.weight())NEWLINENEWLINE w_packed = qemb._packed_params._packed_weightNEWLINE module_out = qemb(indices, offsets)NEWLINENEWLINE # Call the qembedding_bag operator directlyNEWLINE if qdtype == torch.quint8:NEWLINE ref = torch.ops.quantized.embedding_bag_byte(w_packed, indices, offsets, mode=0,NEWLINE per_sample_weights=None,NEWLINE include_last_offset=True)NEWLINE else:NEWLINE ref = torch.ops.quantized.embedding_bag_4bit(w_packed, indices, offsets, mode=0,NEWLINE per_sample_weights=None,NEWLINE include_last_offset=True)NEWLINENEWLINE self.assertEqual(module_out, ref)NEWLINE self.checkEmbeddingSerialization(qemb, num_embeddings, embedding_dim, indices,NEWLINE offsets, set_qconfig, is_emb_bag=True, dtype=qdtype)NEWLINENEWLINENEWLINEclass TestDynamicQuantizedModule(QuantizationTestCase):NEWLINE def _test_qconv_impl(self, q_mod, dq_mod, dim, dtype, bias):NEWLINE in_channels = 3NEWLINE out_channels = 10NEWLINE kernel_size = 2NEWLINE stride = 1NEWLINE padding = 0NEWLINE dilation = 1NEWLINE groups = 1NEWLINE padding_mode = 'zeros'NEWLINENEWLINE if qengine_is_qnnpack():NEWLINE reduce_range = FalseNEWLINE else:NEWLINE reduce_range = TrueNEWLINENEWLINE X_fp32 = torch.randn(*([in_channels] * dim))NEWLINE s, z = _calculate_dynamic_qparams(X_fp32, dtype, reduce_range)NEWLINE X_q = torch.quantize_per_tensor(X_fp32, s, z, dtype)NEWLINE X_dq = torch.dequantize(X_q)NEWLINENEWLINE quantized_module = q_mod(in_channels, out_channels, kernel_size, stride=stride, padding=padding,NEWLINE dilation=dilation, groups=groups, bias=bias, padding_mode=padding_mode)NEWLINE dynamic_module = dq_mod(in_channels, out_channels, kernel_size, stride=stride, padding=padding,NEWLINE dilation=dilation, groups=groups, bias=bias, padding_mode=padding_mode)NEWLINENEWLINE quantized_module.scale, quantized_module.zero_point = s, zNEWLINE dynamic_module.set_weight_bias(*quantized_module._weight_bias())NEWLINENEWLINE Y_q_ref = quantized_module(X_q)NEWLINE Y_ref = torch.dequantize(Y_q_ref)NEWLINENEWLINE Y = dynamic_module(X_dq, reduce_range)NEWLINENEWLINE self.assertEqual(Y, Y_ref)NEWLINENEWLINE # Test serialization of quantized Conv Module using state_dictNEWLINE W_q, b = dynamic_module._weight_bias()NEWLINE model_dict = dynamic_module.state_dict()NEWLINE self.assertEqual(model_dict['weight'], W_q)NEWLINE self.assertEqual(model_dict['bias'], b)NEWLINE bytes_io = io.BytesIO()NEWLINE torch.save(model_dict, bytes_io)NEWLINE bytes_io.seek(0)NEWLINE loaded_dict = torch.load(bytes_io)NEWLINE for key in loaded_dict:NEWLINE self.assertEqual(model_dict[key], loaded_dict[key])NEWLINE loaded_qconv_module = type(dynamic_module)(NEWLINE in_channels, out_channels, kernel_size, stride=stride, padding=padding,NEWLINE dilation=dilation, groups=groups, bias=bias, padding_mode=padding_mode)NEWLINE loaded_qconv_module.load_state_dict(loaded_dict)NEWLINENEWLINE self.assertTrue(dir(loaded_qconv_module) == dir(dynamic_module))NEWLINE self.assertTrue(dynamic_module._get_name() == loaded_qconv_module._get_name())NEWLINE self.assertTrue(hasattr(loaded_qconv_module, '_packed_params'))NEWLINE self.assertTrue(hasattr(loaded_qconv_module, '_weight_bias'))NEWLINENEWLINE self.assertEqual(dynamic_module.weight(), loaded_qconv_module.weight())NEWLINE if bias:NEWLINE self.assertEqual(dynamic_module.bias(), loaded_qconv_module.bias())NEWLINE self.assertEqual(dynamic_module.scale, loaded_qconv_module.scale)NEWLINE self.assertEqual(dynamic_module.zero_point,NEWLINE loaded_qconv_module.zero_point)NEWLINE Y_loaded = loaded_qconv_module(X_fp32, reduce_range)NEWLINE np.testing.assert_array_almost_equal(NEWLINE Y.numpy(), Y_loaded.numpy(), decimal=0)NEWLINENEWLINE # Test serializationNEWLINE b = io.BytesIO()NEWLINE torch.save(dynamic_module, b)NEWLINE b.seek(0)NEWLINE loaded_conv = torch.load(b)NEWLINENEWLINE self.assertEqual(loaded_conv.bias(), dynamic_module.bias())NEWLINE self.assertEqual(loaded_conv.scale, dynamic_module.scale)NEWLINE self.assertEqual(loaded_conv.zero_point,NEWLINE dynamic_module.zero_point)NEWLINENEWLINE # Test copy and deepcopyNEWLINE copied_conv = copy.copy(dynamic_module)NEWLINE self.assertEqual(copied_conv.bias(), dynamic_module.bias())NEWLINE self.assertEqual(copied_conv.scale, dynamic_module.scale)NEWLINE self.assertEqual(copied_conv.zero_point,NEWLINE dynamic_module.zero_point)NEWLINE Y_copied = copied_conv(X_fp32, reduce_range)NEWLINE np.testing.assert_array_almost_equal(NEWLINE Y.numpy(), Y_copied.numpy(), decimal=0)NEWLINENEWLINE deepcopied_conv = copy.deepcopy(dynamic_module)NEWLINE self.assertEqual(deepcopied_conv.bias(), dynamic_module.bias())NEWLINE self.assertEqual(deepcopied_conv.scale, dynamic_module.scale)NEWLINE self.assertEqual(deepcopied_conv.zero_point,NEWLINE dynamic_module.zero_point)NEWLINE Y_deepcopied = copied_conv(X_fp32, reduce_range)NEWLINE np.testing.assert_array_almost_equal(NEWLINE Y.numpy(), Y_deepcopied.numpy(), decimal=0)NEWLINENEWLINE # need to fix thisNEWLINE # JIT testingNEWLINE self.checkScriptable(NEWLINE dynamic_module, [[X_dq]],NEWLINE check_save_load=True)NEWLINENEWLINE # Test from_floatNEWLINE conv_module = dynamic_module._FLOAT_MODULE(in_channels, out_channels, kernel_size)NEWLINE conv_module.qconfig = torch.ao.quantization.default_dynamic_qconfig # type: ignore[assignment]NEWLINE prepare_dynamic(conv_module)NEWLINE conv_module(X_dq)NEWLINE quantized_conv_module = dq_mod.from_float(conv_module)NEWLINENEWLINE # Smoke test to make sure the module actually runsNEWLINE quantized_conv_module(X_dq)NEWLINENEWLINE # Smoke test extra_reprNEWLINE self.assertEqual(dynamic_module._get_name(), quantized_conv_module._get_name())NEWLINENEWLINE @override_qenginesNEWLINE def test_dynamic_conv1d(self):NEWLINE q_mod = torch.nn.quantized.Conv1dNEWLINE dq_mod = torch.nn.quantized.dynamic.Conv1dNEWLINE dim = 3NEWLINE dtype = torch.quint8NEWLINENEWLINE for bias in [True, False]:NEWLINE self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias)NEWLINENEWLINE @override_qenginesNEWLINE def test_dynamic_conv2d(self):NEWLINE q_mod = torch.nn.quantized.Conv2dNEWLINE dq_mod = torch.nn.quantized.dynamic.Conv2dNEWLINE dim = 4NEWLINE dtype = torch.quint8NEWLINENEWLINE for bias in [True, False]:NEWLINE self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias)NEWLINENEWLINE @override_qenginesNEWLINE def test_dynamic_conv3d(self):NEWLINE q_mod = torch.nn.quantized.Conv3dNEWLINE dq_mod = torch.nn.quantized.dynamic.Conv3dNEWLINE dim = 5NEWLINE dtype = torch.quint8NEWLINENEWLINE if qengine_is_qnnpack():NEWLINE return # qnnpack doesn't support unpacking conv3dNEWLINE for bias in [True, False]:NEWLINE self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias)NEWLINENEWLINE @override_qenginesNEWLINE def test_dynamic_convtranspose1d(self):NEWLINE q_mod = torch.nn.quantized.ConvTranspose1dNEWLINE dq_mod = torch.nn.quantized.dynamic.ConvTranspose1dNEWLINE dim = 3NEWLINE dtype = torch.quint8NEWLINENEWLINE for bias in [True, False]:NEWLINE self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias)NEWLINENEWLINE @override_qenginesNEWLINE def test_dynamic_convtranspose2d(self):NEWLINE q_mod = torch.nn.quantized.ConvTranspose2dNEWLINE dq_mod = torch.nn.quantized.dynamic.ConvTranspose2dNEWLINE dim = 4NEWLINE dtype = torch.quint8NEWLINENEWLINE for bias in [True, False]:NEWLINE self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias)NEWLINENEWLINE @override_qenginesNEWLINE def test_dynamic_convtranspose3d(self):NEWLINE q_mod = torch.nn.quantized.ConvTranspose3dNEWLINE dq_mod = torch.nn.quantized.dynamic.ConvTranspose3dNEWLINE dim = 5NEWLINE dtype = torch.quint8NEWLINENEWLINE if qengine_is_qnnpack():NEWLINE return # qnnpack doesn't support unpacking conv3dNEWLINE for bias in [True, False]:NEWLINE self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias)NEWLINENEWLINE @given(NEWLINE batch_size=st.integers(1, 5),NEWLINE in_features=st.integers(16, 32),NEWLINE out_features=st.integers(4, 8),NEWLINE use_bias=st.booleans(),NEWLINE use_default_observer=st.booleans(),NEWLINE )NEWLINE @override_qenginesNEWLINE def test_linear_api(self, batch_size, in_features, out_features, use_bias, use_default_observer):NEWLINE """test API functionality for nn.quantized.dynamic.Linear"""NEWLINE W = torch.rand(out_features, in_features).float()NEWLINE W_scale, W_zp = _calculate_dynamic_qparams(W, torch.qint8)NEWLINE W_q = torch.quantize_per_tensor(W, W_scale, W_zp, torch.qint8)NEWLINE X = torch.rand(batch_size, in_features).float()NEWLINE B = torch.rand(out_features).float() if use_bias else NoneNEWLINE qlinear = nnqd.Linear(in_features, out_features)NEWLINE # Run module with default-initialized parameters.NEWLINE # This tests that the constructor is correct.NEWLINE qlinear.set_weight_bias(W_q, B)NEWLINE qlinear(X)NEWLINENEWLINE # Simple round-trip test to ensure weight()/set_weight() APINEWLINE self.assertEqual(qlinear.weight(), W_q)NEWLINE W_pack = qlinear._packed_params._packed_paramsNEWLINE Z_dq = qlinear(X)NEWLINENEWLINE # Check if the module implementation matches calling theNEWLINE # ops directlyNEWLINE Z_ref = torch.ops.quantized.linear_dynamic(X, W_pack, reduce_range=True)NEWLINE self.assertEqual(Z_ref, Z_dq)NEWLINENEWLINE # Test serialization of dynamic quantized Linear Module using state_dictNEWLINE model_dict = qlinear.state_dict()NEWLINE b = io.BytesIO()NEWLINE torch.save(model_dict, b)NEWLINE b.seek(0)NEWLINE loaded_dict = torch.load(b)NEWLINE for key in model_dict:NEWLINE if isinstance(model_dict[key], torch._C.ScriptObject):NEWLINE assert isinstance(loaded_dict[key], torch._C.ScriptObject)NEWLINE w_model, b_model = torch.ops.quantized.linear_unpack(model_dict[key])NEWLINE w_loaded, b_loaded = torch.ops.quantized.linear_unpack(loaded_dict[key])NEWLINE self.assertEqual(w_model, w_loaded)NEWLINE self.assertEqual(b_model, b_loaded)NEWLINE else:NEWLINE self.assertEqual(model_dict[key], loaded_dict[key])NEWLINE loaded_qlinear = nnqd.Linear(in_features, out_features)NEWLINE loaded_qlinear.load_state_dict(loaded_dict)NEWLINENEWLINE linear_unpack = torch.ops.quantized.linear_unpackNEWLINE self.assertEqual(linear_unpack(qlinear._packed_params._packed_params),NEWLINE linear_unpack(loaded_qlinear._packed_params._packed_params))NEWLINE if use_bias:NEWLINE self.assertEqual(qlinear.bias(), loaded_qlinear.bias())NEWLINE self.assertTrue(dir(qlinear) == dir(loaded_qlinear))NEWLINE self.assertTrue(hasattr(qlinear, '_packed_params'))NEWLINE self.assertTrue(hasattr(loaded_qlinear, '_packed_params'))NEWLINE self.assertTrue(hasattr(qlinear, '_weight_bias'))NEWLINE self.assertTrue(hasattr(loaded_qlinear, '_weight_bias'))NEWLINENEWLINE self.assertEqual(qlinear._weight_bias(), loaded_qlinear._weight_bias())NEWLINE self.assertEqual(qlinear._weight_bias(), torch.ops.quantized.linear_unpack(qlinear._packed_params._packed_params))NEWLINE Z_dq2 = qlinear(X)NEWLINE self.assertEqual(Z_dq, Z_dq2)NEWLINENEWLINE b = io.BytesIO()NEWLINE torch.save(qlinear, b)NEWLINE b.seek(0)NEWLINE loaded = torch.load(b)NEWLINE self.assertEqual(qlinear.weight(), loaded.weight())NEWLINE self.assertEqual(qlinear.zero_point, loaded.zero_point)NEWLINENEWLINE # Test JITNEWLINE self.checkScriptable(qlinear, [[X]], check_save_load=True)NEWLINENEWLINE modules_under_test = [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear]NEWLINE for mut in modules_under_test:NEWLINE # Test from_floatNEWLINE float_linear = mut(in_features, out_features).float()NEWLINE if use_default_observer:NEWLINE float_linear.qconfig = torch.ao.quantization.default_dynamic_qconfigNEWLINE prepare_dynamic(float_linear)NEWLINE float_linear(X.float())NEWLINE quantized_float_linear = nnqd.Linear.from_float(float_linear)NEWLINENEWLINE # Smoke test to make sure the module actually runsNEWLINE quantized_float_linear(X)NEWLINENEWLINE # Smoke test extra_reprNEWLINE self.assertTrue('QuantizedLinear' in str(quantized_float_linear))NEWLINENEWLINE @given(NEWLINE dtype=st.sampled_from([torch.qint8, torch.float16]),NEWLINE bidirectional=st.booleans(),NEWLINE )NEWLINE @override_qenginesNEWLINE def test_lstm_api(self, dtype, bidirectional):NEWLINE r"""Test execution and serialization for dynamic quantized lstm modules on int8 and fp16NEWLINE """NEWLINE # Check that module matches the numerics of the op and ensure that module can beNEWLINE # instantiated for all engines and dtypesNEWLINE seq_len = 4NEWLINE batch = 2NEWLINE input_size = 3NEWLINE hidden_size = 7NEWLINE num_layers = 2NEWLINE bias = TrueNEWLINE weight_keys = []NEWLINE bias_keys = []NEWLINE num_directions = 2 if bidirectional else 1NEWLINE for layer in range(num_layers):NEWLINE for direction in range(num_directions):NEWLINE suffix = '_reverse' if direction == 1 else ''NEWLINE key_name1 = 'weight_ih_l{layer_idx}{suffix}'.format(layer_idx=layer, suffix=suffix)NEWLINE key_name2 = 'weight_hh_l{layer_idx}{suffix}'.format(layer_idx=layer, suffix=suffix)NEWLINE weight_keys.append(key_name1)NEWLINE weight_keys.append(key_name2)NEWLINE key_name1 = 'bias_ih_l{layer_idx}{suffix}'.format(layer_idx=layer, suffix=suffix)NEWLINE key_name2 = 'bias_hh_l{layer_idx}{suffix}'.format(layer_idx=layer, suffix=suffix)NEWLINE bias_keys.append(key_name1)NEWLINE bias_keys.append(key_name2)NEWLINENEWLINE if not (dtype == torch.float16 and torch.backends.quantized.engine == "qnnpack"):NEWLINE # fp16 dynamic quant is not supported for qnnpackNEWLINE x = torch.randn(seq_len, batch, input_size)NEWLINE h = torch.randn(num_layers * (bidirectional + 1), batch, hidden_size)NEWLINE c = torch.randn(num_layers * (bidirectional + 1), batch, hidden_size)NEWLINE cell_dq = torch.nn.quantized.dynamic.LSTM(input_size=input_size,NEWLINE hidden_size=hidden_size,NEWLINE num_layers=num_layers,NEWLINE bias=bias,NEWLINE batch_first=False,NEWLINE dropout=0.0,NEWLINE bidirectional=bidirectional,NEWLINE dtype=dtype)NEWLINE ref_dq = torch.nn.quantized.dynamic.LSTM(input_size=input_size,NEWLINE hidden_size=hidden_size,NEWLINE num_layers=num_layers,NEWLINE bias=bias,NEWLINE batch_first=False,NEWLINE dropout=0.0,NEWLINE bidirectional=bidirectional,NEWLINE dtype=dtype)NEWLINENEWLINE _all_params = ([m.param for m in cell_dq._all_weight_values])NEWLINE result = torch.quantized_lstm(x, (h, c),NEWLINE _all_params,NEWLINE cell_dq.bias,NEWLINE cell_dq.num_layers,NEWLINE float(cell_dq.dropout),NEWLINE False,NEWLINE bidirectional,NEWLINE False,NEWLINE dtype=dtype,NEWLINE use_dynamic=True)NEWLINENEWLINENEWLINE y, (h, c) = cell_dq(x, (h, c))NEWLINE self.assertEqual(result[0], y)NEWLINE self.assertEqual(result[1], h)NEWLINE self.assertEqual(result[2], c)NEWLINE x = torch.randn(10, 20, 3)NEWLINE self.check_eager_serialization(cell_dq, ref_dq, [x])NEWLINE self.check_weight_bias_api(cell_dq, weight_keys, bias_keys)NEWLINENEWLINE @override_qenginesNEWLINE def test_gru_api(self):NEWLINE r"""Test execution and serialization for dynamic quantized lstm modules on int8 and fp16NEWLINE """NEWLINE # Check that module matches the numerics of the op and ensure that module can beNEWLINE # instantiated for all engines and dtypesNEWLINENEWLINE for dtype in [torch.qint8, torch.float16]:NEWLINE if dtype == torch.float16 and torch.backends.quantized.engine == "qnnpack":NEWLINE # fp16 dynamic quant is not supported for qnnpackNEWLINE continueNEWLINE # Test default instantiationNEWLINE seq_len = 4NEWLINE batch = 2NEWLINE input_size = 3NEWLINE hidden_size = 7NEWLINE num_layers = 2NEWLINE bias = TrueNEWLINE bidirectional = FalseNEWLINENEWLINE x = torch.rand(seq_len, batch, input_size)NEWLINE h = torch.rand(num_layers * (bidirectional + 1), batch, hidden_size)NEWLINENEWLINENEWLINE cell_dq = torch.nn.quantized.dynamic.GRU(input_size=input_size,NEWLINE hidden_size=hidden_size,NEWLINE num_layers=num_layers,NEWLINE bias=bias,NEWLINE batch_first=False,NEWLINE dropout=0.0,NEWLINE bidirectional=bidirectional,NEWLINE dtype=dtype)NEWLINENEWLINE _all_params = ([m.param for m in cell_dq._all_weight_values])NEWLINE result = torch.quantized_gru(x,NEWLINE h,NEWLINE _all_params,NEWLINE cell_dq.bias,NEWLINE cell_dq.num_layers,NEWLINE float(cell_dq.dropout),NEWLINE False,NEWLINE bidirectional,NEWLINE False)NEWLINENEWLINENEWLINE y, h = cell_dq(x, h)NEWLINE self.assertEqual(result[0], y, msg="GRU module API failed")NEWLINE self.assertEqual(result[1], h, msg="GRU module API failed")NEWLINENEWLINE @given(NEWLINE dtype=st.sampled_from([torch.qint8, torch.float16]),NEWLINE )NEWLINE @override_qenginesNEWLINE def test_cell_api(self, dtype):NEWLINE r"""Test execution and serialization for dynamic quantized lstm modules on int8 and fp16NEWLINE """NEWLINE # Check that module matches the numerics of the op and ensure that module can beNEWLINE # instantiated for all engines and dtypesNEWLINE batch = 7NEWLINE input_size = 3NEWLINE hidden_size = 7NEWLINE bias = TrueNEWLINENEWLINE x = torch.rand(batch, input_size)NEWLINE h = torch.rand(batch, hidden_size)NEWLINE cell_dict = {'LSTMCell': torch.nn.quantized.dynamic.LSTMCell,NEWLINE 'GRUCell': torch.nn.quantized.dynamic.GRUCell,NEWLINE 'RNNTanh': torch.nn.quantized.dynamic.RNNCell,NEWLINE 'RNNReLU': torch.nn.quantized.dynamic.RNNCellNEWLINE }NEWLINE state = {'LSTMCell': (h, h),NEWLINE 'GRUCell': h,NEWLINE 'RNNTanh': h,NEWLINE 'RNNReLU': h}NEWLINENEWLINE qfn_dict = {'LSTMCell': torch.ops.quantized.quantized_lstm_cell_dynamic,NEWLINE 'GRUCell': torch.ops.quantized.quantized_gru_cell_dynamic,NEWLINE 'RNNTanh': torch.ops.quantized.quantized_rnn_tanh_cell_dynamic,NEWLINE 'RNNReLU': torch.ops.quantized.quantized_rnn_relu_cell_dynamic}NEWLINENEWLINE for rnn_type in cell_dict.keys():NEWLINE if not (dtype == torch.float16 and torch.backends.quantized.engine == "qnnpack"):NEWLINE # fp16 dynamic quant is not supported for qnnpackNEWLINE kwargs = {'input_size': input_size, 'hidden_size': hidden_size, 'bias': bias, 'dtype': dtype}NEWLINE if rnn_type == 'RNNReLU':NEWLINE kwargs['nonlinearity'] = "relu"NEWLINE elif rnn_type == 'RNNTanh':NEWLINE kwargs['nonlinearity'] = "tanh"NEWLINENEWLINE cell_dq = cell_dict[rnn_type](**kwargs)NEWLINE result = qfn_dict[rnn_type](x, state[rnn_type],NEWLINE cell_dq._packed_weight_ih, cell_dq._packed_weight_hh,NEWLINE cell_dq.bias_ih, cell_dq.bias_hh)NEWLINE result_module = cell_dq(x, state[rnn_type])NEWLINE self.assertEqual(result[0], result_module[0], msg="RNNCell module API failed")NEWLINE self.assertEqual(result[1], result_module[1], msg="RNNCell module API failed")NEWLINE weight_keys = ['weight_ih', 'weight_hh']NEWLINE bias_keys = ['bias_ih', 'bias_hh']NEWLINE self.check_eager_serialization(cell_dq, cell_dict[rnn_type](**kwargs), [x])NEWLINE self.check_weight_bias_api(cell_dq, weight_keys, bias_keys)NEWLINENEWLINEclass TestReferenceQuantizedModule(QuantizationTestCase):NEWLINE def _quant_dequant_weight(self, weight, weight_qparams):NEWLINE qscheme = weight_qparams["qscheme"]NEWLINE scale = weight_qparams["scale"]NEWLINE zero_point = weight_qparams["zero_point"]NEWLINE dtype = weight_qparams["dtype"]NEWLINE if qscheme == torch.per_tensor_affine:NEWLINE weight = torch.quantize_per_tensor(weight, scale, zero_point, dtype)NEWLINE else:NEWLINE # per channel affineNEWLINE axis = weight_qparams["axis"]NEWLINE weight = torch.quantize_per_channel(weight, scale, zero_point, axis, dtype)NEWLINE weight = weight.dequantize()NEWLINE return weightNEWLINENEWLINE # TODO: add tests for conv and linearNEWLINE def test_rnn_cell(self):NEWLINE """ Checks the rnn cell reference quantized modules has correct numericsNEWLINE This includes LSTMCell, GRUCell, RNNCellNEWLINE """NEWLINE batch = 7NEWLINE input_size = 3NEWLINE hidden_size = 7NEWLINE bias = TrueNEWLINENEWLINE x = torch.rand(batch, input_size)NEWLINE h = torch.rand(batch, hidden_size)NEWLINE cell_dict = {'LSTMCell': torch.nn.LSTMCell,NEWLINE 'GRUCell': torch.nn.GRUCell,NEWLINE 'RNNTanh': torch.nn.RNNCell,NEWLINE 'RNNReLU': torch.nn.RNNCellNEWLINE }NEWLINE state = {'LSTMCell': (h, h),NEWLINE 'GRUCell': h,NEWLINE 'RNNTanh': h,NEWLINE 'RNNReLU': h}NEWLINENEWLINE qfn_dict = {'LSTMCell': nnqr.LSTMCell,NEWLINE 'GRUCell': nnqr.GRUCell,NEWLINE 'RNNTanh': nnqr.RNNCell,NEWLINE 'RNNReLU': nnqr.RNNCell}NEWLINENEWLINE for rnn_type in cell_dict.keys():NEWLINE kwargs = {'input_size': input_size, 'hidden_size': hidden_size, 'bias': bias}NEWLINE if rnn_type == 'RNNReLU':NEWLINE kwargs['nonlinearity'] = "relu"NEWLINE elif rnn_type == 'RNNTanh':NEWLINE kwargs['nonlinearity'] = "tanh"NEWLINENEWLINE fp_cell = cell_dict[rnn_type](**kwargs)NEWLINE # initialize ref rnn cell moduleNEWLINE weight_qparams = {NEWLINE 'qscheme': torch.per_tensor_affine,NEWLINE 'dtype': torch.quint8,NEWLINE 'scale': 2.0,NEWLINE 'zero_point': 5NEWLINE }NEWLINE weight_qparams_dict = {NEWLINE "weight_ih": weight_qparams,NEWLINE "weight_hh": weight_qparams,NEWLINE }NEWLINE ref_kwargs = kwargs.copy()NEWLINE ref_kwargs["weight_qparams_dict"] = weight_qparams_dictNEWLINE ref_cell = qfn_dict[rnn_type](**ref_kwargs)NEWLINE # reassign the weights from fp32 rnn cell moduleaNEWLINE ref_cell.weight_ih = fp_cell.weight_ihNEWLINE ref_cell.weight_hh = fp_cell.weight_hhNEWLINE ref_cell.bias_ih = fp_cell.bias_ihNEWLINE ref_cell.bias_hh = fp_cell.bias_hhNEWLINENEWLINE ref_res = ref_cell(x, state[rnn_type])NEWLINENEWLINE # change the weight of fp_res, we first want to run a quantie andNEWLINE # dequantize on the weightNEWLINE fp_cell.weight_ih = torch.nn.Parameter(self._quant_dequant_weight(fp_cell.weight_ih, weight_qparams_dict["weight_ih"]))NEWLINE fp_cell.weight_hh = torch.nn.Parameter(self._quant_dequant_weight(fp_cell.weight_hh, weight_qparams_dict["weight_hh"]))NEWLINE fp_res = fp_cell(x, state[rnn_type])NEWLINE self.assertEqual(ref_res[0], fp_res[0], msg="RNNCell module API failed")NEWLINE self.assertEqual(ref_res[1], fp_res[1], msg="RNNCell module API failed")NEWLINENEWLINE def test_rnn(self):NEWLINE """ Checks the rnn reference quantized modules has correct numericsNEWLINE This includes LSTMNEWLINE """NEWLINE seq_len = 4NEWLINE batch = 2NEWLINE input_size = 3NEWLINE hidden_size = 7NEWLINE num_layers = 2NEWLINE bias = TrueNEWLINE weight_keys = []NEWLINE bias_keys = []NEWLINE for bidirectional in [True, False]:NEWLINE num_directions = 2 if bidirectional else 1NEWLINE for layer in range(num_layers):NEWLINE for direction in range(num_directions):NEWLINE suffix = '_reverse' if direction == 1 else ''NEWLINE key_name1 = 'weight_ih_l{layer_idx}{suffix}'.format(layer_idx=layer, suffix=suffix)NEWLINE key_name2 = 'weight_hh_l{layer_idx}{suffix}'.format(layer_idx=layer, suffix=suffix)NEWLINE weight_keys.append(key_name1)NEWLINE weight_keys.append(key_name2)NEWLINE key_name1 = 'bias_ih_l{layer_idx}{suffix}'.format(layer_idx=layer, suffix=suffix)NEWLINE key_name2 = 'bias_hh_l{layer_idx}{suffix}'.format(layer_idx=layer, suffix=suffix)NEWLINE bias_keys.append(key_name1)NEWLINE bias_keys.append(key_name2)NEWLINENEWLINE x = torch.randn(seq_len, batch, input_size)NEWLINE h = torch.randn(num_layers * (bidirectional + 1), batch, hidden_size)NEWLINE c = torch.randn(num_layers * (bidirectional + 1), batch, hidden_size)NEWLINE fp32_rnn = torch.nn.LSTM(NEWLINE input_size=input_size,NEWLINE hidden_size=hidden_size,NEWLINE num_layers=num_layers,NEWLINE bias=bias,NEWLINE batch_first=False,NEWLINE dropout=0.0,NEWLINE bidirectional=bidirectional)NEWLINE # initialize ref rnn moduleNEWLINE weight_qparams = {NEWLINE 'qscheme': torch.per_tensor_affine,NEWLINE 'dtype': torch.quint8,NEWLINE 'scale': 2.0,NEWLINE 'zero_point': 5NEWLINE }NEWLINE weight_qparams_dict = {key: weight_qparams for key in fp32_rnn._flat_weights_names}NEWLINE ref_rnn = nnqr.LSTM(NEWLINE input_size=input_size,NEWLINE hidden_size=hidden_size,NEWLINE num_layers=num_layers,NEWLINE bias=bias,NEWLINE batch_first=False,NEWLINE dropout=0.0,NEWLINE bidirectional=bidirectional,NEWLINE weight_qparams_dict=weight_qparams_dict)NEWLINE ref_rnn._flat_weights = fp32_rnn._flat_weightsNEWLINENEWLINE # quantize and dequantize the weights for fp32_rnn moduleNEWLINE fp32_rnn._flat_weights = [self._quant_dequant_weight(w, weight_qparams) for w in fp32_rnn._flat_weights]NEWLINENEWLINE fp32_res = fp32_rnn(x, (h, c))NEWLINE ref_res = ref_rnn(x, (h, c))NEWLINE self.assertEqual(fp32_res, ref_res)NEWLINENEWLINE def test_sparse(self):NEWLINE """ Embedding and EmbeddingBagNEWLINE """NEWLINE num_embeddings = 10NEWLINE embedding_dim = 3NEWLINE # embedding inputNEWLINE ex = torch.LongTensor([[1, 2, 4, 5], [4, 3, 2, 9]])NEWLINENEWLINE # embedding bag inputNEWLINE ebx = torch.tensor([1, 2, 4, 5, 4, 3, 2, 9], dtype=torch.long)NEWLINE offsets = torch.tensor([0, 4], dtype=torch.long)NEWLINENEWLINE fp_to_ref = {NEWLINE nn.Embedding: (nnqr.Embedding, (ex,)),NEWLINE nn.EmbeddingBag: (nnqr.EmbeddingBag, (ebx, offsets)),NEWLINE }NEWLINENEWLINE per_tensor_weight_qparams = {NEWLINE 'qscheme': torch.per_tensor_affine,NEWLINE 'dtype': torch.quint8,NEWLINE 'scale': 2.0,NEWLINE 'zero_point': 5,NEWLINE }NEWLINENEWLINE per_channel_weight_qparams = {NEWLINE 'qscheme': torch.per_channel_affine,NEWLINE 'dtype': torch.quint8,NEWLINE 'scale': torch.randn(10),NEWLINE 'zero_point': torch.randint(0, 255, (10,)),NEWLINE 'axis': 0,NEWLINE }NEWLINENEWLINE per_channel_weight_qparams_quint4x2 = {NEWLINE 'qscheme': torch.per_channel_affine_float_qparams,NEWLINE 'dtype': torch.quint4x2,NEWLINE 'scale': torch.randn(10),NEWLINE 'zero_point': torch.randint(0, 255, (10,)),NEWLINE 'axis': 0,NEWLINE }NEWLINENEWLINE weight_qparams_options = [NEWLINE per_tensor_weight_qparams,NEWLINE per_channel_weight_qparams,NEWLINE per_channel_weight_qparams_quint4x2,NEWLINE ]NEWLINE for fp_cls, weight_qparams in itertools.product([nn.Embedding, nn.EmbeddingBag], weight_qparams_options):NEWLINE # TODO: torch.quint4x2 not supported in quantize_per_channel, need to add supportNEWLINE if weight_qparams['dtype'] == torch.quint4x2:NEWLINE continueNEWLINE ref_cls, args = fp_to_ref[fp_cls]NEWLINENEWLINE fp32_embedding = fp_cls(num_embeddings, embedding_dim)NEWLINENEWLINE ref_embedding = ref_cls(num_embeddings, embedding_dim, weight_qparams=weight_qparams)NEWLINE ref_embedding.weight = fp32_embedding.weightNEWLINENEWLINE # quantize and dequantize the weight for fp32 moduleNEWLINE fp32_embedding.weight = torch.nn.Parameter(self._quant_dequant_weight(fp32_embedding.weight, weight_qparams))NEWLINENEWLINE fp32_res = fp32_embedding(*args)NEWLINE ref_res = ref_embedding(*args)NEWLINE self.assertEqual(fp32_res, ref_res)NEWLINE import open3d as o3dNEWLINENEWLINENEWLINEFilterScope=o3d.geometry.FilterScopeNEWLINENEWLINEdef removePCDOutlier(pcd,voxel_size=0.001,nb_points=32,radius=0.004):NEWLINE '''NEWLINE 尝试除去点云离群点NEWLINE '''NEWLINE downpcd=pcd.voxel_down_sample(voxel_size=voxel_size)NEWLINE inlierPcd,idxs=downpcd.remove_radius_outlier(nb_points=nb_points,radius=radius)NEWLINE return inlierPcd,idxsNEWLINENEWLINEdef smoothMeshSimple(mesh,iterTimes=1):NEWLINE return mesh.filter_smooth_simple(number_of_iterations=iterTimes,filter_scope=FilterScope.Vertex)NEWLINENEWLINEdef smoothMeshLaplacian(mesh,iterTimes=10,nLambda=0.85):NEWLINE return mesh.filter_smooth_laplacian(NEWLINE number_of_iterations=iterTimes,filter_scope=FilterScope.Vertex,NEWLINE **{"lambda":nLambda}NEWLINE )NEWLINENEWLINEdef smoothMeshTaubin(mesh,iterTimes=30,nLambda=0.85,nMu=-0.25):NEWLINE return mesh.filter_smooth_taubin(number_of_iterations=iterTimes,filter_scope=FilterScope.Vertex,NEWLINE **{"lambda":nLambda,"mu":nMu}NEWLINE )NEWLINENEWLINEdef postProcessMesh(mesh,smoothFunc,*args,**kw):NEWLINE mesh=mesh.remove_non_manifold_edges()NEWLINE mesh=mesh.remove_degenerate_triangles()NEWLINE mesh=mesh.remove_duplicated_triangles()NEWLINE mesh=mesh.remove_unreferenced_vertices()NEWLINE mesh=mesh.remove_duplicated_vertices()NEWLINE meshf=mesh.filter_sharpen(number_of_iterations=1,strength=0.05,filter_scope=FilterScope.Color)NEWLINE mesh.vertex_colors=meshf.vertex_colorsNEWLINE mesh=smoothFunc(mesh,*args,**kw)NEWLINE mesh.compute_vertex_normals()NEWLINE return meshNEWLINE # -*- coding: utf-8 -*-NEWLINE"""NEWLINECreated on Tue Dec 13 01:25:12 2017NEWLINEComplete document analysis:NEWLINE1) Fuzzy String compare for file similarityNEWLINE2) Word frequency counterNEWLINE3) Phrase frequency counterNEWLINE@author: MStattelmanNEWLINE"""NEWLINENEWLINE#ImportsNEWLINEimport pandas as pdNEWLINEimport globNEWLINEimport reNEWLINEimport osNEWLINEimport nltkNEWLINEimport collectionsNEWLINEfrom collections import CounterNEWLINEfrom nltk import ngramsNEWLINEimport sysNEWLINEfrom math import logNEWLINEimport timeNEWLINEimport difflibNEWLINEimport itertoolsNEWLINEimport uuidNEWLINEfrom functools import reduceNEWLINEfrom statistics import mean, stdevNEWLINENEWLINENEWLINENEWLINE#--------------Set up directories and VariablesNEWLINE#Set start time to calculate time of processingNEWLINEstart = time.time()NEWLINE#Set file extension for specific filetypesNEWLINEfileext = '.txt'NEWLINE#Set directory of files for processingNEWLINEcompdir = 'datafiles/'NEWLINE#Create a output directory based on a UIDNEWLINEgui = os.path.join(str(uuid.uuid4().hex))NEWLINEoutdir = gui +'/'NEWLINEif not os.path.exists(outdir):NEWLINE os.makedirs(outdir)NEWLINENEWLINE#get all of the files in the directory into a listNEWLINEtxt_files = list(filter(lambda x: x.endswith(fileext), os.listdir(compdir)))NEWLINENEWLINEdef geo_mean_calc(n):NEWLINE """NEWLINE Calculate the GeomaenNEWLINE """NEWLINE geomean = lambda n: reduce(lambda x,y: x*y, n) ** (1.0 / len(n))NEWLINE return geomean(n)NEWLINENEWLINENEWLINEdef compareEach(x,y):NEWLINE """NEWLINE Compare the 2 files passed in using fuzzy string compareNEWLINE """NEWLINE with open(compdir + x, 'r') as myfile:NEWLINE data=myfile.read().replace('\n', '').lower()NEWLINE myfile.close()NEWLINE with open(compdir + y, 'r') as myfile2:NEWLINE data2=myfile2.read().replace('\n', '').lower() NEWLINE myfile2.close()NEWLINE NEWLINE return difflib.SequenceMatcher(None, data, data2).ratio()NEWLINE NEWLINE#Set up lists for file names and Fuzzy logic calculationsNEWLINEaList = []NEWLINEf1 = []NEWLINEf2 = []NEWLINEbList = []NEWLINE#Loop through each list item and compare it against the other itemsNEWLINEfor a, b in itertools.combinations(txt_files, 2):NEWLINE aList.append("File ["+a+"] and file ["+b+"] has a similarity of ");NEWLINE f1.append(a)NEWLINE f2.append(b)NEWLINE bList.append(compareEach(a,b));NEWLINE NEWLINENEWLINE#Combine both lists into a corolary dictionaryNEWLINEd= dict(zip(aList, bList))NEWLINENEWLINE#Save sorted dict as new dictionary from most similar to leastNEWLINEd1 = dict(sorted(d.items(), key=lambda x: x[1], reverse=True))NEWLINENEWLINE#Save results to file:NEWLINEfo = open(outdir+'datafile-comparison.txt', "w")NEWLINE#Print Headers to fileNEWLINEfo.write('File similarity ranked from most to least similar:\n\n')NEWLINEfo.write('Geometric Mean:'+str(geo_mean_calc(bList))+'\n\n')NEWLINEfo.write('Arithmatic Mean:'+str(mean(bList))+'\n\n')NEWLINE#Print Output to fileNEWLINEfor k, v in d1.items():NEWLINE fo.write(str(k) + ' >>> '+ str(v) + '\n\n')NEWLINEfo.close()NEWLINENEWLINENEWLINENEWLINE#Use tweet tokenizer to prevent contracted words from splitingNEWLINEfrom nltk.tokenize import TweetTokenizerNEWLINENEWLINEdef remove_punctuation(text):NEWLINE # Removes all punctuation and conotation from the string and returns a 'plain' stringNEWLINE punctuation2 = '-&'+'®©™€â´‚³©¥ã¼•ž®è±äüöž!@#“§$%^*()î_+€$=¿{”}[]:«;"»\â¢|<>,.?/~`0123456789'NEWLINE for sign in punctuation2:NEWLINE text = text.replace(sign, " ")NEWLINE return textNEWLINENEWLINENEWLINE#Set length of word combinations for use in counters.NEWLINEphrase_len = 4NEWLINEterm_len = 1NEWLINENEWLINEcorpus = []NEWLINEpath = compdirNEWLINENEWLINEfile_list = []NEWLINEos.chdir(path)NEWLINE#Get all files in the directory loaded into the corpusNEWLINEfor file in glob.glob("*.txt"):NEWLINE file_list.append(file)NEWLINE f = open(file)NEWLINE corpus.append(remove_punctuation(f.read()))NEWLINE f.close()NEWLINENEWLINEfrequencies0 = Counter([])NEWLINEfrequencies = Counter([])NEWLINE#Cycle through corpus to generate frequencies metricsNEWLINEfor text in corpus:NEWLINE tknzr = TweetTokenizer()NEWLINE token = tknzr.tokenize(text)NEWLINE #Frequency for wordsNEWLINE single = ngrams(token, term_len)NEWLINE frequencies0 += Counter(single)NEWLINE #Frequency for phrasesNEWLINE quadgrams = ngrams(token, phrase_len)NEWLINE frequencies += Counter(quadgrams)NEWLINENEWLINEod0 = collections.OrderedDict(frequencies0.most_common())NEWLINEod = collections.OrderedDict(frequencies.most_common())NEWLINENEWLINE#Build dataframesNEWLINEos.chdir('..')NEWLINENEWLINE#Create output for fuzzy string compare as dataframeNEWLINEdfz = pd.DataFrame(list(zip(f1, f2, bList)),NEWLINE columns=['File #1','File #2', 'Similarity'])NEWLINEdfz.sort_values(["Similarity"], inplace=True, ascending=False)NEWLINEdfz.index = pd.RangeIndex(len(dfz.index))NEWLINENEWLINE#Create output for word frequency dataframeNEWLINEdf0 = pd.DataFrame.from_dict(od0, orient='index').reset_index()NEWLINEdf0 = df0.rename(columns={'index':'Word', 0:'Count'})NEWLINENEWLINENEWLINE#Create output for Phrase frequency as dataframeNEWLINEdf = pd.DataFrame.from_dict(od, orient='index').reset_index()NEWLINEdf = df.rename(columns={'index':'Phrase', 0:'Count'})NEWLINENEWLINENEWLINE#Get a count of all words and phrasesNEWLINECount_Words=df0.shape[0]NEWLINECount_Phrase=df.shape[0]NEWLINENEWLINE#Generate html files from dataframesNEWLINEdfz.to_html(open(outdir +'Sim.html', 'a'))NEWLINEdf0.to_html(open(outdir +'Word.html', 'a'))NEWLINEdf.to_html(open(outdir +'Phrase.html', 'a'))NEWLINENEWLINENEWLINE#Write File list to FileNEWLINEwith open (outdir+"complete.txt","a")as fp1:NEWLINE fp1.write("Execution time: " + str(time.time() - start) +"s\n\n")NEWLINE fp1.write("With a total unique word count of:"+str(Count_Words)+"\n\n")NEWLINE fp1.write("With a total unique phrase count of:"+str(Count_Phrase)+"\n\n")NEWLINE fp1.write("The following files ("+str(len(file_list))+") were processed in the comparisons:\n\n")NEWLINE for line in file_list:NEWLINE fp1.write(line+"\n\n")NEWLINE fp1.close()NEWLINENEWLINE#Generate Analysis pdf form files collectionNEWLINEimport pdfkitNEWLINEpdfkit.from_file([outdir+"complete.txt",outdir+'Sim.html',outdir +'Word.html',outdir +'Phrase.html'], outdir +' Task-'+gui+'-Document-Analysis.pdf') import gymNEWLINEimport randomNEWLINEimport numpy as npNEWLINEimport argparseNEWLINEfrom arguments import get_argsNEWLINEfrom actorcritic import Actor, second, act, actorNEWLINEimport torchNEWLINEfrom torch.autograd import VariableNEWLINEimport torch.nn.functional as FNEWLINEimport torch.optim as optimNEWLINEimport torch.cudaNEWLINEimport matplotlib.pyplot as pltNEWLINEfrom torch.distributions import NormalNEWLINEimport osNEWLINEimport randomNEWLINEimport torch.nn as nnNEWLINEfrom itertools import countNEWLINEimport timeNEWLINEimport csvNEWLINENEWLINEdef ensure_shared_grads(model, shared_model):NEWLINE for param, shared_param in zip(model.parameters(),shared_model.parameters()):NEWLINE if shared_param.grad is not None:NEWLINE returnNEWLINE shared_param._grad = param.gradNEWLINENEWLINE# process the inputsNEWLINEdef process_inputs(o, g, o_mean, o_std, g_mean, g_std, args):NEWLINE o_clip = np.clip(o, -args.clip_obs, args.clip_obs)NEWLINE g_clip = np.clip(g, -args.clip_obs, args.clip_obs)NEWLINE o_norm = np.clip((o_clip - o_mean) / (o_std), -args.clip_range, args.clip_range)NEWLINE g_norm = np.clip((g_clip - g_mean) / (g_std), -args.clip_range, args.clip_range)NEWLINE inputs = np.concatenate([o_norm, g_norm])NEWLINE inputs = torch.tensor(inputs, dtype=torch.float32)NEWLINE return inputsNEWLINENEWLINENEWLINENEWLINEdef train(rank, args, shared_model, counter, lock, optimizer=None):NEWLINE NEWLINE args2 = get_args()NEWLINE # load the model paramNEWLINE model_path_approach = args2.save_dir + args2.env_name + '/approach.pt'NEWLINE o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, model_approach = torch.load(model_path_approach, map_location=lambda storage, loc: storage)NEWLINE model_path_manipulate = args2.save_dir + args2.env_name + '/manipulate.pt'NEWLINE o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, model_manipulate = torch.load(model_path_manipulate, map_location=lambda storage, loc: storage)NEWLINE model_path_retract = args2.save_dir + args2.env_name + '/retract.pt'NEWLINE o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, model_retract = torch.load(model_path_retract, map_location=lambda storage, loc: storage)NEWLINENEWLINE FloatTensor = torch.cuda.FloatTensor if args.use_cuda else torch.FloatTensorNEWLINE NEWLINE env = gym.make("FetchPickAndPlace-v1")NEWLINE env2 = gym.wrappers.FlattenDictWrapper(env, dict_keys=['observation', 'desired_goal'])NEWLINE observation = env.reset()NEWLINENEWLINE env_params = {'obs': observation['observation'].shape[0], NEWLINE 'goal': observation['desired_goal'].shape[0], NEWLINE 'action': env.action_space.shape[0], NEWLINE 'action_max': env.action_space.high[0],NEWLINE }NEWLINE hlc = Actor()NEWLINE # create the actor networkNEWLINE actor_network_approach = actor(env_params)NEWLINE actor_network_approach.load_state_dict(model_approach)NEWLINE actor_network_approach.eval()NEWLINE actor_network_manipulate = actor(env_params)NEWLINE actor_network_manipulate.load_state_dict(model_manipulate)NEWLINE actor_network_manipulate.eval()NEWLINE actor_network_retract = actor(env_params)NEWLINE actor_network_retract.load_state_dict(model_retract)NEWLINE actor_network_retract.eval()NEWLINENEWLINE if args.use_cuda:NEWLINE hlc.cuda()NEWLINENEWLINENEWLINE NEWLINE for p in hlc.fc1.parameters():NEWLINE p.requires_grad = FalseNEWLINE for p in hlc.fc2.parameters():NEWLINE p.requires_grad = FalseNEWLINE NEWLINE if optimizer is None:NEWLINE optimizer = optim.Adam(shared_model.parameters(), lr=args.lr)NEWLINE NEWLINE hlc.train()NEWLINE NEWLINE done = True NEWLINE for num_iter in count():NEWLINE with lock:NEWLINE counter.value += 1NEWLINE #print(num_iter, counter.value)NEWLINE observation = env.reset()NEWLINE NEWLINE goal = observation['desired_goal']NEWLINE objectPos = observation['observation'][3:6]NEWLINE object_rel_pos = observation['observation'][6:9]NEWLINE object_oriented_goal = object_rel_pos.copy()NEWLINE object_oriented_goal[2] += 0.03 # first make the gripper go slightly above the object NEWLINE timeStep = 0 #count the total number of timestepsNEWLINE grip_pos = -object_rel_pos + objectPosNEWLINE NEWLINE object_pos_goal = objectPos.copy()NEWLINE if grip_pos[0] > objectPos[0]:NEWLINE object_pos_goal[0] += 0.003NEWLINE else:NEWLINE object_pos_goal[0] -= 0.003NEWLINENEWLINE if grip_pos[1] > objectPos[1]:NEWLINE object_pos_goal[1] += 0.002NEWLINE else:NEWLINE object_pos_goal[1] -= 0.002NEWLINENEWLINE object_pos_goal[2] -= -0.031NEWLINENEWLINE if rank == 0:NEWLINENEWLINE if num_iter % args.save_interval == 0 and num_iter > 0:NEWLINE #print ("Saving model at :" + args.save_path) NEWLINE torch.save(shared_model.state_dict(), args.save_path1)NEWLINENEWLINE if num_iter % (args.save_interval * 2.5) == 0 and num_iter > 0 and rank == 1: # Second saver in-case first processes crashes NEWLINE #print ("Saving model for process 1 at :" + args.save_path) NEWLINE torch.save(shared_model.state_dict(), args.save_path1)NEWLINE NEWLINE hlc.load_state_dict(shared_model.state_dict())NEWLINE values, log_probs, rewards, entropies = [], [], [], []NEWLINE if done:NEWLINE cx = Variable(torch.zeros(1, 32)).type(FloatTensor)NEWLINE hx = Variable(torch.zeros(1, 32)).type(FloatTensor)NEWLINE else:NEWLINE cx = Variable(cx.data).type(FloatTensor)NEWLINE hx = Variable(hx.data).type(FloatTensor)NEWLINENEWLINE state_inp = torch.from_numpy(env2.observation(observation)).type(FloatTensor)NEWLINE #criterion = nn.MSELoss()NEWLINE value, y, (hx, cx) = hlc(state_inp, hx, cx)NEWLINE prob = F.softmax(y)NEWLINE log_prob = F.log_softmax(y, dim=-1)NEWLINE act_model = prob.max(-1, keepdim=True)[1].dataNEWLINE entropy = -(log_prob * prob).sum(-1, keepdim=True)NEWLINE log_prob = log_prob.gather(-1, Variable(act_model))NEWLINE action_out = act_model.to(torch.device("cpu"))NEWLINE #action_out = torch.tensor([[0]])NEWLINE entropies.append(entropy), log_probs.append(log_prob), values.append(value)NEWLINE #print(action_out)NEWLINE obs = observation["observation"]NEWLINE observation_new = observationNEWLINENEWLINE while np.linalg.norm(grip_pos - object_pos_goal) >= 0.031 and timeStep <= 20:NEWLINE actions = [0, 0, 0, 0]NEWLINE if action_out == 0:NEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, object_pos_goal, o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, args2)NEWLINE pi = actor_network_approach(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINENEWLINE elif action_out == 1:NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, objectPos, o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, args2)NEWLINE pi = actor_network_manipulate(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE else: NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, goal, o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, args2)NEWLINE pi = actor_network_retract(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINENEWLINE actions[3] = 0.05NEWLINE observation_new, _, _, info = env.step(actions)NEWLINE obs = observation_new["observation"]NEWLINE g = observation_new["desired_goal"]NEWLINENEWLINE objectPos_new = observation_new["observation"][3:6]NEWLINE object_rel_pos_new = observation_new["observation"][6:9]NEWLINE objectPos = objectPos_newNEWLINE grip_pos_new = -object_rel_pos_new.copy() + objectPos_new.copy()NEWLINENEWLINE grip_pos = grip_pos_newNEWLINE object_oriented_goal = object_rel_pos_newNEWLINE NEWLINE timeStep += 1NEWLINE state_inp = torch.from_numpy(env2.observation(observation_new)).type(FloatTensor)NEWLINE if timeStep >= 21: NEWLINE breakNEWLINE NEWLINE NEWLINE reward = torch.Tensor([-1.0]).type(FloatTensor)NEWLINE rewards.append(reward)NEWLINE NEWLINE value, y, (hx, cx) = hlc(state_inp, hx, cx)NEWLINE prob = F.softmax(y)NEWLINE log_prob = F.log_softmax(y, dim=-1)NEWLINE act_model = prob.max(-1, keepdim=True)[1].dataNEWLINE entropy = -(log_prob * prob).sum(-1, keepdim=True)NEWLINE log_prob = log_prob.gather(-1, Variable(act_model))NEWLINE action_out = act_model.to(torch.device("cpu"))NEWLINE entropies.append(entropy), log_probs.append(log_prob), values.append(value)NEWLINE #action_out = torch.tensor([[1]])NEWLINENEWLINE NEWLINE while np.linalg.norm(grip_pos - objectPos) >= 0.015 and timeStep < env._max_episode_steps:NEWLINE actions = [0, 0, 0, 0]NEWLINE if action_out == 0:NEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, object_pos_goal, o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, args2)NEWLINE pi = actor_network_approach(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINENEWLINE elif action_out == 1:NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, objectPos, o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, args2)NEWLINE pi = actor_network_manipulate(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE else: NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, goal, o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, args2)NEWLINE pi = actor_network_retract(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE actions[3] = -0.01NEWLINE NEWLINE observation_new, _, _, info = env.step(actions)NEWLINE obs = observation_new["observation"]NEWLINE objectPos = observation_new["observation"][3:6]NEWLINE object_rel_pos = observation_new["observation"][6:9]NEWLINE NEWLINE grip_pos_new = -object_rel_pos + objectPosNEWLINE grip_pos = grip_pos_newNEWLINENEWLINE timeStep += 1NEWLINE state_inp = torch.from_numpy(env2.observation(observation_new)).type(FloatTensor)NEWLINE if timeStep >= env._max_episode_steps: NEWLINE breakNEWLINE NEWLINE NEWLINE reward = torch.Tensor([-1.0]).type(FloatTensor)NEWLINE rewards.append(reward)NEWLINENEWLINE value, y, (hx, cx) = hlc(state_inp, hx, cx)NEWLINE prob = F.softmax(y)NEWLINE log_prob = F.log_softmax(y, dim=-1)NEWLINE act_model = prob.max(-1, keepdim=True)[1].dataNEWLINE entropy = -(log_prob * prob).sum(-1, keepdim=True)NEWLINE log_prob = log_prob.gather(-1, Variable(act_model))NEWLINE action_out = act_model.to(torch.device("cpu"))NEWLINE entropies.append(entropy), log_probs.append(log_prob), values.append(value)NEWLINE #action_out = torch.tensor([[2]])NEWLINENEWLINE while np.linalg.norm(goal - objectPos) >= 0.01 and timeStep < env._max_episode_steps:NEWLINE actions = [0, 0, 0, 0]NEWLINE if action_out == 0:NEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, object_pos_goal, o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, args2)NEWLINE pi = actor_network_approach(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINENEWLINE elif action_out == 1:NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, objectPos, o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, args2)NEWLINE pi = actor_network_manipulate(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE else: NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, goal, o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, args2)NEWLINE pi = actor_network_retract(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE actions[3] = -0.01NEWLINENEWLINE # put actions into the environmentNEWLINE observation_new, _, _, info = env.step(actions)NEWLINE obs = observation_new['observation']NEWLINE #inputs = process_inputs(obs, g, o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, args)NEWLINE timeStep += 1NEWLINE state_inp = torch.from_numpy(env2.observation(observation_new)).type(FloatTensor)NEWLINE objectPos = observation_new['observation'][3:6]NEWLINE object_rel_pos = observation_new['observation'][6:9]NEWLINE if timeStep >= env._max_episode_steps: NEWLINE breakNEWLINENEWLINE while True: #limit the number of timesteps in the episode to a fixed durationNEWLINE #env.render()NEWLINE action = [0, 0, 0, 0]NEWLINE action[3] = -0.01 # keep the gripper closedNEWLINENEWLINE obsDataNew, reward, done, info = env.step(action)NEWLINE timeStep += 1NEWLINENEWLINE objectPos = obsDataNew['observation'][3:6]NEWLINE object_rel_pos = obsDataNew['observation'][6:9]NEWLINENEWLINE if timeStep >= env._max_episode_steps: breakNEWLINE NEWLINE if info['is_success'] == 1.0:NEWLINE reward = torch.Tensor([10.0]).type(FloatTensor)NEWLINE else:NEWLINE reward = torch.Tensor([-1.0]).type(FloatTensor)NEWLINE rewards.append(reward)NEWLINE NEWLINE R = torch.zeros(1, 1)NEWLINE values.append(Variable(R).type(FloatTensor))NEWLINE policy_loss = 0NEWLINE value_loss = 0NEWLINE R = Variable(R).type(FloatTensor)NEWLINE gae = torch.zeros(1, 1).type(FloatTensor)NEWLINENEWLINE for i in reversed(range(len(rewards))):NEWLINE R = args.gamma * R + rewards[i]NEWLINE advantage = R - values[i]NEWLINE value_loss = value_loss + 0.5 * advantage.pow(2)NEWLINENEWLINE delta_t = rewards[i] + args.gamma * values[i + 1].data - values[i].dataNEWLINE gae = gae * args.gamma * args.tau + delta_tNEWLINENEWLINE policy_loss = policy_loss - log_probs[i] * Variable(gae).type(FloatTensor)NEWLINENEWLINE total_loss = policy_loss + args.value_loss_coef * value_lossNEWLINE optimizer.zero_grad()NEWLINENEWLINE (total_loss).backward(retain_graph=True)NEWLINE torch.nn.utils.clip_grad_norm_(hlc.parameters(), args.max_grad_norm)NEWLINENEWLINE ensure_shared_grads(hlc, shared_model)NEWLINE optimizer.step()NEWLINENEWLINEdef test(rank, args, shared_model, counter):NEWLINE NEWLINE args2 = get_args()NEWLINE # load the model paramNEWLINE model_path_approach = args2.save_dir + args2.env_name + '/approach.pt'NEWLINE o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, model_approach = torch.load(model_path_approach, map_location=lambda storage, loc: storage)NEWLINE model_path_manipulate = args2.save_dir + args2.env_name + '/manipulate.pt'NEWLINE o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, model_manipulate = torch.load(model_path_manipulate, map_location=lambda storage, loc: storage)NEWLINE model_path_retract = args2.save_dir + args2.env_name + '/retract.pt'NEWLINE o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, model_retract = torch.load(model_path_retract, map_location=lambda storage, loc: storage)NEWLINENEWLINE FloatTensor = torch.cuda.FloatTensor if args.use_cuda else torch.FloatTensorNEWLINE NEWLINE env = gym.make("FetchPickAndPlace-v1")NEWLINE env2 = gym.wrappers.FlattenDictWrapper(env, dict_keys=['observation', 'desired_goal'])NEWLINE observation = env.reset()NEWLINENEWLINE env_params = {'obs': observation['observation'].shape[0], NEWLINE 'goal': observation['desired_goal'].shape[0], NEWLINE 'action': env.action_space.shape[0], NEWLINE 'action_max': env.action_space.high[0],NEWLINE }NEWLINE hlc = Actor()NEWLINE # create the actor networkNEWLINE actor_network_approach = actor(env_params)NEWLINE actor_network_approach.load_state_dict(model_approach)NEWLINE actor_network_approach.eval()NEWLINE actor_network_manipulate = actor(env_params)NEWLINE actor_network_manipulate.load_state_dict(model_manipulate)NEWLINE actor_network_manipulate.eval()NEWLINE actor_network_retract = actor(env_params)NEWLINE actor_network_retract.load_state_dict(model_retract)NEWLINE actor_network_retract.eval()NEWLINE if args.use_cuda:NEWLINE hlc.cuda()NEWLINE NEWLINE done = True NEWLINENEWLINE savefile = os.getcwd() + '/train/mario_curves.csv'NEWLINE title = ['No. episodes', 'No. of success']NEWLINE with open(savefile, 'a', newline='') as sfile:NEWLINE writer = csv.writer(sfile)NEWLINE writer.writerow(title) NEWLINENEWLINE hlc.eval()NEWLINE while True:NEWLINE hlc.load_state_dict(shared_model.state_dict())NEWLINE hlc.eval()NEWLINE ep_num = 0NEWLINE success = 0NEWLINE num_ep = counter.valueNEWLINE while ep_num < 50:NEWLINE ep_num +=1NEWLINE observation = env.reset() NEWLINE #lastObs = observationNEWLINE goal = observation['desired_goal']NEWLINE objectPos = observation['observation'][3:6]NEWLINE object_rel_pos = observation['observation'][6:9]NEWLINE object_oriented_goal = object_rel_pos.copy()NEWLINE object_oriented_goal[2] += 0.03 # first make the gripper go slightly above the object NEWLINE timeStep = 0NEWLINE grip_pos = -object_rel_pos + objectPosNEWLINE NEWLINE object_pos_goal = objectPos.copy()NEWLINE if grip_pos[0] > objectPos[0]:NEWLINE object_pos_goal[0] += 0.003NEWLINE else:NEWLINE object_pos_goal[0] -= 0.003NEWLINENEWLINE if grip_pos[1] > objectPos[1]:NEWLINE object_pos_goal[1] += 0.002NEWLINE else:NEWLINE object_pos_goal[1] -= 0.002NEWLINENEWLINE object_pos_goal[2] -= -0.031NEWLINENEWLINE if done:NEWLINE cx = Variable(torch.zeros(1, 32)).type(FloatTensor)NEWLINE hx = Variable(torch.zeros(1, 32)).type(FloatTensor)NEWLINE else:NEWLINE cx = Variable(cx.data).type(FloatTensor)NEWLINE hx = Variable(hx.data).type(FloatTensor)NEWLINENEWLINE state_inp = torch.from_numpy(env2.observation(observation)).type(FloatTensor)NEWLINE value, y, (hx, cx) = hlc(state_inp, hx, cx)NEWLINE prob = F.softmax(y)NEWLINE act_model = prob.max(-1, keepdim=True)[1].dataNEWLINE action_out = act_model.to(torch.device("cpu"))NEWLINENEWLINENEWLINE #print('action_out before approach:', action_out)NEWLINE obs = observation["observation"]NEWLINE while np.linalg.norm(grip_pos - object_pos_goal) >= 0.031 and timeStep <= 20:NEWLINE #env.render()NEWLINE actions = [0, 0, 0, 0]NEWLINE if action_out == 0:NEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, object_pos_goal, o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, args2)NEWLINE pi = actor_network_approach(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINENEWLINE elif action_out == 1:NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, objectPos, o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, args2)NEWLINE pi = actor_network_manipulate(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE else: NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, goal, o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, args2)NEWLINE pi = actor_network_retract(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINENEWLINE actions[3] = 0.05NEWLINENEWLINE observation_new, _, _, info = env.step(actions)NEWLINE obs = observation_new["observation"]NEWLINE g = observation_new["desired_goal"]NEWLINENEWLINE objectPos_new = observation_new["observation"][3:6]NEWLINE object_rel_pos_new = observation_new["observation"][6:9]NEWLINE objectPos = objectPos_newNEWLINE grip_pos_new = -object_rel_pos_new + objectPos_newNEWLINENEWLINE grip_pos = grip_pos_newNEWLINE object_oriented_goal = object_rel_pos_newNEWLINE NEWLINE #print('timestep: {},reward eval: {}'.format(timeStep, reward))NEWLINE timeStep += 1NEWLINE state_inp = torch.from_numpy(env2.observation(observation_new)).type(FloatTensor)NEWLINE NEWLINE NEWLINENEWLINE value, y, (hx, cx) = hlc(state_inp, hx, cx)NEWLINE prob = F.softmax(y)NEWLINE act_model = prob.max(-1, keepdim=True)[1].dataNEWLINE action_out = act_model.to(torch.device("cpu"))NEWLINE NEWLINE while np.linalg.norm(grip_pos - objectPos) >= 0.015 and timeStep < env._max_episode_steps:NEWLINE #env.render()NEWLINE actions = [0, 0, 0, 0]NEWLINE if action_out == 0:NEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, object_pos_goal, o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, args2)NEWLINE pi = actor_network_approach(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINENEWLINE elif action_out == 1:NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, objectPos, o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, args2)NEWLINE pi = actor_network_manipulate(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE else: NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, goal, o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, args2)NEWLINE pi = actor_network_retract(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE NEWLINE actions[3] = -0.01NEWLINE NEWLINE observation_new, _, _, info = env.step(actions)NEWLINE obs = observation_new["observation"]NEWLINE objectPos = observation_new["observation"][3:6]NEWLINE object_rel_pos = observation_new["observation"][6:9]NEWLINE NEWLINE grip_pos_new = -object_rel_pos + objectPosNEWLINE grip_pos = grip_pos_newNEWLINENEWLINE timeStep += 1NEWLINE state_inp = torch.from_numpy(env2.observation(observation_new)).type(FloatTensor)NEWLINE if timeStep >= env._max_episode_steps: NEWLINE breakNEWLINE NEWLINE value, y, (hx, cx) = hlc(state_inp, hx, cx)NEWLINE prob = F.softmax(y) NEWLINE act_model = prob.max(-1, keepdim=True)[1].data NEWLINE action_out = act_model.to(torch.device("cpu"))NEWLINE NEWLINE NEWLINE while np.linalg.norm(goal - objectPos) >= 0.01 and timeStep < env._max_episode_steps:NEWLINE #env.render()NEWLINE actions = [0, 0, 0, 0]NEWLINE if action_out == 0:NEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, object_pos_goal, o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, args2)NEWLINE pi = actor_network_approach(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINENEWLINE elif action_out == 1:NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, objectPos, o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, args2)NEWLINE pi = actor_network_manipulate(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE else: NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, goal, o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, args2)NEWLINE pi = actor_network_retract(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE actions[3] = -0.01NEWLINENEWLINE # put actions into the environmentNEWLINE observation_new, _, _, info = env.step(actions)NEWLINE obs = observation_new['observation']NEWLINE NEWLINE timeStep += 1NEWLINE state_inp = torch.from_numpy(env2.observation(observation_new)).type(FloatTensor)NEWLINE objectPos = observation_new['observation'][3:6]NEWLINE object_rel_pos = observation_new['observation'][6:9]NEWLINE if timeStep >= env._max_episode_steps: NEWLINE breakNEWLINE NEWLINE while True: #limit the number of timesteps in the episode to a fixed durationNEWLINE #env.render()NEWLINE action = [0, 0, 0, 0]NEWLINE action[3] = -0.01 # keep the gripper closedNEWLINENEWLINE obsDataNew, reward, done, info = env.step(action)NEWLINE timeStep += 1NEWLINENEWLINE objectPos = obsDataNew['observation'][3:6]NEWLINE object_rel_pos = obsDataNew['observation'][6:9]NEWLINE if timeStep >= env._max_episode_steps: breakNEWLINE NEWLINE if info['is_success'] == 1.0:NEWLINE success +=1NEWLINE NEWLINE if ep_num % 49==0: NEWLINE print("num episodes {}, success {}".format(num_ep, success*2))NEWLINE data = [counter.value, success*2]NEWLINE with open(savefile, 'a', newline='') as sfile:NEWLINE writer = csv.writer(sfile)NEWLINE writer.writerows([data])NEWLINE #time.sleep(15)NEWLINE import pytestNEWLINEimport mockNEWLINEimport jsonNEWLINEfrom functools import wrapsNEWLINEfrom unittest.mock import patchNEWLINENEWLINEfrom app import storageNEWLINEfrom data.registry_model.blobuploader import upload_blob, BlobUploadSettingsNEWLINEfrom image.docker.schema2.manifest import DockerSchema2ManifestBuilderNEWLINEfrom data.registry_model import registry_modelNEWLINEfrom data.registry_model.datatypes import RepositoryReferenceNEWLINEfrom data.model.test.test_repo_mirroring import create_mirror_repo_robotNEWLINEfrom data.model.user import retrieve_robot_tokenNEWLINEfrom data.database import Manifest, RepoMirrorConfig, RepoMirrorStatusNEWLINENEWLINEfrom workers.repomirrorworker import delete_obsolete_tagsNEWLINEfrom workers.repomirrorworker.repomirrorworker import RepoMirrorWorkerNEWLINEfrom io import BytesIONEWLINEfrom util.repomirror.skopeomirror import SkopeoResults, SkopeoMirrorNEWLINENEWLINEfrom test.fixtures import *NEWLINENEWLINENEWLINEdef disable_existing_mirrors(func):NEWLINE @wraps(func)NEWLINE def wrapper(*args, **kwargs):NEWLINE for mirror in RepoMirrorConfig.select():NEWLINE mirror.is_enabled = FalseNEWLINE mirror.save()NEWLINENEWLINE func(*args, **kwargs)NEWLINENEWLINE for mirror in RepoMirrorConfig.select():NEWLINE mirror.is_enabled = TrueNEWLINE mirror.save()NEWLINENEWLINE return wrapperNEWLINENEWLINENEWLINEdef _create_tag(repo, name):NEWLINE repo_ref = RepositoryReference.for_repo_obj(repo)NEWLINENEWLINE with upload_blob(repo_ref, storage, BlobUploadSettings(500, 500)) as upload:NEWLINE app_config = {"TESTING": True}NEWLINE config_json = json.dumps(NEWLINE {NEWLINE "config": {NEWLINE "author": "Repo Mirror",NEWLINE },NEWLINE "rootfs": {"type": "layers", "diff_ids": []},NEWLINE "history": [NEWLINE {NEWLINE "created": "2019-07-30T18:37:09.284840891Z",NEWLINE "created_by": "base",NEWLINE "author": "Repo Mirror",NEWLINE },NEWLINE ],NEWLINE }NEWLINE )NEWLINE upload.upload_chunk(app_config, BytesIO(config_json.encode("utf-8")))NEWLINE blob = upload.commit_to_blob(app_config)NEWLINE assert blobNEWLINENEWLINE builder = DockerSchema2ManifestBuilder()NEWLINE builder.set_config_digest(blob.digest, blob.compressed_size)NEWLINE builder.add_layer("sha256:abcd", 1234, urls=["http://hello/world"])NEWLINE manifest = builder.build()NEWLINENEWLINE manifest, tag = registry_model.create_manifest_and_retarget_tag(NEWLINE repo_ref, manifest, name, storage, raise_on_error=TrueNEWLINE )NEWLINE assert tagNEWLINE assert tag.name == nameNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_successful_mirror(run_skopeo_mock, initialized_db, app):NEWLINE """NEWLINE Basic test of successful mirror.NEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(NEWLINE ["latest", "7.1"], external_registry_config={"verify_tls": False}NEWLINE )NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=False",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], '{"RepoTags": ["latest"]}', ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=False",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE "docker://localhost:5000/mirror/repo:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "stdout", "stderr"),NEWLINE },NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINENEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_mirror_unsigned_images(run_skopeo_mock, initialized_db, app):NEWLINE """NEWLINE Test whether the insecure-policy option is added when a repository is passed with unsigned_images.NEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(NEWLINE ["latest"], external_registry_config={"verify_tls": False, "unsigned_images": True}NEWLINE )NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=False",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], '{"RepoTags": ["latest"]}', ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "--insecure-policy",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=False",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE "docker://localhost:5000/mirror/repo:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "stdout", "stderr"),NEWLINE },NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINENEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_successful_disabled_sync_now(run_skopeo_mock, initialized_db, app):NEWLINE """NEWLINE Disabled mirrors still allow "sync now".NEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(["latest", "7.1"])NEWLINE mirror.is_enabled = FalseNEWLINE mirror.sync_status = RepoMirrorStatus.SYNC_NOWNEWLINE mirror.save()NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], '{"RepoTags": ["latest"]}', ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE "docker://localhost:5000/mirror/repo:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "stdout", "stderr"),NEWLINE },NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINENEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_successful_mirror_verbose_logs(run_skopeo_mock, initialized_db, app, monkeypatch):NEWLINE """NEWLINE Basic test of successful mirror with verbose logs turned on.NEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(["latest", "7.1"])NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "--debug",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], '{"RepoTags": ["latest"]}', ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "--debug",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE "docker://localhost:5000/mirror/repo:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "Success", ""),NEWLINE },NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINENEWLINE monkeypatch.setenv("DEBUGLOG", "true")NEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINE@mock.patch("workers.repomirrorworker.retarget_tag")NEWLINE@mock.patch("workers.repomirrorworker.delete_tag")NEWLINEdef test_rollback(delete_tag_mock, retarget_tag_mock, run_skopeo_mock, initialized_db, app):NEWLINE """NEWLINE Tags in the repo:NEWLINENEWLINE "updated" - this tag will be updated during the mirrorNEWLINE "removed" - this tag will be removed during the mirrorNEWLINE "created" - this tag will be created during the mirrorNEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(["updated", "created", "zzerror"])NEWLINE _create_tag(repo, "updated")NEWLINE _create_tag(repo, "deleted")NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:updated",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE True, [], '{"RepoTags": ["latest", "zzerror", "created", "updated"]}', ""NEWLINE ),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:created",NEWLINE "docker://localhost:5000/mirror/repo:created",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "Success", ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:updated",NEWLINE "docker://localhost:5000/mirror/repo:updated",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "Success", ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:zzerror",NEWLINE "docker://localhost:5000/mirror/repo:zzerror",NEWLINE ],NEWLINE "results": SkopeoResults(False, [], "", "ERROR"),NEWLINE },NEWLINE ]NEWLINENEWLINE retarget_tag_calls = [NEWLINE "updated",NEWLINE ]NEWLINENEWLINE delete_tag_calls = [NEWLINE "deleted",NEWLINE "updated",NEWLINE "created",NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE if args[1] == "copy" and args[8].endswith(":updated"):NEWLINE _create_tag(repo, "updated")NEWLINE elif args[1] == "copy" and args[8].endswith(":created"):NEWLINE _create_tag(repo, "created")NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE def retarget_tag_test(name, manifest, is_reversion=False):NEWLINE assert retarget_tag_calls.pop(0) == nameNEWLINE assert is_reversionNEWLINENEWLINE def delete_tag_test(repository_id, tag_name):NEWLINE assert delete_tag_calls.pop(0) == tag_nameNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINE retarget_tag_mock.side_effect = retarget_tag_testNEWLINE delete_tag_mock.side_effect = delete_tag_testNEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINE assert [] == retarget_tag_callsNEWLINE assert [] == delete_tag_callsNEWLINENEWLINENEWLINEdef test_remove_obsolete_tags(initialized_db):NEWLINE """NEWLINE As part of the mirror, the set of tags on the remote repository is compared to the localNEWLINE existing tags.NEWLINENEWLINE Those not present on the remote are removed locally.NEWLINE """NEWLINENEWLINE mirror, repository = create_mirror_repo_robot(["updated", "created"], repo_name="removed")NEWLINENEWLINE _create_tag(repository, "oldtag")NEWLINENEWLINE incoming_tags = ["one", "two"]NEWLINE deleted_tags = delete_obsolete_tags(mirror, incoming_tags)NEWLINENEWLINE assert [tag.name for tag in deleted_tags] == ["oldtag"]NEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_mirror_config_server_hostname(run_skopeo_mock, initialized_db, app, monkeypatch):NEWLINE """NEWLINE Set REPO_MIRROR_SERVER_HOSTNAME to override SERVER_HOSTNAME config.NEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(["latest", "7.1"])NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "--debug",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], '{"RepoTags": ["latest"]}', ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "--debug",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE "docker://config_server_hostname/mirror/repo:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "Success", ""),NEWLINE },NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINENEWLINE monkeypatch.setenv("DEBUGLOG", "true")NEWLINE with patch.dict(NEWLINE "data.model.config.app_config", {"REPO_MIRROR_SERVER_HOSTNAME": "config_server_hostname"}NEWLINE ):NEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_quote_params(run_skopeo_mock, initialized_db, app):NEWLINE """NEWLINE Basic test of successful mirror.NEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(["latest", "7.1"])NEWLINE mirror.external_reference = "& rm -rf /;/namespace/repository"NEWLINE mirror.external_registry_username = "`rm -rf /`"NEWLINE mirror.save()NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "--creds",NEWLINE "`rm -rf /`",NEWLINE "'docker://& rm -rf /;/namespace/repository:latest'",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], '{"RepoTags": ["latest"]}', ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "--src-creds",NEWLINE "`rm -rf /`",NEWLINE "'docker://& rm -rf /;/namespace/repository:latest'",NEWLINE "docker://localhost:5000/mirror/repo:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "stdout", "stderr"),NEWLINE },NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINENEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_quote_params_password(run_skopeo_mock, initialized_db, app):NEWLINE """NEWLINE Basic test of successful mirror.NEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(["latest", "7.1"])NEWLINE mirror.external_reference = "& rm -rf /;/namespace/repository"NEWLINE mirror.external_registry_username = "`rm -rf /`"NEWLINE mirror.external_registry_password = '""$PATH\\"'NEWLINE mirror.save()NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "--creds",NEWLINE '`rm -rf /`:""$PATH\\"',NEWLINE "'docker://& rm -rf /;/namespace/repository:latest'",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], '{"RepoTags": ["latest"]}', ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "--src-creds",NEWLINE '`rm -rf /`:""$PATH\\"',NEWLINE "'docker://& rm -rf /;/namespace/repository:latest'",NEWLINE "docker://localhost:5000/mirror/repo:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "stdout", "stderr"),NEWLINE },NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINENEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_inspect_error_mirror(run_skopeo_mock, initialized_db, app):NEWLINE """NEWLINE Test for no tag for skopeo inspect.NEWLINENEWLINE The mirror is processed four times, asserting that the remaining syncs decrement until next syncNEWLINE is bumped to the future, confirming the fourth is never processed.NEWLINE """NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINE worker = RepoMirrorWorker()NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(["7.1"])NEWLINENEWLINE # Call number 1NEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:7.1",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest 7.1 in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest latest in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE ]NEWLINE worker._process_mirrors()NEWLINE mirror = RepoMirrorConfig.get_by_id(mirror.id)NEWLINE assert [] == skopeo_callsNEWLINE assert 2 == mirror.sync_retries_remainingNEWLINENEWLINE # Call number 2NEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:7.1",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest 7.1 in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest latest in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE ]NEWLINE worker._process_mirrors()NEWLINE mirror = RepoMirrorConfig.get_by_id(mirror.id)NEWLINE assert [] == skopeo_callsNEWLINE assert 1 == mirror.sync_retries_remainingNEWLINENEWLINE # Call number 3NEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:7.1",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest 7.1 in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest latest in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE ]NEWLINE worker._process_mirrors()NEWLINE mirror = RepoMirrorConfig.get_by_id(mirror.id)NEWLINE assert [] == skopeo_callsNEWLINE assert 3 == mirror.sync_retries_remainingNEWLINENEWLINE # Call number 4NEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:7.1",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest 7.1 in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest latest in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE ]NEWLINE worker._process_mirrors()NEWLINE mirror = RepoMirrorConfig.get_by_id(mirror.id)NEWLINE assert 2 == len(skopeo_calls)NEWLINE assert 3 == mirror.sync_retries_remainingNEWLINE # (C) Copyright Artificial Brain 2021.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINENEWLINEfrom quantumcat.gates.custom_gates.braket.u_gate import UGateNEWLINEfrom quantumcat.gates.custom_gates.braket.u1_gate import U1GateNEWLINEfrom quantumcat.gates.custom_gates.braket.u2_gate import U2GateNEWLINEfrom quantumcat.gates.custom_gates.braket.u3_gate import U3GateNEWLINEfrom quantumcat.gates.custom_gates.braket.cu_gate import CUGateNEWLINEfrom quantumcat.gates.custom_gates.braket.ch_gate import CHGateNEWLINEfrom quantumcat.gates.custom_gates.braket.crx_gate import CRXGateNEWLINEfrom quantumcat.gates.custom_gates.braket.r_gate import RGateNEWLINEfrom quantumcat.gates.custom_gates.braket.cry_gate import CRYGateNEWLINEfrom quantumcat.gates.custom_gates.braket.crz_gate import CRZGateNEWLINEfrom quantumcat.gates.custom_gates.braket.csx_gate import CSXGateNEWLINEfrom quantumcat.gates.custom_gates.braket.cu1_gate import CU1GateNEWLINEfrom quantumcat.gates.custom_gates.braket.dcx_gate import DCXGateNEWLINEfrom quantumcat.gates.custom_gates.braket.rc3x_gate import RC3XGateNEWLINEfrom quantumcat.gates.custom_gates.braket.rccx_gate import RCCXGateNEWLINEfrom quantumcat.gates.custom_gates.braket.rzx_gate import RZXGateNEWLINEfrom quantumcat.gates.custom_gates.braket.cu3_gate import CU3GateNEWLINE """NEWLINEUnionFind.pyNEWLINENEWLINESource: http://www.ics.uci.edu/~eppstein/PADS/UnionFind.pyNEWLINENEWLINEUnion-find data structure. Based on Josiah Carlson's code,NEWLINEhttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/215912NEWLINEwith significant additional changes by D. Eppstein.NEWLINE"""NEWLINENEWLINEfrom collections import defaultdictNEWLINENEWLINENEWLINEclass UnionFind(object):NEWLINE """Union-find data structure.NEWLINENEWLINE Each unionFind instance X maintains a family of disjoint sets ofNEWLINE hashable objects, supporting the following two methods:NEWLINENEWLINE - X[item] returns a name for the set containing the given item.NEWLINE Each set is named by an arbitrarily-chosen one of its members; asNEWLINE long as the set remains unchanged it will keep the same name. IfNEWLINE the item is not yet part of a set in X, a new singleton set isNEWLINE created for it.NEWLINENEWLINE - X.union(item1, item2, ...) merges the sets containing each itemNEWLINE into a single larger set. If any item is not yet part of a setNEWLINE in X, it is added to X as one of the members of the merged set.NEWLINE """NEWLINENEWLINE def __init__(self):NEWLINE """Create a new empty union-find structure."""NEWLINE self.weights = {}NEWLINE self.parents = {}NEWLINENEWLINE def __getitem__(self, object):NEWLINE """Find and return the name of the set containing the object."""NEWLINE # check for previously unknown objectNEWLINE if object not in self.parents:NEWLINE self.parents[object] = objectNEWLINE self.weights[object] = 1NEWLINE return objectNEWLINENEWLINE # find path of objects leading to the rootNEWLINE path = [object]NEWLINE root = self.parents[object]NEWLINE while root != path[-1]:NEWLINE path.append(root)NEWLINE root = self.parents[root]NEWLINENEWLINE # compress the path and returnNEWLINE for ancestor in path:NEWLINE self.parents[ancestor] = rootNEWLINE return rootNEWLINENEWLINE def __iter__(self):NEWLINE """Iterate through all items ever found or unioned by this structure."""NEWLINE return iter(self.parents)NEWLINENEWLINE def union(self, *objects):NEWLINE """Find the sets containing the objects and merge them all."""NEWLINE roots = [self[x] for x in objects]NEWLINE heaviest = max([(self.weights[r],r) for r in roots])[1]NEWLINE for r in roots:NEWLINE if r != heaviest:NEWLINE self.weights[heaviest] += self.weights[r]NEWLINE self.parents[r] = heaviestNEWLINENEWLINE def sets(self):NEWLINE """Return a list of each disjoint set"""NEWLINE ret = defaultdict(list)NEWLINE for k, _ in self.parents.iteritems():NEWLINE ret[self[k]].append(k)NEWLINE return ret.values()NEWLINENEWLINE NEWLINEif __name__ == '__main__':NEWLINENEWLINE # testNEWLINE uf = UnionFind()NEWLINE uf.union(0, 1)NEWLINE uf.union(2, 3)NEWLINE uf.union(3, 0)NEWLINE assert uf.sets() == [[0, 1, 2, 3]]NEWLINE """This test creates two top level actors and one sub-actor andNEWLINE verifies that the actors can exchange sequences of messages."""NEWLINENEWLINEimport timeNEWLINEfrom thespian.actors import *NEWLINEfrom thespian.test import *NEWLINENEWLINEclass rosaline(Actor):NEWLINE name = 'Rosaline'NEWLINENEWLINEclass Romeo(Actor):NEWLINE def receiveMessage(self, msg, sender):NEWLINE if isinstance(msg, JulietAppears):NEWLINE self.send(msg.juliet, "But, soft! what light through yonder window breaks?")NEWLINE elif isinstance(msg, ActorExitRequest):NEWLINE pass # nothing special, just dieNEWLINE elif msg == 'Ay me!':NEWLINE self.send(sender, 'She speaks!')NEWLINE elif msg == 'O Romeo, Romeo! wherefore art thou Romeo?':NEWLINE self.send(sender, 'Shall I hear more, or shall I speak at this?')NEWLINE elif 'rose' in msg:NEWLINE pass # wait for itNEWLINE elif 'sweet' in msg:NEWLINE self.send(sender, 'Like softest music to attending ears!')NEWLINE elif 'hello' in msg:NEWLINE print('Hello from %s'%(str(self)))NEWLINE elif 'who_are_you' == msg:NEWLINE self.send(sender, self.myAddress)NEWLINE # otherwise sit and swoonNEWLINENEWLINENEWLINEclass Capulet(Actor):NEWLINE def receiveMessage(self, msg, sender):NEWLINE if msg == "has a daughter?":NEWLINE self.send(sender, self.createActor(Juliet))NEWLINENEWLINENEWLINEclass Juliet(Actor):NEWLINE def __init__(self, *args, **kw):NEWLINE self.nurse = NoneNEWLINE self.recalled = FalseNEWLINE super(Juliet, self).__init__(*args, **kw)NEWLINE def receiveMessage(self, msg, sender):NEWLINE if isinstance(msg, ActorExitRequest):NEWLINE pass # nothing special, just dieNEWLINE elif "what light" in msg:NEWLINE self.send(sender, 'Ay me!')NEWLINE elif msg == 'She speaks!':NEWLINE self.send(sender, 'O Romeo, Romeo! wherefore art thou Romeo?')NEWLINE elif msg == 'Shall I hear more, or shall I speak at this?':NEWLINE self.send(sender, "What's in a name? That which we call a rose")NEWLINE self.send(sender, "By any other name would smell as sweet")NEWLINE elif msg == 'Like softest music to attending ears!':NEWLINE if self.nurse:NEWLINE self.send(self.nurse, 'Anon, good nurse!')NEWLINE else:NEWLINE self.recalled = TrueNEWLINE elif msg == 'Mistress!':NEWLINE self.nurse = senderNEWLINE if self.recalled:NEWLINE self.send(self.nurse, 'Anon, good nurse!')NEWLINE elif 'who_are_you' == msg:NEWLINE self.send(sender, self.myAddress)NEWLINENEWLINENEWLINEclass Nurse(Actor):NEWLINE def __init__(self, *args, **kw):NEWLINE self.heardItAll = FalseNEWLINE super(Nurse, self).__init__(*args, **kw)NEWLINE def receiveMessage(self, msg, sender):NEWLINE if type(msg) == type((1,2)) and msg[0] == 'begin':NEWLINE self.send(msg[1], JulietAppears(msg[2]))NEWLINE self.send(msg[2], 'Mistress!')NEWLINE elif msg == 'Anon, good nurse!':NEWLINE self.heardItAll = TrueNEWLINE elif msg == 'done?':NEWLINE self.send(sender, 'Fini' if self.heardItAll else 'not yet')NEWLINENEWLINENEWLINEclass JulietAppears:NEWLINE stage = 'Right'NEWLINE def __init__(self, julietAddr):NEWLINE self.juliet = julietAddrNEWLINENEWLINENEWLINEclass TestFuncActors():NEWLINENEWLINENEWLINE def test01_ActorSystemStartupShutdown(self, asys):NEWLINE rosalineA = asys.createActor(rosaline)NEWLINE # just finish, make sure no exception is thrown.NEWLINENEWLINE def test01_1_ActorSystemMultipleShutdown(self, asys):NEWLINE rosalineA = asys.createActor(rosaline)NEWLINE asys.shutdown()NEWLINE asys.shutdown()NEWLINENEWLINE def test02_PrimaryActorCreation(self, asys):NEWLINE romeo = asys.createActor(Romeo)NEWLINE juliet = asys.createActor(Juliet)NEWLINE assert romeo != julietNEWLINENEWLINE def test03_CreateActorUniqueAddress(self, asys):NEWLINE romeo = asys.createActor(Romeo)NEWLINE juliet = asys.createActor(Juliet)NEWLINE assert romeo != julietNEWLINE romeo2 = asys.createActor(Romeo)NEWLINE assert romeo != romeo2NEWLINENEWLINE def NOtest04_PossibleActorSystemResourceExhaustion(self):NEWLINE try:NEWLINE addresses = [asys.createActor(Juliet) for n in range(10000)]NEWLINE except OSError as err:NEWLINE import errnoNEWLINE if err.errno == errno.EGAIN:NEWLINE passNEWLINE else:NEWLINE raiseNEWLINENEWLINENEWLINE def test05_ManyActorsUniqueAddress(self, asys):NEWLINE addresses = [asys.createActor(Juliet) for n in range(50)]NEWLINE uniqueAddresses = []NEWLINE duplicates = []NEWLINE for A in addresses:NEWLINE if A in uniqueAddresses:NEWLINE duplicates.append(A)NEWLINE else:NEWLINE uniqueAddresses.append(A)NEWLINE if len(addresses) != len(uniqueAddresses):NEWLINE print('Duplicates: %s'%map(str, duplicates))NEWLINE if duplicates:NEWLINE for each in duplicates:NEWLINE print('... %s at: %s'%(str(each), str([N for N,A in enumerate(addresses) if A == each])))NEWLINE print('Note: if this is a UDPTransport test, be advised that Linux occasionally does seem to assign the same UDP port multiple times. Linux bug?')NEWLINE assert len(addresses) == len(uniqueAddresses)NEWLINENEWLINE def test06_ManyActorsValidAddresses(self, asys):NEWLINE import stringNEWLINE addresses = [asys.createActor(Juliet) for n in range(100)]NEWLINE for addr in addresses:NEWLINE invchar = ''.join([c for c in str(addr)NEWLINE if c not in string.ascii_letters + string.digits + "-~/():., '|>"])NEWLINE assert str(addr) == str(addr) + invchar # invchar should be blankNEWLINE if asys.base_name.startswith('multiprocUDP'):NEWLINE # Normally the asys.shutdown() following this test willNEWLINE # shutdown all actors, but for the multiprocUDP base, theNEWLINE # ActorSystem (and logger) process are left behind becauseNEWLINE # UDP does not have guaranteed delivery and 100 processesNEWLINE # sending a UDP message to the ActorSystem nearlyNEWLINE # simultaneously overloads and drops packets. Use a moreNEWLINE # regulated shutdown here for UDP to avoid this overflowNEWLINE # (which does not hurt anything but leaves actor processesNEWLINE # behind).NEWLINE per_loop = 10NEWLINE for ii in range(0, len(addresses), per_loop):NEWLINE for jj in range(ii, ii + per_loop):NEWLINE asys.tell(addresses[jj], ActorExitRequest())NEWLINE time.sleep(0.25)NEWLINENEWLINE def test07_SingleNonListeningActorTell(self, asys):NEWLINE rosalineA = asys.createActor(rosaline)NEWLINE # rosaline does not override the receiveMessage method, so theNEWLINE # Actor default method will throw an exception. This willNEWLINE # Kill the rosaline Actor. It's a top level Actor, so it willNEWLINE # not be restarted. This will cause the 'hello' message to beNEWLINE # delivered to the DeadLetterBox. Verify that no exceptionNEWLINE # makes its way out of the ActorSystem here.NEWLINE asys.tell(rosalineA, 'hello')NEWLINE assert TrueNEWLINENEWLINE def test08_SingleActorTell(self, asys):NEWLINE romeoA = asys.createActor(Romeo)NEWLINE asys.tell(romeoA, 'hello')NEWLINE # Nothing much happens, Romeo is smitten and has no time for trivialities, butNEWLINE # he will try to generate str() of himself.NEWLINENEWLINE def test09_SingleActorAsk(self, asys):NEWLINE romeoA = asys.createActor(Romeo)NEWLINE resp = asys.ask(romeoA, 'O Romeo, Romeo! wherefore art thou Romeo?', 1)NEWLINE assert resp, 'Shall I hear more == or shall I speak at this?'NEWLINENEWLINE def test10_ActorAskWithNoResponse(self, asys):NEWLINE romeoA = asys.createActor(Romeo)NEWLINE # This test is possibly unique to the simpleSystemBase, whichNEWLINE # will run an process all messages on an ask (or tell) call.NEWLINE # Properly there is no way to determine if an answer isNEWLINE # forthcoming from an asynchronous system, so all this can doNEWLINE # is assert that there is no response within a particular timeNEWLINE # period. At this point, timing is not supported, so thisNEWLINE # test is underspecified and assumptive.NEWLINE resp = asys.ask(romeoA, "What's in a name? That which we call a rose", 1.5)NEWLINE assert resp is NoneNEWLINE # Now verify that the Actor and system are still alive and operating normally.NEWLINE resp = asys.ask(romeoA, 'O Romeo, Romeo! wherefore art thou Romeo?', 1)NEWLINE assert resp, 'Shall I hear more == or shall I speak at this?'NEWLINENEWLINE def test11_SingleActorAskMultipleTimes(self, asys):NEWLINE romeoA = asys.createActor(Romeo)NEWLINE r = asys.ask(romeoA, 'O Romeo, Romeo! wherefore art thou Romeo?', 1)NEWLINE assert r == 'Shall I hear more, or shall I speak at this?'NEWLINE r = asys.ask(romeoA, 'O Romeo, Romeo! wherefore art thou Romeo?', 1)NEWLINE assert r == 'Shall I hear more, or shall I speak at this?'NEWLINE r = asys.ask(romeoA, 'Ay me!', 1)NEWLINE assert r == 'She speaks!'NEWLINE r = asys.ask(romeoA, 'O Romeo, Romeo! wherefore art thou Romeo?', 1)NEWLINE assert r == 'Shall I hear more, or shall I speak at this?'NEWLINENEWLINE def test12_MultipleActorsAskMultipleTimes(self, asys):NEWLINE romeo = asys.createActor(Romeo)NEWLINE r = asys.ask(romeo, 'O Romeo, Romeo! wherefore art thou Romeo?', 1)NEWLINE assert r == 'Shall I hear more, or shall I speak at this?'NEWLINE juliet = asys.createActor(Juliet)NEWLINE r = asys.ask(romeo, 'O Romeo, Romeo! wherefore art thou Romeo?', 1)NEWLINE assert r == 'Shall I hear more, or shall I speak at this?'NEWLINE r = asys.ask(romeo, 'Ay me!', 1)NEWLINE assert r == 'She speaks!'NEWLINE r = asys.ask(juliet, 'She speaks!', 1)NEWLINE assert r == 'O Romeo, Romeo! wherefore art thou Romeo?'NEWLINE r = asys.ask(romeo, 'Ay me!', 1)NEWLINE assert r == 'She speaks!'NEWLINE r = asys.ask(juliet, "Do you know what light that is?", 1)NEWLINE assert r == 'Ay me!'NEWLINENEWLINE def test13_SubActorCreation(self, asys):NEWLINE capulet = asys.createActor(Capulet)NEWLINE juliet = asys.ask(capulet, 'has a daughter?', 2.5)NEWLINE print ('Juliet is: %s'%str(juliet))NEWLINE assert juliet is not NoneNEWLINE if juliet:NEWLINE r = asys.ask(juliet, 'what light?')NEWLINE assert r == 'Ay me!', 0.75NEWLINE juliet2 = asys.ask(capulet, 'has a daughter?', 1)NEWLINE assert juliet2 is not NoneNEWLINE if juliet2:NEWLINE r = asys.ask(juliet2, 'what light?', 0.5)NEWLINE assert r == 'Ay me!'NEWLINE r = asys.ask(juliet, 'what light?', 0.5)NEWLINE assert r == 'Ay me!'NEWLINENEWLINE def test14_EntireActWithActorStart(self, asys):NEWLINE romeo = asys.createActor(Romeo)NEWLINE juliet = asys.createActor(Juliet)NEWLINE nurse = asys.createActor(Nurse)NEWLINE assert asys.ask(nurse, 'done?', 1) == 'not yet'NEWLINE asys.tell(nurse, ('begin', romeo, juliet))NEWLINENEWLINE for X in range(50):NEWLINE if asys.ask(nurse, 'done?', 1) == 'Fini':NEWLINE breakNEWLINE time.sleep(0.01) # Allow some time for the entire actNEWLINE r = asys.ask(nurse, 'done?', 1)NEWLINE assert r == 'Fini'NEWLINENEWLINE def test15_IncompleteActMissingActor(self, asys):NEWLINE romeo = asys.createActor(Romeo)NEWLINE juliet = asys.createActor(Juliet)NEWLINE # no nurse actor createdNEWLINE asys.tell(romeo, JulietAppears(juliet))NEWLINE # No error should occur here when Juliet reaches the end andNEWLINE # doesn't have a nurse to tell.NEWLINENEWLINE time.sleep(0.05) # Allow some time for the entire actNEWLINENEWLINE # Now create the nurse and tell her to talk to romeo andNEWLINE # juliet, which should cause completionNEWLINE nurse = asys.createActor(Nurse)NEWLINE r = asys.ask(nurse, 'done?', 1)NEWLINE assert r == 'not yet'NEWLINE asys.tell(nurse, ('begin', romeo, juliet))NEWLINENEWLINE for X in range(50):NEWLINE if asys.ask(nurse, 'done?', 1) == 'Fini':NEWLINE breakNEWLINE time.sleep(0.01) # Allow some time for the entire actNEWLINE r = asys.ask(nurse, 'done?', 1)NEWLINE assert r == 'Fini'NEWLINENEWLINE def test16_ActorProperties(self, asys):NEWLINE romeo = asys.createActor(Romeo)NEWLINE juliet = asys.createActor(Juliet)NEWLINENEWLINE r = asys.ask(romeo, 'who_are_you', 0.25)NEWLINE assert r is not NoneNEWLINE r = asys.ask(juliet, 'who_are_you', 0.25)NEWLINE assert r is not NoneNEWLINE r1 = asys.ask(romeo, 'who_are_you', 0.25)NEWLINE r2 = asys.ask(juliet, 'who_are_you', 0.25)NEWLINE assert r1 != r2NEWLINE """This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.NEWLINE"""NEWLINE"""NEWLINEDjango Base settings for Label Studio.NEWLINENEWLINEFor more information on this file, seeNEWLINEhttps://docs.djangoproject.com/en/3.1/topics/settings/NEWLINENEWLINEFor the full list of settings and their values, seeNEWLINEhttps://docs.djangoproject.com/en/3.1/ref/settings/NEWLINE"""NEWLINEimport osNEWLINEimport reNEWLINEimport loggingNEWLINENEWLINE# for printing messages before main logging config appliedNEWLINEif not logging.getLogger().hasHandlers():NEWLINE logging.basicConfig(level=logging.DEBUG, format='%(message)s')NEWLINENEWLINEfrom label_studio.core.utils.io import get_data_dirNEWLINEfrom label_studio.core.utils.params import get_bool_env, get_envNEWLINENEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINE# Hostname is used for proper path generation to the resources, pages, etcNEWLINEHOSTNAME = get_env('HOST', '')NEWLINEif HOSTNAME:NEWLINE if not HOSTNAME.startswith('http://') and not HOSTNAME.startswith('https://'):NEWLINE logger.info("! HOST variable found in environment, but it must start with http:// or https://, ignore it: %s", HOSTNAME)NEWLINE HOSTNAME = ''NEWLINE else:NEWLINE logger.info("=> Hostname correctly is set to: %s", HOSTNAME)NEWLINE if HOSTNAME.endswith('/'):NEWLINE HOSTNAME = HOSTNAME[0:-1]NEWLINENEWLINE # for django url resolverNEWLINE if HOSTNAME:NEWLINE # http[s]://domain.com:8080/script_name => /script_nameNEWLINE pattern = re.compile(r'^http[s]?:\/\/([^:\/\s]+(:\d*)?)(.*)?')NEWLINE match = pattern.match(HOSTNAME)NEWLINE FORCE_SCRIPT_NAME = match.group(3)NEWLINE if FORCE_SCRIPT_NAME:NEWLINE logger.info("=> Django URL prefix is set to: %s", FORCE_SCRIPT_NAME)NEWLINENEWLINEINTERNAL_PORT = '8080'NEWLINENEWLINE# SECURITY WARNING: keep the secret key used in production secret!NEWLINESECRET_KEY = '$(fefwefwef13;LFK{P!)@#*!)kdsjfWF2l+i5e3t(8a1n'NEWLINENEWLINE# SECURITY WARNING: don't run with debug turned on in production!NEWLINEDEBUG = get_bool_env('DEBUG', True)NEWLINEDEBUG_MODAL_EXCEPTIONS = get_bool_env('DEBUG_MODAL_EXCEPTIONS', True)NEWLINENEWLINENEWLINE# Build paths inside the project like this: os.path.join(BASE_DIR, ...)NEWLINEBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))NEWLINENEWLINE# Base path for media root and other uploaded filesNEWLINEBASE_DATA_DIR = get_env('BASE_DATA_DIR', get_data_dir())NEWLINEos.makedirs(BASE_DATA_DIR, exist_ok=True)NEWLINElogger.info('=> Database and media directory: %s', BASE_DATA_DIR)NEWLINENEWLINE# DatabasesNEWLINE# https://docs.djangoproject.com/en/2.1/ref/settings/#databasesNEWLINEDJANGO_DB_MYSQL = 'mysql'NEWLINEDJANGO_DB_SQLITE = 'sqlite'NEWLINEDJANGO_DB = 'default'NEWLINEDATABASE_NAME_DEFAULT = os.path.join(BASE_DATA_DIR, 'label_studio.sqlite3')NEWLINEDATABASE_NAME = get_env('DATABASE_NAME', DATABASE_NAME_DEFAULT)NEWLINEDATABASES_ALL = {NEWLINE 'default': {NEWLINE 'ENGINE': 'django.db.backends.postgresql',NEWLINE 'USER': get_env('POSTGRE_USER', 'postgres'),NEWLINE 'PASSWORD': get_env('POSTGRE_PASSWORD', 'postgres'),NEWLINE 'NAME': get_env('POSTGRE_NAME', 'postgres'),NEWLINE 'HOST': get_env('POSTGRE_HOST', 'localhost'),NEWLINE 'PORT': int(get_env('POSTGRE_PORT', '5432')),NEWLINE },NEWLINE DJANGO_DB_MYSQL: {NEWLINE 'ENGINE': 'django.db.backends.mysql',NEWLINE 'USER': get_env('MYSQL_USER', 'root'),NEWLINE 'PASSWORD': get_env('MYSQL_PASSWORD', ''),NEWLINE 'NAME': get_env('MYSQL_NAME', 'labelstudio'),NEWLINE 'HOST': get_env('MYSQL_HOST', 'localhost'),NEWLINE 'PORT': int(get_env('MYSQL_PORT', '3306')),NEWLINE },NEWLINE DJANGO_DB_SQLITE: {NEWLINE 'ENGINE': 'django.db.backends.sqlite3',NEWLINE 'NAME': DATABASE_NAME,NEWLINE 'OPTIONS': {NEWLINE # 'timeout': 20,NEWLINE }NEWLINE }NEWLINE}NEWLINEDATABASES = {'default': DATABASES_ALL.get(get_env('DJANGO_DB', 'default'))}NEWLINENEWLINELOGGING = {NEWLINE 'version': 1,NEWLINE 'disable_existing_loggers': False,NEWLINE 'formatters': {NEWLINE 'standard': {NEWLINE 'format': '[%(asctime)s] [%(name)s::%(funcName)s::%(lineno)d] [%(levelname)s] %(message)s',NEWLINE },NEWLINE 'message_only': {NEWLINE 'format': '%(message)s',NEWLINE },NEWLINE 'rq_console': {NEWLINE 'format': '%(asctime)s %(message)s',NEWLINE 'datefmt': '%H:%M:%S',NEWLINE },NEWLINE },NEWLINE 'handlers': {NEWLINE 'console_raw': {NEWLINE 'level': get_env('LOG_LEVEL', 'WARNING'),NEWLINE 'class': 'logging.StreamHandler',NEWLINE },NEWLINE 'console': {NEWLINE 'level': get_env('LOG_LEVEL', 'WARNING'),NEWLINE 'class': 'logging.StreamHandler',NEWLINE 'formatter': 'standard'NEWLINE },NEWLINE 'rq_console': {NEWLINE 'level': 'WARNING',NEWLINE 'class': 'rq.utils.ColorizingStreamHandler',NEWLINE 'formatter': 'rq_console',NEWLINE 'exclude': ['%(asctime)s'],NEWLINE }NEWLINE },NEWLINE 'root': {NEWLINE 'handlers': ['console'],NEWLINE 'level': get_env('LOG_LEVEL', 'WARNING'),NEWLINE }NEWLINE}NEWLINENEWLINEif get_bool_env('GOOGLE_LOGGING_ENABLED', False):NEWLINE logging.info('Google Cloud Logging handler is enabled.')NEWLINE try:NEWLINE import google.cloud.loggingNEWLINE from google.auth.exceptions import GoogleAuthErrorNEWLINENEWLINE client = google.cloud.logging.Client()NEWLINE client.setup_logging()NEWLINENEWLINE LOGGING['handlers']['google_cloud_logging'] = {NEWLINE 'level': get_env('LOG_LEVEL', 'WARNING'),NEWLINE 'class': 'google.cloud.logging.handlers.CloudLoggingHandler',NEWLINE 'client': clientNEWLINE }NEWLINE LOGGING['root']['handlers'].append('google_cloud_logging')NEWLINE except GoogleAuthError as e:NEWLINE logger.exception('Google Cloud Logging handler could not be setup.')NEWLINENEWLINEINSTALLED_APPS = [NEWLINE 'django.contrib.admin',NEWLINE 'django.contrib.auth',NEWLINE 'django.contrib.contenttypes',NEWLINE 'django.contrib.sessions',NEWLINE 'django.contrib.messages',NEWLINE 'django.contrib.staticfiles',NEWLINE 'django.contrib.humanize',NEWLINENEWLINE 'drf_yasg',NEWLINE 'corsheaders',NEWLINE 'django_extensions',NEWLINE 'django_rq',NEWLINE 'django_filters',NEWLINE 'rules',NEWLINE 'annoying',NEWLINENEWLINE 'rest_framework',NEWLINE 'rest_framework_swagger',NEWLINE 'rest_framework.authtoken',NEWLINE 'drf_generators',NEWLINENEWLINE 'core',NEWLINE 'users',NEWLINE 'organizations',NEWLINE 'data_import',NEWLINE 'data_export',NEWLINENEWLINE 'projects',NEWLINE 'tasks',NEWLINE 'data_manager',NEWLINE 'io_storages',NEWLINE 'ml',NEWLINE 'webhooks',NEWLINE]NEWLINENEWLINEMIDDLEWARE = [NEWLINE 'corsheaders.middleware.CorsMiddleware',NEWLINE 'django.middleware.security.SecurityMiddleware',NEWLINE 'django.contrib.sessions.middleware.SessionMiddleware',NEWLINE 'django.middleware.locale.LocaleMiddleware',NEWLINE 'django.middleware.csrf.CsrfViewMiddleware',NEWLINE 'core.middleware.DisableCSRF',NEWLINE 'django.contrib.auth.middleware.AuthenticationMiddleware',NEWLINE 'django.contrib.messages.middleware.MessageMiddleware',NEWLINE 'django.middleware.clickjacking.XFrameOptionsMiddleware',NEWLINE 'core.middleware.CommonMiddlewareAppendSlashWithoutRedirect', # instead of 'CommonMiddleware'NEWLINE 'core.middleware.CommonMiddleware',NEWLINE 'django_user_agents.middleware.UserAgentMiddleware',NEWLINE 'core.middleware.SetSessionUIDMiddleware',NEWLINE 'core.middleware.ContextLogMiddleware',NEWLINE 'core.middleware.DatabaseIsLockedRetryMiddleware',NEWLINE]NEWLINENEWLINEREST_FRAMEWORK = {NEWLINE 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],NEWLINE 'DEFAULT_AUTHENTICATION_CLASSES': (NEWLINE 'rest_framework.authentication.TokenAuthentication',NEWLINE 'rest_framework.authentication.SessionAuthentication',NEWLINE ),NEWLINE 'DEFAULT_PERMISSION_CLASSES': [NEWLINE 'core.api_permissions.HasObjectPermission',NEWLINE 'rest_framework.permissions.IsAuthenticated',NEWLINENEWLINE ],NEWLINE 'EXCEPTION_HANDLER': 'core.utils.common.custom_exception_handler',NEWLINE 'DEFAULT_RENDERER_CLASSES': (NEWLINE 'rest_framework.renderers.JSONRenderer',NEWLINE ),NEWLINE 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning'NEWLINE}NEWLINENEWLINE# CORS & Host settingsNEWLINEINTERNAL_IPS = [ # django debug toolbar for django==2.2 requirementNEWLINE '127.0.0.1',NEWLINE 'localhost',NEWLINE]NEWLINECORS_ORIGIN_ALLOW_ALL = TrueNEWLINECORS_ALLOW_METHODS = [NEWLINE 'DELETE',NEWLINE 'GET',NEWLINE 'OPTIONS',NEWLINE 'PATCH',NEWLINE 'POST',NEWLINE 'PUT',NEWLINE]NEWLINEALLOWED_HOSTS = ['*']NEWLINENEWLINE# Auth modulesNEWLINEAUTH_USER_MODEL = 'users.User'NEWLINEAUTHENTICATION_BACKENDS = [NEWLINE 'rules.permissions.ObjectPermissionBackend',NEWLINE 'django.contrib.auth.backends.ModelBackend'NEWLINE]NEWLINEUSE_USERNAME_FOR_LOGIN = FalseNEWLINENEWLINEDISABLE_SIGNUP_WITHOUT_LINK = get_bool_env('DISABLE_SIGNUP_WITHOUT_LINK', False)NEWLINENEWLINE# Password validation:NEWLINE# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validatorsNEWLINEAUTH_PASSWORD_VALIDATORS = [NEWLINE {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},NEWLINE {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},NEWLINE {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},NEWLINE {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},NEWLINE]NEWLINENEWLINE# Django templatesNEWLINETEMPLATES_DIR = os.path.join(os.path.dirname(BASE_DIR), 'templates') # ../../from_this = 'web' dirNEWLINETEMPLATES = [NEWLINE {NEWLINE 'BACKEND': 'django.template.backends.django.DjangoTemplates',NEWLINE 'DIRS': [TEMPLATES_DIR],NEWLINE 'APP_DIRS': True,NEWLINE 'OPTIONS': {NEWLINE 'context_processors': [NEWLINE 'django.template.context_processors.debug',NEWLINE 'django.template.context_processors.request',NEWLINE 'django.contrib.auth.context_processors.auth',NEWLINE 'django.contrib.messages.context_processors.messages',NEWLINE 'core.context_processors.settings'NEWLINE ],NEWLINE 'builtins': ['django.templatetags.i18n'],NEWLINE },NEWLINE }NEWLINE]NEWLINENEWLINE# RQNEWLINERQ_QUEUES = {NEWLINE 'default': {NEWLINE 'HOST': 'localhost',NEWLINE 'PORT': 6379,NEWLINE 'DB': 0,NEWLINE 'DEFAULT_TIMEOUT': 180NEWLINE }NEWLINE}NEWLINENEWLINE# Swagger: automatic API documentationNEWLINESWAGGER_SETTINGS = {NEWLINE 'SECURITY_DEFINITIONS': {NEWLINE 'token': {NEWLINE 'type': 'token',NEWLINE 'name': 'Token',NEWLINE 'in': 'header',NEWLINE 'url': '/user/account'NEWLINE }NEWLINE },NEWLINE 'APIS_SORTER': 'alpha',NEWLINE 'SUPPORTED_SUBMIT_METHODS': ['get', 'post', 'put', 'delete', 'patch'],NEWLINE # "DEFAULT_AUTO_SCHEMA_CLASS": "core.utils.CustomAutoSchema",NEWLINE 'OPERATIONS_SORTER': 'alpha'NEWLINE}NEWLINENEWLINESENTRY_DSN = get_env('SENTRY_DSN', None)NEWLINESENTRY_RATE = float(get_env('SENTRY_RATE', 0.25))NEWLINESENTRY_ENVIRONMENT = get_env('SENTRY_ENVIRONMENT', 'stage.opensource')NEWLINESENTRY_REDIS_ENABLED = FalseNEWLINEFRONTEND_SENTRY_DSN = get_env('FRONTEND_SENTRY_DSN', None)NEWLINEFRONTEND_SENTRY_RATE = get_env('FRONTEND_SENTRY_RATE', 0.1)NEWLINEFRONTEND_SENTRY_ENVIRONMENT = get_env('FRONTEND_SENTRY_ENVIRONMENT', 'stage.opensource')NEWLINENEWLINEROOT_URLCONF = 'core.urls'NEWLINEWSGI_APPLICATION = 'core.wsgi.application'NEWLINEGRAPHIQL = TrueNEWLINENEWLINE# InternationalizationNEWLINE# https://docs.djangoproject.com/en/2.1/topics/i18n/NEWLINELANGUAGE_CODE = 'en-us'NEWLINETIME_ZONE = 'UTC'NEWLINEUSE_I18N = FalseNEWLINEUSE_L10N = TrueNEWLINEUSE_TZ = TrueNEWLINENEWLINE# Static files (CSS, JavaScript, Images)NEWLINE# https://docs.djangoproject.com/en/2.1/howto/static-files/NEWLINESTATIC_URL = '/static/'NEWLINE# if FORCE_SCRIPT_NAME:NEWLINE# STATIC_URL = FORCE_SCRIPT_NAME + STATIC_URLNEWLINElogger.info(f'=> Static URL is set to: {STATIC_URL}')NEWLINENEWLINESTATIC_ROOT = os.path.join(BASE_DIR, 'static_build')NEWLINESTATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]NEWLINESTATICFILES_FINDERS = (NEWLINE 'django.contrib.staticfiles.finders.FileSystemFinder',NEWLINE 'django.contrib.staticfiles.finders.AppDirectoriesFinder'NEWLINE)NEWLINESTATICFILES_STORAGE = 'core.storage.SkipMissedManifestStaticFilesStorage'NEWLINENEWLINE# Sessions and CSRFNEWLINESESSION_COOKIE_SECURE = bool(int(get_env('SESSION_COOKIE_SECURE', True)))NEWLINECSRF_COOKIE_SECURE = bool(int(get_env('CSRF_COOKIE_SECURE', SESSION_COOKIE_SECURE)))NEWLINECSRF_COOKIE_HTTPONLY = bool(int(get_env('CSRF_COOKIE_HTTPONLY', SESSION_COOKIE_SECURE)))NEWLINENEWLINE# user media filesNEWLINEMEDIA_ROOT = os.path.join(BASE_DATA_DIR, 'media')NEWLINEos.makedirs(MEDIA_ROOT, exist_ok=True)NEWLINEMEDIA_URL = '/data/'NEWLINEUPLOAD_DIR = 'upload'NEWLINEAVATAR_PATH = 'avatars'NEWLINENEWLINE# project exportsNEWLINEEXPORT_DIR = os.path.join(BASE_DATA_DIR, 'export')NEWLINEEXPORT_URL_ROOT = '/export/'NEWLINE# old export dirNEWLINEos.makedirs(EXPORT_DIR, exist_ok=True)NEWLINE# dir for delayed exportNEWLINEDELAYED_EXPORT_DIR = 'export'NEWLINEos.makedirs(os.path.join(BASE_DATA_DIR, MEDIA_ROOT, DELAYED_EXPORT_DIR), exist_ok=True)NEWLINENEWLINE# file / task size limitsNEWLINEDATA_UPLOAD_MAX_MEMORY_SIZE = int(get_env('DATA_UPLOAD_MAX_MEMORY_SIZE', 250 * 1024 * 1024))NEWLINETASKS_MAX_NUMBER = 1000000NEWLINETASKS_MAX_FILE_SIZE = DATA_UPLOAD_MAX_MEMORY_SIZENEWLINENEWLINETASK_LOCK_TTL = int(get_env('TASK_LOCK_TTL')) if get_env('TASK_LOCK_TTL') else NoneNEWLINETASK_LOCK_DEFAULT_TTL = int(get_env('TASK_LOCK_DEFAULT_TTL', 3600))NEWLINETASK_LOCK_MIN_TTL = int(get_env('TASK_LOCK_MIN_TTL', 120))NEWLINENEWLINE# Email backendNEWLINEFROM_EMAIL = get_env('FROM_EMAIL', 'Label Studio ')NEWLINEEMAIL_BACKEND = get_env('EMAIL_BACKEND', 'django.core.mail.backends.dummy.EmailBackend')NEWLINENEWLINEENABLE_LOCAL_FILES_STORAGE = get_bool_env('ENABLE_LOCAL_FILES_STORAGE', default=True)NEWLINELOCAL_FILES_SERVING_ENABLED = get_bool_env('LOCAL_FILES_SERVING_ENABLED', default=False)NEWLINENEWLINE""" React Libraries: do not forget to change this dir in /etc/nginx/nginx.conf """NEWLINE# EDITOR = label-studio-frontend repositoryNEWLINEEDITOR_ROOT = os.path.join(BASE_DIR, '../frontend/dist/lsf')NEWLINE# DM = data manager (included into FRONTEND due npm building, we need only version.json file from there)NEWLINEDM_ROOT = os.path.join(BASE_DIR, '../frontend/dist/dm')NEWLINE# FRONTEND = GUI for django backendNEWLINEREACT_APP_ROOT = os.path.join(BASE_DIR, '../frontend/dist/react-app')NEWLINENEWLINE# per project settingsNEWLINEBATCH_SIZE = 1000NEWLINEPROJECT_TITLE_MIN_LEN = 3NEWLINEPROJECT_TITLE_MAX_LEN = 50NEWLINELOGIN_REDIRECT_URL = '/'NEWLINELOGIN_URL = '/'NEWLINEMIN_GROUND_TRUTH = 10NEWLINEDATA_UNDEFINED_NAME = '$undefined$'NEWLINELICENSE = {}NEWLINEVERSIONS = {}NEWLINEVERSION_EDITION = 'Community Edition'NEWLINELATEST_VERSION_CHECK = TrueNEWLINEVERSIONS_CHECK_TIME = 0NEWLINEALLOW_ORGANIZATION_WEBHOOKS = get_bool_env('ALLOW_ORGANIZATION_WEBHOOKS', False)NEWLINECONVERTER_DOWNLOAD_RESOURCES = get_bool_env('CONVERTER_DOWNLOAD_RESOURCES', True)NEWLINEEXPERIMENTAL_FEATURES = get_bool_env('EXPERIMENTAL_FEATURES', False)NEWLINENEWLINECREATE_ORGANIZATION = 'organizations.functions.create_organization'NEWLINEGET_OBJECT_WITH_CHECK_AND_LOG = 'core.utils.get_object.get_object_with_check_and_log'NEWLINESAVE_USER = 'users.functions.save_user'NEWLINEUSER_SERIALIZER = 'users.serializers.BaseUserSerializer'NEWLINEDATA_MANAGER_GET_ALL_COLUMNS = 'data_manager.functions.get_all_columns'NEWLINEDATA_MANAGER_ANNOTATIONS_MAP = {}NEWLINEDATA_MANAGER_ACTIONS = {}NEWLINEDATA_MANAGER_CUSTOM_FILTER_EXPRESSIONS = ''NEWLINEUSER_LOGIN_FORM = 'users.forms.LoginForm'NEWLINEPROJECT_MIXIN = 'core.mixins.DummyModelMixin'NEWLINETASK_MIXIN = 'core.mixins.DummyModelMixin'NEWLINEANNOTATION_MIXIN = 'core.mixins.DummyModelMixin'NEWLINEORGANIZATION_MIXIN = 'core.mixins.DummyModelMixin'NEWLINEUSER_MIXIN = 'users.mixins.UserMixin'NEWLINEGET_STORAGE_LIST = 'io_storages.functions.get_storage_list'NEWLINENEWLINESTORAGE_ANNOTATION_SERIALIZER = 'io_storages.serializers.StorageAnnotationSerializer'NEWLINENEWLINENEWLINEdef project_delete(project):NEWLINE project.delete()NEWLINENEWLINENEWLINEdef user_auth(user_model, email, password):NEWLINE return NoneNEWLINENEWLINENEWLINEdef collect_versions_dummy(**kwargs):NEWLINE return {}NEWLINENEWLINENEWLINEPROJECT_DELETE = project_deleteNEWLINEUSER_AUTH = user_authNEWLINECOLLECT_VERSIONS = collect_versions_dummyNEWLINENEWLINEWEBHOOK_TIMEOUT = float(get_env('WEBHOOK_TIMEOUT', 1.0))NEWLINENEWLINE# fix a problem with Windows mimetypes for JS and PNGNEWLINEimport mimetypesNEWLINEmimetypes.add_type("application/javascript", ".js", True)NEWLINEmimetypes.add_type("image/png", ".png", True)NEWLINE from enum import EnumNEWLINEimport loggingNEWLINEimport randomNEWLINEimport reNEWLINEimport requestsNEWLINEfrom r2d7.core import DroidCoreNEWLINENEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINEclass Talkback(DroidCore):NEWLINE """NEWLINE Chat responses unrelated to other commandsNEWLINE """NEWLINE pattern_fix = re.compile('^!((fix)|(typo))', re.I)NEWLINE pattern_data = re.compile('^!(data)', re.I)NEWLINE pattern_help = re.compile('^!(help)', re.I)NEWLINE pattern_stitchCrew = re.compile('^!(stitch ?crew)', re.I)NEWLINE pattern_stitchCard = re.compile('\[\[(stitch ?crew)\]\]', re.I)NEWLINE pattern_egg = re.compile('^!((egg)|(sooga))', re.I)NEWLINENEWLINE _data_url = 'https://github.com/guidokessels/xwing-data2'NEWLINE _r2d7_url = 'https://github.com/FreakyDug/r2-d7'NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINE self.register_handler(Talkback.pattern_fix, self.fixHandler)NEWLINE self.register_handler(Talkback.pattern_data, self.dataHandler)NEWLINE self.register_handler(Talkback.pattern_help, self.helpHandler)NEWLINE self.register_handler(Talkback.pattern_stitchCrew, self.stitchCrewHandler)NEWLINE self.register_handler(Talkback.pattern_stitchCard, self.stitchCardHandler)NEWLINE self.register_handler(Talkback.pattern_egg, self.eggHandler)NEWLINENEWLINE def fixHandler(self, message):NEWLINE dataErrorText = 'For issues with card data, raise an issue or pull request at 'NEWLINE dataErrorText += self.link(self._data_url, self._data_url)NEWLINE squadErrorText = 'For issues with squad lists, raise an issue at 'NEWLINE squadErrorText += self.link(self._r2d7_url, self._r2d7_url)NEWLINE return [[dataErrorText, squadErrorText]]NEWLINENEWLINE def dataHandler(self, message):NEWLINE text = 'X-Wing card data taken from 'NEWLINE text += self.link(self._data_url, self._data_url)NEWLINE return [[text]]NEWLINENEWLINE def helpHandler(self, message):NEWLINE return [[self.helpMessage()]]NEWLINENEWLINE def stitchCrewHandler(self, message):NEWLINE lines = [NEWLINE ['Stitch who?'],NEWLINE ['STITCH CREW!'],NEWLINE [':sewing_needle::crew:'],NEWLINE [NEWLINE self.bold('Stitch Crew'),NEWLINE '4 players, 200pts, 2 ships per player, 2 obstacles per player. First player is random and player order proceeds clockwise.',NEWLINE f'{self.bold("Setup:")} Players place obstacles in player order until 6 obstacles have been placed. Players deploy ships within range 3 of their assigned table corner and range 1 of the table edge.',NEWLINE f'{self.bold("Rules:")} The last surviving player wins the game. Alliances are forbidden, but table talk is encouraged. When a ship engages, if it has one or more valid enemy targets, it must shoot.'NEWLINE ]NEWLINE ]NEWLINE return [random.choice(lines)]NEWLINENEWLINE def stitchCardHandler(self, message):NEWLINE lines = [NEWLINE [NEWLINE f':crew::crew::crew::crew:• {self.bold("Stitch Crew")} [0]',NEWLINE self.italics('Restrictions: Stitch Crew Only'),NEWLINE 'Pew Pew Pew'NEWLINE ],NEWLINE ]NEWLINE return [random.choice(lines)]NEWLINENEWLINE def eggHandler(self, message):NEWLINE lines = [NEWLINE ['Sooga! Sooga! Sooga!'],NEWLINE ['Utinni!'],NEWLINE [':egg:'],NEWLINE ['Maclunkey!'],NEWLINE ]NEWLINE return [random.choice(lines)]NEWLINE import numpy as npNEWLINEimport unittestNEWLINENEWLINEimport chainerNEWLINEfrom chainer import optimizersNEWLINEfrom chainer import testingNEWLINEfrom chainer.testing import attrNEWLINENEWLINEfrom chainercv.links.model.ssd import GradientScalingNEWLINENEWLINENEWLINEclass SimpleLink(chainer.Link):NEWLINENEWLINE def __init__(self, w, g):NEWLINE super(SimpleLink, self).__init__()NEWLINE with self.init_scope():NEWLINE self.param = chainer.Parameter(w)NEWLINE self.param.grad = gNEWLINENEWLINENEWLINEclass TestGradientScaling(unittest.TestCase):NEWLINENEWLINE def setUp(self):NEWLINE self.target = SimpleLink(NEWLINE np.arange(6, dtype=np.float32).reshape((2, 3)),NEWLINE np.arange(3, -3, -1, dtype=np.float32).reshape((2, 3)))NEWLINENEWLINE def check_gradient_scaling(self):NEWLINE w = self.target.param.arrayNEWLINE g = self.target.param.gradNEWLINENEWLINE rate = 0.2NEWLINE expect = w - g * rateNEWLINENEWLINE opt = optimizers.SGD(lr=1)NEWLINE opt.setup(self.target)NEWLINE opt.add_hook(GradientScaling(rate))NEWLINE opt.update()NEWLINENEWLINE testing.assert_allclose(expect, w)NEWLINENEWLINE def test_gradient_scaling_cpu(self):NEWLINE self.check_gradient_scaling()NEWLINENEWLINE @attr.gpuNEWLINE def test_gradient_scaling_gpu(self):NEWLINE self.target.to_gpu()NEWLINE self.check_gradient_scaling()NEWLINENEWLINENEWLINEtesting.run_module(__name__, __file__)NEWLINE # exported from PySB model 'model'NEWLINENEWLINEfrom pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILDNEWLINENEWLINEModel()NEWLINENEWLINEMonomer('Ligand', ['Receptor'])NEWLINEMonomer('ParpU', ['C3A'])NEWLINEMonomer('C8A', ['BidU', 'C3pro'])NEWLINEMonomer('SmacM', ['BaxA'])NEWLINEMonomer('BaxM', ['BidM', 'BaxA'])NEWLINEMonomer('Apop', ['C3pro', 'Xiap'])NEWLINEMonomer('Fadd', ['Receptor', 'C8pro'])NEWLINEMonomer('SmacC', ['Xiap'])NEWLINEMonomer('ParpC')NEWLINEMonomer('Xiap', ['SmacC', 'Apop', 'C3A'])NEWLINEMonomer('C9')NEWLINEMonomer('C3ub')NEWLINEMonomer('C8pro', ['Fadd', 'C6A'])NEWLINEMonomer('Bcl2', ['BidM', 'BaxA'])NEWLINEMonomer('C3pro', ['Apop', 'C8A'])NEWLINEMonomer('CytoCM', ['BaxA'])NEWLINEMonomer('CytoCC')NEWLINEMonomer('BaxA', ['BaxM', 'Bcl2', 'BaxA_1', 'BaxA_2', 'SmacM', 'CytoCM'])NEWLINEMonomer('ApafI')NEWLINEMonomer('BidU', ['C8A'])NEWLINEMonomer('BidT')NEWLINEMonomer('C3A', ['Xiap', 'ParpU', 'C6pro'])NEWLINEMonomer('ApafA')NEWLINEMonomer('BidM', ['BaxM', 'Bcl2'])NEWLINEMonomer('Receptor', ['Ligand', 'Fadd'])NEWLINEMonomer('C6A', ['C8pro'])NEWLINEMonomer('C6pro', ['C3A'])NEWLINENEWLINEParameter('bind_0_Ligand_binder_Receptor_binder_target_2kf', 1.0)NEWLINEParameter('bind_0_Ligand_binder_Receptor_binder_target_1kr', 1.0)NEWLINEParameter('bind_0_Receptor_binder_Fadd_binder_target_2kf', 1.0)NEWLINEParameter('bind_0_Receptor_binder_Fadd_binder_target_1kr', 1.0)NEWLINEParameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf', 1.0)NEWLINEParameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr', 1.0)NEWLINEParameter('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0)NEWLINEParameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf', 1.0)NEWLINEParameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr', 1.0)NEWLINEParameter('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc', 1.0)NEWLINEParameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf', 1.0)NEWLINEParameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr', 1.0)NEWLINEParameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf', 1.0)NEWLINEParameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr', 1.0)NEWLINEParameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf', 1.0)NEWLINEParameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr', 1.0)NEWLINEParameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0)NEWLINEParameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0)NEWLINEParameter('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0)NEWLINEParameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf', 1.0)NEWLINEParameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr', 1.0)NEWLINEParameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf', 1.0)NEWLINEParameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr', 1.0)NEWLINEParameter('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc', 1.0)NEWLINEParameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf', 1.0)NEWLINEParameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr', 1.0)NEWLINEParameter('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc', 1.0)NEWLINEParameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kf', 1.0)NEWLINEParameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kr', 1.0)NEWLINEParameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf', 1.0)NEWLINEParameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr', 1.0)NEWLINEParameter('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc', 1.0)NEWLINEParameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf', 1.0)NEWLINEParameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr', 1.0)NEWLINEParameter('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc', 1.0)NEWLINEParameter('inhibition_0_Bcl2_inhibitor_BidM_inh_target_2kf', 1.0)NEWLINEParameter('inhibition_0_Bcl2_inhibitor_BidM_inh_target_1kr', 1.0)NEWLINEParameter('inhibition_0_Bcl2_inhibitor_BaxA_inh_target_2kf', 1.0)NEWLINEParameter('inhibition_0_Bcl2_inhibitor_BaxA_inh_target_1kr', 1.0)NEWLINEParameter('pore_formation_0_BaxA_pore_2kf', 1.0)NEWLINEParameter('pore_formation_0_BaxA_pore_1kr', 1.0)NEWLINEParameter('pore_formation_1_BaxA_pore_2kf', 1.0)NEWLINEParameter('pore_formation_1_BaxA_pore_1kr', 1.0)NEWLINEParameter('pore_formation_2_BaxA_pore_2kf', 1.0)NEWLINEParameter('pore_formation_2_BaxA_pore_1kr', 1.0)NEWLINEParameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf', 1.0)NEWLINEParameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr', 1.0)NEWLINEParameter('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc', 1.0)NEWLINEParameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf', 1.0)NEWLINEParameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr', 1.0)NEWLINEParameter('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc', 1.0)NEWLINEParameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0)NEWLINEParameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0)NEWLINEParameter('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0)NEWLINEParameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf', 1.0)NEWLINEParameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr', 1.0)NEWLINEParameter('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc', 1.0)NEWLINEParameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf', 1.0)NEWLINEParameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr', 1.0)NEWLINEParameter('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0)NEWLINEParameter('Ligand_0', 1000.0)NEWLINEParameter('ParpU_0', 1000000.0)NEWLINEParameter('C8A_0', 0.0)NEWLINEParameter('SmacM_0', 100000.0)NEWLINEParameter('BaxM_0', 40000.0)NEWLINEParameter('Apop_0', 0.0)NEWLINEParameter('Fadd_0', 130000.0)NEWLINEParameter('SmacC_0', 0.0)NEWLINEParameter('ParpC_0', 0.0)NEWLINEParameter('Xiap_0', 75000.0)NEWLINEParameter('C9_0', 100000.0)NEWLINEParameter('C3ub_0', 0.0)NEWLINEParameter('C8pro_0', 130000.0)NEWLINEParameter('Bcl2_0', 130000.0)NEWLINEParameter('C3pro_0', 21000.0)NEWLINEParameter('CytoCM_0', 500000.0)NEWLINEParameter('CytoCC_0', 0.0)NEWLINEParameter('BaxA_0', 0.0)NEWLINEParameter('ApafI_0', 100000.0)NEWLINEParameter('BidU_0', 171000.0)NEWLINEParameter('BidT_0', 0.0)NEWLINEParameter('C3A_0', 0.0)NEWLINEParameter('ApafA_0', 0.0)NEWLINEParameter('BidM_0', 0.0)NEWLINEParameter('Receptor_0', 100.0)NEWLINEParameter('C6A_0', 0.0)NEWLINEParameter('C6pro_0', 100.0)NEWLINENEWLINEObservable('Ligand_obs', Ligand())NEWLINEObservable('ParpU_obs', ParpU())NEWLINEObservable('C8A_obs', C8A())NEWLINEObservable('SmacM_obs', SmacM())NEWLINEObservable('BaxM_obs', BaxM())NEWLINEObservable('Apop_obs', Apop())NEWLINEObservable('Fadd_obs', Fadd())NEWLINEObservable('SmacC_obs', SmacC())NEWLINEObservable('ParpC_obs', ParpC())NEWLINEObservable('Xiap_obs', Xiap())NEWLINEObservable('C9_obs', C9())NEWLINEObservable('C3ub_obs', C3ub())NEWLINEObservable('C8pro_obs', C8pro())NEWLINEObservable('Bcl2_obs', Bcl2())NEWLINEObservable('C3pro_obs', C3pro())NEWLINEObservable('CytoCM_obs', CytoCM())NEWLINEObservable('CytoCC_obs', CytoCC())NEWLINEObservable('BaxA_obs', BaxA())NEWLINEObservable('ApafI_obs', ApafI())NEWLINEObservable('BidU_obs', BidU())NEWLINEObservable('BidT_obs', BidT())NEWLINEObservable('C3A_obs', C3A())NEWLINEObservable('ApafA_obs', ApafA())NEWLINEObservable('BidM_obs', BidM())NEWLINEObservable('Receptor_obs', Receptor())NEWLINEObservable('C6A_obs', C6A())NEWLINEObservable('C6pro_obs', C6pro())NEWLINENEWLINERule('bind_0_Ligand_binder_Receptor_binder_target', Ligand(Receptor=None) + Receptor(Ligand=None, Fadd=None) | Ligand(Receptor=1) % Receptor(Ligand=1, Fadd=None), bind_0_Ligand_binder_Receptor_binder_target_2kf, bind_0_Ligand_binder_Receptor_binder_target_1kr)NEWLINERule('bind_0_Receptor_binder_Fadd_binder_target', Receptor(Ligand=ANY, Fadd=None) + Fadd(Receptor=None, C8pro=None) | Receptor(Ligand=ANY, Fadd=1) % Fadd(Receptor=1, C8pro=None), bind_0_Receptor_binder_Fadd_binder_target_2kf, bind_0_Receptor_binder_Fadd_binder_target_1kr)NEWLINERule('substrate_binding_0_Fadd_catalyzer_C8pro_substrate', Fadd(Receptor=ANY, C8pro=None) + C8pro(Fadd=None, C6A=None) | Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None), substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf, substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr)NEWLINERule('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product', Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None) >> Fadd(Receptor=ANY, C8pro=None) + C8A(BidU=None, C3pro=None), catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc)NEWLINERule('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=None, C3pro=None) + BidU(C8A=None) | C8A(BidU=1, C3pro=None) % BidU(C8A=1), catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf, catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr)NEWLINERule('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=1, C3pro=None) % BidU(C8A=1) >> C8A(BidU=None, C3pro=None) + BidT(), catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc)NEWLINERule('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex', ApafI() + CytoCC() | ApafA(), conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf, conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr)NEWLINERule('inhibition_0_SmacC_inhibitor_Xiap_inh_target', SmacC(Xiap=None) + Xiap(SmacC=None, Apop=None, C3A=None) | SmacC(Xiap=1) % Xiap(SmacC=1, Apop=None, C3A=None), inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf, inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr)NEWLINERule('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex', ApafA() + C9() | Apop(C3pro=None, Xiap=None), conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf, conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr)NEWLINERule('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=None, Xiap=None) + C3pro(Apop=None, C8A=None) | Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None), catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr)NEWLINERule('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None) >> Apop(C3pro=None, Xiap=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc)NEWLINERule('inhibition_0_Xiap_inhibitor_Apop_inh_target', Xiap(SmacC=None, Apop=None, C3A=None) + Apop(C3pro=None, Xiap=None) | Xiap(SmacC=None, Apop=1, C3A=None) % Apop(C3pro=None, Xiap=1), inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf, inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr)NEWLINERule('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=None) + C3A(Xiap=None, ParpU=None, C6pro=None) | Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None), catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf, catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr)NEWLINERule('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None) >> Xiap(SmacC=None, Apop=None, C3A=None) + C3ub(), catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc)NEWLINERule('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=None, C6pro=None) + ParpU(C3A=None) | C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1), catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf, catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr)NEWLINERule('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + ParpC(), catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc)NEWLINERule('equilibration_0_BidT_equil_a_BidM_equil_b', BidT() | BidM(BaxM=None, Bcl2=None), equilibration_0_BidT_equil_a_BidM_equil_b_1kf, equilibration_0_BidT_equil_a_BidM_equil_b_1kr)NEWLINERule('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=None, Bcl2=None) + BaxM(BidM=None, BaxA=None) | BidM(BaxM=1, Bcl2=None) % BaxM(BidM=1, BaxA=None), catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf, catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr)NEWLINERule('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=1, Bcl2=None) % BaxM(BidM=1, BaxA=None) >> BidM(BaxM=None, Bcl2=None) + BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc)NEWLINERule('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxM(BidM=None, BaxA=None) | BaxA(BaxM=1, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1), self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf, self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr)NEWLINERule('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=1, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1) >> BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc)NEWLINERule('inhibition_0_Bcl2_inhibitor_BidM_inh_target', Bcl2(BidM=None, BaxA=None) + BidM(BaxM=None, Bcl2=None) | Bcl2(BidM=1, BaxA=None) % BidM(BaxM=None, Bcl2=1), inhibition_0_Bcl2_inhibitor_BidM_inh_target_2kf, inhibition_0_Bcl2_inhibitor_BidM_inh_target_1kr)NEWLINERule('inhibition_0_Bcl2_inhibitor_BaxA_inh_target', Bcl2(BidM=None, BaxA=None) + BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) | Bcl2(BidM=None, BaxA=1) % BaxA(BaxM=None, Bcl2=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), inhibition_0_Bcl2_inhibitor_BaxA_inh_target_2kf, inhibition_0_Bcl2_inhibitor_BaxA_inh_target_1kr)NEWLINERule('pore_formation_0_BaxA_pore', BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None), pore_formation_0_BaxA_pore_2kf, pore_formation_0_BaxA_pore_1kr)NEWLINERule('pore_formation_1_BaxA_pore', BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None), pore_formation_1_BaxA_pore_2kf, pore_formation_1_BaxA_pore_1kr)NEWLINERule('pore_formation_2_BaxA_pore', BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) | BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None), pore_formation_2_BaxA_pore_2kf, pore_formation_2_BaxA_pore_1kr)NEWLINERule('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacM(BaxA=None) | BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5), transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf, transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr)NEWLINERule('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5) >> BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacC(Xiap=None), transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc)NEWLINERule('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCM(BaxA=None) | BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5), transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf, transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr)NEWLINERule('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5) >> BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCC(), transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc)NEWLINERule('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=None) + C3pro(Apop=None, C8A=None) | C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1), catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr)NEWLINERule('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1) >> C8A(BidU=None, C3pro=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc)NEWLINERule('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=None) + C6pro(C3A=None) | C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1), catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf, catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr)NEWLINERule('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + C6A(C8pro=None), catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc)NEWLINERule('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=None) + C8pro(Fadd=None, C6A=None) | C6A(C8pro=1) % C8pro(Fadd=None, C6A=1), catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf, catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr)NEWLINERule('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=1) % C8pro(Fadd=None, C6A=1) >> C6A(C8pro=None) + C8A(BidU=None, C3pro=None), catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc)NEWLINENEWLINEInitial(Ligand(Receptor=None), Ligand_0)NEWLINEInitial(ParpU(C3A=None), ParpU_0)NEWLINEInitial(C8A(BidU=None, C3pro=None), C8A_0)NEWLINEInitial(SmacM(BaxA=None), SmacM_0)NEWLINEInitial(BaxM(BidM=None, BaxA=None), BaxM_0)NEWLINEInitial(Apop(C3pro=None, Xiap=None), Apop_0)NEWLINEInitial(Fadd(Receptor=None, C8pro=None), Fadd_0)NEWLINEInitial(SmacC(Xiap=None), SmacC_0)NEWLINEInitial(ParpC(), ParpC_0)NEWLINEInitial(Xiap(SmacC=None, Apop=None, C3A=None), Xiap_0)NEWLINEInitial(C9(), C9_0)NEWLINEInitial(C3ub(), C3ub_0)NEWLINEInitial(C8pro(Fadd=None, C6A=None), C8pro_0)NEWLINEInitial(Bcl2(BidM=None, BaxA=None), Bcl2_0)NEWLINEInitial(C3pro(Apop=None, C8A=None), C3pro_0)NEWLINEInitial(CytoCM(BaxA=None), CytoCM_0)NEWLINEInitial(CytoCC(), CytoCC_0)NEWLINEInitial(BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), BaxA_0)NEWLINEInitial(ApafI(), ApafI_0)NEWLINEInitial(BidU(C8A=None), BidU_0)NEWLINEInitial(BidT(), BidT_0)NEWLINEInitial(C3A(Xiap=None, ParpU=None, C6pro=None), C3A_0)NEWLINEInitial(ApafA(), ApafA_0)NEWLINEInitial(BidM(BaxM=None, Bcl2=None), BidM_0)NEWLINEInitial(Receptor(Ligand=None, Fadd=None), Receptor_0)NEWLINEInitial(C6A(C8pro=None), C6A_0)NEWLINEInitial(C6pro(C3A=None), C6pro_0)NEWLINENEWLINE import torchNEWLINEimport torch.nn as nnNEWLINENEWLINEfrom . import EmbeddingFeedForwardNEWLINEfrom .. import utilNEWLINEfrom ..distributions import TruncatedNormal, MixtureNEWLINENEWLINENEWLINEclass ProposalUniformTruncatedNormalMixture(nn.Module):NEWLINE def __init__(self, input_shape, num_layers=2, mixture_components=10):NEWLINE super().__init__()NEWLINE # Currently only supports event_shape=torch.Size([]) for the mixture componentsNEWLINE self._mixture_components = mixture_componentsNEWLINE input_shape = util.to_size(input_shape)NEWLINE self._ff = EmbeddingFeedForward(input_shape=input_shape, output_shape=torch.Size([3 * self._mixture_components]), num_layers=num_layers, activation=torch.relu, activation_last=None)NEWLINE self._total_train_iterations = 0NEWLINENEWLINE def forward(self, x, prior_variables):NEWLINE batch_size = x.size(0)NEWLINE x = self._ff(x)NEWLINE means = x[:, :self._mixture_components].view(batch_size, -1)NEWLINE stddevs = x[:, self._mixture_components:2*self._mixture_components].view(batch_size, -1)NEWLINE coeffs = x[:, 2*self._mixture_components:].view(batch_size, -1)NEWLINE means = torch.sigmoid(means)NEWLINE stddevs = torch.sigmoid(stddevs)NEWLINE coeffs = torch.softmax(coeffs, dim=1)NEWLINE means = means.view(batch_size, -1)NEWLINE stddevs = stddevs.view(batch_size, -1)NEWLINE prior_lows = torch.stack([util.to_tensor(v.distribution.low) for v in prior_variables]).view(batch_size)NEWLINE prior_highs = torch.stack([util.to_tensor(v.distribution.high) for v in prior_variables]).view(batch_size)NEWLINE prior_range = (prior_highs - prior_lows).view(batch_size, -1)NEWLINE means = prior_lows.view(batch_size, -1) + (means * prior_range)NEWLINE # stddevs = stddevs * prior_stddevsNEWLINE stddevs = (prior_range / 1000) + (stddevs * prior_range * 10)NEWLINE distributions = [TruncatedNormal(means[:, i:i+1].view(batch_size), stddevs[:, i:i+1].view(batch_size), low=prior_lows, high=prior_highs) for i in range(self._mixture_components)]NEWLINE return Mixture(distributions, coeffs)NEWLINE # -*- coding: utf-8 -*-NEWLINE# Generated by Django 1.10.4 on 2018-03-13 00:29NEWLINEfrom __future__ import unicode_literalsNEWLINENEWLINEfrom django.db import migrationsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ('board', '0006_merge_20180310_2200'),NEWLINE ('board', '0007_auto_20180311_1704'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE ]NEWLINE """This test creates two top level actors and one sub-actor andNEWLINE verifies that the actors can exchange sequences of messages."""NEWLINENEWLINEimport timeNEWLINEfrom thespian.actors import *NEWLINEfrom thespian.test import *NEWLINENEWLINEclass rosaline(Actor):NEWLINE name = 'Rosaline'NEWLINENEWLINEclass Romeo(Actor):NEWLINE def receiveMessage(self, msg, sender):NEWLINE if isinstance(msg, JulietAppears):NEWLINE self.send(msg.juliet, "But, soft! what light through yonder window breaks?")NEWLINE elif isinstance(msg, ActorExitRequest):NEWLINE pass # nothing special, just dieNEWLINE elif msg == 'Ay me!':NEWLINE self.send(sender, 'She speaks!')NEWLINE elif msg == 'O Romeo, Romeo! wherefore art thou Romeo?':NEWLINE self.send(sender, 'Shall I hear more, or shall I speak at this?')NEWLINE elif 'rose' in msg:NEWLINE pass # wait for itNEWLINE elif 'sweet' in msg:NEWLINE self.send(sender, 'Like softest music to attending ears!')NEWLINE elif 'hello' in msg:NEWLINE print('Hello from %s'%(str(self)))NEWLINE elif 'who_are_you' == msg:NEWLINE self.send(sender, self.myAddress)NEWLINE # otherwise sit and swoonNEWLINENEWLINENEWLINEclass Capulet(Actor):NEWLINE def receiveMessage(self, msg, sender):NEWLINE if msg == "has a daughter?":NEWLINE self.send(sender, self.createActor(Juliet))NEWLINENEWLINENEWLINEclass Juliet(Actor):NEWLINE def __init__(self, *args, **kw):NEWLINE self.nurse = NoneNEWLINE self.recalled = FalseNEWLINE super(Juliet, self).__init__(*args, **kw)NEWLINE def receiveMessage(self, msg, sender):NEWLINE if isinstance(msg, ActorExitRequest):NEWLINE pass # nothing special, just dieNEWLINE elif "what light" in msg:NEWLINE self.send(sender, 'Ay me!')NEWLINE elif msg == 'She speaks!':NEWLINE self.send(sender, 'O Romeo, Romeo! wherefore art thou Romeo?')NEWLINE elif msg == 'Shall I hear more, or shall I speak at this?':NEWLINE self.send(sender, "What's in a name? That which we call a rose")NEWLINE self.send(sender, "By any other name would smell as sweet")NEWLINE elif msg == 'Like softest music to attending ears!':NEWLINE if self.nurse:NEWLINE self.send(self.nurse, 'Anon, good nurse!')NEWLINE else:NEWLINE self.recalled = TrueNEWLINE elif msg == 'Mistress!':NEWLINE self.nurse = senderNEWLINE if self.recalled:NEWLINE self.send(self.nurse, 'Anon, good nurse!')NEWLINE elif 'who_are_you' == msg:NEWLINE self.send(sender, self.myAddress)NEWLINENEWLINENEWLINEclass Nurse(Actor):NEWLINE def __init__(self, *args, **kw):NEWLINE self.heardItAll = FalseNEWLINE super(Nurse, self).__init__(*args, **kw)NEWLINE def receiveMessage(self, msg, sender):NEWLINE if type(msg) == type((1,2)) and msg[0] == 'begin':NEWLINE self.send(msg[1], JulietAppears(msg[2]))NEWLINE self.send(msg[2], 'Mistress!')NEWLINE elif msg == 'Anon, good nurse!':NEWLINE self.heardItAll = TrueNEWLINE elif msg == 'done?':NEWLINE self.send(sender, 'Fini' if self.heardItAll else 'not yet')NEWLINENEWLINENEWLINEclass JulietAppears:NEWLINE stage = 'Right'NEWLINE def __init__(self, julietAddr):NEWLINE self.juliet = julietAddrNEWLINENEWLINENEWLINEclass TestFuncActors():NEWLINENEWLINENEWLINE def test01_ActorSystemStartupShutdown(self, asys):NEWLINE rosalineA = asys.createActor(rosaline)NEWLINE # just finish, make sure no exception is thrown.NEWLINENEWLINE def test01_1_ActorSystemMultipleShutdown(self, asys):NEWLINE rosalineA = asys.createActor(rosaline)NEWLINE asys.shutdown()NEWLINE asys.shutdown()NEWLINENEWLINE def test02_PrimaryActorCreation(self, asys):NEWLINE romeo = asys.createActor(Romeo)NEWLINE juliet = asys.createActor(Juliet)NEWLINE assert romeo != julietNEWLINENEWLINE def test03_CreateActorUniqueAddress(self, asys):NEWLINE romeo = asys.createActor(Romeo)NEWLINE juliet = asys.createActor(Juliet)NEWLINE assert romeo != julietNEWLINE romeo2 = asys.createActor(Romeo)NEWLINE assert romeo != romeo2NEWLINENEWLINE def NOtest04_PossibleActorSystemResourceExhaustion(self):NEWLINE try:NEWLINE addresses = [asys.createActor(Juliet) for n in range(10000)]NEWLINE except OSError as err:NEWLINE import errnoNEWLINE if err.errno == errno.EGAIN:NEWLINE passNEWLINE else:NEWLINE raiseNEWLINENEWLINENEWLINE def test05_ManyActorsUniqueAddress(self, asys):NEWLINE addresses = [asys.createActor(Juliet) for n in range(50)]NEWLINE uniqueAddresses = []NEWLINE duplicates = []NEWLINE for A in addresses:NEWLINE if A in uniqueAddresses:NEWLINE duplicates.append(A)NEWLINE else:NEWLINE uniqueAddresses.append(A)NEWLINE if len(addresses) != len(uniqueAddresses):NEWLINE print('Duplicates: %s'%map(str, duplicates))NEWLINE if duplicates:NEWLINE for each in duplicates:NEWLINE print('... %s at: %s'%(str(each), str([N for N,A in enumerate(addresses) if A == each])))NEWLINE print('Note: if this is a UDPTransport test, be advised that Linux occasionally does seem to assign the same UDP port multiple times. Linux bug?')NEWLINE assert len(addresses) == len(uniqueAddresses)NEWLINENEWLINE def test06_ManyActorsValidAddresses(self, asys):NEWLINE import stringNEWLINE addresses = [asys.createActor(Juliet) for n in range(100)]NEWLINE for addr in addresses:NEWLINE invchar = ''.join([c for c in str(addr)NEWLINE if c not in string.ascii_letters + string.digits + "-~/():., '|>"])NEWLINE assert str(addr) == str(addr) + invchar # invchar should be blankNEWLINE if asys.base_name.startswith('multiprocUDP'):NEWLINE # Normally the asys.shutdown() following this test willNEWLINE # shutdown all actors, but for the multiprocUDP base, theNEWLINE # ActorSystem (and logger) process are left behind becauseNEWLINE # UDP does not have guaranteed delivery and 100 processesNEWLINE # sending a UDP message to the ActorSystem nearlyNEWLINE # simultaneously overloads and drops packets. Use a moreNEWLINE # regulated shutdown here for UDP to avoid this overflowNEWLINE # (which does not hurt anything but leaves actor processesNEWLINE # behind).NEWLINE per_loop = 10NEWLINE for ii in range(0, len(addresses), per_loop):NEWLINE for jj in range(ii, ii + per_loop):NEWLINE asys.tell(addresses[jj], ActorExitRequest())NEWLINE time.sleep(0.25)NEWLINENEWLINE def test07_SingleNonListeningActorTell(self, asys):NEWLINE rosalineA = asys.createActor(rosaline)NEWLINE # rosaline does not override the receiveMessage method, so theNEWLINE # Actor default method will throw an exception. This willNEWLINE # Kill the rosaline Actor. It's a top level Actor, so it willNEWLINE # not be restarted. This will cause the 'hello' message to beNEWLINE # delivered to the DeadLetterBox. Verify that no exceptionNEWLINE # makes its way out of the ActorSystem here.NEWLINE asys.tell(rosalineA, 'hello')NEWLINE assert TrueNEWLINENEWLINE def test08_SingleActorTell(self, asys):NEWLINE romeoA = asys.createActor(Romeo)NEWLINE asys.tell(romeoA, 'hello')NEWLINE # Nothing much happens, Romeo is smitten and has no time for trivialities, butNEWLINE # he will try to generate str() of himself.NEWLINENEWLINE def test09_SingleActorAsk(self, asys):NEWLINE romeoA = asys.createActor(Romeo)NEWLINE resp = asys.ask(romeoA, 'O Romeo, Romeo! wherefore art thou Romeo?', 1)NEWLINE assert resp, 'Shall I hear more == or shall I speak at this?'NEWLINENEWLINE def test10_ActorAskWithNoResponse(self, asys):NEWLINE romeoA = asys.createActor(Romeo)NEWLINE # This test is possibly unique to the simpleSystemBase, whichNEWLINE # will run an process all messages on an ask (or tell) call.NEWLINE # Properly there is no way to determine if an answer isNEWLINE # forthcoming from an asynchronous system, so all this can doNEWLINE # is assert that there is no response within a particular timeNEWLINE # period. At this point, timing is not supported, so thisNEWLINE # test is underspecified and assumptive.NEWLINE resp = asys.ask(romeoA, "What's in a name? That which we call a rose", 1.5)NEWLINE assert resp is NoneNEWLINE # Now verify that the Actor and system are still alive and operating normally.NEWLINE resp = asys.ask(romeoA, 'O Romeo, Romeo! wherefore art thou Romeo?', 1)NEWLINE assert resp, 'Shall I hear more == or shall I speak at this?'NEWLINENEWLINE def test11_SingleActorAskMultipleTimes(self, asys):NEWLINE romeoA = asys.createActor(Romeo)NEWLINE r = asys.ask(romeoA, 'O Romeo, Romeo! wherefore art thou Romeo?', 1)NEWLINE assert r == 'Shall I hear more, or shall I speak at this?'NEWLINE r = asys.ask(romeoA, 'O Romeo, Romeo! wherefore art thou Romeo?', 1)NEWLINE assert r == 'Shall I hear more, or shall I speak at this?'NEWLINE r = asys.ask(romeoA, 'Ay me!', 1)NEWLINE assert r == 'She speaks!'NEWLINE r = asys.ask(romeoA, 'O Romeo, Romeo! wherefore art thou Romeo?', 1)NEWLINE assert r == 'Shall I hear more, or shall I speak at this?'NEWLINENEWLINE def test12_MultipleActorsAskMultipleTimes(self, asys):NEWLINE romeo = asys.createActor(Romeo)NEWLINE r = asys.ask(romeo, 'O Romeo, Romeo! wherefore art thou Romeo?', 1)NEWLINE assert r == 'Shall I hear more, or shall I speak at this?'NEWLINE juliet = asys.createActor(Juliet)NEWLINE r = asys.ask(romeo, 'O Romeo, Romeo! wherefore art thou Romeo?', 1)NEWLINE assert r == 'Shall I hear more, or shall I speak at this?'NEWLINE r = asys.ask(romeo, 'Ay me!', 1)NEWLINE assert r == 'She speaks!'NEWLINE r = asys.ask(juliet, 'She speaks!', 1)NEWLINE assert r == 'O Romeo, Romeo! wherefore art thou Romeo?'NEWLINE r = asys.ask(romeo, 'Ay me!', 1)NEWLINE assert r == 'She speaks!'NEWLINE r = asys.ask(juliet, "Do you know what light that is?", 1)NEWLINE assert r == 'Ay me!'NEWLINENEWLINE def test13_SubActorCreation(self, asys):NEWLINE capulet = asys.createActor(Capulet)NEWLINE juliet = asys.ask(capulet, 'has a daughter?', 2.5)NEWLINE print ('Juliet is: %s'%str(juliet))NEWLINE assert juliet is not NoneNEWLINE if juliet:NEWLINE r = asys.ask(juliet, 'what light?')NEWLINE assert r == 'Ay me!', 0.75NEWLINE juliet2 = asys.ask(capulet, 'has a daughter?', 1)NEWLINE assert juliet2 is not NoneNEWLINE if juliet2:NEWLINE r = asys.ask(juliet2, 'what light?', 0.5)NEWLINE assert r == 'Ay me!'NEWLINE r = asys.ask(juliet, 'what light?', 0.5)NEWLINE assert r == 'Ay me!'NEWLINENEWLINE def test14_EntireActWithActorStart(self, asys):NEWLINE romeo = asys.createActor(Romeo)NEWLINE juliet = asys.createActor(Juliet)NEWLINE nurse = asys.createActor(Nurse)NEWLINE assert asys.ask(nurse, 'done?', 1) == 'not yet'NEWLINE asys.tell(nurse, ('begin', romeo, juliet))NEWLINENEWLINE for X in range(50):NEWLINE if asys.ask(nurse, 'done?', 1) == 'Fini':NEWLINE breakNEWLINE time.sleep(0.01) # Allow some time for the entire actNEWLINE r = asys.ask(nurse, 'done?', 1)NEWLINE assert r == 'Fini'NEWLINENEWLINE def test15_IncompleteActMissingActor(self, asys):NEWLINE romeo = asys.createActor(Romeo)NEWLINE juliet = asys.createActor(Juliet)NEWLINE # no nurse actor createdNEWLINE asys.tell(romeo, JulietAppears(juliet))NEWLINE # No error should occur here when Juliet reaches the end andNEWLINE # doesn't have a nurse to tell.NEWLINENEWLINE time.sleep(0.05) # Allow some time for the entire actNEWLINENEWLINE # Now create the nurse and tell her to talk to romeo andNEWLINE # juliet, which should cause completionNEWLINE nurse = asys.createActor(Nurse)NEWLINE r = asys.ask(nurse, 'done?', 1)NEWLINE assert r == 'not yet'NEWLINE asys.tell(nurse, ('begin', romeo, juliet))NEWLINENEWLINE for X in range(50):NEWLINE if asys.ask(nurse, 'done?', 1) == 'Fini':NEWLINE breakNEWLINE time.sleep(0.01) # Allow some time for the entire actNEWLINE r = asys.ask(nurse, 'done?', 1)NEWLINE assert r == 'Fini'NEWLINENEWLINE def test16_ActorProperties(self, asys):NEWLINE romeo = asys.createActor(Romeo)NEWLINE juliet = asys.createActor(Juliet)NEWLINENEWLINE r = asys.ask(romeo, 'who_are_you', 0.25)NEWLINE assert r is not NoneNEWLINE r = asys.ask(juliet, 'who_are_you', 0.25)NEWLINE assert r is not NoneNEWLINE r1 = asys.ask(romeo, 'who_are_you', 0.25)NEWLINE r2 = asys.ask(juliet, 'who_are_you', 0.25)NEWLINE assert r1 != r2NEWLINE import yamlNEWLINEimport typesNEWLINEimport pandas as pdNEWLINEfrom Handler.mongo_handler import MongoHandlerNEWLINEfrom Utils.utils import LogNEWLINEyaml.warnings({'YAMLLoadWarning': False})NEWLINEwith open("config.yaml", "rt", encoding="utf-8") as stream:NEWLINE CONFIG = yaml.load(stream)['StockCrawler']NEWLINENEWLINENEWLINEclass DataHandler:NEWLINE def __init__(self):NEWLINE self.log = Log(DataHandler)NEWLINE self.mongo = MongoHandler()NEWLINE self.company_info = NoneNEWLINE self.company_list = NoneNEWLINENEWLINE check_target_location = CONFIG['company_name_location']NEWLINE if check_target_location == 'DB':NEWLINE self.get_target_company = types.MethodType(self._get_company_by_mongo, self)NEWLINE elif check_target_location == 'File':NEWLINE self.get_target_company = types.MethodType(self._get_company_by_file, self)NEWLINENEWLINE def get_target_company(self):NEWLINE passNEWLINENEWLINE def save_stock_data(self, stock_df):NEWLINE self.mongo.update_stock_data(stock_df)NEWLINENEWLINE def _get_company_by_mongo(self, obj):NEWLINE self.log.debug("Get company information by database(MongoDB)")NEWLINE self.company_info = pd.DataFrame(self.mongo.get_company())NEWLINE self.company_list = self.company_info[['company', 'code']]NEWLINENEWLINE def _get_company_by_file(self, obj):NEWLINE passNEWLINE # Copyright 2020 Google LLC. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE"""Tests for tfx.orchestration.portable.cache_utils."""NEWLINEimport osNEWLINEimport tensorflow as tfNEWLINENEWLINEfrom tfx.dsl.io import fileioNEWLINEfrom tfx.orchestration import metadataNEWLINEfrom tfx.orchestration.portable import cache_utilsNEWLINEfrom tfx.orchestration.portable import execution_publish_utilsNEWLINEfrom tfx.orchestration.portable.mlmd import context_libNEWLINEfrom tfx.proto.orchestration import pipeline_pb2NEWLINEfrom tfx.types import standard_artifactsNEWLINEfrom tfx.utils import test_case_utilsNEWLINEfrom google.protobuf import text_formatNEWLINEfrom ml_metadata.proto import metadata_store_pb2NEWLINENEWLINENEWLINEclass CacheUtilsTest(test_case_utils.TfxTest):NEWLINENEWLINE def setUp(self):NEWLINE super().setUp()NEWLINE self._connection_config = metadata_store_pb2.ConnectionConfig()NEWLINE self._connection_config.sqlite.SetInParent()NEWLINE self._module_file_path = os.path.join(self.tmp_dir, 'module_file')NEWLINE self._input_artifacts = {'input_examples': [standard_artifacts.Examples()]}NEWLINE self._output_artifacts = {'output_models': [standard_artifacts.Model()]}NEWLINE self._parameters = {'module_file': self._module_file_path}NEWLINE self._module_file_content = 'module content'NEWLINE self._pipeline_node = text_format.Parse(NEWLINE """NEWLINE executor {NEWLINE python_class_executor_spec {class_path: 'a.b.c'}NEWLINE }NEWLINE """, pipeline_pb2.PipelineNode())NEWLINE self._executor_class_path = 'a.b.c'NEWLINE self._pipeline_info = pipeline_pb2.PipelineInfo(id='pipeline_id')NEWLINENEWLINE def _get_cache_context(self,NEWLINE metadata_handler,NEWLINE custom_pipeline_node=None,NEWLINE custom_pipeline_info=None,NEWLINE custom_input_artifacts=None,NEWLINE custom_output_artifacts=None,NEWLINE custom_parameters=None,NEWLINE custom_module_content=None):NEWLINE with fileio.open(self._module_file_path, 'w+') as f:NEWLINE f.write(custom_module_content or self._module_file_content)NEWLINE return cache_utils.get_cache_context(NEWLINE metadata_handler,NEWLINE custom_pipeline_node or self._pipeline_node,NEWLINE custom_pipeline_info or self._pipeline_info,NEWLINE input_artifacts=(custom_input_artifacts or self._input_artifacts),NEWLINE output_artifacts=(custom_output_artifacts or self._output_artifacts),NEWLINE parameters=(custom_parameters or self._parameters))NEWLINENEWLINE def testGetCacheContext(self):NEWLINE with metadata.Metadata(connection_config=self._connection_config) as m:NEWLINE cache_context = self._get_cache_context(m)NEWLINE [context_from_mlmd] = m.store.get_contexts()NEWLINE self.assertProtoPartiallyEquals(NEWLINE cache_context,NEWLINE context_from_mlmd,NEWLINE ignored_fields=[NEWLINE 'create_time_since_epoch', 'last_update_time_since_epoch'NEWLINE ])NEWLINENEWLINE def testGetCacheContextTwiceSameArgs(self):NEWLINE with metadata.Metadata(connection_config=self._connection_config) as m:NEWLINE self._get_cache_context(m)NEWLINE self._get_cache_context(m)NEWLINE # Same args should not create a new cache context.NEWLINE self.assertLen(m.store.get_contexts(), 1)NEWLINENEWLINE def testGetCacheContextTwiceDifferentOutputUri(self):NEWLINE with metadata.Metadata(connection_config=self._connection_config) as m:NEWLINE self._get_cache_context(m)NEWLINE output_model_different_uri = standard_artifacts.Model()NEWLINE output_model_different_uri.uri = 'diff_uri'NEWLINE self._get_cache_context(NEWLINE m,NEWLINE custom_output_artifacts={NEWLINE 'output_models': [output_model_different_uri]NEWLINE })NEWLINE # Only different output uri should not create a new cache context.NEWLINE self.assertLen(m.store.get_contexts(), 1)NEWLINENEWLINE def testGetCacheContextTwiceDifferentOutputs(self):NEWLINE with metadata.Metadata(connection_config=self._connection_config) as m:NEWLINE self._get_cache_context(m)NEWLINE self._get_cache_context(NEWLINE m, custom_output_artifacts={'k': [standard_artifacts.Model()]})NEWLINE # Different output skeleton will result in a new cache context.NEWLINE self.assertLen(m.store.get_contexts(), 2)NEWLINENEWLINE def testGetCacheContextTwiceDifferentInputs(self):NEWLINE with metadata.Metadata(connection_config=self._connection_config) as m:NEWLINE self._get_cache_context(m)NEWLINE self._get_cache_context(NEWLINE m, custom_input_artifacts={'k': [standard_artifacts.Examples(),]})NEWLINE # Different input artifacts will result in new cache context.NEWLINE self.assertLen(m.store.get_contexts(), 2)NEWLINENEWLINE def testGetCacheContextTwiceDifferentParameters(self):NEWLINE with metadata.Metadata(connection_config=self._connection_config) as m:NEWLINE self._get_cache_context(m)NEWLINE self._get_cache_context(m, custom_parameters={'new_prop': 'value'})NEWLINE # Different parameters will result in new cache context.NEWLINE self.assertLen(m.store.get_contexts(), 2)NEWLINENEWLINE def testGetCacheContextTwiceDifferentModuleContent(self):NEWLINE with metadata.Metadata(connection_config=self._connection_config) as m:NEWLINE self._get_cache_context(m)NEWLINE self._get_cache_context(m, custom_module_content='new module content')NEWLINE # Different module file content will result in new cache context.NEWLINE self.assertLen(m.store.get_contexts(), 2)NEWLINENEWLINE def testGetCacheContextTwiceDifferentPipelineInfo(self):NEWLINE with metadata.Metadata(connection_config=self._connection_config) as m:NEWLINE self._get_cache_context(m)NEWLINE self._get_cache_context(NEWLINE m, custom_pipeline_info=pipeline_pb2.PipelineInfo(id='new_id'))NEWLINE # Different pipeline info will result in new cache context.NEWLINE self.assertLen(m.store.get_contexts(), 2)NEWLINENEWLINE def testGetCacheContextTwiceDifferentExecutorSpec(self):NEWLINE with metadata.Metadata(connection_config=self._connection_config) as m:NEWLINE self._get_cache_context(m)NEWLINE self._get_cache_context(NEWLINE m,NEWLINE custom_pipeline_node=text_format.Parse(NEWLINE """NEWLINE executor {NEWLINE python_class_executor_spec {class_path: 'n.e.w'}NEWLINE }NEWLINE """, pipeline_pb2.PipelineNode()))NEWLINE # Different executor spec will result in new cache context.NEWLINE self.assertLen(m.store.get_contexts(), 2)NEWLINENEWLINE def testGetCachedOutputArtifacts(self):NEWLINE # Output artifacts that will be used by the first execution with the sameNEWLINE # cache key.NEWLINE output_model_one = standard_artifacts.Model()NEWLINE output_model_one.uri = 'model_one'NEWLINE output_model_two = standard_artifacts.Model()NEWLINE output_model_two.uri = 'model_two'NEWLINE output_example_one = standard_artifacts.Examples()NEWLINE output_example_one.uri = 'example_one'NEWLINE # Output artifacts that will be used by the second execution with the sameNEWLINE # cache key.NEWLINE output_model_three = standard_artifacts.Model()NEWLINE output_model_three.uri = 'model_three'NEWLINE output_model_four = standard_artifacts.Model()NEWLINE output_model_four.uri = 'model_four'NEWLINE output_example_two = standard_artifacts.Examples()NEWLINE output_example_two.uri = 'example_two'NEWLINE output_models_key = 'output_models'NEWLINE output_examples_key = 'output_examples'NEWLINE with metadata.Metadata(connection_config=self._connection_config) as m:NEWLINE cache_context = context_lib.register_context_if_not_exists(NEWLINE m, context_lib.CONTEXT_TYPE_EXECUTION_CACHE, 'cache_key')NEWLINE execution_one = execution_publish_utils.register_execution(NEWLINE m, metadata_store_pb2.ExecutionType(name='my_type'), [cache_context])NEWLINE execution_publish_utils.publish_succeeded_execution(NEWLINE m,NEWLINE execution_one.id, [cache_context],NEWLINE output_artifacts={NEWLINE output_models_key: [output_model_one, output_model_two],NEWLINE output_examples_key: [output_example_one]NEWLINE })NEWLINE execution_two = execution_publish_utils.register_execution(NEWLINE m, metadata_store_pb2.ExecutionType(name='my_type'), [cache_context])NEWLINE output_artifacts = execution_publish_utils.publish_succeeded_execution(NEWLINE m,NEWLINE execution_two.id, [cache_context],NEWLINE output_artifacts={NEWLINE output_models_key: [output_model_three, output_model_four],NEWLINE output_examples_key: [output_example_two]NEWLINE })NEWLINE # The cached output got should be the artifacts produced by the mostNEWLINE # recent execution under the given cache context.NEWLINE cached_output = cache_utils.get_cached_outputs(m, cache_context)NEWLINE self.assertLen(cached_output, 2)NEWLINE self.assertLen(cached_output[output_models_key], 2)NEWLINE self.assertLen(cached_output[output_examples_key], 1)NEWLINE self.assertProtoPartiallyEquals(NEWLINE cached_output[output_models_key][0].mlmd_artifact,NEWLINE output_artifacts[output_models_key][0].mlmd_artifact,NEWLINE ignored_fields=[NEWLINE 'create_time_since_epoch', 'last_update_time_since_epoch'NEWLINE ])NEWLINE self.assertProtoPartiallyEquals(NEWLINE cached_output[output_models_key][1].mlmd_artifact,NEWLINE output_artifacts[output_models_key][1].mlmd_artifact,NEWLINE ignored_fields=[NEWLINE 'create_time_since_epoch', 'last_update_time_since_epoch'NEWLINE ])NEWLINE self.assertProtoPartiallyEquals(NEWLINE cached_output[output_examples_key][0].mlmd_artifact,NEWLINE output_artifacts[output_examples_key][0].mlmd_artifact,NEWLINE ignored_fields=[NEWLINE 'create_time_since_epoch', 'last_update_time_since_epoch'NEWLINE ])NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE tf.test.main()NEWLINE """NEWLINEThe script is for creating a new graphml including nodes and edges NEWLINEbased on the subset geopackage created by "sv_createSubsetData.py".NEWLINEThis can reduce the volume of graphml, which can reduce the usage of memory in pc and NEWLINEimprove performace.NEWLINENEWLINE"""NEWLINEimport osmnx as oxNEWLINEimport networkx as nxNEWLINEimport osNEWLINEimport pandas as pdNEWLINEimport geopandas as gpdNEWLINEimport timeNEWLINENEWLINENEWLINEdef creatSubGraph(graphPath, gpkg_path, graphOutput):NEWLINE print('read original grapml, and save nodes and edges to geopackage.')NEWLINE G = ox.load_graphml(graphPath)NEWLINE nodes, edges = ox.graph_to_gdfs(G)NEWLINE # nodes = nodes.astype(str)NEWLINE columns = edges.columns.tolist()NEWLINE columns.remove('geometry')NEWLINE edges[columns] = edges[columns].astype(str)NEWLINE nodes.to_file(gpkg_path, layer='nodes_original', driver='GPKG')NEWLINE edges.to_file(gpkg_path, layer='edges_original', driver='GPKG')NEWLINE # sp = gpd.read_file(gpkg_path, layer='urban_sample_points')NEWLINE # nodesIds = pd.concat([sp.n1, sp.n2])NEWLINE # node_drop = nodesIds.drop_duplicates()NEWLINE # nodes = node_drop.tolist()NEWLINE # nodes_int = list(map(int, nodes))NEWLINE print('select nodes within study region buffer.')NEWLINE region_buffer = gpd.read_file(gpkg_path,NEWLINE layer='urban_study_region_buffered')NEWLINE nodes_withinbuffer = gpd.sjoin(nodes,NEWLINE region_buffer,NEWLINE how='inner',NEWLINE op='within')NEWLINE nodes_withinbuffer = nodes_withinbuffer.drop_duplicates(subset='osmid')NEWLINE nodesIds = nodes_withinbuffer.osmid.tolist()NEWLINE nodes_int = list(map(int, nodesIds))NEWLINE print('create sub grapml.')NEWLINE G_sub = G.subgraph(nodes_int).copy()NEWLINE # print(G_sub.nodes)NEWLINE print('save sub nodes and edges to geopackage.')NEWLINE nodes_sub, edges_sub = ox.graph_to_gdfs(G_sub)NEWLINE # nodes_sub = nodes_sub.astype(str)NEWLINE cols = edges_sub.columns.tolist()NEWLINE cols.remove('geometry')NEWLINE edges_sub[cols] = edges_sub[cols].astype(str)NEWLINE nodes_sub.to_file(gpkg_path, layer='nodes_subset', driver='GPKG')NEWLINE edges_sub.to_file(gpkg_path, layer='edges_subset', driver='GPKG')NEWLINE del nodes, edgesNEWLINE del edges_sub, nodes_subNEWLINE ox.save_graphml(G_sub,NEWLINE filename=graphOutput,NEWLINE folder=os.path.join(dirname, 'data'))NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE startTime = time.time()NEWLINE print('begin to process')NEWLINE dirname = os.path.abspath('')NEWLINE graph_path = os.path.join(NEWLINE dirname,NEWLINE 'data/phoenix_us_2019_10000m_pedestrian_osm_20190902_proj.graphml')NEWLINE gpkg_path = os.path.join(dirname,NEWLINE 'data/phoenix_us_2019_subset.gpkg')NEWLINE graph_output = 'phoenix_us_2019_10000m_pedestrian_osm_20190902_proj_subset.graphml'NEWLINE creatSubGraph(graph_path, gpkg_path, graph_output)NEWLINE print("finished, time is {}".format(time.time() - startTime)) #!/usr/bin/pythonNEWLINE#NEWLINE# Copyright: Ansible ProjectNEWLINE# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)NEWLINENEWLINEfrom __future__ import absolute_import, division, print_functionNEWLINE__metaclass__ = typeNEWLINENEWLINEANSIBLE_METADATA = {'metadata_version': '1.1',NEWLINE 'status': ['preview'],NEWLINE 'supported_by': 'community'}NEWLINENEWLINEDOCUMENTATION = '''NEWLINE---NEWLINEmodule: onyx_vlanNEWLINEauthor: "Samer Deeb (@samerd) Alex Tabachnik (@atabachnik)"NEWLINEshort_description: Manage VLANs on Mellanox ONYX network devicesNEWLINEdescription:NEWLINE - This module provides declarative management of VLANsNEWLINE on Mellanox ONYX network devices.NEWLINEoptions:NEWLINE name:NEWLINE description:NEWLINE - Name of the VLAN.NEWLINE vlan_id:NEWLINE description:NEWLINE - ID of the VLAN.NEWLINE aggregate:NEWLINE description: List of VLANs definitions.NEWLINE purge:NEWLINE description:NEWLINE - Purge VLANs not defined in the I(aggregate) parameter.NEWLINE default: noNEWLINE type: boolNEWLINE state:NEWLINE description:NEWLINE - State of the VLAN configuration.NEWLINE default: presentNEWLINE choices: ['present', 'absent']NEWLINE'''NEWLINENEWLINEEXAMPLES = """NEWLINE- name: configure VLAN ID and nameNEWLINE onyx_vlan:NEWLINE vlan_id: 20NEWLINE name: test-vlanNEWLINENEWLINE- name: remove configurationNEWLINE onyx_vlan:NEWLINE state: absentNEWLINE"""NEWLINENEWLINERETURN = """NEWLINEcommands:NEWLINE description: The list of configuration mode commands to send to the deviceNEWLINE returned: always.NEWLINE type: listNEWLINE sample:NEWLINE - vlan 20NEWLINE - name test-vlanNEWLINE - exitNEWLINE"""NEWLINENEWLINEfrom copy import deepcopyNEWLINENEWLINEfrom ansible.module_utils.basic import AnsibleModuleNEWLINEfrom ansible.module_utils.six import iteritemsNEWLINEfrom ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import remove_default_specNEWLINENEWLINEfrom ansible_collections.community.general.plugins.module_utils.network.onyx.onyx import BaseOnyxModuleNEWLINEfrom ansible_collections.community.general.plugins.module_utils.network.onyx.onyx import show_cmdNEWLINENEWLINENEWLINEclass OnyxVlanModule(BaseOnyxModule):NEWLINE _purge = FalseNEWLINENEWLINE @classmethodNEWLINE def _get_element_spec(cls):NEWLINE return dict(NEWLINE vlan_id=dict(type='int'),NEWLINE name=dict(type='str'),NEWLINE state=dict(default='present', choices=['present', 'absent']),NEWLINE )NEWLINENEWLINE @classmethodNEWLINE def _get_aggregate_spec(cls, element_spec):NEWLINE aggregate_spec = deepcopy(element_spec)NEWLINE aggregate_spec['vlan_id'] = dict(required=True)NEWLINENEWLINE # remove default in aggregate spec, to handle common argumentsNEWLINE remove_default_spec(aggregate_spec)NEWLINE return aggregate_specNEWLINENEWLINE def init_module(self):NEWLINE """ module initializationNEWLINE """NEWLINE element_spec = self._get_element_spec()NEWLINE aggregate_spec = self._get_aggregate_spec(element_spec)NEWLINE argument_spec = dict(NEWLINE aggregate=dict(type='list', elements='dict',NEWLINE options=aggregate_spec),NEWLINE purge=dict(default=False, type='bool'),NEWLINE )NEWLINE argument_spec.update(element_spec)NEWLINE required_one_of = [['vlan_id', 'aggregate']]NEWLINE mutually_exclusive = [['vlan_id', 'aggregate']]NEWLINE self._module = AnsibleModule(NEWLINE argument_spec=argument_spec,NEWLINE required_one_of=required_one_of,NEWLINE mutually_exclusive=mutually_exclusive,NEWLINE supports_check_mode=True)NEWLINENEWLINE def validate_vlan_id(self, value):NEWLINE if value and not 1 <= int(value) <= 4094:NEWLINE self._module.fail_json(msg='vlan id must be between 1 and 4094')NEWLINENEWLINE def get_required_config(self):NEWLINE self._required_config = list()NEWLINE module_params = self._module.paramsNEWLINE aggregate = module_params.get('aggregate')NEWLINE self._purge = module_params.get('purge', False)NEWLINE if aggregate:NEWLINE for item in aggregate:NEWLINE for key in item:NEWLINE if item.get(key) is None:NEWLINE item[key] = module_params[key]NEWLINE self.validate_param_values(item, item)NEWLINE req_item = item.copy()NEWLINE req_item['vlan_id'] = int(req_item['vlan_id'])NEWLINE self._required_config.append(req_item)NEWLINE else:NEWLINE params = {NEWLINE 'vlan_id': module_params['vlan_id'],NEWLINE 'name': module_params['name'],NEWLINE 'state': module_params['state'],NEWLINE }NEWLINE self.validate_param_values(params)NEWLINE self._required_config.append(params)NEWLINENEWLINE def _create_vlan_data(self, vlan_id, vlan_data):NEWLINE if self._os_version >= self.ONYX_API_VERSION:NEWLINE vlan_data = vlan_data[0]NEWLINE return {NEWLINE 'vlan_id': vlan_id,NEWLINE 'name': self.get_config_attr(vlan_data, 'Name')NEWLINE }NEWLINENEWLINE def _get_vlan_config(self):NEWLINE return show_cmd(self._module, "show vlan")NEWLINENEWLINE def load_current_config(self):NEWLINE # called in base class in run functionNEWLINE self._os_version = self._get_os_version()NEWLINE self._current_config = dict()NEWLINE vlan_config = self._get_vlan_config()NEWLINE if not vlan_config:NEWLINE returnNEWLINE for vlan_id, vlan_data in iteritems(vlan_config):NEWLINE try:NEWLINE vlan_id = int(vlan_id)NEWLINE except ValueError:NEWLINE continueNEWLINE self._current_config[vlan_id] = \NEWLINE self._create_vlan_data(vlan_id, vlan_data)NEWLINENEWLINE def generate_commands(self):NEWLINE req_vlans = set()NEWLINE for req_conf in self._required_config:NEWLINE state = req_conf['state']NEWLINE vlan_id = req_conf['vlan_id']NEWLINE if state == 'absent':NEWLINE if vlan_id in self._current_config:NEWLINE self._commands.append('no vlan %s' % vlan_id)NEWLINE else:NEWLINE req_vlans.add(vlan_id)NEWLINE self._generate_vlan_commands(vlan_id, req_conf)NEWLINE if self._purge:NEWLINE for vlan_id in self._current_config:NEWLINE if vlan_id not in req_vlans:NEWLINE self._commands.append('no vlan %s' % vlan_id)NEWLINENEWLINE def _generate_vlan_commands(self, vlan_id, req_conf):NEWLINE curr_vlan = self._current_config.get(vlan_id, {})NEWLINE if not curr_vlan:NEWLINE self._commands.append("vlan %s" % vlan_id)NEWLINE self._commands.append("exit")NEWLINE req_name = req_conf['name']NEWLINE curr_name = curr_vlan.get('name')NEWLINE if req_name:NEWLINE if req_name != curr_name:NEWLINE self._commands.append("vlan %s name %s" % (vlan_id, req_name))NEWLINE elif req_name is not None:NEWLINE if curr_name:NEWLINE self._commands.append("vlan %s no name" % vlan_id)NEWLINENEWLINENEWLINEdef main():NEWLINE """ main entry point for module executionNEWLINE """NEWLINE OnyxVlanModule.main()NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE main()NEWLINE def isMatch(s: str, p: str) -> bool:NEWLINE m, n = len(s), len(p)NEWLINE dp = [[False] * (n + 1) for _ in range(m + 1)]NEWLINE dp[0][0] = TrueNEWLINE for i in range(1, n + 1):NEWLINE if p[i - 1] == "*":NEWLINE dp[0][i] = TrueNEWLINE else:NEWLINE breakNEWLINENEWLINE for i in range(1, m + 1):NEWLINE for j in range(1, n + 1):NEWLINE if p[j - 1] == "*":NEWLINE dp[i][j] = dp[i][j - 1] | dp[i - 1][j]NEWLINE elif p[j - 1] == "?" or s[i - 1] == p[j - 1]:NEWLINE dp[i][j] = dp[i - 1][j - 1]NEWLINE return dp[m][n]NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE s = "adceb"NEWLINE p = "*a*b"NEWLINE result = isMatch(s,p)NEWLINE print(result)NEWLINE # -*- coding: utf-8 -*-NEWLINE# Generated by Django 1.10.5 on 2017-11-03 13:12NEWLINEfrom __future__ import unicode_literalsNEWLINENEWLINEfrom django.db import migrations, modelsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ('main', '0003_profile'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.AlterField(NEWLINE model_name='medication',NEWLINE name='img_path',NEWLINE field=models.CharField(max_length=200, null=True),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name='medication',NEWLINE name='title',NEWLINE field=models.CharField(max_length=200, unique=True),NEWLINE ),NEWLINE ]NEWLINE """This is the one place the version number is stored."""NEWLINENEWLINE__version__ = '0.5.1'NEWLINE import torchNEWLINENEWLINEfrom .resnet import NormalizationNEWLINEfrom .preact_resnet import preact_resnetNEWLINEfrom .resnet import resnetNEWLINEfrom .wideresnet import wideresnetNEWLINENEWLINEfrom .preact_resnetwithswish import preact_resnetwithswishNEWLINEfrom .wideresnetwithswish import wideresnetwithswishNEWLINENEWLINEfrom core.data import DATASETSNEWLINENEWLINENEWLINEMODELS = ['resnet18', 'resnet34', 'resnet50', 'resnet101', NEWLINE 'preact-resnet18', 'preact-resnet34', 'preact-resnet50', 'preact-resnet101', NEWLINE 'wrn-28-10', 'wrn-32-10', 'wrn-34-10', 'wrn-34-20', NEWLINE 'preact-resnet18-swish', 'preact-resnet34-swish',NEWLINE 'wrn-28-10-swish', 'wrn-34-20-swish', 'wrn-70-16-swish']NEWLINENEWLINENEWLINEdef create_model(name, normalize, info, device):NEWLINE """NEWLINE Returns suitable model from its name.NEWLINE Arguments:NEWLINE name (str): name of resnet architecture.NEWLINE normalize (bool): normalize input.NEWLINE info (dict): dataset information.NEWLINE device (str or torch.device): device to work on.NEWLINE Returns:NEWLINE torch.nn.Module.NEWLINE """NEWLINE if info['data'] in ['tiny-imagenet']:NEWLINE assert 'preact-resnet' in name, 'Only preact-resnets are supported for this dataset!'NEWLINE from .ti_preact_resnet import ti_preact_resnetNEWLINE backbone = ti_preact_resnet(name, num_classes=info['num_classes'], device=device)NEWLINE NEWLINE elif info['data'] in DATASETS and info['data'] not in ['tiny-imagenet']:NEWLINE if 'preact-resnet' in name and 'swish' not in name:NEWLINE backbone = preact_resnet(name, num_classes=info['num_classes'], pretrained=False, device=device)NEWLINE elif 'preact-resnet' in name and 'swish' in name:NEWLINE backbone = preact_resnetwithswish(name, dataset=info['data'], num_classes=info['num_classes'])NEWLINE elif 'resnet' in name and 'preact' not in name:NEWLINE backbone = resnet(name, num_classes=info['num_classes'], pretrained=False, device=device)NEWLINE elif 'wrn' in name and 'swish' not in name:NEWLINE backbone = wideresnet(name, num_classes=info['num_classes'], device=device)NEWLINE elif 'wrn' in name and 'swish' in name:NEWLINE backbone = wideresnetwithswish(name, dataset=info['data'], num_classes=info['num_classes'], device=device)NEWLINE else:NEWLINE raise ValueError('Invalid model name {}!'.format(name))NEWLINE NEWLINE else:NEWLINE raise ValueError('Models for {} not yet supported!'.format(info['data']))NEWLINE NEWLINE if normalize:NEWLINE model = torch.nn.Sequential(Normalization(info['mean'], info['std']), backbone)NEWLINE else:NEWLINE model = torch.nn.Sequential(backbone)NEWLINE NEWLINE model = torch.nn.DataParallel(model)NEWLINE model = model.to(device)NEWLINE return modelNEWLINE # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and ContributorsNEWLINE# MIT License. See license.txtNEWLINEfrom __future__ import unicode_literalsNEWLINENEWLINEimport frappe, unittestNEWLINENEWLINEfrom frappe.model.db_query import DatabaseQueryNEWLINEfrom frappe.desk.reportview import get_filters_condNEWLINENEWLINEclass TestReportview(unittest.TestCase):NEWLINE def test_basic(self):NEWLINE self.assertTrue({"name":"DocType"} in DatabaseQuery("DocType").execute(limit_page_length=None))NEWLINENEWLINE def test_fields(self):NEWLINE self.assertTrue({"name":"DocType", "issingle":0} \NEWLINE in DatabaseQuery("DocType").execute(fields=["name", "issingle"], limit_page_length=None))NEWLINENEWLINE def test_filters_1(self):NEWLINE self.assertFalse({"name":"DocType"} \NEWLINE in DatabaseQuery("DocType").execute(filters=[["DocType", "name", "like", "J%"]]))NEWLINENEWLINE def test_filters_2(self):NEWLINE self.assertFalse({"name":"DocType"} \NEWLINE in DatabaseQuery("DocType").execute(filters=[{"name": ["like", "J%"]}]))NEWLINENEWLINE def test_filters_3(self):NEWLINE self.assertFalse({"name":"DocType"} \NEWLINE in DatabaseQuery("DocType").execute(filters={"name": ["like", "J%"]}))NEWLINENEWLINE def test_filters_4(self):NEWLINE self.assertTrue({"name":"DocField"} \NEWLINE in DatabaseQuery("DocType").execute(filters={"name": "DocField"}))NEWLINENEWLINE def test_in_not_in_filters(self):NEWLINE self.assertFalse(DatabaseQuery("DocType").execute(filters={"name": ["in", None]}))NEWLINE self.assertTrue({"name":"DocType"} \NEWLINE in DatabaseQuery("DocType").execute(filters={"name": ["not in", None]}))NEWLINENEWLINE for result in [{"name":"DocType"}, {"name":"DocField"}]:NEWLINE self.assertTrue(resultNEWLINE in DatabaseQuery("DocType").execute(filters={"name": ["in", 'DocType,DocField']}))NEWLINENEWLINE for result in [{"name":"DocType"}, {"name":"DocField"}]:NEWLINE self.assertFalse(resultNEWLINE in DatabaseQuery("DocType").execute(filters={"name": ["not in", 'DocType,DocField']}))NEWLINENEWLINE def test_or_filters(self):NEWLINE data = DatabaseQuery("DocField").execute(NEWLINE filters={"parent": "DocType"}, fields=["fieldname", "fieldtype"],NEWLINE or_filters=[{"fieldtype":"Table"}, {"fieldtype":"Select"}])NEWLINENEWLINE self.assertTrue({"fieldtype":"Table", "fieldname":"fields"} in data)NEWLINE self.assertTrue({"fieldtype":"Select", "fieldname":"document_type"} in data)NEWLINE self.assertFalse({"fieldtype":"Check", "fieldname":"issingle"} in data)NEWLINENEWLINE def test_between_filters(self):NEWLINE """ test case to check between filter for date fields """NEWLINE frappe.db.sql("delete from tabEvent")NEWLINENEWLINE # create events to test the between operator filterNEWLINE todays_event = create_event()NEWLINE event1 = create_event(starts_on="2016-07-05 23:59:59")NEWLINE event2 = create_event(starts_on="2016-07-06 00:00:00")NEWLINE event3 = create_event(starts_on="2016-07-07 23:59:59")NEWLINE event4 = create_event(starts_on="2016-07-08 00:00:01")NEWLINENEWLINE # if the values are not passed in filters then event should be filter as current datetimeNEWLINE data = DatabaseQuery("Event").execute(NEWLINE filters={"starts_on": ["between", None]}, fields=["name"])NEWLINENEWLINE self.assertTrue({ "name": event1.name } not in data)NEWLINENEWLINE # if both from and to_date values are passedNEWLINE data = DatabaseQuery("Event").execute(NEWLINE filters={"starts_on": ["between", ["2016-07-06", "2016-07-07"]]},NEWLINE fields=["name"])NEWLINENEWLINE self.assertTrue({ "name": event2.name } in data)NEWLINE self.assertTrue({ "name": event3.name } in data)NEWLINE self.assertTrue({ "name": event1.name } not in data)NEWLINE self.assertTrue({ "name": event4.name } not in data)NEWLINENEWLINE # if only one value is passed in the filterNEWLINE data = DatabaseQuery("Event").execute(NEWLINE filters={"starts_on": ["between", ["2016-07-07"]]},NEWLINE fields=["name"])NEWLINENEWLINE self.assertTrue({ "name": event3.name } in data)NEWLINE self.assertTrue({ "name": event4.name } in data)NEWLINE self.assertTrue({ "name": todays_event.name } in data)NEWLINE self.assertTrue({ "name": event1.name } not in data)NEWLINE self.assertTrue({ "name": event2.name } not in data)NEWLINENEWLINE def test_ignore_permissions_for_get_filters_cond(self):NEWLINE frappe.set_user('test1@example.com')NEWLINE self.assertRaises(frappe.PermissionError, get_filters_cond, 'DocType', dict(istable=1), [])NEWLINE self.assertTrue(get_filters_cond('DocType', dict(istable=1), [], ignore_permissions=True))NEWLINE frappe.set_user('Administrator')NEWLINENEWLINE def test_query_fields_sanitizer(self):NEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name", "issingle, version()"], limit_start=0, limit_page_length=1)NEWLINENEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name", "issingle, IF(issingle=1, (select name from tabUser), count(name))"],NEWLINE limit_start=0, limit_page_length=1)NEWLINENEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name", "issingle, (select count(*) from tabSessions)"],NEWLINE limit_start=0, limit_page_length=1)NEWLINENEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name", "issingle, SELECT LOCATE('', `tabUser`.`user`) AS user;"],NEWLINE limit_start=0, limit_page_length=1)NEWLINENEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name", "issingle, IF(issingle=1, (SELECT name from tabUser), count(*))"],NEWLINE limit_start=0, limit_page_length=1)NEWLINENEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name", "issingle ''"],limit_start=0, limit_page_length=1)NEWLINENEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name", "issingle,'"],limit_start=0, limit_page_length=1)NEWLINENEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name", "select * from tabSessions"],limit_start=0, limit_page_length=1)NEWLINENEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name", "issingle from --"],limit_start=0, limit_page_length=1)NEWLINENEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name", "issingle from tabDocType order by 2 --"],limit_start=0, limit_page_length=1)NEWLINENEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name", "1' UNION SELECT * FROM __Auth --"],limit_start=0, limit_page_length=1)NEWLINENEWLINE data = DatabaseQuery("DocType").execute(fields=["name", "issingle", "count(name)"],NEWLINE limit_start=0, limit_page_length=1)NEWLINE self.assertTrue('count(name)' in data[0])NEWLINENEWLINE data = DatabaseQuery("DocType").execute(fields=["name", "issingle", "locate('', name) as _relevance"],NEWLINE limit_start=0, limit_page_length=1)NEWLINE self.assertTrue('_relevance' in data[0])NEWLINENEWLINE data = DatabaseQuery("DocType").execute(fields=["name", "issingle", "date(creation) as creation"],NEWLINE limit_start=0, limit_page_length=1)NEWLINE self.assertTrue('creation' in data[0])NEWLINENEWLINE data = DatabaseQuery("DocType").execute(fields=["name", "issingle",NEWLINE "datediff(modified, creation) as date_diff"], limit_start=0, limit_page_length=1)NEWLINE self.assertTrue('date_diff' in data[0])NEWLINENEWLINE def test_filter_sanitizer(self):NEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name"], filters={'istable,': 1}, limit_start=0, limit_page_length=1)NEWLINENEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name"], filters={'editable_grid,': 1}, or_filters={'istable,': 1},NEWLINE limit_start=0, limit_page_length=1)NEWLINENEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name"], filters={'editable_grid,': 1},NEWLINE or_filters=[['DocType', 'istable,', '=', 1]],NEWLINE limit_start=0, limit_page_length=1)NEWLINENEWLINE self.assertRaises(frappe.DataError, DatabaseQuery("DocType").execute,NEWLINE fields=["name"], filters={'editable_grid,': 1},NEWLINE or_filters=[['DocType', 'istable', '=', 1], ['DocType', 'beta and 1=1', '=', 0]],NEWLINE limit_start=0, limit_page_length=1)NEWLINENEWLINE out = DatabaseQuery("DocType").execute(fields=["name"],NEWLINE filters={'editable_grid': 1, 'module': 'Core'},NEWLINE or_filters=[['DocType', 'istable', '=', 1]], order_by='creation')NEWLINE self.assertTrue('DocField' in [d['name'] for d in out])NEWLINENEWLINE out = DatabaseQuery("DocType").execute(fields=["name"],NEWLINE filters={'issingle': 1}, or_filters=[['DocType', 'module', '=', 'Core']],NEWLINE order_by='creation')NEWLINE self.assertTrue('User Permission for Page and Report' in [d['name'] for d in out])NEWLINENEWLINE out = DatabaseQuery("DocType").execute(fields=["name"],NEWLINE filters={'track_changes': 1, 'module': 'Core'},NEWLINE order_by='creation')NEWLINE self.assertTrue('File' in [d['name'] for d in out])NEWLINENEWLINE out = DatabaseQuery("DocType").execute(fields=["name"],NEWLINE filters=[NEWLINE ['DocType', 'ifnull(track_changes, 0)', '=', 0],NEWLINE ['DocType', 'module', '=', 'Core']NEWLINE ], order_by='creation')NEWLINE self.assertTrue('DefaultValue' in [d['name'] for d in out])NEWLINENEWLINEdef create_event(subject="_Test Event", starts_on=None):NEWLINE """ create a test event """NEWLINENEWLINE from frappe.utils import get_datetimeNEWLINENEWLINE event = frappe.get_doc({NEWLINE "doctype": "Event",NEWLINE "subject": subject,NEWLINE "event_type": "Public",NEWLINE "starts_on": get_datetime(starts_on),NEWLINE }).insert(ignore_permissions=True)NEWLINENEWLINE return eventNEWLINE # Copyright 2022 AI SingaporeNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# https://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINE"""NEWLINEAbstract Node class for all nodes.NEWLINE"""NEWLINENEWLINENEWLINE# pylint: disable=unused-importNEWLINEfrom peekingduck.pipeline.nodes.abstract_node import AbstractNodeNEWLINEfrom peekingduck.utils.deprecation import deprecateNEWLINENEWLINEdeprecate(NEWLINE "importing AbstractNode from peekingduck.pipeline.nodes.node is deprecated "NEWLINE "and will be removed in a future version. Please import from "NEWLINE "peekingduck.pipeline.nodes.abstract_node instead.",NEWLINE 3,NEWLINE)NEWLINE from sklearn.model_selection import StratifiedKFoldNEWLINEfrom scipy import sparseNEWLINEfrom skml.datasets import sample_down_label_spaceNEWLINE# liac-arffNEWLINEimport arffNEWLINEimport randomNEWLINENEWLINErandom.seed(2018)NEWLINENEWLINENEWLINEdef load_from_arff(filename, labelcount, endian="big",NEWLINE input_feature_type='float', encode_nominal=True, load_sparse=False,NEWLINE return_attribute_definitions=False):NEWLINE """Method for loading ARFF files as numpy arrayNEWLINE ParametersNEWLINE ----------NEWLINE filename : strNEWLINE path to ARFF fileNEWLINE labelcount: integerNEWLINE number of labels in the ARFF fileNEWLINE endian: str {"big", "little"} (default is "big")NEWLINE whether the ARFF file contains labels at the beginning of theNEWLINE attributes list ("big" endianness, MEKA format) or at the endNEWLINE ("little" endianness, MULAN format)NEWLINE input_feature_type: numpy.type as string (default is "float")NEWLINE the desire type of the contents of the return 'X' array-likes,NEWLINE default 'i8', should be a numpy type,NEWLINE see http://docs.scipy.org/doc/numpy/user/basics.types.htmlNEWLINE encode_nominal: bool (default is True)NEWLINE whether convert categorical data into numeric factors - requiredNEWLINE for some scikit classifiers that can't handle non-numericNEWLINE input features.NEWLINE load_sparse: boolean (default is False)NEWLINE whether to read arff file as a sparse file format, liac-arffNEWLINE breaks if sparse reading is enabled for non-sparse ARFFs.NEWLINE return_attribute_definitions: boolean (default is False)NEWLINE whether to return the definitions for each attribute in theNEWLINE datasetNEWLINE ReturnsNEWLINE -------NEWLINE X : scipy.sparseNEWLINE matrix with :code:`input_feature_type` elementsNEWLINE y: scipy.sparseNEWLINE matrix of binary label indicator matrixNEWLINE """NEWLINE matrix = NoneNEWLINENEWLINE if not load_sparse:NEWLINE arff_frame = arff.load(open(filename, 'r'),NEWLINE encode_nominal=encode_nominal,NEWLINE return_type=arff.DENSE)NEWLINE try:NEWLINE matrix = sparse.csr_matrix(NEWLINE arff_frame['data'], dtype=input_feature_type)NEWLINE except:NEWLINE print(arff_frame['data'])NEWLINE else:NEWLINE arff_frame = arff.load(open(filename, 'r'),NEWLINE encode_nominal=encode_nominal,NEWLINE return_type=arff.COO)NEWLINE data = arff_frame['data'][0]NEWLINE row = arff_frame['data'][1]NEWLINE col = arff_frame['data'][2]NEWLINE matrix = sparse.coo_matrix((data, (row, col)),NEWLINE shape=(max(row) + 1, max(col) + 1))NEWLINENEWLINE X, y = None, NoneNEWLINENEWLINE if endian == "big":NEWLINE X, y = matrix.tocsc()[:, labelcount:].tolil(), matrix.tocsc()[NEWLINE :, :labelcount].astype(int).tolil()NEWLINE elif endian == "little":NEWLINE X, y = matrix.tocsc()[NEWLINE :, :-labelcount].tolil(), matrix.tocsc()[:, -labelcount:].astype(int).tolil()NEWLINE else:NEWLINE # unknown endianNEWLINE return NoneNEWLINENEWLINE if return_attribute_definitions:NEWLINE return X, y, arff_frame['attributes']NEWLINE else:NEWLINE return X, yNEWLINENEWLINENEWLINEdef load_data(name):NEWLINE if name == 'scene':NEWLINE # src: MULANNEWLINE return load_from_arff('../data/scene/scene.arff',NEWLINE labelcount=6, endian="little")NEWLINE elif name == 'emotions':NEWLINE return load_from_arff('../data/emotions/emotions.arff',NEWLINE labelcount=6, endian="little")NEWLINE elif name == 'yeast-10':NEWLINE return load_from_arff('../data/yeast/yeast.arff',NEWLINE labelcount=14, endian="little")NEWLINE elif name == 'mediamill-10':NEWLINE return load_from_arff('../data/mediamill/mediamill.arff',NEWLINE labelcount=101, endian="little")NEWLINE elif name == 'enron-10':NEWLINE return load_from_arff('../data/enron/enron.arff',NEWLINE labelcount=53, endian="little")NEWLINE elif name == 'medical-10':NEWLINE return load_from_arff('../data/medical/medical.arff',NEWLINE labelcount=44, endian="little")NEWLINE elif name == 'slashdot-10':NEWLINE return load_from_arff('../data/slashdot/SLASHDOT-F.arff',NEWLINE labelcount=22)NEWLINE elif name == 'ohsumed-10':NEWLINE return load_from_arff('../data/ohsumed/OHSUMED-F.arff',NEWLINE labelcount=23),NEWLINE elif name == 'tmc2007-500-10':NEWLINE return load_from_arff('../data/tmc2007-500/tmc2007-500.arff',NEWLINE labelcount=22, endian="little")NEWLINE elif name == 'imdb-10':NEWLINE # head ../data/imdb/IMDB-F.arff -n 40 | grep "{0,1}" | uniq | wc -lNEWLINE return load_from_arff('../data/imdb/IMDB-F.arff',NEWLINE labelcount=28)NEWLINE else:NEWLINE raise ValueError("No such ../data set: {}".format(name))NEWLINENEWLINE """Test whether all elements of cls.args are instances of Basic. """NEWLINENEWLINE# NOTE: keep tests sorted by (module, class name) key. If a class can'tNEWLINE# be instantiated, add it here anyway with @SKIP("abstract class) (seeNEWLINE# e.g. Function).NEWLINENEWLINEimport osNEWLINEimport reNEWLINEimport warningsNEWLINEimport ioNEWLINENEWLINEfrom sympy import (Basic, S, symbols, sqrt, sin, oo, Interval, exp, Lambda, pi,NEWLINE Eq, log)NEWLINENEWLINEfrom sympy.core.compatibility import rangeNEWLINEfrom sympy.utilities.pytest import XFAIL, SKIPNEWLINEfrom sympy.utilities.exceptions import SymPyDeprecationWarningNEWLINENEWLINEx, y, z = symbols('x,y,z')NEWLINENEWLINENEWLINEdef test_all_classes_are_tested():NEWLINE this = os.path.split(__file__)[0]NEWLINE path = os.path.join(this, os.pardir, os.pardir)NEWLINE sympy_path = os.path.abspath(path)NEWLINE prefix = os.path.split(sympy_path)[0] + os.sepNEWLINENEWLINE re_cls = re.compile(r"^class ([A-Za-z][A-Za-z0-9_]*)\s*\(", re.MULTILINE)NEWLINENEWLINE modules = {}NEWLINENEWLINE for root, dirs, files in os.walk(sympy_path):NEWLINE module = root.replace(prefix, "").replace(os.sep, ".")NEWLINENEWLINE for file in files:NEWLINE if file.startswith(("_", "test_", "bench_")):NEWLINE continueNEWLINE if not file.endswith(".py"):NEWLINE continueNEWLINENEWLINE with io.open(os.path.join(root, file), "r", encoding='utf-8') as f:NEWLINE text = f.read()NEWLINENEWLINE submodule = module + '.' + file[:-3]NEWLINE names = re_cls.findall(text)NEWLINENEWLINE if not names:NEWLINE continueNEWLINENEWLINE try:NEWLINE mod = __import__(submodule, fromlist=names)NEWLINE except ImportError:NEWLINE continueNEWLINENEWLINE def is_Basic(name):NEWLINE cls = getattr(mod, name)NEWLINE if hasattr(cls, '_sympy_deprecated_func'):NEWLINE cls = cls._sympy_deprecated_funcNEWLINE return issubclass(cls, Basic)NEWLINENEWLINE names = list(filter(is_Basic, names))NEWLINENEWLINE if names:NEWLINE modules[submodule] = namesNEWLINENEWLINE ns = globals()NEWLINE failed = []NEWLINENEWLINE for module, names in modules.items():NEWLINE mod = module.replace('.', '__')NEWLINENEWLINE for name in names:NEWLINE test = 'test_' + mod + '__' + nameNEWLINENEWLINE if test not in ns:NEWLINE failed.append(module + '.' + name)NEWLINENEWLINE # reset all SymPyDeprecationWarning into errorsNEWLINE warnings.simplefilter("error", category=SymPyDeprecationWarning)NEWLINENEWLINE assert not failed, "Missing classes: %s. Please add tests for these to sympy/core/tests/test_args.py." % ", ".join(failed)NEWLINENEWLINENEWLINEdef _test_args(obj):NEWLINE return all(isinstance(arg, Basic) for arg in obj.args)NEWLINENEWLINENEWLINEdef test_sympy__assumptions__assume__AppliedPredicate():NEWLINE from sympy.assumptions.assume import AppliedPredicate, PredicateNEWLINE assert _test_args(AppliedPredicate(Predicate("test"), 2))NEWLINENEWLINEdef test_sympy__assumptions__assume__Predicate():NEWLINE from sympy.assumptions.assume import PredicateNEWLINE assert _test_args(Predicate("test"))NEWLINENEWLINEdef test_sympy__assumptions__sathandlers__UnevaluatedOnFree():NEWLINE from sympy.assumptions.sathandlers import UnevaluatedOnFreeNEWLINE from sympy import QNEWLINE assert _test_args(UnevaluatedOnFree(Q.positive))NEWLINE assert _test_args(UnevaluatedOnFree(Q.positive(x)))NEWLINE assert _test_args(UnevaluatedOnFree(Q.positive(x*y)))NEWLINENEWLINEdef test_sympy__assumptions__sathandlers__AllArgs():NEWLINE from sympy.assumptions.sathandlers import AllArgsNEWLINE from sympy import QNEWLINE assert _test_args(AllArgs(Q.positive))NEWLINE assert _test_args(AllArgs(Q.positive(x)))NEWLINE assert _test_args(AllArgs(Q.positive(x*y)))NEWLINENEWLINEdef test_sympy__assumptions__sathandlers__AnyArgs():NEWLINE from sympy.assumptions.sathandlers import AnyArgsNEWLINE from sympy import QNEWLINE assert _test_args(AnyArgs(Q.positive))NEWLINE assert _test_args(AnyArgs(Q.positive(x)))NEWLINE assert _test_args(AnyArgs(Q.positive(x*y)))NEWLINENEWLINEdef test_sympy__assumptions__sathandlers__ExactlyOneArg():NEWLINE from sympy.assumptions.sathandlers import ExactlyOneArgNEWLINE from sympy import QNEWLINE assert _test_args(ExactlyOneArg(Q.positive))NEWLINE assert _test_args(ExactlyOneArg(Q.positive(x)))NEWLINE assert _test_args(ExactlyOneArg(Q.positive(x*y)))NEWLINENEWLINEdef test_sympy__assumptions__sathandlers__CheckOldAssump():NEWLINE from sympy.assumptions.sathandlers import CheckOldAssumpNEWLINE from sympy import QNEWLINE assert _test_args(CheckOldAssump(Q.positive))NEWLINE assert _test_args(CheckOldAssump(Q.positive(x)))NEWLINE assert _test_args(CheckOldAssump(Q.positive(x*y)))NEWLINENEWLINEdef test_sympy__assumptions__sathandlers__CheckIsPrime():NEWLINE from sympy.assumptions.sathandlers import CheckIsPrimeNEWLINE from sympy import QNEWLINE # Input must be a numberNEWLINE assert _test_args(CheckIsPrime(Q.positive))NEWLINE assert _test_args(CheckIsPrime(Q.positive(5)))NEWLINENEWLINE@SKIP("abstract Class")NEWLINEdef test_sympy__codegen__ast__AugmentedAssignment():NEWLINE from sympy.codegen.ast import AugmentedAssignmentNEWLINE assert _test_args(AugmentedAssignment(x, 1))NEWLINENEWLINEdef test_sympy__codegen__ast__AddAugmentedAssignment():NEWLINE from sympy.codegen.ast import AddAugmentedAssignmentNEWLINE assert _test_args(AddAugmentedAssignment(x, 1))NEWLINENEWLINEdef test_sympy__codegen__ast__SubAugmentedAssignment():NEWLINE from sympy.codegen.ast import SubAugmentedAssignmentNEWLINE assert _test_args(SubAugmentedAssignment(x, 1))NEWLINENEWLINEdef test_sympy__codegen__ast__MulAugmentedAssignment():NEWLINE from sympy.codegen.ast import MulAugmentedAssignmentNEWLINE assert _test_args(MulAugmentedAssignment(x, 1))NEWLINENEWLINEdef test_sympy__codegen__ast__DivAugmentedAssignment():NEWLINE from sympy.codegen.ast import DivAugmentedAssignmentNEWLINE assert _test_args(DivAugmentedAssignment(x, 1))NEWLINENEWLINEdef test_sympy__codegen__ast__ModAugmentedAssignment():NEWLINE from sympy.codegen.ast import ModAugmentedAssignmentNEWLINE assert _test_args(ModAugmentedAssignment(x, 1))NEWLINENEWLINEdef test_sympy__codegen__ast__CodeBlock():NEWLINE from sympy.codegen.ast import CodeBlock, AssignmentNEWLINE assert _test_args(CodeBlock(Assignment(x, 1), Assignment(y, 2)))NEWLINENEWLINEdef test_sympy__codegen__ast__For():NEWLINE from sympy.codegen.ast import For, CodeBlock, AddAugmentedAssignmentNEWLINE from sympy import RangeNEWLINE assert _test_args(For(x, Range(10), CodeBlock(AddAugmentedAssignment(y, 1))))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ast__Token():NEWLINE from sympy.codegen.ast import TokenNEWLINE assert _test_args(Token())NEWLINENEWLINENEWLINEdef test_sympy__codegen__ast__Type():NEWLINE from sympy.codegen.ast import TypeNEWLINE assert _test_args(Type('float128'))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ast__IntBaseType():NEWLINE from sympy.codegen.ast import IntBaseTypeNEWLINE assert _test_args(IntBaseType('bigint'))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ast___SizedIntType():NEWLINE from sympy.codegen.ast import _SizedIntTypeNEWLINE assert _test_args(_SizedIntType('int128', 128))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ast__SignedIntType():NEWLINE from sympy.codegen.ast import SignedIntTypeNEWLINE assert _test_args(SignedIntType('int128_with_sign', 128))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ast__UnsignedIntType():NEWLINE from sympy.codegen.ast import UnsignedIntTypeNEWLINE assert _test_args(UnsignedIntType('unt128', 128))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ast__FloatType():NEWLINE from sympy.codegen.ast import FloatTypeNEWLINE assert _test_args(FloatType('float242', 242, nmant=142, nexp=99))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ast__ComplexType():NEWLINE from sympy.codegen.ast import ComplexTypeNEWLINE assert _test_args(ComplexType('complex42', 42, nmant=15, nexp=5))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ast__Attribute():NEWLINE from sympy.codegen.ast import AttributeNEWLINE assert _test_args(Attribute('noexcept'))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ast__Variable():NEWLINE from sympy.codegen.ast import Variable, Type, value_constNEWLINE assert _test_args(Variable(x))NEWLINE assert _test_args(Variable(y, {value_const}, Type('float32')))NEWLINE assert _test_args(Variable(z, type_=Type('float64')))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ast__Pointer():NEWLINE from sympy.codegen.ast import Pointer, Type, pointer_constNEWLINE assert _test_args(Pointer(x))NEWLINE assert _test_args(Pointer(y, type_=Type('float32')))NEWLINE assert _test_args(Pointer(z, {pointer_const}, Type('float64')))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ast__Declaration():NEWLINE from sympy.codegen.ast import Declaration, Variable, TypeNEWLINE vx = Variable(x, type_=Type('float'))NEWLINE assert _test_args(Declaration(vx))NEWLINE assert _test_args(Declaration(vx, 3.0))NEWLINENEWLINENEWLINE@XFAILNEWLINEdef test_sympy__combinatorics__graycode__GrayCode():NEWLINE from sympy.combinatorics.graycode import GrayCodeNEWLINE # an integer is given and returned from GrayCode as the argNEWLINE assert _test_args(GrayCode(3, start='100'))NEWLINE assert _test_args(GrayCode(3, rank=1))NEWLINENEWLINENEWLINEdef test_sympy__combinatorics__subsets__Subset():NEWLINE from sympy.combinatorics.subsets import SubsetNEWLINE assert _test_args(Subset([0, 1], [0, 1, 2, 3]))NEWLINE assert _test_args(Subset(['c', 'd'], ['a', 'b', 'c', 'd']))NEWLINENEWLINENEWLINE@XFAILNEWLINEdef test_sympy__combinatorics__permutations__Permutation():NEWLINE from sympy.combinatorics.permutations import PermutationNEWLINE assert _test_args(Permutation([0, 1, 2, 3]))NEWLINENEWLINENEWLINEdef test_sympy__combinatorics__perm_groups__PermutationGroup():NEWLINE from sympy.combinatorics.permutations import PermutationNEWLINE from sympy.combinatorics.perm_groups import PermutationGroupNEWLINE assert _test_args(PermutationGroup([Permutation([0, 1])]))NEWLINENEWLINENEWLINEdef test_sympy__combinatorics__polyhedron__Polyhedron():NEWLINE from sympy.combinatorics.permutations import PermutationNEWLINE from sympy.combinatorics.polyhedron import PolyhedronNEWLINE from sympy.abc import w, x, y, zNEWLINE pgroup = [Permutation([[0, 1, 2], [3]]),NEWLINE Permutation([[0, 1, 3], [2]]),NEWLINE Permutation([[0, 2, 3], [1]]),NEWLINE Permutation([[1, 2, 3], [0]]),NEWLINE Permutation([[0, 1], [2, 3]]),NEWLINE Permutation([[0, 2], [1, 3]]),NEWLINE Permutation([[0, 3], [1, 2]]),NEWLINE Permutation([[0, 1, 2, 3]])]NEWLINE corners = [w, x, y, z]NEWLINE faces = [(w, x, y), (w, y, z), (w, z, x), (x, y, z)]NEWLINE assert _test_args(Polyhedron(corners, faces, pgroup))NEWLINENEWLINENEWLINE@XFAILNEWLINEdef test_sympy__combinatorics__prufer__Prufer():NEWLINE from sympy.combinatorics.prufer import PruferNEWLINE assert _test_args(Prufer([[0, 1], [0, 2], [0, 3]], 4))NEWLINENEWLINENEWLINEdef test_sympy__combinatorics__partitions__Partition():NEWLINE from sympy.combinatorics.partitions import PartitionNEWLINE assert _test_args(Partition([1]))NEWLINENEWLINENEWLINE@XFAILNEWLINEdef test_sympy__combinatorics__partitions__IntegerPartition():NEWLINE from sympy.combinatorics.partitions import IntegerPartitionNEWLINE assert _test_args(IntegerPartition([1]))NEWLINENEWLINENEWLINEdef test_sympy__concrete__products__Product():NEWLINE from sympy.concrete.products import ProductNEWLINE assert _test_args(Product(x, (x, 0, 10)))NEWLINE assert _test_args(Product(x, (x, 0, y), (y, 0, 10)))NEWLINENEWLINENEWLINE@SKIP("abstract Class")NEWLINEdef test_sympy__concrete__expr_with_limits__ExprWithLimits():NEWLINE from sympy.concrete.expr_with_limits import ExprWithLimitsNEWLINE assert _test_args(ExprWithLimits(x, (x, 0, 10)))NEWLINE assert _test_args(ExprWithLimits(x*y, (x, 0, 10.),(y,1.,3)))NEWLINENEWLINENEWLINE@SKIP("abstract Class")NEWLINEdef test_sympy__concrete__expr_with_limits__AddWithLimits():NEWLINE from sympy.concrete.expr_with_limits import AddWithLimitsNEWLINE assert _test_args(AddWithLimits(x, (x, 0, 10)))NEWLINE assert _test_args(AddWithLimits(x*y, (x, 0, 10),(y,1,3)))NEWLINENEWLINENEWLINE@SKIP("abstract Class")NEWLINEdef test_sympy__concrete__expr_with_intlimits__ExprWithIntLimits():NEWLINE from sympy.concrete.expr_with_intlimits import ExprWithIntLimitsNEWLINE assert _test_args(ExprWithIntLimits(x, (x, 0, 10)))NEWLINE assert _test_args(ExprWithIntLimits(x*y, (x, 0, 10),(y,1,3)))NEWLINENEWLINENEWLINEdef test_sympy__concrete__summations__Sum():NEWLINE from sympy.concrete.summations import SumNEWLINE assert _test_args(Sum(x, (x, 0, 10)))NEWLINE assert _test_args(Sum(x, (x, 0, y), (y, 0, 10)))NEWLINENEWLINENEWLINEdef test_sympy__core__add__Add():NEWLINE from sympy.core.add import AddNEWLINE assert _test_args(Add(x, y, z, 2))NEWLINENEWLINENEWLINEdef test_sympy__core__basic__Atom():NEWLINE from sympy.core.basic import AtomNEWLINE assert _test_args(Atom())NEWLINENEWLINENEWLINEdef test_sympy__core__basic__Basic():NEWLINE from sympy.core.basic import BasicNEWLINE assert _test_args(Basic())NEWLINENEWLINENEWLINEdef test_sympy__core__containers__Dict():NEWLINE from sympy.core.containers import DictNEWLINE assert _test_args(Dict({x: y, y: z}))NEWLINENEWLINENEWLINEdef test_sympy__core__containers__Tuple():NEWLINE from sympy.core.containers import TupleNEWLINE assert _test_args(Tuple(x, y, z, 2))NEWLINENEWLINENEWLINEdef test_sympy__core__expr__AtomicExpr():NEWLINE from sympy.core.expr import AtomicExprNEWLINE assert _test_args(AtomicExpr())NEWLINENEWLINENEWLINEdef test_sympy__core__expr__Expr():NEWLINE from sympy.core.expr import ExprNEWLINE assert _test_args(Expr())NEWLINENEWLINENEWLINEdef test_sympy__core__expr__UnevaluatedExpr():NEWLINE from sympy.core.expr import UnevaluatedExprNEWLINE from sympy.abc import xNEWLINE assert _test_args(UnevaluatedExpr(x))NEWLINENEWLINENEWLINEdef test_sympy__core__function__Application():NEWLINE from sympy.core.function import ApplicationNEWLINE assert _test_args(Application(1, 2, 3))NEWLINENEWLINENEWLINEdef test_sympy__core__function__AppliedUndef():NEWLINE from sympy.core.function import AppliedUndefNEWLINE assert _test_args(AppliedUndef(1, 2, 3))NEWLINENEWLINENEWLINEdef test_sympy__core__function__Derivative():NEWLINE from sympy.core.function import DerivativeNEWLINE assert _test_args(Derivative(2, x, y, 3))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__core__function__Function():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__core__function__Lambda():NEWLINE assert _test_args(Lambda((x, y), x + y + z))NEWLINENEWLINENEWLINEdef test_sympy__core__function__Subs():NEWLINE from sympy.core.function import SubsNEWLINE assert _test_args(Subs(x + y, x, 2))NEWLINENEWLINENEWLINEdef test_sympy__core__function__WildFunction():NEWLINE from sympy.core.function import WildFunctionNEWLINE assert _test_args(WildFunction('f'))NEWLINENEWLINENEWLINEdef test_sympy__core__mod__Mod():NEWLINE from sympy.core.mod import ModNEWLINE assert _test_args(Mod(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__core__mul__Mul():NEWLINE from sympy.core.mul import MulNEWLINE assert _test_args(Mul(2, x, y, z))NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__Catalan():NEWLINE from sympy.core.numbers import CatalanNEWLINE assert _test_args(Catalan())NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__ComplexInfinity():NEWLINE from sympy.core.numbers import ComplexInfinityNEWLINE assert _test_args(ComplexInfinity())NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__EulerGamma():NEWLINE from sympy.core.numbers import EulerGammaNEWLINE assert _test_args(EulerGamma())NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__Exp1():NEWLINE from sympy.core.numbers import Exp1NEWLINE assert _test_args(Exp1())NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__Float():NEWLINE from sympy.core.numbers import FloatNEWLINE assert _test_args(Float(1.23))NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__GoldenRatio():NEWLINE from sympy.core.numbers import GoldenRatioNEWLINE assert _test_args(GoldenRatio())NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__Half():NEWLINE from sympy.core.numbers import HalfNEWLINE assert _test_args(Half())NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__ImaginaryUnit():NEWLINE from sympy.core.numbers import ImaginaryUnitNEWLINE assert _test_args(ImaginaryUnit())NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__Infinity():NEWLINE from sympy.core.numbers import InfinityNEWLINE assert _test_args(Infinity())NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__Integer():NEWLINE from sympy.core.numbers import IntegerNEWLINE assert _test_args(Integer(7))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__core__numbers__IntegerConstant():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__core__numbers__NaN():NEWLINE from sympy.core.numbers import NaNNEWLINE assert _test_args(NaN())NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__NegativeInfinity():NEWLINE from sympy.core.numbers import NegativeInfinityNEWLINE assert _test_args(NegativeInfinity())NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__NegativeOne():NEWLINE from sympy.core.numbers import NegativeOneNEWLINE assert _test_args(NegativeOne())NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__Number():NEWLINE from sympy.core.numbers import NumberNEWLINE assert _test_args(Number(1, 7))NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__NumberSymbol():NEWLINE from sympy.core.numbers import NumberSymbolNEWLINE assert _test_args(NumberSymbol())NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__One():NEWLINE from sympy.core.numbers import OneNEWLINE assert _test_args(One())NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__Pi():NEWLINE from sympy.core.numbers import PiNEWLINE assert _test_args(Pi())NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__Rational():NEWLINE from sympy.core.numbers import RationalNEWLINE assert _test_args(Rational(1, 7))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__core__numbers__RationalConstant():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__core__numbers__Zero():NEWLINE from sympy.core.numbers import ZeroNEWLINE assert _test_args(Zero())NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__core__operations__AssocOp():NEWLINE passNEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__core__operations__LatticeOp():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__core__power__Pow():NEWLINE from sympy.core.power import PowNEWLINE assert _test_args(Pow(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__algebras__quaternion__Quaternion():NEWLINE from sympy.algebras.quaternion import QuaternionNEWLINE assert _test_args(Quaternion(x, 1, 2, 3))NEWLINENEWLINENEWLINEdef test_sympy__core__relational__Equality():NEWLINE from sympy.core.relational import EqualityNEWLINE assert _test_args(Equality(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__core__relational__GreaterThan():NEWLINE from sympy.core.relational import GreaterThanNEWLINE assert _test_args(GreaterThan(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__core__relational__LessThan():NEWLINE from sympy.core.relational import LessThanNEWLINE assert _test_args(LessThan(x, 2))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__core__relational__Relational():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__core__relational__StrictGreaterThan():NEWLINE from sympy.core.relational import StrictGreaterThanNEWLINE assert _test_args(StrictGreaterThan(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__core__relational__StrictLessThan():NEWLINE from sympy.core.relational import StrictLessThanNEWLINE assert _test_args(StrictLessThan(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__core__relational__Unequality():NEWLINE from sympy.core.relational import UnequalityNEWLINE assert _test_args(Unequality(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__sandbox__indexed_integrals__IndexedIntegral():NEWLINE from sympy.tensor import IndexedBase, IdxNEWLINE from sympy.sandbox.indexed_integrals import IndexedIntegralNEWLINE A = IndexedBase('A')NEWLINE i, j = symbols('i j', integer=True)NEWLINE a1, a2 = symbols('a1:3', cls=Idx)NEWLINE assert _test_args(IndexedIntegral(A[a1], A[a2]))NEWLINE assert _test_args(IndexedIntegral(A[i], A[j]))NEWLINENEWLINENEWLINEdef test_sympy__calculus__util__AccumulationBounds():NEWLINE from sympy.calculus.util import AccumulationBoundsNEWLINE assert _test_args(AccumulationBounds(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__sets__sets__EmptySet():NEWLINE from sympy.sets.sets import EmptySetNEWLINE assert _test_args(EmptySet())NEWLINENEWLINENEWLINEdef test_sympy__sets__sets__UniversalSet():NEWLINE from sympy.sets.sets import UniversalSetNEWLINE assert _test_args(UniversalSet())NEWLINENEWLINENEWLINEdef test_sympy__sets__sets__FiniteSet():NEWLINE from sympy.sets.sets import FiniteSetNEWLINE assert _test_args(FiniteSet(x, y, z))NEWLINENEWLINENEWLINEdef test_sympy__sets__sets__Interval():NEWLINE from sympy.sets.sets import IntervalNEWLINE assert _test_args(Interval(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__sets__sets__ProductSet():NEWLINE from sympy.sets.sets import ProductSet, IntervalNEWLINE assert _test_args(ProductSet(Interval(0, 1), Interval(0, 1)))NEWLINENEWLINENEWLINE@SKIP("does it make sense to test this?")NEWLINEdef test_sympy__sets__sets__Set():NEWLINE from sympy.sets.sets import SetNEWLINE assert _test_args(Set())NEWLINENEWLINENEWLINEdef test_sympy__sets__sets__Intersection():NEWLINE from sympy.sets.sets import Intersection, IntervalNEWLINE assert _test_args(Intersection(Interval(0, 3), Interval(2, 4),NEWLINE evaluate=False))NEWLINENEWLINENEWLINEdef test_sympy__sets__sets__Union():NEWLINE from sympy.sets.sets import Union, IntervalNEWLINE assert _test_args(Union(Interval(0, 1), Interval(2, 3)))NEWLINENEWLINENEWLINEdef test_sympy__sets__sets__Complement():NEWLINE from sympy.sets.sets import ComplementNEWLINE assert _test_args(Complement(Interval(0, 2), Interval(0, 1)))NEWLINENEWLINENEWLINEdef test_sympy__sets__sets__SymmetricDifference():NEWLINE from sympy.sets.sets import FiniteSet, SymmetricDifferenceNEWLINE assert _test_args(SymmetricDifference(FiniteSet(1, 2, 3), \NEWLINE FiniteSet(2, 3, 4)))NEWLINENEWLINENEWLINEdef test_sympy__core__trace__Tr():NEWLINE from sympy.core.trace import TrNEWLINE a, b = symbols('a b')NEWLINE assert _test_args(Tr(a + b))NEWLINENEWLINENEWLINEdef test_sympy__sets__fancysets__Naturals():NEWLINE from sympy.sets.fancysets import NaturalsNEWLINE assert _test_args(Naturals())NEWLINENEWLINEdef test_sympy__sets__fancysets__Naturals0():NEWLINE from sympy.sets.fancysets import Naturals0NEWLINE assert _test_args(Naturals0())NEWLINENEWLINEdef test_sympy__sets__fancysets__Integers():NEWLINE from sympy.sets.fancysets import IntegersNEWLINE assert _test_args(Integers())NEWLINENEWLINENEWLINEdef test_sympy__sets__fancysets__Reals():NEWLINE from sympy.sets.fancysets import RealsNEWLINE assert _test_args(Reals())NEWLINENEWLINENEWLINEdef test_sympy__sets__fancysets__Complexes():NEWLINE from sympy.sets.fancysets import ComplexesNEWLINE assert _test_args(Complexes())NEWLINENEWLINENEWLINEdef test_sympy__sets__fancysets__ComplexRegion():NEWLINE from sympy.sets.fancysets import ComplexRegionNEWLINE from sympy import SNEWLINE from sympy.sets import IntervalNEWLINE a = Interval(0, 1)NEWLINE b = Interval(2, 3)NEWLINE theta = Interval(0, 2*S.Pi)NEWLINE assert _test_args(ComplexRegion(a*b))NEWLINE assert _test_args(ComplexRegion(a*theta, polar=True))NEWLINENEWLINENEWLINEdef test_sympy__sets__fancysets__ImageSet():NEWLINE from sympy.sets.fancysets import ImageSetNEWLINE from sympy import S, SymbolNEWLINE x = Symbol('x')NEWLINE assert _test_args(ImageSet(Lambda(x, x**2), S.Naturals))NEWLINENEWLINENEWLINEdef test_sympy__sets__fancysets__Range():NEWLINE from sympy.sets.fancysets import RangeNEWLINE assert _test_args(Range(1, 5, 1))NEWLINENEWLINENEWLINEdef test_sympy__sets__conditionset__ConditionSet():NEWLINE from sympy.sets.conditionset import ConditionSetNEWLINE from sympy import S, SymbolNEWLINE x = Symbol('x')NEWLINE assert _test_args(ConditionSet(x, Eq(x**2, 1), S.Reals))NEWLINENEWLINENEWLINEdef test_sympy__sets__contains__Contains():NEWLINE from sympy.sets.fancysets import RangeNEWLINE from sympy.sets.contains import ContainsNEWLINE assert _test_args(Contains(x, Range(0, 10, 2)))NEWLINENEWLINENEWLINE# STATSNEWLINENEWLINENEWLINEfrom sympy.stats.crv_types import NormalDistributionNEWLINEnd = NormalDistribution(0, 1)NEWLINEfrom sympy.stats.frv_types import DieDistributionNEWLINEdie = DieDistribution(6)NEWLINENEWLINENEWLINEdef test_sympy__stats__crv__ContinuousDomain():NEWLINE from sympy.stats.crv import ContinuousDomainNEWLINE assert _test_args(ContinuousDomain({x}, Interval(-oo, oo)))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv__SingleContinuousDomain():NEWLINE from sympy.stats.crv import SingleContinuousDomainNEWLINE assert _test_args(SingleContinuousDomain(x, Interval(-oo, oo)))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv__ProductContinuousDomain():NEWLINE from sympy.stats.crv import SingleContinuousDomain, ProductContinuousDomainNEWLINE D = SingleContinuousDomain(x, Interval(-oo, oo))NEWLINE E = SingleContinuousDomain(y, Interval(0, oo))NEWLINE assert _test_args(ProductContinuousDomain(D, E))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv__ConditionalContinuousDomain():NEWLINE from sympy.stats.crv import (SingleContinuousDomain,NEWLINE ConditionalContinuousDomain)NEWLINE D = SingleContinuousDomain(x, Interval(-oo, oo))NEWLINE assert _test_args(ConditionalContinuousDomain(D, x > 0))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv__ContinuousPSpace():NEWLINE from sympy.stats.crv import ContinuousPSpace, SingleContinuousDomainNEWLINE D = SingleContinuousDomain(x, Interval(-oo, oo))NEWLINE assert _test_args(ContinuousPSpace(D, nd))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv__SingleContinuousPSpace():NEWLINE from sympy.stats.crv import SingleContinuousPSpaceNEWLINE assert _test_args(SingleContinuousPSpace(x, nd))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv__ProductContinuousPSpace():NEWLINE from sympy.stats.crv import ProductContinuousPSpace, SingleContinuousPSpaceNEWLINE A = SingleContinuousPSpace(x, nd)NEWLINE B = SingleContinuousPSpace(y, nd)NEWLINE assert _test_args(ProductContinuousPSpace(A, B))NEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__stats__crv__SingleContinuousDistribution():NEWLINE passNEWLINENEWLINEdef test_sympy__stats__drv__SingleDiscreteDomain():NEWLINE from sympy.stats.drv import SingleDiscreteDomainNEWLINE assert _test_args(SingleDiscreteDomain(x, S.Naturals))NEWLINENEWLINEdef test_sympy__stats__drv__SingleDiscretePSpace():NEWLINE from sympy.stats.drv import SingleDiscretePSpaceNEWLINE from sympy.stats.drv_types import PoissonDistributionNEWLINE assert _test_args(SingleDiscretePSpace(x, PoissonDistribution(1)))NEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__stats__drv__SingleDiscreteDistribution():NEWLINE passNEWLINENEWLINEdef test_sympy__stats__rv__RandomDomain():NEWLINE from sympy.stats.rv import RandomDomainNEWLINE from sympy.sets.sets import FiniteSetNEWLINE assert _test_args(RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3)))NEWLINENEWLINENEWLINEdef test_sympy__stats__rv__SingleDomain():NEWLINE from sympy.stats.rv import SingleDomainNEWLINE from sympy.sets.sets import FiniteSetNEWLINE assert _test_args(SingleDomain(x, FiniteSet(1, 2, 3)))NEWLINENEWLINENEWLINEdef test_sympy__stats__rv__ConditionalDomain():NEWLINE from sympy.stats.rv import ConditionalDomain, RandomDomainNEWLINE from sympy.sets.sets import FiniteSetNEWLINE D = RandomDomain(FiniteSet(x), FiniteSet(1, 2))NEWLINE assert _test_args(ConditionalDomain(D, x > 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__rv__PSpace():NEWLINE from sympy.stats.rv import PSpace, RandomDomainNEWLINE from sympy import FiniteSetNEWLINE D = RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3, 4, 5, 6))NEWLINE assert _test_args(PSpace(D, die))NEWLINENEWLINENEWLINE@SKIP("abstract Class")NEWLINEdef test_sympy__stats__rv__SinglePSpace():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__stats__rv__RandomSymbol():NEWLINE from sympy.stats.rv import RandomSymbolNEWLINE from sympy.stats.crv import SingleContinuousPSpaceNEWLINE A = SingleContinuousPSpace(x, nd)NEWLINE assert _test_args(RandomSymbol(x, A))NEWLINENEWLINENEWLINEdef test_sympy__stats__rv__ProductPSpace():NEWLINE from sympy.stats.rv import ProductPSpaceNEWLINE from sympy.stats.crv import SingleContinuousPSpaceNEWLINE A = SingleContinuousPSpace(x, nd)NEWLINE B = SingleContinuousPSpace(y, nd)NEWLINE assert _test_args(ProductPSpace(A, B))NEWLINENEWLINENEWLINEdef test_sympy__stats__rv__ProductDomain():NEWLINE from sympy.stats.rv import ProductDomain, SingleDomainNEWLINE D = SingleDomain(x, Interval(-oo, oo))NEWLINE E = SingleDomain(y, Interval(0, oo))NEWLINE assert _test_args(ProductDomain(D, E))NEWLINENEWLINENEWLINEdef test_sympy__stats__symbolic_probability__Probability():NEWLINE from sympy.stats.symbolic_probability import ProbabilityNEWLINE from sympy.stats import NormalNEWLINE X = Normal('X', 0, 1)NEWLINE assert _test_args(Probability(X > 0))NEWLINENEWLINENEWLINEdef test_sympy__stats__symbolic_probability__Expectation():NEWLINE from sympy.stats.symbolic_probability import ExpectationNEWLINE from sympy.stats import NormalNEWLINE X = Normal('X', 0, 1)NEWLINE assert _test_args(Expectation(X > 0))NEWLINENEWLINENEWLINEdef test_sympy__stats__symbolic_probability__Covariance():NEWLINE from sympy.stats.symbolic_probability import CovarianceNEWLINE from sympy.stats import NormalNEWLINE X = Normal('X', 0, 1)NEWLINE Y = Normal('Y', 0, 3)NEWLINE assert _test_args(Covariance(X, Y))NEWLINENEWLINENEWLINEdef test_sympy__stats__symbolic_probability__Variance():NEWLINE from sympy.stats.symbolic_probability import VarianceNEWLINE from sympy.stats import NormalNEWLINE X = Normal('X', 0, 1)NEWLINE assert _test_args(Variance(X))NEWLINENEWLINENEWLINEdef test_sympy__stats__frv_types__DiscreteUniformDistribution():NEWLINE from sympy.stats.frv_types import DiscreteUniformDistributionNEWLINE from sympy.core.containers import TupleNEWLINE assert _test_args(DiscreteUniformDistribution(Tuple(*list(range(6)))))NEWLINENEWLINENEWLINEdef test_sympy__stats__frv_types__DieDistribution():NEWLINE from sympy.stats.frv_types import DieDistributionNEWLINE assert _test_args(DieDistribution(6))NEWLINENEWLINENEWLINEdef test_sympy__stats__frv_types__BernoulliDistribution():NEWLINE from sympy.stats.frv_types import BernoulliDistributionNEWLINE assert _test_args(BernoulliDistribution(S.Half, 0, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__frv_types__BinomialDistribution():NEWLINE from sympy.stats.frv_types import BinomialDistributionNEWLINE assert _test_args(BinomialDistribution(5, S.Half, 1, 0))NEWLINENEWLINENEWLINEdef test_sympy__stats__frv_types__HypergeometricDistribution():NEWLINE from sympy.stats.frv_types import HypergeometricDistributionNEWLINE assert _test_args(HypergeometricDistribution(10, 5, 3))NEWLINENEWLINENEWLINEdef test_sympy__stats__frv_types__RademacherDistribution():NEWLINE from sympy.stats.frv_types import RademacherDistributionNEWLINE assert _test_args(RademacherDistribution())NEWLINENEWLINENEWLINEdef test_sympy__stats__frv__FiniteDomain():NEWLINE from sympy.stats.frv import FiniteDomainNEWLINE assert _test_args(FiniteDomain({(x, 1), (x, 2)})) # x can be 1 or 2NEWLINENEWLINENEWLINEdef test_sympy__stats__frv__SingleFiniteDomain():NEWLINE from sympy.stats.frv import SingleFiniteDomainNEWLINE assert _test_args(SingleFiniteDomain(x, {1, 2})) # x can be 1 or 2NEWLINENEWLINENEWLINEdef test_sympy__stats__frv__ProductFiniteDomain():NEWLINE from sympy.stats.frv import SingleFiniteDomain, ProductFiniteDomainNEWLINE xd = SingleFiniteDomain(x, {1, 2})NEWLINE yd = SingleFiniteDomain(y, {1, 2})NEWLINE assert _test_args(ProductFiniteDomain(xd, yd))NEWLINENEWLINENEWLINEdef test_sympy__stats__frv__ConditionalFiniteDomain():NEWLINE from sympy.stats.frv import SingleFiniteDomain, ConditionalFiniteDomainNEWLINE xd = SingleFiniteDomain(x, {1, 2})NEWLINE assert _test_args(ConditionalFiniteDomain(xd, x > 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__frv__FinitePSpace():NEWLINE from sympy.stats.frv import FinitePSpace, SingleFiniteDomainNEWLINE xd = SingleFiniteDomain(x, {1, 2, 3, 4, 5, 6})NEWLINE p = 1.0/6NEWLINE xd = SingleFiniteDomain(x, {1, 2})NEWLINE assert _test_args(FinitePSpace(xd, {(x, 1): S.Half, (x, 2): S.Half}))NEWLINENEWLINENEWLINEdef test_sympy__stats__frv__SingleFinitePSpace():NEWLINE from sympy.stats.frv import SingleFinitePSpaceNEWLINE from sympy import SymbolNEWLINENEWLINE assert _test_args(SingleFinitePSpace(Symbol('x'), die))NEWLINENEWLINENEWLINEdef test_sympy__stats__frv__ProductFinitePSpace():NEWLINE from sympy.stats.frv import SingleFinitePSpace, ProductFinitePSpaceNEWLINE from sympy import SymbolNEWLINE xp = SingleFinitePSpace(Symbol('x'), die)NEWLINE yp = SingleFinitePSpace(Symbol('y'), die)NEWLINE assert _test_args(ProductFinitePSpace(xp, yp))NEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__stats__frv__SingleFiniteDistribution():NEWLINE passNEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__stats__crv__ContinuousDistribution():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__stats__frv_types__FiniteDistributionHandmade():NEWLINE from sympy.stats.frv_types import FiniteDistributionHandmadeNEWLINE assert _test_args(FiniteDistributionHandmade({1: 1}))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv__ContinuousDistributionHandmade():NEWLINE from sympy.stats.crv import ContinuousDistributionHandmadeNEWLINE from sympy import Symbol, IntervalNEWLINE assert _test_args(ContinuousDistributionHandmade(Symbol('x'),NEWLINE Interval(0, 2)))NEWLINENEWLINEdef test_sympy__stats__rv__Density():NEWLINE from sympy.stats.rv import DensityNEWLINE from sympy.stats.crv_types import NormalNEWLINE assert _test_args(Density(Normal('x', 0, 1)))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__ArcsinDistribution():NEWLINE from sympy.stats.crv_types import ArcsinDistributionNEWLINE assert _test_args(ArcsinDistribution(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__BeniniDistribution():NEWLINE from sympy.stats.crv_types import BeniniDistributionNEWLINE assert _test_args(BeniniDistribution(1, 1, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__BetaDistribution():NEWLINE from sympy.stats.crv_types import BetaDistributionNEWLINE assert _test_args(BetaDistribution(1, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__BetaPrimeDistribution():NEWLINE from sympy.stats.crv_types import BetaPrimeDistributionNEWLINE assert _test_args(BetaPrimeDistribution(1, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__CauchyDistribution():NEWLINE from sympy.stats.crv_types import CauchyDistributionNEWLINE assert _test_args(CauchyDistribution(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__ChiDistribution():NEWLINE from sympy.stats.crv_types import ChiDistributionNEWLINE assert _test_args(ChiDistribution(1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__ChiNoncentralDistribution():NEWLINE from sympy.stats.crv_types import ChiNoncentralDistributionNEWLINE assert _test_args(ChiNoncentralDistribution(1,1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__ChiSquaredDistribution():NEWLINE from sympy.stats.crv_types import ChiSquaredDistributionNEWLINE assert _test_args(ChiSquaredDistribution(1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__DagumDistribution():NEWLINE from sympy.stats.crv_types import DagumDistributionNEWLINE assert _test_args(DagumDistribution(1, 1, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__ExponentialDistribution():NEWLINE from sympy.stats.crv_types import ExponentialDistributionNEWLINE assert _test_args(ExponentialDistribution(1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__FDistributionDistribution():NEWLINE from sympy.stats.crv_types import FDistributionDistributionNEWLINE assert _test_args(FDistributionDistribution(1, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__FisherZDistribution():NEWLINE from sympy.stats.crv_types import FisherZDistributionNEWLINE assert _test_args(FisherZDistribution(1, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__FrechetDistribution():NEWLINE from sympy.stats.crv_types import FrechetDistributionNEWLINE assert _test_args(FrechetDistribution(1, 1, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__GammaInverseDistribution():NEWLINE from sympy.stats.crv_types import GammaInverseDistributionNEWLINE assert _test_args(GammaInverseDistribution(1, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__GammaDistribution():NEWLINE from sympy.stats.crv_types import GammaDistributionNEWLINE assert _test_args(GammaDistribution(1, 1))NEWLINENEWLINEdef test_sympy__stats__crv_types__GumbelDistribution():NEWLINE from sympy.stats.crv_types import GumbelDistributionNEWLINE assert _test_args(GumbelDistribution(1, 1))NEWLINENEWLINEdef test_sympy__stats__crv_types__GompertzDistribution():NEWLINE from sympy.stats.crv_types import GompertzDistributionNEWLINE assert _test_args(GompertzDistribution(1, 1))NEWLINENEWLINEdef test_sympy__stats__crv_types__KumaraswamyDistribution():NEWLINE from sympy.stats.crv_types import KumaraswamyDistributionNEWLINE assert _test_args(KumaraswamyDistribution(1, 1))NEWLINENEWLINEdef test_sympy__stats__crv_types__LaplaceDistribution():NEWLINE from sympy.stats.crv_types import LaplaceDistributionNEWLINE assert _test_args(LaplaceDistribution(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__LogisticDistribution():NEWLINE from sympy.stats.crv_types import LogisticDistributionNEWLINE assert _test_args(LogisticDistribution(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__LogNormalDistribution():NEWLINE from sympy.stats.crv_types import LogNormalDistributionNEWLINE assert _test_args(LogNormalDistribution(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__MaxwellDistribution():NEWLINE from sympy.stats.crv_types import MaxwellDistributionNEWLINE assert _test_args(MaxwellDistribution(1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__NakagamiDistribution():NEWLINE from sympy.stats.crv_types import NakagamiDistributionNEWLINE assert _test_args(NakagamiDistribution(1, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__NormalDistribution():NEWLINE from sympy.stats.crv_types import NormalDistributionNEWLINE assert _test_args(NormalDistribution(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__ParetoDistribution():NEWLINE from sympy.stats.crv_types import ParetoDistributionNEWLINE assert _test_args(ParetoDistribution(1, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__QuadraticUDistribution():NEWLINE from sympy.stats.crv_types import QuadraticUDistributionNEWLINE assert _test_args(QuadraticUDistribution(1, 2))NEWLINENEWLINEdef test_sympy__stats__crv_types__RaisedCosineDistribution():NEWLINE from sympy.stats.crv_types import RaisedCosineDistributionNEWLINE assert _test_args(RaisedCosineDistribution(1, 1))NEWLINENEWLINEdef test_sympy__stats__crv_types__RayleighDistribution():NEWLINE from sympy.stats.crv_types import RayleighDistributionNEWLINE assert _test_args(RayleighDistribution(1))NEWLINENEWLINEdef test_sympy__stats__crv_types__ShiftedGompertzDistribution():NEWLINE from sympy.stats.crv_types import ShiftedGompertzDistributionNEWLINE assert _test_args(ShiftedGompertzDistribution(1, 1))NEWLINENEWLINEdef test_sympy__stats__crv_types__StudentTDistribution():NEWLINE from sympy.stats.crv_types import StudentTDistributionNEWLINE assert _test_args(StudentTDistribution(1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__TriangularDistribution():NEWLINE from sympy.stats.crv_types import TriangularDistributionNEWLINE assert _test_args(TriangularDistribution(-1, 0, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__UniformDistribution():NEWLINE from sympy.stats.crv_types import UniformDistributionNEWLINE assert _test_args(UniformDistribution(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__UniformSumDistribution():NEWLINE from sympy.stats.crv_types import UniformSumDistributionNEWLINE assert _test_args(UniformSumDistribution(1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__VonMisesDistribution():NEWLINE from sympy.stats.crv_types import VonMisesDistributionNEWLINE assert _test_args(VonMisesDistribution(1, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__WeibullDistribution():NEWLINE from sympy.stats.crv_types import WeibullDistributionNEWLINE assert _test_args(WeibullDistribution(1, 1))NEWLINENEWLINENEWLINEdef test_sympy__stats__crv_types__WignerSemicircleDistribution():NEWLINE from sympy.stats.crv_types import WignerSemicircleDistributionNEWLINE assert _test_args(WignerSemicircleDistribution(1))NEWLINENEWLINEdef test_sympy__stats__drv_types__PoissonDistribution():NEWLINE from sympy.stats.drv_types import PoissonDistributionNEWLINE assert _test_args(PoissonDistribution(1))NEWLINENEWLINEdef test_sympy__stats__drv_types__GeometricDistribution():NEWLINE from sympy.stats.drv_types import GeometricDistributionNEWLINE assert _test_args(GeometricDistribution(.5))NEWLINENEWLINEdef test_sympy__core__symbol__Dummy():NEWLINE from sympy.core.symbol import DummyNEWLINE assert _test_args(Dummy('t'))NEWLINENEWLINENEWLINEdef test_sympy__core__symbol__Symbol():NEWLINE from sympy.core.symbol import SymbolNEWLINE assert _test_args(Symbol('t'))NEWLINENEWLINENEWLINEdef test_sympy__core__symbol__Wild():NEWLINE from sympy.core.symbol import WildNEWLINE assert _test_args(Wild('x', exclude=[x]))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__combinatorial__factorials__CombinatorialFunction():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__factorials__FallingFactorial():NEWLINE from sympy.functions.combinatorial.factorials import FallingFactorialNEWLINE assert _test_args(FallingFactorial(2, x))NEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__factorials__MultiFactorial():NEWLINE from sympy.functions.combinatorial.factorials import MultiFactorialNEWLINE assert _test_args(MultiFactorial(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__factorials__RisingFactorial():NEWLINE from sympy.functions.combinatorial.factorials import RisingFactorialNEWLINE assert _test_args(RisingFactorial(2, x))NEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__factorials__binomial():NEWLINE from sympy.functions.combinatorial.factorials import binomialNEWLINE assert _test_args(binomial(2, x))NEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__factorials__subfactorial():NEWLINE from sympy.functions.combinatorial.factorials import subfactorialNEWLINE assert _test_args(subfactorial(1))NEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__factorials__factorial():NEWLINE from sympy.functions.combinatorial.factorials import factorialNEWLINE assert _test_args(factorial(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__factorials__factorial2():NEWLINE from sympy.functions.combinatorial.factorials import factorial2NEWLINE assert _test_args(factorial2(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__numbers__bell():NEWLINE from sympy.functions.combinatorial.numbers import bellNEWLINE assert _test_args(bell(x, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__numbers__bernoulli():NEWLINE from sympy.functions.combinatorial.numbers import bernoulliNEWLINE assert _test_args(bernoulli(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__numbers__catalan():NEWLINE from sympy.functions.combinatorial.numbers import catalanNEWLINE assert _test_args(catalan(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__numbers__genocchi():NEWLINE from sympy.functions.combinatorial.numbers import genocchiNEWLINE assert _test_args(genocchi(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__numbers__euler():NEWLINE from sympy.functions.combinatorial.numbers import eulerNEWLINE assert _test_args(euler(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__numbers__fibonacci():NEWLINE from sympy.functions.combinatorial.numbers import fibonacciNEWLINE assert _test_args(fibonacci(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__numbers__harmonic():NEWLINE from sympy.functions.combinatorial.numbers import harmonicNEWLINE assert _test_args(harmonic(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__combinatorial__numbers__lucas():NEWLINE from sympy.functions.combinatorial.numbers import lucasNEWLINE assert _test_args(lucas(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__complexes__Abs():NEWLINE from sympy.functions.elementary.complexes import AbsNEWLINE assert _test_args(Abs(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__complexes__adjoint():NEWLINE from sympy.functions.elementary.complexes import adjointNEWLINE assert _test_args(adjoint(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__complexes__arg():NEWLINE from sympy.functions.elementary.complexes import argNEWLINE assert _test_args(arg(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__complexes__conjugate():NEWLINE from sympy.functions.elementary.complexes import conjugateNEWLINE assert _test_args(conjugate(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__complexes__im():NEWLINE from sympy.functions.elementary.complexes import imNEWLINE assert _test_args(im(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__complexes__re():NEWLINE from sympy.functions.elementary.complexes import reNEWLINE assert _test_args(re(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__complexes__sign():NEWLINE from sympy.functions.elementary.complexes import signNEWLINE assert _test_args(sign(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__complexes__polar_lift():NEWLINE from sympy.functions.elementary.complexes import polar_liftNEWLINE assert _test_args(polar_lift(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__complexes__periodic_argument():NEWLINE from sympy.functions.elementary.complexes import periodic_argumentNEWLINE assert _test_args(periodic_argument(x, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__complexes__principal_branch():NEWLINE from sympy.functions.elementary.complexes import principal_branchNEWLINE assert _test_args(principal_branch(x, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__complexes__transpose():NEWLINE from sympy.functions.elementary.complexes import transposeNEWLINE assert _test_args(transpose(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__exponential__LambertW():NEWLINE from sympy.functions.elementary.exponential import LambertWNEWLINE assert _test_args(LambertW(2))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__elementary__exponential__ExpBase():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__exponential__exp():NEWLINE from sympy.functions.elementary.exponential import expNEWLINE assert _test_args(exp(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__exponential__exp_polar():NEWLINE from sympy.functions.elementary.exponential import exp_polarNEWLINE assert _test_args(exp_polar(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__exponential__log():NEWLINE from sympy.functions.elementary.exponential import logNEWLINE assert _test_args(log(2))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__elementary__hyperbolic__HyperbolicFunction():NEWLINE passNEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__elementary__hyperbolic__ReciprocalHyperbolicFunction():NEWLINE passNEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__elementary__hyperbolic__InverseHyperbolicFunction():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__hyperbolic__acosh():NEWLINE from sympy.functions.elementary.hyperbolic import acoshNEWLINE assert _test_args(acosh(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__hyperbolic__acoth():NEWLINE from sympy.functions.elementary.hyperbolic import acothNEWLINE assert _test_args(acoth(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__hyperbolic__asinh():NEWLINE from sympy.functions.elementary.hyperbolic import asinhNEWLINE assert _test_args(asinh(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__hyperbolic__atanh():NEWLINE from sympy.functions.elementary.hyperbolic import atanhNEWLINE assert _test_args(atanh(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__hyperbolic__asech():NEWLINE from sympy.functions.elementary.hyperbolic import asechNEWLINE assert _test_args(asech(2))NEWLINENEWLINEdef test_sympy__functions__elementary__hyperbolic__acsch():NEWLINE from sympy.functions.elementary.hyperbolic import acschNEWLINE assert _test_args(acsch(2))NEWLINENEWLINEdef test_sympy__functions__elementary__hyperbolic__cosh():NEWLINE from sympy.functions.elementary.hyperbolic import coshNEWLINE assert _test_args(cosh(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__hyperbolic__coth():NEWLINE from sympy.functions.elementary.hyperbolic import cothNEWLINE assert _test_args(coth(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__hyperbolic__csch():NEWLINE from sympy.functions.elementary.hyperbolic import cschNEWLINE assert _test_args(csch(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__hyperbolic__sech():NEWLINE from sympy.functions.elementary.hyperbolic import sechNEWLINE assert _test_args(sech(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__hyperbolic__sinh():NEWLINE from sympy.functions.elementary.hyperbolic import sinhNEWLINE assert _test_args(sinh(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__hyperbolic__tanh():NEWLINE from sympy.functions.elementary.hyperbolic import tanhNEWLINE assert _test_args(tanh(2))NEWLINENEWLINENEWLINE@SKIP("does this work at all?")NEWLINEdef test_sympy__functions__elementary__integers__RoundFunction():NEWLINE from sympy.functions.elementary.integers import RoundFunctionNEWLINE assert _test_args(RoundFunction())NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__integers__ceiling():NEWLINE from sympy.functions.elementary.integers import ceilingNEWLINE assert _test_args(ceiling(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__integers__floor():NEWLINE from sympy.functions.elementary.integers import floorNEWLINE assert _test_args(floor(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__integers__frac():NEWLINE from sympy.functions.elementary.integers import fracNEWLINE assert _test_args(frac(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__miscellaneous__IdentityFunction():NEWLINE from sympy.functions.elementary.miscellaneous import IdentityFunctionNEWLINE assert _test_args(IdentityFunction())NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__miscellaneous__Max():NEWLINE from sympy.functions.elementary.miscellaneous import MaxNEWLINE assert _test_args(Max(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__miscellaneous__Min():NEWLINE from sympy.functions.elementary.miscellaneous import MinNEWLINE assert _test_args(Min(x, 2))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__elementary__miscellaneous__MinMaxBase():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__piecewise__ExprCondPair():NEWLINE from sympy.functions.elementary.piecewise import ExprCondPairNEWLINE assert _test_args(ExprCondPair(1, True))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__piecewise__Piecewise():NEWLINE from sympy.functions.elementary.piecewise import PiecewiseNEWLINE assert _test_args(Piecewise((1, x >= 0), (0, True)))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__elementary__trigonometric__TrigonometricFunction():NEWLINE passNEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__elementary__trigonometric__ReciprocalTrigonometricFunction():NEWLINE passNEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__elementary__trigonometric__InverseTrigonometricFunction():NEWLINE passNEWLINENEWLINEdef test_sympy__functions__elementary__trigonometric__acos():NEWLINE from sympy.functions.elementary.trigonometric import acosNEWLINE assert _test_args(acos(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__trigonometric__acot():NEWLINE from sympy.functions.elementary.trigonometric import acotNEWLINE assert _test_args(acot(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__trigonometric__asin():NEWLINE from sympy.functions.elementary.trigonometric import asinNEWLINE assert _test_args(asin(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__trigonometric__asec():NEWLINE from sympy.functions.elementary.trigonometric import asecNEWLINE assert _test_args(asec(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__trigonometric__acsc():NEWLINE from sympy.functions.elementary.trigonometric import acscNEWLINE assert _test_args(acsc(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__trigonometric__atan():NEWLINE from sympy.functions.elementary.trigonometric import atanNEWLINE assert _test_args(atan(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__trigonometric__atan2():NEWLINE from sympy.functions.elementary.trigonometric import atan2NEWLINE assert _test_args(atan2(2, 3))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__trigonometric__cos():NEWLINE from sympy.functions.elementary.trigonometric import cosNEWLINE assert _test_args(cos(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__trigonometric__csc():NEWLINE from sympy.functions.elementary.trigonometric import cscNEWLINE assert _test_args(csc(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__trigonometric__cot():NEWLINE from sympy.functions.elementary.trigonometric import cotNEWLINE assert _test_args(cot(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__trigonometric__sin():NEWLINE assert _test_args(sin(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__trigonometric__sinc():NEWLINE from sympy.functions.elementary.trigonometric import sincNEWLINE assert _test_args(sinc(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__trigonometric__sec():NEWLINE from sympy.functions.elementary.trigonometric import secNEWLINE assert _test_args(sec(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__elementary__trigonometric__tan():NEWLINE from sympy.functions.elementary.trigonometric import tanNEWLINE assert _test_args(tan(2))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__special__bessel__BesselBase():NEWLINE passNEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__special__bessel__SphericalBesselBase():NEWLINE passNEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__special__bessel__SphericalHankelBase():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__besseli():NEWLINE from sympy.functions.special.bessel import besseliNEWLINE assert _test_args(besseli(x, 1))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__besselj():NEWLINE from sympy.functions.special.bessel import besseljNEWLINE assert _test_args(besselj(x, 1))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__besselk():NEWLINE from sympy.functions.special.bessel import besselkNEWLINE assert _test_args(besselk(x, 1))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__bessely():NEWLINE from sympy.functions.special.bessel import besselyNEWLINE assert _test_args(bessely(x, 1))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__hankel1():NEWLINE from sympy.functions.special.bessel import hankel1NEWLINE assert _test_args(hankel1(x, 1))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__hankel2():NEWLINE from sympy.functions.special.bessel import hankel2NEWLINE assert _test_args(hankel2(x, 1))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__jn():NEWLINE from sympy.functions.special.bessel import jnNEWLINE assert _test_args(jn(0, x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__yn():NEWLINE from sympy.functions.special.bessel import ynNEWLINE assert _test_args(yn(0, x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__hn1():NEWLINE from sympy.functions.special.bessel import hn1NEWLINE assert _test_args(hn1(0, x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__hn2():NEWLINE from sympy.functions.special.bessel import hn2NEWLINE assert _test_args(hn2(0, x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__AiryBase():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__airyai():NEWLINE from sympy.functions.special.bessel import airyaiNEWLINE assert _test_args(airyai(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__airybi():NEWLINE from sympy.functions.special.bessel import airybiNEWLINE assert _test_args(airybi(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__airyaiprime():NEWLINE from sympy.functions.special.bessel import airyaiprimeNEWLINE assert _test_args(airyaiprime(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__bessel__airybiprime():NEWLINE from sympy.functions.special.bessel import airybiprimeNEWLINE assert _test_args(airybiprime(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__elliptic_integrals__elliptic_k():NEWLINE from sympy.functions.special.elliptic_integrals import elliptic_k as KNEWLINE assert _test_args(K(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__elliptic_integrals__elliptic_f():NEWLINE from sympy.functions.special.elliptic_integrals import elliptic_f as FNEWLINE assert _test_args(F(x, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__elliptic_integrals__elliptic_e():NEWLINE from sympy.functions.special.elliptic_integrals import elliptic_e as ENEWLINE assert _test_args(E(x))NEWLINE assert _test_args(E(x, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__elliptic_integrals__elliptic_pi():NEWLINE from sympy.functions.special.elliptic_integrals import elliptic_pi as PNEWLINE assert _test_args(P(x, y))NEWLINE assert _test_args(P(x, y, z))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__delta_functions__DiracDelta():NEWLINE from sympy.functions.special.delta_functions import DiracDeltaNEWLINE assert _test_args(DiracDelta(x, 1))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__singularity_functions__SingularityFunction():NEWLINE from sympy.functions.special.singularity_functions import SingularityFunctionNEWLINE assert _test_args(SingularityFunction(x, y, z))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__delta_functions__Heaviside():NEWLINE from sympy.functions.special.delta_functions import HeavisideNEWLINE assert _test_args(Heaviside(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__error_functions__erf():NEWLINE from sympy.functions.special.error_functions import erfNEWLINE assert _test_args(erf(2))NEWLINENEWLINEdef test_sympy__functions__special__error_functions__erfc():NEWLINE from sympy.functions.special.error_functions import erfcNEWLINE assert _test_args(erfc(2))NEWLINENEWLINEdef test_sympy__functions__special__error_functions__erfi():NEWLINE from sympy.functions.special.error_functions import erfiNEWLINE assert _test_args(erfi(2))NEWLINENEWLINEdef test_sympy__functions__special__error_functions__erf2():NEWLINE from sympy.functions.special.error_functions import erf2NEWLINE assert _test_args(erf2(2, 3))NEWLINENEWLINEdef test_sympy__functions__special__error_functions__erfinv():NEWLINE from sympy.functions.special.error_functions import erfinvNEWLINE assert _test_args(erfinv(2))NEWLINENEWLINEdef test_sympy__functions__special__error_functions__erfcinv():NEWLINE from sympy.functions.special.error_functions import erfcinvNEWLINE assert _test_args(erfcinv(2))NEWLINENEWLINEdef test_sympy__functions__special__error_functions__erf2inv():NEWLINE from sympy.functions.special.error_functions import erf2invNEWLINE assert _test_args(erf2inv(2, 3))NEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__special__error_functions__FresnelIntegral():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__functions__special__error_functions__fresnels():NEWLINE from sympy.functions.special.error_functions import fresnelsNEWLINE assert _test_args(fresnels(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__error_functions__fresnelc():NEWLINE from sympy.functions.special.error_functions import fresnelcNEWLINE assert _test_args(fresnelc(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__error_functions__erfs():NEWLINE from sympy.functions.special.error_functions import _erfsNEWLINE assert _test_args(_erfs(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__error_functions__Ei():NEWLINE from sympy.functions.special.error_functions import EiNEWLINE assert _test_args(Ei(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__error_functions__li():NEWLINE from sympy.functions.special.error_functions import liNEWLINE assert _test_args(li(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__error_functions__Li():NEWLINE from sympy.functions.special.error_functions import LiNEWLINE assert _test_args(Li(2))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__special__error_functions__TrigonometricIntegral():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__functions__special__error_functions__Si():NEWLINE from sympy.functions.special.error_functions import SiNEWLINE assert _test_args(Si(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__error_functions__Ci():NEWLINE from sympy.functions.special.error_functions import CiNEWLINE assert _test_args(Ci(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__error_functions__Shi():NEWLINE from sympy.functions.special.error_functions import ShiNEWLINE assert _test_args(Shi(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__error_functions__Chi():NEWLINE from sympy.functions.special.error_functions import ChiNEWLINE assert _test_args(Chi(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__error_functions__expint():NEWLINE from sympy.functions.special.error_functions import expintNEWLINE assert _test_args(expint(y, x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__gamma_functions__gamma():NEWLINE from sympy.functions.special.gamma_functions import gammaNEWLINE assert _test_args(gamma(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__gamma_functions__loggamma():NEWLINE from sympy.functions.special.gamma_functions import loggammaNEWLINE assert _test_args(loggamma(2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__gamma_functions__lowergamma():NEWLINE from sympy.functions.special.gamma_functions import lowergammaNEWLINE assert _test_args(lowergamma(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__gamma_functions__polygamma():NEWLINE from sympy.functions.special.gamma_functions import polygammaNEWLINE assert _test_args(polygamma(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__gamma_functions__uppergamma():NEWLINE from sympy.functions.special.gamma_functions import uppergammaNEWLINE assert _test_args(uppergamma(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__beta_functions__beta():NEWLINE from sympy.functions.special.beta_functions import betaNEWLINE assert _test_args(beta(x, x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__mathieu_functions__MathieuBase():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__functions__special__mathieu_functions__mathieus():NEWLINE from sympy.functions.special.mathieu_functions import mathieusNEWLINE assert _test_args(mathieus(1, 1, 1))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__mathieu_functions__mathieuc():NEWLINE from sympy.functions.special.mathieu_functions import mathieucNEWLINE assert _test_args(mathieuc(1, 1, 1))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__mathieu_functions__mathieusprime():NEWLINE from sympy.functions.special.mathieu_functions import mathieusprimeNEWLINE assert _test_args(mathieusprime(1, 1, 1))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__mathieu_functions__mathieucprime():NEWLINE from sympy.functions.special.mathieu_functions import mathieucprimeNEWLINE assert _test_args(mathieucprime(1, 1, 1))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__special__hyper__TupleParametersBase():NEWLINE passNEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__special__hyper__TupleArg():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__functions__special__hyper__hyper():NEWLINE from sympy.functions.special.hyper import hyperNEWLINE assert _test_args(hyper([1, 2, 3], [4, 5], x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__hyper__meijerg():NEWLINE from sympy.functions.special.hyper import meijergNEWLINE assert _test_args(meijerg([1, 2, 3], [4, 5], [6], [], x))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__special__hyper__HyperRep():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__functions__special__hyper__HyperRep_power1():NEWLINE from sympy.functions.special.hyper import HyperRep_power1NEWLINE assert _test_args(HyperRep_power1(x, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__hyper__HyperRep_power2():NEWLINE from sympy.functions.special.hyper import HyperRep_power2NEWLINE assert _test_args(HyperRep_power2(x, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__hyper__HyperRep_log1():NEWLINE from sympy.functions.special.hyper import HyperRep_log1NEWLINE assert _test_args(HyperRep_log1(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__hyper__HyperRep_atanh():NEWLINE from sympy.functions.special.hyper import HyperRep_atanhNEWLINE assert _test_args(HyperRep_atanh(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__hyper__HyperRep_asin1():NEWLINE from sympy.functions.special.hyper import HyperRep_asin1NEWLINE assert _test_args(HyperRep_asin1(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__hyper__HyperRep_asin2():NEWLINE from sympy.functions.special.hyper import HyperRep_asin2NEWLINE assert _test_args(HyperRep_asin2(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__hyper__HyperRep_sqrts1():NEWLINE from sympy.functions.special.hyper import HyperRep_sqrts1NEWLINE assert _test_args(HyperRep_sqrts1(x, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__hyper__HyperRep_sqrts2():NEWLINE from sympy.functions.special.hyper import HyperRep_sqrts2NEWLINE assert _test_args(HyperRep_sqrts2(x, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__hyper__HyperRep_log2():NEWLINE from sympy.functions.special.hyper import HyperRep_log2NEWLINE assert _test_args(HyperRep_log2(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__hyper__HyperRep_cosasin():NEWLINE from sympy.functions.special.hyper import HyperRep_cosasinNEWLINE assert _test_args(HyperRep_cosasin(x, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__hyper__HyperRep_sinasin():NEWLINE from sympy.functions.special.hyper import HyperRep_sinasinNEWLINE assert _test_args(HyperRep_sinasin(x, y))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__functions__special__polynomials__OrthogonalPolynomial():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__functions__special__polynomials__jacobi():NEWLINE from sympy.functions.special.polynomials import jacobiNEWLINE assert _test_args(jacobi(x, 2, 2, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__polynomials__gegenbauer():NEWLINE from sympy.functions.special.polynomials import gegenbauerNEWLINE assert _test_args(gegenbauer(x, 2, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__polynomials__chebyshevt():NEWLINE from sympy.functions.special.polynomials import chebyshevtNEWLINE assert _test_args(chebyshevt(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__polynomials__chebyshevt_root():NEWLINE from sympy.functions.special.polynomials import chebyshevt_rootNEWLINE assert _test_args(chebyshevt_root(3, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__polynomials__chebyshevu():NEWLINE from sympy.functions.special.polynomials import chebyshevuNEWLINE assert _test_args(chebyshevu(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__polynomials__chebyshevu_root():NEWLINE from sympy.functions.special.polynomials import chebyshevu_rootNEWLINE assert _test_args(chebyshevu_root(3, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__polynomials__hermite():NEWLINE from sympy.functions.special.polynomials import hermiteNEWLINE assert _test_args(hermite(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__polynomials__legendre():NEWLINE from sympy.functions.special.polynomials import legendreNEWLINE assert _test_args(legendre(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__polynomials__assoc_legendre():NEWLINE from sympy.functions.special.polynomials import assoc_legendreNEWLINE assert _test_args(assoc_legendre(x, 0, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__polynomials__laguerre():NEWLINE from sympy.functions.special.polynomials import laguerreNEWLINE assert _test_args(laguerre(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__polynomials__assoc_laguerre():NEWLINE from sympy.functions.special.polynomials import assoc_laguerreNEWLINE assert _test_args(assoc_laguerre(x, 0, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__spherical_harmonics__Ynm():NEWLINE from sympy.functions.special.spherical_harmonics import YnmNEWLINE assert _test_args(Ynm(1, 1, x, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__spherical_harmonics__Znm():NEWLINE from sympy.functions.special.spherical_harmonics import ZnmNEWLINE assert _test_args(Znm(1, 1, x, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__tensor_functions__LeviCivita():NEWLINE from sympy.functions.special.tensor_functions import LeviCivitaNEWLINE assert _test_args(LeviCivita(x, y, 2))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__tensor_functions__KroneckerDelta():NEWLINE from sympy.functions.special.tensor_functions import KroneckerDeltaNEWLINE assert _test_args(KroneckerDelta(x, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__zeta_functions__dirichlet_eta():NEWLINE from sympy.functions.special.zeta_functions import dirichlet_etaNEWLINE assert _test_args(dirichlet_eta(x))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__zeta_functions__zeta():NEWLINE from sympy.functions.special.zeta_functions import zetaNEWLINE assert _test_args(zeta(101))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__zeta_functions__lerchphi():NEWLINE from sympy.functions.special.zeta_functions import lerchphiNEWLINE assert _test_args(lerchphi(x, y, z))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__zeta_functions__polylog():NEWLINE from sympy.functions.special.zeta_functions import polylogNEWLINE assert _test_args(polylog(x, y))NEWLINENEWLINENEWLINEdef test_sympy__functions__special__zeta_functions__stieltjes():NEWLINE from sympy.functions.special.zeta_functions import stieltjesNEWLINE assert _test_args(stieltjes(x, y))NEWLINENEWLINENEWLINEdef test_sympy__integrals__integrals__Integral():NEWLINE from sympy.integrals.integrals import IntegralNEWLINE assert _test_args(Integral(2, (x, 0, 1)))NEWLINENEWLINENEWLINEdef test_sympy__integrals__risch__NonElementaryIntegral():NEWLINE from sympy.integrals.risch import NonElementaryIntegralNEWLINE assert _test_args(NonElementaryIntegral(exp(-x**2), x))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__integrals__transforms__IntegralTransform():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__integrals__transforms__MellinTransform():NEWLINE from sympy.integrals.transforms import MellinTransformNEWLINE assert _test_args(MellinTransform(2, x, y))NEWLINENEWLINENEWLINEdef test_sympy__integrals__transforms__InverseMellinTransform():NEWLINE from sympy.integrals.transforms import InverseMellinTransformNEWLINE assert _test_args(InverseMellinTransform(2, x, y, 0, 1))NEWLINENEWLINENEWLINEdef test_sympy__integrals__transforms__LaplaceTransform():NEWLINE from sympy.integrals.transforms import LaplaceTransformNEWLINE assert _test_args(LaplaceTransform(2, x, y))NEWLINENEWLINENEWLINEdef test_sympy__integrals__transforms__InverseLaplaceTransform():NEWLINE from sympy.integrals.transforms import InverseLaplaceTransformNEWLINE assert _test_args(InverseLaplaceTransform(2, x, y, 0))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__integrals__transforms__FourierTypeTransform():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__integrals__transforms__InverseFourierTransform():NEWLINE from sympy.integrals.transforms import InverseFourierTransformNEWLINE assert _test_args(InverseFourierTransform(2, x, y))NEWLINENEWLINENEWLINEdef test_sympy__integrals__transforms__FourierTransform():NEWLINE from sympy.integrals.transforms import FourierTransformNEWLINE assert _test_args(FourierTransform(2, x, y))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__integrals__transforms__SineCosineTypeTransform():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__integrals__transforms__InverseSineTransform():NEWLINE from sympy.integrals.transforms import InverseSineTransformNEWLINE assert _test_args(InverseSineTransform(2, x, y))NEWLINENEWLINENEWLINEdef test_sympy__integrals__transforms__SineTransform():NEWLINE from sympy.integrals.transforms import SineTransformNEWLINE assert _test_args(SineTransform(2, x, y))NEWLINENEWLINENEWLINEdef test_sympy__integrals__transforms__InverseCosineTransform():NEWLINE from sympy.integrals.transforms import InverseCosineTransformNEWLINE assert _test_args(InverseCosineTransform(2, x, y))NEWLINENEWLINENEWLINEdef test_sympy__integrals__transforms__CosineTransform():NEWLINE from sympy.integrals.transforms import CosineTransformNEWLINE assert _test_args(CosineTransform(2, x, y))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__integrals__transforms__HankelTypeTransform():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__integrals__transforms__InverseHankelTransform():NEWLINE from sympy.integrals.transforms import InverseHankelTransformNEWLINE assert _test_args(InverseHankelTransform(2, x, y, 0))NEWLINENEWLINENEWLINEdef test_sympy__integrals__transforms__HankelTransform():NEWLINE from sympy.integrals.transforms import HankelTransformNEWLINE assert _test_args(HankelTransform(2, x, y, 0))NEWLINENEWLINE@XFAILNEWLINEdef test_sympy__liealgebras__cartan_type__CartanType_generator():NEWLINE from sympy.liealgebras.cartan_type import CartanType_generatorNEWLINE assert _test_args(CartanType_generator("A2"))NEWLINENEWLINE@XFAILNEWLINEdef test_sympy__liealgebras__cartan_type__Standard_Cartan():NEWLINE from sympy.liealgebras.cartan_type import Standard_CartanNEWLINE assert _test_args(Standard_Cartan("A", 2))NEWLINENEWLINE@XFAILNEWLINEdef test_sympy__liealgebras__weyl_group__WeylGroup():NEWLINE from sympy.liealgebras.weyl_group import WeylGroupNEWLINE assert _test_args(WeylGroup("B4"))NEWLINENEWLINE@XFAILNEWLINEdef test_sympy__liealgebras__root_system__RootSystem():NEWLINE from sympy.liealgebras.root_system import RootSystemNEWLINE assert _test_args(RootSystem("A2"))NEWLINENEWLINE@XFAILNEWLINEdef test_sympy__liealgebras__type_a__TypeA():NEWLINE from sympy.liealgebras.type_a import TypeANEWLINE assert _test_args(TypeA(2))NEWLINENEWLINE@XFAILNEWLINEdef test_sympy__liealgebras__type_b__TypeB():NEWLINE from sympy.liealgebras.type_b import TypeBNEWLINE assert _test_args(TypeB(4))NEWLINENEWLINE@XFAILNEWLINEdef test_sympy__liealgebras__type_c__TypeC():NEWLINE from sympy.liealgebras.type_c import TypeCNEWLINE assert _test_args(TypeC(4))NEWLINENEWLINE@XFAILNEWLINEdef test_sympy__liealgebras__type_d__TypeD():NEWLINE from sympy.liealgebras.type_d import TypeDNEWLINE assert _test_args(TypeD(4))NEWLINENEWLINE@XFAILNEWLINEdef test_sympy__liealgebras__type_e__TypeE():NEWLINE from sympy.liealgebras.type_e import TypeENEWLINE assert _test_args(TypeE(6))NEWLINENEWLINE@XFAILNEWLINEdef test_sympy__liealgebras__type_f__TypeF():NEWLINE from sympy.liealgebras.type_f import TypeFNEWLINE assert _test_args(TypeF(4))NEWLINENEWLINE@XFAILNEWLINEdef test_sympy__liealgebras__type_g__TypeG():NEWLINE from sympy.liealgebras.type_g import TypeGNEWLINE assert _test_args(TypeG(2))NEWLINENEWLINENEWLINEdef test_sympy__logic__boolalg__And():NEWLINE from sympy.logic.boolalg import AndNEWLINE assert _test_args(And(x, y, 2))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__logic__boolalg__Boolean():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__logic__boolalg__BooleanFunction():NEWLINE from sympy.logic.boolalg import BooleanFunctionNEWLINE assert _test_args(BooleanFunction(1, 2, 3))NEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__logic__boolalg__BooleanAtom():NEWLINE passNEWLINENEWLINEdef test_sympy__logic__boolalg__BooleanTrue():NEWLINE from sympy.logic.boolalg import trueNEWLINE assert _test_args(true)NEWLINENEWLINEdef test_sympy__logic__boolalg__BooleanFalse():NEWLINE from sympy.logic.boolalg import falseNEWLINE assert _test_args(false)NEWLINENEWLINEdef test_sympy__logic__boolalg__Equivalent():NEWLINE from sympy.logic.boolalg import EquivalentNEWLINE assert _test_args(Equivalent(x, 2))NEWLINENEWLINENEWLINEdef test_sympy__logic__boolalg__ITE():NEWLINE from sympy.logic.boolalg import ITENEWLINE assert _test_args(ITE(x, y, 2))NEWLINENEWLINENEWLINEdef test_sympy__logic__boolalg__Implies():NEWLINE from sympy.logic.boolalg import ImpliesNEWLINE assert _test_args(Implies(x, y))NEWLINENEWLINENEWLINEdef test_sympy__logic__boolalg__Nand():NEWLINE from sympy.logic.boolalg import NandNEWLINE assert _test_args(Nand(x, y, 2))NEWLINENEWLINENEWLINEdef test_sympy__logic__boolalg__Nor():NEWLINE from sympy.logic.boolalg import NorNEWLINE assert _test_args(Nor(x, y))NEWLINENEWLINENEWLINEdef test_sympy__logic__boolalg__Not():NEWLINE from sympy.logic.boolalg import NotNEWLINE assert _test_args(Not(x))NEWLINENEWLINENEWLINEdef test_sympy__logic__boolalg__Or():NEWLINE from sympy.logic.boolalg import OrNEWLINE assert _test_args(Or(x, y))NEWLINENEWLINENEWLINEdef test_sympy__logic__boolalg__Xor():NEWLINE from sympy.logic.boolalg import XorNEWLINE assert _test_args(Xor(x, y, 2))NEWLINENEWLINEdef test_sympy__logic__boolalg__Xnor():NEWLINE from sympy.logic.boolalg import XnorNEWLINE assert _test_args(Xnor(x, y, 2))NEWLINENEWLINENEWLINEdef test_sympy__matrices__matrices__DeferredVector():NEWLINE from sympy.matrices.matrices import DeferredVectorNEWLINE assert _test_args(DeferredVector("X"))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__matrices__expressions__matexpr__MatrixBase():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__matrices__immutable__ImmutableDenseMatrix():NEWLINE from sympy.matrices.immutable import ImmutableDenseMatrixNEWLINE m = ImmutableDenseMatrix([[1, 2], [3, 4]])NEWLINE assert _test_args(m)NEWLINE assert _test_args(Basic(*list(m)))NEWLINE m = ImmutableDenseMatrix(1, 1, [1])NEWLINE assert _test_args(m)NEWLINE assert _test_args(Basic(*list(m)))NEWLINE m = ImmutableDenseMatrix(2, 2, lambda i, j: 1)NEWLINE assert m[0, 0] is S.OneNEWLINE m = ImmutableDenseMatrix(2, 2, lambda i, j: 1/(1 + i) + 1/(1 + j))NEWLINE assert m[1, 1] is S.One # true div. will give 1.0 if i,j not sympifiedNEWLINE assert _test_args(m)NEWLINE assert _test_args(Basic(*list(m)))NEWLINENEWLINENEWLINEdef test_sympy__matrices__immutable__ImmutableSparseMatrix():NEWLINE from sympy.matrices.immutable import ImmutableSparseMatrixNEWLINE m = ImmutableSparseMatrix([[1, 2], [3, 4]])NEWLINE assert _test_args(m)NEWLINE assert _test_args(Basic(*list(m)))NEWLINE m = ImmutableSparseMatrix(1, 1, {(0, 0): 1})NEWLINE assert _test_args(m)NEWLINE assert _test_args(Basic(*list(m)))NEWLINE m = ImmutableSparseMatrix(1, 1, [1])NEWLINE assert _test_args(m)NEWLINE assert _test_args(Basic(*list(m)))NEWLINE m = ImmutableSparseMatrix(2, 2, lambda i, j: 1)NEWLINE assert m[0, 0] is S.OneNEWLINE m = ImmutableSparseMatrix(2, 2, lambda i, j: 1/(1 + i) + 1/(1 + j))NEWLINE assert m[1, 1] is S.One # true div. will give 1.0 if i,j not sympifiedNEWLINE assert _test_args(m)NEWLINE assert _test_args(Basic(*list(m)))NEWLINENEWLINENEWLINEdef test_sympy__matrices__expressions__slice__MatrixSlice():NEWLINE from sympy.matrices.expressions.slice import MatrixSliceNEWLINE from sympy.matrices.expressions import MatrixSymbolNEWLINE X = MatrixSymbol('X', 4, 4)NEWLINE assert _test_args(MatrixSlice(X, (0, 2), (0, 2)))NEWLINENEWLINENEWLINEdef test_sympy__matrices__expressions__blockmatrix__BlockDiagMatrix():NEWLINE from sympy.matrices.expressions.blockmatrix import BlockDiagMatrixNEWLINE from sympy.matrices.expressions import MatrixSymbolNEWLINE X = MatrixSymbol('X', x, x)NEWLINE Y = MatrixSymbol('Y', y, y)NEWLINE assert _test_args(BlockDiagMatrix(X, Y))NEWLINENEWLINENEWLINEdef test_sympy__matrices__expressions__blockmatrix__BlockMatrix():NEWLINE from sympy.matrices.expressions.blockmatrix import BlockMatrixNEWLINE from sympy.matrices.expressions import MatrixSymbol, ZeroMatrixNEWLINE X = MatrixSymbol('X', x, x)NEWLINE Y = MatrixSymbol('Y', y, y)NEWLINE Z = MatrixSymbol('Z', x, y)NEWLINE O = ZeroMatrix(y, x)NEWLINE assert _test_args(BlockMatrix([[X, Z], [O, Y]]))NEWLINENEWLINENEWLINEdef test_sympy__matrices__expressions__inverse__Inverse():NEWLINE from sympy.matrices.expressions.inverse import InverseNEWLINE from sympy.matrices.expressions import MatrixSymbolNEWLINE assert _test_args(Inverse(MatrixSymbol('A', 3, 3)))NEWLINENEWLINENEWLINEdef test_sympy__matrices__expressions__matadd__MatAdd():NEWLINE from sympy.matrices.expressions.matadd import MatAddNEWLINE from sympy.matrices.expressions import MatrixSymbolNEWLINE X = MatrixSymbol('X', x, y)NEWLINE Y = MatrixSymbol('Y', x, y)NEWLINE assert _test_args(MatAdd(X, Y))NEWLINENEWLINENEWLINEdef test_sympy__matrices__expressions__matexpr__Identity():NEWLINE from sympy.matrices.expressions.matexpr import IdentityNEWLINE assert _test_args(Identity(3))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__matrices__expressions__matexpr__MatrixExpr():NEWLINE passNEWLINENEWLINEdef test_sympy__matrices__expressions__matexpr__MatrixElement():NEWLINE from sympy.matrices.expressions.matexpr import MatrixSymbol, MatrixElementNEWLINE from sympy import SNEWLINE assert _test_args(MatrixElement(MatrixSymbol('A', 3, 5), S(2), S(3)))NEWLINENEWLINE@XFAILNEWLINEdef test_sympy__matrices__expressions__matexpr__MatrixSymbol():NEWLINE from sympy.matrices.expressions.matexpr import MatrixSymbolNEWLINE assert _test_args(MatrixSymbol('A', 3, 5))NEWLINENEWLINENEWLINEdef test_sympy__matrices__expressions__matexpr__ZeroMatrix():NEWLINE from sympy.matrices.expressions.matexpr import ZeroMatrixNEWLINE assert _test_args(ZeroMatrix(3, 5))NEWLINENEWLINENEWLINEdef test_sympy__matrices__expressions__matmul__MatMul():NEWLINE from sympy.matrices.expressions.matmul import MatMulNEWLINE from sympy.matrices.expressions import MatrixSymbolNEWLINE X = MatrixSymbol('X', x, y)NEWLINE Y = MatrixSymbol('Y', y, x)NEWLINE assert _test_args(MatMul(X, Y))NEWLINENEWLINENEWLINEdef test_sympy__matrices__expressions__dotproduct__DotProduct():NEWLINE from sympy.matrices.expressions.dotproduct import DotProductNEWLINE from sympy.matrices.expressions import MatrixSymbolNEWLINE X = MatrixSymbol('X', x, 1)NEWLINE Y = MatrixSymbol('Y', x, 1)NEWLINE assert _test_args(DotProduct(X, Y))NEWLINENEWLINEdef test_sympy__matrices__expressions__diagonal__DiagonalMatrix():NEWLINE from sympy.matrices.expressions.diagonal import DiagonalMatrixNEWLINE from sympy.matrices.expressions import MatrixSymbolNEWLINE x = MatrixSymbol('x', 10, 1)NEWLINE assert _test_args(DiagonalMatrix(x))NEWLINENEWLINEdef test_sympy__matrices__expressions__diagonal__DiagonalOf():NEWLINE from sympy.matrices.expressions.diagonal import DiagonalOfNEWLINE from sympy.matrices.expressions import MatrixSymbolNEWLINE X = MatrixSymbol('x', 10, 10)NEWLINE assert _test_args(DiagonalOf(X))NEWLINENEWLINEdef test_sympy__matrices__expressions__hadamard__HadamardProduct():NEWLINE from sympy.matrices.expressions.hadamard import HadamardProductNEWLINE from sympy.matrices.expressions import MatrixSymbolNEWLINE X = MatrixSymbol('X', x, y)NEWLINE Y = MatrixSymbol('Y', x, y)NEWLINE assert _test_args(HadamardProduct(X, Y))NEWLINENEWLINENEWLINEdef test_sympy__matrices__expressions__matpow__MatPow():NEWLINE from sympy.matrices.expressions.matpow import MatPowNEWLINE from sympy.matrices.expressions import MatrixSymbolNEWLINE X = MatrixSymbol('X', x, x)NEWLINE assert _test_args(MatPow(X, 2))NEWLINENEWLINENEWLINEdef test_sympy__matrices__expressions__transpose__Transpose():NEWLINE from sympy.matrices.expressions.transpose import TransposeNEWLINE from sympy.matrices.expressions import MatrixSymbolNEWLINE assert _test_args(Transpose(MatrixSymbol('A', 3, 5)))NEWLINENEWLINENEWLINEdef test_sympy__matrices__expressions__adjoint__Adjoint():NEWLINE from sympy.matrices.expressions.adjoint import AdjointNEWLINE from sympy.matrices.expressions import MatrixSymbolNEWLINE assert _test_args(Adjoint(MatrixSymbol('A', 3, 5)))NEWLINENEWLINENEWLINEdef test_sympy__matrices__expressions__trace__Trace():NEWLINE from sympy.matrices.expressions.trace import TraceNEWLINE from sympy.matrices.expressions import MatrixSymbolNEWLINE assert _test_args(Trace(MatrixSymbol('A', 3, 3)))NEWLINENEWLINEdef test_sympy__matrices__expressions__determinant__Determinant():NEWLINE from sympy.matrices.expressions.determinant import DeterminantNEWLINE from sympy.matrices.expressions import MatrixSymbolNEWLINE assert _test_args(Determinant(MatrixSymbol('A', 3, 3)))NEWLINENEWLINENEWLINEdef test_sympy__matrices__expressions__funcmatrix__FunctionMatrix():NEWLINE from sympy.matrices.expressions.funcmatrix import FunctionMatrixNEWLINE from sympy import symbolsNEWLINE i, j = symbols('i,j')NEWLINE assert _test_args(FunctionMatrix(3, 3, Lambda((i, j), i - j) ))NEWLINENEWLINEdef test_sympy__matrices__expressions__fourier__DFT():NEWLINE from sympy.matrices.expressions.fourier import DFTNEWLINE from sympy import SNEWLINE assert _test_args(DFT(S(2)))NEWLINENEWLINEdef test_sympy__matrices__expressions__fourier__IDFT():NEWLINE from sympy.matrices.expressions.fourier import IDFTNEWLINE from sympy import SNEWLINE assert _test_args(IDFT(S(2)))NEWLINENEWLINEfrom sympy.matrices.expressions import MatrixSymbolNEWLINEX = MatrixSymbol('X', 10, 10)NEWLINENEWLINEdef test_sympy__matrices__expressions__factorizations__LofLU():NEWLINE from sympy.matrices.expressions.factorizations import LofLUNEWLINE assert _test_args(LofLU(X))NEWLINENEWLINEdef test_sympy__matrices__expressions__factorizations__UofLU():NEWLINE from sympy.matrices.expressions.factorizations import UofLUNEWLINE assert _test_args(UofLU(X))NEWLINENEWLINEdef test_sympy__matrices__expressions__factorizations__QofQR():NEWLINE from sympy.matrices.expressions.factorizations import QofQRNEWLINE assert _test_args(QofQR(X))NEWLINENEWLINEdef test_sympy__matrices__expressions__factorizations__RofQR():NEWLINE from sympy.matrices.expressions.factorizations import RofQRNEWLINE assert _test_args(RofQR(X))NEWLINENEWLINEdef test_sympy__matrices__expressions__factorizations__LofCholesky():NEWLINE from sympy.matrices.expressions.factorizations import LofCholeskyNEWLINE assert _test_args(LofCholesky(X))NEWLINENEWLINEdef test_sympy__matrices__expressions__factorizations__UofCholesky():NEWLINE from sympy.matrices.expressions.factorizations import UofCholeskyNEWLINE assert _test_args(UofCholesky(X))NEWLINENEWLINEdef test_sympy__matrices__expressions__factorizations__EigenVectors():NEWLINE from sympy.matrices.expressions.factorizations import EigenVectorsNEWLINE assert _test_args(EigenVectors(X))NEWLINENEWLINEdef test_sympy__matrices__expressions__factorizations__EigenValues():NEWLINE from sympy.matrices.expressions.factorizations import EigenValuesNEWLINE assert _test_args(EigenValues(X))NEWLINENEWLINEdef test_sympy__matrices__expressions__factorizations__UofSVD():NEWLINE from sympy.matrices.expressions.factorizations import UofSVDNEWLINE assert _test_args(UofSVD(X))NEWLINENEWLINEdef test_sympy__matrices__expressions__factorizations__VofSVD():NEWLINE from sympy.matrices.expressions.factorizations import VofSVDNEWLINE assert _test_args(VofSVD(X))NEWLINENEWLINEdef test_sympy__matrices__expressions__factorizations__SofSVD():NEWLINE from sympy.matrices.expressions.factorizations import SofSVDNEWLINE assert _test_args(SofSVD(X))NEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__matrices__expressions__factorizations__Factorization():NEWLINE passNEWLINENEWLINEdef test_sympy__physics__vector__frame__CoordinateSym():NEWLINE from sympy.physics.vector import CoordinateSymNEWLINE from sympy.physics.vector import ReferenceFrameNEWLINE assert _test_args(CoordinateSym('R_x', ReferenceFrame('R'), 0))NEWLINENEWLINENEWLINEdef test_sympy__physics__paulialgebra__Pauli():NEWLINE from sympy.physics.paulialgebra import PauliNEWLINE assert _test_args(Pauli(1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__anticommutator__AntiCommutator():NEWLINE from sympy.physics.quantum.anticommutator import AntiCommutatorNEWLINE assert _test_args(AntiCommutator(x, y))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cartesian__PositionBra3D():NEWLINE from sympy.physics.quantum.cartesian import PositionBra3DNEWLINE assert _test_args(PositionBra3D(x, y, z))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cartesian__PositionKet3D():NEWLINE from sympy.physics.quantum.cartesian import PositionKet3DNEWLINE assert _test_args(PositionKet3D(x, y, z))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cartesian__PositionState3D():NEWLINE from sympy.physics.quantum.cartesian import PositionState3DNEWLINE assert _test_args(PositionState3D(x, y, z))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cartesian__PxBra():NEWLINE from sympy.physics.quantum.cartesian import PxBraNEWLINE assert _test_args(PxBra(x, y, z))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cartesian__PxKet():NEWLINE from sympy.physics.quantum.cartesian import PxKetNEWLINE assert _test_args(PxKet(x, y, z))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cartesian__PxOp():NEWLINE from sympy.physics.quantum.cartesian import PxOpNEWLINE assert _test_args(PxOp(x, y, z))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cartesian__XBra():NEWLINE from sympy.physics.quantum.cartesian import XBraNEWLINE assert _test_args(XBra(x))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cartesian__XKet():NEWLINE from sympy.physics.quantum.cartesian import XKetNEWLINE assert _test_args(XKet(x))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cartesian__XOp():NEWLINE from sympy.physics.quantum.cartesian import XOpNEWLINE assert _test_args(XOp(x))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cartesian__YOp():NEWLINE from sympy.physics.quantum.cartesian import YOpNEWLINE assert _test_args(YOp(x))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cartesian__ZOp():NEWLINE from sympy.physics.quantum.cartesian import ZOpNEWLINE assert _test_args(ZOp(x))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cg__CG():NEWLINE from sympy.physics.quantum.cg import CGNEWLINE from sympy import SNEWLINE assert _test_args(CG(S(3)/2, S(3)/2, S(1)/2, -S(1)/2, 1, 1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cg__Wigner3j():NEWLINE from sympy.physics.quantum.cg import Wigner3jNEWLINE assert _test_args(Wigner3j(6, 0, 4, 0, 2, 0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cg__Wigner6j():NEWLINE from sympy.physics.quantum.cg import Wigner6jNEWLINE assert _test_args(Wigner6j(1, 2, 3, 2, 1, 2))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__cg__Wigner9j():NEWLINE from sympy.physics.quantum.cg import Wigner9jNEWLINE assert _test_args(Wigner9j(2, 1, 1, S(3)/2, S(1)/2, 1, S(1)/2, S(1)/2, 0))NEWLINENEWLINEdef test_sympy__physics__quantum__circuitplot__Mz():NEWLINE from sympy.physics.quantum.circuitplot import MzNEWLINE assert _test_args(Mz(0))NEWLINENEWLINEdef test_sympy__physics__quantum__circuitplot__Mx():NEWLINE from sympy.physics.quantum.circuitplot import MxNEWLINE assert _test_args(Mx(0))NEWLINENEWLINEdef test_sympy__physics__quantum__commutator__Commutator():NEWLINE from sympy.physics.quantum.commutator import CommutatorNEWLINE A, B = symbols('A,B', commutative=False)NEWLINE assert _test_args(Commutator(A, B))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__constants__HBar():NEWLINE from sympy.physics.quantum.constants import HBarNEWLINE assert _test_args(HBar())NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__dagger__Dagger():NEWLINE from sympy.physics.quantum.dagger import DaggerNEWLINE from sympy.physics.quantum.state import KetNEWLINE assert _test_args(Dagger(Dagger(Ket('psi'))))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__CGate():NEWLINE from sympy.physics.quantum.gate import CGate, GateNEWLINE assert _test_args(CGate((0, 1), Gate(2)))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__CGateS():NEWLINE from sympy.physics.quantum.gate import CGateS, GateNEWLINE assert _test_args(CGateS((0, 1), Gate(2)))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__CNotGate():NEWLINE from sympy.physics.quantum.gate import CNotGateNEWLINE assert _test_args(CNotGate(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__Gate():NEWLINE from sympy.physics.quantum.gate import GateNEWLINE assert _test_args(Gate(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__HadamardGate():NEWLINE from sympy.physics.quantum.gate import HadamardGateNEWLINE assert _test_args(HadamardGate(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__IdentityGate():NEWLINE from sympy.physics.quantum.gate import IdentityGateNEWLINE assert _test_args(IdentityGate(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__OneQubitGate():NEWLINE from sympy.physics.quantum.gate import OneQubitGateNEWLINE assert _test_args(OneQubitGate(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__PhaseGate():NEWLINE from sympy.physics.quantum.gate import PhaseGateNEWLINE assert _test_args(PhaseGate(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__SwapGate():NEWLINE from sympy.physics.quantum.gate import SwapGateNEWLINE assert _test_args(SwapGate(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__TGate():NEWLINE from sympy.physics.quantum.gate import TGateNEWLINE assert _test_args(TGate(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__TwoQubitGate():NEWLINE from sympy.physics.quantum.gate import TwoQubitGateNEWLINE assert _test_args(TwoQubitGate(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__UGate():NEWLINE from sympy.physics.quantum.gate import UGateNEWLINE from sympy.matrices.immutable import ImmutableDenseMatrixNEWLINE from sympy import Integer, TupleNEWLINE assert _test_args(NEWLINE UGate(Tuple(Integer(1)), ImmutableDenseMatrix([[1, 0], [0, 2]])))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__XGate():NEWLINE from sympy.physics.quantum.gate import XGateNEWLINE assert _test_args(XGate(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__YGate():NEWLINE from sympy.physics.quantum.gate import YGateNEWLINE assert _test_args(YGate(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__gate__ZGate():NEWLINE from sympy.physics.quantum.gate import ZGateNEWLINE assert _test_args(ZGate(0))NEWLINENEWLINENEWLINE@SKIP("TODO: sympy.physics")NEWLINEdef test_sympy__physics__quantum__grover__OracleGate():NEWLINE from sympy.physics.quantum.grover import OracleGateNEWLINE assert _test_args(OracleGate())NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__grover__WGate():NEWLINE from sympy.physics.quantum.grover import WGateNEWLINE assert _test_args(WGate(1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__hilbert__ComplexSpace():NEWLINE from sympy.physics.quantum.hilbert import ComplexSpaceNEWLINE assert _test_args(ComplexSpace(x))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__hilbert__DirectSumHilbertSpace():NEWLINE from sympy.physics.quantum.hilbert import DirectSumHilbertSpace, ComplexSpace, FockSpaceNEWLINE c = ComplexSpace(2)NEWLINE f = FockSpace()NEWLINE assert _test_args(DirectSumHilbertSpace(c, f))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__hilbert__FockSpace():NEWLINE from sympy.physics.quantum.hilbert import FockSpaceNEWLINE assert _test_args(FockSpace())NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__hilbert__HilbertSpace():NEWLINE from sympy.physics.quantum.hilbert import HilbertSpaceNEWLINE assert _test_args(HilbertSpace())NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__hilbert__L2():NEWLINE from sympy.physics.quantum.hilbert import L2NEWLINE from sympy import oo, IntervalNEWLINE assert _test_args(L2(Interval(0, oo)))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__hilbert__TensorPowerHilbertSpace():NEWLINE from sympy.physics.quantum.hilbert import TensorPowerHilbertSpace, FockSpaceNEWLINE f = FockSpace()NEWLINE assert _test_args(TensorPowerHilbertSpace(f, 2))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__hilbert__TensorProductHilbertSpace():NEWLINE from sympy.physics.quantum.hilbert import TensorProductHilbertSpace, FockSpace, ComplexSpaceNEWLINE c = ComplexSpace(2)NEWLINE f = FockSpace()NEWLINE assert _test_args(TensorProductHilbertSpace(f, c))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__innerproduct__InnerProduct():NEWLINE from sympy.physics.quantum import Bra, Ket, InnerProductNEWLINE b = Bra('b')NEWLINE k = Ket('k')NEWLINE assert _test_args(InnerProduct(b, k))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__operator__DifferentialOperator():NEWLINE from sympy.physics.quantum.operator import DifferentialOperatorNEWLINE from sympy import Derivative, FunctionNEWLINE f = Function('f')NEWLINE assert _test_args(DifferentialOperator(1/x*Derivative(f(x), x), f(x)))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__operator__HermitianOperator():NEWLINE from sympy.physics.quantum.operator import HermitianOperatorNEWLINE assert _test_args(HermitianOperator('H'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__operator__IdentityOperator():NEWLINE from sympy.physics.quantum.operator import IdentityOperatorNEWLINE assert _test_args(IdentityOperator(5))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__operator__Operator():NEWLINE from sympy.physics.quantum.operator import OperatorNEWLINE assert _test_args(Operator('A'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__operator__OuterProduct():NEWLINE from sympy.physics.quantum.operator import OuterProductNEWLINE from sympy.physics.quantum import Ket, BraNEWLINE b = Bra('b')NEWLINE k = Ket('k')NEWLINE assert _test_args(OuterProduct(k, b))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__operator__UnitaryOperator():NEWLINE from sympy.physics.quantum.operator import UnitaryOperatorNEWLINE assert _test_args(UnitaryOperator('U'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__piab__PIABBra():NEWLINE from sympy.physics.quantum.piab import PIABBraNEWLINE assert _test_args(PIABBra('B'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__boson__BosonOp():NEWLINE from sympy.physics.quantum.boson import BosonOpNEWLINE assert _test_args(BosonOp('a'))NEWLINE assert _test_args(BosonOp('a', False))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__boson__BosonFockKet():NEWLINE from sympy.physics.quantum.boson import BosonFockKetNEWLINE assert _test_args(BosonFockKet(1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__boson__BosonFockBra():NEWLINE from sympy.physics.quantum.boson import BosonFockBraNEWLINE assert _test_args(BosonFockBra(1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__boson__BosonCoherentKet():NEWLINE from sympy.physics.quantum.boson import BosonCoherentKetNEWLINE assert _test_args(BosonCoherentKet(1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__boson__BosonCoherentBra():NEWLINE from sympy.physics.quantum.boson import BosonCoherentBraNEWLINE assert _test_args(BosonCoherentBra(1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__fermion__FermionOp():NEWLINE from sympy.physics.quantum.fermion import FermionOpNEWLINE assert _test_args(FermionOp('c'))NEWLINE assert _test_args(FermionOp('c', False))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__fermion__FermionFockKet():NEWLINE from sympy.physics.quantum.fermion import FermionFockKetNEWLINE assert _test_args(FermionFockKet(1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__fermion__FermionFockBra():NEWLINE from sympy.physics.quantum.fermion import FermionFockBraNEWLINE assert _test_args(FermionFockBra(1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__pauli__SigmaOpBase():NEWLINE from sympy.physics.quantum.pauli import SigmaOpBaseNEWLINE assert _test_args(SigmaOpBase())NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__pauli__SigmaX():NEWLINE from sympy.physics.quantum.pauli import SigmaXNEWLINE assert _test_args(SigmaX())NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__pauli__SigmaY():NEWLINE from sympy.physics.quantum.pauli import SigmaYNEWLINE assert _test_args(SigmaY())NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__pauli__SigmaZ():NEWLINE from sympy.physics.quantum.pauli import SigmaZNEWLINE assert _test_args(SigmaZ())NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__pauli__SigmaMinus():NEWLINE from sympy.physics.quantum.pauli import SigmaMinusNEWLINE assert _test_args(SigmaMinus())NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__pauli__SigmaPlus():NEWLINE from sympy.physics.quantum.pauli import SigmaPlusNEWLINE assert _test_args(SigmaPlus())NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__pauli__SigmaZKet():NEWLINE from sympy.physics.quantum.pauli import SigmaZKetNEWLINE assert _test_args(SigmaZKet(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__pauli__SigmaZBra():NEWLINE from sympy.physics.quantum.pauli import SigmaZBraNEWLINE assert _test_args(SigmaZBra(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__piab__PIABHamiltonian():NEWLINE from sympy.physics.quantum.piab import PIABHamiltonianNEWLINE assert _test_args(PIABHamiltonian('P'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__piab__PIABKet():NEWLINE from sympy.physics.quantum.piab import PIABKetNEWLINE assert _test_args(PIABKet('K'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__qexpr__QExpr():NEWLINE from sympy.physics.quantum.qexpr import QExprNEWLINE assert _test_args(QExpr(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__qft__Fourier():NEWLINE from sympy.physics.quantum.qft import FourierNEWLINE assert _test_args(Fourier(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__qft__IQFT():NEWLINE from sympy.physics.quantum.qft import IQFTNEWLINE assert _test_args(IQFT(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__qft__QFT():NEWLINE from sympy.physics.quantum.qft import QFTNEWLINE assert _test_args(QFT(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__qft__RkGate():NEWLINE from sympy.physics.quantum.qft import RkGateNEWLINE assert _test_args(RkGate(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__qubit__IntQubit():NEWLINE from sympy.physics.quantum.qubit import IntQubitNEWLINE assert _test_args(IntQubit(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__qubit__IntQubitBra():NEWLINE from sympy.physics.quantum.qubit import IntQubitBraNEWLINE assert _test_args(IntQubitBra(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__qubit__IntQubitState():NEWLINE from sympy.physics.quantum.qubit import IntQubitState, QubitStateNEWLINE assert _test_args(IntQubitState(QubitState(0, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__qubit__Qubit():NEWLINE from sympy.physics.quantum.qubit import QubitNEWLINE assert _test_args(Qubit(0, 0, 0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__qubit__QubitBra():NEWLINE from sympy.physics.quantum.qubit import QubitBraNEWLINE assert _test_args(QubitBra('1', 0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__qubit__QubitState():NEWLINE from sympy.physics.quantum.qubit import QubitStateNEWLINE assert _test_args(QubitState(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__density__Density():NEWLINE from sympy.physics.quantum.density import DensityNEWLINE from sympy.physics.quantum.state import KetNEWLINE assert _test_args(Density([Ket(0), 0.5], [Ket(1), 0.5]))NEWLINENEWLINENEWLINE@SKIP("TODO: sympy.physics.quantum.shor: Cmod Not Implemented")NEWLINEdef test_sympy__physics__quantum__shor__CMod():NEWLINE from sympy.physics.quantum.shor import CModNEWLINE assert _test_args(CMod())NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__CoupledSpinState():NEWLINE from sympy.physics.quantum.spin import CoupledSpinStateNEWLINE assert _test_args(CoupledSpinState(1, 0, (1, 1)))NEWLINE assert _test_args(CoupledSpinState(1, 0, (1, S(1)/2, S(1)/2)))NEWLINE assert _test_args(CoupledSpinState(NEWLINE 1, 0, (1, S(1)/2, S(1)/2), ((2, 3, S(1)/2), (1, 2, 1)) ))NEWLINE j, m, j1, j2, j3, j12, x = symbols('j m j1:4 j12 x')NEWLINE assert CoupledSpinState(NEWLINE j, m, (j1, j2, j3)).subs(j2, x) == CoupledSpinState(j, m, (j1, x, j3))NEWLINE assert CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, j12), (1, 2, j)) ).subs(j12, x) == \NEWLINE CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, x), (1, 2, j)) )NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__J2Op():NEWLINE from sympy.physics.quantum.spin import J2OpNEWLINE assert _test_args(J2Op('J'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JminusOp():NEWLINE from sympy.physics.quantum.spin import JminusOpNEWLINE assert _test_args(JminusOp('J'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JplusOp():NEWLINE from sympy.physics.quantum.spin import JplusOpNEWLINE assert _test_args(JplusOp('J'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JxBra():NEWLINE from sympy.physics.quantum.spin import JxBraNEWLINE assert _test_args(JxBra(1, 0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JxBraCoupled():NEWLINE from sympy.physics.quantum.spin import JxBraCoupledNEWLINE assert _test_args(JxBraCoupled(1, 0, (1, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JxKet():NEWLINE from sympy.physics.quantum.spin import JxKetNEWLINE assert _test_args(JxKet(1, 0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JxKetCoupled():NEWLINE from sympy.physics.quantum.spin import JxKetCoupledNEWLINE assert _test_args(JxKetCoupled(1, 0, (1, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JxOp():NEWLINE from sympy.physics.quantum.spin import JxOpNEWLINE assert _test_args(JxOp('J'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JyBra():NEWLINE from sympy.physics.quantum.spin import JyBraNEWLINE assert _test_args(JyBra(1, 0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JyBraCoupled():NEWLINE from sympy.physics.quantum.spin import JyBraCoupledNEWLINE assert _test_args(JyBraCoupled(1, 0, (1, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JyKet():NEWLINE from sympy.physics.quantum.spin import JyKetNEWLINE assert _test_args(JyKet(1, 0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JyKetCoupled():NEWLINE from sympy.physics.quantum.spin import JyKetCoupledNEWLINE assert _test_args(JyKetCoupled(1, 0, (1, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JyOp():NEWLINE from sympy.physics.quantum.spin import JyOpNEWLINE assert _test_args(JyOp('J'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JzBra():NEWLINE from sympy.physics.quantum.spin import JzBraNEWLINE assert _test_args(JzBra(1, 0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JzBraCoupled():NEWLINE from sympy.physics.quantum.spin import JzBraCoupledNEWLINE assert _test_args(JzBraCoupled(1, 0, (1, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JzKet():NEWLINE from sympy.physics.quantum.spin import JzKetNEWLINE assert _test_args(JzKet(1, 0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JzKetCoupled():NEWLINE from sympy.physics.quantum.spin import JzKetCoupledNEWLINE assert _test_args(JzKetCoupled(1, 0, (1, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__JzOp():NEWLINE from sympy.physics.quantum.spin import JzOpNEWLINE assert _test_args(JzOp('J'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__Rotation():NEWLINE from sympy.physics.quantum.spin import RotationNEWLINE assert _test_args(Rotation(pi, 0, pi/2))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__SpinState():NEWLINE from sympy.physics.quantum.spin import SpinStateNEWLINE assert _test_args(SpinState(1, 0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__spin__WignerD():NEWLINE from sympy.physics.quantum.spin import WignerDNEWLINE assert _test_args(WignerD(0, 1, 2, 3, 4, 5))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__state__Bra():NEWLINE from sympy.physics.quantum.state import BraNEWLINE assert _test_args(Bra(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__state__BraBase():NEWLINE from sympy.physics.quantum.state import BraBaseNEWLINE assert _test_args(BraBase(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__state__Ket():NEWLINE from sympy.physics.quantum.state import KetNEWLINE assert _test_args(Ket(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__state__KetBase():NEWLINE from sympy.physics.quantum.state import KetBaseNEWLINE assert _test_args(KetBase(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__state__State():NEWLINE from sympy.physics.quantum.state import StateNEWLINE assert _test_args(State(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__state__StateBase():NEWLINE from sympy.physics.quantum.state import StateBaseNEWLINE assert _test_args(StateBase(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__state__TimeDepBra():NEWLINE from sympy.physics.quantum.state import TimeDepBraNEWLINE assert _test_args(TimeDepBra('psi', 't'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__state__TimeDepKet():NEWLINE from sympy.physics.quantum.state import TimeDepKetNEWLINE assert _test_args(TimeDepKet('psi', 't'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__state__TimeDepState():NEWLINE from sympy.physics.quantum.state import TimeDepStateNEWLINE assert _test_args(TimeDepState('psi', 't'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__state__Wavefunction():NEWLINE from sympy.physics.quantum.state import WavefunctionNEWLINE from sympy.functions import sinNEWLINE from sympy import PiecewiseNEWLINE n = 1NEWLINE L = 1NEWLINE g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True))NEWLINE assert _test_args(Wavefunction(g, x))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__tensorproduct__TensorProduct():NEWLINE from sympy.physics.quantum.tensorproduct import TensorProductNEWLINE assert _test_args(TensorProduct(x, y))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__identitysearch__GateIdentity():NEWLINE from sympy.physics.quantum.gate import XNEWLINE from sympy.physics.quantum.identitysearch import GateIdentityNEWLINE assert _test_args(GateIdentity(X(0), X(0)))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__sho1d__SHOOp():NEWLINE from sympy.physics.quantum.sho1d import SHOOpNEWLINE assert _test_args(SHOOp('a'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__sho1d__RaisingOp():NEWLINE from sympy.physics.quantum.sho1d import RaisingOpNEWLINE assert _test_args(RaisingOp('a'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__sho1d__LoweringOp():NEWLINE from sympy.physics.quantum.sho1d import LoweringOpNEWLINE assert _test_args(LoweringOp('a'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__sho1d__NumberOp():NEWLINE from sympy.physics.quantum.sho1d import NumberOpNEWLINE assert _test_args(NumberOp('N'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__sho1d__Hamiltonian():NEWLINE from sympy.physics.quantum.sho1d import HamiltonianNEWLINE assert _test_args(Hamiltonian('H'))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__sho1d__SHOState():NEWLINE from sympy.physics.quantum.sho1d import SHOStateNEWLINE assert _test_args(SHOState(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__sho1d__SHOKet():NEWLINE from sympy.physics.quantum.sho1d import SHOKetNEWLINE assert _test_args(SHOKet(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__quantum__sho1d__SHOBra():NEWLINE from sympy.physics.quantum.sho1d import SHOBraNEWLINE assert _test_args(SHOBra(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__AnnihilateBoson():NEWLINE from sympy.physics.secondquant import AnnihilateBosonNEWLINE assert _test_args(AnnihilateBoson(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__AnnihilateFermion():NEWLINE from sympy.physics.secondquant import AnnihilateFermionNEWLINE assert _test_args(AnnihilateFermion(0))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__physics__secondquant__Annihilator():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__AntiSymmetricTensor():NEWLINE from sympy.physics.secondquant import AntiSymmetricTensorNEWLINE i, j = symbols('i j', below_fermi=True)NEWLINE a, b = symbols('a b', above_fermi=True)NEWLINE assert _test_args(AntiSymmetricTensor('v', (a, i), (b, j)))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__BosonState():NEWLINE from sympy.physics.secondquant import BosonStateNEWLINE assert _test_args(BosonState((0, 1)))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__physics__secondquant__BosonicOperator():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__Commutator():NEWLINE from sympy.physics.secondquant import CommutatorNEWLINE assert _test_args(Commutator(x, y))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__CreateBoson():NEWLINE from sympy.physics.secondquant import CreateBosonNEWLINE assert _test_args(CreateBoson(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__CreateFermion():NEWLINE from sympy.physics.secondquant import CreateFermionNEWLINE assert _test_args(CreateFermion(0))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__physics__secondquant__Creator():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__Dagger():NEWLINE from sympy.physics.secondquant import DaggerNEWLINE from sympy import INEWLINE assert _test_args(Dagger(2*I))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__FermionState():NEWLINE from sympy.physics.secondquant import FermionStateNEWLINE assert _test_args(FermionState((0, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__FermionicOperator():NEWLINE from sympy.physics.secondquant import FermionicOperatorNEWLINE assert _test_args(FermionicOperator(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__FockState():NEWLINE from sympy.physics.secondquant import FockStateNEWLINE assert _test_args(FockState((0, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__FockStateBosonBra():NEWLINE from sympy.physics.secondquant import FockStateBosonBraNEWLINE assert _test_args(FockStateBosonBra((0, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__FockStateBosonKet():NEWLINE from sympy.physics.secondquant import FockStateBosonKetNEWLINE assert _test_args(FockStateBosonKet((0, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__FockStateBra():NEWLINE from sympy.physics.secondquant import FockStateBraNEWLINE assert _test_args(FockStateBra((0, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__FockStateFermionBra():NEWLINE from sympy.physics.secondquant import FockStateFermionBraNEWLINE assert _test_args(FockStateFermionBra((0, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__FockStateFermionKet():NEWLINE from sympy.physics.secondquant import FockStateFermionKetNEWLINE assert _test_args(FockStateFermionKet((0, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__FockStateKet():NEWLINE from sympy.physics.secondquant import FockStateKetNEWLINE assert _test_args(FockStateKet((0, 1)))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__InnerProduct():NEWLINE from sympy.physics.secondquant import InnerProductNEWLINE from sympy.physics.secondquant import FockStateKet, FockStateBraNEWLINE assert _test_args(InnerProduct(FockStateBra((0, 1)), FockStateKet((0, 1))))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__NO():NEWLINE from sympy.physics.secondquant import NO, F, FdNEWLINE assert _test_args(NO(Fd(x)*F(y)))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__PermutationOperator():NEWLINE from sympy.physics.secondquant import PermutationOperatorNEWLINE assert _test_args(PermutationOperator(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__SqOperator():NEWLINE from sympy.physics.secondquant import SqOperatorNEWLINE assert _test_args(SqOperator(0))NEWLINENEWLINENEWLINEdef test_sympy__physics__secondquant__TensorSymbol():NEWLINE from sympy.physics.secondquant import TensorSymbolNEWLINE assert _test_args(TensorSymbol(x))NEWLINENEWLINENEWLINEdef test_sympy__physics__units__dimensions__Dimension():NEWLINE from sympy.physics.units.dimensions import DimensionNEWLINE assert _test_args(Dimension("length", "L"))NEWLINENEWLINENEWLINEdef test_sympy__physics__units__dimensions__DimensionSystem():NEWLINE from sympy.physics.units.dimensions import DimensionSystemNEWLINE from sympy.physics.units.dimensions import length, time, velocityNEWLINE assert _test_args(DimensionSystem((length, time), (velocity,)))NEWLINENEWLINENEWLINEdef test_sympy__physics__units__quantities__Quantity():NEWLINE from sympy.physics.units.quantities import QuantityNEWLINE from sympy.physics.units import lengthNEWLINE assert _test_args(Quantity("dam", length, 10))NEWLINENEWLINENEWLINEdef test_sympy__physics__units__prefixes__Prefix():NEWLINE from sympy.physics.units.prefixes import PrefixNEWLINE assert _test_args(Prefix('kilo', 'k', 3))NEWLINENEWLINENEWLINEdef test_sympy__core__numbers__AlgebraicNumber():NEWLINE from sympy.core.numbers import AlgebraicNumberNEWLINE assert _test_args(AlgebraicNumber(sqrt(2), [1, 2, 3]))NEWLINENEWLINENEWLINEdef test_sympy__polys__polytools__GroebnerBasis():NEWLINE from sympy.polys.polytools import GroebnerBasisNEWLINE assert _test_args(GroebnerBasis([x, y, z], x, y, z))NEWLINENEWLINENEWLINEdef test_sympy__polys__polytools__Poly():NEWLINE from sympy.polys.polytools import PolyNEWLINE assert _test_args(Poly(2, x, y))NEWLINENEWLINENEWLINEdef test_sympy__polys__polytools__PurePoly():NEWLINE from sympy.polys.polytools import PurePolyNEWLINE assert _test_args(PurePoly(2, x, y))NEWLINENEWLINENEWLINE@SKIP('abstract class')NEWLINEdef test_sympy__polys__rootoftools__RootOf():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__polys__rootoftools__ComplexRootOf():NEWLINE from sympy.polys.rootoftools import ComplexRootOfNEWLINE assert _test_args(ComplexRootOf(x**3 + x + 1, 0))NEWLINENEWLINENEWLINEdef test_sympy__polys__rootoftools__RootSum():NEWLINE from sympy.polys.rootoftools import RootSumNEWLINE assert _test_args(RootSum(x**3 + x + 1, sin))NEWLINENEWLINENEWLINEdef test_sympy__series__limits__Limit():NEWLINE from sympy.series.limits import LimitNEWLINE assert _test_args(Limit(x, x, 0, dir='-'))NEWLINENEWLINENEWLINEdef test_sympy__series__order__Order():NEWLINE from sympy.series.order import OrderNEWLINE assert _test_args(Order(1, x, y))NEWLINENEWLINENEWLINE@SKIP('Abstract Class')NEWLINEdef test_sympy__series__sequences__SeqBase():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__series__sequences__EmptySequence():NEWLINE from sympy.series.sequences import EmptySequenceNEWLINE assert _test_args(EmptySequence())NEWLINENEWLINENEWLINE@SKIP('Abstract Class')NEWLINEdef test_sympy__series__sequences__SeqExpr():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__series__sequences__SeqPer():NEWLINE from sympy.series.sequences import SeqPerNEWLINE assert _test_args(SeqPer((1, 2, 3), (0, 10)))NEWLINENEWLINENEWLINEdef test_sympy__series__sequences__SeqFormula():NEWLINE from sympy.series.sequences import SeqFormulaNEWLINE assert _test_args(SeqFormula(x**2, (0, 10)))NEWLINENEWLINENEWLINEdef test_sympy__series__sequences__SeqExprOp():NEWLINE from sympy.series.sequences import SeqExprOp, sequenceNEWLINE s1 = sequence((1, 2, 3))NEWLINE s2 = sequence(x**2)NEWLINE assert _test_args(SeqExprOp(s1, s2))NEWLINENEWLINENEWLINEdef test_sympy__series__sequences__SeqAdd():NEWLINE from sympy.series.sequences import SeqAdd, sequenceNEWLINE s1 = sequence((1, 2, 3))NEWLINE s2 = sequence(x**2)NEWLINE assert _test_args(SeqAdd(s1, s2))NEWLINENEWLINENEWLINEdef test_sympy__series__sequences__SeqMul():NEWLINE from sympy.series.sequences import SeqMul, sequenceNEWLINE s1 = sequence((1, 2, 3))NEWLINE s2 = sequence(x**2)NEWLINE assert _test_args(SeqMul(s1, s2))NEWLINENEWLINENEWLINE@SKIP('Abstract Class')NEWLINEdef test_sympy__series__series_class__SeriesBase():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__series__fourier__FourierSeries():NEWLINE from sympy.series.fourier import fourier_seriesNEWLINE assert _test_args(fourier_series(x, (x, -pi, pi)))NEWLINENEWLINENEWLINEdef test_sympy__series__formal__FormalPowerSeries():NEWLINE from sympy.series.formal import fpsNEWLINE assert _test_args(fps(log(1 + x), x))NEWLINENEWLINENEWLINEdef test_sympy__simplify__hyperexpand__Hyper_Function():NEWLINE from sympy.simplify.hyperexpand import Hyper_FunctionNEWLINE assert _test_args(Hyper_Function([2], [1]))NEWLINENEWLINENEWLINEdef test_sympy__simplify__hyperexpand__G_Function():NEWLINE from sympy.simplify.hyperexpand import G_FunctionNEWLINE assert _test_args(G_Function([2], [1], [], []))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__tensor__array__ndim_array__ImmutableNDimArray():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__tensor__array__dense_ndim_array__ImmutableDenseNDimArray():NEWLINE from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArrayNEWLINE densarr = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))NEWLINE assert _test_args(densarr)NEWLINENEWLINENEWLINEdef test_sympy__tensor__array__sparse_ndim_array__ImmutableSparseNDimArray():NEWLINE from sympy.tensor.array.sparse_ndim_array import ImmutableSparseNDimArrayNEWLINE sparr = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))NEWLINE assert _test_args(sparr)NEWLINENEWLINENEWLINEdef test_sympy__tensor__indexed__Idx():NEWLINE from sympy.tensor.indexed import IdxNEWLINE assert _test_args(Idx('test'))NEWLINE assert _test_args(Idx(1, (0, 10)))NEWLINENEWLINENEWLINEdef test_sympy__tensor__indexed__Indexed():NEWLINE from sympy.tensor.indexed import Indexed, IdxNEWLINE assert _test_args(Indexed('A', Idx('i'), Idx('j')))NEWLINENEWLINENEWLINEdef test_sympy__tensor__indexed__IndexedBase():NEWLINE from sympy.tensor.indexed import IndexedBaseNEWLINE assert _test_args(IndexedBase('A', shape=(x, y)))NEWLINE assert _test_args(IndexedBase('A', 1))NEWLINE assert _test_args(IndexedBase('A')[0, 1])NEWLINENEWLINENEWLINEdef test_sympy__tensor__tensor__TensorIndexType():NEWLINE from sympy.tensor.tensor import TensorIndexTypeNEWLINE assert _test_args(TensorIndexType('Lorentz', metric=False))NEWLINENEWLINENEWLINEdef test_sympy__tensor__tensor__TensorSymmetry():NEWLINE from sympy.tensor.tensor import TensorSymmetry, get_symmetric_group_sgsNEWLINE assert _test_args(TensorSymmetry(get_symmetric_group_sgs(2)))NEWLINENEWLINENEWLINEdef test_sympy__tensor__tensor__TensorType():NEWLINE from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorTypeNEWLINE Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')NEWLINE sym = TensorSymmetry(get_symmetric_group_sgs(1))NEWLINE assert _test_args(TensorType([Lorentz], sym))NEWLINENEWLINENEWLINEdef test_sympy__tensor__tensor__TensorHead():NEWLINE from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, TensorType, get_symmetric_group_sgs, TensorHeadNEWLINE Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')NEWLINE sym = TensorSymmetry(get_symmetric_group_sgs(1))NEWLINE S1 = TensorType([Lorentz], sym)NEWLINE assert _test_args(TensorHead('p', S1, 0))NEWLINENEWLINENEWLINEdef test_sympy__tensor__tensor__TensorIndex():NEWLINE from sympy.tensor.tensor import TensorIndexType, TensorIndexNEWLINE Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')NEWLINE assert _test_args(TensorIndex('i', Lorentz))NEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__tensor__tensor__TensExpr():NEWLINE passNEWLINENEWLINEdef test_sympy__tensor__tensor__TensAdd():NEWLINE from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, TensorType, get_symmetric_group_sgs, tensor_indices, TensAddNEWLINE Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')NEWLINE a, b = tensor_indices('a,b', Lorentz)NEWLINE sym = TensorSymmetry(get_symmetric_group_sgs(1))NEWLINE S1 = TensorType([Lorentz], sym)NEWLINE p, q = S1('p,q')NEWLINE t1 = p(a)NEWLINE t2 = q(a)NEWLINE assert _test_args(TensAdd(t1, t2))NEWLINENEWLINENEWLINEdef test_sympy__tensor__tensor__Tensor():NEWLINE from sympy.core import SNEWLINE from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, TensorType, get_symmetric_group_sgs, tensor_indices, TensMul, TIDSNEWLINE Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')NEWLINE a, b = tensor_indices('a,b', Lorentz)NEWLINE sym = TensorSymmetry(get_symmetric_group_sgs(1))NEWLINE S1 = TensorType([Lorentz], sym)NEWLINE p = S1('p')NEWLINE assert _test_args(p(a))NEWLINENEWLINENEWLINEdef test_sympy__tensor__tensor__TensMul():NEWLINE from sympy.core import SNEWLINE from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, TensorType, get_symmetric_group_sgs, tensor_indices, TensMul, TIDSNEWLINE Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')NEWLINE a, b = tensor_indices('a,b', Lorentz)NEWLINE sym = TensorSymmetry(get_symmetric_group_sgs(1))NEWLINE S1 = TensorType([Lorentz], sym)NEWLINE p = S1('p')NEWLINE q = S1('q')NEWLINE assert _test_args(3*p(a)*q(b))NEWLINENEWLINENEWLINEdef test_as_coeff_add():NEWLINE assert (7, (3*x, 4*x**2)) == (7 + 3*x + 4*x**2).as_coeff_add()NEWLINENEWLINENEWLINEdef test_sympy__geometry__curve__Curve():NEWLINE from sympy.geometry.curve import CurveNEWLINE assert _test_args(Curve((x, 1), (x, 0, 1)))NEWLINENEWLINENEWLINEdef test_sympy__geometry__point__Point():NEWLINE from sympy.geometry.point import PointNEWLINE assert _test_args(Point(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__geometry__point__Point2D():NEWLINE from sympy.geometry.point import Point2DNEWLINE assert _test_args(Point2D(0, 1))NEWLINENEWLINENEWLINEdef test_sympy__geometry__point__Point3D():NEWLINE from sympy.geometry.point import Point3DNEWLINE assert _test_args(Point3D(0, 1, 2))NEWLINENEWLINENEWLINEdef test_sympy__geometry__ellipse__Ellipse():NEWLINE from sympy.geometry.ellipse import EllipseNEWLINE assert _test_args(Ellipse((0, 1), 2, 3))NEWLINENEWLINENEWLINEdef test_sympy__geometry__ellipse__Circle():NEWLINE from sympy.geometry.ellipse import CircleNEWLINE assert _test_args(Circle((0, 1), 2))NEWLINENEWLINENEWLINEdef test_sympy__geometry__parabola__Parabola():NEWLINE from sympy.geometry.parabola import ParabolaNEWLINE from sympy.geometry.line import LineNEWLINE assert _test_args(Parabola((0, 0), Line((2, 3), (4, 3))))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__geometry__line__LinearEntity():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__geometry__line__Line():NEWLINE from sympy.geometry.line import LineNEWLINE assert _test_args(Line((0, 1), (2, 3)))NEWLINENEWLINENEWLINEdef test_sympy__geometry__line__Ray():NEWLINE from sympy.geometry.line import RayNEWLINE assert _test_args(Ray((0, 1), (2, 3)))NEWLINENEWLINENEWLINEdef test_sympy__geometry__line__Segment():NEWLINE from sympy.geometry.line import SegmentNEWLINE assert _test_args(Segment((0, 1), (2, 3)))NEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__geometry__line__LinearEntity2D():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__geometry__line__Line2D():NEWLINE from sympy.geometry.line import Line2DNEWLINE assert _test_args(Line2D((0, 1), (2, 3)))NEWLINENEWLINENEWLINEdef test_sympy__geometry__line__Ray2D():NEWLINE from sympy.geometry.line import Ray2DNEWLINE assert _test_args(Ray2D((0, 1), (2, 3)))NEWLINENEWLINENEWLINEdef test_sympy__geometry__line__Segment2D():NEWLINE from sympy.geometry.line import Segment2DNEWLINE assert _test_args(Segment2D((0, 1), (2, 3)))NEWLINENEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__geometry__line__LinearEntity3D():NEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__geometry__line__Line3D():NEWLINE from sympy.geometry.line import Line3DNEWLINE assert _test_args(Line3D((0, 1, 1), (2, 3, 4)))NEWLINENEWLINENEWLINEdef test_sympy__geometry__line__Segment3D():NEWLINE from sympy.geometry.line import Segment3DNEWLINE assert _test_args(Segment3D((0, 1, 1), (2, 3, 4)))NEWLINENEWLINENEWLINEdef test_sympy__geometry__line__Ray3D():NEWLINE from sympy.geometry.line import Ray3DNEWLINE assert _test_args(Ray3D((0, 1, 1), (2, 3, 4)))NEWLINENEWLINENEWLINEdef test_sympy__geometry__plane__Plane():NEWLINE from sympy.geometry.plane import PlaneNEWLINE assert _test_args(Plane((1, 1, 1), (-3, 4, -2), (1, 2, 3)))NEWLINENEWLINENEWLINEdef test_sympy__geometry__polygon__Polygon():NEWLINE from sympy.geometry.polygon import PolygonNEWLINE assert _test_args(Polygon((0, 1), (2, 3), (4, 5), (6, 7)))NEWLINENEWLINENEWLINEdef test_sympy__geometry__polygon__RegularPolygon():NEWLINE from sympy.geometry.polygon import RegularPolygonNEWLINE assert _test_args(RegularPolygon((0, 1), 2, 3, 4))NEWLINENEWLINENEWLINEdef test_sympy__geometry__polygon__Triangle():NEWLINE from sympy.geometry.polygon import TriangleNEWLINE assert _test_args(Triangle((0, 1), (2, 3), (4, 5)))NEWLINENEWLINENEWLINEdef test_sympy__geometry__entity__GeometryEntity():NEWLINE from sympy.geometry.entity import GeometryEntityNEWLINE from sympy.geometry.point import PointNEWLINE assert _test_args(GeometryEntity(Point(1, 0), 1, [1, 2]))NEWLINENEWLINE@SKIP("abstract class")NEWLINEdef test_sympy__geometry__entity__GeometrySet():NEWLINE passNEWLINENEWLINEdef test_sympy__diffgeom__diffgeom__Manifold():NEWLINE from sympy.diffgeom import ManifoldNEWLINE assert _test_args(Manifold('name', 3))NEWLINENEWLINENEWLINEdef test_sympy__diffgeom__diffgeom__Patch():NEWLINE from sympy.diffgeom import Manifold, PatchNEWLINE assert _test_args(Patch('name', Manifold('name', 3)))NEWLINENEWLINENEWLINEdef test_sympy__diffgeom__diffgeom__CoordSystem():NEWLINE from sympy.diffgeom import Manifold, Patch, CoordSystemNEWLINE assert _test_args(CoordSystem('name', Patch('name', Manifold('name', 3))))NEWLINENEWLINENEWLINE@XFAILNEWLINEdef test_sympy__diffgeom__diffgeom__Point():NEWLINE from sympy.diffgeom import Manifold, Patch, CoordSystem, PointNEWLINE assert _test_args(Point(NEWLINE CoordSystem('name', Patch('name', Manifold('name', 3))), [x, y]))NEWLINENEWLINENEWLINEdef test_sympy__diffgeom__diffgeom__BaseScalarField():NEWLINE from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarFieldNEWLINE cs = CoordSystem('name', Patch('name', Manifold('name', 3)))NEWLINE assert _test_args(BaseScalarField(cs, 0))NEWLINENEWLINENEWLINEdef test_sympy__diffgeom__diffgeom__BaseVectorField():NEWLINE from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorFieldNEWLINE cs = CoordSystem('name', Patch('name', Manifold('name', 3)))NEWLINE assert _test_args(BaseVectorField(cs, 0))NEWLINENEWLINENEWLINEdef test_sympy__diffgeom__diffgeom__Differential():NEWLINE from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, DifferentialNEWLINE cs = CoordSystem('name', Patch('name', Manifold('name', 3)))NEWLINE assert _test_args(Differential(BaseScalarField(cs, 0)))NEWLINENEWLINENEWLINEdef test_sympy__diffgeom__diffgeom__Commutator():NEWLINE from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, CommutatorNEWLINE cs = CoordSystem('name', Patch('name', Manifold('name', 3)))NEWLINE cs1 = CoordSystem('name1', Patch('name', Manifold('name', 3)))NEWLINE v = BaseVectorField(cs, 0)NEWLINE v1 = BaseVectorField(cs1, 0)NEWLINE assert _test_args(Commutator(v, v1))NEWLINENEWLINENEWLINEdef test_sympy__diffgeom__diffgeom__TensorProduct():NEWLINE from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, TensorProductNEWLINE cs = CoordSystem('name', Patch('name', Manifold('name', 3)))NEWLINE d = Differential(BaseScalarField(cs, 0))NEWLINE assert _test_args(TensorProduct(d, d))NEWLINENEWLINENEWLINEdef test_sympy__diffgeom__diffgeom__WedgeProduct():NEWLINE from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, WedgeProductNEWLINE cs = CoordSystem('name', Patch('name', Manifold('name', 3)))NEWLINE d = Differential(BaseScalarField(cs, 0))NEWLINE d1 = Differential(BaseScalarField(cs, 1))NEWLINE assert _test_args(WedgeProduct(d, d1))NEWLINENEWLINENEWLINEdef test_sympy__diffgeom__diffgeom__LieDerivative():NEWLINE from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, BaseVectorField, LieDerivativeNEWLINE cs = CoordSystem('name', Patch('name', Manifold('name', 3)))NEWLINE d = Differential(BaseScalarField(cs, 0))NEWLINE v = BaseVectorField(cs, 0)NEWLINE assert _test_args(LieDerivative(v, d))NEWLINENEWLINENEWLINE@XFAILNEWLINEdef test_sympy__diffgeom__diffgeom__BaseCovarDerivativeOp():NEWLINE from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseCovarDerivativeOpNEWLINE cs = CoordSystem('name', Patch('name', Manifold('name', 3)))NEWLINE assert _test_args(BaseCovarDerivativeOp(cs, 0, [[[0, ]*3, ]*3, ]*3))NEWLINENEWLINENEWLINEdef test_sympy__diffgeom__diffgeom__CovarDerivativeOp():NEWLINE from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, CovarDerivativeOpNEWLINE cs = CoordSystem('name', Patch('name', Manifold('name', 3)))NEWLINE v = BaseVectorField(cs, 0)NEWLINE _test_args(CovarDerivativeOp(v, [[[0, ]*3, ]*3, ]*3))NEWLINENEWLINENEWLINEdef test_sympy__categories__baseclasses__Class():NEWLINE from sympy.categories.baseclasses import ClassNEWLINE assert _test_args(Class())NEWLINENEWLINENEWLINEdef test_sympy__categories__baseclasses__Object():NEWLINE from sympy.categories import ObjectNEWLINE assert _test_args(Object("A"))NEWLINENEWLINENEWLINE@XFAILNEWLINEdef test_sympy__categories__baseclasses__Morphism():NEWLINE from sympy.categories import Object, MorphismNEWLINE assert _test_args(Morphism(Object("A"), Object("B")))NEWLINENEWLINENEWLINEdef test_sympy__categories__baseclasses__IdentityMorphism():NEWLINE from sympy.categories import Object, IdentityMorphismNEWLINE assert _test_args(IdentityMorphism(Object("A")))NEWLINENEWLINENEWLINEdef test_sympy__categories__baseclasses__NamedMorphism():NEWLINE from sympy.categories import Object, NamedMorphismNEWLINE assert _test_args(NamedMorphism(Object("A"), Object("B"), "f"))NEWLINENEWLINENEWLINEdef test_sympy__categories__baseclasses__CompositeMorphism():NEWLINE from sympy.categories import Object, NamedMorphism, CompositeMorphismNEWLINE A = Object("A")NEWLINE B = Object("B")NEWLINE C = Object("C")NEWLINE f = NamedMorphism(A, B, "f")NEWLINE g = NamedMorphism(B, C, "g")NEWLINE assert _test_args(CompositeMorphism(f, g))NEWLINENEWLINENEWLINEdef test_sympy__categories__baseclasses__Diagram():NEWLINE from sympy.categories import Object, NamedMorphism, DiagramNEWLINE A = Object("A")NEWLINE B = Object("B")NEWLINE C = Object("C")NEWLINE f = NamedMorphism(A, B, "f")NEWLINE d = Diagram([f])NEWLINE assert _test_args(d)NEWLINENEWLINENEWLINEdef test_sympy__categories__baseclasses__Category():NEWLINE from sympy.categories import Object, NamedMorphism, Diagram, CategoryNEWLINE A = Object("A")NEWLINE B = Object("B")NEWLINE C = Object("C")NEWLINE f = NamedMorphism(A, B, "f")NEWLINE g = NamedMorphism(B, C, "g")NEWLINE d1 = Diagram([f, g])NEWLINE d2 = Diagram([f])NEWLINE K = Category("K", commutative_diagrams=[d1, d2])NEWLINE assert _test_args(K)NEWLINENEWLINENEWLINEdef test_sympy__ntheory__factor___totient():NEWLINE from sympy.ntheory.factor_ import totientNEWLINE k = symbols('k', integer=True)NEWLINE t = totient(k)NEWLINE assert _test_args(t)NEWLINENEWLINENEWLINEdef test_sympy__ntheory__factor___reduced_totient():NEWLINE from sympy.ntheory.factor_ import reduced_totientNEWLINE k = symbols('k', integer=True)NEWLINE t = reduced_totient(k)NEWLINE assert _test_args(t)NEWLINENEWLINENEWLINEdef test_sympy__ntheory__factor___divisor_sigma():NEWLINE from sympy.ntheory.factor_ import divisor_sigmaNEWLINE k = symbols('k', integer=True)NEWLINE n = symbols('n', integer=True)NEWLINE t = divisor_sigma(n, k)NEWLINE assert _test_args(t)NEWLINENEWLINENEWLINEdef test_sympy__ntheory__factor___udivisor_sigma():NEWLINE from sympy.ntheory.factor_ import udivisor_sigmaNEWLINE k = symbols('k', integer=True)NEWLINE n = symbols('n', integer=True)NEWLINE t = udivisor_sigma(n, k)NEWLINE assert _test_args(t)NEWLINENEWLINENEWLINEdef test_sympy__ntheory__factor___primenu():NEWLINE from sympy.ntheory.factor_ import primenuNEWLINE n = symbols('n', integer=True)NEWLINE t = primenu(n)NEWLINE assert _test_args(t)NEWLINENEWLINENEWLINEdef test_sympy__ntheory__factor___primeomega():NEWLINE from sympy.ntheory.factor_ import primeomegaNEWLINE n = symbols('n', integer=True)NEWLINE t = primeomega(n)NEWLINE assert _test_args(t)NEWLINENEWLINENEWLINEdef test_sympy__ntheory__residue_ntheory__mobius():NEWLINE from sympy.ntheory import mobiusNEWLINE assert _test_args(mobius(2))NEWLINENEWLINENEWLINEdef test_sympy__physics__optics__waves__TWave():NEWLINE from sympy.physics.optics import TWaveNEWLINE A, f, phi = symbols('A, f, phi')NEWLINE assert _test_args(TWave(A, f, phi))NEWLINENEWLINENEWLINEdef test_sympy__physics__optics__gaussopt__BeamParameter():NEWLINE from sympy.physics.optics import BeamParameterNEWLINE assert _test_args(BeamParameter(530e-9, 1, w=1e-3))NEWLINENEWLINENEWLINEdef test_sympy__physics__optics__medium__Medium():NEWLINE from sympy.physics.optics import MediumNEWLINE assert _test_args(Medium('m'))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ast__Assignment():NEWLINE from sympy.codegen.ast import AssignmentNEWLINE assert _test_args(Assignment(x, y))NEWLINENEWLINENEWLINEdef test_sympy__codegen__cfunctions__expm1():NEWLINE from sympy.codegen.cfunctions import expm1NEWLINE assert _test_args(expm1(x))NEWLINENEWLINENEWLINEdef test_sympy__codegen__cfunctions__log1p():NEWLINE from sympy.codegen.cfunctions import log1pNEWLINE assert _test_args(log1p(x))NEWLINENEWLINENEWLINEdef test_sympy__codegen__cfunctions__exp2():NEWLINE from sympy.codegen.cfunctions import exp2NEWLINE assert _test_args(exp2(x))NEWLINENEWLINENEWLINEdef test_sympy__codegen__cfunctions__log2():NEWLINE from sympy.codegen.cfunctions import log2NEWLINE assert _test_args(log2(x))NEWLINENEWLINENEWLINEdef test_sympy__codegen__cfunctions__fma():NEWLINE from sympy.codegen.cfunctions import fmaNEWLINE assert _test_args(fma(x, y, z))NEWLINENEWLINENEWLINEdef test_sympy__codegen__cfunctions__log10():NEWLINE from sympy.codegen.cfunctions import log10NEWLINE assert _test_args(log10(x))NEWLINENEWLINENEWLINEdef test_sympy__codegen__cfunctions__Sqrt():NEWLINE from sympy.codegen.cfunctions import SqrtNEWLINE assert _test_args(Sqrt(x))NEWLINENEWLINEdef test_sympy__codegen__cfunctions__Cbrt():NEWLINE from sympy.codegen.cfunctions import CbrtNEWLINE assert _test_args(Cbrt(x))NEWLINENEWLINEdef test_sympy__codegen__cfunctions__hypot():NEWLINE from sympy.codegen.cfunctions import hypotNEWLINE assert _test_args(hypot(x, y))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ffunctions__FFunction():NEWLINE from sympy.codegen.ffunctions import FFunctionNEWLINE assert _test_args(FFunction('f'))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ffunctions__F95Function():NEWLINE from sympy.codegen.ffunctions import F95FunctionNEWLINE assert _test_args(F95Function('f'))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ffunctions__isign():NEWLINE from sympy.codegen.ffunctions import isignNEWLINE assert _test_args(isign(1, x))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ffunctions__dsign():NEWLINE from sympy.codegen.ffunctions import dsignNEWLINE assert _test_args(dsign(1, x))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ffunctions__cmplx():NEWLINE from sympy.codegen.ffunctions import cmplxNEWLINE assert _test_args(cmplx(x, y))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ffunctions__kind():NEWLINE from sympy.codegen.ffunctions import kindNEWLINE assert _test_args(kind(x))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ffunctions__merge():NEWLINE from sympy.codegen.ffunctions import mergeNEWLINE assert _test_args(merge(1, 2, Eq(x, 0)))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ffunctions___literal():NEWLINE from sympy.codegen.ffunctions import _literalNEWLINE assert _test_args(_literal(1))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ffunctions__literal_sp():NEWLINE from sympy.codegen.ffunctions import literal_spNEWLINE assert _test_args(literal_sp(1))NEWLINENEWLINENEWLINEdef test_sympy__codegen__ffunctions__literal_dp():NEWLINE from sympy.codegen.ffunctions import literal_dpNEWLINE assert _test_args(literal_dp(1))NEWLINENEWLINENEWLINEdef test_sympy__vector__coordsysrect__CoordSys3D():NEWLINE from sympy.vector.coordsysrect import CoordSys3DNEWLINE assert _test_args(CoordSys3D('C'))NEWLINENEWLINENEWLINEdef test_sympy__vector__point__Point():NEWLINE from sympy.vector.point import PointNEWLINE assert _test_args(Point('P'))NEWLINENEWLINENEWLINEdef test_sympy__vector__basisdependent__BasisDependent():NEWLINE from sympy.vector.basisdependent import BasisDependentNEWLINE #These classes have been created to maintain an OOP hierarchyNEWLINE #for Vectors and Dyadics. Are NOT meant to be initializedNEWLINENEWLINENEWLINEdef test_sympy__vector__basisdependent__BasisDependentMul():NEWLINE from sympy.vector.basisdependent import BasisDependentMulNEWLINE #These classes have been created to maintain an OOP hierarchyNEWLINE #for Vectors and Dyadics. Are NOT meant to be initializedNEWLINENEWLINENEWLINEdef test_sympy__vector__basisdependent__BasisDependentAdd():NEWLINE from sympy.vector.basisdependent import BasisDependentAddNEWLINE #These classes have been created to maintain an OOP hierarchyNEWLINE #for Vectors and Dyadics. Are NOT meant to be initializedNEWLINENEWLINENEWLINEdef test_sympy__vector__basisdependent__BasisDependentZero():NEWLINE from sympy.vector.basisdependent import BasisDependentZeroNEWLINE #These classes have been created to maintain an OOP hierarchyNEWLINE #for Vectors and Dyadics. Are NOT meant to be initializedNEWLINENEWLINENEWLINEdef test_sympy__vector__vector__BaseVector():NEWLINE from sympy.vector.vector import BaseVectorNEWLINE from sympy.vector.coordsysrect import CoordSys3DNEWLINE C = CoordSys3D('C')NEWLINE assert _test_args(BaseVector(0, C, ' ', ' '))NEWLINENEWLINENEWLINEdef test_sympy__vector__vector__VectorAdd():NEWLINE from sympy.vector.vector import VectorAdd, VectorMulNEWLINE from sympy.vector.coordsysrect import CoordSys3DNEWLINE C = CoordSys3D('C')NEWLINE from sympy.abc import a, b, c, x, y, zNEWLINE v1 = a*C.i + b*C.j + c*C.kNEWLINE v2 = x*C.i + y*C.j + z*C.kNEWLINE assert _test_args(VectorAdd(v1, v2))NEWLINE assert _test_args(VectorMul(x, v1))NEWLINENEWLINENEWLINEdef test_sympy__vector__vector__VectorMul():NEWLINE from sympy.vector.vector import VectorMulNEWLINE from sympy.vector.coordsysrect import CoordSys3DNEWLINE C = CoordSys3D('C')NEWLINE from sympy.abc import aNEWLINE assert _test_args(VectorMul(a, C.i))NEWLINENEWLINENEWLINEdef test_sympy__vector__vector__VectorZero():NEWLINE from sympy.vector.vector import VectorZeroNEWLINE assert _test_args(VectorZero())NEWLINENEWLINENEWLINEdef test_sympy__vector__vector__Vector():NEWLINE from sympy.vector.vector import VectorNEWLINE #Vector is never to be initialized using argsNEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__vector__vector__Cross():NEWLINE from sympy.vector.vector import CrossNEWLINE from sympy.vector.coordsysrect import CoordSys3DNEWLINE C = CoordSys3D('C')NEWLINE _test_args(Cross(C.i, C.j))NEWLINENEWLINENEWLINEdef test_sympy__vector__vector__Dot():NEWLINE from sympy.vector.vector import DotNEWLINE from sympy.vector.coordsysrect import CoordSys3DNEWLINE C = CoordSys3D('C')NEWLINE _test_args(Dot(C.i, C.j))NEWLINENEWLINENEWLINEdef test_sympy__vector__dyadic__Dyadic():NEWLINE from sympy.vector.dyadic import DyadicNEWLINE #Dyadic is never to be initialized using argsNEWLINE passNEWLINENEWLINENEWLINEdef test_sympy__vector__dyadic__BaseDyadic():NEWLINE from sympy.vector.dyadic import BaseDyadicNEWLINE from sympy.vector.coordsysrect import CoordSys3DNEWLINE C = CoordSys3D('C')NEWLINE assert _test_args(BaseDyadic(C.i, C.j))NEWLINENEWLINENEWLINEdef test_sympy__vector__dyadic__DyadicMul():NEWLINE from sympy.vector.dyadic import BaseDyadic, DyadicMulNEWLINE from sympy.vector.coordsysrect import CoordSys3DNEWLINE C = CoordSys3D('C')NEWLINE assert _test_args(DyadicMul(3, BaseDyadic(C.i, C.j)))NEWLINENEWLINENEWLINEdef test_sympy__vector__dyadic__DyadicAdd():NEWLINE from sympy.vector.dyadic import BaseDyadic, DyadicAddNEWLINE from sympy.vector.coordsysrect import CoordSys3DNEWLINE C = CoordSys3D('C')NEWLINE assert _test_args(2 * DyadicAdd(BaseDyadic(C.i, C.i),NEWLINE BaseDyadic(C.i, C.j)))NEWLINENEWLINENEWLINEdef test_sympy__vector__dyadic__DyadicZero():NEWLINE from sympy.vector.dyadic import DyadicZeroNEWLINE assert _test_args(DyadicZero())NEWLINENEWLINENEWLINEdef test_sympy__vector__deloperator__Del():NEWLINE from sympy.vector.deloperator import DelNEWLINE assert _test_args(Del())NEWLINENEWLINENEWLINEdef test_sympy__vector__operators__Curl():NEWLINE from sympy.vector.operators import CurlNEWLINE from sympy.vector.coordsysrect import CoordSys3DNEWLINE C = CoordSys3D('C')NEWLINE assert _test_args(Curl(C.i))NEWLINENEWLINENEWLINEdef test_sympy__vector__operators__Divergence():NEWLINE from sympy.vector.operators import DivergenceNEWLINE from sympy.vector.coordsysrect import CoordSys3DNEWLINE C = CoordSys3D('C')NEWLINE assert _test_args(Divergence(C.i))NEWLINENEWLINENEWLINEdef test_sympy__vector__operators__Gradient():NEWLINE from sympy.vector.operators import GradientNEWLINE from sympy.vector.coordsysrect import CoordSys3DNEWLINE C = CoordSys3D('C')NEWLINE assert _test_args(Gradient(C.x))NEWLINENEWLINENEWLINEdef test_sympy__vector__orienters__Orienter():NEWLINE from sympy.vector.orienters import OrienterNEWLINE #Not to be initializedNEWLINENEWLINENEWLINEdef test_sympy__vector__orienters__ThreeAngleOrienter():NEWLINE from sympy.vector.orienters import ThreeAngleOrienterNEWLINE #Not to be initializedNEWLINENEWLINENEWLINEdef test_sympy__vector__orienters__AxisOrienter():NEWLINE from sympy.vector.orienters import AxisOrienterNEWLINE from sympy.vector.coordsysrect import CoordSys3DNEWLINE C = CoordSys3D('C')NEWLINE assert _test_args(AxisOrienter(x, C.i))NEWLINENEWLINENEWLINEdef test_sympy__vector__orienters__BodyOrienter():NEWLINE from sympy.vector.orienters import BodyOrienterNEWLINE assert _test_args(BodyOrienter(x, y, z, '123'))NEWLINENEWLINENEWLINEdef test_sympy__vector__orienters__SpaceOrienter():NEWLINE from sympy.vector.orienters import SpaceOrienterNEWLINE assert _test_args(SpaceOrienter(x, y, z, '123'))NEWLINENEWLINENEWLINEdef test_sympy__vector__orienters__QuaternionOrienter():NEWLINE from sympy.vector.orienters import QuaternionOrienterNEWLINE a, b, c, d = symbols('a b c d')NEWLINE assert _test_args(QuaternionOrienter(a, b, c, d))NEWLINENEWLINENEWLINEdef test_sympy__vector__scalar__BaseScalar():NEWLINE from sympy.vector.scalar import BaseScalarNEWLINE from sympy.vector.coordsysrect import CoordSys3DNEWLINE C = CoordSys3D('C')NEWLINE assert _test_args(BaseScalar(0, C, ' ', ' '))NEWLINENEWLINENEWLINEdef test_sympy__physics__wigner__Wigner3j():NEWLINE from sympy.physics.wigner import Wigner3jNEWLINE assert _test_args(Wigner3j(0, 0, 0, 0, 0, 0))NEWLINENEWLINEdef test_sympy__integrals__rubi__symbol__matchpyWC():NEWLINE from sympy.integrals.rubi.symbol import matchpyWCNEWLINE assert _test_args(matchpyWC(1, True, 'a'))NEWLINE import setuptoolsNEWLINENEWLINEwith open("README.md", "r", encoding="utf-8") as f:NEWLINE long_description = f.read()NEWLINENEWLINEsetuptools.setup(NEWLINE name="sunnyvale",NEWLINE version="0.0.1",NEWLINE author="Gunhoon Lee",NEWLINE author_email="gunhoon@gmail.com",NEWLINE description="A small example package",NEWLINE long_description=long_description,NEWLINE long_description_content_type="text/markdown",NEWLINE url="https://github.com/gunhoon/sunnyvale",NEWLINE packages=setuptools.find_packages(),NEWLINE classifiers=[NEWLINE "Programming Language :: Python :: 3",NEWLINE "License :: OSI Approved :: MIT License",NEWLINE "Operating System :: OS Independent",NEWLINE ],NEWLINE python_requires='>=3.6',NEWLINE)NEWLINE # -*- coding: utf-8 -*-NEWLINE"""NEWLINETests for the Py2-like class:`basestring` type.NEWLINE"""NEWLINENEWLINEfrom __future__ import absolute_import, unicode_literals, print_functionNEWLINEimport osNEWLINENEWLINEfrom past import utilsNEWLINEfrom future.tests.base import unittestNEWLINEfrom past.builtins import basestring, str as oldstrNEWLINENEWLINENEWLINEclass TestBaseString(unittest.TestCase):NEWLINENEWLINE def test_isinstance(self):NEWLINE s = b'abc'NEWLINE self.assertTrue(isinstance(s, basestring))NEWLINE s2 = oldstr(b'abc')NEWLINE self.assertTrue(isinstance(s2, basestring))NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE unittest.main()NEWLINE import importlibNEWLINEimport osNEWLINEimport timeNEWLINEimport randomNEWLINENEWLINEimport torchNEWLINEimport torch.nn.functional as FNEWLINEimport numpy as npNEWLINEimport ComputePostBNNEWLINEfrom utils.setlogger import get_loggerNEWLINENEWLINEfrom utils.model_profiling import model_profilingNEWLINEfrom utils.config import FLAGSNEWLINEfrom utils.datasets import get_datasetNEWLINENEWLINE# set log filesNEWLINEsaved_path = os.path.join("logs", '{}-{}'.format(FLAGS.dataset, FLAGS.model[7:]))NEWLINEif not os.path.exists(saved_path):NEWLINE os.makedirs(saved_path)NEWLINElogger = get_logger(os.path.join(saved_path, '{}_div1optimizer.log'.format('test' if FLAGS.test_only else 'train')))NEWLINENEWLINEdef set_random_seed():NEWLINE """set random seed"""NEWLINE if hasattr(FLAGS, 'random_seed'):NEWLINE seed = FLAGS.random_seedNEWLINE else:NEWLINE seed = 0NEWLINE random.seed(seed)NEWLINE np.random.seed(seed)NEWLINE torch.manual_seed(seed)NEWLINE torch.cuda.manual_seed(seed)NEWLINE torch.cuda.manual_seed_all(seed)NEWLINENEWLINEdef get_model():NEWLINE """get model"""NEWLINE model_lib = importlib.import_module(FLAGS.model)NEWLINE model = model_lib.Model(FLAGS.num_classes, input_size=FLAGS.image_size)NEWLINE return modelNEWLINENEWLINEdef get_optimizer(model):NEWLINE """get optimizer"""NEWLINE # all depthwise convolution (N, 1, x, x) has no weight decayNEWLINE # weight decay only on normal conv and fcNEWLINE if FLAGS.dataset == 'imagenet1k':NEWLINE model_params = []NEWLINE for params in model.parameters():NEWLINE ps = list(params.size())NEWLINE if len(ps) == 4 and ps[1] != 1: # normal convNEWLINE weight_decay = FLAGS.weight_decayNEWLINE elif len(ps) == 2: # fcNEWLINE weight_decay = FLAGS.weight_decayNEWLINE else:NEWLINE weight_decay = 0NEWLINE item = {'params': params, 'weight_decay': weight_decay,NEWLINE 'lr': FLAGS.lr, 'momentum': FLAGS.momentum,NEWLINE 'nesterov': FLAGS.nesterov}NEWLINE model_params.append(item)NEWLINE optimizer = torch.optim.SGD(model_params)NEWLINE else:NEWLINE optimizer = torch.optim.SGD(model.parameters(), FLAGS.lr,NEWLINE momentum=FLAGS.momentum, nesterov=FLAGS.nesterov,NEWLINE weight_decay=FLAGS.weight_decay)NEWLINE return optimizerNEWLINENEWLINEdef profiling(model, use_cuda):NEWLINE """profiling on either gpu or cpu"""NEWLINE print('Start model profiling, use_cuda:{}.'.format(use_cuda))NEWLINE for width_mult in sorted(FLAGS.width_mult_list, reverse=True):NEWLINE model.apply(NEWLINE lambda m: setattr(m, 'width_mult', width_mult))NEWLINE print('Model profiling with width mult {}x:'.format(width_mult))NEWLINE verbose = width_mult == max(FLAGS.width_mult_list)NEWLINE model_profiling(NEWLINE model, FLAGS.image_size, FLAGS.image_size,NEWLINE verbose=getattr(FLAGS, 'model_profiling_verbose', verbose))NEWLINENEWLINEdef train(epoch, loader, model, criterion, optimizer, lr_scheduler):NEWLINE t_start = time.time()NEWLINE model.train()NEWLINE for batch_idx, (input_list, target) in enumerate(loader):NEWLINE target = target.cuda(non_blocking=True)NEWLINE optimizer.zero_grad()NEWLINE # do max widthNEWLINE max_width = FLAGS.width_mult_range[1]NEWLINE model.apply(lambda m: setattr(m, 'width_mult', max_width))NEWLINE max_output = model(input_list[0])NEWLINE loss = criterion(max_output, target)NEWLINE loss.backward()NEWLINE max_output_detach = max_output.detach()NEWLINE # do other widths and resolutionNEWLINE min_width = FLAGS.width_mult_range[0]NEWLINE width_mult_list = [min_width]NEWLINE sampled_width = list(np.random.uniform(FLAGS.width_mult_range[0], FLAGS.width_mult_range[1], 2))NEWLINE width_mult_list.extend(sampled_width)NEWLINE for width_mult in sorted(width_mult_list, reverse=True):NEWLINE model.apply(NEWLINE lambda m: setattr(m, 'width_mult', width_mult))NEWLINE output = model(input_list[random.randint(0, 3)])NEWLINE loss = torch.nn.KLDivLoss(reduction='batchmean')(F.log_softmax(output, dim=1), F.softmax(max_output_detach, dim=1))NEWLINE loss.backward()NEWLINE optimizer.step()NEWLINE lr_scheduler.step()NEWLINE # print training logNEWLINE if batch_idx % FLAGS.print_freq == 0 or batch_idx == len(loader)-1:NEWLINE with torch.no_grad():NEWLINE for width_mult in sorted(FLAGS.width_mult_list, reverse=True):NEWLINE model.apply(lambda m: setattr(m, 'width_mult', width_mult))NEWLINE output = model(input_list[0])NEWLINE loss = criterion(output, target).cpu().numpy()NEWLINE indices = torch.max(output, dim=1)[1]NEWLINE acc = (indices == target).sum().cpu().numpy() / indices.size()[0]NEWLINE logger.info('TRAIN {:.1f}s LR:{:.4f} {}x Epoch:{}/{} Iter:{}/{} Loss:{:.4f} Acc:{:.3f}'.format(NEWLINE time.time() - t_start, optimizer.param_groups[0]['lr'], str(width_mult), epoch,NEWLINE FLAGS.num_epochs, batch_idx, len(loader), loss, acc))NEWLINENEWLINENEWLINEdef validate(epoch, loader, model, criterion, postloader):NEWLINE t_start = time.time()NEWLINE model.eval()NEWLINE resolution = FLAGS.image_sizeNEWLINE with torch.no_grad():NEWLINE for width_mult in sorted(FLAGS.width_mult_list, reverse=True):NEWLINE model.apply(lambda m: setattr(m, 'width_mult', width_mult))NEWLINE model = ComputePostBN.ComputeBN(model, postloader, resolution)NEWLINE loss, acc, cnt = 0, 0, 0NEWLINE for batch_idx, (input, target) in enumerate(loader):NEWLINE input, target = input.cuda(non_blocking=True), target.cuda(non_blocking=True)NEWLINE output = model(input)NEWLINE loss += criterion(output, target).cpu().numpy() * target.size()[0]NEWLINE indices = torch.max(output, dim=1)[1]NEWLINE acc += (indices == target).sum().cpu().numpy()NEWLINE cnt += target.size()[0]NEWLINE logger.info('VAL {:.1f}s {}x Epoch:{}/{} Loss:{:.4f} Acc:{:.3f}'.format(NEWLINE time.time() - t_start, str(width_mult), epoch,NEWLINE FLAGS.num_epochs, loss/cnt, acc/cnt))NEWLINENEWLINEdef test(epoch, loader, model, criterion, postloader):NEWLINE t_start = time.time()NEWLINE model.eval()NEWLINE with torch.no_grad():NEWLINE for resolution in FLAGS.resolution_list:NEWLINE for width_mult in sorted(FLAGS.width_mult_list, reverse=True):NEWLINE model.apply(lambda m: setattr(m, 'width_mult', width_mult))NEWLINE model = ComputePostBN.ComputeBN(model, postloader, resolution)NEWLINE loss, acc, cnt = 0, 0, 0NEWLINE for batch_idx, (input, target) in enumerate(loader):NEWLINE input, target =input.cuda(non_blocking=True), target.cuda(non_blocking=True)NEWLINE output = model(F.interpolate(input, (resolution, resolution), mode='bilinear', align_corners=True))NEWLINE loss += criterion(output, target).cpu().numpy() * target.size()[0]NEWLINE indices = torch.max(output, dim=1)[1]NEWLINE acc += (indices==target).sum().cpu().numpy()NEWLINE cnt += target.size()[0]NEWLINE logger.info('VAL {:.1f}s {}x-{} Epoch:{}/{} Loss:{:.4f} Acc:{:.3f}'.format(NEWLINE time.time() - t_start, str(width_mult), str(resolution), epoch,NEWLINE FLAGS.num_epochs, loss/cnt, acc/cnt))NEWLINENEWLINEdef train_val_test():NEWLINE """train and val"""NEWLINE # seedNEWLINE set_random_seed()NEWLINENEWLINE # modelNEWLINE model = get_model()NEWLINE model_wrapper = torch.nn.DataParallel(model).cuda()NEWLINE criterion = torch.nn.CrossEntropyLoss().cuda()NEWLINE train_loader, val_loader = get_dataset()NEWLINENEWLINE # check pretrainedNEWLINE if FLAGS.pretrained:NEWLINE checkpoint = torch.load(FLAGS.pretrained)NEWLINE # update keys from external modelsNEWLINE if type(checkpoint) == dict and 'model' in checkpoint:NEWLINE checkpoint = checkpoint['model']NEWLINE new_keys = list(model_wrapper.state_dict().keys())NEWLINE old_keys = list(checkpoint.keys())NEWLINE new_keys = [key for key in new_keys if 'running' not in key]NEWLINE new_keys = [key for key in new_keys if 'tracked' not in key]NEWLINE old_keys = [key for key in old_keys if 'running' not in key]NEWLINE old_keys = [key for key in old_keys if 'tracked' not in key]NEWLINE if not FLAGS.test_only:NEWLINE old_keys = old_keys[:-2]NEWLINE new_keys = new_keys[:-2]NEWLINENEWLINE new_checkpoint = {}NEWLINE for key_new, key_old in zip(new_keys, old_keys):NEWLINE new_checkpoint[key_new] = checkpoint[key_old]NEWLINE model_wrapper.load_state_dict(new_checkpoint, strict=False)NEWLINE print('Loaded model {}.'.format(FLAGS.pretrained))NEWLINE optimizer = get_optimizer(model_wrapper)NEWLINE # check resume trainingNEWLINE if FLAGS.resume:NEWLINE checkpoint = torch.load(FLAGS.resume)NEWLINE model_wrapper.load_state_dict(checkpoint['model'])NEWLINE optimizer.load_state_dict(checkpoint['optimizer'])NEWLINE last_epoch = checkpoint['last_epoch']NEWLINE lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, len(train_loader)*FLAGS.num_epochs)NEWLINE lr_scheduler.last_epoch = last_epochNEWLINE print('Loaded checkpoint {} at epoch {}.'.format(NEWLINE FLAGS.resume, last_epoch))NEWLINE else:NEWLINE lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, len(train_loader)*FLAGS.num_epochs)NEWLINE last_epoch = lr_scheduler.last_epochNEWLINE # print model and do profilingNEWLINE print(model_wrapper)NEWLINE if FLAGS.profiling:NEWLINE if 'gpu' in FLAGS.profiling:NEWLINE profiling(model, use_cuda=True)NEWLINE if 'cpu' in FLAGS.profiling:NEWLINE profiling(model, use_cuda=False)NEWLINENEWLINE if FLAGS.test_only:NEWLINE logger.info('Start testing.')NEWLINE test(last_epoch, val_loader, model_wrapper, criterion, train_loader)NEWLINE returnNEWLINENEWLINE logger.info('Start training.')NEWLINE for epoch in range(last_epoch + 1, FLAGS.num_epochs):NEWLINE # trainNEWLINE train(epoch, train_loader, model_wrapper, criterion, optimizer, lr_scheduler)NEWLINENEWLINE # valNEWLINE validate(epoch, val_loader, model_wrapper, criterion, train_loader)NEWLINENEWLINE # lr_scheduler.step()NEWLINE torch.save(NEWLINE {NEWLINE 'model': model_wrapper.state_dict(),NEWLINE 'optimizer': optimizer.state_dict(),NEWLINE 'last_epoch': epoch,NEWLINE },NEWLINE os.path.join(saved_path, 'checkpoint_{}.pt'.format(epoch)))NEWLINE returnNEWLINENEWLINENEWLINEdef main():NEWLINE """train and eval model"""NEWLINE train_val_test()NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE main() # Copyright 2021 The Flax Authors.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINE"""Class and functions to define and initialize the actor-critic model."""NEWLINENEWLINEimport functoolsNEWLINEimport numpy as onpNEWLINEfrom flax import linen as nnNEWLINEfrom flax import optimNEWLINEimport jaxNEWLINEimport jax.numpy as jnpNEWLINENEWLINE# See issue #620.NEWLINE# pytype: disable=wrong-keyword-argsNEWLINENEWLINENEWLINEclass ActorCritic(nn.Module):NEWLINE """Class defining the actor-critic model."""NEWLINENEWLINE num_outputs: intNEWLINENEWLINE @nn.compactNEWLINE def __call__(self, x):NEWLINE """Define the convolutional network architecture.NEWLINENEWLINE Architecture originates from "Human-level control through deep reinforcementNEWLINE learning.", Nature 518, no. 7540 (2015): 529-533.NEWLINE Note that this is different than the one from "Playing atari with deepNEWLINE reinforcement learning." arxiv.org/abs/1312.5602 (2013)NEWLINENEWLINE Network is used to both estimate policy (logits) and expected state value;NEWLINE in other words, hidden layers' params are shared between policy and valueNEWLINE networks, see e.g.:NEWLINE github.com/openai/baselines/blob/master/baselines/ppo1/cnn_policy.pyNEWLINE """NEWLINE dtype = jnp.float32NEWLINE x = x.astype(dtype) / 255.NEWLINE x = nn.Conv(features=32, kernel_size=(8, 8), strides=(4, 4), name='conv1',NEWLINE dtype=dtype)(x)NEWLINE x = nn.relu(x)NEWLINE x = nn.Conv(features=64, kernel_size=(4, 4), strides=(2, 2), name='conv2',NEWLINE dtype=dtype)(x)NEWLINE x = nn.relu(x)NEWLINE x = nn.Conv(features=64, kernel_size=(3, 3), strides=(1, 1), name='conv3',NEWLINE dtype=dtype)(x)NEWLINE x = nn.relu(x)NEWLINE x = x.reshape((x.shape[0], -1)) # flattenNEWLINE x = nn.Dense(features=512, name='hidden', dtype=dtype)(x)NEWLINE x = nn.relu(x)NEWLINE logits = nn.Dense(features=self.num_outputs, name='logits', dtype=dtype)(x)NEWLINE policy_log_probabilities = nn.log_softmax(logits)NEWLINE value = nn.Dense(features=1, name='value', dtype=dtype)(x)NEWLINE return policy_log_probabilities, valueNEWLINENEWLINE@functools.partial(jax.jit, static_argnums=1)NEWLINEdef get_initial_params(key: onp.ndarray, module: ActorCritic):NEWLINE input_dims = (1, 84, 84, 4) # (minibatch, height, width, stacked frames)NEWLINE init_shape = jnp.ones(input_dims, jnp.float32)NEWLINE initial_params = module.init(key, init_shape)['params']NEWLINE return initial_paramsNEWLINENEWLINEdef create_optimizer(params, learning_rate: float):NEWLINE optimizer_def = optim.Adam(learning_rate)NEWLINE optimizer = optimizer_def.create(params)NEWLINE return optimizerNEWLINE import matplotlib.pyplot as pltNEWLINEfrom sklearn.manifold import TSNENEWLINENEWLINE# Tsne PlotNEWLINEdef tsneplot(embeddings,labels,fig_path):NEWLINE print("********************* tSNE Plot*********************")NEWLINE X = TSNE(n_components=2,perplexity=100,n_iter=1000).fit_transform(embeddings)NEWLINE colors = ['#FF0000', '#06D506', '#0931F7', '#00FFFF', '#FFE500', '#F700FF', '#9300FF', '#FFD700','#10DADE'] # Red , Green, BlueNEWLINE for c in range(len(colors)):NEWLINE points = []NEWLINE for j in range(len(labels)):NEWLINE if (labels[j] == c):NEWLINE points.append(list(X[j]))NEWLINE x = []NEWLINE y = []NEWLINE for z in points:NEWLINE x.append(z[0])NEWLINE y.append(z[1])NEWLINE plt.plot(x, y, 'ro', c=colors[c], markersize=20, marker='.')NEWLINE plt.axis('off')NEWLINE plt.savefig(fig_path)NEWLINE plt.close() # proxy moduleNEWLINEfrom traitsui.wx.boolean_editor import *NEWLINE import pathlibNEWLINEimport randomNEWLINEimport reNEWLINENEWLINENEWLINEclass Tip:NEWLINE def __init__(self, html=None, ref_url=None, ref_name=None):NEWLINE self.html = htmlNEWLINE self.ref_url = ref_urlNEWLINE self.ref_name = ref_nameNEWLINENEWLINE @staticmethodNEWLINE def parse_meta(meta):NEWLINE meta = meta.split('\n')NEWLINE meta = [kv.split(': ') for kv in meta]NEWLINE meta = {k: v for k, v in meta}NEWLINE return metaNEWLINENEWLINE @classmethodNEWLINE def from_file(cls, path):NEWLINE with open(path, 'r') as f:NEWLINE html = f.read() # .split('\n')NEWLINE try:NEWLINE meta, content = re.split(r'\n-{3,}\n', html, maxsplit=1)NEWLINE except (IndexError, ValueError):NEWLINE return cls('parse error', '', '')NEWLINE meta = cls.parse_meta(meta)NEWLINE return cls(content, **meta)NEWLINENEWLINE def __repr__(self):NEWLINE return self.htmlNEWLINENEWLINE def _repr_html_(self):NEWLINE return self.nice_output()NEWLINENEWLINE def nice_output(self):NEWLINE html = f'''NEWLINE NEWLINE

NEWLINE Source: {self.ref_name}NEWLINE

NEWLINE '''NEWLINE return htmlNEWLINENEWLINENEWLINEdef random_tip():NEWLINE tip_list = pathlib.Path(__file__).parent / 'tip_files'NEWLINE tip_list = list(tip_list.iterdir())NEWLINE tip_file = random.choice(tip_list)NEWLINE tip = Tip.from_file(tip_file)NEWLINE return tipNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE random_tip()NEWLINE from django.db import modelsNEWLINEfrom django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \NEWLINE PermissionsMixinNEWLINENEWLINEclass UserManager(BaseUserManager):NEWLINE def create_user(self, email, password=None, **extra_fields):NEWLINE """creates and saves a new user"""NEWLINE if not email:NEWLINE raise ValueError('Users must have an email address')NEWLINE user = self.model(email=self.normalize_email(email), **extra_fields)NEWLINE user.set_password(password)NEWLINE user.save(using=self._db)NEWLINE return userNEWLINENEWLINE def create_superuser(self, email, password):NEWLINE """Creates and saves a new super user"""NEWLINE user = self.create_user(email, password)NEWLINE user.is_staff = TrueNEWLINE user.is_superuser = TrueNEWLINE user.save(using= self._db)NEWLINE return user NEWLINENEWLINENEWLINEclass User(AbstractBaseUser,PermissionsMixin):NEWLINE """custom user model that supports using email insteadof username"""NEWLINE email = models.EmailField(max_length=255, unique=True)NEWLINE name = models.CharField(max_length=255)NEWLINE is_active = models.BooleanField(default=True)NEWLINE is_staff = models.BooleanField(default=False)NEWLINENEWLINE objects = UserManager()NEWLINENEWLINE USERNAME_FIELD = 'email' n = int(input())NEWLINEfor j in range(n):NEWLINE word = input()NEWLINE if len(word) <= 10:NEWLINE print(word)NEWLINE else:NEWLINE print(word[0] + str(len(word)-2) + word[-1])NEWLINE import torchNEWLINENEWLINE#from tinydfa import DFA, DFALayer, FeedbackPointsHandlingNEWLINEfrom tinydfa.light_dfa import DFA, DFALayerNEWLINENEWLINENEWLINEclass VeryTinyNeRFModel(torch.nn.Module):NEWLINE r"""Define a "very tiny" NeRF model comprising three fully connected layers.NEWLINE """NEWLINENEWLINE def __init__(self, filter_size=128, num_encoding_functions=6, use_viewdirs=True):NEWLINE super(VeryTinyNeRFModel, self).__init__()NEWLINE self.num_encoding_functions = num_encoding_functionsNEWLINE self.xyz_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINE if use_viewdirs is True:NEWLINE self.viewdir_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINE else:NEWLINE self.viewdir_encoding_dims = 0NEWLINE # Input layer (default: 65 -> 128)NEWLINE self.layer1 = torch.nn.Linear(NEWLINE self.xyz_encoding_dims + self.viewdir_encoding_dims, filter_sizeNEWLINE )NEWLINE # Layer 2 (default: 128 -> 128)NEWLINE self.layer2 = torch.nn.Linear(filter_size, filter_size)NEWLINE # Layer 3 (default: 128 -> 4)NEWLINE self.layer3 = torch.nn.Linear(filter_size, 4)NEWLINE # Short hand for torch.nn.functional.reluNEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE x = self.relu(self.layer1(x))NEWLINE x = self.relu(self.layer2(x))NEWLINE x = self.layer3(x)NEWLINE return xNEWLINENEWLINENEWLINEclass MultiHeadNeRFModel(torch.nn.Module):NEWLINE r"""Define a "multi-head" NeRF model (radiance and RGB colors are predicted byNEWLINE separate heads).NEWLINE """NEWLINENEWLINE def __init__(self, hidden_size=128, num_encoding_functions=6, use_viewdirs=True):NEWLINE super(MultiHeadNeRFModel, self).__init__()NEWLINE self.num_encoding_functions = num_encoding_functionsNEWLINE self.xyz_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINE if use_viewdirs is True:NEWLINE self.viewdir_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINE else:NEWLINE self.viewdir_encoding_dims = 0NEWLINE # Input layer (default: 39 -> 128)NEWLINE self.layer1 = torch.nn.Linear(self.xyz_encoding_dims, hidden_size)NEWLINE # Layer 2 (default: 128 -> 128)NEWLINE self.layer2 = torch.nn.Linear(hidden_size, hidden_size)NEWLINE # Layer 3_1 (default: 128 -> 1): Predicts radiance ("sigma")NEWLINE self.layer3_1 = torch.nn.Linear(hidden_size, 1)NEWLINE # Layer 3_2 (default: 128 -> 1): Predicts a feature vector (used for color)NEWLINE self.layer3_2 = torch.nn.Linear(hidden_size, hidden_size)NEWLINENEWLINE # Layer 4 (default: 39 + 128 -> 128)NEWLINE self.layer4 = torch.nn.Linear(NEWLINE self.viewdir_encoding_dims + hidden_size, hidden_sizeNEWLINE )NEWLINE # Layer 5 (default: 128 -> 128)NEWLINE self.layer5 = torch.nn.Linear(hidden_size, hidden_size)NEWLINE # Layer 6 (default: 128 -> 3): Predicts RGB colorNEWLINE self.layer6 = torch.nn.Linear(hidden_size, 3)NEWLINENEWLINE # Short hand for torch.nn.functional.reluNEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE x, view = x[..., : self.xyz_encoding_dims], x[..., self.xyz_encoding_dims :]NEWLINE x = self.relu(self.layer1(x))NEWLINE x = self.relu(self.layer2(x))NEWLINE sigma = self.layer3_1(x)NEWLINE feat = self.relu(self.layer3_2(x))NEWLINE x = torch.cat((feat, view), dim=-1)NEWLINE x = self.relu(self.layer4(x))NEWLINE x = self.relu(self.layer5(x))NEWLINE x = self.layer6(x)NEWLINE return torch.cat((x, sigma), dim=-1)NEWLINENEWLINENEWLINEclass ReplicateNeRFModel(torch.nn.Module):NEWLINE r"""NeRF model that follows the figure (from the supp. material of NeRF) toNEWLINE every last detail. (ofc, with some flexibility)NEWLINE """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE hidden_size=256,NEWLINE num_layers=4,NEWLINE num_encoding_fn_xyz=6,NEWLINE num_encoding_fn_dir=4,NEWLINE include_input_xyz=True,NEWLINE include_input_dir=True,NEWLINE ):NEWLINE super(ReplicateNeRFModel, self).__init__()NEWLINE # xyz_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINENEWLINE self.dim_xyz = (3 if include_input_xyz else 0) + 2 * 3 * num_encoding_fn_xyzNEWLINE self.dim_dir = (3 if include_input_dir else 0) + 2 * 3 * num_encoding_fn_dirNEWLINENEWLINE self.layer1 = torch.nn.Linear(self.dim_xyz, hidden_size)NEWLINE self.layer2 = torch.nn.Linear(hidden_size, hidden_size)NEWLINE self.layer3 = torch.nn.Linear(hidden_size, hidden_size)NEWLINE self.fc_alpha = torch.nn.Linear(hidden_size, 1)NEWLINENEWLINE self.layer4 = torch.nn.Linear(hidden_size + self.dim_dir, hidden_size // 2)NEWLINE self.layer5 = torch.nn.Linear(hidden_size // 2, hidden_size // 2)NEWLINE self.fc_rgb = torch.nn.Linear(hidden_size // 2, 3)NEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE xyz, direction = x[..., : self.dim_xyz], x[..., self.dim_xyz :]NEWLINE x_ = self.relu(self.layer1(xyz))NEWLINE x_ = self.relu(self.layer2(x_))NEWLINE feat = self.layer3(x_)NEWLINE alpha = self.fc_alpha(x_)NEWLINE y_ = self.relu(self.layer4(torch.cat((feat, direction), dim=-1)))NEWLINE y_ = self.relu(self.layer5(y_))NEWLINE rgb = self.fc_rgb(y_)NEWLINE return torch.cat((rgb, alpha), dim=-1)NEWLINENEWLINENEWLINEclass PaperNeRFModel(torch.nn.Module):NEWLINE r"""Implements the NeRF model as described in Fig. 7 (appendix) of theNEWLINE arXiv submission (v0). """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE num_layers=8,NEWLINE hidden_size=256,NEWLINE skip_connect_every=4,NEWLINE num_encoding_fn_xyz=6,NEWLINE num_encoding_fn_dir=4,NEWLINE include_input_xyz=True,NEWLINE include_input_dir=True,NEWLINE use_viewdirs=True,NEWLINE ):NEWLINE super(PaperNeRFModel, self).__init__()NEWLINENEWLINE include_input_xyz = 3 if include_input_xyz else 0NEWLINE include_input_dir = 3 if include_input_dir else 0NEWLINE self.dim_xyz = include_input_xyz + 2 * 3 * num_encoding_fn_xyzNEWLINE self.dim_dir = include_input_dir + 2 * 3 * num_encoding_fn_dirNEWLINENEWLINE self.layers_xyz = torch.nn.ModuleList()NEWLINE self.use_viewdirs = use_viewdirsNEWLINE self.layers_xyz.append(torch.nn.Linear(self.dim_xyz, 256))NEWLINE for i in range(1, 8):NEWLINE if i == 4:NEWLINE self.layers_xyz.append(torch.nn.Linear(self.dim_xyz + 256, 256))NEWLINE else:NEWLINE self.layers_xyz.append(torch.nn.Linear(256, 256))NEWLINE self.fc_feat = torch.nn.Linear(256, 256)NEWLINE self.fc_alpha = torch.nn.Linear(256, 1)NEWLINENEWLINE self.layers_dir = torch.nn.ModuleList()NEWLINE self.layers_dir.append(torch.nn.Linear(256 + self.dim_dir, 128))NEWLINE for i in range(3):NEWLINE self.layers_dir.append(torch.nn.Linear(128, 128))NEWLINE self.fc_rgb = torch.nn.Linear(128, 3)NEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE xyz, dirs = x[..., : self.dim_xyz], x[..., self.dim_xyz :]NEWLINE for i in range(8):NEWLINE if i == 4:NEWLINE x = self.layers_xyz[i](torch.cat((xyz, x), -1))NEWLINE else:NEWLINE x = self.layers_xyz[i](x)NEWLINE x = self.relu(x)NEWLINE feat = self.fc_feat(x)NEWLINE alpha = self.fc_alpha(feat)NEWLINE if self.use_viewdirs:NEWLINE x = self.layers_dir[0](torch.cat((feat, dirs), -1))NEWLINE else:NEWLINE x = self.layers_dir[0](feat)NEWLINE x = self.relu(x)NEWLINE for i in range(1, 3):NEWLINE x = self.layers_dir[i](x)NEWLINE x = self.relu(x)NEWLINE rgb = self.fc_rgb(x)NEWLINE return torch.cat((rgb, alpha), dim=-1)NEWLINENEWLINENEWLINEclass FlexibleNeRFModel(torch.nn.Module):NEWLINE def __init__(NEWLINE self,NEWLINE num_layers=4,NEWLINE hidden_size=128,NEWLINE skip_connect_every=4,NEWLINE num_encoding_fn_xyz=6,NEWLINE num_encoding_fn_dir=4,NEWLINE include_input_xyz=True,NEWLINE include_input_dir=True,NEWLINE use_viewdirs=True,NEWLINE ):NEWLINE super(FlexibleNeRFModel, self).__init__()NEWLINENEWLINE include_input_xyz = 3 if include_input_xyz else 0NEWLINE include_input_dir = 3 if include_input_dir else 0NEWLINE self.dim_xyz = include_input_xyz + 2 * 3 * num_encoding_fn_xyzNEWLINE self.dim_dir = include_input_dir + 2 * 3 * num_encoding_fn_dirNEWLINE self.skip_connect_every = skip_connect_everyNEWLINE if not use_viewdirs:NEWLINE self.dim_dir = 0NEWLINENEWLINE self.layer1 = torch.nn.Linear(self.dim_xyz, hidden_size)NEWLINE self.layers_xyz = torch.nn.ModuleList()NEWLINE for i in range(num_layers - 1):NEWLINE if i % self.skip_connect_every == 0 and i > 0 and i != num_layers - 1:NEWLINE self.layers_xyz.append(NEWLINE torch.nn.Linear(self.dim_xyz + hidden_size, hidden_size)NEWLINE )NEWLINE else:NEWLINE self.layers_xyz.append(torch.nn.Linear(hidden_size, hidden_size))NEWLINENEWLINE self.use_viewdirs = use_viewdirsNEWLINE if self.use_viewdirs:NEWLINE self.layers_dir = torch.nn.ModuleList()NEWLINE # This deviates from the original paper, and follows the code release instead.NEWLINE self.layers_dir.append(NEWLINE torch.nn.Linear(self.dim_dir + hidden_size, hidden_size // 2)NEWLINE )NEWLINENEWLINE self.fc_alpha = torch.nn.Linear(hidden_size, 1)NEWLINE self.fc_rgb = torch.nn.Linear(hidden_size // 2, 3)NEWLINE self.fc_feat = torch.nn.Linear(hidden_size, hidden_size)NEWLINE else:NEWLINE self.fc_out = torch.nn.Linear(hidden_size, 4)NEWLINENEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE if self.use_viewdirs:NEWLINE xyz, view = x[..., : self.dim_xyz], x[..., self.dim_xyz :]NEWLINE else:NEWLINE xyz = x[..., : self.dim_xyz]NEWLINE x = self.layer1(xyz) # Missing a ReLU (?)NEWLINE for i in range(len(self.layers_xyz)):NEWLINE if (NEWLINE i % self.skip_connect_every == 0NEWLINE and i > 0NEWLINE and i != len(self.linear_layers) - 1NEWLINE ):NEWLINE x = torch.cat((x, xyz), dim=-1)NEWLINE x = self.relu(self.layers_xyz[i](x))NEWLINE if self.use_viewdirs:NEWLINE feat = self.relu(self.fc_feat(x))NEWLINE alpha = self.fc_alpha(x)NEWLINE x = torch.cat((feat, view), dim=-1)NEWLINE for l in self.layers_dir:NEWLINE x = self.relu(l(x))NEWLINE rgb = self.fc_rgb(x)NEWLINE return torch.cat((rgb, alpha), dim=-1)NEWLINE else:NEWLINE return self.fc_out(x)NEWLINENEWLINENEWLINEclass DFAFlexibleNeRFModel(torch.nn.Module):NEWLINE def __init__(self, num_layers=4, hidden_size=128, skip_connect_every=4, num_encoding_fn_xyz=6,NEWLINE num_encoding_fn_dir=4, include_input_xyz=True, include_input_dir=True, use_viewdirs=True,):NEWLINE super(DFAFlexibleNeRFModel, self).__init__()NEWLINENEWLINE # Determine the inputs:NEWLINE include_input_xyz = 3 if include_input_xyz else 0 # Add raw xyz coordinatesNEWLINE include_input_dir = 3 if include_input_dir else 0 # Add raw viewing angle (specularity)NEWLINE self.dim_xyz = include_input_xyz + 2 * 3 * num_encoding_fn_xyz # Total xyz input: raw? + embeddingNEWLINENEWLINE self.use_viewdirs = use_viewdirs # Are we using view direction? (specularity)NEWLINE if not self.use_viewdirs:NEWLINE self.dim_dir = 0NEWLINE else:NEWLINE self.dim_dir = include_input_dir + 2 * 3 * num_encoding_fn_dirNEWLINENEWLINE # Network layersNEWLINE self.layer1 = torch.nn.Linear(self.dim_xyz, hidden_size) # Input layerNEWLINE self.dfa1 = DFALayer(name='dfa1')NEWLINE # First stack of layers, using only xyz coordinates:NEWLINE self.layers_xyz = torch.nn.ModuleList()NEWLINE self.dfa_xyz = torch.nn.ModuleList()NEWLINE self.skip_connect_every = skip_connect_everyNEWLINE for i in range(num_layers - 1):NEWLINE if i % self.skip_connect_every == 0 and i > 0 and i != num_layers - 1:NEWLINE # Handle skip-connection.NEWLINE self.layers_xyz.append(torch.nn.Linear(self.dim_xyz + hidden_size, hidden_size))NEWLINE else:NEWLINE self.layers_xyz.append(torch.nn.Linear(hidden_size, hidden_size))NEWLINE self.dfa_xyz.append(DFALayer(name=f'dfa_xyz{i}'))NEWLINENEWLINENEWLINE if self.use_viewdirs:NEWLINE self.fc_alpha = torch.nn.Linear(hidden_size, 1) # Transparency output at top of xyz stackNEWLINENEWLINE self.fc_feat = torch.nn.Linear(hidden_size, hidden_size) # Link between angle stack and xyz stackNEWLINE self.dfa_feat = DFALayer(name='dfa_feat')NEWLINENEWLINE # Second stack of layers, using viewing angle:NEWLINE self.layers_dir = torch.nn.ModuleList()NEWLINE # This deviates from the original paper, and follows the code release instead.NEWLINE self.layers_dir.append(NEWLINE torch.nn.Linear(self.dim_dir + hidden_size, hidden_size // 2)NEWLINE )NEWLINE self.dfa_dir = DFALayer(name='dfa_dir')NEWLINENEWLINE self.fc_rgb = torch.nn.Linear(hidden_size // 2, 3) # RGB color output, at top of viewing angle stackNEWLINE else:NEWLINE # If not using viewing angle, go straight to (transparency, r, g, b) output:NEWLINE self.fc_out = torch.nn.Linear(hidden_size, 4)NEWLINENEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE self.dfa_layers = [self.dfa1, *self.dfa_xyz, self.dfa_feat, self.dfa_dir]NEWLINE self.dfa = DFA(self.dfa_layers) #feedback_points_handling=FeedbackPointsHandling.MINIBATCH)NEWLINENEWLINE def forward(self, x):NEWLINE # Separate the xyz and viewing angle embeddingsNEWLINE if self.use_viewdirs:NEWLINE xyz, view = x[..., :self.dim_xyz], x[..., self.dim_xyz:]NEWLINE else:NEWLINE xyz = x[..., :self.dim_xyz]NEWLINENEWLINE x = self.dfa1(self.relu(self.layer1(xyz))) # Go through first layerNEWLINE # Go through xyz stack:NEWLINE for i in range(len(self.layers_xyz)):NEWLINE if (i % self.skip_connect_every == 0 and i > 0 and i != len(self.linear_layers) - 1):NEWLINE # Handle skip connectionNEWLINE x = torch.cat((x, xyz), dim=-1)NEWLINE x = self.dfa_xyz[i](self.relu(self.layers_xyz[i](x))) # Go through layerNEWLINENEWLINE if self.use_viewdirs:NEWLINE alpha = self.fc_alpha(x) # Output alpha (transparency value)NEWLINE # Prepare for viewing angle stack:NEWLINE feat = self.dfa_feat(self.relu(self.fc_feat(x))) # Link between xyz/viewing angle stackNEWLINE x = torch.cat((feat, view), dim=-1) # Add viewing angle informationNEWLINE for l in self.layers_dir:NEWLINE # Go through viewing angle stack (proper):NEWLINE x = self.dfa_dir(self.relu(l(x)))NEWLINE rgb = self.fc_rgb(x) # Output rgb valueNEWLINE return self.dfa(torch.cat((rgb, alpha), dim=-1))NEWLINE else:NEWLINE return self.dfa(self.fc_out(x))NEWLINE """NEWLINEWSGI config for DjangoECom project.NEWLINENEWLINEIt exposes the WSGI callable as a module-level variable named ``application``.NEWLINENEWLINEFor more information on this file, seeNEWLINEhttps://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/NEWLINE"""NEWLINENEWLINEimport osNEWLINENEWLINEfrom django.core.wsgi import get_wsgi_applicationNEWLINENEWLINEos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoECom.settings')NEWLINENEWLINEapplication = get_wsgi_application()NEWLINE # import the generic views you want, and the models NEWLINE# they apply to.NEWLINEfrom django.views.generic import ListViewNEWLINENEWLINE# Import the models you want to use.NEWLINEfrom snippets.models import SnippetNEWLINENEWLINE# Create a class for your model that subclassesNEWLINE# the generic view you want. This serves as anNEWLINE# index view.NEWLINEclass SnippetListView(ListView):NEWLINE # Finally, tell the generic view what modelNEWLINE # it applies to, and which template to use.NEWLINE model = SnippetNEWLINE template_name = 'snippets/index.html'NEWLINENEWLINE# ==============================================NEWLINENEWLINE# In your urls.py, you'll need to update the NEWLINE# corresponding route. It'll look like this.NEWLINEurls(r'^index/$', views.SnippetListView.as_view())NEWLINE # Copyright © 2019 Province of British ColumbiaNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE"""The unique worker functionality for this service is contained here.NEWLINENEWLINEThe entry-point is the **cb_subscription_handler**NEWLINENEWLINEThe design and flow leverage a few constraints that are placed upon itNEWLINEby NATS Streaming and using AWAIT on the default loop.NEWLINE- NATS streaming queues require one message to be processed at a time.NEWLINE- AWAIT on the default loop effectively runs synchronouslyNEWLINENEWLINEIf these constraints change, the use of Flask-SQLAlchemy would need to change.NEWLINEFlask-SQLAlchemy currently allows the base model to be changed, or reworkingNEWLINEthe model to a standalone SQLAlchemy usage with an async engine would needNEWLINEto be pursued.NEWLINE"""NEWLINEimport asyncioNEWLINEimport datetimeNEWLINEimport jsonNEWLINEimport osNEWLINENEWLINEimport natsNEWLINEfrom flask import FlaskNEWLINEfrom legal_api import dbNEWLINEfrom legal_api.models import FilingNEWLINEfrom sentry_sdk import capture_messageNEWLINEfrom sqlalchemy.exc import OperationalErrorNEWLINEfrom entity_queue_common.messages import create_filing_msgNEWLINEfrom entity_queue_common.service import QueueServiceManagerNEWLINEfrom entity_queue_common.service_utils import FilingException, QueueException, loggerNEWLINENEWLINEfrom entity_pay import configNEWLINENEWLINEqsm = QueueServiceManager() # pylint: disable=invalid-nameNEWLINEAPP_CONFIG = config.get_named_config(os.getenv('DEPLOYMENT_ENV', 'production'))NEWLINEFLASK_APP = Flask(__name__)NEWLINEFLASK_APP.config.from_object(APP_CONFIG)NEWLINEdb.init_app(FLASK_APP)NEWLINENEWLINENEWLINEdef extract_payment_token(msg: nats.aio.client.Msg) -> dict:NEWLINE """Return a dict of the json string in the Msg.data."""NEWLINE return json.loads(msg.data.decode('utf-8'))NEWLINENEWLINENEWLINEdef get_filing_by_payment_id(payment_id: int) -> Filing:NEWLINE """Return the outcome of Filing.get_filing_by_payment_token."""NEWLINE return Filing.get_filing_by_payment_token(str(payment_id))NEWLINENEWLINENEWLINEasync def publish_filing(filing: Filing):NEWLINE """Publish the filing message onto the NATS filing subject."""NEWLINE payload = create_filing_msg(filing.id)NEWLINE subject = APP_CONFIG.FILER_PUBLISH_OPTIONS['subject']NEWLINENEWLINE await qsm.service.publish(subject, payload)NEWLINENEWLINENEWLINEasync def process_payment(payment_token, flask_app):NEWLINE """Render the payment status."""NEWLINE if not flask_app:NEWLINE raise QueueException('Flask App not available.')NEWLINENEWLINE with flask_app.app_context():NEWLINENEWLINE # try to find the filing 5 times before putting back on the queue - in case payment token ends up on the queueNEWLINE # before it is assigned to filing.NEWLINE counter = 1NEWLINE filing_submission = NoneNEWLINE while not filing_submission and counter <= 5:NEWLINE filing_submission = get_filing_by_payment_id(payment_token['paymentToken'].get('id'))NEWLINE counter += 1NEWLINE if not filing_submission:NEWLINE await asyncio.sleep(0.2)NEWLINE if not filing_submission:NEWLINE raise FilingExceptionNEWLINENEWLINE if filing_submission.status == Filing.Status.COMPLETED.value:NEWLINE # log and skip thisNEWLINE # it shouldn't be an error, but there could be something to investigate ifNEWLINE # multiple retries are happening on something that should have been completed.NEWLINE logger.warning('Queue: Attempting to reprocess business.id=%s, filing.id=%s payment=%s',NEWLINE filing_submission.business_id, filing_submission.id, payment_token)NEWLINE capture_message(f'Queue Issue: Attempting to reprocess business.id={filing_submission.business_id},'NEWLINE 'filing.id={filing_submission.id} payment={payment_token}')NEWLINE returnNEWLINENEWLINE if payment_token['paymentToken'].get('statusCode') == 'TRANSACTION_FAILED':NEWLINE # TODO: The customer has cancelled out of paying, so we could note this betterNEWLINE # technically the filing is still pending payment/processingNEWLINE returnNEWLINENEWLINE if payment_token['paymentToken'].get('statusCode') == Filing.Status.COMPLETED.value:NEWLINE filing_submission.payment_completion_date = datetime.datetime.utcnow()NEWLINE db.session.add(filing_submission)NEWLINE db.session.commit()NEWLINENEWLINE if not filing_submission.effective_date or \NEWLINE filing_submission.effective_date <= datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc):NEWLINE # if we're not a future effective date, then submit for processingNEWLINE try:NEWLINE await publish_filing(filing_submission)NEWLINE except Exception as err: # pylint: disable=broad-except, unused-variable # noqa F841;NEWLINE # mark any failure for human reviewNEWLINE capture_message('Queue Error: Failied to place filing:{filing_submission.id} on Queue with error:{err}',NEWLINE level='error')NEWLINENEWLINE returnNEWLINENEWLINE # if we're here and haven't been able to action it,NEWLINE # then we've received an unknown status and should throw an errorNEWLINE logger.error('Unknown payment status given: %s', payment_token['paymentToken'].get('statusCode'))NEWLINE raise QueueExceptionNEWLINENEWLINENEWLINEasync def cb_subscription_handler(msg: nats.aio.client.Msg):NEWLINE """Use Callback to process Queue Msg objects."""NEWLINE try:NEWLINE logger.info('Received raw message seq:%s, data= %s', msg.sequence, msg.data.decode())NEWLINE payment_token = extract_payment_token(msg)NEWLINE logger.debug('Extracted payment token: %s', payment_token)NEWLINE await process_payment(payment_token, FLASK_APP)NEWLINE except OperationalError as err:NEWLINE logger.error('Queue Blocked - Database Issue: %s', json.dumps(payment_token), exc_info=True)NEWLINE raise err # We don't want to handle the error, as a DB down would drain the queueNEWLINE except FilingException as err:NEWLINE logger.error('Queue Error - cannot find filing: %s'NEWLINE '\n\nThis message has been put back on the queue for reprocessing.',NEWLINE json.dumps(payment_token), exc_info=True)NEWLINE raise err # we don't want to handle the error, so that the message gets put back on the queueNEWLINE except (QueueException, Exception): # pylint: disable=broad-exceptNEWLINE # Catch Exception so that any error is still caught and the message is removed from the queueNEWLINE capture_message('Queue Error:' + json.dumps(payment_token), level='error')NEWLINE logger.error('Queue Error: %s', json.dumps(payment_token), exc_info=True)NEWLINE import pyaf.Bench.TS_datasets as tsdsNEWLINEimport tests.artificial.process_artificial_dataset as artNEWLINENEWLINENEWLINENEWLINENEWLINEart.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 7, transform = "RelativeDifference", sigma = 0.0, exog_count = 0, ar_order = 12); # coding=utf-8NEWLINE# Copyright 2020 The TensorFlow GAN Authors.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINE"""Trains a CycleGAN model."""NEWLINENEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import print_functionNEWLINENEWLINEfrom absl import appNEWLINEfrom absl import flagsNEWLINENEWLINEimport tensorflow.compat.v1 as tfNEWLINEfrom tensorflow_gan.examples.cyclegan import train_libNEWLINENEWLINEflags.DEFINE_string('image_set_x_file_pattern', None,NEWLINE 'File pattern of images in image set X')NEWLINEflags.DEFINE_string('image_set_y_file_pattern', None,NEWLINE 'File pattern of images in image set Y')NEWLINEflags.DEFINE_integer('batch_size', 1, 'The number of images in each batch.')NEWLINEflags.DEFINE_integer('patch_size', 64, 'The patch size of images.')NEWLINEflags.DEFINE_string('master', '', 'Name of the TensorFlow master to use.')NEWLINEflags.DEFINE_string('train_log_dir', '/tmp/tfgan_logdir/cyclegan/',NEWLINE 'Directory where to write event logs.')NEWLINEflags.DEFINE_float('generator_lr', 0.0002,NEWLINE 'The compression model learning rate.')NEWLINEflags.DEFINE_float('discriminator_lr', 0.0001,NEWLINE 'The discriminator learning rate.')NEWLINEflags.DEFINE_integer('max_number_of_steps', 500000,NEWLINE 'The maximum number of gradient steps.')NEWLINEflags.DEFINE_integer(NEWLINE 'ps_replicas', 0,NEWLINE 'The number of parameter servers. If the value is 0, then the parameters 'NEWLINE 'are handled locally by the worker.')NEWLINEflags.DEFINE_integer(NEWLINE 'task', 0,NEWLINE 'The Task ID. This value is used when training with multiple workers to 'NEWLINE 'identify each worker.')NEWLINEflags.DEFINE_float('cycle_consistency_loss_weight', 10.0,NEWLINE 'The weight of cycle consistency loss')NEWLINENEWLINEFLAGS = flags.FLAGSNEWLINENEWLINENEWLINEdef main(_):NEWLINE hparams = train_lib.HParams(NEWLINE FLAGS.image_set_x_file_pattern, FLAGS.image_set_y_file_pattern,NEWLINE FLAGS.batch_size, FLAGS.patch_size, FLAGS.master, FLAGS.train_log_dir,NEWLINE FLAGS.generator_lr, FLAGS.discriminator_lr, FLAGS.max_number_of_steps,NEWLINE FLAGS.ps_replicas, FLAGS.task, FLAGS.cycle_consistency_loss_weight)NEWLINE train_lib.train(hparams)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE tf.disable_v2_behavior()NEWLINE app.run(main)NEWLINE #NEWLINE# Copyright (c) 2016-2021 JEP AUTHORS.NEWLINE#NEWLINE# This file is licensed under the the zlib/libpng License.NEWLINE#NEWLINE# This software is provided 'as-is', without any express or impliedNEWLINE# warranty. In no event will the authors be held liable for anyNEWLINE# damages arising from the use of this software.NEWLINE# NEWLINE# Permission is granted to anyone to use this software for anyNEWLINE# purpose, including commercial applications, and to alter it andNEWLINE# redistribute it freely, subject to the following restrictions:NEWLINE# NEWLINE# 1. The origin of this software must not be misrepresented; youNEWLINE# must not claim that you wrote the original software. If you useNEWLINE# this software in a product, an acknowledgment in the productNEWLINE# documentation would be appreciated but is not required.NEWLINE# NEWLINE# 2. Altered source versions must be plainly marked as such, andNEWLINE# must not be misrepresented as being the original software.NEWLINE# NEWLINE# 3. This notice may not be removed or altered from any sourceNEWLINE# distribution.NEWLINE#NEWLINENEWLINEimport sysNEWLINENEWLINEclass StreamRedirect(object):NEWLINE "Redirects a Python output stream to a Java OutputStream"NEWLINENEWLINE def __init__(self, javaOutputStream):NEWLINE from java.io import PrintStreamNEWLINE self.printstream = PrintStream(javaOutputStream)NEWLINE self.printmethod = getattr(self.printstream, 'print')NEWLINE self.flushmethod = getattr(self.printstream, 'flush')NEWLINENEWLINE def write(self, msg):NEWLINE self.printmethod(msg)NEWLINENEWLINE def flush(self):NEWLINE self.flushmethod()NEWLINENEWLINEdef redirectStdout(javaOutputStream):NEWLINE sys.stdout = StreamRedirect(javaOutputStream)NEWLINENEWLINEdef redirectStderr(javaOutputStream):NEWLINE sys.stderr = StreamRedirect(javaOutputStream)NEWLINE #!/usr/bin/env pythonNEWLINE# -*- coding: utf-8 -*-NEWLINE# **************************************************************************NEWLINE# Copyright © 2016 jianglinNEWLINE# File Name: __init__.pyNEWLINE# Author: jianglinNEWLINE# Email: xiyang0807@gmail.comNEWLINE# Created: 2016-11-25 17:45:36 (CST)NEWLINE# Last Update:星期五 2016-11-25 17:45:36 (CST)NEWLINE# By:NEWLINE# Description:NEWLINE# **************************************************************************NEWLINE from typing import ListNEWLINENEWLINEfrom .en import FILTERS as EN_FILTERSNEWLINEfrom .de import FILTERS as DE_FILTERSNEWLINEfrom .fr import FILTERS as FR_FILTERSNEWLINEfrom .es import FILTERS as ES_FILTERSNEWLINEfrom .mx import FILTERS as MX_FILTERSNEWLINEfrom .ru import FILTERS as RU_FILTERSNEWLINEfrom .cn import FILTERS as CN_FILTERSNEWLINEfrom .pt import FILTERS as PT_FILTERSNEWLINEfrom .ko import FILTERS as KO_FILTERSNEWLINENEWLINENEWLINEdef get_filter_list_by_lang(lang: str) -> List[str]:NEWLINE if lang == "en":NEWLINE return EN_FILTERSNEWLINE elif lang == "de":NEWLINE return DE_FILTERSNEWLINE elif lang == "fr":NEWLINE return FR_FILTERSNEWLINE elif lang == "es":NEWLINE return ES_FILTERSNEWLINE elif lang == "mx":NEWLINE return MX_FILTERSNEWLINE elif lang == "ru":NEWLINE return RU_FILTERSNEWLINE elif lang == "cn":NEWLINE return CN_FILTERSNEWLINE elif lang == "pt":NEWLINE return PT_FILTERSNEWLINE elif lang == "ko":NEWLINE return KO_FILTERSNEWLINE else:NEWLINE raise ValueError("Language '{}' not supported".format(lang))NEWLINE #ABC089eNEWLINEimport sysNEWLINEinput = sys.stdin.readlineNEWLINEsys.setrecursionlimit(10**6)NEWLINE from __future__ import absolute_importNEWLINENEWLINEimport sixNEWLINEimport pytzNEWLINENEWLINEfrom datetime import datetimeNEWLINENEWLINEfrom sentry.coreapi import APIUnauthorizedNEWLINEfrom sentry.mediators import Mediator, ParamNEWLINEfrom sentry.mediators.token_exchange.validator import ValidatorNEWLINEfrom sentry.mediators.token_exchange.util import token_expirationNEWLINEfrom sentry.models import ApiApplication, ApiToken, SentryAppNEWLINEfrom sentry.utils.cache import memoizeNEWLINENEWLINENEWLINEclass Refresher(Mediator):NEWLINE """NEWLINE Exchanges a Refresh Token for a new Access TokenNEWLINE """NEWLINENEWLINE install = Param('sentry.models.SentryAppInstallation')NEWLINE refresh_token = Param(six.string_types)NEWLINE client_id = Param(six.string_types)NEWLINE user = Param('sentry.models.User')NEWLINENEWLINE def call(self):NEWLINE self._validate()NEWLINE self._expire_token()NEWLINENEWLINE return ApiToken.objects.create(NEWLINE user=self.user,NEWLINE application=self.application,NEWLINE scope_list=self.sentry_app.scope_list,NEWLINE expires_at=token_expiration(),NEWLINE )NEWLINENEWLINE def _validate(self):NEWLINE Validator.run(NEWLINE install=self.install,NEWLINE client_id=self.client_id,NEWLINE user=self.user,NEWLINE )NEWLINENEWLINE self._validate_token_belongs_to_app()NEWLINE self._validate_token_is_active()NEWLINENEWLINE def _validate_token_belongs_to_app(self):NEWLINE if self.token.application != self.application:NEWLINE raise APIUnauthorizedNEWLINENEWLINE def _validate_token_is_active(self):NEWLINE if self.token.expires_at < datetime.utcnow().replace(tzinfo=pytz.UTC):NEWLINE raise APIUnauthorizedNEWLINENEWLINE def _expire_token(self):NEWLINE self.token.update(expires_at=datetime.utcnow())NEWLINENEWLINE @memoizeNEWLINE def token(self):NEWLINE try:NEWLINE return ApiToken.objects.get(refresh_token=self.refresh_token)NEWLINE except ApiToken.DoesNotExist:NEWLINE raise APIUnauthorizedNEWLINENEWLINE @memoizeNEWLINE def application(self):NEWLINE try:NEWLINE return ApiApplication.objects.get(client_id=self.client_id)NEWLINE except ApiApplication.DoesNotExist:NEWLINE raise APIUnauthorizedNEWLINENEWLINE @propertyNEWLINE def sentry_app(self):NEWLINE try:NEWLINE return self.application.sentry_appNEWLINE except SentryApp.DoesNotExist:NEWLINE raise APIUnauthorizedNEWLINE # -*- coding: utf-8 -*-NEWLINE# Copyright 2020 Google Inc.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINE# Make sure that your AWS credentials are configured correclty, seeNEWLINE# https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html #pylint: disable=line-too-longNEWLINE"""Demo CLI tool for AWS."""NEWLINENEWLINEfrom datetime import datetimeNEWLINEfrom typing import TYPE_CHECKINGNEWLINENEWLINEfrom libcloudforensics.providers.aws.internal import accountNEWLINEfrom libcloudforensics.providers.aws.internal import log as aws_logNEWLINEfrom libcloudforensics.providers.aws import forensicsNEWLINENEWLINEif TYPE_CHECKING:NEWLINE import argparseNEWLINENEWLINENEWLINEdef ListInstances(args: 'argparse.Namespace') -> None:NEWLINE """List EC2 instances in AWS account.NEWLINENEWLINE Args:NEWLINE args (argparse.Namespace): Arguments from ArgumentParser.NEWLINE """NEWLINENEWLINE aws_account = account.AWSAccount(args.zone)NEWLINE instances = aws_account.ListInstances()NEWLINENEWLINE print('Instances found:')NEWLINE for instance in instances:NEWLINE boot_volume = instances[instance].GetBootVolume().volume_idNEWLINE print('Name: {0:s}, Boot volume: {1:s}'.format(instance, boot_volume))NEWLINENEWLINENEWLINEdef ListVolumes(args: 'argparse.Namespace') -> None:NEWLINE """List EBS volumes in AWS account.NEWLINENEWLINE Args:NEWLINE args (argparse.Namespace): Arguments from ArgumentParser.NEWLINE """NEWLINENEWLINE aws_account = account.AWSAccount(args.zone)NEWLINE volumes = aws_account.ListVolumes()NEWLINENEWLINE print('Volumes found:')NEWLINE for volume in volumes:NEWLINE print('Name: {0:s}, Zone: {1:s}'.format(NEWLINE volume, volumes[volume].availability_zone))NEWLINENEWLINENEWLINEdef CreateVolumeCopy(args: 'argparse.Namespace') -> None:NEWLINE """Create a AWS Volume copy.NEWLINENEWLINE Args:NEWLINE args (argparse.Namespace): Arguments from ArgumentParser.NEWLINE """NEWLINE print('Starting volume copy...')NEWLINE volume_copy = forensics.CreateVolumeCopy(args.zone,NEWLINE dst_zone=args.dst_zone,NEWLINE instance_id=args.instance_id,NEWLINE volume_id=args.volume_id,NEWLINE src_profile=args.src_profile,NEWLINE dst_profile=args.dst_profile)NEWLINE print(NEWLINE 'Done! Volume {0:s} successfully created. You will find it in 'NEWLINE 'your AWS account under the name {1:s}.'.format(NEWLINE volume_copy.volume_id, volume_copy.name))NEWLINENEWLINENEWLINEdef QueryLogs(args: 'argparse.Namespace') -> None:NEWLINE """Query AWS CloudTrail log events.NEWLINENEWLINE Args:NEWLINE args (argparse.Namespace): Arguments from ArgumentParser.NEWLINE """NEWLINE ct = aws_log.AWSCloudTrail(account.AWSAccount(args.zone))NEWLINENEWLINE params = {}NEWLINE if args.filter:NEWLINE params['qfilter'] = args.filterNEWLINE if args.start:NEWLINE params['starttime'] = datetime.strptime(args.start, '%Y-%m-%d %H:%M:%S')NEWLINE if args.end:NEWLINE params['endtime'] = datetime.strptime(args.end, '%Y-%m-%d %H:%M:%S')NEWLINENEWLINE result = ct.LookupEvents(**params)NEWLINENEWLINE if result:NEWLINE print('Log events found: {0:d}'.format(len(result)))NEWLINE for event in result:NEWLINE print(event)NEWLINE # coding=utf-8NEWLINEimport shelveNEWLINENEWLINENEWLINEdef store_person(db): # 存储用户输入数据到shelf对象中NEWLINE pid = input('Enter unique ID number: ')NEWLINE person = {}NEWLINE person['name'] = input('Enter name: ')NEWLINE person['age'] = input('Enter age: ')NEWLINE person['phone'] = input('Enter phone number: ')NEWLINE db[pid] = personNEWLINENEWLINENEWLINEdef lookup_person(db): # 从shelf对象中查询数据NEWLINE pid = input('Enter ID number: ')NEWLINE field = input('What would you like to know? (name, age, phone) ')NEWLINE field = field.strip().lower() # 忽略大小写NEWLINE try:NEWLINE print(field.capitalize() + ':', db[pid][field])NEWLINE except KeyError:NEWLINE print("No record.")NEWLINENEWLINENEWLINEdef print_help(): # 帮助信息NEWLINE print('The available commands are:')NEWLINE print('store : Stores information about a person')NEWLINE print('lookup : Looks up a person from ID number')NEWLINE print('quit : Save changes and exit')NEWLINE print('? : Prints this message')NEWLINENEWLINENEWLINEdef enter_command(): # 获取用户输入的命令NEWLINE cmd = input('Enter command (? for help): ')NEWLINE cmd = cmd.strip().lower() # 忽略大小写NEWLINE return cmdNEWLINENEWLINENEWLINEdef main():NEWLINE database = shelve.open('Chapter18_shelve_db') # 打开一个数据库文件NEWLINE try:NEWLINE while True:NEWLINE cmd = enter_command()NEWLINE if cmd == 'store':NEWLINE store_person(database)NEWLINE elif cmd == 'lookup':NEWLINE lookup_person(database)NEWLINE elif cmd == '?':NEWLINE print_help()NEWLINE elif cmd == 'quit':NEWLINE returnNEWLINE finally:NEWLINE database.close() # 关闭数据库NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE main()NEWLINENEWLINE# ### 标准库shelve模块NEWLINE# - Python object persistenceNEWLINE# - 官方文档:https://docs.python.org/3/library/shelve.htmlNEWLINE# - shelve模块可以简单地将数据存储在文件中;NEWLINE#NEWLINE# ### 文件的打开与关闭NEWLINE# shelve.open()函数将一个文件名作为参数,并返回一个可用来存储数据的shelf对象,其类似与所有键都为字符串的字典;NEWLINE# 如果shelve.open()函数的参数writeback设置为True,那么操作过程中的数据结构都将保存在内存中,直到关闭shelf对象时才写入磁盘;NEWLINE# 如果处理的数据量不多,建议将参数writeback设置为True;NEWLINE# 操作完成后,可以调用shelf对象的close()方法关闭;NEWLINE#NEWLINE# ### 特别注意NEWLINE# 修改使用模块shelve存储的对象,必须将获取的副本赋值给一个临时变量,并在这个副本后再次存储;NEWLINE """NEWLINE Copyright (c) 2019-2020 Intel CorporationNEWLINE Licensed under the Apache License, Version 2.0 (the "License");NEWLINE you may not use this file except in compliance with the License.NEWLINE You may obtain a copy of the License atNEWLINE http://www.apache.org/licenses/LICENSE-2.0NEWLINE Unless required by applicable law or agreed to in writing, softwareNEWLINE distributed under the License is distributed on an "AS IS" BASIS,NEWLINE WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE See the License for the specific language governing permissions andNEWLINE limitations under the License.NEWLINE"""NEWLINEimport itertoolsNEWLINEfrom collections import CounterNEWLINEfrom pathlib import PathNEWLINEfrom typing import ListNEWLINENEWLINEimport networkx as nxNEWLINEimport pytestNEWLINEimport torchNEWLINEfrom copy import deepcopyNEWLINEfrom torch import nnNEWLINENEWLINEfrom nncf import register_moduleNEWLINEfrom nncf.dynamic_graph.context import ScopeNEWLINEfrom nncf.dynamic_graph.graph import InputAgnosticOperationExecutionContext, NNCFGraph, OperationExecutionContextNEWLINEfrom nncf.dynamic_graph.graph_builder import ModelInputInfoNEWLINEfrom nncf.dynamic_graph.operator_metatypes import NoopMetatypeNEWLINEfrom nncf.dynamic_graph.patch_pytorch import MODEL_INPUT_OP_NAMENEWLINEfrom nncf.dynamic_graph.version_agnostic_op_names import VersionAgnosticNamesNEWLINEfrom nncf.layer_utils import _NNCFModuleMixinNEWLINEfrom nncf.module_operations import BaseOpNEWLINEfrom nncf.nncf_network import NNCFNetwork, InsertionCommand, InsertionPoint, InsertionType, OperationPriority, \NEWLINE InsertionPointGraph, InsertionPointGraphNodeTypeNEWLINEfrom tests.conftest import TEST_ROOTNEWLINEfrom tests.helpers import TwoConvTestModel, BasicConvTestModel, check_correct_nncf_modules_replacementNEWLINENEWLINENEWLINEdef test_disable_shape_matching():NEWLINE class MatMulModel(nn.Module):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINE self.dummy_param = torch.nn.Parameter(torch.ones([1]))NEWLINENEWLINE def forward(self, inputs):NEWLINE half1, half2 = torch.chunk(inputs, 2, dim=2)NEWLINE return torch.bmm(half1, half2.transpose(1, 2))NEWLINENEWLINE model = MatMulModel()NEWLINENEWLINE input_shape_1 = (3, 32, 32)NEWLINE input_shape_2 = (4, 64, 64)NEWLINENEWLINE qnet_no_shape = NNCFNetwork(deepcopy(model), input_infos=[ModelInputInfo(input_shape_1), ],NEWLINE scopes_without_shape_matching=['MatMulModel']) # type: NNCFNetworkNEWLINE _ = qnet_no_shape(torch.zeros(*input_shape_1))NEWLINE graph_1 = deepcopy(qnet_no_shape.get_graph())NEWLINENEWLINE _ = qnet_no_shape(torch.zeros(*input_shape_2))NEWLINE graph_2 = deepcopy(qnet_no_shape.get_graph())NEWLINENEWLINE keys_1 = list(graph_1.get_all_node_keys())NEWLINE keys_2 = list(graph_2.get_all_node_keys())NEWLINE assert len(keys_1) == 2 # 1 input node + 1 operation nodeNEWLINE assert keys_1 == keys_2NEWLINENEWLINENEWLINE qnet = NNCFNetwork(model, input_infos=[ModelInputInfo(input_shape_1), ]) # type: NNCFNetworkNEWLINE _ = qnet(torch.zeros(*input_shape_1))NEWLINE _ = qnet(torch.zeros(*input_shape_2))NEWLINE # The second forward run should have led to an increase in registered node countsNEWLINE # since disable_shape_matching was False and the network was run with a differentNEWLINE # shape of input tensorNEWLINE assert qnet.get_graph().get_nodes_count() > graph_1.get_nodes_count()NEWLINENEWLINENEWLINEdef test_check_correct_modules_replacement():NEWLINE model = TwoConvTestModel()NEWLINE nncf_model = NNCFNetwork(TwoConvTestModel(), input_infos=[ModelInputInfo([1, 1, 4, 4])]) # type: NNCFNetworkNEWLINENEWLINE _, nncf_modules = check_correct_nncf_modules_replacement(model, nncf_model)NEWLINE assert set(nncf_modules) == set(nncf_model.get_nncf_modules())NEWLINENEWLINENEWLINE@register_moduleNEWLINEclass ModuleOfUser(torch.nn.Module):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINE self.weight = torch.nn.Parameter(torch.ones([1]))NEWLINENEWLINE def forward(self, input_):NEWLINE return input_ * self.weightNEWLINENEWLINENEWLINEclass TwoConvTestModelWithUserModule(TwoConvTestModel):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINE self.user_module = ModuleOfUser()NEWLINENEWLINE def forward(self, x):NEWLINE x = super().forward(x)NEWLINE x = self.user_module(x)NEWLINE return xNEWLINENEWLINENEWLINEdef test_custom_module_registering():NEWLINE model = TwoConvTestModelWithUserModule()NEWLINE nncf_model = NNCFNetwork(model, input_infos=[ModelInputInfo([1, 1, 4, 4])]) # type: NNCFNetworkNEWLINENEWLINE from nncf.layers import UNWRAPPED_USER_MODULESNEWLINE assert ModuleOfUser in UNWRAPPED_USER_MODULES.registry_dict.values()NEWLINENEWLINE # pylint: disable=protected-accessNEWLINE assert isinstance(nncf_model.user_module, ModuleOfUser)NEWLINE assert isinstance(nncf_model.user_module, _NNCFModuleMixin)NEWLINE assert type(nncf_model.user_module).__name__ == "NNCFUserModuleOfUser"NEWLINENEWLINE user_module_attrs = dir(nncf_model.user_module)NEWLINE for attr in dir(_NNCFModuleMixin):NEWLINE assert attr in user_module_attrsNEWLINENEWLINENEWLINE# pylint: disable=protected-accessNEWLINEdef test_find_node_in_nx_graph_by_scope():NEWLINE model = TwoConvTestModel()NEWLINE nncf_model = NNCFNetwork(deepcopy(model), input_infos=[ModelInputInfo([1, 1, 4, 4])]) # type: NNCFNetworkNEWLINE nncf_graph = nncf_model.get_original_graph()NEWLINENEWLINE # Valid scopes should be successfully foundNEWLINE valid_nncf_modules = nncf_model.get_nncf_modules()NEWLINE nodes_list = list(nncf_graph._nx_graph.nodes)NEWLINE for module_scope, _ in valid_nncf_modules.items():NEWLINE graph_node = nncf_graph.find_node_in_nx_graph_by_scope(module_scope)NEWLINE assert graph_node is not NoneNEWLINE assert isinstance(graph_node, dict)NEWLINE assert graph_node['key'] in nodes_listNEWLINENEWLINE fake_model = BasicConvTestModel()NEWLINE fake_nncf_model = NNCFNetwork(deepcopy(fake_model), input_infos=[ModelInputInfo([1, 1, 4, 4])])NEWLINENEWLINE # Not valid scopes shouldn't be foundNEWLINE fake_nncf_modules = fake_nncf_model.get_nncf_modules()NEWLINE for module_scope, _ in fake_nncf_modules.items():NEWLINE graph_node = nncf_graph.find_node_in_nx_graph_by_scope(module_scope)NEWLINE assert graph_node is NoneNEWLINENEWLINENEWLINEclass InsertionPointTestModel(nn.Module):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINE self.conv1 = nn.Conv2d(1, 1, 1, 1)NEWLINE self.linear_wts = nn.Parameter(torch.FloatTensor(size=(100, 100)))NEWLINE self.conv2 = nn.Conv2d(1, 1, 1, 1)NEWLINE self.relu = nn.ReLU()NEWLINENEWLINE def forward(self, input_):NEWLINE x = self.conv1(input_)NEWLINE x = x.flatten()NEWLINE x = nn.functional.linear(x, self.linear_wts)NEWLINE x = x.reshape((1, 1, 10, 10))NEWLINE x = self.conv2(x)NEWLINE x = self.relu(x)NEWLINE return xNEWLINENEWLINENEWLINEclass TestInsertionCommands:NEWLINE @pytest.fixture()NEWLINE def setup(self):NEWLINE self.compressed_model = NNCFNetwork(InsertionPointTestModel(),NEWLINE [ModelInputInfo([1, 1, 10, 10])]) # type: NNCFNetworkNEWLINENEWLINE conv1_module_scope = Scope.from_str('InsertionPointTestModel/NNCFConv2d[conv1]')NEWLINE conv1_module_context = InputAgnosticOperationExecutionContext('', conv1_module_scope, 0)NEWLINE point_for_conv1_weights = InsertionPoint(ia_op_exec_context=conv1_module_context,NEWLINE insertion_type=InsertionType.NNCF_MODULE_PRE_OP)NEWLINE point_for_conv1_inputs = InsertionPoint(ia_op_exec_context=conv1_module_context,NEWLINE insertion_type=InsertionType.NNCF_MODULE_PRE_OP)NEWLINE point_for_conv1_activations = InsertionPoint(ia_op_exec_context=conv1_module_context,NEWLINE insertion_type=InsertionType.NNCF_MODULE_POST_OP)NEWLINENEWLINE conv2_module_scope = Scope.from_str('InsertionPointTestModel/NNCFConv2d[conv2]')NEWLINE conv2_module_context = InputAgnosticOperationExecutionContext('', conv2_module_scope, 0)NEWLINE point_for_conv2_weights = InsertionPoint(ia_op_exec_context=conv2_module_context,NEWLINE insertion_type=InsertionType.NNCF_MODULE_PRE_OP)NEWLINE point_for_conv2_inputs = InsertionPoint(ia_op_exec_context=conv2_module_context,NEWLINE insertion_type=InsertionType.NNCF_MODULE_PRE_OP)NEWLINE point_for_conv2_activations = InsertionPoint(ia_op_exec_context=conv2_module_context,NEWLINE insertion_type=InsertionType.NNCF_MODULE_POST_OP)NEWLINENEWLINE linear_op_scope = Scope.from_str('InsertionPointTestModel/linear_0')NEWLINE linear_op_context = InputAgnosticOperationExecutionContext('linear',NEWLINE linear_op_scope,NEWLINE 0)NEWLINE point_for_linear_weight_input = InsertionPoint(ia_op_exec_context=linear_op_context,NEWLINE insertion_type=InsertionType.OPERATOR_PRE_HOOK)NEWLINE point_for_linear_activation = InsertionPoint(ia_op_exec_context=linear_op_context,NEWLINE insertion_type=InsertionType.OPERATOR_POST_HOOK)NEWLINENEWLINE relu_op_scope = Scope.from_str('InsertionPointTestModel/ReLU[relu]/relu')NEWLINE relu_op_context = InputAgnosticOperationExecutionContext('relu',NEWLINE relu_op_scope,NEWLINE 0)NEWLINE point_for_relu_inputs = InsertionPoint(ia_op_exec_context=relu_op_context,NEWLINE insertion_type=InsertionType.OPERATOR_PRE_HOOK)NEWLINE point_for_relu_activations = InsertionPoint(ia_op_exec_context=relu_op_context,NEWLINE insertion_type=InsertionType.OPERATOR_POST_HOOK)NEWLINENEWLINE available_points = [point_for_conv1_weights,NEWLINE point_for_conv2_weights,NEWLINE point_for_conv1_inputs,NEWLINE point_for_conv2_inputs,NEWLINE point_for_conv1_activations,NEWLINE point_for_conv2_activations,NEWLINE point_for_linear_activation,NEWLINE point_for_linear_weight_input,NEWLINE point_for_relu_activations,NEWLINE point_for_relu_inputs]NEWLINENEWLINE @pytest.mark.parametrize("insertion_point", available_points)NEWLINE def test_single_insertions(self, setup, insertion_point):NEWLINE if insertion_point.insertion_type in [InsertionType.OPERATOR_PRE_HOOK, InsertionType.OPERATOR_POST_HOOK]:NEWLINE hook = lambda x: xNEWLINE else:NEWLINE hook = BaseOp(lambda x: x)NEWLINENEWLINE command = InsertionCommand(insertion_point, hook)NEWLINE self.compressed_model.register_insertion_command(command)NEWLINE self.compressed_model.commit_compression_changes()NEWLINENEWLINE #pylint:disable=protected-accessNEWLINE if insertion_point.insertion_type == InsertionType.OPERATOR_PRE_HOOK:NEWLINE ctx = self.compressed_model.get_tracing_context()NEWLINE assert ctx._pre_hooks[command.insertion_point.ia_op_exec_context][0] is hookNEWLINE if insertion_point.insertion_type == InsertionType.OPERATOR_POST_HOOK:NEWLINE ctx = self.compressed_model.get_tracing_context()NEWLINE assert ctx._post_hooks[command.insertion_point.ia_op_exec_context][0] is hookNEWLINE if insertion_point.insertion_type == InsertionType.NNCF_MODULE_PRE_OP:NEWLINE module = self.compressed_model.get_module_by_scope(NEWLINE command.insertion_point.ia_op_exec_context.scope_in_model)NEWLINE assert module.pre_ops["0"] is hookNEWLINENEWLINE if insertion_point.insertion_type == InsertionType.NNCF_MODULE_POST_OP:NEWLINE module = self.compressed_model.get_module_by_scope(NEWLINE command.insertion_point.ia_op_exec_context.scope_in_model)NEWLINE assert module.post_ops["0"] is hookNEWLINENEWLINE priority_types = ["same", "different"]NEWLINE insertion_types = InsertionTypeNEWLINE priority_test_cases = list(itertools.product(priority_types, insertion_types))NEWLINENEWLINE @staticmethodNEWLINE def check_order(iterable1: List, iterable2: List, ordering: List):NEWLINE for idx, order in enumerate(ordering):NEWLINE assert iterable1[idx] is iterable2[order]NEWLINENEWLINE # pylint:disable=undefined-variableNEWLINE @pytest.mark.parametrize("case", priority_test_cases, ids=[x[1].name + '-' + x[0] for x in priority_test_cases])NEWLINE def test_priority(self, case, setup):NEWLINE #pylint:disable=too-many-branchesNEWLINE priority_type = case[0]NEWLINE insertion_type = case[1]NEWLINE if insertion_type in [InsertionType.NNCF_MODULE_PRE_OP, InsertionType.NNCF_MODULE_POST_OP]:NEWLINE hook1 = BaseOp(lambda x: x)NEWLINE hook2 = BaseOp(lambda x: 2 * x)NEWLINE hook3 = BaseOp(lambda x: 3 * x)NEWLINE else:NEWLINE hook1 = lambda x: xNEWLINE hook2 = lambda x: 2 * xNEWLINE hook3 = lambda x: 3 * xNEWLINENEWLINE if insertion_type == InsertionType.NNCF_MODULE_PRE_OP:NEWLINE point = self.point_for_conv2_weightsNEWLINE elif insertion_type == InsertionType.NNCF_MODULE_POST_OP:NEWLINE point = self.point_for_conv1_activationsNEWLINE elif insertion_type == InsertionType.OPERATOR_PRE_HOOK:NEWLINE point = self.point_for_linear_weight_inputNEWLINE elif insertion_type == InsertionType.OPERATOR_POST_HOOK:NEWLINE point = self.point_for_relu_activationsNEWLINENEWLINE if priority_type == "same":NEWLINE # Same-priority commands will be executed in registration orderNEWLINE command1 = InsertionCommand(point, hook1, OperationPriority.DEFAULT_PRIORITY)NEWLINE command2 = InsertionCommand(point, hook2, OperationPriority.DEFAULT_PRIORITY)NEWLINE command3 = InsertionCommand(point, hook3, OperationPriority.DEFAULT_PRIORITY)NEWLINE else:NEWLINE # Prioritized commands will be executed in ascending priority orderNEWLINE command1 = InsertionCommand(point, hook1, OperationPriority.SPARSIFICATION_PRIORITY)NEWLINE command2 = InsertionCommand(point, hook2, OperationPriority.QUANTIZATION_PRIORITY)NEWLINE command3 = InsertionCommand(point, hook3, OperationPriority.DEFAULT_PRIORITY)NEWLINENEWLINE self.compressed_model.register_insertion_command(command1)NEWLINE self.compressed_model.register_insertion_command(command2)NEWLINE self.compressed_model.register_insertion_command(command3)NEWLINE self.compressed_model.commit_compression_changes()NEWLINENEWLINE hook_list = [hook1, hook2, hook3]NEWLINENEWLINE if priority_type == "same":NEWLINE order = [0, 1, 2]NEWLINE elif priority_type == "different":NEWLINE order = [2, 0, 1]NEWLINENEWLINE #pylint:disable=protected-accessNEWLINE if insertion_type == InsertionType.OPERATOR_PRE_HOOK:NEWLINE ctx = self.compressed_model.get_tracing_context()NEWLINE self.check_order(ctx._pre_hooks[point.ia_op_exec_context], hook_list, order)NEWLINE if insertion_type == InsertionType.OPERATOR_POST_HOOK:NEWLINE ctx = self.compressed_model.get_tracing_context()NEWLINE self.check_order(ctx._post_hooks[point.ia_op_exec_context], hook_list, order)NEWLINENEWLINE if insertion_type == InsertionType.NNCF_MODULE_PRE_OP:NEWLINE module = self.compressed_model.get_module_by_scope(point.ia_op_exec_context.scope_in_model)NEWLINE # Works because Pytorch ModuleDict is orderedNEWLINE self.check_order(list(module.pre_ops.values()), hook_list, order)NEWLINENEWLINE if insertion_type == InsertionType.NNCF_MODULE_POST_OP:NEWLINE module = self.compressed_model.get_module_by_scope(point.ia_op_exec_context.scope_in_model)NEWLINE # Works because Pytorch ModuleDict is orderedNEWLINE self.check_order(list(module.post_ops.values()), hook_list, order)NEWLINENEWLINENEWLINEdef get_two_branch_mock_model_graph() -> nx.DiGraph:NEWLINE mock_node_attrs = get_mock_nncf_node_attrs()NEWLINE mock_graph = nx.DiGraph()NEWLINENEWLINE # (A)NEWLINE # |NEWLINE # (B)NEWLINE # / \NEWLINE # (C) (D)NEWLINE # | |NEWLINE # (E) |NEWLINE # \ /NEWLINE # (F)NEWLINE # |NEWLINE # (G)NEWLINE # |NEWLINE # (H)NEWLINENEWLINE node_keys = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']NEWLINE for node_key in node_keys:NEWLINE mock_graph.add_node(node_key, **mock_node_attrs)NEWLINENEWLINE mock_graph.add_edges_from([('A', 'B'), ('B', 'C'), ('B', 'D'), ('C', 'E'), ('E', 'F'),NEWLINE ('D', 'F'), ('F', 'G'), ('G', 'H')])NEWLINE return mock_graphNEWLINENEWLINENEWLINEMOCK_OPERATOR_NAME = "conv_transpose2d"NEWLINENEWLINENEWLINEdef get_mock_nncf_node_attrs(op_name=None):NEWLINE op_name_to_set = op_name if op_name is not None else MOCK_OPERATOR_NAMENEWLINE return {NEWLINE NNCFGraph.OP_EXEC_CONTEXT_NODE_ATTR: OperationExecutionContext(op_name_to_set,NEWLINE Scope(),NEWLINE 0,NEWLINE [None])NEWLINE }NEWLINENEWLINENEWLINEdef get_mock_model_graph_with_mergeable_pattern() -> nx.DiGraph:NEWLINE mock_graph = nx.DiGraph()NEWLINENEWLINE # (A)NEWLINE # |NEWLINE # (conv2d)NEWLINE # |NEWLINE # (batch_norm)NEWLINE # |NEWLINE # (RELU)NEWLINE # |NEWLINE # (B)NEWLINENEWLINE node_keys = ['conv2d', 'batch_norm', VersionAgnosticNames.RELU, 'A', 'B']NEWLINE for node_key in node_keys:NEWLINE mock_graph.add_node(node_key, **get_mock_nncf_node_attrs(op_name=node_key))NEWLINENEWLINE mock_graph.add_edges_from([('A', 'conv2d'), ('conv2d', 'batch_norm'),NEWLINE ('batch_norm', VersionAgnosticNames.RELU),NEWLINE (VersionAgnosticNames.RELU, 'B')])NEWLINE return mock_graphNEWLINENEWLINENEWLINEdef get_mock_model_graph_with_no_mergeable_pattern() -> nx.DiGraph:NEWLINE mock_graph = nx.DiGraph()NEWLINENEWLINE # (A)NEWLINE # |NEWLINE # (conv2d)NEWLINE # |NEWLINE # (C)NEWLINE # |NEWLINE # (batch_norm)NEWLINE # |NEWLINE # (D)NEWLINE # |NEWLINE # (RELU)NEWLINE # |NEWLINE # (B)NEWLINENEWLINE node_keys = ['conv2d', 'batch_norm', VersionAgnosticNames.RELU, 'A', 'B', 'C', 'D']NEWLINE for node_key in node_keys:NEWLINE mock_graph.add_node(node_key, **get_mock_nncf_node_attrs(op_name=node_key))NEWLINENEWLINE mock_graph.add_edges_from([('A', 'conv2d'), ('conv2d', 'C'),NEWLINE ('C', 'batch_norm'),NEWLINE ('batch_norm', 'D'),NEWLINE ('D', VersionAgnosticNames.RELU),NEWLINE (VersionAgnosticNames.RELU, 'B')])NEWLINE return mock_graphNEWLINENEWLINENEWLINEdef get_mock_model_graph_with_broken_output_edge_pattern() -> nx.DiGraph:NEWLINE mock_graph = nx.DiGraph()NEWLINENEWLINE # (A)NEWLINE # |NEWLINE # (conv2d)----\NEWLINE # | |NEWLINE # (batch_norm) |NEWLINE # | |NEWLINE # (RELU) |NEWLINE # | |NEWLINE # (C)--------/NEWLINE # |NEWLINE # (B)NEWLINENEWLINE node_keys = ['conv2d', 'batch_norm', VersionAgnosticNames.RELU, 'A', 'B', 'C']NEWLINE for node_key in node_keys:NEWLINE mock_graph.add_node(node_key, **get_mock_nncf_node_attrs(op_name=node_key))NEWLINENEWLINE mock_graph.add_edges_from([('A', 'conv2d'), ('conv2d', 'batch_norm'),NEWLINE ('conv2d', 'C'),NEWLINE ('batch_norm', VersionAgnosticNames.RELU),NEWLINE (VersionAgnosticNames.RELU, 'C'),NEWLINE ('C', 'B')])NEWLINE return mock_graphNEWLINENEWLINENEWLINEMERGE_PATTERN_TEST_CASES = (NEWLINE [get_mock_model_graph_with_mergeable_pattern, "basic_pattern"],NEWLINE [get_mock_model_graph_with_no_mergeable_pattern, "no_pattern"],NEWLINE [get_mock_model_graph_with_broken_output_edge_pattern, "broken_output_edges_pattern"]NEWLINE)NEWLINENEWLINENEWLINEclass TestInsertionPointGraph:NEWLINE def test_insertion_point_setup(self):NEWLINE # TODO: Change testing premises when module pre/post-op hooks and input/output nodesNEWLINE # are correctly handledNEWLINE mock_graph = get_two_branch_mock_model_graph()NEWLINENEWLINE ip_graph = InsertionPointGraph(mock_graph)NEWLINENEWLINE ref_node_len = 3 * len(mock_graph.nodes) # 2 additional nodes per each operator nodeNEWLINE ref_edge_len = 3 * len(mock_graph.edges)NEWLINENEWLINE assert len(ip_graph.nodes) == ref_node_lenNEWLINE assert len(ip_graph.edges) == ref_edge_lenNEWLINENEWLINE for node_key, node in mock_graph.nodes.items():NEWLINE ip_graph_op_node = ip_graph.nodes[node_key]NEWLINE assert ip_graph_op_node[InsertionPointGraph.NODE_TYPE_NODE_ATTR] == InsertionPointGraphNodeType.OPERATORNEWLINE preds = list(ip_graph.predecessors(node_key))NEWLINE succs = list(ip_graph.successors(node_key))NEWLINE assert len(preds) == 1NEWLINE assert len(succs) == 1NEWLINE pre_hook_ip_node_key = preds[0]NEWLINE post_hook_ip_node_key = succs[0]NEWLINE pre_hook_ip_node = ip_graph.nodes[preds[0]]NEWLINE post_hook_ip_node = ip_graph.nodes[succs[0]]NEWLINE pre_hook_ip_node_type = pre_hook_ip_node[InsertionPointGraph.NODE_TYPE_NODE_ATTR]NEWLINE post_hook_ip_node_type = post_hook_ip_node[InsertionPointGraph.NODE_TYPE_NODE_ATTR]NEWLINE assert pre_hook_ip_node_type == InsertionPointGraphNodeType.INSERTION_POINTNEWLINE assert post_hook_ip_node_type == InsertionPointGraphNodeType.INSERTION_POINTNEWLINE ref_associated_ip_node_keys_set = {pre_hook_ip_node_key, post_hook_ip_node_key}NEWLINE assert ref_associated_ip_node_keys_set == ip_graph_op_node[NEWLINE InsertionPointGraph.ASSOCIATED_IP_NODE_KEYS_NODE_ATTR]NEWLINE original_neighbours = mock_graph.neighbors(node_key)NEWLINE for neighbour in original_neighbours:NEWLINE # IP node insertion should not disrupt the graph superstructureNEWLINE ip_graph_paths = list(nx.all_simple_paths(ip_graph, node_key, neighbour))NEWLINE for path in ip_graph_paths:NEWLINE path = path[1:-1]NEWLINE for path_node_key in path:NEWLINE node = ip_graph.nodes[path_node_key]NEWLINE node_type = node[InsertionPointGraph.NODE_TYPE_NODE_ATTR]NEWLINE assert node_type == InsertionPointGraphNodeType.INSERTION_POINTNEWLINENEWLINE for node_key, node in ip_graph.nodes.items():NEWLINE preds = list(ip_graph.predecessors(node_key))NEWLINE succs = list(ip_graph.successors(node_key))NEWLINE assert len(preds) != 0 or len(succs) != 0NEWLINENEWLINE for from_node_key, to_node_key in ip_graph.edges.keys():NEWLINE assert from_node_key in ip_graph.nodesNEWLINE assert to_node_key in ip_graph.nodesNEWLINENEWLINE def test_insertion_point_data_in_ip_nodes(self):NEWLINE # TODO: extend for modulesNEWLINE mock_graph = nx.DiGraph()NEWLINE ref_op_exec_context = OperationExecutionContext("baz",NEWLINE Scope.from_str("Test/Scope[foo]/bar"),NEWLINE 0,NEWLINE [None])NEWLINE node_attrs = {NEWLINE NNCFGraph.OP_EXEC_CONTEXT_NODE_ATTR: ref_op_exec_contextNEWLINE }NEWLINENEWLINE node_key = 0NEWLINE mock_graph.add_node(node_key, **node_attrs)NEWLINENEWLINE ip_graph = InsertionPointGraph(mock_graph)NEWLINENEWLINE for node_key in mock_graph.nodes.keys():NEWLINE preds = list(ip_graph.predecessors(node_key))NEWLINE succs = list(ip_graph.successors(node_key))NEWLINE pre_hook_ip_node = ip_graph.nodes[preds[0]]NEWLINE post_hook_ip_node = ip_graph.nodes[succs[0]]NEWLINENEWLINE pre_hook_ip = pre_hook_ip_node[InsertionPointGraph.INSERTION_POINT_DATA_NODE_ATTR]NEWLINE post_hook_ip = post_hook_ip_node[InsertionPointGraph.INSERTION_POINT_DATA_NODE_ATTR]NEWLINE assert pre_hook_ip.insertion_type == InsertionType.OPERATOR_PRE_HOOKNEWLINE assert post_hook_ip.insertion_type == InsertionType.OPERATOR_POST_HOOKNEWLINENEWLINE assert pre_hook_ip.ia_op_exec_context == ref_op_exec_context.input_agnosticNEWLINE assert post_hook_ip.ia_op_exec_context == ref_op_exec_context.input_agnosticNEWLINENEWLINE def test_operator_metatype_marking(self):NEWLINE from nncf.dynamic_graph.operator_metatypes import Conv2dMetatype, BatchNormMetatype, RELUMetatype, \NEWLINE MaxPool2dMetatype, \NEWLINE ConvTranspose2dMetatype, DepthwiseConv2dSubtype, AddMetatype, AvgPool2dMetatype, LinearMetatypeNEWLINE ref_scope_vs_metatype_dict = {NEWLINE "/" + MODEL_INPUT_OP_NAME + "_0": NoopMetatype,NEWLINE "ModelForMetatypeTesting/NNCFConv2d[conv_regular]/conv2d_0": Conv2dMetatype,NEWLINE "ModelForMetatypeTesting/BatchNorm2d[bn]/batch_norm_0": BatchNormMetatype,NEWLINE "ModelForMetatypeTesting/RELU_0": RELUMetatype,NEWLINE "ModelForMetatypeTesting/MaxPool2d[max_pool2d]/max_pool2d_0": MaxPool2dMetatype,NEWLINE "ModelForMetatypeTesting/NNCFConvTranspose2d[conv_transpose]/conv_transpose2d_0": ConvTranspose2dMetatype,NEWLINE "ModelForMetatypeTesting/NNCFConv2d[conv_depthwise]/conv2d_0": DepthwiseConv2dSubtype,NEWLINE "ModelForMetatypeTesting/__iadd___0": AddMetatype,NEWLINE "ModelForMetatypeTesting/AdaptiveAvgPool2d[adaptive_avg_pool]/adaptive_avg_pool2d_0": AvgPool2dMetatype,NEWLINE "ModelForMetatypeTesting/NNCFLinear[linear]/linear_0": LinearMetatypeNEWLINE }NEWLINE class ModelForMetatypeTesting(torch.nn.Module):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINE self.conv_regular = torch.nn.Conv2d(in_channels=3,NEWLINE out_channels=16,NEWLINE kernel_size=3)NEWLINE self.bn = torch.nn.BatchNorm2d(num_features=16)NEWLINE self.max_pool2d = torch.nn.MaxPool2d(kernel_size=2)NEWLINE self.conv_transpose = torch.nn.ConvTranspose2d(in_channels=16,NEWLINE out_channels=8,NEWLINE kernel_size=3)NEWLINE self.conv_depthwise = torch.nn.Conv2d(in_channels=8, out_channels=8,NEWLINE kernel_size=5, groups=8)NEWLINE self.adaptive_avg_pool = torch.nn.AdaptiveAvgPool2d(output_size=1)NEWLINE self.linear = torch.nn.Linear(in_features=8, out_features=1)NEWLINENEWLINE def forward(self, input_):NEWLINE x = self.conv_regular(input_)NEWLINE x = self.bn(x)NEWLINE x = torch.nn.functional.relu(x)NEWLINE x.transpose_(2, 3)NEWLINE x = self.max_pool2d(x)NEWLINE x = self.conv_transpose(x)NEWLINE x = self.conv_depthwise(x)NEWLINE x += torch.ones_like(x)NEWLINE x = self.adaptive_avg_pool(x)NEWLINE x = self.linear(x.flatten())NEWLINE return xNEWLINENEWLINE model = ModelForMetatypeTesting()NEWLINE nncf_network = NNCFNetwork(model, [ModelInputInfo([1, 3, 300, 300])])NEWLINE ip_graph = nncf_network.get_insertion_point_graph()NEWLINENEWLINE for node in ip_graph.nodes().values():NEWLINE if node[InsertionPointGraph.NODE_TYPE_NODE_ATTR] == InsertionPointGraphNodeType.OPERATOR:NEWLINE nncf_node_ref = node[InsertionPointGraph.REGULAR_NODE_REF_NODE_ATTR]NEWLINE scope_str = str(nncf_node_ref[NNCFGraph.OP_EXEC_CONTEXT_NODE_ATTR].input_agnostic)NEWLINE assert scope_str in ref_scope_vs_metatype_dictNEWLINE ref_metatype = ref_scope_vs_metatype_dict[scope_str]NEWLINE assert node[InsertionPointGraph.OPERATOR_METATYPE_NODE_ATTR] == ref_metatypeNEWLINENEWLINE @pytest.mark.parametrize(("mock_graph_factory", "dot_file_name"),NEWLINE MERGE_PATTERN_TEST_CASES,NEWLINE ids=[x[1] for x in MERGE_PATTERN_TEST_CASES])NEWLINE def test_get_ip_graph_with_merged_operations(self, mock_graph_factory, dot_file_name):NEWLINE mock_graph = mock_graph_factory()NEWLINE ip_graph = InsertionPointGraph(mock_graph)NEWLINE merged_ip_graph = ip_graph.get_ip_graph_with_merged_hw_optimized_operations()NEWLINENEWLINE data_dir = TEST_ROOT / 'data/reference_graphs/pattern_merging' # type: PathNEWLINENEWLINE path_to_dot_file = data_dir / '{}.dot'.format(dot_file_name)NEWLINENEWLINE # validate .dot file manually!NEWLINE if not path_to_dot_file.exists():NEWLINE if not data_dir.exists():NEWLINE data_dir.mkdir(parents=True)NEWLINE nx.drawing.nx_pydot.write_dot(merged_ip_graph, str(path_to_dot_file))NEWLINENEWLINE load_graph = nx.drawing.nx_pydot.read_dot(str(path_to_dot_file))NEWLINENEWLINE for key in load_graph.nodes.keys():NEWLINE key.replace(r'\\n', r'\n') # Somehow pydot mangles the \n characters while writing a .dot fileNEWLINENEWLINE sanitized_loaded_keys = [key.replace('\\n', '\n') for key in load_graph.nodes.keys()]NEWLINE sanitized_loaded_edges = [(u.replace('\\n', '\n'),NEWLINE v.replace('\\n', '\n')) for u, v in nx.DiGraph(load_graph).edges]NEWLINENEWLINE assert Counter(sanitized_loaded_keys) == Counter(list(merged_ip_graph.nodes.keys()))NEWLINE assert Counter(sanitized_loaded_edges) == Counter(list(merged_ip_graph.edges))NEWLINE import os.pathNEWLINENEWLINEimport torchNEWLINEimport seaborn as snsNEWLINEfrom pandas import DataFrameNEWLINEfrom torch.utils.data import DataLoaderNEWLINEfrom transformers import RobertaTokenizerNEWLINENEWLINEfrom bond.data import DatasetName, DatasetType, SubTokenDataset, load_dataset, load_tags_dictNEWLINEfrom bond.utils import ner_scoresNEWLINENEWLINENEWLINEdef plot_distant_dataset_stats(dataset_name: DatasetName) -> None:NEWLINE tokenizer = RobertaTokenizer.from_pretrained('roberta-base') # for loading datasets - doesn't really matter what tokenizer to useNEWLINENEWLINE distant_dataset = load_dataset(dataset_name, DatasetType.DISTANT, tokenizer, 'roberta-base', 128)NEWLINE gold_dataset = load_dataset(dataset_name, DatasetType.TRAIN, tokenizer, 'roberta-base', 128)NEWLINENEWLINE distant_labels = []NEWLINE for _, labels, mask, _ in DataLoader(distant_dataset, batch_size=1):NEWLINE distant_labels.extend(labels.masked_select(mask > 0).tolist())NEWLINENEWLINE gold_labels = []NEWLINE for _, labels, mask, _ in DataLoader(gold_dataset, batch_size=1):NEWLINE gold_labels.extend(labels.masked_select(mask > 0).tolist())NEWLINENEWLINE stats = ner_scores(gold_labels, distant_labels, load_tags_dict(dataset_name))NEWLINE print(stats) # TODO: do actual stats visuallizationNEWLINENEWLINENEWLINEdef score_cached_dataset(dataset_path: str) -> None:NEWLINE cached_name = os.path.basename(dataset_path)NEWLINE info = cached_name.split('_')NEWLINE tokenizer = RobertaTokenizer.from_pretrained(info[-2])NEWLINE dataset_name = DatasetName(info[0])NEWLINE max_seq_len = int(info[-1][3:])NEWLINENEWLINE distant_dataset: SubTokenDataset = torch.load(dataset_path)NEWLINE gold_dataset = load_dataset(dataset_name, DatasetType.TRAIN, tokenizer, 'roberta-base', max_seq_len)NEWLINENEWLINE distant_labels = []NEWLINE for _, _, _, labels, mask, _, _ in DataLoader(distant_dataset, batch_size=1, collate_fn=distant_dataset.collate_fn):NEWLINE distant_labels.extend(labels.masked_select(mask).tolist())NEWLINENEWLINE gold_labels = []NEWLINE for _, _, _, labels, mask, _, _ in DataLoader(gold_dataset, batch_size=1, collate_fn=gold_dataset.collate_fn):NEWLINE gold_labels.extend(labels.masked_select(mask).tolist())NEWLINENEWLINE assert len(gold_labels) == len(distant_labels)NEWLINE stats = ner_scores(gold_labels, distant_labels, load_tags_dict(dataset_name))NEWLINE print(stats)NEWLINE from game.combat.effects.moveeffect.basemoveeffect import BaseMoveEffectNEWLINEfrom game.combat.effects.partialeffect.applystatuseffect import ApplyStatusNEWLINEfrom game.combat.effects import statuseffectNEWLINENEWLINENEWLINEclass Confusion(BaseMoveEffect):NEWLINE def after_action(self):NEWLINE if self.scene.board.random_roll(self.move.chance):NEWLINE ApplyStatus(self.scene, statuseffect.CONFUSION, self.move.user, self.move.target).apply()NEWLINE return True, False, FalseNEWLINE """NEWLINEThe MIT License (MIT)NEWLINENEWLINECopyright (c) 2015-present RapptzNEWLINENEWLINEPermission is hereby granted, free of charge, to any person obtaining aNEWLINEcopy of this software and associated documentation files (the "Software"),NEWLINEto deal in the Software without restriction, including without limitationNEWLINEthe rights to use, copy, modify, merge, publish, distribute, sublicense,NEWLINEand/or sell copies of the Software, and to permit persons to whom theNEWLINESoftware is furnished to do so, subject to the following conditions:NEWLINENEWLINEThe above copyright notice and this permission notice shall be included inNEWLINEall copies or substantial portions of the Software.NEWLINENEWLINETHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESSNEWLINEOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,NEWLINEFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THENEWLINEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERNEWLINELIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISINGNEWLINEFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHERNEWLINEDEALINGS IN THE SOFTWARE.NEWLINE"""NEWLINENEWLINEfrom __future__ import annotationsNEWLINENEWLINEimport asyncioNEWLINEimport datetimeNEWLINEimport loggingNEWLINEimport sysNEWLINEimport tracebackNEWLINEfrom typing import (NEWLINE Any,NEWLINE AsyncIterator,NEWLINE Callable,NEWLINE Coroutine,NEWLINE Dict,NEWLINE Generator,NEWLINE List,NEWLINE Optional,NEWLINE Sequence,NEWLINE TYPE_CHECKING,NEWLINE Tuple,NEWLINE Type,NEWLINE TypeVar,NEWLINE Union,NEWLINE)NEWLINENEWLINEimport aiohttpNEWLINENEWLINEfrom .user import User, ClientUserNEWLINEfrom .invite import InviteNEWLINEfrom .template import TemplateNEWLINEfrom .widget import WidgetNEWLINEfrom .guild import GuildNEWLINEfrom .emoji import EmojiNEWLINEfrom .channel import _threaded_channel_factory, PartialMessageableNEWLINEfrom .enums import ChannelTypeNEWLINEfrom .mentions import AllowedMentionsNEWLINEfrom .errors import *NEWLINEfrom .enums import StatusNEWLINEfrom .flags import ApplicationFlags, IntentsNEWLINEfrom .gateway import *NEWLINEfrom .activity import ActivityTypes, BaseActivity, create_activityNEWLINEfrom .voice_client import VoiceClientNEWLINEfrom .http import HTTPClientNEWLINEfrom .state import ConnectionStateNEWLINEfrom . import utilsNEWLINEfrom .utils import MISSING, time_snowflakeNEWLINEfrom .object import ObjectNEWLINEfrom .backoff import ExponentialBackoffNEWLINEfrom .webhook import WebhookNEWLINEfrom .appinfo import AppInfoNEWLINEfrom .ui.view import ViewNEWLINEfrom .stage_instance import StageInstanceNEWLINEfrom .threads import ThreadNEWLINEfrom .sticker import GuildSticker, StandardSticker, StickerPack, _sticker_factoryNEWLINENEWLINEif TYPE_CHECKING:NEWLINE from typing_extensions import SelfNEWLINE from types import TracebackTypeNEWLINE from .types.guild import Guild as GuildPayloadNEWLINE from .abc import SnowflakeTime, Snowflake, PrivateChannelNEWLINE from .guild import GuildChannelNEWLINE from .channel import DMChannelNEWLINE from .message import MessageNEWLINE from .member import MemberNEWLINE from .voice_client import VoiceProtocolNEWLINENEWLINE# fmt: offNEWLINE__all__ = (NEWLINE 'Client',NEWLINE)NEWLINE# fmt: onNEWLINENEWLINECoro = TypeVar('Coro', bound=Callable[..., Coroutine[Any, Any, Any]])NEWLINENEWLINE_log = logging.getLogger(__name__)NEWLINENEWLINENEWLINEclass _LoopSentinel:NEWLINE __slots__ = ()NEWLINENEWLINE def __getattr__(self, attr: str) -> None:NEWLINE msg = (NEWLINE 'loop attribute cannot be accessed in non-async contexts. 'NEWLINE 'Consider using either an asynchronous main function and passing it to asyncio.run or 'NEWLINE 'using asynchronous initialisation hooks such as Client.setup_hook'NEWLINE )NEWLINE raise AttributeError(msg)NEWLINENEWLINENEWLINE_loop: Any = _LoopSentinel()NEWLINENEWLINENEWLINEclass Client:NEWLINE r"""Represents a client connection that connects to Discord.NEWLINE This class is used to interact with the Discord WebSocket and API.NEWLINENEWLINE A number of options can be passed to the :class:`Client`.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE max_messages: Optional[:class:`int`]NEWLINE The maximum number of messages to store in the internal message cache.NEWLINE This defaults to ``1000``. Passing in ``None`` disables the message cache.NEWLINENEWLINE .. versionchanged:: 1.3NEWLINE Allow disabling the message cache and change the default size to ``1000``.NEWLINE proxy: Optional[:class:`str`]NEWLINE Proxy URL.NEWLINE proxy_auth: Optional[:class:`aiohttp.BasicAuth`]NEWLINE An object that represents proxy HTTP Basic Authorization.NEWLINE shard_id: Optional[:class:`int`]NEWLINE Integer starting at ``0`` and less than :attr:`.shard_count`.NEWLINE shard_count: Optional[:class:`int`]NEWLINE The total number of shards.NEWLINE application_id: :class:`int`NEWLINE The client's application ID.NEWLINE intents: :class:`Intents`NEWLINE The intents that you want to enable for the session. This is a way ofNEWLINE disabling and enabling certain gateway events from triggering and being sent.NEWLINE If not given, defaults to a regularly constructed :class:`Intents` class.NEWLINENEWLINE .. versionadded:: 1.5NEWLINE member_cache_flags: :class:`MemberCacheFlags`NEWLINE Allows for finer control over how the library caches members.NEWLINE If not given, defaults to cache as much as possible with theNEWLINE currently selected intents.NEWLINENEWLINE .. versionadded:: 1.5NEWLINE chunk_guilds_at_startup: :class:`bool`NEWLINE Indicates if :func:`.on_ready` should be delayed to chunk all guildsNEWLINE at start-up if necessary. This operation is incredibly slow for largeNEWLINE amounts of guilds. The default is ``True`` if :attr:`Intents.members`NEWLINE is ``True``.NEWLINENEWLINE .. versionadded:: 1.5NEWLINE status: Optional[:class:`.Status`]NEWLINE A status to start your presence with upon logging on to Discord.NEWLINE activity: Optional[:class:`.BaseActivity`]NEWLINE An activity to start your presence with upon logging on to Discord.NEWLINE allowed_mentions: Optional[:class:`AllowedMentions`]NEWLINE Control how the client handles mentions by default on every message sent.NEWLINENEWLINE .. versionadded:: 1.4NEWLINE heartbeat_timeout: :class:`float`NEWLINE The maximum numbers of seconds before timing out and restarting theNEWLINE WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful ifNEWLINE processing the initial packets take too long to the point of disconnectingNEWLINE you. The default timeout is 60 seconds.NEWLINE guild_ready_timeout: :class:`float`NEWLINE The maximum number of seconds to wait for the GUILD_CREATE stream to end beforeNEWLINE preparing the member cache and firing READY. The default timeout is 2 seconds.NEWLINENEWLINE .. versionadded:: 1.4NEWLINE assume_unsync_clock: :class:`bool`NEWLINE Whether to assume the system clock is unsynced. This applies to the ratelimit handlingNEWLINE code. If this is set to ``True``, the default, then the library uses the time to resetNEWLINE a rate limit bucket given by Discord. If this is ``False`` then your system clock isNEWLINE used to calculate how long to sleep for. If this is set to ``False`` it is recommended toNEWLINE sync your system clock to Google's NTP server.NEWLINENEWLINE .. versionadded:: 1.3NEWLINE enable_debug_events: :class:`bool`NEWLINE Whether to enable events that are useful only for debugging gateway related information.NEWLINENEWLINE Right now this involves :func:`on_socket_raw_receive` and :func:`on_socket_raw_send`. IfNEWLINE this is ``False`` then those events will not be dispatched (due to performance considerations).NEWLINE To enable these events, this must be set to ``True``. Defaults to ``False``.NEWLINENEWLINE .. versionadded:: 2.0NEWLINE http_trace: :class:`aiohttp.TraceConfig`NEWLINE The trace configuration to use for tracking HTTP requests the library does using ``aiohttp``.NEWLINE This allows you to check requests the library is using. For more information, check theNEWLINE `aiohttp documentation `_.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE AttributesNEWLINE -----------NEWLINE wsNEWLINE The websocket gateway the client is currently connected to. Could be ``None``.NEWLINE """NEWLINENEWLINE def __init__(self, **options: Any) -> None:NEWLINE self.loop: asyncio.AbstractEventLoop = _loopNEWLINE # self.ws is set in the connect methodNEWLINE self.ws: DiscordWebSocket = None # type: ignoreNEWLINE self._listeners: Dict[str, List[Tuple[asyncio.Future, Callable[..., bool]]]] = {}NEWLINE self.shard_id: Optional[int] = options.get('shard_id')NEWLINE self.shard_count: Optional[int] = options.get('shard_count')NEWLINENEWLINE proxy: Optional[str] = options.pop('proxy', None)NEWLINE proxy_auth: Optional[aiohttp.BasicAuth] = options.pop('proxy_auth', None)NEWLINE unsync_clock: bool = options.pop('assume_unsync_clock', True)NEWLINE http_trace: Optional[aiohttp.TraceConfig] = options.pop('http_trace', None)NEWLINE self.http: HTTPClient = HTTPClient(NEWLINE self.loop,NEWLINE proxy=proxy,NEWLINE proxy_auth=proxy_auth,NEWLINE unsync_clock=unsync_clock,NEWLINE http_trace=http_trace,NEWLINE )NEWLINENEWLINE self._handlers: Dict[str, Callable[..., None]] = {NEWLINE 'ready': self._handle_ready,NEWLINE }NEWLINENEWLINE self._hooks: Dict[str, Callable[..., Coroutine[Any, Any, Any]]] = {NEWLINE 'before_identify': self._call_before_identify_hook,NEWLINE }NEWLINENEWLINE self._enable_debug_events: bool = options.pop('enable_debug_events', False)NEWLINE self._connection: ConnectionState = self._get_state(**options)NEWLINE self._connection.shard_count = self.shard_countNEWLINE self._closed: bool = FalseNEWLINE self._ready: asyncio.Event = MISSINGNEWLINE self._connection._get_websocket = self._get_websocketNEWLINE self._connection._get_client = lambda: selfNEWLINENEWLINE if VoiceClient.warn_nacl:NEWLINE VoiceClient.warn_nacl = FalseNEWLINE _log.warning("PyNaCl is not installed, voice will NOT be supported")NEWLINENEWLINE async def __aenter__(self) -> Self:NEWLINE await self._async_setup_hook()NEWLINE return selfNEWLINENEWLINE async def __aexit__(NEWLINE self,NEWLINE exc_type: Optional[Type[BaseException]],NEWLINE exc_value: Optional[BaseException],NEWLINE traceback: Optional[TracebackType],NEWLINE ) -> None:NEWLINE if not self.is_closed():NEWLINE await self.close()NEWLINENEWLINE # internalsNEWLINENEWLINE def _get_websocket(self, guild_id: Optional[int] = None, *, shard_id: Optional[int] = None) -> DiscordWebSocket:NEWLINE return self.wsNEWLINENEWLINE def _get_state(self, **options: Any) -> ConnectionState:NEWLINE return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, **options)NEWLINENEWLINE def _handle_ready(self) -> None:NEWLINE self._ready.set()NEWLINENEWLINE @propertyNEWLINE def latency(self) -> float:NEWLINE """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.NEWLINENEWLINE This could be referred to as the Discord WebSocket protocol latency.NEWLINE """NEWLINE ws = self.wsNEWLINE return float('nan') if not ws else ws.latencyNEWLINENEWLINE def is_ws_ratelimited(self) -> bool:NEWLINE """:class:`bool`: Whether the websocket is currently rate limited.NEWLINENEWLINE This can be useful to know when deciding whether you should query membersNEWLINE using HTTP or via the gateway.NEWLINENEWLINE .. versionadded:: 1.6NEWLINE """NEWLINE return FalseNEWLINENEWLINE @propertyNEWLINE def user(self) -> Optional[ClientUser]:NEWLINE """Optional[:class:`.ClientUser`]: Represents the connected client. ``None`` if not logged in."""NEWLINE return self._connection.userNEWLINENEWLINE @propertyNEWLINE def guilds(self) -> List[Guild]:NEWLINE """List[:class:`.Guild`]: The guilds that the connected client is a member of."""NEWLINE return self._connection.guildsNEWLINENEWLINE @propertyNEWLINE def emojis(self) -> List[Emoji]:NEWLINE """List[:class:`.Emoji`]: The emojis that the connected client has."""NEWLINE return self._connection.emojisNEWLINENEWLINE @propertyNEWLINE def stickers(self) -> List[GuildSticker]:NEWLINE """List[:class:`.GuildSticker`]: The stickers that the connected client has.NEWLINENEWLINE .. versionadded:: 2.0NEWLINE """NEWLINE return self._connection.stickersNEWLINENEWLINE @propertyNEWLINE def cached_messages(self) -> Sequence[Message]:NEWLINE """Sequence[:class:`.Message`]: Read-only list of messages the connected client has cached.NEWLINENEWLINE .. versionadded:: 1.1NEWLINE """NEWLINE return utils.SequenceProxy(self._connection._messages or [])NEWLINENEWLINE @propertyNEWLINE def private_channels(self) -> List[PrivateChannel]:NEWLINE """List[:class:`.abc.PrivateChannel`]: The private channels that the connected client is participating on.NEWLINENEWLINE .. note::NEWLINENEWLINE This returns only up to 128 most recent private channels due to an internal workingNEWLINE on how Discord deals with private channels.NEWLINE """NEWLINE return self._connection.private_channelsNEWLINENEWLINE @propertyNEWLINE def voice_clients(self) -> List[VoiceProtocol]:NEWLINE """List[:class:`.VoiceProtocol`]: Represents a list of voice connections.NEWLINENEWLINE These are usually :class:`.VoiceClient` instances.NEWLINE """NEWLINE return self._connection.voice_clientsNEWLINENEWLINE @propertyNEWLINE def application_id(self) -> Optional[int]:NEWLINE """Optional[:class:`int`]: The client's application ID.NEWLINENEWLINE If this is not passed via ``__init__`` then this is retrievedNEWLINE through the gateway when an event contains the data. UsuallyNEWLINE after :func:`~discord.on_connect` is called.NEWLINENEWLINE .. versionadded:: 2.0NEWLINE """NEWLINE return self._connection.application_idNEWLINENEWLINE @propertyNEWLINE def application_flags(self) -> ApplicationFlags:NEWLINE """:class:`~discord.ApplicationFlags`: The client's application flags.NEWLINENEWLINE .. versionadded:: 2.0NEWLINE """NEWLINE return self._connection.application_flagsNEWLINENEWLINE def is_ready(self) -> bool:NEWLINE """:class:`bool`: Specifies if the client's internal cache is ready for use."""NEWLINE return self._ready is not MISSING and self._ready.is_set()NEWLINENEWLINE async def _run_event(NEWLINE self,NEWLINE coro: Callable[..., Coroutine[Any, Any, Any]],NEWLINE event_name: str,NEWLINE *args: Any,NEWLINE **kwargs: Any,NEWLINE ) -> None:NEWLINE try:NEWLINE await coro(*args, **kwargs)NEWLINE except asyncio.CancelledError:NEWLINE passNEWLINE except Exception:NEWLINE try:NEWLINE await self.on_error(event_name, *args, **kwargs)NEWLINE except asyncio.CancelledError:NEWLINE passNEWLINENEWLINE def _schedule_event(NEWLINE self,NEWLINE coro: Callable[..., Coroutine[Any, Any, Any]],NEWLINE event_name: str,NEWLINE *args: Any,NEWLINE **kwargs: Any,NEWLINE ) -> asyncio.Task:NEWLINE wrapped = self._run_event(coro, event_name, *args, **kwargs)NEWLINE # Schedules the taskNEWLINE return self.loop.create_task(wrapped, name=f'discord.py: {event_name}')NEWLINENEWLINE def dispatch(self, event: str, *args: Any, **kwargs: Any) -> None:NEWLINE _log.debug('Dispatching event %s', event)NEWLINE method = 'on_' + eventNEWLINENEWLINE listeners = self._listeners.get(event)NEWLINE if listeners:NEWLINE removed = []NEWLINE for i, (future, condition) in enumerate(listeners):NEWLINE if future.cancelled():NEWLINE removed.append(i)NEWLINE continueNEWLINENEWLINE try:NEWLINE result = condition(*args)NEWLINE except Exception as exc:NEWLINE future.set_exception(exc)NEWLINE removed.append(i)NEWLINE else:NEWLINE if result:NEWLINE if len(args) == 0:NEWLINE future.set_result(None)NEWLINE elif len(args) == 1:NEWLINE future.set_result(args[0])NEWLINE else:NEWLINE future.set_result(args)NEWLINE removed.append(i)NEWLINENEWLINE if len(removed) == len(listeners):NEWLINE self._listeners.pop(event)NEWLINE else:NEWLINE for idx in reversed(removed):NEWLINE del listeners[idx]NEWLINENEWLINE try:NEWLINE coro = getattr(self, method)NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE self._schedule_event(coro, method, *args, **kwargs)NEWLINENEWLINE async def on_error(self, event_method: str, *args: Any, **kwargs: Any) -> None:NEWLINE """|coro|NEWLINENEWLINE The default error handler provided by the client.NEWLINENEWLINE By default this prints to :data:`sys.stderr` however it could beNEWLINE overridden to have a different implementation.NEWLINE Check :func:`~discord.on_error` for more details.NEWLINE """NEWLINE print(f'Ignoring exception in {event_method}', file=sys.stderr)NEWLINE traceback.print_exc()NEWLINENEWLINE # hooksNEWLINENEWLINE async def _call_before_identify_hook(self, shard_id: Optional[int], *, initial: bool = False) -> None:NEWLINE # This hook is an internal hook that actually calls the public one.NEWLINE # It allows the library to have its own hook without stepping on theNEWLINE # toes of those who need to override their own hook.NEWLINE await self.before_identify_hook(shard_id, initial=initial)NEWLINENEWLINE async def before_identify_hook(self, shard_id: Optional[int], *, initial: bool = False) -> None:NEWLINE """|coro|NEWLINENEWLINE A hook that is called before IDENTIFYing a session. This is usefulNEWLINE if you wish to have more control over the synchronization of multipleNEWLINE IDENTIFYing clients.NEWLINENEWLINE The default implementation does nothing.NEWLINENEWLINE .. versionadded:: 1.4NEWLINENEWLINE ParametersNEWLINE ------------NEWLINE shard_id: :class:`int`NEWLINE The shard ID that requested being IDENTIFY'dNEWLINE initial: :class:`bool`NEWLINE Whether this IDENTIFY is the first initial IDENTIFY.NEWLINE """NEWLINENEWLINE passNEWLINENEWLINE async def _async_setup_hook(self) -> None:NEWLINE # Called whenever the client needs to initialise asyncio objects with a running loopNEWLINE loop = asyncio.get_running_loop()NEWLINE self.loop = loopNEWLINE self.http.loop = loopNEWLINE self._connection.loop = loopNEWLINE await self._connection.async_setup()NEWLINENEWLINE self._ready = asyncio.Event()NEWLINENEWLINE async def setup_hook(self) -> None:NEWLINE """|coro|NEWLINENEWLINE A coroutine to be called to setup the bot, by default this is blank.NEWLINENEWLINE To perform asynchronous setup after the bot is logged in but beforeNEWLINE it has connected to the Websocket, overwrite this coroutine.NEWLINENEWLINE This is only called once, in :meth:`login`, and will be called beforeNEWLINE any events are dispatched, making it a better solution than doing suchNEWLINE setup in the :func:`~discord.on_ready` event.NEWLINENEWLINE .. warning::NEWLINENEWLINE Since this is called *before* the websocket connection is made thereforeNEWLINE anything that waits for the websocket will deadlock, this includes thingsNEWLINE like :meth:`wait_for` and :meth:`wait_until_ready`.NEWLINENEWLINE .. versionadded:: 2.0NEWLINE """NEWLINE passNEWLINENEWLINE # login state managementNEWLINENEWLINE async def login(self, token: str) -> None:NEWLINE """|coro|NEWLINENEWLINE Logs in the client with the specified credentials andNEWLINE calls the :meth:`setup_hook`.NEWLINENEWLINENEWLINE ParametersNEWLINE -----------NEWLINE token: :class:`str`NEWLINE The authentication token. Do not prefix this token withNEWLINE anything as the library will do it for you.NEWLINENEWLINE RaisesNEWLINE ------NEWLINE LoginFailureNEWLINE The wrong credentials are passed.NEWLINE HTTPExceptionNEWLINE An unknown HTTP related error occurred,NEWLINE usually when it isn't 200 or the known incorrect credentialsNEWLINE passing status code.NEWLINE """NEWLINENEWLINE _log.info('logging in using static token')NEWLINENEWLINE await self._async_setup_hook()NEWLINENEWLINE data = await self.http.static_login(token.strip())NEWLINE self._connection.user = ClientUser(state=self._connection, data=data)NEWLINE await self.setup_hook()NEWLINENEWLINE async def connect(self, *, reconnect: bool = True) -> None:NEWLINE """|coro|NEWLINENEWLINE Creates a websocket connection and lets the websocket listenNEWLINE to messages from Discord. This is a loop that runs the entireNEWLINE event system and miscellaneous aspects of the library. ControlNEWLINE is not resumed until the WebSocket connection is terminated.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE reconnect: :class:`bool`NEWLINE If we should attempt reconnecting, either due to internetNEWLINE failure or a specific failure on Discord's part. CertainNEWLINE disconnects that lead to bad state will not be handled (such asNEWLINE invalid sharding payloads or bad tokens).NEWLINENEWLINE RaisesNEWLINE -------NEWLINE GatewayNotFoundNEWLINE If the gateway to connect to Discord is not found. Usually if thisNEWLINE is thrown then there is a Discord API outage.NEWLINE ConnectionClosedNEWLINE The websocket connection has been terminated.NEWLINE """NEWLINENEWLINE backoff = ExponentialBackoff()NEWLINE ws_params = {NEWLINE 'initial': True,NEWLINE 'shard_id': self.shard_id,NEWLINE }NEWLINE while not self.is_closed():NEWLINE try:NEWLINE coro = DiscordWebSocket.from_client(self, **ws_params)NEWLINE self.ws = await asyncio.wait_for(coro, timeout=60.0)NEWLINE ws_params['initial'] = FalseNEWLINE while True:NEWLINE await self.ws.poll_event()NEWLINE except ReconnectWebSocket as e:NEWLINE _log.info('Got a request to %s the websocket.', e.op)NEWLINE self.dispatch('disconnect')NEWLINE ws_params.update(sequence=self.ws.sequence, resume=e.resume, session=self.ws.session_id)NEWLINE continueNEWLINE except (NEWLINE OSError,NEWLINE HTTPException,NEWLINE GatewayNotFound,NEWLINE ConnectionClosed,NEWLINE aiohttp.ClientError,NEWLINE asyncio.TimeoutError,NEWLINE ) as exc:NEWLINENEWLINE self.dispatch('disconnect')NEWLINE if not reconnect:NEWLINE await self.close()NEWLINE if isinstance(exc, ConnectionClosed) and exc.code == 1000:NEWLINE # clean close, don't re-raise thisNEWLINE returnNEWLINE raiseNEWLINENEWLINE if self.is_closed():NEWLINE returnNEWLINENEWLINE # If we get connection reset by peer then try to RESUMENEWLINE if isinstance(exc, OSError) and exc.errno in (54, 10054):NEWLINE ws_params.update(sequence=self.ws.sequence, initial=False, resume=True, session=self.ws.session_id)NEWLINE continueNEWLINENEWLINE # We should only get this when an unhandled close code happens,NEWLINE # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc)NEWLINE # sometimes, discord sends us 1000 for unknown reasons so we should reconnectNEWLINE # regardless and rely on is_closed insteadNEWLINE if isinstance(exc, ConnectionClosed):NEWLINE if exc.code == 4014:NEWLINE raise PrivilegedIntentsRequired(exc.shard_id) from NoneNEWLINE if exc.code != 1000:NEWLINE await self.close()NEWLINE raiseNEWLINENEWLINE retry = backoff.delay()NEWLINE _log.exception("Attempting a reconnect in %.2fs", retry)NEWLINE await asyncio.sleep(retry)NEWLINE # Always try to RESUME the connectionNEWLINE # If the connection is not RESUME-able then the gateway will invalidate the session.NEWLINE # This is apparently what the official Discord client does.NEWLINE ws_params.update(sequence=self.ws.sequence, resume=True, session=self.ws.session_id)NEWLINENEWLINE async def close(self) -> None:NEWLINE """|coro|NEWLINENEWLINE Closes the connection to Discord.NEWLINE """NEWLINE if self._closed:NEWLINE returnNEWLINENEWLINE self._closed = TrueNEWLINENEWLINE for voice in self.voice_clients:NEWLINE try:NEWLINE await voice.disconnect(force=True)NEWLINE except Exception:NEWLINE # if an error happens during disconnects, disregard it.NEWLINE passNEWLINENEWLINE if self.ws is not None and self.ws.open:NEWLINE await self.ws.close(code=1000)NEWLINENEWLINE await self.http.close()NEWLINENEWLINE if self._ready is not MISSING:NEWLINE self._ready.clear()NEWLINENEWLINE self.loop = MISSINGNEWLINENEWLINE def clear(self) -> None:NEWLINE """Clears the internal state of the bot.NEWLINENEWLINE After this, the bot can be considered "re-opened", i.e. :meth:`is_closed`NEWLINE and :meth:`is_ready` both return ``False`` along with the bot's internalNEWLINE cache cleared.NEWLINE """NEWLINE self._closed = FalseNEWLINE self._ready.clear()NEWLINE self._connection.clear()NEWLINE self.http.recreate()NEWLINENEWLINE async def start(self, token: str, *, reconnect: bool = True) -> None:NEWLINE """|coro|NEWLINENEWLINE A shorthand coroutine for :meth:`login` + :meth:`connect`.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE TypeErrorNEWLINE An unexpected keyword argument was received.NEWLINE """NEWLINE await self.login(token)NEWLINE await self.connect(reconnect=reconnect)NEWLINENEWLINE def run(self, *args: Any, **kwargs: Any) -> None:NEWLINE """A blocking call that abstracts away the event loopNEWLINE initialisation from you.NEWLINENEWLINE If you want more control over the event loop then thisNEWLINE function should not be used. Use :meth:`start` coroutineNEWLINE or :meth:`connect` + :meth:`login`.NEWLINENEWLINE Roughly Equivalent to: ::NEWLINENEWLINE try:NEWLINE asyncio.run(self.start(*args, **kwargs))NEWLINE except KeyboardInterrupt:NEWLINE returnNEWLINENEWLINE .. warning::NEWLINENEWLINE This function must be the last function to call due to the fact that itNEWLINE is blocking. That means that registration of events or anything beingNEWLINE called after this function call will not execute until it returns.NEWLINE """NEWLINENEWLINE async def runner():NEWLINE async with self:NEWLINE await self.start(*args, **kwargs)NEWLINENEWLINE try:NEWLINE asyncio.run(runner())NEWLINE except KeyboardInterrupt:NEWLINE # nothing to do hereNEWLINE # `asyncio.run` handles the loop cleanupNEWLINE # and `self.start` closes all sockets and the HTTPClient instance.NEWLINE returnNEWLINENEWLINE # propertiesNEWLINENEWLINE def is_closed(self) -> bool:NEWLINE """:class:`bool`: Indicates if the websocket connection is closed."""NEWLINE return self._closedNEWLINENEWLINE @propertyNEWLINE def activity(self) -> Optional[ActivityTypes]:NEWLINE """Optional[:class:`.BaseActivity`]: The activity being used uponNEWLINE logging in.NEWLINE """NEWLINE return create_activity(self._connection._activity, self._connection)NEWLINENEWLINE @activity.setterNEWLINE def activity(self, value: Optional[ActivityTypes]) -> None:NEWLINE if value is None:NEWLINE self._connection._activity = NoneNEWLINE elif isinstance(value, BaseActivity):NEWLINE # ConnectionState._activity is typehinted as ActivityPayload, we're passing Dict[str, Any]NEWLINE self._connection._activity = value.to_dict() # type: ignoreNEWLINE else:NEWLINE raise TypeError('activity must derive from BaseActivity.')NEWLINENEWLINE @propertyNEWLINE def status(self) -> Status:NEWLINE """:class:`.Status`:NEWLINE The status being used upon logging on to Discord.NEWLINENEWLINE .. versionadded: 2.0NEWLINE """NEWLINE if self._connection._status in set(state.value for state in Status):NEWLINE return Status(self._connection._status)NEWLINE return Status.onlineNEWLINENEWLINE @status.setterNEWLINE def status(self, value: Status) -> None:NEWLINE if value is Status.offline:NEWLINE self._connection._status = 'invisible'NEWLINE elif isinstance(value, Status):NEWLINE self._connection._status = str(value)NEWLINE else:NEWLINE raise TypeError('status must derive from Status.')NEWLINENEWLINE @propertyNEWLINE def allowed_mentions(self) -> Optional[AllowedMentions]:NEWLINE """Optional[:class:`~discord.AllowedMentions`]: The allowed mention configuration.NEWLINENEWLINE .. versionadded:: 1.4NEWLINE """NEWLINE return self._connection.allowed_mentionsNEWLINENEWLINE @allowed_mentions.setterNEWLINE def allowed_mentions(self, value: Optional[AllowedMentions]) -> None:NEWLINE if value is None or isinstance(value, AllowedMentions):NEWLINE self._connection.allowed_mentions = valueNEWLINE else:NEWLINE raise TypeError(f'allowed_mentions must be AllowedMentions not {value.__class__!r}')NEWLINENEWLINE @propertyNEWLINE def intents(self) -> Intents:NEWLINE """:class:`~discord.Intents`: The intents configured for this connection.NEWLINENEWLINE .. versionadded:: 1.5NEWLINE """NEWLINE return self._connection.intentsNEWLINENEWLINE # helpers/gettersNEWLINENEWLINE @propertyNEWLINE def users(self) -> List[User]:NEWLINE """List[:class:`~discord.User`]: Returns a list of all the users the bot can see."""NEWLINE return list(self._connection._users.values())NEWLINENEWLINE def get_channel(self, id: int, /) -> Optional[Union[GuildChannel, Thread, PrivateChannel]]:NEWLINE """Returns a channel or thread with the given ID.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``id`` parameter is now positional-only.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE id: :class:`int`NEWLINE The ID to search for.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Optional[Union[:class:`.abc.GuildChannel`, :class:`.Thread`, :class:`.abc.PrivateChannel`]]NEWLINE The returned channel or ``None`` if not found.NEWLINE """NEWLINE return self._connection.get_channel(id) # type: ignore - The cache contains all channel typesNEWLINENEWLINE def get_partial_messageable(self, id: int, *, type: Optional[ChannelType] = None) -> PartialMessageable:NEWLINE """Returns a partial messageable with the given channel ID.NEWLINENEWLINE This is useful if you have a channel_id but don't want to do an API callNEWLINE to send messages to it.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE id: :class:`int`NEWLINE The channel ID to create a partial messageable for.NEWLINE type: Optional[:class:`.ChannelType`]NEWLINE The underlying channel type for the partial messageable.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`.PartialMessageable`NEWLINE The partial messageableNEWLINE """NEWLINE return PartialMessageable(state=self._connection, id=id, type=type)NEWLINENEWLINE def get_stage_instance(self, id: int, /) -> Optional[StageInstance]:NEWLINE """Returns a stage instance with the given stage channel ID.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE id: :class:`int`NEWLINE The ID to search for.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Optional[:class:`.StageInstance`]NEWLINE The stage instance or ``None`` if not found.NEWLINE """NEWLINE from .channel import StageChannelNEWLINENEWLINE channel = self._connection.get_channel(id)NEWLINENEWLINE if isinstance(channel, StageChannel):NEWLINE return channel.instanceNEWLINENEWLINE def get_guild(self, id: int, /) -> Optional[Guild]:NEWLINE """Returns a guild with the given ID.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``id`` parameter is now positional-only.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE id: :class:`int`NEWLINE The ID to search for.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Optional[:class:`.Guild`]NEWLINE The guild or ``None`` if not found.NEWLINE """NEWLINE return self._connection._get_guild(id)NEWLINENEWLINE def get_user(self, id: int, /) -> Optional[User]:NEWLINE """Returns a user with the given ID.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``id`` parameter is now positional-only.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE id: :class:`int`NEWLINE The ID to search for.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Optional[:class:`~discord.User`]NEWLINE The user or ``None`` if not found.NEWLINE """NEWLINE return self._connection.get_user(id)NEWLINENEWLINE def get_emoji(self, id: int, /) -> Optional[Emoji]:NEWLINE """Returns an emoji with the given ID.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``id`` parameter is now positional-only.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE id: :class:`int`NEWLINE The ID to search for.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Optional[:class:`.Emoji`]NEWLINE The custom emoji or ``None`` if not found.NEWLINE """NEWLINE return self._connection.get_emoji(id)NEWLINENEWLINE def get_sticker(self, id: int, /) -> Optional[GuildSticker]:NEWLINE """Returns a guild sticker with the given ID.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE .. note::NEWLINENEWLINE To retrieve standard stickers, use :meth:`.fetch_sticker`.NEWLINE or :meth:`.fetch_premium_sticker_packs`.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Optional[:class:`.GuildSticker`]NEWLINE The sticker or ``None`` if not found.NEWLINE """NEWLINE return self._connection.get_sticker(id)NEWLINENEWLINE def get_all_channels(self) -> Generator[GuildChannel, None, None]:NEWLINE """A generator that retrieves every :class:`.abc.GuildChannel` the client can 'access'.NEWLINENEWLINE This is equivalent to: ::NEWLINENEWLINE for guild in client.guilds:NEWLINE for channel in guild.channels:NEWLINE yield channelNEWLINENEWLINE .. note::NEWLINENEWLINE Just because you receive a :class:`.abc.GuildChannel` does not mean thatNEWLINE you can communicate in said channel. :meth:`.abc.GuildChannel.permissions_for` shouldNEWLINE be used for that.NEWLINENEWLINE YieldsNEWLINE ------NEWLINE :class:`.abc.GuildChannel`NEWLINE A channel the client can 'access'.NEWLINE """NEWLINENEWLINE for guild in self.guilds:NEWLINE yield from guild.channelsNEWLINENEWLINE def get_all_members(self) -> Generator[Member, None, None]:NEWLINE """Returns a generator with every :class:`.Member` the client can see.NEWLINENEWLINE This is equivalent to: ::NEWLINENEWLINE for guild in client.guilds:NEWLINE for member in guild.members:NEWLINE yield memberNEWLINENEWLINE YieldsNEWLINE ------NEWLINE :class:`.Member`NEWLINE A member the client can see.NEWLINE """NEWLINE for guild in self.guilds:NEWLINE yield from guild.membersNEWLINENEWLINE # listeners/waitersNEWLINENEWLINE async def wait_until_ready(self) -> None:NEWLINE """|coro|NEWLINENEWLINE Waits until the client's internal cache is all ready.NEWLINENEWLINE .. warning::NEWLINENEWLINE Calling this inside :meth:`setup_hook` can lead to a deadlock.NEWLINE """NEWLINE if self._ready is not MISSING:NEWLINE await self._ready.wait()NEWLINENEWLINE def wait_for(NEWLINE self,NEWLINE event: str,NEWLINE *,NEWLINE check: Optional[Callable[..., bool]] = None,NEWLINE timeout: Optional[float] = None,NEWLINE ) -> Any:NEWLINE """|coro|NEWLINENEWLINE Waits for a WebSocket event to be dispatched.NEWLINENEWLINE This could be used to wait for a user to reply to a message,NEWLINE or to react to a message, or to edit a message in a self-containedNEWLINE way.NEWLINENEWLINE The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default,NEWLINE it does not timeout. Note that this does propagate theNEWLINE :exc:`asyncio.TimeoutError` for you in case of timeout and is provided forNEWLINE ease of use.NEWLINENEWLINE In case the event returns multiple arguments, a :class:`tuple` containing thoseNEWLINE arguments is returned instead. Please check theNEWLINE :ref:`documentation ` for a list of events and theirNEWLINE parameters.NEWLINENEWLINE This function returns the **first event that meets the requirements**.NEWLINENEWLINE ExamplesNEWLINE ---------NEWLINENEWLINE Waiting for a user reply: ::NEWLINENEWLINE @client.eventNEWLINE async def on_message(message):NEWLINE if message.content.startswith('$greet'):NEWLINE channel = message.channelNEWLINE await channel.send('Say hello!')NEWLINENEWLINE def check(m):NEWLINE return m.content == 'hello' and m.channel == channelNEWLINENEWLINE msg = await client.wait_for('message', check=check)NEWLINE await channel.send(f'Hello {msg.author}!')NEWLINENEWLINE Waiting for a thumbs up reaction from the message author: ::NEWLINENEWLINE @client.eventNEWLINE async def on_message(message):NEWLINE if message.content.startswith('$thumb'):NEWLINE channel = message.channelNEWLINE await channel.send('Send me that \N{THUMBS UP SIGN} reaction, mate')NEWLINENEWLINE def check(reaction, user):NEWLINE return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}'NEWLINENEWLINE try:NEWLINE reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)NEWLINE except asyncio.TimeoutError:NEWLINE await channel.send('\N{THUMBS DOWN SIGN}')NEWLINE else:NEWLINE await channel.send('\N{THUMBS UP SIGN}')NEWLINENEWLINENEWLINE ParametersNEWLINE ------------NEWLINE event: :class:`str`NEWLINE The event name, similar to the :ref:`event reference `,NEWLINE but without the ``on_`` prefix, to wait for.NEWLINE check: Optional[Callable[..., :class:`bool`]]NEWLINE A predicate to check what to wait for. The arguments must meet theNEWLINE parameters of the event being waited for.NEWLINE timeout: Optional[:class:`float`]NEWLINE The number of seconds to wait before timing out and raisingNEWLINE :exc:`asyncio.TimeoutError`.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE asyncio.TimeoutErrorNEWLINE If a timeout is provided and it was reached.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE AnyNEWLINE Returns no arguments, a single argument, or a :class:`tuple` of multipleNEWLINE arguments that mirrors the parameters passed in theNEWLINE :ref:`event reference `.NEWLINE """NEWLINENEWLINE future = self.loop.create_future()NEWLINE if check is None:NEWLINENEWLINE def _check(*args):NEWLINE return TrueNEWLINENEWLINE check = _checkNEWLINENEWLINE ev = event.lower()NEWLINE try:NEWLINE listeners = self._listeners[ev]NEWLINE except KeyError:NEWLINE listeners = []NEWLINE self._listeners[ev] = listenersNEWLINENEWLINE listeners.append((future, check))NEWLINE return asyncio.wait_for(future, timeout)NEWLINENEWLINE # event registrationNEWLINENEWLINE def event(self, coro: Coro) -> Coro:NEWLINE """A decorator that registers an event to listen to.NEWLINENEWLINE You can find more info about the events on the :ref:`documentation below `.NEWLINENEWLINE The events must be a :ref:`coroutine `, if not, :exc:`TypeError` is raised.NEWLINENEWLINE ExampleNEWLINE ---------NEWLINENEWLINE .. code-block:: python3NEWLINENEWLINE @client.eventNEWLINE async def on_ready():NEWLINE print('Ready!')NEWLINENEWLINE RaisesNEWLINE --------NEWLINE TypeErrorNEWLINE The coroutine passed is not actually a coroutine.NEWLINE """NEWLINENEWLINE if not asyncio.iscoroutinefunction(coro):NEWLINE raise TypeError('event registered must be a coroutine function')NEWLINENEWLINE setattr(self, coro.__name__, coro)NEWLINE _log.debug('%s has successfully been registered as an event', coro.__name__)NEWLINE return coroNEWLINENEWLINE async def change_presence(NEWLINE self,NEWLINE *,NEWLINE activity: Optional[BaseActivity] = None,NEWLINE status: Optional[Status] = None,NEWLINE ) -> None:NEWLINE """|coro|NEWLINENEWLINE Changes the client's presence.NEWLINENEWLINE ExampleNEWLINE ---------NEWLINENEWLINE .. code-block:: python3NEWLINENEWLINE game = discord.Game("with the API")NEWLINE await client.change_presence(status=discord.Status.idle, activity=game)NEWLINENEWLINE .. versionchanged:: 2.0NEWLINE Removed the ``afk`` keyword-only parameter.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINE This function will now raise :exc:`TypeError` instead ofNEWLINE ``InvalidArgument``.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE activity: Optional[:class:`.BaseActivity`]NEWLINE The activity being done. ``None`` if no currently active activity is done.NEWLINE status: Optional[:class:`.Status`]NEWLINE Indicates what status to change to. If ``None``, thenNEWLINE :attr:`.Status.online` is used.NEWLINENEWLINE RaisesNEWLINE ------NEWLINE TypeErrorNEWLINE If the ``activity`` parameter is not the proper type.NEWLINE """NEWLINENEWLINE if status is None:NEWLINE status_str = 'online'NEWLINE status = Status.onlineNEWLINE elif status is Status.offline:NEWLINE status_str = 'invisible'NEWLINE status = Status.offlineNEWLINE else:NEWLINE status_str = str(status)NEWLINENEWLINE await self.ws.change_presence(activity=activity, status=status_str)NEWLINENEWLINE for guild in self._connection.guilds:NEWLINE me = guild.meNEWLINE if me is None:NEWLINE continueNEWLINENEWLINE if activity is not None:NEWLINE me.activities = (activity,) # type: ignore - Type checker does not understand the downcast hereNEWLINE else:NEWLINE me.activities = ()NEWLINENEWLINE me.status = statusNEWLINENEWLINE # Guild stuffNEWLINENEWLINE async def fetch_guilds(NEWLINE self,NEWLINE *,NEWLINE limit: Optional[int] = 100,NEWLINE before: Optional[SnowflakeTime] = None,NEWLINE after: Optional[SnowflakeTime] = None,NEWLINE ) -> AsyncIterator[Guild]:NEWLINE """Retrieves an :term:`asynchronous iterator` that enables receiving your guilds.NEWLINENEWLINE .. note::NEWLINENEWLINE Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`,NEWLINE :attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`.NEWLINENEWLINE .. note::NEWLINENEWLINE This method is an API call. For general usage, consider :attr:`guilds` instead.NEWLINENEWLINE ExamplesNEWLINE ---------NEWLINENEWLINE Usage ::NEWLINENEWLINE async for guild in client.fetch_guilds(limit=150):NEWLINE print(guild.name)NEWLINENEWLINE Flattening into a list ::NEWLINENEWLINE guilds = [guild async for guild in client.fetch_guilds(limit=150)]NEWLINE # guilds is now a list of Guild...NEWLINENEWLINE All parameters are optional.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE limit: Optional[:class:`int`]NEWLINE The number of guilds to retrieve.NEWLINE If ``None``, it retrieves every guild you have access to. Note, however,NEWLINE that this would make it a slow operation.NEWLINE Defaults to ``100``.NEWLINE before: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`]NEWLINE Retrieves guilds before this date or object.NEWLINE If a datetime is provided, it is recommended to use a UTC aware datetime.NEWLINE If the datetime is naive, it is assumed to be local time.NEWLINE after: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`]NEWLINE Retrieve guilds after this date or object.NEWLINE If a datetime is provided, it is recommended to use a UTC aware datetime.NEWLINE If the datetime is naive, it is assumed to be local time.NEWLINENEWLINE RaisesNEWLINE ------NEWLINE HTTPExceptionNEWLINE Getting the guilds failed.NEWLINENEWLINE YieldsNEWLINE --------NEWLINE :class:`.Guild`NEWLINE The guild with the guild data parsed.NEWLINE """NEWLINENEWLINE async def _before_strategy(retrieve, before, limit):NEWLINE before_id = before.id if before else NoneNEWLINE data = await self.http.get_guilds(retrieve, before=before_id)NEWLINENEWLINE if data:NEWLINE if limit is not None:NEWLINE limit -= len(data)NEWLINENEWLINE before = Object(id=int(data[-1]['id']))NEWLINENEWLINE return data, before, limitNEWLINENEWLINE async def _after_strategy(retrieve, after, limit):NEWLINE after_id = after.id if after else NoneNEWLINE data = await self.http.get_guilds(retrieve, after=after_id)NEWLINENEWLINE if data:NEWLINE if limit is not None:NEWLINE limit -= len(data)NEWLINENEWLINE after = Object(id=int(data[0]['id']))NEWLINENEWLINE return data, after, limitNEWLINENEWLINE if isinstance(before, datetime.datetime):NEWLINE before = Object(id=time_snowflake(before, high=False))NEWLINE if isinstance(after, datetime.datetime):NEWLINE after = Object(id=time_snowflake(after, high=True))NEWLINENEWLINE predicate: Optional[Callable[[GuildPayload], bool]] = NoneNEWLINE strategy, state = _before_strategy, beforeNEWLINENEWLINE if before and after:NEWLINE predicate = lambda m: int(m['id']) > after.idNEWLINE elif after:NEWLINE strategy, state = _after_strategy, afterNEWLINENEWLINE while True:NEWLINE retrieve = min(100 if limit is None else limit, 100)NEWLINE if retrieve < 1:NEWLINE returnNEWLINENEWLINE data, state, limit = await strategy(retrieve, state, limit)NEWLINENEWLINE # Terminate loop on next iteration; there's no data left after thisNEWLINE if len(data) < 100:NEWLINE limit = 0NEWLINENEWLINE if predicate:NEWLINE data = filter(predicate, data)NEWLINENEWLINE for raw_guild in data:NEWLINE yield Guild(state=self._connection, data=raw_guild)NEWLINENEWLINE async def fetch_template(self, code: Union[Template, str]) -> Template:NEWLINE """|coro|NEWLINENEWLINE Gets a :class:`.Template` from a discord.new URL or code.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE code: Union[:class:`.Template`, :class:`str`]NEWLINE The Discord Template Code or URL (must be a discord.new URL).NEWLINENEWLINE RaisesNEWLINE -------NEWLINE NotFoundNEWLINE The template is invalid.NEWLINE HTTPExceptionNEWLINE Getting the template failed.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`.Template`NEWLINE The template from the URL/code.NEWLINE """NEWLINE code = utils.resolve_template(code)NEWLINE data = await self.http.get_template(code)NEWLINE return Template(data=data, state=self._connection)NEWLINENEWLINE async def fetch_guild(self, guild_id: int, /, *, with_counts: bool = True) -> Guild:NEWLINE """|coro|NEWLINENEWLINE Retrieves a :class:`.Guild` from an ID.NEWLINENEWLINE .. note::NEWLINENEWLINE Using this, you will **not** receive :attr:`.Guild.channels`, :attr:`.Guild.members`,NEWLINE :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`.NEWLINENEWLINE .. note::NEWLINENEWLINE This method is an API call. For general usage, consider :meth:`get_guild` instead.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``guild_id`` parameter is now positional-only.NEWLINENEWLINENEWLINE ParametersNEWLINE -----------NEWLINE guild_id: :class:`int`NEWLINE The guild's ID to fetch from.NEWLINE with_counts: :class:`bool`NEWLINE Whether to include count information in the guild. This fills theNEWLINE :attr:`.Guild.approximate_member_count` and :attr:`.Guild.approximate_presence_count`NEWLINE attributes without needing any privileged intents. Defaults to ``True``.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE RaisesNEWLINE ------NEWLINE ForbiddenNEWLINE You do not have access to the guild.NEWLINE HTTPExceptionNEWLINE Getting the guild failed.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`.Guild`NEWLINE The guild from the ID.NEWLINE """NEWLINE data = await self.http.get_guild(guild_id, with_counts=with_counts)NEWLINE return Guild(data=data, state=self._connection)NEWLINENEWLINE async def create_guild(NEWLINE self,NEWLINE *,NEWLINE name: str,NEWLINE icon: bytes = MISSING,NEWLINE code: str = MISSING,NEWLINE ) -> Guild:NEWLINE """|coro|NEWLINENEWLINE Creates a :class:`.Guild`.NEWLINENEWLINE Bot accounts in more than 10 guilds are not allowed to create guilds.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINE ``name`` and ``icon`` parameters are now keyword-only. The `region`` parameter has been removed.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINE This function will now raise :exc:`ValueError` instead ofNEWLINE ``InvalidArgument``.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE name: :class:`str`NEWLINE The name of the guild.NEWLINE icon: Optional[:class:`bytes`]NEWLINE The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit`NEWLINE for more details on what is expected.NEWLINE code: :class:`str`NEWLINE The code for a template to create the guild with.NEWLINENEWLINE .. versionadded:: 1.4NEWLINENEWLINE RaisesNEWLINE ------NEWLINE HTTPExceptionNEWLINE Guild creation failed.NEWLINE ValueErrorNEWLINE Invalid icon image format given. Must be PNG or JPG.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE :class:`.Guild`NEWLINE The guild created. This is not the same guild that isNEWLINE added to cache.NEWLINE """NEWLINE if icon is not MISSING:NEWLINE icon_base64 = utils._bytes_to_base64_data(icon)NEWLINE else:NEWLINE icon_base64 = NoneNEWLINENEWLINE if code:NEWLINE data = await self.http.create_from_template(code, name, icon_base64)NEWLINE else:NEWLINE data = await self.http.create_guild(name, icon_base64)NEWLINE return Guild(data=data, state=self._connection)NEWLINENEWLINE async def fetch_stage_instance(self, channel_id: int, /) -> StageInstance:NEWLINE """|coro|NEWLINENEWLINE Gets a :class:`.StageInstance` for a stage channel id.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE channel_id: :class:`int`NEWLINE The stage channel ID.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE NotFoundNEWLINE The stage instance or channel could not be found.NEWLINE HTTPExceptionNEWLINE Getting the stage instance failed.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`.StageInstance`NEWLINE The stage instance from the stage channel ID.NEWLINE """NEWLINE data = await self.http.get_stage_instance(channel_id)NEWLINE guild = self.get_guild(int(data['guild_id']))NEWLINE # Guild can technically be None here but this is being explicitly silenced right now.NEWLINE return StageInstance(guild=guild, state=self._connection, data=data) # type: ignoreNEWLINENEWLINE # Invite managementNEWLINENEWLINE async def fetch_invite(NEWLINE self,NEWLINE url: Union[Invite, str],NEWLINE *,NEWLINE with_counts: bool = True,NEWLINE with_expiration: bool = True,NEWLINE scheduled_event_id: Optional[int] = None,NEWLINE ) -> Invite:NEWLINE """|coro|NEWLINENEWLINE Gets an :class:`.Invite` from a discord.gg URL or ID.NEWLINENEWLINE .. note::NEWLINENEWLINE If the invite is for a guild you have not joined, the guild and channelNEWLINE attributes of the returned :class:`.Invite` will be :class:`.PartialInviteGuild` andNEWLINE :class:`.PartialInviteChannel` respectively.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE url: Union[:class:`.Invite`, :class:`str`]NEWLINE The Discord invite ID or URL (must be a discord.gg URL).NEWLINE with_counts: :class:`bool`NEWLINE Whether to include count information in the invite. This fills theNEWLINE :attr:`.Invite.approximate_member_count` and :attr:`.Invite.approximate_presence_count`NEWLINE fields.NEWLINE with_expiration: :class:`bool`NEWLINE Whether to include the expiration date of the invite. This fills theNEWLINE :attr:`.Invite.expires_at` field.NEWLINENEWLINE .. versionadded:: 2.0NEWLINE scheduled_event_id: Optional[:class:`int`]NEWLINE The ID of the scheduled event this invite is for.NEWLINENEWLINE .. note::NEWLINENEWLINE It is not possible to provide a url that contains an ``event_id`` parameterNEWLINE when using this parameter.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE RaisesNEWLINE -------NEWLINE ValueErrorNEWLINE The url contains an ``event_id``, but ``scheduled_event_id`` has also been provided.NEWLINE NotFoundNEWLINE The invite has expired or is invalid.NEWLINE HTTPExceptionNEWLINE Getting the invite failed.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`.Invite`NEWLINE The invite from the URL/ID.NEWLINE """NEWLINENEWLINE resolved = utils.resolve_invite(url)NEWLINENEWLINE if scheduled_event_id and resolved.event:NEWLINE raise ValueError('Cannot specify scheduled_event_id and contain an event_id in the url.')NEWLINENEWLINE scheduled_event_id = scheduled_event_id or resolved.eventNEWLINENEWLINE data = await self.http.get_invite(NEWLINE resolved.code,NEWLINE with_counts=with_counts,NEWLINE with_expiration=with_expiration,NEWLINE guild_scheduled_event_id=scheduled_event_id,NEWLINE )NEWLINE return Invite.from_incomplete(state=self._connection, data=data)NEWLINENEWLINE async def delete_invite(self, invite: Union[Invite, str], /) -> None:NEWLINE """|coro|NEWLINENEWLINE Revokes an :class:`.Invite`, URL, or ID to an invite.NEWLINENEWLINE You must have the :attr:`~.Permissions.manage_channels` permission inNEWLINE the associated guild to do this.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``invite`` parameter is now positional-only.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE invite: Union[:class:`.Invite`, :class:`str`]NEWLINE The invite to revoke.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE ForbiddenNEWLINE You do not have permissions to revoke invites.NEWLINE NotFoundNEWLINE The invite is invalid or expired.NEWLINE HTTPExceptionNEWLINE Revoking the invite failed.NEWLINE """NEWLINENEWLINE resolved = utils.resolve_invite(invite)NEWLINE await self.http.delete_invite(resolved.code)NEWLINENEWLINE # Miscellaneous stuffNEWLINENEWLINE async def fetch_widget(self, guild_id: int, /) -> Widget:NEWLINE """|coro|NEWLINENEWLINE Gets a :class:`.Widget` from a guild ID.NEWLINENEWLINE .. note::NEWLINENEWLINE The guild must have the widget enabled to get this information.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``guild_id`` parameter is now positional-only.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE guild_id: :class:`int`NEWLINE The ID of the guild.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE ForbiddenNEWLINE The widget for this guild is disabled.NEWLINE HTTPExceptionNEWLINE Retrieving the widget failed.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`.Widget`NEWLINE The guild's widget.NEWLINE """NEWLINE data = await self.http.get_widget(guild_id)NEWLINENEWLINE return Widget(state=self._connection, data=data)NEWLINENEWLINE async def application_info(self) -> AppInfo:NEWLINE """|coro|NEWLINENEWLINE Retrieves the bot's application information.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE HTTPExceptionNEWLINE Retrieving the information failed somehow.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`.AppInfo`NEWLINE The bot's application information.NEWLINE """NEWLINE data = await self.http.application_info()NEWLINE if 'rpc_origins' not in data:NEWLINE data['rpc_origins'] = NoneNEWLINE return AppInfo(self._connection, data)NEWLINENEWLINE async def fetch_user(self, user_id: int, /) -> User:NEWLINE """|coro|NEWLINENEWLINE Retrieves a :class:`~discord.User` based on their ID.NEWLINE You do not have to share any guilds with the user to get this information,NEWLINE however many operations do require that you do.NEWLINENEWLINE .. note::NEWLINENEWLINE This method is an API call. If you have :attr:`discord.Intents.members` and member cache enabled, consider :meth:`get_user` instead.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``user_id`` parameter is now positional-only.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE user_id: :class:`int`NEWLINE The user's ID to fetch from.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE NotFoundNEWLINE A user with this ID does not exist.NEWLINE HTTPExceptionNEWLINE Fetching the user failed.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`~discord.User`NEWLINE The user you requested.NEWLINE """NEWLINE data = await self.http.get_user(user_id)NEWLINE return User(state=self._connection, data=data)NEWLINENEWLINE async def fetch_channel(self, channel_id: int, /) -> Union[GuildChannel, PrivateChannel, Thread]:NEWLINE """|coro|NEWLINENEWLINE Retrieves a :class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`, or :class:`.Thread` with the specified ID.NEWLINENEWLINE .. note::NEWLINENEWLINE This method is an API call. For general usage, consider :meth:`get_channel` instead.NEWLINENEWLINE .. versionadded:: 1.2NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``channel_id`` parameter is now positional-only.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE InvalidDataNEWLINE An unknown channel type was received from Discord.NEWLINE HTTPExceptionNEWLINE Retrieving the channel failed.NEWLINE NotFoundNEWLINE Invalid Channel ID.NEWLINE ForbiddenNEWLINE You do not have permission to fetch this channel.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Union[:class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`, :class:`.Thread`]NEWLINE The channel from the ID.NEWLINE """NEWLINE data = await self.http.get_channel(channel_id)NEWLINENEWLINE factory, ch_type = _threaded_channel_factory(data['type'])NEWLINE if factory is None:NEWLINE raise InvalidData('Unknown channel type {type} for channel ID {id}.'.format_map(data))NEWLINENEWLINE if ch_type in (ChannelType.group, ChannelType.private):NEWLINE # the factory will be a DMChannel or GroupChannel hereNEWLINE channel = factory(me=self.user, data=data, state=self._connection) # type: ignoreNEWLINE else:NEWLINE # the factory can't be a DMChannel or GroupChannel hereNEWLINE guild_id = int(data['guild_id']) # type: ignoreNEWLINE guild = self.get_guild(guild_id) or Object(id=guild_id)NEWLINE # GuildChannels expect a Guild, we may be passing an ObjectNEWLINE channel = factory(guild=guild, state=self._connection, data=data) # type: ignoreNEWLINENEWLINE return channelNEWLINENEWLINE async def fetch_webhook(self, webhook_id: int, /) -> Webhook:NEWLINE """|coro|NEWLINENEWLINE Retrieves a :class:`.Webhook` with the specified ID.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``webhook_id`` parameter is now positional-only.NEWLINENEWLINE RaisesNEWLINE --------NEWLINE HTTPExceptionNEWLINE Retrieving the webhook failed.NEWLINE NotFoundNEWLINE Invalid webhook ID.NEWLINE ForbiddenNEWLINE You do not have permission to fetch this webhook.NEWLINENEWLINE ReturnsNEWLINE ---------NEWLINE :class:`.Webhook`NEWLINE The webhook you requested.NEWLINE """NEWLINE data = await self.http.get_webhook(webhook_id)NEWLINE return Webhook.from_state(data, state=self._connection)NEWLINENEWLINE async def fetch_sticker(self, sticker_id: int, /) -> Union[StandardSticker, GuildSticker]:NEWLINE """|coro|NEWLINENEWLINE Retrieves a :class:`.Sticker` with the specified ID.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE RaisesNEWLINE --------NEWLINE HTTPExceptionNEWLINE Retrieving the sticker failed.NEWLINE NotFoundNEWLINE Invalid sticker ID.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Union[:class:`.StandardSticker`, :class:`.GuildSticker`]NEWLINE The sticker you requested.NEWLINE """NEWLINE data = await self.http.get_sticker(sticker_id)NEWLINE cls, _ = _sticker_factory(data['type'])NEWLINE # The type checker is not smart enough to figure out the constructor is correctNEWLINE return cls(state=self._connection, data=data) # type: ignoreNEWLINENEWLINE async def fetch_premium_sticker_packs(self) -> List[StickerPack]:NEWLINE """|coro|NEWLINENEWLINE Retrieves all available premium sticker packs.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE RaisesNEWLINE -------NEWLINE HTTPExceptionNEWLINE Retrieving the sticker packs failed.NEWLINENEWLINE ReturnsNEWLINE ---------NEWLINE List[:class:`.StickerPack`]NEWLINE All available premium sticker packs.NEWLINE """NEWLINE data = await self.http.list_premium_sticker_packs()NEWLINE return [StickerPack(state=self._connection, data=pack) for pack in data['sticker_packs']]NEWLINENEWLINE async def create_dm(self, user: Snowflake) -> DMChannel:NEWLINE """|coro|NEWLINENEWLINE Creates a :class:`.DMChannel` with this user.NEWLINENEWLINE This should be rarely called, as this is done transparently for mostNEWLINE people.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE user: :class:`~discord.abc.Snowflake`NEWLINE The user to create a DM with.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE :class:`.DMChannel`NEWLINE The channel that was created.NEWLINE """NEWLINE state = self._connectionNEWLINE found = state._get_private_channel_by_user(user.id)NEWLINE if found:NEWLINE return foundNEWLINENEWLINE data = await state.http.start_private_message(user.id)NEWLINE return state.add_dm_channel(data)NEWLINENEWLINE def add_view(self, view: View, *, message_id: Optional[int] = None) -> None:NEWLINE """Registers a :class:`~discord.ui.View` for persistent listening.NEWLINENEWLINE This method should be used for when a view is comprised of componentsNEWLINE that last longer than the lifecycle of the program.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE ParametersNEWLINE ------------NEWLINE view: :class:`discord.ui.View`NEWLINE The view to register for dispatching.NEWLINE message_id: Optional[:class:`int`]NEWLINE The message ID that the view is attached to. This is currently used toNEWLINE refresh the view's state during message update events. If not givenNEWLINE then message update events are not propagated for the view.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE TypeErrorNEWLINE A view was not passed.NEWLINE ValueErrorNEWLINE The view is not persistent. A persistent view has no timeoutNEWLINE and all their components have an explicitly provided custom_id.NEWLINE """NEWLINENEWLINE if not isinstance(view, View):NEWLINE raise TypeError(f'expected an instance of View not {view.__class__!r}')NEWLINENEWLINE if not view.is_persistent():NEWLINE raise ValueError('View is not persistent. Items need to have a custom_id set and View must have no timeout')NEWLINENEWLINE self._connection.store_view(view, message_id)NEWLINENEWLINE @propertyNEWLINE def persistent_views(self) -> Sequence[View]:NEWLINE """Sequence[:class:`.View`]: A sequence of persistent views added to the client.NEWLINENEWLINE .. versionadded:: 2.0NEWLINE """NEWLINE return self._connection.persistent_viewsNEWLINE #!/usr/bin/env pythonNEWLINE# -*- coding: utf-8 -*-NEWLINE"""NEWLINEIn this example, we are going to make a dark code editor widget and make it show visualNEWLINEwhitespaces.NEWLINENEWLINE"""NEWLINEimport sysNEWLINEimport osNEWLINEos.environ['QT_API'] = 'pyside2'NEWLINE# os.environ['QT_API'] = 'pyqt5'NEWLINEfrom pyqode.qt import QtWidgets, QtGuiNEWLINEfrom pyqode.core import apiNEWLINEfrom pyqode.core import modesNEWLINEfrom pyqode.core import panelsNEWLINENEWLINENEWLINEdef main():NEWLINE app = QtWidgets.QApplication(sys.argv)NEWLINE window = QtWidgets.QMainWindow()NEWLINENEWLINE # code from the simple exampleNEWLINE editor = api.CodeEdit()NEWLINE editor.file.open(__file__)NEWLINE editor.modes.append(modes.CaretLineHighlighterMode())NEWLINE sh = modes.PygmentsSyntaxHighlighter(editor.document())NEWLINE editor.modes.append(sh)NEWLINE editor.panels.append(panels.SearchAndReplacePanel(),NEWLINE api.Panel.Position.TOP)NEWLINE # make the code edit show whitespaces in dark grayNEWLINE editor.show_white_spaces = TrueNEWLINE editor.whitespaces_foreground = QtGui.QColor('#606020')NEWLINENEWLINE # make a dark editor using the monokai themeNEWLINE sh.pygments_style = 'monokai'NEWLINENEWLINE window.setCentralWidget(editor)NEWLINE window.show()NEWLINENEWLINE app.exec_()NEWLINENEWLINE editor.file.close()NEWLINE del editorNEWLINE del windowNEWLINE del appNEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE main()NEWLINENEWLINE #!/usr/bin/env pythonNEWLINEfrom __future__ import division, print_function, absolute_importNEWLINENEWLINEimport numpy as npNEWLINEfrom numpy.testing import (run_module_suite, assert_allclose, assert_,NEWLINE assert_raises)NEWLINENEWLINEimport pywtNEWLINENEWLINENEWLINEdef test_dwt_idwt_basic():NEWLINE x = [3, 7, 1, 1, -2, 5, 4, 6]NEWLINE cA, cD = pywt.dwt(x, 'db2')NEWLINE cA_expect = [5.65685425, 7.39923721, 0.22414387, 3.33677403, 7.77817459]NEWLINE cD_expect = [-2.44948974, -1.60368225, -4.44140056, -0.41361256,NEWLINE 1.22474487]NEWLINE assert_allclose(cA, cA_expect)NEWLINE assert_allclose(cD, cD_expect)NEWLINENEWLINE x_roundtrip = pywt.idwt(cA, cD, 'db2')NEWLINE assert_allclose(x_roundtrip, x, rtol=1e-10)NEWLINENEWLINENEWLINEdef test_dwt_wavelet_kwd():NEWLINE x = np.array([3, 7, 1, 1, -2, 5, 4, 6])NEWLINE w = pywt.Wavelet('sym3')NEWLINE cA, cD = pywt.dwt(x, wavelet=w, mode='cpd')NEWLINE cA_expect = [4.38354585, 3.80302657, 7.31813271, -0.58565539, 4.09727044,NEWLINE 7.81994027]NEWLINE cD_expect = [-1.33068221, -2.78795192, -3.16825651, -0.67715519,NEWLINE -0.09722957, -0.07045258]NEWLINE assert_allclose(cA, cA_expect)NEWLINE assert_allclose(cD, cD_expect)NEWLINENEWLINENEWLINEdef test_dwt_coeff_len():NEWLINE x = np.array([3, 7, 1, 1, -2, 5, 4, 6])NEWLINE w = pywt.Wavelet('sym3')NEWLINE ln = pywt.dwt_coeff_len(data_len=len(x), filter_len=w.dec_len, mode='sym')NEWLINE assert_(ln == 6)NEWLINE ln_modes = [pywt.dwt_coeff_len(len(x), w.dec_len, mode) for mode inNEWLINE pywt.MODES.modes]NEWLINE assert_allclose(ln_modes, [6, 6, 6, 6, 6, 4])NEWLINENEWLINENEWLINEdef test_idwt_none_input():NEWLINE # None input equals arrays of zeros of the right lengthNEWLINE res1 = pywt.idwt([1,2,0,1], None, 'db2', 'sym')NEWLINE res2 = pywt.idwt([1, 2, 0, 1], [0, 0, 0, 0], 'db2', 'sym')NEWLINE assert_allclose(res1, res2, rtol=1e-15, atol=1e-15)NEWLINENEWLINE res1 = pywt.idwt(None, [1, 2, 0, 1], 'db2', 'sym')NEWLINE res2 = pywt.idwt([0, 0, 0, 0], [1, 2, 0, 1], 'db2', 'sym')NEWLINE assert_allclose(res1, res2, rtol=1e-15, atol=1e-15)NEWLINENEWLINE # Only one argument at a time can be NoneNEWLINE assert_raises(ValueError, pywt.idwt, None, None, 'db2', 'sym')NEWLINENEWLINENEWLINEdef test_idwt_correct_size_kw():NEWLINE res = pywt.idwt([1, 2, 3, 4, 5], [1, 2, 3, 4], 'db2', 'sym',NEWLINE correct_size=True)NEWLINE expected = [1.76776695, 0.61237244, 3.18198052, 0.61237244, 4.59619408,NEWLINE 0.61237244]NEWLINE assert_allclose(res, expected)NEWLINENEWLINE assert_raises(ValueError, pywt.idwt,NEWLINE [1, 2, 3, 4, 5], [1, 2, 3, 4], 'db2', 'sym')NEWLINE assert_raises(ValueError, pywt.idwt, [1, 2, 3, 4], [1, 2, 3, 4, 5], 'db2',NEWLINE 'sym', correct_size=True)NEWLINENEWLINENEWLINEdef test_idwt_invalid_input():NEWLINE # Too short, min length is 4 for 'db4':NEWLINE assert_raises(ValueError, pywt.idwt, [1,2,4], [4,1,3], 'db4', 'sym')NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE run_module_suite()NEWLINE from neo.Prompt.Commands.Invoke import InvokeContract, InvokeWithTokenVerificationScriptNEWLINEfrom neo.Core.Fixed8 import Fixed8NEWLINEfrom neo.Core.UInt160 import UInt160NEWLINEfrom neo.Network.common import blocking_prompt as promptNEWLINEfrom decimal import DecimalNEWLINEfrom neo.Core.TX.TransactionAttribute import TransactionAttributeNEWLINEimport binasciiNEWLINEfrom neo.Prompt.CommandBase import CommandBase, CommandDesc, ParameterDescNEWLINEfrom neo.Prompt.PromptData import PromptDataNEWLINEfrom neo.Prompt import Utils as PromptUtilsNEWLINEfrom neo.Implementations.Wallets.peewee.Models import NEP5Token as ModelNEP5TokenNEWLINEfrom neo.Implementations.Notifications.NotificationDB import NotificationDBNEWLINEfrom neo.Core.TX.TransactionAttribute import TransactionAttributeUsageNEWLINEfrom neo.Core.Utils import isValidPublicAddressNEWLINEimport peeweeNEWLINEimport tracebackNEWLINEfrom neo.Prompt.PromptPrinter import prompt_print as printNEWLINEfrom neo.logging import log_managerNEWLINENEWLINElogger = log_manager.getLogger()NEWLINENEWLINENEWLINEclass CommandWalletToken(CommandBase):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINE self.register_sub_command(CommandTokenDelete())NEWLINE self.register_sub_command(CommandTokenSend())NEWLINE self.register_sub_command(CommandTokenSendFrom())NEWLINE self.register_sub_command(CommandTokenHistory())NEWLINE self.register_sub_command(CommandTokenApprove())NEWLINE self.register_sub_command(CommandTokenAllowance())NEWLINE self.register_sub_command(CommandTokenMint())NEWLINE self.register_sub_command(CommandTokenRegister())NEWLINENEWLINE def command_desc(self):NEWLINE return CommandDesc('token', 'various token operations')NEWLINENEWLINE def execute(self, arguments):NEWLINE item = PromptUtils.get_arg(arguments)NEWLINENEWLINE if not item:NEWLINE print(f"run `{self.command_desc().command} help` to see supported queries")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE return self.execute_sub_command(item, arguments[1:])NEWLINE except KeyError:NEWLINE print(f"{item} is an invalid parameter")NEWLINE return FalseNEWLINENEWLINENEWLINEclass CommandTokenDelete(CommandBase):NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) != 1:NEWLINE print("Please specify the required parameter")NEWLINE return FalseNEWLINENEWLINE hash_string = arguments[0]NEWLINE try:NEWLINE script_hash = UInt160.ParseString(hash_string)NEWLINE except Exception:NEWLINE # because UInt160 throws a generic exception. Should be fixed in the futureNEWLINE print("Invalid script hash")NEWLINE return FalseNEWLINENEWLINE # try to find token and collect some dataNEWLINE try:NEWLINE token = ModelNEP5Token.get(ContractHash=script_hash)NEWLINE except peewee.DoesNotExist:NEWLINE print(f"Could not find a token with script_hash {arguments[0]}")NEWLINE return FalseNEWLINENEWLINE success = wallet.DeleteNEP5Token(script_hash)NEWLINE if success:NEWLINE print(f"Token {token.Symbol} with script_hash {arguments[0]} deleted")NEWLINE else:NEWLINE # probably unreachable to due token check earlier. Better safe than sorrowNEWLINE print(f"Could not find a token with script_hash {arguments[0]}")NEWLINENEWLINE return successNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('contract', 'token contract hash (script hash)')NEWLINE return CommandDesc('delete', 'remove a token from the wallet', [p1])NEWLINENEWLINENEWLINEclass CommandTokenSend(CommandBase):NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 4:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE if len(arguments) > 6:NEWLINE # the 5th and 6th arguments are optionalNEWLINE print("Too many parameters supplied. Please check your command")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINE arguments, user_tx_attributes = PromptUtils.get_tx_attr_from_args(arguments)NEWLINENEWLINE token = arguments[0]NEWLINE from_addr = arguments[1]NEWLINE to_addr = arguments[2]NEWLINE try:NEWLINE amount = float(arguments[3])NEWLINE except ValueError:NEWLINE print(f"{arguments[3]} is not a valid amount")NEWLINE return FalseNEWLINENEWLINE fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE fee = priority_feeNEWLINE if fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE success = token_send(wallet, token, from_addr, to_addr, amount, fee=fee, user_tx_attributes=user_tx_attributes)NEWLINE except ValueError as e:NEWLINE # occurs if arguments are invalidNEWLINE print(str(e))NEWLINE success = FalseNEWLINENEWLINE return successNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('token', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('from_addr', 'address to send token from')NEWLINE p3 = ParameterDesc('to_addr', 'address to send token to')NEWLINE p4 = ParameterDesc('amount', 'number of tokens to send')NEWLINE p5 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINE p6 = ParameterDesc('--tx-attr', f"a list of transaction attributes to attach to the transaction\n\n"NEWLINE f"{' ':>17} See: http://docs.neo.org/en-us/network/network-protocol.html section 4 for a description of possible attributes\n\n" # noqa: E128 ignore indentationNEWLINE f"{' ':>17} Example:\n"NEWLINE f"{' ':>20} --tx-attr=[{{\"usage\": ,\"data\":\"\"}}, ...]\n"NEWLINE f"{' ':>20} --tx-attr=[{{\"usage\": 0x90,\"data\":\"my brief description\"}}]\n", optional=True)NEWLINENEWLINE return CommandDesc('send', 'send a token from the wallet', [p1, p2, p3, p4, p5, p6])NEWLINENEWLINENEWLINEclass CommandTokenSendFrom(CommandBase):NEWLINE """NEWLINE This command is for old style NEP-5 tokens before the proposal got amended to remove this optional command.NEWLINE """NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 4:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINENEWLINE token_str = arguments[0]NEWLINE from_addr = arguments[1]NEWLINE to_addr = arguments[2]NEWLINENEWLINE try:NEWLINE amount = float(arguments[3])NEWLINE except ValueError:NEWLINE print(f"{arguments[3]} is not a valid amount")NEWLINE return FalseNEWLINENEWLINE p_fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE p_fee = priority_feeNEWLINE if p_fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE token, tx, fee, results = test_token_send_from(wallet, token_str, from_addr, to_addr, amount)NEWLINE except ValueError as e:NEWLINE # invalid arguments or bad allowanceNEWLINE print(str(e))NEWLINE return FalseNEWLINE except Exception as e:NEWLINE # we act as the final capturing placeNEWLINE print("Something really unexpected happened")NEWLINE logger.error(traceback.format_exc())NEWLINE return FalseNEWLINENEWLINE if tx is not None and results is not None:NEWLINE vm_result = results[0].GetBigInteger()NEWLINE if vm_result == 1:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print("Transfer of %s %s from %s to %s" % (NEWLINE string_from_amount(token, amount), token.symbol, from_addr, to_addr))NEWLINE print("Transfer fee: %s " % (fee.value / Fixed8.D))NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Transfer Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Transaction cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeContract(wallet, tx, comb_fee)NEWLINENEWLINE print(f"Could not transfer tokens. Virtual machine returned: {vm_result}")NEWLINE return FalseNEWLINENEWLINE print(f"Could not transfer tokens. An unknown error occurred resulting in no Transaction object or VM output.")NEWLINE return FalseNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('token', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('from_addr', 'address to send token from')NEWLINE p3 = ParameterDesc('to_addr', 'address to send token to')NEWLINE p4 = ParameterDesc('amount', 'number of tokens to send')NEWLINE p5 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINENEWLINE return CommandDesc('sendfrom', 'send a token on behalf of another account (requires approval)', [p1, p2, p3, p4, p5])NEWLINENEWLINENEWLINEclass CommandTokenHistory(CommandBase):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) != 1:NEWLINE print("Please specify the required parameter")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE token, events = token_history(wallet, arguments[0])NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE if events:NEWLINE addresses = wallet.AddressesNEWLINE print("-----------------------------------------------------------")NEWLINE print("Recent transaction history (last = more recent):")NEWLINE for event in events:NEWLINE if event.Type != 'transfer':NEWLINE continueNEWLINE if event.AddressFrom in addresses:NEWLINE print(f"[{event.AddressFrom}]: Sent {string_from_amount(token, event.Amount)}"NEWLINE f" {token.symbol} to {event.AddressTo}")NEWLINE if event.AddressTo in addresses:NEWLINE print(f"[{event.AddressTo}]: Received {string_from_amount(token, event.Amount)}"NEWLINE f" {token.symbol} from {event.AddressFrom}")NEWLINE print("-----------------------------------------------------------")NEWLINE else:NEWLINE print("History contains no transactions")NEWLINE return TrueNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE return CommandDesc('history', 'show transaction history', [p1])NEWLINENEWLINENEWLINEclass CommandTokenApprove(CommandBase):NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 4:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINENEWLINE token_str = arguments[0]NEWLINE from_addr = arguments[1]NEWLINE to_addr = arguments[2]NEWLINENEWLINE try:NEWLINE amount = float(arguments[3])NEWLINE except ValueError:NEWLINE print(f"{arguments[3]} is not a valid amount")NEWLINE return FalseNEWLINENEWLINE p_fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE p_fee = priority_feeNEWLINE if p_fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE token = _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount)NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE decimal_amount = amount_from_string(token, amount)NEWLINENEWLINE tx, fee, results = token.Approve(wallet, from_addr, to_addr, decimal_amount)NEWLINENEWLINE if tx is not None and results is not None:NEWLINE if results[0].GetBigInteger() == 1:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print(f"Approve allowance of {amount} {token.symbol} from {from_addr} to {to_addr}")NEWLINE print(f"Invocation fee: {fee.value / Fixed8.D}")NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Invocation Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Allowance approval cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeContract(wallet, tx, comb_fee)NEWLINENEWLINE print("Failed to approve tokens. Make sure you are entitled for approving.")NEWLINE return FalseNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('from_addr', 'address to send token from')NEWLINE p3 = ParameterDesc('to_addr', 'address to send token to')NEWLINE p4 = ParameterDesc('amount', 'number of tokens to send')NEWLINE p5 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINENEWLINE return CommandDesc('approve', 'approve an allowance', [p1, p2, p3, p4, p5])NEWLINENEWLINE def handle_help(self, arguments):NEWLINE super().handle_help(arguments)NEWLINE print(NEWLINE "\nThis is an optional NEP-5 command (now legacy).\nFor more information see https://github.com/neo-project/proposals/blob/c357f5965afc2155615b6b96c7d15da688f81982/nep-5.mediawiki#approve_optional")NEWLINENEWLINENEWLINEclass CommandTokenAllowance(CommandBase):NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) != 3:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE token_str = arguments[0]NEWLINE from_addr = arguments[1]NEWLINE to_addr = arguments[2]NEWLINENEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE try:NEWLINE allowance = token_get_allowance(wallet, token_str, from_addr, to_addr)NEWLINE print(f"{token.symbol} allowance for {from_addr} from {to_addr} : {allowance} ")NEWLINE return TrueNEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('from_addr', 'address to send token from')NEWLINE p3 = ParameterDesc('to_addr', 'address to send token to')NEWLINENEWLINE return CommandDesc('allowance', 'get the amount an account can transfer from another acount', [p1, p2, p3])NEWLINENEWLINENEWLINEclass CommandTokenMint(CommandBase):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 2:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE if len(arguments) > 6:NEWLINE # the 3rd and 4th argument are for attaching neo/gas, 5th for attaching a fee, 6th for attaching attributesNEWLINE print("Too many parameters supplied. Please check your command")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINE arguments, invoke_attrs = PromptUtils.get_tx_attr_from_args(arguments)NEWLINENEWLINE token_str = arguments[0]NEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE to_addr = arguments[1]NEWLINE if not isValidPublicAddress(to_addr):NEWLINE print(f"{to_addr} is not a valid address")NEWLINE return FalseNEWLINENEWLINE remaining_args = arguments[2:]NEWLINE asset_attachments = []NEWLINE for optional in remaining_args:NEWLINE _, neo_to_attach, gas_to_attach = PromptUtils.get_asset_attachments([optional])NEWLINENEWLINE if "attach-neo" in optional:NEWLINE if not neo_to_attach:NEWLINE print(f"Could not parse value from --attach-neo. Value must be an integer")NEWLINE return FalseNEWLINE else:NEWLINE asset_attachments.append(optional)NEWLINENEWLINE if "attach-gas" in optional:NEWLINE if not gas_to_attach:NEWLINE print(f"Could not parse value from --attach-gas")NEWLINE return FalseNEWLINE else:NEWLINE asset_attachments.append(optional)NEWLINENEWLINE fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE fee = priority_feeNEWLINE if fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE return token_mint(token, wallet, to_addr, asset_attachments=asset_attachments, fee=fee, invoke_attrs=invoke_attrs)NEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('to_addr', 'address to mint tokens to')NEWLINE p3 = ParameterDesc('--attach-neo', 'amount of neo to attach to the transaction', optional=True)NEWLINE p4 = ParameterDesc('--attach-gas', 'amount of gas to attach to the transaction', optional=True)NEWLINE p5 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINE p6 = ParameterDesc('--tx-attr', f"a list of transaction attributes to attach to the transaction\n\n"NEWLINE f"{' ':>17} See: http://docs.neo.org/en-us/network/network-protocol.html section 4 for a description of possible attributes\n\n" # noqa: E128 ignore indentationNEWLINE f"{' ':>17} Example:\n"NEWLINE f"{' ':>20} --tx-attr=[{{\"usage\": ,\"data\":\"\"}}, ...]\n"NEWLINE f"{' ':>20} --tx-attr=[{{\"usage\": 0x90,\"data\":\"my brief description\"}}]\n", optional=True)NEWLINENEWLINE return CommandDesc('mint', 'mint tokens from a contract', [p1, p2, p3, p4, p5, p6])NEWLINENEWLINENEWLINEclass CommandTokenRegister(CommandBase):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 2:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINENEWLINE token_str = arguments[0]NEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE register_addr = arguments[1:]NEWLINE addr_list = []NEWLINE for addr in register_addr:NEWLINE if isValidPublicAddress(addr):NEWLINE addr_list.append(addr)NEWLINE else:NEWLINE print(f"{addr} is not a valid address")NEWLINE return FalseNEWLINENEWLINE p_fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE p_fee = priority_feeNEWLINE if p_fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE tx, fee, results = token.CrowdsaleRegister(wallet, addr_list)NEWLINENEWLINE if tx is not None and results is not None:NEWLINE if len(results) > 0 and results[0].GetBigInteger() > 0:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print("[%s] Will register addresses for crowdsale: %s " % (token.symbol, register_addr))NEWLINE print("Invocation Fee: %s " % (fee.value / Fixed8.D))NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Invocation Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Registration cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeContract(wallet, tx, comb_fee)NEWLINENEWLINE print("Could not register address(es)")NEWLINE return FalseNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('addresses', 'space separated list of NEO addresses')NEWLINE p3 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINE return CommandDesc('register', 'register for a crowd sale', [p1, p2, p3])NEWLINENEWLINENEWLINEdef _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount):NEWLINE """NEWLINE A helper function to validate common arguments used in NEP-5 functionsNEWLINENEWLINE Args:NEWLINE wallet (Wallet): a UserWallet instanceNEWLINE token_str (str): symbol name or script_hashNEWLINE from_addr (str): a wallet addressNEWLINE to_addr (str): a wallet addressNEWLINE amount (float): the number of tokens to sendNEWLINENEWLINE Raises:NEWLINE ValueError: for invalid argumentsNEWLINENEWLINE Returns:NEWLINE token (NEP5Token): instanceNEWLINE """NEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError:NEWLINE raiseNEWLINENEWLINE if not isValidPublicAddress(from_addr):NEWLINE raise ValueError("send_from is not a valid address")NEWLINENEWLINE if not isValidPublicAddress(to_addr):NEWLINE raise ValueError("send_to is not a valid address")NEWLINENEWLINE try:NEWLINE # internally this function uses the `Decimal` class which will parse the float amount to its required format.NEWLINE # the name is a bit misleading /shrugNEWLINE amount = amount_from_string(token, amount)NEWLINE except Exception:NEWLINE raise ValueError(f"{amount} is not a valid amount")NEWLINENEWLINE return tokenNEWLINENEWLINENEWLINEdef token_send(wallet, token_str, from_addr, to_addr, amount, fee=Fixed8.Zero(), user_tx_attributes=None):NEWLINE """NEWLINE Send `amount` of tokens from `from_addr` to `to_addr`NEWLINENEWLINE Args:NEWLINE wallet (Wallet): a UserWallet instanceNEWLINE token_str (str): symbol name or script_hashNEWLINE from_addr (str): a wallet addressNEWLINE to_addr (str): a wallet addressNEWLINE amount (float): the number of tokens to sendNEWLINE fee (Fixed8): (optional) a fee to give the transaction priority (> 0.001) NEWLINE user_tx_attributes (list): a list of ``TransactionAttribute``s.NEWLINENEWLINE Raises:NEWLINE ValueError: for invalid argumentsNEWLINENEWLINE Returns:NEWLINE a Transaction object if successful, False otherwise.NEWLINE """NEWLINE if not user_tx_attributes:NEWLINE user_tx_attributes = []NEWLINENEWLINE try:NEWLINE token = _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount)NEWLINE except ValueError:NEWLINE # just making it explicit for the readerNEWLINE raiseNEWLINENEWLINE for attr in user_tx_attributes:NEWLINE if not isinstance(attr, TransactionAttribute):NEWLINE raise ValueError(f"{attr} is not a valid transaction attribute")NEWLINENEWLINE decimal_amount = amount_from_string(token, amount)NEWLINENEWLINE return do_token_transfer(token, wallet, from_addr, to_addr, decimal_amount, fee=fee, tx_attributes=user_tx_attributes)NEWLINENEWLINENEWLINEdef test_token_send_from(wallet, token_str, from_addr, to_addr, amount):NEWLINE """NEWLINE Test sending funds from `addr_from` to `addr_to` without commiting to the network.NEWLINENEWLINE This does a local test to validate all supplied arguments and if the blockchain state allows for the transfer.NEWLINENEWLINE Args:NEWLINE wallet (Wallet): a UserWallet instanceNEWLINE token_str (str): symbol name or script_hashNEWLINE from_addr (str): a wallet addressNEWLINE to_addr (str): a wallet addressNEWLINE amount (float): the number of tokens to sendNEWLINENEWLINE Raises:NEWLINE ValueError: for invalid arguments or if allowance is insufficient.NEWLINENEWLINE Returns:NEWLINE tuple:NEWLINE token (NEP5Token): instanceNEWLINE InvocationTransaction: the transaction.NEWLINE int: the transaction fee.NEWLINE list: the neo VM evaluation stack results.NEWLINE """NEWLINE try:NEWLINE token = _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount)NEWLINE allowance = token_get_allowance(wallet, token_str, from_addr, to_addr, verbose=False)NEWLINENEWLINE if allowance < amount:NEWLINE raise ValueError(f"Insufficient allowance: {allowance}")NEWLINE except ValueError:NEWLINE # bad args or allowanceNEWLINE raiseNEWLINENEWLINE tx, fees, results = token.TransferFrom(wallet, from_addr, to_addr, amount)NEWLINE return token, tx, fees, resultsNEWLINENEWLINENEWLINEdef token_get_allowance(wallet, token_str, from_addr, to_addr, verbose=False):NEWLINE """NEWLINE Query the smart contract for the amount from_addr is allowed to send to to_addrNEWLINENEWLINE Requires amount to be `approved`.NEWLINENEWLINE Args:NEWLINE wallet (Wallet): a UserWallet instanceNEWLINE token_str (str): symbol name or script_hashNEWLINE from_addr (str): a wallet addressNEWLINE to_addr (str): a wallet addressNEWLINE verbose (bool): flag indicating whether to print VM resultsNEWLINENEWLINE Raises:NEWLINE ValueError: for invalid arguments or if allowance could not be queriedNEWLINENEWLINE Returns:NEWLINE int: allowanceNEWLINE """NEWLINE try:NEWLINE token = _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount=0)NEWLINE except ValueError:NEWLINE raiseNEWLINENEWLINE tx, fee, results = token.Allowance(wallet, from_addr, to_addr)NEWLINENEWLINE if tx is not None and results is not None:NEWLINE allowance = results[0].GetBigInteger()NEWLINE if verbose:NEWLINE print("%s allowance for %s from %s : %s " % (token.symbol, from_addr, to_addr, allowance))NEWLINENEWLINE return allowanceNEWLINE else:NEWLINE if verbose:NEWLINE print("Could not get allowance for token %s " % token.symbol)NEWLINE raise ValueError(f"Could not get allowance for token {token.symbol}")NEWLINENEWLINENEWLINEdef token_mint(token, wallet, to_addr, asset_attachments=[], fee=Fixed8.Zero(), invoke_attrs=None):NEWLINE if not invoke_attrs:NEWLINE invoke_attrs = []NEWLINENEWLINE p_fee = feeNEWLINENEWLINE tx, fee, results = token.Mint(wallet, to_addr, asset_attachments, invoke_attrs=invoke_attrs)NEWLINENEWLINE if tx is not None and results is not None:NEWLINE if len(results) > 0 and results[0] is not None:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print(f"[{token.symbol}] Will mint tokens to address: {to_addr}")NEWLINE print(f"Invocation Fee: {fee.value / Fixed8.D}")NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Invocation Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Token mint cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeWithTokenVerificationScript(wallet, tx, token, comb_fee, invoke_attrs=invoke_attrs)NEWLINENEWLINE print("Failed to mint tokens")NEWLINE return FalseNEWLINENEWLINENEWLINEdef do_token_transfer(token, wallet, from_address, to_address, amount, fee=Fixed8.Zero(), tx_attributes=None):NEWLINE if not tx_attributes:NEWLINE tx_attributes = []NEWLINENEWLINE p_fee = feeNEWLINENEWLINE # because we cannot differentiate between a normal and multisig from_addr, and because we want to makeNEWLINE # sending NEP5 tokens straight forward even when sending from multisig addresses, we include the script_hashNEWLINE # for verification by default to the transaction attributes. See PR/Issue: https://github.com/CityOfZion/neo-python/pull/491NEWLINE from_script_hash = binascii.unhexlify(bytes(wallet.ToScriptHash(from_address).ToString2(), 'utf-8'))NEWLINE tx_attributes.append(TransactionAttribute(usage=TransactionAttributeUsage.Script, data=from_script_hash))NEWLINENEWLINE tx, fee, results = token.Transfer(wallet, from_address, to_address, amount, tx_attributes=tx_attributes)NEWLINENEWLINE if tx is not None and results is not None and len(results) > 0:NEWLINENEWLINE if results[0].GetBigInteger() == 1:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print("Will transfer %s %s from %s to %s" % (string_from_amount(token, amount), token.symbol, from_address, to_address))NEWLINE print("Transfer fee: %s " % (fee.value / Fixed8.D))NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Transfer Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Transfer cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeContract(wallet, tx, comb_fee)NEWLINENEWLINE print("could not transfer tokens")NEWLINE return FalseNEWLINENEWLINENEWLINEdef token_history(wallet, token_str):NEWLINE notification_db = NotificationDB.instance()NEWLINENEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError:NEWLINE raiseNEWLINENEWLINE events = notification_db.get_by_contract(token.ScriptHash)NEWLINE return token, eventsNEWLINENEWLINENEWLINEdef amount_from_string(token, amount_str):NEWLINE precision_mult = pow(10, token.decimals)NEWLINE amount = Decimal(amount_str) * precision_multNEWLINENEWLINE return int(amount)NEWLINENEWLINENEWLINEdef string_from_amount(token, amount):NEWLINE precision_mult = pow(10, token.decimals)NEWLINE amount = Decimal(amount) / Decimal(precision_mult)NEWLINE formatter_str = '.%sf' % token.decimalsNEWLINE amount_str = format(amount, formatter_str)NEWLINENEWLINE return amount_strNEWLINE # Copyright 2019, Google LLC.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINEimport collectionsNEWLINENEWLINEfrom absl.testing import parameterizedNEWLINEimport tensorflow as tfNEWLINENEWLINEfrom tensorflow_federated.python.core.backends.native import execution_contextsNEWLINEfrom tensorflow_federated.python.simulation.baselines import client_specNEWLINEfrom tensorflow_federated.python.simulation.baselines.stackoverflow import word_prediction_preprocessingNEWLINENEWLINENEWLINETEST_DATA = collections.OrderedDict(NEWLINE creation_date=(['unused date']),NEWLINE score=([tf.constant(0, dtype=tf.int64)]),NEWLINE tags=(['unused test tag']),NEWLINE title=(['unused title']),NEWLINE tokens=(['one must imagine']),NEWLINE type=(['unused type']),NEWLINE)NEWLINENEWLINENEWLINEdef _compute_length_of_dataset(ds):NEWLINE return ds.reduce(0, lambda x, _: x + 1)NEWLINENEWLINENEWLINEclass SplitInputTest(tf.test.TestCase):NEWLINENEWLINE def test_split_input_returns_expected_result(self):NEWLINE tokens = tf.constant([[0, 1, 2, 3, 4]], dtype=tf.int64)NEWLINE expected_input = [[0, 1, 2, 3]]NEWLINE expected_target = [[1, 2, 3, 4]]NEWLINE split = word_prediction_preprocessing.split_input_target(tokens)NEWLINE self.assertAllEqual(self.evaluate(split[0]), expected_input)NEWLINE self.assertAllEqual(self.evaluate(split[1]), expected_target)NEWLINENEWLINENEWLINEclass ToIDsFnTest(tf.test.TestCase):NEWLINENEWLINE def test_ids_fn_truncates_on_input_longer_than_sequence_length(self):NEWLINE vocab = ['A', 'B', 'C']NEWLINE max_seq_len = 1NEWLINE bos = word_prediction_preprocessing.get_special_tokens(NEWLINE len(vocab)).beginning_of_sentenceNEWLINE to_ids_fn = word_prediction_preprocessing.build_to_ids_fn(NEWLINE vocab, max_seq_len)NEWLINE data = {'tokens': 'A B C'}NEWLINE processed = to_ids_fn(data)NEWLINE self.assertAllEqual(self.evaluate(processed), [bos, 1])NEWLINENEWLINE def test_build_to_ids_fn_embeds_all_vocab(self):NEWLINE vocab = ['A', 'B', 'C']NEWLINE max_seq_len = 5NEWLINE special_tokens = word_prediction_preprocessing.get_special_tokens(NEWLINE len(vocab))NEWLINE bos = special_tokens.beginning_of_sentenceNEWLINE eos = special_tokens.end_of_sentenceNEWLINE to_ids_fn = word_prediction_preprocessing.build_to_ids_fn(NEWLINE vocab, max_seq_len)NEWLINE data = {'tokens': 'A B C'}NEWLINE processed = to_ids_fn(data)NEWLINE self.assertAllEqual(self.evaluate(processed), [bos, 1, 2, 3, eos])NEWLINENEWLINE def test_pad_token_correct(self):NEWLINE vocab = ['A', 'B', 'C']NEWLINE max_seq_len = 5NEWLINE to_ids_fn = word_prediction_preprocessing.build_to_ids_fn(NEWLINE vocab, max_seq_len)NEWLINE special_tokens = word_prediction_preprocessing.get_special_tokens(NEWLINE len(vocab))NEWLINE pad = special_tokens.paddingNEWLINE bos = special_tokens.beginning_of_sentenceNEWLINE eos = special_tokens.end_of_sentenceNEWLINE data = {'tokens': 'A B C'}NEWLINE processed = to_ids_fn(data)NEWLINE batched_ds = tf.data.Dataset.from_tensor_slices([processed]).padded_batch(NEWLINE 1, padded_shapes=[6])NEWLINE sample_elem = next(iter(batched_ds))NEWLINE self.assertAllEqual(self.evaluate(sample_elem), [[bos, 1, 2, 3, eos, pad]])NEWLINENEWLINE def test_out_of_vocab_tokens_are_correct(self):NEWLINE vocab = ['A', 'B', 'C']NEWLINE max_seq_len = 5NEWLINE num_out_of_vocab_buckets = 2NEWLINE to_ids_fn = word_prediction_preprocessing.build_to_ids_fn(NEWLINE vocab, max_seq_len, num_out_of_vocab_buckets=num_out_of_vocab_buckets)NEWLINE out_of_vocab_tokens = word_prediction_preprocessing.get_special_tokens(NEWLINE len(vocab),NEWLINE num_out_of_vocab_buckets=num_out_of_vocab_buckets).out_of_vocabNEWLINE data = {'tokens': 'A B D'}NEWLINE processed = to_ids_fn(data)NEWLINE self.assertLen(out_of_vocab_tokens, num_out_of_vocab_buckets)NEWLINE self.assertIn(self.evaluate(processed)[3], out_of_vocab_tokens)NEWLINENEWLINENEWLINEclass BatchAndSplitTest(tf.test.TestCase):NEWLINENEWLINE def test_batch_and_split_fn_returns_dataset_with_correct_type_spec(self):NEWLINE token = tf.constant([[0, 1, 2, 3, 4]], dtype=tf.int64)NEWLINE ds = tf.data.Dataset.from_tensor_slices(token)NEWLINE padded_and_batched = word_prediction_preprocessing.batch_and_split(NEWLINE ds, sequence_length=6, batch_size=1)NEWLINE self.assertIsInstance(padded_and_batched, tf.data.Dataset)NEWLINE self.assertEqual(padded_and_batched.element_spec, (tf.TensorSpec(NEWLINE [None, 6], dtype=tf.int64), tf.TensorSpec([None, 6], dtype=tf.int64)))NEWLINENEWLINE def test_batch_and_split_fn_returns_dataset_yielding_expected_elements(self):NEWLINE token = tf.constant([[0, 1, 2, 3, 4]], dtype=tf.int64)NEWLINE ds = tf.data.Dataset.from_tensor_slices(token)NEWLINE padded_and_batched = word_prediction_preprocessing.batch_and_split(NEWLINE ds, sequence_length=6, batch_size=1)NEWLINE num_elems = 0NEWLINE for elem in padded_and_batched:NEWLINE self.assertAllEqual(NEWLINE self.evaluate(elem[0]),NEWLINE tf.constant([[0, 1, 2, 3, 4, 0]], dtype=tf.int64))NEWLINE self.assertAllEqual(NEWLINE self.evaluate(elem[1]),NEWLINE tf.constant([[1, 2, 3, 4, 0, 0]], dtype=tf.int64))NEWLINE num_elems += 1NEWLINE self.assertEqual(num_elems, 1)NEWLINENEWLINENEWLINEclass PreprocessFnTest(tf.test.TestCase, parameterized.TestCase):NEWLINENEWLINE def test_preprocess_fn_with_empty_vocab_raises(self):NEWLINE preprocess_spec = client_spec.ClientSpec(num_epochs=1, batch_size=1)NEWLINE with self.assertRaisesRegex(ValueError, 'vocab must be non-empty'):NEWLINE word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec, vocab=[], sequence_length=10)NEWLINENEWLINE @parameterized.named_parameters(('zero_value', 0), ('negative_value1', -1),NEWLINE ('negative_value2', -2))NEWLINE def test_nonpositive_sequence_length_raises(self, sequence_length):NEWLINE del sequence_length # Unused.NEWLINE preprocess_spec = client_spec.ClientSpec(num_epochs=1, batch_size=1)NEWLINE with self.assertRaisesRegex(ValueError,NEWLINE 'sequence_length must be a positive integer'):NEWLINE word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec, vocab=['A'], sequence_length=0)NEWLINENEWLINE @parameterized.named_parameters(('zero_value', 0), ('negative_value1', -1),NEWLINE ('negative_value2', -2))NEWLINE def test_nonpositive_num_out_of_vocab_buckets_length_raises(NEWLINE self, num_out_of_vocab_buckets):NEWLINE preprocess_spec = client_spec.ClientSpec(num_epochs=1, batch_size=1)NEWLINE with self.assertRaisesRegex(NEWLINE ValueError, 'num_out_of_vocab_buckets must be a positive integer'):NEWLINE word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec,NEWLINE vocab=['A'],NEWLINE sequence_length=10,NEWLINE num_out_of_vocab_buckets=num_out_of_vocab_buckets)NEWLINENEWLINE @parameterized.named_parameters(('param1', 1, 1), ('param2', 4, 2),NEWLINE ('param3', 100, 3))NEWLINE def test_preprocess_fn_returns_correct_dataset_element_spec(NEWLINE self, sequence_length, num_out_of_vocab_buckets):NEWLINE ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)NEWLINE preprocess_spec = client_spec.ClientSpec(NEWLINE num_epochs=1, batch_size=32, max_elements=100)NEWLINE preprocess_fn = word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec,NEWLINE sequence_length=sequence_length,NEWLINE vocab=['one', 'must'],NEWLINE num_out_of_vocab_buckets=num_out_of_vocab_buckets)NEWLINE preprocessed_ds = preprocess_fn(ds)NEWLINE self.assertEqual(NEWLINE preprocessed_ds.element_spec,NEWLINE (tf.TensorSpec(shape=[None, sequence_length], dtype=tf.int64),NEWLINE tf.TensorSpec(shape=[None, sequence_length], dtype=tf.int64)))NEWLINENEWLINE def test_preprocess_fn_returns_correct_sequence_with_1_out_of_vocab_bucket(NEWLINE self):NEWLINE ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)NEWLINE preprocess_spec = client_spec.ClientSpec(NEWLINE num_epochs=1, batch_size=32, max_elements=100)NEWLINE preprocess_fn = word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec,NEWLINE sequence_length=6,NEWLINE vocab=['one', 'must'],NEWLINE num_out_of_vocab_buckets=1)NEWLINENEWLINE preprocessed_ds = preprocess_fn(ds)NEWLINE element = next(iter(preprocessed_ds))NEWLINENEWLINE # BOS is len(vocab)+2, EOS is len(vocab)+3, pad is 0, OOV is len(vocab)+1NEWLINE self.assertAllEqual(NEWLINE self.evaluate(element[0]),NEWLINE tf.constant([[4, 1, 2, 3, 5, 0]], dtype=tf.int64))NEWLINENEWLINE def test_preprocess_fn_returns_correct_sequence_with_3_out_of_vocab_buckets(NEWLINE self):NEWLINE ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)NEWLINE preprocess_spec = client_spec.ClientSpec(NEWLINE num_epochs=1, batch_size=32, max_elements=100)NEWLINE preprocess_fn = word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec,NEWLINE sequence_length=6,NEWLINE vocab=['one', 'must'],NEWLINE num_out_of_vocab_buckets=3)NEWLINE preprocessed_ds = preprocess_fn(ds)NEWLINE element = next(iter(preprocessed_ds))NEWLINE # BOS is len(vocab)+3+1NEWLINE self.assertEqual(self.evaluate(element[0])[0][0], 6)NEWLINE self.assertEqual(self.evaluate(element[0])[0][1], 1)NEWLINE self.assertEqual(self.evaluate(element[0])[0][2], 2)NEWLINE # OOV is [len(vocab)+1, len(vocab)+2, len(vocab)+3]NEWLINE self.assertIn(self.evaluate(element[0])[0][3], [3, 4, 5])NEWLINE # EOS is len(vocab)+3+2NEWLINE self.assertEqual(self.evaluate(element[0])[0][4], 7)NEWLINE # pad is 0NEWLINE self.assertEqual(self.evaluate(element[0])[0][5], 0)NEWLINENEWLINE @parameterized.named_parameters(NEWLINE ('num_epochs_1_batch_size_1', 1, 1),NEWLINE ('num_epochs_4_batch_size_2', 4, 2),NEWLINE ('num_epochs_9_batch_size_3', 9, 3),NEWLINE ('num_epochs_12_batch_size_1', 12, 1),NEWLINE ('num_epochs_3_batch_size_5', 3, 5),NEWLINE ('num_epochs_7_batch_size_2', 7, 2),NEWLINE )NEWLINE def test_ds_length_is_ceil_num_epochs_over_batch_size(self, num_epochs,NEWLINE batch_size):NEWLINE ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)NEWLINE preprocess_spec = client_spec.ClientSpec(NEWLINE num_epochs=num_epochs, batch_size=batch_size)NEWLINE preprocess_fn = word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec, vocab=['A'], sequence_length=10)NEWLINE preprocessed_ds = preprocess_fn(ds)NEWLINE self.assertEqual(NEWLINE _compute_length_of_dataset(preprocessed_ds),NEWLINE tf.cast(tf.math.ceil(num_epochs / batch_size), tf.int32))NEWLINENEWLINE @parameterized.named_parameters(NEWLINE ('max_elements1', 1),NEWLINE ('max_elements3', 3),NEWLINE ('max_elements7', 7),NEWLINE ('max_elements11', 11),NEWLINE ('max_elements18', 18),NEWLINE )NEWLINE def test_ds_length_with_max_elements(self, max_elements):NEWLINE repeat_size = 10NEWLINE ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)NEWLINE preprocess_spec = client_spec.ClientSpec(NEWLINE num_epochs=repeat_size, batch_size=1, max_elements=max_elements)NEWLINE preprocess_fn = word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec, vocab=['A'])NEWLINE preprocessed_ds = preprocess_fn(ds)NEWLINE self.assertEqual(NEWLINE _compute_length_of_dataset(preprocessed_ds),NEWLINE min(repeat_size, max_elements))NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE execution_contexts.set_local_python_execution_context()NEWLINE tf.test.main()NEWLINE # Copyright (c) 2017-2019 Uber Technologies, Inc.NEWLINE# SPDX-License-Identifier: Apache-2.0NEWLINENEWLINE"""NEWLINEThis example demonstrates how to use the Causal Effect Variational AutoencoderNEWLINE[1] implemented in pyro.contrib.cevae.CEVAE, documented atNEWLINEhttp://docs.pyro.ai/en/latest/contrib.cevae.htmlNEWLINENEWLINE**References**NEWLINENEWLINE[1] C. Louizos, U. Shalit, J. Mooij, D. Sontag, R. Zemel, M. Welling (2017).NEWLINE Causal Effect Inference with Deep Latent-Variable Models.NEWLINE http://papers.nips.cc/paper/7223-causal-effect-inference-with-deep-latent-variable-models.pdfNEWLINE https://github.com/AMLab-Amsterdam/CEVAENEWLINE"""NEWLINEimport argparseNEWLINEimport loggingNEWLINENEWLINEimport torchNEWLINENEWLINEimport pyroNEWLINEimport pyro.distributions as distNEWLINEfrom pyro.contrib.cevae import CEVAENEWLINENEWLINElogging.getLogger("pyro").setLevel(logging.DEBUG)NEWLINElogging.getLogger("pyro").handlers[0].setLevel(logging.DEBUG)NEWLINENEWLINENEWLINEdef generate_data(args):NEWLINE """NEWLINE This implements the generative process of [1], but using larger feature andNEWLINE latent spaces ([1] assumes ``feature_dim=1`` and ``latent_dim=5``).NEWLINE """NEWLINE z = dist.Bernoulli(0.5).sample([args.num_data])NEWLINE x = dist.Normal(z, 5 * z + 3 * (1 - z)).sample([args.feature_dim]).t()NEWLINE t = dist.Bernoulli(0.75 * z + 0.25 * (1 - z)).sample()NEWLINE y = dist.Bernoulli(logits=3 * (z + 2 * (2 * t - 2))).sample()NEWLINENEWLINE # Compute true ite for evaluation (via Monte Carlo approximation).NEWLINE t0_t1 = torch.tensor([[0.], [1.]])NEWLINE y_t0, y_t1 = dist.Bernoulli(logits=3 * (z + 2 * (2 * t0_t1 - 2))).meanNEWLINE true_ite = y_t1 - y_t0NEWLINE return x, t, y, true_iteNEWLINENEWLINENEWLINEdef main(args):NEWLINE pyro.enable_validation(__debug__)NEWLINE if args.cuda:NEWLINE torch.set_default_tensor_type('torch.cuda.FloatTensor')NEWLINENEWLINE # Generate synthetic data.NEWLINE pyro.set_rng_seed(args.seed)NEWLINE x_train, t_train, y_train, _ = generate_data(args)NEWLINENEWLINE # Train.NEWLINE pyro.set_rng_seed(args.seed)NEWLINE pyro.clear_param_store()NEWLINE cevae = CEVAE(feature_dim=args.feature_dim,NEWLINE latent_dim=args.latent_dim,NEWLINE hidden_dim=args.hidden_dim,NEWLINE num_layers=args.num_layers,NEWLINE num_samples=10)NEWLINE cevae.fit(x_train, t_train, y_train,NEWLINE num_epochs=args.num_epochs,NEWLINE batch_size=args.batch_size,NEWLINE learning_rate=args.learning_rate,NEWLINE learning_rate_decay=args.learning_rate_decay,NEWLINE weight_decay=args.weight_decay)NEWLINENEWLINE # Evaluate.NEWLINE x_test, t_test, y_test, true_ite = generate_data(args)NEWLINE true_ate = true_ite.mean()NEWLINE print("true ATE = {:0.3g}".format(true_ate.item()))NEWLINE naive_ate = y_test[t_test == 1].mean() - y_test[t_test == 0].mean()NEWLINE print("naive ATE = {:0.3g}".format(naive_ate))NEWLINE if args.jit:NEWLINE cevae = cevae.to_script_module()NEWLINE est_ite = cevae.ite(x_test)NEWLINE est_ate = est_ite.mean()NEWLINE print("estimated ATE = {:0.3g}".format(est_ate.item()))NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE assert pyro.__version__.startswith('1.5.0')NEWLINE parser = argparse.ArgumentParser(description="Causal Effect Variational Autoencoder")NEWLINE parser.add_argument("--num-data", default=1000, type=int)NEWLINE parser.add_argument("--feature-dim", default=5, type=int)NEWLINE parser.add_argument("--latent-dim", default=20, type=int)NEWLINE parser.add_argument("--hidden-dim", default=200, type=int)NEWLINE parser.add_argument("--num-layers", default=3, type=int)NEWLINE parser.add_argument("-n", "--num-epochs", default=50, type=int)NEWLINE parser.add_argument("-b", "--batch-size", default=100, type=int)NEWLINE parser.add_argument("-lr", "--learning-rate", default=1e-3, type=float)NEWLINE parser.add_argument("-lrd", "--learning-rate-decay", default=0.1, type=float)NEWLINE parser.add_argument("--weight-decay", default=1e-4, type=float)NEWLINE parser.add_argument("--seed", default=1234567890, type=int)NEWLINE parser.add_argument("--jit", action="store_true")NEWLINE parser.add_argument("--cuda", action="store_true")NEWLINE args = parser.parse_args()NEWLINE main(args)NEWLINE """Config Flow for PlayStation 4."""NEWLINEfrom collections import OrderedDictNEWLINEimport loggingNEWLINENEWLINEimport voluptuous as volNEWLINENEWLINEfrom homeassistant import config_entriesNEWLINEfrom homeassistant.components.ps4.const import (NEWLINE DEFAULT_NAME, DEFAULT_REGION, DOMAIN, REGIONS)NEWLINEfrom homeassistant.const import (NEWLINE CONF_CODE, CONF_HOST, CONF_IP_ADDRESS, CONF_NAME, CONF_REGION, CONF_TOKEN)NEWLINENEWLINE_LOGGER = logging.getLogger(__name__)NEWLINENEWLINEUDP_PORT = 987NEWLINETCP_PORT = 997NEWLINEPORT_MSG = {UDP_PORT: 'port_987_bind_error', TCP_PORT: 'port_997_bind_error'}NEWLINENEWLINENEWLINE@config_entries.HANDLERS.register(DOMAIN)NEWLINEclass PlayStation4FlowHandler(config_entries.ConfigFlow):NEWLINE """Handle a PlayStation 4 config flow."""NEWLINENEWLINE VERSION = 1NEWLINE CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLLNEWLINENEWLINE def __init__(self):NEWLINE """Initialize the config flow."""NEWLINE from pyps4_homeassistant import HelperNEWLINENEWLINE self.helper = Helper()NEWLINE self.creds = NoneNEWLINE self.name = NoneNEWLINE self.host = NoneNEWLINE self.region = NoneNEWLINE self.pin = NoneNEWLINENEWLINE async def async_step_user(self, user_input=None):NEWLINE """Handle a user config flow."""NEWLINE # Check if able to bind to ports: UDP 987, TCP 997.NEWLINE ports = PORT_MSG.keys()NEWLINE failed = await self.hass.async_add_executor_job(NEWLINE self.helper.port_bind, ports)NEWLINE if failed in ports:NEWLINE reason = PORT_MSG[failed]NEWLINE return self.async_abort(reason=reason)NEWLINE # Skip Creds Step if a device is configured.NEWLINE if self.hass.config_entries.async_entries(DOMAIN):NEWLINE return await self.async_step_link()NEWLINE return await self.async_step_creds()NEWLINENEWLINE async def async_step_creds(self, user_input=None):NEWLINE """Return PS4 credentials from 2nd Screen App."""NEWLINE if user_input is not None:NEWLINE self.creds = await self.hass.async_add_executor_job(NEWLINE self.helper.get_creds)NEWLINENEWLINE if self.creds is not None:NEWLINE return await self.async_step_link()NEWLINE return self.async_abort(reason='credential_error')NEWLINENEWLINE return self.async_show_form(NEWLINE step_id='creds')NEWLINENEWLINE async def async_step_link(self, user_input=None):NEWLINE """Prompt user input. Create or edit entry."""NEWLINE errors = {}NEWLINENEWLINE # Search for device.NEWLINE devices = await self.hass.async_add_executor_job(NEWLINE self.helper.has_devices)NEWLINENEWLINE # Abort if can't find device.NEWLINE if not devices:NEWLINE return self.async_abort(reason='no_devices_found')NEWLINENEWLINE device_list = [NEWLINE device['host-ip'] for device in devices]NEWLINENEWLINE # If entry exists check that devices found aren't configured.NEWLINE if self.hass.config_entries.async_entries(DOMAIN):NEWLINE for entry in self.hass.config_entries.async_entries(DOMAIN):NEWLINE conf_devices = entry.data['devices']NEWLINE for c_device in conf_devices:NEWLINE if c_device['host'] in device_list:NEWLINE # Remove configured device from search list.NEWLINE device_list.remove(c_device['host'])NEWLINE # If list is empty then all devices are configured.NEWLINE if not device_list:NEWLINE return self.async_abort(reason='devices_configured')NEWLINENEWLINE # Login to PS4 with user data.NEWLINE if user_input is not None:NEWLINE self.region = user_input[CONF_REGION]NEWLINE self.name = user_input[CONF_NAME]NEWLINE self.pin = user_input[CONF_CODE]NEWLINE self.host = user_input[CONF_IP_ADDRESS]NEWLINENEWLINE is_ready, is_login = await self.hass.async_add_executor_job(NEWLINE self.helper.link, self.host, self.creds, self.pin)NEWLINENEWLINE if is_ready is False:NEWLINE errors['base'] = 'not_ready'NEWLINE elif is_login is False:NEWLINE errors['base'] = 'login_failed'NEWLINE else:NEWLINE device = {NEWLINE CONF_HOST: self.host,NEWLINE CONF_NAME: self.name,NEWLINE CONF_REGION: self.regionNEWLINE }NEWLINENEWLINE # Create entry.NEWLINE return self.async_create_entry(NEWLINE title='PlayStation 4',NEWLINE data={NEWLINE CONF_TOKEN: self.creds,NEWLINE 'devices': [device],NEWLINE },NEWLINE )NEWLINENEWLINE # Show User Input form.NEWLINE link_schema = OrderedDict()NEWLINE link_schema[vol.Required(CONF_IP_ADDRESS)] = vol.In(list(device_list))NEWLINE link_schema[vol.Required(NEWLINE CONF_REGION, default=DEFAULT_REGION)] = vol.In(list(REGIONS))NEWLINE link_schema[vol.Required(CONF_CODE)] = strNEWLINE link_schema[vol.Required(CONF_NAME, default=DEFAULT_NAME)] = strNEWLINENEWLINE return self.async_show_form(NEWLINE step_id='link',NEWLINE data_schema=vol.Schema(link_schema),NEWLINE errors=errors,NEWLINE )NEWLINE from .. import fstNEWLINENEWLINENEWLINEdef fstFromDict(initDict):NEWLINE """NEWLINE fstInitMealy = {NEWLINE 'initState': 'S0',NEWLINE 'inAlphabet': ( 0, 1, ),NEWLINE 'transition': { 'S0': ( 'S1', 'S0', ),NEWLINE 'S1': ( 'S1', 'S0', ), },NEWLINE 'outputMealy':{ 'S0': ( 0, 0, ),NEWLINE 'S1': ( 0, 1, ), },NEWLINE }NEWLINE fstInitMoore = {NEWLINE 'initState': 'S0',NEWLINE 'inAlphabet': ( 0, 1, ),NEWLINE 'transition': { 'S0': ( 'S1', 'S0', ),NEWLINE 'S1': ( 'S1', 'S0', ), },NEWLINE 'outputMoore':{ 'S0':2, 'S1':3, },NEWLINE }NEWLINE fsaInit = {NEWLINE 'initState': 'S0',NEWLINE 'finalStates': ('S1', 'S3'),NEWLINE 'inAlphabet': ( 0, 1, None, ),NEWLINE 'transition': { 'S0': ( None, None, ('S1', 'S3', ), ),NEWLINE 'S1': ( 'S2', 'S1', None, ),NEWLINE 'S2': ( 'S1', 'S2', None, ),NEWLINE 'S3': ( 'S3', 'S4', None, ),NEWLINE 'S4': ( 'S4', 'S3', None, ),NEWLINE },NEWLINE }NEWLINENEWLINE """NEWLINE initState = initDict['initState']NEWLINE inAlphabet = initDict['inAlphabet']NEWLINE transitionFunc = list()NEWLINE isMealy = 'outputMealy' in initDictNEWLINE isMoore = 'outputMoore' in initDictNEWLINE if isMealy or isMoore:NEWLINE outputFunc = list()NEWLINE for st, stNextTuple in initDict['transition'].items():NEWLINE if isMoore:NEWLINE outputFunc.append([st, initDict['outputMoore'][st]])NEWLINE else:NEWLINE for inSig, outSig in zip(inAlphabet, initDict['outputMealy'][st]):NEWLINE outputFunc.append([st, inSig, outSig])NEWLINE for inSig, stNext in zip(inAlphabet, stNextTuple):NEWLINE transitionFunc.append([st, inSig, stNext])NEWLINE return fst(initState=initState,NEWLINE transitionFunction=transitionFunc,NEWLINE outputFunction=outputFunc)NEWLINE if 'finalStates' in initDict:NEWLINE finalStates = initDict['finalStates']NEWLINE for st, stNextTuple in initDict['transition'].items():NEWLINE for inSig, stNext in zip(inAlphabet, stNextTuple):NEWLINE if isinstance(stNext, (tuple,)):NEWLINE for stN in stNext:NEWLINE transitionFunc.append([st, inSig, stN])NEWLINE else:NEWLINE transitionFunc.append([st, inSig, stNext])NEWLINE return fst(initState=initState,NEWLINE transitionFunction=transitionFunc,NEWLINE finalStates=finalStates)NEWLINE import torchNEWLINEimport loggingNEWLINENEWLINEimport models.modules.UNet_arch as UNet_archNEWLINElogger = logging.getLogger('base')NEWLINENEWLINENEWLINE####################NEWLINE# define networkNEWLINE####################NEWLINE#### GeneratorNEWLINEdef define_G(opt):NEWLINE opt_net = opt['network_G']NEWLINE which_model = opt_net['which_model_G']NEWLINENEWLINE if which_model == 'HDRUNet':NEWLINE netG = UNet_arch.HDRUNet(in_nc=opt_net['in_nc'], out_nc=opt_net['out_nc'], nf=opt_net['nf'], act_type=opt_net['act_type'])NEWLINE else:NEWLINE raise NotImplementedError('Generator model [{:s}] not recognized'.format(which_model))NEWLINE return netG """Auto-generated file, do not edit by hand. 81 metadata"""NEWLINEfrom ..phonemetadata import NumberFormatNEWLINENEWLINEPHONE_ALT_FORMAT_81 = [NumberFormat(pattern='(\\d{3})(\\d{2})(\\d{4})', format=u'\\1-\\2-\\3', leading_digits_pattern=['(?:12|57|99)0']), NumberFormat(pattern='(\\d{3})(\\d{2})(\\d{2})(\\d{2})', format=u'\\1-\\2-\\3-\\4', leading_digits_pattern=['(?:12|57|99)0']), NumberFormat(pattern='(\\d{3})(\\d{4})(\\d{2})', format=u'\\1-\\2-\\3', leading_digits_pattern=['(?:12|57|99)0'])]NEWLINE """This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.NEWLINE"""NEWLINE"""NEWLINEDjango Base settings for Label Studio.NEWLINENEWLINEFor more information on this file, seeNEWLINEhttps://docs.djangoproject.com/en/3.1/topics/settings/NEWLINENEWLINEFor the full list of settings and their values, seeNEWLINEhttps://docs.djangoproject.com/en/3.1/ref/settings/NEWLINE"""NEWLINEimport osNEWLINEimport reNEWLINEimport loggingNEWLINENEWLINE# for printing messages before main logging config appliedNEWLINEif not logging.getLogger().hasHandlers():NEWLINE logging.basicConfig(level=logging.DEBUG, format='%(message)s')NEWLINENEWLINEfrom label_studio.core.utils.io import get_data_dirNEWLINEfrom label_studio.core.utils.params import get_bool_env, get_envNEWLINENEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINE# Hostname is used for proper path generation to the resources, pages, etcNEWLINEHOSTNAME = get_env('HOST', '')NEWLINEif HOSTNAME:NEWLINE if not HOSTNAME.startswith('http://') and not HOSTNAME.startswith('https://'):NEWLINE logger.info("! HOST variable found in environment, but it must start with http:// or https://, ignore it: %s", HOSTNAME)NEWLINE HOSTNAME = ''NEWLINE else:NEWLINE logger.info("=> Hostname correctly is set to: %s", HOSTNAME)NEWLINE if HOSTNAME.endswith('/'):NEWLINE HOSTNAME = HOSTNAME[0:-1]NEWLINENEWLINE # for django url resolverNEWLINE if HOSTNAME:NEWLINE # http[s]://domain.com:8080/script_name => /script_nameNEWLINE pattern = re.compile(r'^http[s]?:\/\/([^:\/\s]+(:\d*)?)(.*)?')NEWLINE match = pattern.match(HOSTNAME)NEWLINE FORCE_SCRIPT_NAME = match.group(3)NEWLINE if FORCE_SCRIPT_NAME:NEWLINE logger.info("=> Django URL prefix is set to: %s", FORCE_SCRIPT_NAME)NEWLINENEWLINEINTERNAL_PORT = '8080'NEWLINENEWLINE# SECURITY WARNING: keep the secret key used in production secret!NEWLINESECRET_KEY = '$(fefwefwef13;LFK{P!)@#*!)kdsjfWF2l+i5e3t(8a1n'NEWLINENEWLINE# SECURITY WARNING: don't run with debug turned on in production!NEWLINEDEBUG = get_bool_env('DEBUG', True)NEWLINEDEBUG_MODAL_EXCEPTIONS = get_bool_env('DEBUG_MODAL_EXCEPTIONS', True)NEWLINENEWLINENEWLINE# Build paths inside the project like this: os.path.join(BASE_DIR, ...)NEWLINEBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))NEWLINENEWLINE# Base path for media root and other uploaded filesNEWLINEBASE_DATA_DIR = get_env('BASE_DATA_DIR', get_data_dir())NEWLINEos.makedirs(BASE_DATA_DIR, exist_ok=True)NEWLINElogger.info('=> Database and media directory: %s', BASE_DATA_DIR)NEWLINENEWLINE# DatabasesNEWLINE# https://docs.djangoproject.com/en/2.1/ref/settings/#databasesNEWLINEDJANGO_DB_MYSQL = 'mysql'NEWLINEDJANGO_DB_SQLITE = 'sqlite'NEWLINEDJANGO_DB = 'default'NEWLINEDATABASE_NAME_DEFAULT = os.path.join(BASE_DATA_DIR, 'label_studio.sqlite3')NEWLINEDATABASE_NAME = get_env('DATABASE_NAME', DATABASE_NAME_DEFAULT)NEWLINEDATABASES_ALL = {NEWLINE 'default': {NEWLINE 'ENGINE': 'django.db.backends.postgresql',NEWLINE 'USER': get_env('POSTGRE_USER', 'postgres'),NEWLINE 'PASSWORD': get_env('POSTGRE_PASSWORD', 'postgres'),NEWLINE 'NAME': get_env('POSTGRE_NAME', 'postgres'),NEWLINE 'HOST': get_env('POSTGRE_HOST', 'localhost'),NEWLINE 'PORT': int(get_env('POSTGRE_PORT', '5432')),NEWLINE },NEWLINE DJANGO_DB_MYSQL: {NEWLINE 'ENGINE': 'django.db.backends.mysql',NEWLINE 'USER': get_env('MYSQL_USER', 'root'),NEWLINE 'PASSWORD': get_env('MYSQL_PASSWORD', ''),NEWLINE 'NAME': get_env('MYSQL_NAME', 'labelstudio'),NEWLINE 'HOST': get_env('MYSQL_HOST', 'localhost'),NEWLINE 'PORT': int(get_env('MYSQL_PORT', '3306')),NEWLINE },NEWLINE DJANGO_DB_SQLITE: {NEWLINE 'ENGINE': 'django.db.backends.sqlite3',NEWLINE 'NAME': DATABASE_NAME,NEWLINE 'OPTIONS': {NEWLINE # 'timeout': 20,NEWLINE }NEWLINE }NEWLINE}NEWLINEDATABASES = {'default': DATABASES_ALL.get(get_env('DJANGO_DB', 'default'))}NEWLINENEWLINELOGGING = {NEWLINE 'version': 1,NEWLINE 'disable_existing_loggers': False,NEWLINE 'formatters': {NEWLINE 'standard': {NEWLINE 'format': '[%(asctime)s] [%(name)s::%(funcName)s::%(lineno)d] [%(levelname)s] %(message)s',NEWLINE },NEWLINE 'message_only': {NEWLINE 'format': '%(message)s',NEWLINE },NEWLINE 'rq_console': {NEWLINE 'format': '%(asctime)s %(message)s',NEWLINE 'datefmt': '%H:%M:%S',NEWLINE },NEWLINE },NEWLINE 'handlers': {NEWLINE 'console_raw': {NEWLINE 'level': get_env('LOG_LEVEL', 'WARNING'),NEWLINE 'class': 'logging.StreamHandler',NEWLINE },NEWLINE 'console': {NEWLINE 'level': get_env('LOG_LEVEL', 'WARNING'),NEWLINE 'class': 'logging.StreamHandler',NEWLINE 'formatter': 'standard'NEWLINE },NEWLINE 'rq_console': {NEWLINE 'level': 'WARNING',NEWLINE 'class': 'rq.utils.ColorizingStreamHandler',NEWLINE 'formatter': 'rq_console',NEWLINE 'exclude': ['%(asctime)s'],NEWLINE }NEWLINE },NEWLINE 'root': {NEWLINE 'handlers': ['console'],NEWLINE 'level': get_env('LOG_LEVEL', 'WARNING'),NEWLINE }NEWLINE}NEWLINENEWLINEif get_bool_env('GOOGLE_LOGGING_ENABLED', False):NEWLINE logging.info('Google Cloud Logging handler is enabled.')NEWLINE try:NEWLINE import google.cloud.loggingNEWLINE from google.auth.exceptions import GoogleAuthErrorNEWLINENEWLINE client = google.cloud.logging.Client()NEWLINE client.setup_logging()NEWLINENEWLINE LOGGING['handlers']['google_cloud_logging'] = {NEWLINE 'level': get_env('LOG_LEVEL', 'WARNING'),NEWLINE 'class': 'google.cloud.logging.handlers.CloudLoggingHandler',NEWLINE 'client': clientNEWLINE }NEWLINE LOGGING['root']['handlers'].append('google_cloud_logging')NEWLINE except GoogleAuthError as e:NEWLINE logger.exception('Google Cloud Logging handler could not be setup.')NEWLINENEWLINEINSTALLED_APPS = [NEWLINE 'django.contrib.admin',NEWLINE 'django.contrib.auth',NEWLINE 'django.contrib.contenttypes',NEWLINE 'django.contrib.sessions',NEWLINE 'django.contrib.messages',NEWLINE 'django.contrib.staticfiles',NEWLINE 'django.contrib.humanize',NEWLINENEWLINE 'drf_yasg',NEWLINE 'corsheaders',NEWLINE 'django_extensions',NEWLINE 'django_rq',NEWLINE 'django_filters',NEWLINE 'rules',NEWLINE 'annoying',NEWLINENEWLINE 'rest_framework',NEWLINE 'rest_framework_swagger',NEWLINE 'rest_framework.authtoken',NEWLINE 'drf_generators',NEWLINENEWLINE 'core',NEWLINE 'users',NEWLINE 'organizations',NEWLINE 'data_import',NEWLINE 'data_export',NEWLINENEWLINE 'projects',NEWLINE 'tasks',NEWLINE 'data_manager',NEWLINE 'io_storages',NEWLINE 'ml',NEWLINE 'webhooks',NEWLINE]NEWLINENEWLINEMIDDLEWARE = [NEWLINE 'corsheaders.middleware.CorsMiddleware',NEWLINE 'django.middleware.security.SecurityMiddleware',NEWLINE 'django.contrib.sessions.middleware.SessionMiddleware',NEWLINE 'django.middleware.locale.LocaleMiddleware',NEWLINE 'django.middleware.csrf.CsrfViewMiddleware',NEWLINE 'core.middleware.DisableCSRF',NEWLINE 'django.contrib.auth.middleware.AuthenticationMiddleware',NEWLINE 'django.contrib.messages.middleware.MessageMiddleware',NEWLINE 'django.middleware.clickjacking.XFrameOptionsMiddleware',NEWLINE 'core.middleware.CommonMiddlewareAppendSlashWithoutRedirect', # instead of 'CommonMiddleware'NEWLINE 'core.middleware.CommonMiddleware',NEWLINE 'django_user_agents.middleware.UserAgentMiddleware',NEWLINE 'core.middleware.SetSessionUIDMiddleware',NEWLINE 'core.middleware.ContextLogMiddleware',NEWLINE 'core.middleware.DatabaseIsLockedRetryMiddleware',NEWLINE]NEWLINENEWLINEREST_FRAMEWORK = {NEWLINE 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],NEWLINE 'DEFAULT_AUTHENTICATION_CLASSES': (NEWLINE 'rest_framework.authentication.TokenAuthentication',NEWLINE 'rest_framework.authentication.SessionAuthentication',NEWLINE ),NEWLINE 'DEFAULT_PERMISSION_CLASSES': [NEWLINE 'core.api_permissions.HasObjectPermission',NEWLINE 'rest_framework.permissions.IsAuthenticated',NEWLINENEWLINE ],NEWLINE 'EXCEPTION_HANDLER': 'core.utils.common.custom_exception_handler',NEWLINE 'DEFAULT_RENDERER_CLASSES': (NEWLINE 'rest_framework.renderers.JSONRenderer',NEWLINE ),NEWLINE 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning'NEWLINE}NEWLINENEWLINE# CORS & Host settingsNEWLINEINTERNAL_IPS = [ # django debug toolbar for django==2.2 requirementNEWLINE '127.0.0.1',NEWLINE 'localhost',NEWLINE]NEWLINECORS_ORIGIN_ALLOW_ALL = TrueNEWLINECORS_ALLOW_METHODS = [NEWLINE 'DELETE',NEWLINE 'GET',NEWLINE 'OPTIONS',NEWLINE 'PATCH',NEWLINE 'POST',NEWLINE 'PUT',NEWLINE]NEWLINEALLOWED_HOSTS = ['*']NEWLINENEWLINE# Auth modulesNEWLINEAUTH_USER_MODEL = 'users.User'NEWLINEAUTHENTICATION_BACKENDS = [NEWLINE 'rules.permissions.ObjectPermissionBackend',NEWLINE 'django.contrib.auth.backends.ModelBackend'NEWLINE]NEWLINEUSE_USERNAME_FOR_LOGIN = FalseNEWLINENEWLINEDISABLE_SIGNUP_WITHOUT_LINK = get_bool_env('DISABLE_SIGNUP_WITHOUT_LINK', False)NEWLINENEWLINE# Password validation:NEWLINE# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validatorsNEWLINEAUTH_PASSWORD_VALIDATORS = [NEWLINE {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},NEWLINE {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},NEWLINE {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},NEWLINE {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},NEWLINE]NEWLINENEWLINE# Django templatesNEWLINETEMPLATES_DIR = os.path.join(os.path.dirname(BASE_DIR), 'templates') # ../../from_this = 'web' dirNEWLINETEMPLATES = [NEWLINE {NEWLINE 'BACKEND': 'django.template.backends.django.DjangoTemplates',NEWLINE 'DIRS': [TEMPLATES_DIR],NEWLINE 'APP_DIRS': True,NEWLINE 'OPTIONS': {NEWLINE 'context_processors': [NEWLINE 'django.template.context_processors.debug',NEWLINE 'django.template.context_processors.request',NEWLINE 'django.contrib.auth.context_processors.auth',NEWLINE 'django.contrib.messages.context_processors.messages',NEWLINE 'core.context_processors.settings'NEWLINE ],NEWLINE 'builtins': ['django.templatetags.i18n'],NEWLINE },NEWLINE }NEWLINE]NEWLINENEWLINE# RQNEWLINERQ_QUEUES = {NEWLINE 'default': {NEWLINE 'HOST': 'localhost',NEWLINE 'PORT': 6379,NEWLINE 'DB': 0,NEWLINE 'DEFAULT_TIMEOUT': 180NEWLINE }NEWLINE}NEWLINENEWLINE# Swagger: automatic API documentationNEWLINESWAGGER_SETTINGS = {NEWLINE 'SECURITY_DEFINITIONS': {NEWLINE 'token': {NEWLINE 'type': 'token',NEWLINE 'name': 'Token',NEWLINE 'in': 'header',NEWLINE 'url': '/user/account'NEWLINE }NEWLINE },NEWLINE 'APIS_SORTER': 'alpha',NEWLINE 'SUPPORTED_SUBMIT_METHODS': ['get', 'post', 'put', 'delete', 'patch'],NEWLINE # "DEFAULT_AUTO_SCHEMA_CLASS": "core.utils.CustomAutoSchema",NEWLINE 'OPERATIONS_SORTER': 'alpha'NEWLINE}NEWLINENEWLINESENTRY_DSN = get_env('SENTRY_DSN', None)NEWLINESENTRY_RATE = float(get_env('SENTRY_RATE', 0.25))NEWLINESENTRY_ENVIRONMENT = get_env('SENTRY_ENVIRONMENT', 'stage.opensource')NEWLINESENTRY_REDIS_ENABLED = FalseNEWLINEFRONTEND_SENTRY_DSN = get_env('FRONTEND_SENTRY_DSN', None)NEWLINEFRONTEND_SENTRY_RATE = get_env('FRONTEND_SENTRY_RATE', 0.1)NEWLINEFRONTEND_SENTRY_ENVIRONMENT = get_env('FRONTEND_SENTRY_ENVIRONMENT', 'stage.opensource')NEWLINENEWLINEROOT_URLCONF = 'core.urls'NEWLINEWSGI_APPLICATION = 'core.wsgi.application'NEWLINEGRAPHIQL = TrueNEWLINENEWLINE# InternationalizationNEWLINE# https://docs.djangoproject.com/en/2.1/topics/i18n/NEWLINELANGUAGE_CODE = 'en-us'NEWLINETIME_ZONE = 'UTC'NEWLINEUSE_I18N = FalseNEWLINEUSE_L10N = TrueNEWLINEUSE_TZ = TrueNEWLINENEWLINE# Static files (CSS, JavaScript, Images)NEWLINE# https://docs.djangoproject.com/en/2.1/howto/static-files/NEWLINESTATIC_URL = '/static/'NEWLINE# if FORCE_SCRIPT_NAME:NEWLINE# STATIC_URL = FORCE_SCRIPT_NAME + STATIC_URLNEWLINElogger.info(f'=> Static URL is set to: {STATIC_URL}')NEWLINENEWLINESTATIC_ROOT = os.path.join(BASE_DIR, 'static_build')NEWLINESTATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]NEWLINESTATICFILES_FINDERS = (NEWLINE 'django.contrib.staticfiles.finders.FileSystemFinder',NEWLINE 'django.contrib.staticfiles.finders.AppDirectoriesFinder'NEWLINE)NEWLINESTATICFILES_STORAGE = 'core.storage.SkipMissedManifestStaticFilesStorage'NEWLINENEWLINE# Sessions and CSRFNEWLINESESSION_COOKIE_SECURE = bool(int(get_env('SESSION_COOKIE_SECURE', True)))NEWLINECSRF_COOKIE_SECURE = bool(int(get_env('CSRF_COOKIE_SECURE', SESSION_COOKIE_SECURE)))NEWLINECSRF_COOKIE_HTTPONLY = bool(int(get_env('CSRF_COOKIE_HTTPONLY', SESSION_COOKIE_SECURE)))NEWLINENEWLINE# user media filesNEWLINEMEDIA_ROOT = os.path.join(BASE_DATA_DIR, 'media')NEWLINEos.makedirs(MEDIA_ROOT, exist_ok=True)NEWLINEMEDIA_URL = '/data/'NEWLINEUPLOAD_DIR = 'upload'NEWLINEAVATAR_PATH = 'avatars'NEWLINENEWLINE# project exportsNEWLINEEXPORT_DIR = os.path.join(BASE_DATA_DIR, 'export')NEWLINEEXPORT_URL_ROOT = '/export/'NEWLINE# old export dirNEWLINEos.makedirs(EXPORT_DIR, exist_ok=True)NEWLINE# dir for delayed exportNEWLINEDELAYED_EXPORT_DIR = 'export'NEWLINEos.makedirs(os.path.join(BASE_DATA_DIR, MEDIA_ROOT, DELAYED_EXPORT_DIR), exist_ok=True)NEWLINENEWLINE# file / task size limitsNEWLINEDATA_UPLOAD_MAX_MEMORY_SIZE = int(get_env('DATA_UPLOAD_MAX_MEMORY_SIZE', 250 * 1024 * 1024))NEWLINETASKS_MAX_NUMBER = 1000000NEWLINETASKS_MAX_FILE_SIZE = DATA_UPLOAD_MAX_MEMORY_SIZENEWLINENEWLINETASK_LOCK_TTL = int(get_env('TASK_LOCK_TTL')) if get_env('TASK_LOCK_TTL') else NoneNEWLINETASK_LOCK_DEFAULT_TTL = int(get_env('TASK_LOCK_DEFAULT_TTL', 3600))NEWLINETASK_LOCK_MIN_TTL = int(get_env('TASK_LOCK_MIN_TTL', 120))NEWLINENEWLINE# Email backendNEWLINEFROM_EMAIL = get_env('FROM_EMAIL', 'Label Studio ')NEWLINEEMAIL_BACKEND = get_env('EMAIL_BACKEND', 'django.core.mail.backends.dummy.EmailBackend')NEWLINENEWLINEENABLE_LOCAL_FILES_STORAGE = get_bool_env('ENABLE_LOCAL_FILES_STORAGE', default=True)NEWLINELOCAL_FILES_SERVING_ENABLED = get_bool_env('LOCAL_FILES_SERVING_ENABLED', default=False)NEWLINENEWLINE""" React Libraries: do not forget to change this dir in /etc/nginx/nginx.conf """NEWLINE# EDITOR = label-studio-frontend repositoryNEWLINEEDITOR_ROOT = os.path.join(BASE_DIR, '../frontend/dist/lsf')NEWLINE# DM = data manager (included into FRONTEND due npm building, we need only version.json file from there)NEWLINEDM_ROOT = os.path.join(BASE_DIR, '../frontend/dist/dm')NEWLINE# FRONTEND = GUI for django backendNEWLINEREACT_APP_ROOT = os.path.join(BASE_DIR, '../frontend/dist/react-app')NEWLINENEWLINE# per project settingsNEWLINEBATCH_SIZE = 1000NEWLINEPROJECT_TITLE_MIN_LEN = 3NEWLINEPROJECT_TITLE_MAX_LEN = 50NEWLINELOGIN_REDIRECT_URL = '/'NEWLINELOGIN_URL = '/'NEWLINEMIN_GROUND_TRUTH = 10NEWLINEDATA_UNDEFINED_NAME = '$undefined$'NEWLINELICENSE = {}NEWLINEVERSIONS = {}NEWLINEVERSION_EDITION = 'Community Edition'NEWLINELATEST_VERSION_CHECK = TrueNEWLINEVERSIONS_CHECK_TIME = 0NEWLINEALLOW_ORGANIZATION_WEBHOOKS = get_bool_env('ALLOW_ORGANIZATION_WEBHOOKS', False)NEWLINECONVERTER_DOWNLOAD_RESOURCES = get_bool_env('CONVERTER_DOWNLOAD_RESOURCES', True)NEWLINEEXPERIMENTAL_FEATURES = get_bool_env('EXPERIMENTAL_FEATURES', False)NEWLINENEWLINECREATE_ORGANIZATION = 'organizations.functions.create_organization'NEWLINEGET_OBJECT_WITH_CHECK_AND_LOG = 'core.utils.get_object.get_object_with_check_and_log'NEWLINESAVE_USER = 'users.functions.save_user'NEWLINEUSER_SERIALIZER = 'users.serializers.BaseUserSerializer'NEWLINEDATA_MANAGER_GET_ALL_COLUMNS = 'data_manager.functions.get_all_columns'NEWLINEDATA_MANAGER_ANNOTATIONS_MAP = {}NEWLINEDATA_MANAGER_ACTIONS = {}NEWLINEDATA_MANAGER_CUSTOM_FILTER_EXPRESSIONS = ''NEWLINEUSER_LOGIN_FORM = 'users.forms.LoginForm'NEWLINEPROJECT_MIXIN = 'core.mixins.DummyModelMixin'NEWLINETASK_MIXIN = 'core.mixins.DummyModelMixin'NEWLINEANNOTATION_MIXIN = 'core.mixins.DummyModelMixin'NEWLINEORGANIZATION_MIXIN = 'core.mixins.DummyModelMixin'NEWLINEUSER_MIXIN = 'users.mixins.UserMixin'NEWLINEGET_STORAGE_LIST = 'io_storages.functions.get_storage_list'NEWLINENEWLINESTORAGE_ANNOTATION_SERIALIZER = 'io_storages.serializers.StorageAnnotationSerializer'NEWLINENEWLINENEWLINEdef project_delete(project):NEWLINE project.delete()NEWLINENEWLINENEWLINEdef user_auth(user_model, email, password):NEWLINE return NoneNEWLINENEWLINENEWLINEdef collect_versions_dummy(**kwargs):NEWLINE return {}NEWLINENEWLINENEWLINEPROJECT_DELETE = project_deleteNEWLINEUSER_AUTH = user_authNEWLINECOLLECT_VERSIONS = collect_versions_dummyNEWLINENEWLINEWEBHOOK_TIMEOUT = float(get_env('WEBHOOK_TIMEOUT', 1.0))NEWLINENEWLINE# fix a problem with Windows mimetypes for JS and PNGNEWLINEimport mimetypesNEWLINEmimetypes.add_type("application/javascript", ".js", True)NEWLINEmimetypes.add_type("image/png", ".png", True)NEWLINE # Copyright (c) 2017-2019 Uber Technologies, Inc.NEWLINE# SPDX-License-Identifier: Apache-2.0NEWLINENEWLINE"""NEWLINEThis example demonstrates how to use the Causal Effect Variational AutoencoderNEWLINE[1] implemented in pyro.contrib.cevae.CEVAE, documented atNEWLINEhttp://docs.pyro.ai/en/latest/contrib.cevae.htmlNEWLINENEWLINE**References**NEWLINENEWLINE[1] C. Louizos, U. Shalit, J. Mooij, D. Sontag, R. Zemel, M. Welling (2017).NEWLINE Causal Effect Inference with Deep Latent-Variable Models.NEWLINE http://papers.nips.cc/paper/7223-causal-effect-inference-with-deep-latent-variable-models.pdfNEWLINE https://github.com/AMLab-Amsterdam/CEVAENEWLINE"""NEWLINEimport argparseNEWLINEimport loggingNEWLINENEWLINEimport torchNEWLINENEWLINEimport pyroNEWLINEimport pyro.distributions as distNEWLINEfrom pyro.contrib.cevae import CEVAENEWLINENEWLINElogging.getLogger("pyro").setLevel(logging.DEBUG)NEWLINElogging.getLogger("pyro").handlers[0].setLevel(logging.DEBUG)NEWLINENEWLINENEWLINEdef generate_data(args):NEWLINE """NEWLINE This implements the generative process of [1], but using larger feature andNEWLINE latent spaces ([1] assumes ``feature_dim=1`` and ``latent_dim=5``).NEWLINE """NEWLINE z = dist.Bernoulli(0.5).sample([args.num_data])NEWLINE x = dist.Normal(z, 5 * z + 3 * (1 - z)).sample([args.feature_dim]).t()NEWLINE t = dist.Bernoulli(0.75 * z + 0.25 * (1 - z)).sample()NEWLINE y = dist.Bernoulli(logits=3 * (z + 2 * (2 * t - 2))).sample()NEWLINENEWLINE # Compute true ite for evaluation (via Monte Carlo approximation).NEWLINE t0_t1 = torch.tensor([[0.], [1.]])NEWLINE y_t0, y_t1 = dist.Bernoulli(logits=3 * (z + 2 * (2 * t0_t1 - 2))).meanNEWLINE true_ite = y_t1 - y_t0NEWLINE return x, t, y, true_iteNEWLINENEWLINENEWLINEdef main(args):NEWLINE pyro.enable_validation(__debug__)NEWLINE if args.cuda:NEWLINE torch.set_default_tensor_type('torch.cuda.FloatTensor')NEWLINENEWLINE # Generate synthetic data.NEWLINE pyro.set_rng_seed(args.seed)NEWLINE x_train, t_train, y_train, _ = generate_data(args)NEWLINENEWLINE # Train.NEWLINE pyro.set_rng_seed(args.seed)NEWLINE pyro.clear_param_store()NEWLINE cevae = CEVAE(feature_dim=args.feature_dim,NEWLINE latent_dim=args.latent_dim,NEWLINE hidden_dim=args.hidden_dim,NEWLINE num_layers=args.num_layers,NEWLINE num_samples=10)NEWLINE cevae.fit(x_train, t_train, y_train,NEWLINE num_epochs=args.num_epochs,NEWLINE batch_size=args.batch_size,NEWLINE learning_rate=args.learning_rate,NEWLINE learning_rate_decay=args.learning_rate_decay,NEWLINE weight_decay=args.weight_decay)NEWLINENEWLINE # Evaluate.NEWLINE x_test, t_test, y_test, true_ite = generate_data(args)NEWLINE true_ate = true_ite.mean()NEWLINE print("true ATE = {:0.3g}".format(true_ate.item()))NEWLINE naive_ate = y_test[t_test == 1].mean() - y_test[t_test == 0].mean()NEWLINE print("naive ATE = {:0.3g}".format(naive_ate))NEWLINE if args.jit:NEWLINE cevae = cevae.to_script_module()NEWLINE est_ite = cevae.ite(x_test)NEWLINE est_ate = est_ite.mean()NEWLINE print("estimated ATE = {:0.3g}".format(est_ate.item()))NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE assert pyro.__version__.startswith('1.5.0')NEWLINE parser = argparse.ArgumentParser(description="Causal Effect Variational Autoencoder")NEWLINE parser.add_argument("--num-data", default=1000, type=int)NEWLINE parser.add_argument("--feature-dim", default=5, type=int)NEWLINE parser.add_argument("--latent-dim", default=20, type=int)NEWLINE parser.add_argument("--hidden-dim", default=200, type=int)NEWLINE parser.add_argument("--num-layers", default=3, type=int)NEWLINE parser.add_argument("-n", "--num-epochs", default=50, type=int)NEWLINE parser.add_argument("-b", "--batch-size", default=100, type=int)NEWLINE parser.add_argument("-lr", "--learning-rate", default=1e-3, type=float)NEWLINE parser.add_argument("-lrd", "--learning-rate-decay", default=0.1, type=float)NEWLINE parser.add_argument("--weight-decay", default=1e-4, type=float)NEWLINE parser.add_argument("--seed", default=1234567890, type=int)NEWLINE parser.add_argument("--jit", action="store_true")NEWLINE parser.add_argument("--cuda", action="store_true")NEWLINE args = parser.parse_args()NEWLINE main(args)NEWLINE # coding: utf-8NEWLINENEWLINE"""NEWLINE KubernetesNEWLINENEWLINE No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501NEWLINENEWLINE The version of the OpenAPI document: v1.20.7NEWLINE Generated by: https://openapi-generator.techNEWLINE"""NEWLINENEWLINENEWLINEimport pprintNEWLINEimport re # noqa: F401NEWLINENEWLINEimport sixNEWLINENEWLINEfrom kubernetes.client.configuration import ConfigurationNEWLINENEWLINENEWLINEclass V1EventSource(object):NEWLINE """NOTE: This class is auto generated by OpenAPI Generator.NEWLINE Ref: https://openapi-generator.techNEWLINENEWLINE Do not edit the class manually.NEWLINE """NEWLINENEWLINE """NEWLINE Attributes:NEWLINE openapi_types (dict): The key is attribute nameNEWLINE and the value is attribute type.NEWLINE attribute_map (dict): The key is attribute nameNEWLINE and the value is json key in definition.NEWLINE """NEWLINE openapi_types = {NEWLINE 'component': 'str',NEWLINE 'host': 'str'NEWLINE }NEWLINENEWLINE attribute_map = {NEWLINE 'component': 'component',NEWLINE 'host': 'host'NEWLINE }NEWLINENEWLINE def __init__(self, component=None, host=None, local_vars_configuration=None): # noqa: E501NEWLINE """V1EventSource - a model defined in OpenAPI""" # noqa: E501NEWLINE if local_vars_configuration is None:NEWLINE local_vars_configuration = Configuration()NEWLINE self.local_vars_configuration = local_vars_configurationNEWLINENEWLINE self._component = NoneNEWLINE self._host = NoneNEWLINE self.discriminator = NoneNEWLINENEWLINE if component is not None:NEWLINE self.component = componentNEWLINE if host is not None:NEWLINE self.host = hostNEWLINENEWLINE @propertyNEWLINE def component(self):NEWLINE """Gets the component of this V1EventSource. # noqa: E501NEWLINENEWLINE Component from which the event is generated. # noqa: E501NEWLINENEWLINE :return: The component of this V1EventSource. # noqa: E501NEWLINE :rtype: strNEWLINE """NEWLINE return self._componentNEWLINENEWLINE @component.setterNEWLINE def component(self, component):NEWLINE """Sets the component of this V1EventSource.NEWLINENEWLINE Component from which the event is generated. # noqa: E501NEWLINENEWLINE :param component: The component of this V1EventSource. # noqa: E501NEWLINE :type: strNEWLINE """NEWLINENEWLINE self._component = componentNEWLINENEWLINE @propertyNEWLINE def host(self):NEWLINE """Gets the host of this V1EventSource. # noqa: E501NEWLINENEWLINE Node name on which the event is generated. # noqa: E501NEWLINENEWLINE :return: The host of this V1EventSource. # noqa: E501NEWLINE :rtype: strNEWLINE """NEWLINE return self._hostNEWLINENEWLINE @host.setterNEWLINE def host(self, host):NEWLINE """Sets the host of this V1EventSource.NEWLINENEWLINE Node name on which the event is generated. # noqa: E501NEWLINENEWLINE :param host: The host of this V1EventSource. # noqa: E501NEWLINE :type: strNEWLINE """NEWLINENEWLINE self._host = hostNEWLINENEWLINE def to_dict(self):NEWLINE """Returns the model properties as a dict"""NEWLINE result = {}NEWLINENEWLINE for attr, _ in six.iteritems(self.openapi_types):NEWLINE value = getattr(self, attr)NEWLINE if isinstance(value, list):NEWLINE result[attr] = list(map(NEWLINE lambda x: x.to_dict() if hasattr(x, "to_dict") else x,NEWLINE valueNEWLINE ))NEWLINE elif hasattr(value, "to_dict"):NEWLINE result[attr] = value.to_dict()NEWLINE elif isinstance(value, dict):NEWLINE result[attr] = dict(map(NEWLINE lambda item: (item[0], item[1].to_dict())NEWLINE if hasattr(item[1], "to_dict") else item,NEWLINE value.items()NEWLINE ))NEWLINE else:NEWLINE result[attr] = valueNEWLINENEWLINE return resultNEWLINENEWLINE def to_str(self):NEWLINE """Returns the string representation of the model"""NEWLINE return pprint.pformat(self.to_dict())NEWLINENEWLINE def __repr__(self):NEWLINE """For `print` and `pprint`"""NEWLINE return self.to_str()NEWLINENEWLINE def __eq__(self, other):NEWLINE """Returns true if both objects are equal"""NEWLINE if not isinstance(other, V1EventSource):NEWLINE return FalseNEWLINENEWLINE return self.to_dict() == other.to_dict()NEWLINENEWLINE def __ne__(self, other):NEWLINE """Returns true if both objects are not equal"""NEWLINE if not isinstance(other, V1EventSource):NEWLINE return TrueNEWLINENEWLINE return self.to_dict() != other.to_dict()NEWLINE # -*- coding: utf-8 -*-NEWLINE# Generated by Django 1.11.20 on 2019-02-25 16:08NEWLINEfrom __future__ import unicode_literalsNEWLINENEWLINEimport django.contrib.postgres.fields.hstoreNEWLINEfrom django.db import migrations, modelsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [("research", "0004_public_flag")]NEWLINENEWLINE operations = [NEWLINE migrations.CreateModel(NEWLINE name="Classification",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.AutoField(NEWLINE auto_created=True,NEWLINE primary_key=True,NEWLINE serialize=False,NEWLINE verbose_name="ID",NEWLINE ),NEWLINE ),NEWLINE ("name", django.contrib.postgres.fields.hstore.HStoreField()),NEWLINE ],NEWLINE options={"db_table": "research_classification", "managed": False},NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name="Education",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.AutoField(NEWLINE auto_created=True,NEWLINE primary_key=True,NEWLINE serialize=False,NEWLINE verbose_name="ID",NEWLINE ),NEWLINE ),NEWLINE ("name", django.contrib.postgres.fields.hstore.HStoreField()),NEWLINE ],NEWLINE options={"db_table": "research_education", "managed": False},NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name="Expertise",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.AutoField(NEWLINE auto_created=True,NEWLINE primary_key=True,NEWLINE serialize=False,NEWLINE verbose_name="ID",NEWLINE ),NEWLINE ),NEWLINE ("name", django.contrib.postgres.fields.hstore.HStoreField()),NEWLINE ],NEWLINE options={"db_table": "research_expertise", "managed": False},NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name="Knowledge",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.AutoField(NEWLINE auto_created=True,NEWLINE primary_key=True,NEWLINE serialize=False,NEWLINE verbose_name="ID",NEWLINE ),NEWLINE ),NEWLINE ("name", django.contrib.postgres.fields.hstore.HStoreField()),NEWLINE ],NEWLINE options={"db_table": "research_knowledge", "managed": False},NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name="Program",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.AutoField(NEWLINE auto_created=True,NEWLINE primary_key=True,NEWLINE serialize=False,NEWLINE verbose_name="ID",NEWLINE ),NEWLINE ),NEWLINE ("name", models.CharField(blank=True, max_length=256, null=True)),NEWLINE ("active", models.BooleanField()),NEWLINE ],NEWLINE options={"db_table": "research_program", "managed": False},NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name="PublicationAuthorship",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.AutoField(NEWLINE auto_created=True,NEWLINE primary_key=True,NEWLINE serialize=False,NEWLINE verbose_name="ID",NEWLINE ),NEWLINE ),NEWLINE ("name", django.contrib.postgres.fields.hstore.HStoreField()),NEWLINE ],NEWLINE options={"db_table": "research_publicationauthorship", "managed": False},NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name="PublicationOrganization",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.CharField(max_length=256, primary_key=True, serialize=False),NEWLINE ),NEWLINE ("assigned", models.DateTimeField(blank=True, null=True)),NEWLINE ],NEWLINE options={"db_table": "research_publicationorganization", "managed": False},NEWLINE ),NEWLINE ]NEWLINE # creating list out of dictionariesNEWLINENEWLINEpen_1 = {'color': 'black',NEWLINE 'price': '2.5',NEWLINE 'brand': 'faber castel'NEWLINE }NEWLINENEWLINEpen_2 = {'color': 'blue',NEWLINE 'price': '2.5',NEWLINE 'brand': 'faber castel'NEWLINE }NEWLINENEWLINEpen_3 = {'color': 'red',NEWLINE 'price': '2.5',NEWLINE 'brand': 'faber castel'NEWLINE }NEWLINENEWLINEall_pens = [pen_1, pen_2, pen_3]NEWLINENEWLINEprint(all_pens) """NEWLINEImplementation of custom solvers: advection equation with forward-time, backward-space; Burgers' equation withNEWLINEMacCormack scheme and Korteweg-de Vries equation with Zabusky and Kruska scheme.NEWLINE"""NEWLINEimport numpy as npNEWLINEimport matplotlib.pyplot as pltNEWLINEimport matplotlib as mplNEWLINEimport sympy as spNEWLINEimport warningsNEWLINENEWLINENEWLINE# enable pgf printing of solution plotNEWLINEmpl.use("pgf")NEWLINEpgf_with_custom_preamble = {NEWLINE "font.family": "serif", # use serif/main font for text elementsNEWLINE "pgf.rcfonts": False,NEWLINE "text.usetex": True, # use inline math for ticksNEWLINE}NEWLINEmpl.rcParams.update(pgf_with_custom_preamble)NEWLINENEWLINENEWLINEclass FDgrid:NEWLINE """NEWLINE Class for initialization of the calculation domain and data storage;NEWLINE handles an arbitrary number of ghost cells 'n_ghost'NEWLINE """NEWLINE def __init__(self, x_nodes, n_t, x_min, x_max, u_max_convection, cfl, n_ghost):NEWLINE """NEWLINE Initializes the calculation domainNEWLINENEWLINE :param x_nodes: Number of points in domain OmegaNEWLINE :param n_t: Total number of time steps including IC t = 0NEWLINE :param x_min: left bound of OmegaNEWLINE :param x_max: right bound of OmegaNEWLINE :param u_max_convection: convection speed to calculate dt from cflNEWLINE :param cfl: cfl number of ICNEWLINE :param n_ghost: number of ghost cells for periodic BC needed by scheme (1 for advection and Burgers; 2 for KdV)NEWLINE """NEWLINENEWLINE self.n_x = x_nodes + n_ghost * 2 # ghost nodes at both sidesNEWLINE self.x_nodes = x_nodesNEWLINE self.n_t = n_tNEWLINE self.x_min = x_minNEWLINE self.x_max = x_maxNEWLINE self.n_ghost = n_ghostNEWLINE self.i_ghost_r = x_nodes + n_ghost # index of leftmost ghost node at right boundaryNEWLINE self.i_ghost_l = n_ghost - 1 # index of rightmost ghost node at left boundaryNEWLINE self.dx = (x_max - x_min) / x_nodes # save spatial widthNEWLINE self.dt = (cfl*self.dx)/u_max_convection # set dt according to desired cfl numberNEWLINE self.t_max = self.dt * (n_t - 1) # t = 0 is initial conditionNEWLINE self.grid = np.zeros((self.n_x, n_t), dtype=np.float64) # initialize array to store simulation resultsNEWLINENEWLINE def fill_BC(self, i_time):NEWLINE """fills ghost cells with periodic boundary conditions"""NEWLINE vect_to_set = np.zeros(self.n_x)NEWLINE # copies the data within the domain to a vectorNEWLINE vect_to_set[self.i_ghost_l + 1: self.i_ghost_r] = self.grid[self.i_ghost_l + 1: self.i_ghost_r, i_time]NEWLINE vect_to_set = set_periodic_BC(self, vect_to_set) # sets periodic BCs for vectorNEWLINE self.grid[:, i_time] = vect_to_set # copies filled vector back onto the gridNEWLINENEWLINENEWLINEdef set_periodic_BC(domain, vect):NEWLINE """Helper function called from 'fill_BC' to set the periodic BCs for arbitrary number of ghost cells"""NEWLINE for i in range(domain.n_ghost): # set all values for ghost cells, starting from left for both sidesNEWLINE # value of left ghost cell is value of most right real cellNEWLINE # leftmost left node is to be n_ghost nodes left of the leftmost right ghost nodeNEWLINE vect[i] = vect[domain.i_ghost_r - domain.n_ghost + i] # set left boundary elementNEWLINE # leftmost right ghost node is first real left nodeNEWLINE vect[domain.i_ghost_r + i] = vect[i + domain.n_ghost] # right boundaryNEWLINE return vectNEWLINENEWLINENEWLINEdef solve(x_nodes, n_t, initial_cond, equation, x_min=0., x_max=1., cfl=0.1, a=1., manufactured=False, s=None):NEWLINE """NEWLINENEWLINE :param x_nodes: Number of points in domain OmegaNEWLINE :param n_t: Total number of time steps including IC t = 0NEWLINE :param initial_cond: Numpy array containing the values of the IC; Dimension is x_nodesNEWLINE :param equation: String of equation to be solvedNEWLINE :param x_min: left bound of Omega (default=0.0)NEWLINE :param x_max: right bound of Omega (default=1.0)NEWLINE :param cfl: desired cfl number of IC (default=0.1)NEWLINE :param a: Advection speed; Only used if 'equation' == 'Advection' (default=1.0)NEWLINE :param manufactured: Whether the Method of Manufactured solution is to be calculated (forcing 's' will be applied)NEWLINE (default=False)NEWLINE :param s: Forcing Function of MMS (default=None)NEWLINE :return: FDgrid object containing the simulation results in FDgrid.grid and information about the discretizationNEWLINE """NEWLINENEWLINE # set up calculation domain:NEWLINE if equation == 'Advection':NEWLINE u_max_convection = aNEWLINE if a < 0.: warnings.warn('FTBS only implemented for a > 0: solver will not be stable')NEWLINE else: # for nonlinear equations: calculate maximum convection speed in cfl from initial conditionsNEWLINE u_max_convection = np.max(np.abs(initial_cond))NEWLINE n_ghost = 1 # for FTBS and MacCormackNEWLINE if equation == 'KdV':NEWLINE n_ghost = 2NEWLINE domain = FDgrid(x_nodes, n_t, x_min, x_max, u_max_convection, cfl, n_ghost) # initializes calculation domainNEWLINE domain.grid[domain.i_ghost_l + 1:domain.i_ghost_r, 0] = initial_cond # set ICNEWLINE domain.fill_BC(0) # sets ghost cells for ICNEWLINENEWLINE # initialize sympy variables to process forcing term used in MMSNEWLINE x_values = np.arange(x_min, x_max, domain.dx) # for evaluation of forcing functionNEWLINE x = sp.symbols('x')NEWLINE t = sp.symbols('t')NEWLINENEWLINE if equation == 'Advection': # solve advection u_t + a u_x = 0 using FTBSNEWLINE for i_t in range(1, n_t):NEWLINE for i_x in range(domain.i_ghost_l + 1, domain.i_ghost_r): # iterate domain without ghost cellsNEWLINE # FTBS for a > 0:NEWLINE # u_i^n+1 = u_i^n - cfl (u_i^n - u_i-1^n) ; cfl = a * t / dxNEWLINE domain.grid[i_x, i_t] = domain.grid[i_x, i_t - 1] - cfl * \NEWLINE (domain.grid[i_x, i_t - 1] - domain.grid[i_x - 1, i_t - 1])NEWLINE if manufactured: # add forcing from MMSNEWLINE time = (i_t - 1) * domain.dt # to evaluate source term for current time stepNEWLINE domain.grid[domain.i_ghost_l + 1:domain.i_ghost_r, i_t] += domain.dt * calculate_forcing_manufactured(NEWLINE x_values, x, t, s, time)NEWLINE domain.fill_BC(i_t)NEWLINENEWLINE elif equation == 'Burgers':NEWLINE # solve Burgers equation u_t + g_x = 0 ; g = u^2/2 using 2nd order scheme in time and space of Mac CormackNEWLINE u_predictor = np.zeros(domain.n_x) # initialize saving of predictor stepNEWLINE for i_t in range(1, n_t):NEWLINE time = (i_t - 1) * domain.dt # time for evaluation source termNEWLINENEWLINE # prediction step:NEWLINE for i_x in range(domain.i_ghost_l + 1, domain.i_ghost_r): # iterate domain without ghost cellsNEWLINE # u_i^n+1_pred = u_i^n - dt/dx(g_i+1^n - g_i^n)NEWLINE u_predictor[i_x] = domain.grid[i_x, i_t - 1] - (domain.dt / domain.dx) *\NEWLINE (0.5 * domain.grid[i_x + 1, i_t - 1] ** 2 - 0.5 * domain.grid[i_x, i_t - 1] ** 2)NEWLINE if manufactured: # add forcing from MMSNEWLINE u_predictor[domain.i_ghost_l + 1:domain.i_ghost_r] += domain.dt * calculate_forcing_manufactured(NEWLINE x_values, x, t, s, time)NEWLINE # set periodic BC for predictor; MacCormack only needs a single ghost cellNEWLINE u_predictor[domain.i_ghost_l] = u_predictor[domain.i_ghost_r - 1]NEWLINE u_predictor[domain.i_ghost_r] = u_predictor[domain.i_ghost_l + 1]NEWLINENEWLINE # correction step:NEWLINE for i_x in range(domain.i_ghost_l + 1, domain.i_ghost_r): # iterate domain without ghost cellsNEWLINE # u_i^n+1 = u_i^n - 0.5*(dt/dx) * ((g_i+1^n - g_i^n) + (g_i^n_pred - g_i-1^n_pred))NEWLINE domain.grid[i_x, i_t] = domain.grid[i_x, i_t - 1] - 0.5 * (domain.dt/domain.dx) * \NEWLINE ((0.5 * domain.grid[i_x + 1, i_t - 1] ** 2 - 0.5 * domain.grid[i_x, i_t - 1] ** 2) +NEWLINE (0.5 * u_predictor[i_x] ** 2 - 0.5 * u_predictor[i_x - 1] ** 2))NEWLINE if manufactured: # forcing needs to be evaluated at intermediate stepNEWLINE domain.grid[domain.i_ghost_l + 1:domain.i_ghost_r, i_t] += domain.dt * calculate_forcing_manufactured(NEWLINE x_values, x, t, s, time + 0.5*domain.dt)NEWLINENEWLINE domain.fill_BC(i_t)NEWLINENEWLINE elif equation == 'KdV':NEWLINE # solve KdV u_x + 6*uu_x + u_xxx = 0 using the explicit 2nd order scheme in space and time of Zabusky and KruskaNEWLINENEWLINE # use forward time scheme in first time step to generate data to use for central time steppingNEWLINE for i_x in range(domain.i_ghost_l + 1, domain.i_ghost_r):NEWLINE # u_j^k+1 = u_j^k - (dt/dx)*(u_j+1^k + u_j^k + u_j-1^k) * (u_j+1^k - u_j-1^k) -NEWLINE # 0.5 * dt/dx**3 * (u_j+2^k - 2 * u_j+1^k + 2 * u_j-1^k - u_j-2^k)NEWLINE domain.grid[i_x, 1] = domain.grid[i_x, 0] - (domain.dt/domain.dx) * (domain.grid[i_x + 1, 0] +NEWLINE domain.grid[i_x, 0] + domain.grid[i_x - 1, 0]) * 0.5 * (domain.grid[i_x + 1, 0]NEWLINE - domain.grid[i_x - 1, 0]) - 0.5 * (domain.dt / domain.dx ** 3) * \NEWLINE (domain.grid[i_x + 2, 0] - 2. * domain.grid[i_x + 1, 0] + 2. * domain.grid[i_x - 1, 0]NEWLINE - domain.grid[i_x - 2, 0])NEWLINE if manufactured: # add forcing for MMSNEWLINE domain.grid[domain.i_ghost_l + 1:domain.i_ghost_r, 1] += domain.dt * calculate_forcing_manufactured(NEWLINE x_values, x, t, s, 0.)NEWLINE domain.fill_BC(1)NEWLINENEWLINE # central time stepping from now onNEWLINE for i_t in range(2, n_t):NEWLINENEWLINE for i_x in range(domain.i_ghost_l + 1, domain.i_ghost_r):NEWLINE # u_j^k+1 = u_j^k-1 - 2 * (dt/dx) * (u_j+1^k + u_j^k + u_j-1^k) * (u_j+1^k - u_j-1^k) - dt / dx**3 *NEWLINE # (u_j+2^k - 2 * u_j+1^k + 2 * u_j-1^k - u_j-2^k)NEWLINE domain.grid[i_x, i_t] = domain.grid[i_x, i_t - 2] - 2. * (domain.dt / domain.dx) * \NEWLINE (domain.grid[i_x + 1, i_t - 1] + domain.grid[i_x, i_t - 1] +NEWLINE domain.grid[i_x - 1, i_t - 1]) * (domain.grid[i_x + 1, i_t - 1] -NEWLINE domain.grid[i_x - 1, i_t - 1]) - (domain.dt / (domain.dx ** 3)) * \NEWLINE (domain.grid[i_x + 2, i_t - 1] - 2. * domain.grid[i_x + 1, i_t - 1] +NEWLINE 2. * domain.grid[i_x - 1, i_t - 1] - domain.grid[i_x - 2, i_t - 1])NEWLINE if manufactured: # add forcing for MMSNEWLINE time = (i_t - 1) * domain.dtNEWLINE domain.grid[domain.i_ghost_l + 1:domain.i_ghost_r, i_t] += 2. * domain.dt * \NEWLINE calculate_forcing_manufactured(x_values, x, t, s, time)NEWLINE domain.fill_BC(i_t)NEWLINENEWLINE else: raise Exception('Equation not implemented! (or typo)')NEWLINENEWLINE return domainNEWLINENEWLINENEWLINEdef calculate_forcing_manufactured(x_values, x, t, s, time):NEWLINE """Calculates the forcing term for MMS from the source term; directly depends on time"""NEWLINE lam_s = sp.lambdify(x, s.subs({t: time}), modules=['numpy'])NEWLINE return lam_s(x_values)NEWLINENEWLINENEWLINEdef visualize(domain):NEWLINE """Function to plot the first and last time step of a simulation; to check if everything worked as expected"""NEWLINE tn = np.arange(0., domain.n_t * domain.dt, domain.dt) # array with all timestampsNEWLINE xn = np.arange(domain.x_min, domain.x_max, domain.dx) # array with all x_valuesNEWLINENEWLINE fig = plt.figure(figsize=(5., 3.3))NEWLINE colorlist = [(0., 101 / 256., 189 / 256., 1.), (227/256., 114/256., 34/256., 1.)]NEWLINENEWLINE for index, i in enumerate([0, domain.n_t-1]): # plot IC and last time stepNEWLINE subfig = fig.add_subplot(1, 1, 1)NEWLINE label = 't = ' + str(round(tn[i], 2))NEWLINE subfig.plot(xn, domain.grid[domain.i_ghost_l + 1:domain.i_ghost_r, i], label=label, color=colorlist[index])NEWLINE subfig.legend()NEWLINENEWLINE plt.xlabel('$x$')NEWLINE plt.ylabel('$u(x, t)$')NEWLINE plt.title('Time evolution of solution')NEWLINENEWLINE plt.savefig('transport-equation.png')NEWLINE plt.savefig('transport-equation.pgf')NEWLINE from __future__ import unicode_literalsNEWLINENEWLINEfrom .theplatform import ThePlatformFeedIENEWLINEfrom ..utils import (NEWLINE ExtractorError,NEWLINE int_or_none,NEWLINE find_xpath_attr,NEWLINE xpath_element,NEWLINE xpath_text,NEWLINE update_url_query,NEWLINE)NEWLINENEWLINENEWLINEclass CBSBaseIE(ThePlatformFeedIE):NEWLINE def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):NEWLINE subtitles = {}NEWLINE for k, ext in [('sMPTE-TTCCURL', 'tt'), ('ClosedCaptionURL', 'ttml'), ('webVTTCaptionURL', 'vtt')]:NEWLINE cc_e = find_xpath_attr(smil, self._xpath_ns('.//param', namespace), 'name', k)NEWLINE if cc_e is not None:NEWLINE cc_url = cc_e.get('value')NEWLINE if cc_url:NEWLINE subtitles.setdefault(subtitles_lang, []).append({NEWLINE 'ext': ext,NEWLINE 'url': cc_url,NEWLINE })NEWLINE return subtitlesNEWLINENEWLINENEWLINEclass CBSIE(CBSBaseIE):NEWLINE _VALID_URL = r'(?:cbs:|https?://(?:www\.)?(?:cbs\.com/shows/[^/]+/video|colbertlateshow\.com/(?:video|podcasts))/)(?P[\w-]+)'NEWLINENEWLINE _TESTS = [{NEWLINE 'url': 'http://www.cbs.com/shows/garth-brooks/video/_u7W953k6la293J7EPTd9oHkSPs6Xn6_/connect-chat-feat-garth-brooks/',NEWLINE 'info_dict': {NEWLINE 'id': '_u7W953k6la293J7EPTd9oHkSPs6Xn6_',NEWLINE 'ext': 'mp4',NEWLINE 'title': 'Connect Chat feat. Garth Brooks',NEWLINE 'description': 'Connect with country music singer Garth Brooks, as he chats with fans on Wednesday November 27, 2013. Be sure to tune in to Garth Brooks: Live from Las Vegas, Friday November 29, at 9/8c on CBS!',NEWLINE 'duration': 1495,NEWLINE 'timestamp': 1385585425,NEWLINE 'upload_date': '20131127',NEWLINE 'uploader': 'CBSI-NEW',NEWLINE },NEWLINE 'params': {NEWLINE # m3u8 downloadNEWLINE 'skip_download': True,NEWLINE },NEWLINE '_skip': 'Blocked outside the US',NEWLINE }, {NEWLINE 'url': 'http://colbertlateshow.com/video/8GmB0oY0McANFvp2aEffk9jZZZ2YyXxy/the-colbeard/',NEWLINE 'only_matching': True,NEWLINE }, {NEWLINE 'url': 'http://www.colbertlateshow.com/podcasts/dYSwjqPs_X1tvbV_P2FcPWRa_qT6akTC/in-the-bad-room-with-stephen/',NEWLINE 'only_matching': True,NEWLINE }]NEWLINENEWLINE def _extract_video_info(self, content_id, site='cbs', mpx_acc=2198311517):NEWLINE items_data = self._download_xml(NEWLINE 'http://can.cbs.com/thunder/player/videoPlayerService.php',NEWLINE content_id, query={'partner': site, 'contentId': content_id})NEWLINE video_data = xpath_element(items_data, './/item')NEWLINE title = xpath_text(video_data, 'videoTitle', 'title') or xpath_text(video_data, 'videotitle', 'title')NEWLINE tp_path = 'dJ5BDC/media/guid/%d/%s' % (mpx_acc, content_id)NEWLINE tp_release_url = 'http://link.theplatform.com/s/' + tp_pathNEWLINENEWLINE asset_types = []NEWLINE subtitles = {}NEWLINE formats = []NEWLINE last_e = NoneNEWLINE for item in items_data.findall('.//item'):NEWLINE asset_type = xpath_text(item, 'assetType')NEWLINE if not asset_type or asset_type in asset_types or 'HLS_FPS' in asset_type or 'DASH_CENC' in asset_type:NEWLINE continueNEWLINE asset_types.append(asset_type)NEWLINE query = {NEWLINE 'mbr': 'true',NEWLINE 'assetTypes': asset_type,NEWLINE }NEWLINE if asset_type.startswith('HLS') or asset_type in ('OnceURL', 'StreamPack'):NEWLINE query['formats'] = 'MPEG4,M3U'NEWLINE elif asset_type in ('RTMP', 'WIFI', '3G'):NEWLINE query['formats'] = 'MPEG4,FLV'NEWLINE try:NEWLINE tp_formats, tp_subtitles = self._extract_theplatform_smil(NEWLINE update_url_query(tp_release_url, query), content_id,NEWLINE 'Downloading %s SMIL data' % asset_type)NEWLINE except ExtractorError as e:NEWLINE last_e = eNEWLINE continueNEWLINE formats.extend(tp_formats)NEWLINE subtitles = self._merge_subtitles(subtitles, tp_subtitles)NEWLINE if last_e and not formats:NEWLINE raise last_eNEWLINE self._sort_formats(formats)NEWLINENEWLINE info = self._extract_theplatform_metadata(tp_path, content_id)NEWLINE info.update({NEWLINE 'id': content_id,NEWLINE 'title': title,NEWLINE 'series': xpath_text(video_data, 'seriesTitle'),NEWLINE 'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')),NEWLINE 'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')),NEWLINE 'duration': int_or_none(xpath_text(video_data, 'videoLength'), 1000),NEWLINE 'thumbnail': xpath_text(video_data, 'previewImageURL'),NEWLINE 'formats': formats,NEWLINE 'subtitles': subtitles,NEWLINE })NEWLINE return infoNEWLINENEWLINE def _real_extract(self, url):NEWLINE content_id = self._match_id(url)NEWLINE return self._extract_video_info(content_id)NEWLINE # -*- coding:utf-8 -*-NEWLINE# @Time: 2021/1/18 8:49NEWLINE# @Author: Zhanyi HouNEWLINE# @Email: 1295752786@qq.comNEWLINE# @File: syntaxana.pyNEWLINE# -*- coding: utf-8 -*-NEWLINE'''NEWLINEpowered by NovalIDENEWLINE来自NovalIDE的词法分析模块NEWLINE作者:侯展意NEWLINE词法分析模块的重要组成单元、NEWLINE依靠各种正则表达式进行特征的提取。NEWLINENEWLINE'''NEWLINEfrom typing import List, Tuple, DictNEWLINEimport reNEWLINENEWLINENEWLINEdef getReplacingDic() -> Dict:NEWLINE dic = {}NEWLINE dic[','] = ','NEWLINE dic['。'] = '.'NEWLINE dic[';'] = ';'NEWLINE dic[':'] = ':'NEWLINE dic['‘'] = '\''NEWLINE dic['’'] = '\''NEWLINE dic['“'] = '\"'NEWLINE dic['”'] = '\"'NEWLINE dic['【'] = '['NEWLINE dic['】'] = ']'NEWLINE dic['('] = '('NEWLINE dic[')'] = ')'NEWLINE return dicNEWLINENEWLINENEWLINEdef getIndent(s: str) -> Tuple[str, int]:NEWLINE s = s.replace('\t', ' ') # tab替换成四个空格NEWLINE s = s.rstrip()NEWLINE if (len(s) > 0):NEWLINE for i, ch in enumerate(s):NEWLINE if (ch != ' '):NEWLINE return s[i:], iNEWLINE return "", i + 1NEWLINE else:NEWLINE return "", 0NEWLINENEWLINENEWLINEdef removeComment(s: str) -> str:NEWLINE pos = s.find('#')NEWLINE if (pos != -1):NEWLINE return s[:pos]NEWLINE else:NEWLINE return sNEWLINENEWLINENEWLINEdef getStringContent(row):NEWLINE passNEWLINENEWLINENEWLINEdef removeStringContent(row: str) -> str:NEWLINE row = row.replace('\"', '\'')NEWLINE if (row.count('\'') >= 2):NEWLINE s = getAllFromRegex(regex=r'[\'](.*?)[\']', st=row)NEWLINE for item in s:NEWLINE row = row.replace('\'%s\'' % item, '\'\'') # 带着分号一起换掉。NEWLINE return rowNEWLINE else:NEWLINE return rowNEWLINENEWLINENEWLINEdef parseVarType(row: str):NEWLINE getInfoFromRegex(r'[\'](.*?)[\']', row)NEWLINENEWLINENEWLINEdef getAllFromRegex(regex: str, st: str) -> List[str]:NEWLINE foundList = re.findall(re.compile(regex, re.S), st)NEWLINENEWLINE return foundListNEWLINENEWLINENEWLINEdef getInfoFromRegex(regex: str, st: str) -> str: # 从正则表达式中获取信息的函数。如果没有任何结果则返回0。NEWLINE foundList = re.findall(re.compile(regex, re.S), st)NEWLINE item = ''NEWLINE if (foundList != []):NEWLINE item = foundList[0]NEWLINE return itemNEWLINENEWLINENEWLINEdef getWordsFromString(s: str) -> list:NEWLINE if (s != ''):NEWLINE syms = s.split(',') # 用逗号分隔开。NEWLINE for i in range(len(syms)):NEWLINE syms[i] = syms[i].strip()NEWLINE return symsNEWLINE else:NEWLINE return []NEWLINENEWLINENEWLINEdef countPar(row: str) -> Tuple[int, int, int]: # 检测三类括号的数量。NEWLINE lparNum = row.count('(')NEWLINE rparNum = row.count(')')NEWLINE lbraceNum = row.count('{')NEWLINE rbraceNum = row.count('}')NEWLINE lbracketNum = row.count('[')NEWLINE rbracketNum = row.count(']')NEWLINENEWLINE return lparNum - rparNum, lbraceNum - rbraceNum, lbracketNum - rbracketNum # 返回左括号数量减去右括号数量。NEWLINENEWLINENEWLINEdef checkPar(row: str) -> int:NEWLINE a, b, c = countPar(row)NEWLINE if (a == 0) & (b == 0) & (c == 0):NEWLINE return 1NEWLINE else:NEWLINE if (a < 0) | (b < 0) | (c < 0):NEWLINE return -1NEWLINE else:NEWLINE return 0NEWLINENEWLINENEWLINEdef getBracketedContent(row: str) -> Tuple[str, str, str]: # 获取任何类型括号最外层内部的东西。(不是小括号!!!)NEWLINE # 返回值:一个表示括号类型的量,以及一个有关括号中内容的字符串,以及括号前的内容。NEWLINE lst = [-1, -1, -1]NEWLINE symList = ['(', '[', '{']NEWLINE symListCouple = [')', ']', '}']NEWLINE length = len(row)NEWLINE for i in range(len(lst)):NEWLINE lst[i] = row.find(symList[i])NEWLINE if (lst[i] == -1):NEWLINE lst[i] = lengthNEWLINE minVal = min(lst)NEWLINE if (minVal == length): # 说明根本没括号NEWLINE return '', '', row[:minVal] # 所以返回值不仅没有括号,还没有括号中的内容(废话),只是返回括号前面的东西。NEWLINE else:NEWLINE pos = lst.index(minVal) # 获取最小值的索引NEWLINE regex = r'[%s](.*)[%s]' % (symList[pos], symListCouple[pos])NEWLINE return symList[pos], getInfoFromRegex(regex=regex, st=row), row[:minVal]NEWLINENEWLINENEWLINEdef getFuncArgs(row: str) -> List[str]: # 获取函数的输入参数。NEWLINENEWLINE s = getInfoFromRegex(regex=r'[(](.*)[)]', st=row)NEWLINENEWLINE li = getWordsFromString(s)NEWLINENEWLINE if (len(li) > 0):NEWLINE if (li[0] == 'self'): # 不允许函数的第一个参数名字叫self。NEWLINE li.pop(0)NEWLINE for i in range(len(li)):NEWLINE eqSymPos = li[i].find('=')NEWLINENEWLINE if (eqSymPos != -1): # 如果eqSymPos中有一个等号NEWLINE li[i] = li[i][:eqSymPos] # 那么将等号去除NEWLINE colonSymPos = li[i].find(':')NEWLINE if colonSymPos != -1:NEWLINE li[i] = li[i][:colonSymPos]NEWLINENEWLINE return liNEWLINENEWLINENEWLINEdef getFuncName(row: str) -> str: # 获取函数的名称。NEWLINE return getInfoFromRegex(regex=r'def\s(.*?)[(]', st=row) # 注意,需要匹配函数名,其中还有个空格。NEWLINENEWLINENEWLINEdef getLocalVarNames(row: str) -> List[str]: # 获取局部变量的名称。NEWLINE li = getInfoFromRegex(regex=r'(.*?)[=]', st=row) # 注意,需要匹配局部变量的名称,其中还有个空格。NEWLINENEWLINE words = getWordsFromString(li)NEWLINE result = []NEWLINE for w in words: # 如果是函数的方法,则不可。NEWLINE if (w.find('.') == -1):NEWLINE result.append(w)NEWLINE return resultNEWLINENEWLINENEWLINEdef is_number(str_number: str) -> bool:NEWLINE if (str_number.split(".")[0]).isdigit() or str_number.isdigit() or (str_number.split('-')[-1]).split(".")[NEWLINE -1].isdigit():NEWLINE return TrueNEWLINE else:NEWLINE return FalseNEWLINENEWLINENEWLINEdef getForVariables(row: str) -> List[int]:NEWLINE '''NEWLINE 获取for循环中定义的变量。NEWLINE '''NEWLINE s = getInfoFromRegex(r'for(.*?)in', row)NEWLINE s = s.strip()NEWLINE return getWordsFromString(s)NEWLINENEWLINENEWLINEdef getVarType(row: str) -> str:NEWLINE '''NEWLINE 获取变量的类型,比如集合,数字等等。NEWLINE '''NEWLINE bracket, content, outer = getBracketedContent(row)NEWLINE li = outer.split('=')NEWLINE if (len(li) >= 1):NEWLINENEWLINE if (li[1].strip() == ''): # 这种情况下为直接赋值的语句,NEWLINE if (bracket == '('):NEWLINE return ':tuple'NEWLINE elif (bracket == '['):NEWLINE return ':list'NEWLINE else:NEWLINE st = li[1].split(',')[0]NEWLINE if (is_number(st)):NEWLINE return ':number'NEWLINENEWLINE return ''NEWLINENEWLINENEWLINEclass Row():NEWLINE def __init__(self, pos: int, text: str, indent: int) -> None:NEWLINE self.pos = posNEWLINE self.text = textNEWLINE self.indent = indentNEWLINENEWLINE def __repr__(self) -> str:NEWLINE return 'row:' + repr(self.pos) + "\t indent:" + repr(self.indent) + "\t text:" + self.text + '\n'NEWLINENEWLINENEWLINEdef regularize(rawText: List[str]) -> List[Row]:NEWLINE global kwdTuple, indexList, charStrNEWLINENEWLINE f = rawText # 获取打开的文件数组,每个元素是一行。NEWLINE regularifiedText = ''NEWLINE rowList = []NEWLINE currentRow = Row(0, '', 0) # 创建一个没有含义的对象,这样方便类型检查。NEWLINE inStaticFunction = FalseNEWLINE inFunctionDefinition = FalseNEWLINE skipLine = FalseNEWLINE currentFuncIndent = 0NEWLINE currentIndent = 0NEWLINE funcIndent = 0NEWLINENEWLINE for i, l in enumerate(f):NEWLINE l = removeStringContent(l)NEWLINE l = removeComment(l)NEWLINENEWLINE if (skipLine == False):NEWLINE row, currentIndent = getIndent(l) # 获取当前的行名和缩进,同时修剪掉行首的空格NEWLINE currentRow = Row(i, row, currentIndent)NEWLINE rowList.append(currentRow)NEWLINENEWLINE else:NEWLINE currentRow.text += l.strip() # 如果判断出这一行还没有结束,就不用获取当前的缩进,直接缀连即可。NEWLINE rowList.append(Row(i, '', 0)) # 这一行相应的没有任何内容NEWLINENEWLINE cp = checkPar(currentRow.text)NEWLINENEWLINE if (cp == 0): # 如果括号不匹配,那么就再继续进行,直至寻找到符合要求的行为止。NEWLINE skipLine = TrueNEWLINE if (len(currentRow.text) >= 200): # 长度超出,强行退出。NEWLINE skipLine = FalseNEWLINE continueNEWLINE elif (cp == -1): # 如果右边括号反倒更多,就跳出这种情况。NEWLINE skipLine = FalseNEWLINE continueNEWLINE else:NEWLINE skipLine = FalseNEWLINE return rowListNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE regularize(['', '', ''])NEWLINE import numpy as npNEWLINEimport copyNEWLINENEWLINEfrom . import ekf_utilsNEWLINENEWLINEgtrack_MIN_DISPERSION_ALPHA = 0.1NEWLINEgtrack_EST_POINTS = 10NEWLINEgtrack_MIN_POINTS_TO_UPDATE_DISPERSION = 3NEWLINEgtrack_KNOWN_TARGET_POINTS_THRESHOLD = 50NEWLINENEWLINENEWLINE# GTRACK Module calls this function to instantiate GTRACK Unit with desired configuration parameters. NEWLINE# Function returns a handle, which is used my module to call units' methodsNEWLINENEWLINEdef unit_create(params):NEWLINE inst = ekf_utils.GtrackUnitInstance()NEWLINENEWLINE inst.gatingParams = params.gatingParamsNEWLINE inst.stateParams = params.stateParamsNEWLINE inst.allocationParams = params.allocationParamsNEWLINE inst.unrollingParams = params.unrollingParamsNEWLINE inst.variationParams = params.variationParamsNEWLINE inst.sceneryParams = params.sceneryParamsNEWLINENEWLINE inst.uid = params.uidNEWLINE inst.maxAcceleration = params.maxAccelerationNEWLINE inst.maxRadialVelocity = params.maxRadialVelocityNEWLINE inst.radialVelocityResolution = params.radialVelocityResolutionNEWLINE inst.verbose = params.verboseNEWLINE inst.initialRadialVelocity = params.initialRadialVelocityNEWLINENEWLINE inst.F4 = params.F4NEWLINE inst.Q4 = params.Q4NEWLINE inst.F6 = params.F6NEWLINE inst.Q6 = params.Q6NEWLINENEWLINE if params.stateVectorType == ekf_utils.gtrack_STATE_VECTOR_TYPE().gtrack_STATE_VECTORS_2DA:NEWLINE inst.stateVectorType = ekf_utils.gtrack_STATE_VECTOR_TYPE().gtrack_STATE_VECTORS_2DANEWLINE inst.stateVectorLength = 6NEWLINE inst.measurementVectorLength = 3NEWLINE else:NEWLINE raise ValueError('not supported, unit_create')NEWLINENEWLINE inst.dt = params.deltaTNEWLINE inst.state = ekf_utils.TrackState().TRACK_STATE_FREENEWLINENEWLINE return instNEWLINENEWLINENEWLINE# GTRACK Module calls this function to run GTRACK unit prediction step NEWLINEdef unit_predict(handle):NEWLINE inst = handleNEWLINE inst.heartBeatCount += 1NEWLINE temp1 = np.zeros(shape=(36,), dtype=np.float32)NEWLINE temp2 = np.zeros(shape=(36,), dtype=np.float32)NEWLINE temp3 = np.zeros(shape=(36,), dtype=np.float32)NEWLINENEWLINE # Current state vector lengthNEWLINE sLen = inst.stateVectorLengthNEWLINENEWLINE if inst.processVariance != 0:NEWLINE inst.S_apriori_hat = ekf_utils.gtrack_matrixMultiply(sLen, sLen, 1, inst.F, inst.S_hat)NEWLINE temp1 = ekf_utils.gtrack_matrixMultiply(6, 6, 6, inst.F, inst.P_hat)NEWLINE temp2 = ekf_utils.gtrack_matrixTransposeMultiply(6, 6, 6, temp1, inst.F)NEWLINE temp1 = ekf_utils.gtrack_matrixScalerMultiply(sLen, sLen, inst.Q, inst.processVariance)NEWLINE temp3 = ekf_utils.gtrack_matrixAdd(sLen, sLen, temp1, temp2)NEWLINENEWLINE inst.P_apriori_hat = ekf_utils.gtrack_matrixMakeSymmetrical(sLen, temp3)NEWLINE else:NEWLINE inst.S_apriori_hat = copy.deepcopy(inst.S_hat)NEWLINE inst.P_apriori_hat = copy.deepcopy(inst.P_hat)NEWLINENEWLINE ekf_utils.gtrack_cartesian2spherical(inst.stateVectorType, inst.S_apriori_hat, inst.H_s)NEWLINENEWLINENEWLINE# GTRACK Module calls this function to obtain the measurement vector scoring from the GTRACK unit perspectiveNEWLINEdef unit_score(handle, point, best_score, best_ind, num):NEWLINE limits = np.zeros(shape=(3,), dtype=np.float32)NEWLINE u_tilda = np.zeros(shape=(3,), dtype=np.float32)NEWLINENEWLINE inst = handleNEWLINENEWLINE limits[0] = inst.gatingParams.limits[0].lengthNEWLINE limits[1] = inst.gatingParams.limits[0].widthNEWLINE limits[2] = inst.gatingParams.limits[0].velNEWLINENEWLINE if inst.processVariance == 0:NEWLINE inst.G = 1NEWLINE else:NEWLINE inst.G = ekf_utils.gtrack_gateCreateLim(inst.gatingParams.volume, inst.gC_inv, inst.H_s[0], limits)NEWLINENEWLINE det = ekf_utils.gtrack_matrixDet3(inst.gC)NEWLINENEWLINE log_det = np.float32(np.log(det))NEWLINENEWLINE for n in range(num):NEWLINE if best_ind[n] == ekf_utils.gtrack_ID_POINT_BEHIND_THE_WALL:NEWLINE continueNEWLINENEWLINE u_tilda[0] = np.float32(point[n].range - inst.H_s[0])NEWLINE u_tilda[1] = np.float32(point[n].angle - inst.H_s[1])NEWLINENEWLINE if inst.velocityHandling < ekf_utils.VelocityHandlingState().VELOCITY_LOCKED:NEWLINE # Radial velocity estimation is not yet known, unroll based on velocity measured at allocation timeNEWLINE rv_out = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.allocationVelocity,NEWLINE point[n].doppler)NEWLINE u_tilda[2] = np.float32(rv_out - inst.allocationVelocity)NEWLINE else:NEWLINE # Radial velocity estimation is known NEWLINE rv_out = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.H_s[2], point[n].doppler)NEWLINE u_tilda[2] = np.float32(rv_out - inst.H_s[2])NEWLINENEWLINE chi2 = ekf_utils.gtrack_computeMahalanobis3(u_tilda, inst.gC_inv)NEWLINE # print(inst.gC_inv)NEWLINENEWLINE if chi2 < inst.G:NEWLINE score = np.float32(log_det + chi2)NEWLINE if score < best_score[n]:NEWLINE best_score[n] = scoreNEWLINE best_ind[n] = np.uint8(inst.uid)NEWLINE point[n].doppler = rv_outNEWLINENEWLINENEWLINE# GTRACK Module calls this function to start target tracking. This function is called during modules' allocation step,NEWLINE# once new set of points passes allocation thresholds NEWLINEdef unit_start(handle, time_stamp, tid, um):NEWLINE inst = handleNEWLINENEWLINE m = np.zeros(shape=(3,), dtype=np.float32)NEWLINENEWLINE inst.tid = tidNEWLINE inst.heartBeatCount = time_stampNEWLINE inst.allocationTime = time_stampNEWLINE inst.allocationRange = um[0]NEWLINE inst.allocationVelocity = um[2]NEWLINE inst.associatedPoints = 0NEWLINENEWLINE inst.state = ekf_utils.TrackState().TRACK_STATE_DETECTIONNEWLINE inst.currentStateVectorType = ekf_utils.gtrack_STATE_VECTOR_TYPE().gtrack_STATE_VECTORS_2DANEWLINE inst.stateVectorLength = 6NEWLINENEWLINE inst.processVariance = (0.5 * inst.maxAcceleration) * (0.5 * inst.maxAcceleration)NEWLINENEWLINE inst.F = inst.F6NEWLINE inst.Q = inst.Q6NEWLINENEWLINE inst.velocityHandling = ekf_utils.VelocityHandlingState().VELOCITY_INITNEWLINENEWLINE m[2] = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.initialRadialVelocity, um[2])NEWLINENEWLINE inst.rangeRate = m[2]NEWLINENEWLINE m[0] = um[0]NEWLINE m[1] = um[1]NEWLINENEWLINE ekf_utils.gtrack_spherical2cartesian(inst.currentStateVectorType, m, inst.S_apriori_hat)NEWLINE inst.H_s = copy.deepcopy(m)NEWLINENEWLINE inst.P_apriori_hat = copy.deepcopy(ekf_utils.pinit6x6)NEWLINE inst.gD = copy.deepcopy(ekf_utils.zero3x3)NEWLINE inst.G = 1.NEWLINENEWLINENEWLINE# GTRACK Module calls this function to perform an update step for the tracking unit. NEWLINEdef unit_update(handle, point, var, pInd, num):NEWLINE J = np.zeros(shape=(18,), dtype=np.float32) # 3x6NEWLINE PJ = np.zeros(shape=(18,), dtype=np.float32) # 6x3NEWLINE JPJ = np.zeros(shape=(9,), dtype=np.float32) # 3x3NEWLINE U = np.zeros(shape=(3,), dtype=np.float32)NEWLINE u_tilda = np.zeros(shape=(3,), dtype=np.float32)NEWLINE cC = np.zeros(shape=(9,), dtype=np.float32)NEWLINE cC_inv = np.zeros(shape=(9,), dtype=np.float32)NEWLINE K = np.zeros(shape=(18,), dtype=np.float32) # 6x3NEWLINENEWLINE u_mean = ekf_utils.gtrack_measurementPoint()NEWLINENEWLINE D = np.zeros(shape=(9,), dtype=np.float32)NEWLINE Rm = np.zeros(shape=(9,), dtype=np.float32)NEWLINE Rc = np.zeros(shape=(9,), dtype=np.float32)NEWLINENEWLINE temp1 = np.zeros(shape=(36,), dtype=np.float32)NEWLINENEWLINE inst = handleNEWLINE mlen = inst.measurementVectorLengthNEWLINE slen = inst.stateVectorLengthNEWLINENEWLINE myPointNum = 0NEWLINENEWLINE for n in range(num):NEWLINE if pInd[n] == inst.uid:NEWLINE myPointNum += 1NEWLINE u_mean.range += point[n].rangeNEWLINE u_mean.angle += point[n].angleNEWLINENEWLINE if var != None:NEWLINE Rm[0] += var[n].rangeVarNEWLINE Rm[4] += var[n].angleVarNEWLINE Rm[8] += var[n].dopplerVarNEWLINENEWLINE if myPointNum == 1:NEWLINE rvPilot = point[n].dopplerNEWLINE u_mean.doppler = rvPilotNEWLINE else:NEWLINE rvCurrent = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, rvPilot, point[n].doppler)NEWLINE point[n].doppler = rvCurrentNEWLINE u_mean.doppler += rvCurrentNEWLINENEWLINE if myPointNum == 0:NEWLINE # INACTIVENEWLINE if (np.abs(inst.S_hat[2]) < inst.radialVelocityResolution) and \NEWLINE (np.abs(inst.S_hat[3]) < inst.radialVelocityResolution):NEWLINE inst.S_hat = np.zeros(shape=(inst.S_hat.shape), dtype=np.float32)NEWLINENEWLINE inst.S_hat[0] = inst.S_apriori_hat[0]NEWLINE inst.S_hat[1] = inst.S_apriori_hat[1]NEWLINENEWLINE inst.P_hat = copy.deepcopy(inst.P_apriori_hat)NEWLINENEWLINE inst.processVariance = 0NEWLINE else:NEWLINE inst.S_hat = copy.deepcopy(inst.S_apriori_hat)NEWLINE inst.P_hat = copy.deepcopy(inst.P_apriori_hat)NEWLINENEWLINE unit_event(inst, myPointNum)NEWLINE return inst.stateNEWLINENEWLINE inst.associatedPoints += myPointNumNEWLINENEWLINE if inst.processVariance == 0:NEWLINE inst.processVariance = np.float32((0.5 * (inst.maxAcceleration)) * (0.5 * (inst.maxAcceleration)))NEWLINENEWLINE u_mean.range = np.float32(u_mean.range / myPointNum)NEWLINE u_mean.angle = np.float32(u_mean.angle / myPointNum)NEWLINE u_mean.doppler = np.float32(u_mean.doppler / myPointNum)NEWLINENEWLINE if var != None:NEWLINE Rm[0] = np.float32(Rm[0] / myPointNum)NEWLINE Rm[4] = np.float32(Rm[4] / myPointNum)NEWLINE Rm[8] = np.float32(Rm[8] / myPointNum)NEWLINE else:NEWLINE dRangeVar = np.float32((inst.variationParams.lengthStd) * (inst.variationParams.lengthStd))NEWLINE dDopplerVar = np.float32((inst.variationParams.dopplerStd) * (inst.variationParams.dopplerStd))NEWLINENEWLINE Rm[0] = dRangeVarNEWLINE angleStd = np.float32(2 * np.float32(np.arctan(0.5 * (inst.variationParams.widthStd) / inst.H_s[0])))NEWLINE Rm[4] = angleStd * angleStdNEWLINE Rm[8] = dDopplerVarNEWLINENEWLINE U[0] = u_mean.rangeNEWLINE U[1] = u_mean.angleNEWLINE U[2] = u_mean.dopplerNEWLINENEWLINE velocity_state_handling(inst, U)NEWLINENEWLINE if myPointNum > gtrack_MIN_POINTS_TO_UPDATE_DISPERSION:NEWLINE for n in range(num):NEWLINE if pInd[n] == inst.uid:NEWLINE D[0] += np.float32((point[n].range - u_mean.range) * (point[n].range - u_mean.range))NEWLINE D[4] += np.float32((point[n].angle - u_mean.angle) * (point[n].angle - u_mean.angle))NEWLINE D[8] += np.float32((point[n].doppler - u_mean.doppler) * (point[n].doppler - u_mean.doppler))NEWLINE D[1] += np.float32((point[n].range - u_mean.range) * (point[n].angle - u_mean.angle))NEWLINE D[2] += np.float32((point[n].range - u_mean.range) * (point[n].doppler - u_mean.doppler))NEWLINE D[5] += np.float32((point[n].angle - u_mean.angle) * (point[n].doppler - u_mean.doppler))NEWLINENEWLINE D[0] = np.float32(D[0] / myPointNum)NEWLINE D[4] = np.float32(D[4] / myPointNum)NEWLINE D[8] = np.float32(D[8] / myPointNum)NEWLINE D[1] = np.float32(D[1] / myPointNum)NEWLINE D[2] = np.float32(D[2] / myPointNum)NEWLINE D[5] = np.float32(D[5] / myPointNum)NEWLINENEWLINE alpha = np.float32(myPointNum / (inst.associatedPoints))NEWLINE # print(alpha)NEWLINE if alpha < gtrack_MIN_DISPERSION_ALPHA:NEWLINE alpha = gtrack_MIN_DISPERSION_ALPHANEWLINENEWLINE inst.gD[0] = np.float32((1. - alpha) * inst.gD[0] + alpha * D[0])NEWLINE inst.gD[1] = np.float32((1. - alpha) * inst.gD[1] + alpha * D[1])NEWLINE inst.gD[2] = np.float32((1. - alpha) * inst.gD[2] + alpha * D[2])NEWLINE inst.gD[3] = np.float32(inst.gD[1])NEWLINE inst.gD[4] = np.float32((1. - alpha) * inst.gD[4] + alpha * D[4])NEWLINE inst.gD[5] = np.float32((1. - alpha) * inst.gD[5] + alpha * D[5])NEWLINE inst.gD[6] = np.float32(inst.gD[2])NEWLINE inst.gD[7] = np.float32(inst.gD[5])NEWLINE inst.gD[8] = np.float32((1. - alpha) * inst.gD[8] + alpha * D[8])NEWLINENEWLINE if myPointNum > gtrack_EST_POINTS:NEWLINE alpha = 0NEWLINE else:NEWLINE alpha = np.float32((gtrack_EST_POINTS - myPointNum) / ((gtrack_EST_POINTS - 1) * myPointNum))NEWLINENEWLINE Rc[0] = np.float32((Rm[0] / myPointNum) + alpha * (inst.gD[0]))NEWLINE Rc[4] = np.float32((Rm[4] / myPointNum) + alpha * (inst.gD[4]))NEWLINE Rc[8] = np.float32((Rm[8] / myPointNum) + alpha * (inst.gD[8]))NEWLINENEWLINE ekf_utils.gtrack_computeJacobian(inst.currentStateVectorType, inst.S_apriori_hat, J)NEWLINENEWLINE u_tilda = ekf_utils.gtrack_matrixSub(mlen, 1, U, inst.H_s)NEWLINE PJ = ekf_utils.gtrack_matrixComputePJT(inst.P_apriori_hat, J)NEWLINE JPJ = ekf_utils.gtrack_matrixMultiply(mlen, slen, mlen, J, PJ)NEWLINE cC = ekf_utils.gtrack_matrixAdd(mlen, mlen, JPJ, Rc)NEWLINENEWLINE cC_inv = ekf_utils.gtrack_matrixInv3(cC)NEWLINENEWLINE K = ekf_utils.gtrack_matrixMultiply(slen, mlen, mlen, PJ, cC_inv)NEWLINENEWLINE temp1 = ekf_utils.gtrack_matrixMultiply(slen, mlen, 1, K, u_tilda)NEWLINE inst.S_hat = ekf_utils.gtrack_matrixAdd(slen, 1, inst.S_apriori_hat, temp1)NEWLINE # print(temp1)NEWLINENEWLINE temp1 = ekf_utils.gtrack_matrixTransposeMultiply(slen, mlen, slen, K, PJ)NEWLINE inst.P_hat = ekf_utils.gtrack_matrixSub(slen, slen, inst.P_apriori_hat, temp1)NEWLINENEWLINE temp1 = ekf_utils.gtrack_matrixAdd(mlen, mlen, JPJ, Rm)NEWLINE inst.gC = ekf_utils.gtrack_matrixAdd(mlen, mlen, temp1, inst.gD)NEWLINENEWLINE inst.gC_inv = ekf_utils.gtrack_matrixInv3(inst.gC)NEWLINENEWLINE unit_event(inst, myPointNum)NEWLINE return inst.stateNEWLINENEWLINENEWLINE# this is the helper function for GTRACK unit updateNEWLINEdef velocity_state_handling(handle, um):NEWLINE inst = handleNEWLINE rvIn = um[2]NEWLINE # print(inst.velocityHandling)NEWLINENEWLINE if inst.velocityHandling == ekf_utils.VelocityHandlingState().VELOCITY_INIT:NEWLINE um[2] = inst.rangeRateNEWLINE inst.velocityHandling = ekf_utils.VelocityHandlingState().VELOCITY_RATE_FILTERNEWLINE elif inst.velocityHandling == ekf_utils.VelocityHandlingState().VELOCITY_RATE_FILTER:NEWLINE instanteneousRangeRate = np.float32(NEWLINE (um[0] - inst.allocationRange) / ((inst.heartBeatCount - inst.allocationTime) * (inst.dt)))NEWLINE inst.rangeRate = np.float32((inst.unrollingParams.alpha) * (inst.rangeRate) + (NEWLINE 1 - (inst.unrollingParams.alpha)) * instanteneousRangeRate)NEWLINE um[2] = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.rangeRate, rvIn)NEWLINENEWLINE rrError = np.float32((instanteneousRangeRate - inst.rangeRate) / inst.rangeRate)NEWLINENEWLINE if np.abs(rrError) < inst.unrollingParams.confidence:NEWLINE inst.velocityHandling = ekf_utils.VelocityHandlingState().VELOCITY_TRACKINGNEWLINE elif inst.velocityHandling == ekf_utils.VelocityHandlingState().VELOCITY_TRACKING:NEWLINE instanteneousRangeRate = np.float32(NEWLINE (um[0] - inst.allocationRange) / ((inst.heartBeatCount - inst.allocationTime) * inst.dt))NEWLINENEWLINE inst.rangeRate = np.float32(NEWLINE (inst.unrollingParams.alpha) * inst.rangeRate + (1 - inst.unrollingParams.alpha) * instanteneousRangeRate)NEWLINE um[2] = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.rangeRate, rvIn)NEWLINE rvError = np.float32((inst.H_s[2] - um[2]) / um[2])NEWLINE if np.abs(rvError) < 0.1:NEWLINE inst.velocityHandling = ekf_utils.VelocityHandlingState().VELOCITY_LOCKEDNEWLINE elif inst.velocityHandling == ekf_utils.VelocityHandlingState().VELOCITY_LOCKED:NEWLINE um[2] = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.H_s[2], um[2])NEWLINENEWLINENEWLINE# GTRACK Module calls this function to run GTRACK unit level state machineNEWLINEdef unit_event(handle, num):NEWLINE inst = handleNEWLINENEWLINE if inst.state == ekf_utils.TrackState().TRACK_STATE_DETECTION:NEWLINE if num > inst.allocationParams.pointsThre:NEWLINE inst.detect2freeCount = 0NEWLINE inst.detect2activeCount += 1NEWLINE if inst.detect2activeCount > inst.stateParams.det2actThre:NEWLINE inst.state = ekf_utils.TrackState().TRACK_STATE_ACTIVENEWLINE else:NEWLINE if num == 0:NEWLINE inst.detect2freeCount += 1NEWLINE if inst.detect2activeCount > 0:NEWLINE inst.detect2activeCount -= 1NEWLINE if inst.detect2freeCount > inst.stateParams.det2freeThre:NEWLINE inst.state = ekf_utils.TrackState().TRACK_STATE_FREENEWLINE elif inst.state == ekf_utils.TrackState().TRACK_STATE_ACTIVE:NEWLINE if num != 0:NEWLINE inst.active2freeCount = 0NEWLINE else:NEWLINE inst.active2freeCount += 1NEWLINENEWLINE if inst.sceneryParams.numStaticBoxes != 0:NEWLINE thre = inst.stateParams.exit2freeThreNEWLINE for numBoxes in range(inst.sceneryParams.numStaticBoxes):NEWLINE if ekf_utils.isPointInsideBox(inst.S_hat[0], inst.S_hat[1],NEWLINE inst.sceneryParams.boundaryBox[numBoxes]) == 1:NEWLINE if inst.processVariance == 0:NEWLINE thre = inst.stateParams.static2freeThreNEWLINE else:NEWLINE thre = inst.stateParams.active2freeThreNEWLINE breakNEWLINE else:NEWLINE thre = inst.stateParams.active2freeThreNEWLINENEWLINE if thre > inst.heartBeatCount:NEWLINE thre = np.uint16(inst.heartBeatCount)NEWLINENEWLINE if inst.active2freeCount > thre:NEWLINE inst.state = ekf_utils.TrackState().TRACK_STATE_FREENEWLINENEWLINENEWLINE# GTRACK Module calls this function to report GTRACK unit results to the target descriptorNEWLINEdef unit_report(handle, target):NEWLINE inst = handleNEWLINENEWLINE target.uid = inst.uidNEWLINE target.tid = inst.tidNEWLINENEWLINE target.S = copy.deepcopy(inst.S_hat)NEWLINE target.EC = copy.deepcopy(inst.gC_inv)NEWLINE target.G = inst.GNEWLINE import numpy as npNEWLINEimport sysNEWLINEimport osNEWLINEimport timeNEWLINEimport copyNEWLINEimport datetimeNEWLINEimport pickleNEWLINEimport torch.nn as nnNEWLINEfrom torch.utils.data import DataLoaderNEWLINEimport torch.optim as optimNEWLINEimport torch.optim.lr_scheduler as lr_schedulerNEWLINEimport argparseNEWLINEimport platformNEWLINEimport subprocessNEWLINEfrom sklearn.metrics import roc_auc_score, average_precision_scoreNEWLINEfrom social_data_loader import SocialEvolutionDatasetNEWLINEfrom github_data_loader import GithubDatasetNEWLINEfrom example_data_loader import ExampleDatasetNEWLINEfrom utils import *NEWLINEfrom dyrep import DyRepNEWLINEfrom freq import FreqBaselineNEWLINENEWLINEdef load_checkpoint(file):NEWLINE # TODO: Loading the checkpoint stopped working, need to fix.NEWLINE print('loading the model')NEWLINE state = torch.load(file)NEWLINE pos1 = file.find('checkpoint_dygraphs')NEWLINE experiment_ID = str.join('_', file[pos1:].split('_')[2:-2])NEWLINE model.load_state_dict(state['state_dict'])NEWLINE optimizer.load_state_dict(state['optimizer'])NEWLINE scheduler.load_state_dict(state['scheduler'])NEWLINE model.Lambda_dict = state['Lambda_dict']NEWLINE model.time_keys = state['time_keys']NEWLINE print('loading from epoch %d, batch %d done' % (state['epoch'], state['batch_idx']))NEWLINE return state['epoch'], state['batch_idx'], state['time_bar'], state['node_degree_global'], experiment_IDNEWLINENEWLINENEWLINEdef save_checkpoint(batch_idx, epoch):NEWLINE try:NEWLINE fname = '%s/checkpoints/checkpoint_dygraphs_%s_epoch%d_batch%d.pth.tar' % (args.results, experiment_ID, epoch, batch_idx)NEWLINE state = {NEWLINE 'epoch': epoch,NEWLINE 'batch_idx': batch_idx,NEWLINE 'args': args,NEWLINE 'time_bar': time_bar,NEWLINE 'node_degree_global': node_degree_global,NEWLINE 'Lambda_dict': model.Lambda_dict,NEWLINE 'time_keys': model.time_keys,NEWLINE 'state_dict': model.state_dict(),NEWLINE 'scheduler': scheduler.state_dict(),NEWLINE 'optimizer': optimizer.state_dict(),NEWLINE }NEWLINE if os.path.isfile(fname):NEWLINE print('WARNING: file %s exists and will be overwritten' % fname)NEWLINE torch.save(state, fname)NEWLINE print('the model is saved to %s' % fname)NEWLINE except Exception as e:NEWLINE print('error saving the model', e)NEWLINENEWLINENEWLINEdef test(model, n_test_batches=10, epoch=0):NEWLINE model.eval()NEWLINE loss = 0NEWLINE losses =[ [np.Inf, 0], [np.Inf, 0] ]NEWLINE n_samples = 0NEWLINE # Time slots with 10 days intervals as in the DyRep paperNEWLINE timeslots = [t.toordinal() for t in test_loader.dataset.TEST_TIMESLOTS]NEWLINE event_types = list(test_loader.dataset.event_types_num.keys()) #['comm', 'assoc']NEWLINE # sort it by kNEWLINE for event_t in test_loader.dataset.event_types_num:NEWLINE event_types[test_loader.dataset.event_types_num[event_t]] = event_tNEWLINENEWLINE event_types += ['Com']NEWLINENEWLINE mar, hits_10 = {}, {}NEWLINE for event_t in event_types:NEWLINE mar[event_t] = []NEWLINE hits_10[event_t] = []NEWLINE for c, slot in enumerate(timeslots):NEWLINE mar[event_t].append([])NEWLINE hits_10[event_t].append([])NEWLINENEWLINENEWLINE start = time.time()NEWLINE with torch.no_grad():NEWLINE for batch_idx, data in enumerate(test_loader):NEWLINE data[2] = data[2].float().to(args.device)NEWLINE data[4] = data[4].double().to(args.device)NEWLINE data[5] = data[5].double()NEWLINE output = model(data)NEWLINE loss += (-torch.sum(torch.log(output[0]) + 1e-10) + torch.sum(output[1])).item()NEWLINE for i in range(len(losses)):NEWLINE m1 = output[i].min()NEWLINE m2 = output[i].max()NEWLINE if m1 < losses[i][0]:NEWLINE losses[i][0] = m1NEWLINE if m2 > losses[i][1]:NEWLINE losses[i][1] = m2NEWLINE n_samples += 1NEWLINE A_pred, Survival_term = output[2]NEWLINE u, v, k = data[0], data[1], data[3]NEWLINENEWLINE time_cur = data[5]NEWLINE m, h = MAR(A_pred, u, v, k, Survival_term=Survival_term, freq_prior=freq.H_train_norm if args.freq else None)NEWLINE assert len(time_cur) == len(m) == len(h) == len(k)NEWLINE for t, m, h, k_ in zip(time_cur, m, h, k):NEWLINE d = datetime.datetime.fromtimestamp(t.item()).toordinal()NEWLINE event_t = event_types[k_.item()]NEWLINE for c, slot in enumerate(timeslots):NEWLINE if d <= slot:NEWLINE mar[event_t][c].append(m)NEWLINE hits_10[event_t][c].append(h)NEWLINE if k_ > 0:NEWLINE mar['Com'][c].append(m)NEWLINE hits_10['Com'][c].append(h)NEWLINE if c > 0:NEWLINE assert slot > timeslots[c-1] and d > timeslots[c-1], (d, slot, timeslots[c-1])NEWLINE breakNEWLINENEWLINE if batch_idx % 10 == 0 and args.verbose:NEWLINE print('test', batch_idx)NEWLINENEWLINE if n_test_batches is not None and batch_idx >= n_test_batches - 1:NEWLINE breakNEWLINENEWLINE time_iter = time.time() - startNEWLINENEWLINE print('\nTEST batch={}/{}, loss={:.3f}, psi={}, loss1 min/max={:.4f}/{:.4f}, 'NEWLINE 'loss2 min/max={:.4f}/{:.4f}, integral time stamps={}, sec/iter={:.4f}'.NEWLINE format(batch_idx + 1, len(test_loader), (loss / n_samples),NEWLINE [model.psi[c].item() for c in range(len(model.psi))],NEWLINE losses[0][0], losses[0][1], losses[1][0], losses[1][1],NEWLINE len(model.Lambda_dict), time_iter / (batch_idx + 1)))NEWLINENEWLINE # Report results for different time slots in the test setNEWLINE if args.verbose:NEWLINE for c, slot in enumerate(timeslots):NEWLINE s = 'Slot {}: '.format(c)NEWLINE for event_t in event_types:NEWLINE sfx = '' if event_t == event_types[-1] else ', 'NEWLINE if len(mar[event_t][c]) > 0:NEWLINE s += '{} ({} events): MAR={:.2f}+-{:.2f}, HITS_10={:.3f}+-{:.3f}'.\NEWLINE format(event_t, len(mar[event_t][c]), np.mean(mar[event_t][c]), np.std(mar[event_t][c]),NEWLINE np.mean(hits_10[event_t][c]), np.std(hits_10[event_t][c]))NEWLINE else:NEWLINE s += '{} (no events)'.format(event_t)NEWLINE s += sfxNEWLINE print(s)NEWLINENEWLINE mar_all, hits_10_all = {}, {}NEWLINE for event_t in event_types:NEWLINE mar_all[event_t] = []NEWLINE hits_10_all[event_t] = []NEWLINE for c, slot in enumerate(timeslots):NEWLINE mar_all[event_t].extend(mar[event_t][c])NEWLINE hits_10_all[event_t].extend(hits_10[event_t][c])NEWLINENEWLINE s = 'Epoch {}: results per event type for all test time slots: \n'.format(epoch)NEWLINE print(''.join(['-']*100))NEWLINE for event_t in event_types:NEWLINE if len(mar_all[event_t]) > 0:NEWLINE s += '====== {:10s}\t ({:7s} events): \tMAR={:.2f}+-{:.2f}\t HITS_10={:.3f}+-{:.3f}'.\NEWLINE format(event_t, str(len(mar_all[event_t])), np.mean(mar_all[event_t]), np.std(mar_all[event_t]),NEWLINE np.mean(hits_10_all[event_t]), np.std(hits_10_all[event_t]))NEWLINE else:NEWLINE s += '====== {:10s}\t (no events)'.format(event_t)NEWLINE if event_t != event_types[-1]:NEWLINE s += '\n'NEWLINE print(s)NEWLINE print(''.join(['-'] * 100))NEWLINENEWLINE return mar_all, hits_10_all, loss / n_samplesNEWLINENEWLINENEWLINEdef get_temporal_variables():NEWLINE variables = {}NEWLINE variables['time_bar'] = copy.deepcopy(time_bar)NEWLINE variables['node_degree_global'] = copy.deepcopy(node_degree_global)NEWLINE variables['time_keys'] = copy.deepcopy(model.time_keys)NEWLINE variables['z'] = model.z.clone()NEWLINE variables['S'] = model.S.clone()NEWLINE variables['A'] = model.A.clone()NEWLINE variables['Lambda_dict'] = model.Lambda_dict.clone()NEWLINE return variablesNEWLINENEWLINENEWLINEdef set_temporal_variables(variables, model, train_loader, test_loader):NEWLINE time_bar = copy.deepcopy(variables['time_bar'])NEWLINE train_loader.dataset.time_bar = time_barNEWLINE test_loader.dataset.time_bar = time_barNEWLINE model.node_degree_global = copy.deepcopy(variables['node_degree_global'])NEWLINE model.time_keys = copy.deepcopy(variables['time_keys'])NEWLINE model.z = variables['z'].clone()NEWLINE model.S = variables['S'].clone()NEWLINE model.A = variables['A'].clone()NEWLINE model.Lambda_dict = variables['Lambda_dict'].clone()NEWLINE return time_barNEWLINENEWLINEif __name__ == '__main__':NEWLINENEWLINE parser = argparse.ArgumentParser(description='DyGraphs Training Parameters')NEWLINE parser.add_argument('--data_dir', type=str, default='./')NEWLINE parser.add_argument('--dataset', type=str, default='social', choices=['social', 'github', 'example'])NEWLINE parser.add_argument('--prob', default=0.8, help='filter events by this probability value in the Social Evolution data')NEWLINE parser.add_argument('--batch_size', type=int, default=200, help='batch size (sequence length)')NEWLINE parser.add_argument('--n_hid', type=int, default=32, help='hidden layer size')NEWLINE parser.add_argument('--epochs', type=int, default=5, help='number of epochs')NEWLINE parser.add_argument('--seed', type=int, default=1111, help='random seed')NEWLINE parser.add_argument('--lr', type=float, default=0.0002, help='Learning Rate')NEWLINE parser.add_argument('--lr_decay_step', type=str, default='10',NEWLINE help='number of epochs after which to reduce learning rate')NEWLINE parser.add_argument('--weight', type=float, default=1, help='weight for the second term in the loss')NEWLINE parser.add_argument('--wdecay', type=float, default=0, help='weight decay')NEWLINE parser.add_argument('--model', type=str, default='dyrep', help='trained model', choices=['dyrep', 'gcn', 'gat'])NEWLINE parser.add_argument('--bilinear', action='store_true', default=False, help='use bilinear intensity (omega) model')NEWLINE parser.add_argument('--bilinear_enc', action='store_true', default=False, help='use bilinear NRI')NEWLINE parser.add_argument('--encoder', type=str, default=None, choices=['linear', 'mlp', 'mlp1', 'rand'])NEWLINE parser.add_argument('--sparse', action='store_true', default=False,NEWLINE help='sparsity prior as in some tasks in Kipf et al., ICML 2018')NEWLINE parser.add_argument('--n_rel', type=int, default=2, help='number of edges for learned graphs')NEWLINE parser.add_argument('--device', type=str, default='cuda')NEWLINE parser.add_argument('--association', type=str, default='CloseFriend', help='The long term graph of the Social Evolution data used as long term edges')NEWLINE parser.add_argument('--resume', type=str, default='')NEWLINE parser.add_argument('--log_interval', type=int, default=20, help='print interval')NEWLINE parser.add_argument('--results', type=str, default='results', help='results file path')NEWLINE parser.add_argument('--soft_attn', action='store_true', default=False)NEWLINE parser.add_argument('--freq', action='store_true', default=False, help='use the Frequency bias')NEWLINE parser.add_argument('--verbose', action='store_true', default=False, help='print a lot of debugging stuff and results details')NEWLINENEWLINE args = parser.parse_args()NEWLINENEWLINE args.lr_decay_step = list(map(int, args.lr_decay_step.split(',')))NEWLINE args.torch = torch.__version__NEWLINE print('\n~~~~~ Script arguments ~~~~~')NEWLINE for arg in vars(args):NEWLINE print(arg, getattr(args, arg))NEWLINENEWLINE dt = datetime.datetime.now()NEWLINE print('start time:', dt)NEWLINE experiment_ID = '%s_%06d' % (platform.node(), dt.microsecond)NEWLINE print('experiment_ID: ', experiment_ID)NEWLINENEWLINE try:NEWLINE gitcommit = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('ascii').strip()NEWLINE print('gitcommit', gitcommit, '\n')NEWLINE except Exception as e:NEWLINE print('gitcommit is not available', e)NEWLINENEWLINE # Set seedNEWLINE np.random.seed(args.seed)NEWLINE rnd = np.random.RandomState(args.seed)NEWLINE torch.backends.cudnn.deterministic = TrueNEWLINE torch.backends.cudnn.benchmark = TrueNEWLINE torch.manual_seed(args.seed)NEWLINE torch.cuda.manual_seed(args.seed)NEWLINE torch.cuda.manual_seed_all(args.seed)NEWLINENEWLINE if args.dataset == 'social':NEWLINE try:NEWLINE data = SocialEvolutionDataset.load_data(args.data_dir, args.prob)NEWLINE except FileNotFoundError as e:NEWLINE raise ValueError('Original nor preprocessed data not found. Please consult README.md to prepare data before running the code. Error:', e)NEWLINENEWLINE train_set = SocialEvolutionDataset(data['initial_embeddings'], data['train'], args.association, verbose=args.verbose)NEWLINE test_set = SocialEvolutionDataset(data['initial_embeddings'], data['test'], args.association,NEWLINE data_train=data['train'], verbose=args.verbose)NEWLINE initial_embeddings = data['initial_embeddings'].copy()NEWLINE A_initial = train_set.get_Adjacency()[0]NEWLINE elif args.dataset == 'github':NEWLINE train_set = GithubDataset('train', data_dir=args.data_dir)NEWLINE test_set = GithubDataset('test', data_dir=args.data_dir)NEWLINE initial_embeddings = np.random.randn(train_set.N_nodes, args.n_hid)NEWLINE A_initial = train_set.get_Adjacency()[0]NEWLINE elif args.dataset == 'example':NEWLINE train_set = ExampleDataset('train')NEWLINE test_set = ExampleDataset('test')NEWLINE initial_embeddings = np.random.randn(train_set.N_nodes, args.n_hid)NEWLINE A_initial = train_set.get_Adjacency()[0]NEWLINE else:NEWLINE raise NotImplementedError(args.dataset)NEWLINENEWLINE def initalize_state(dataset, keepS=False):NEWLINE '''Initializes node embeddings and the graph to the original state after every epoch'''NEWLINENEWLINE Adj_all = dataset.get_Adjacency()[0]NEWLINENEWLINE if not isinstance(Adj_all, list):NEWLINE Adj_all = [Adj_all]NEWLINENEWLINE node_degree_global = []NEWLINE for rel, A in enumerate(Adj_all):NEWLINE node_degree_global.append(np.zeros(A.shape[0]))NEWLINE for u in range(A.shape[0]):NEWLINE node_degree_global[rel][u] = np.sum(A[u])NEWLINENEWLINE Adj_all = Adj_all[0]NEWLINE if args.verbose:NEWLINE print('Adj_all', Adj_all.shape, len(node_degree_global), node_degree_global[0].min(), node_degree_global[0].max())NEWLINE time_bar = np.zeros((dataset.N_nodes, 1)) + dataset.FIRST_DATE.timestamp()NEWLINENEWLINE model.initialize(node_embeddings=initial_embeddings,NEWLINE A_initial=Adj_all, keepS=keepS) # train_loader.dataset.H_trainNEWLINENEWLINENEWLINE model.to(args.device)NEWLINE return time_bar, node_degree_globalNEWLINENEWLINE train_loader = DataLoader(train_set, batch_size=args.batch_size, shuffle=False)NEWLINE test_loader = DataLoader(test_set, batch_size=args.batch_size, shuffle=False)NEWLINENEWLINE freq = FreqBaseline(train_set, test_set, verbose=args.verbose)NEWLINENEWLINE model = DyRep(node_embeddings=initial_embeddings,NEWLINE N_nodes=train_set.N_nodes,NEWLINE A_initial=A_initial,NEWLINE n_hidden=args.n_hid,NEWLINE bilinear=args.bilinear,NEWLINE bilinear_enc=args.bilinear_enc,NEWLINE sparse=args.sparse,NEWLINE encoder=args.encoder,NEWLINE n_rel=args.n_rel,NEWLINE rnd=rnd,NEWLINE device=args.device,NEWLINE model=args.model,NEWLINE soft_attn=args.soft_attn,NEWLINE freq=freq.H_train_norm if args.freq else None,NEWLINE verbose=args.verbose,NEWLINE node_degree_global=None).to(args.device)NEWLINENEWLINE print('') # new stringNEWLINE if args.verbose:NEWLINE print('model', model)NEWLINE print('number of training parameters: %d' %NEWLINE np.sum([np.prod(p.size()) if p.requires_grad else 0 for p in model.parameters()]))NEWLINENEWLINE params_main, params_enc = [], []NEWLINE for name, param in model.named_parameters():NEWLINE if name.find('encoder') >= 0 and param.requires_grad:NEWLINE params_enc.append(param)NEWLINE elif param.requires_grad:NEWLINE params_main.append(param)NEWLINENEWLINENEWLINE optimizer = optim.Adam([{"params": params_main, "weight_decay": args.wdecay},NEWLINE {"params": params_enc, "weight_decay": 1e-4}], lr=args.lr, betas=(0.5, 0.999))NEWLINE scheduler = lr_scheduler.MultiStepLR(optimizer, args.lr_decay_step, gamma=0.5)NEWLINENEWLINE if args.resume != '':NEWLINE epoch_start, batch_start, time_bar, node_degree_global, experiment_ID = load_checkpoint(args.resume)NEWLINE resume = TrueNEWLINE model.node_degree_global = node_degree_globalNEWLINE else:NEWLINE epoch_start = 1NEWLINE batch_start = 0NEWLINE resume = FalseNEWLINENEWLINENEWLINE losses_events, losses_nonevents, losses_KL, losses_sum = [], [], [], []NEWLINE test_MAR, test_HITS10, test_loss = [], [], []NEWLINE print('\nStarting training...')NEWLINE for epoch in range(epoch_start, args.epochs + 1):NEWLINENEWLINE if not (resume and epoch == epoch_start):NEWLINE # Reinitialize node embeddings and adjacency matrices, but keep the model parameters intactNEWLINE time_bar, node_degree_global = initalize_state(train_loader.dataset, keepS=epoch > 1)NEWLINE model.node_degree_global = node_degree_globalNEWLINENEWLINE train_loader.dataset.time_bar = time_barNEWLINE test_loader.dataset.time_bar = time_barNEWLINENEWLINE start = time.time()NEWLINENEWLINE for batch_idx, data_batch in enumerate(train_loader):NEWLINENEWLINE if resume and batch_idx <= batch_start:NEWLINE continueNEWLINE model.train()NEWLINENEWLINE optimizer.zero_grad()NEWLINE data_batch[2] = data_batch[2].float().to(args.device)NEWLINE data_batch[4] = data_batch[4].double().to(args.device)NEWLINE data_batch[5] = data_batch[5].double() # no need of GPUNEWLINE output = model(data_batch)NEWLINE losses = [-torch.sum(torch.log(output[0]) + 1e-10), args.weight * torch.sum(output[1])] #NEWLINENEWLINE # KL losses (one item per event)NEWLINE if len(output[-1]) > 0:NEWLINE losses.extend(output[-1])NEWLINE losses_KL.append(torch.stack(losses[2:]).sum().item())NEWLINENEWLINE loss = torch.sum(torch.stack(losses)) / args.batch_sizeNEWLINE loss.backward()NEWLINE nn.utils.clip_grad_value_(model.parameters(), 100)NEWLINENEWLINE optimizer.step()NEWLINENEWLINE losses_events.append(losses[0].item())NEWLINE losses_nonevents.append(losses[1].item())NEWLINE losses_sum.append(loss.item())NEWLINENEWLINE assert np.allclose(train_loader.dataset.time_bar, time_bar)NEWLINE assert np.allclose(test_loader.dataset.time_bar, time_bar)NEWLINENEWLINE model.psi.data = torch.clamp(model.psi.data, 1e-1, 1e+3) # to prevent overflow in computing LambdaNEWLINENEWLINE time_iter = time.time() - startNEWLINENEWLINE model.z = model.z.detach() # to reset the computational graph and avoid backpropagating second timeNEWLINE model.S = model.S.detach()NEWLINENEWLINE if (batch_idx + 1) % args.log_interval == 0 or batch_idx == len(train_loader) - 1:NEWLINE # Report (intermediate) resultsNEWLINENEWLINE print('\nTRAIN epoch={}/{}, batch={}/{}, sec/iter: {:.4f}, loss={:.3f}, loss components: {}'.format(epoch,NEWLINE args.epochs,NEWLINE batch_idx + 1,NEWLINE len(train_loader),NEWLINE time_iter / (batch_idx + 1),NEWLINE loss.item(), [l.item() for l in losses]))NEWLINENEWLINE if args.encoder is not None:NEWLINE S = model.S.data.cpu().numpy()NEWLINE S_batch = output[3].sum(axis=0)NEWLINE A_all_first, keys, A_all_last = train_loader.dataset.get_Adjacency(multirelations=True)NEWLINENEWLINE for survey, A_all in zip(['first', 'last'], [A_all_first, A_all_last]):NEWLINE for rel, key in enumerate(keys):NEWLINE if len(A_all.shape) == 2:NEWLINE A_all = A_all[:, :, None]NEWLINENEWLINE A = A_all[:, :, rel].flatten()NEWLINE for edge_type in range(S.shape[2]):NEWLINE prec = average_precision_score(y_true=A, y_score=S[:, :, edge_type].flatten())NEWLINE acc = np.mean(np.equal(A, (S[:, :, edge_type].flatten() > 0).astype(np.float)))NEWLINE auc = roc_auc_score(y_true=A, y_score=S[:, :, edge_type].flatten())NEWLINE c = np.corrcoef(A.flatten(), S[:, :, edge_type].flatten())[0, 1]NEWLINENEWLINE prec_batch = average_precision_score(y_true=A, y_score=S_batch[:, :, edge_type].flatten())NEWLINE acc_batch = np.mean(np.equal(A, (S_batch[:, :, edge_type].flatten() > 0).astype(np.float)))NEWLINE auc_batch = roc_auc_score(y_true=A, y_score=S_batch[:, :, edge_type].flatten())NEWLINE c_batch = np.corrcoef(A.flatten(), S_batch[:, :, edge_type].flatten())[0, 1]NEWLINENEWLINE print('{}: Edge {} with {}: acc={:.4f}, auc={:.4f}, prec={:.4f}, corr={:.4f}, 'NEWLINE 'acc_batch={:.4f}, auc_batch={:.4f}, prec_batch={:.4f}, corr_batch={:.4f}'.NEWLINE format(survey, edge_type, key, acc, auc, prec, c,NEWLINE acc_batch, auc_batch, prec_batch, c_batch))NEWLINENEWLINE for edge_type in range(S.shape[2]):NEWLINE c = np.corrcoef(freq.H_train.flatten(), S[:, :, edge_type].flatten())[0, 1]NEWLINE c_batch = np.corrcoef(freq.H_train.flatten(), S_batch[:, :, edge_type].flatten())[0, 1]NEWLINE print('Edge {} with H_train: corr={:.4f}, corr_batch={:.4f}'.format(edge_type, c, c_batch))NEWLINENEWLINENEWLINE # save node embeddings and other data before testing since these variables will be updated during testingNEWLINE variables = get_temporal_variables()NEWLINE if args.verbose:NEWLINE print('time', datetime.datetime.fromtimestamp(np.max(time_bar)))NEWLINE save_checkpoint(batch_idx + 1, epoch)NEWLINENEWLINE result = test(model, n_test_batches=None if batch_idx == len(train_loader) - 1 else 10, epoch=epoch)NEWLINE test_MAR.append(np.mean(result[0]['Com']))NEWLINE test_HITS10.append(np.mean(result[1]['Com']))NEWLINE test_loss.append(result[2])NEWLINENEWLINENEWLINE # restore node embeddings and other dataNEWLINE time_bar = set_temporal_variables(variables, model, train_loader, test_loader)NEWLINENEWLINE scheduler.step()NEWLINENEWLINENEWLINE print('end time:', datetime.datetime.now())NEWLINENEWLINE class StatusAuditoria:NEWLINE CONCLUIDO = "OK"NEWLINE NAO_CONCLUIDO = "NOK"NEWLINE import gymNEWLINEimport randomNEWLINEimport numpy as npNEWLINEimport argparseNEWLINEfrom arguments import get_argsNEWLINEfrom actorcritic import Actor, second, act, actorNEWLINEimport torchNEWLINEfrom torch.autograd import VariableNEWLINEimport torch.nn.functional as FNEWLINEimport torch.optim as optimNEWLINEimport torch.cudaNEWLINEimport matplotlib.pyplot as pltNEWLINEfrom torch.distributions import NormalNEWLINEimport osNEWLINEimport randomNEWLINEimport torch.nn as nnNEWLINEfrom itertools import countNEWLINEimport timeNEWLINEimport csvNEWLINENEWLINEdef ensure_shared_grads(model, shared_model):NEWLINE for param, shared_param in zip(model.parameters(),shared_model.parameters()):NEWLINE if shared_param.grad is not None:NEWLINE returnNEWLINE shared_param._grad = param.gradNEWLINENEWLINE# process the inputsNEWLINEdef process_inputs(o, g, o_mean, o_std, g_mean, g_std, args):NEWLINE o_clip = np.clip(o, -args.clip_obs, args.clip_obs)NEWLINE g_clip = np.clip(g, -args.clip_obs, args.clip_obs)NEWLINE o_norm = np.clip((o_clip - o_mean) / (o_std), -args.clip_range, args.clip_range)NEWLINE g_norm = np.clip((g_clip - g_mean) / (g_std), -args.clip_range, args.clip_range)NEWLINE inputs = np.concatenate([o_norm, g_norm])NEWLINE inputs = torch.tensor(inputs, dtype=torch.float32)NEWLINE return inputsNEWLINENEWLINENEWLINENEWLINEdef train(rank, args, shared_model, counter, lock, optimizer=None):NEWLINE NEWLINE args2 = get_args()NEWLINE # load the model paramNEWLINE model_path_approach = args2.save_dir + args2.env_name + '/approach.pt'NEWLINE o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, model_approach = torch.load(model_path_approach, map_location=lambda storage, loc: storage)NEWLINE model_path_manipulate = args2.save_dir + args2.env_name + '/manipulate.pt'NEWLINE o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, model_manipulate = torch.load(model_path_manipulate, map_location=lambda storage, loc: storage)NEWLINE model_path_retract = args2.save_dir + args2.env_name + '/retract.pt'NEWLINE o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, model_retract = torch.load(model_path_retract, map_location=lambda storage, loc: storage)NEWLINENEWLINE FloatTensor = torch.cuda.FloatTensor if args.use_cuda else torch.FloatTensorNEWLINE NEWLINE env = gym.make("FetchPickAndPlace-v1")NEWLINE env2 = gym.wrappers.FlattenDictWrapper(env, dict_keys=['observation', 'desired_goal'])NEWLINE observation = env.reset()NEWLINENEWLINE env_params = {'obs': observation['observation'].shape[0], NEWLINE 'goal': observation['desired_goal'].shape[0], NEWLINE 'action': env.action_space.shape[0], NEWLINE 'action_max': env.action_space.high[0],NEWLINE }NEWLINE hlc = Actor()NEWLINE # create the actor networkNEWLINE actor_network_approach = actor(env_params)NEWLINE actor_network_approach.load_state_dict(model_approach)NEWLINE actor_network_approach.eval()NEWLINE actor_network_manipulate = actor(env_params)NEWLINE actor_network_manipulate.load_state_dict(model_manipulate)NEWLINE actor_network_manipulate.eval()NEWLINE actor_network_retract = actor(env_params)NEWLINE actor_network_retract.load_state_dict(model_retract)NEWLINE actor_network_retract.eval()NEWLINENEWLINE if args.use_cuda:NEWLINE hlc.cuda()NEWLINENEWLINENEWLINE NEWLINE for p in hlc.fc1.parameters():NEWLINE p.requires_grad = FalseNEWLINE for p in hlc.fc2.parameters():NEWLINE p.requires_grad = FalseNEWLINE NEWLINE if optimizer is None:NEWLINE optimizer = optim.Adam(shared_model.parameters(), lr=args.lr)NEWLINE NEWLINE hlc.train()NEWLINE NEWLINE done = True NEWLINE for num_iter in count():NEWLINE with lock:NEWLINE counter.value += 1NEWLINE #print(num_iter, counter.value)NEWLINE observation = env.reset()NEWLINE NEWLINE goal = observation['desired_goal']NEWLINE objectPos = observation['observation'][3:6]NEWLINE object_rel_pos = observation['observation'][6:9]NEWLINE object_oriented_goal = object_rel_pos.copy()NEWLINE object_oriented_goal[2] += 0.03 # first make the gripper go slightly above the object NEWLINE timeStep = 0 #count the total number of timestepsNEWLINE grip_pos = -object_rel_pos + objectPosNEWLINE NEWLINE object_pos_goal = objectPos.copy()NEWLINE if grip_pos[0] > objectPos[0]:NEWLINE object_pos_goal[0] += 0.003NEWLINE else:NEWLINE object_pos_goal[0] -= 0.003NEWLINENEWLINE if grip_pos[1] > objectPos[1]:NEWLINE object_pos_goal[1] += 0.002NEWLINE else:NEWLINE object_pos_goal[1] -= 0.002NEWLINENEWLINE object_pos_goal[2] -= -0.031NEWLINENEWLINE if rank == 0:NEWLINENEWLINE if num_iter % args.save_interval == 0 and num_iter > 0:NEWLINE #print ("Saving model at :" + args.save_path) NEWLINE torch.save(shared_model.state_dict(), args.save_path1)NEWLINENEWLINE if num_iter % (args.save_interval * 2.5) == 0 and num_iter > 0 and rank == 1: # Second saver in-case first processes crashes NEWLINE #print ("Saving model for process 1 at :" + args.save_path) NEWLINE torch.save(shared_model.state_dict(), args.save_path1)NEWLINE NEWLINE hlc.load_state_dict(shared_model.state_dict())NEWLINE values, log_probs, rewards, entropies = [], [], [], []NEWLINE if done:NEWLINE cx = Variable(torch.zeros(1, 32)).type(FloatTensor)NEWLINE hx = Variable(torch.zeros(1, 32)).type(FloatTensor)NEWLINE else:NEWLINE cx = Variable(cx.data).type(FloatTensor)NEWLINE hx = Variable(hx.data).type(FloatTensor)NEWLINENEWLINE state_inp = torch.from_numpy(env2.observation(observation)).type(FloatTensor)NEWLINE #criterion = nn.MSELoss()NEWLINE value, y, (hx, cx) = hlc(state_inp, hx, cx)NEWLINE prob = F.softmax(y)NEWLINE log_prob = F.log_softmax(y, dim=-1)NEWLINE act_model = prob.max(-1, keepdim=True)[1].dataNEWLINE entropy = -(log_prob * prob).sum(-1, keepdim=True)NEWLINE log_prob = log_prob.gather(-1, Variable(act_model))NEWLINE action_out = act_model.to(torch.device("cpu"))NEWLINE #action_out = torch.tensor([[0]])NEWLINE entropies.append(entropy), log_probs.append(log_prob), values.append(value)NEWLINE #print(action_out)NEWLINE obs = observation["observation"]NEWLINE observation_new = observationNEWLINENEWLINE while np.linalg.norm(grip_pos - object_pos_goal) >= 0.031 and timeStep <= 20:NEWLINE actions = [0, 0, 0, 0]NEWLINE if action_out == 0:NEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, object_pos_goal, o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, args2)NEWLINE pi = actor_network_approach(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINENEWLINE elif action_out == 1:NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, objectPos, o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, args2)NEWLINE pi = actor_network_manipulate(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE else: NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, goal, o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, args2)NEWLINE pi = actor_network_retract(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINENEWLINE actions[3] = 0.05NEWLINE observation_new, _, _, info = env.step(actions)NEWLINE obs = observation_new["observation"]NEWLINE g = observation_new["desired_goal"]NEWLINENEWLINE objectPos_new = observation_new["observation"][3:6]NEWLINE object_rel_pos_new = observation_new["observation"][6:9]NEWLINE objectPos = objectPos_newNEWLINE grip_pos_new = -object_rel_pos_new.copy() + objectPos_new.copy()NEWLINENEWLINE grip_pos = grip_pos_newNEWLINE object_oriented_goal = object_rel_pos_newNEWLINE NEWLINE timeStep += 1NEWLINE state_inp = torch.from_numpy(env2.observation(observation_new)).type(FloatTensor)NEWLINE if timeStep >= 21: NEWLINE breakNEWLINE NEWLINE NEWLINE reward = torch.Tensor([-1.0]).type(FloatTensor)NEWLINE rewards.append(reward)NEWLINE NEWLINE value, y, (hx, cx) = hlc(state_inp, hx, cx)NEWLINE prob = F.softmax(y)NEWLINE log_prob = F.log_softmax(y, dim=-1)NEWLINE act_model = prob.max(-1, keepdim=True)[1].dataNEWLINE entropy = -(log_prob * prob).sum(-1, keepdim=True)NEWLINE log_prob = log_prob.gather(-1, Variable(act_model))NEWLINE action_out = act_model.to(torch.device("cpu"))NEWLINE entropies.append(entropy), log_probs.append(log_prob), values.append(value)NEWLINE #action_out = torch.tensor([[1]])NEWLINENEWLINE NEWLINE while np.linalg.norm(grip_pos - objectPos) >= 0.015 and timeStep < env._max_episode_steps:NEWLINE actions = [0, 0, 0, 0]NEWLINE if action_out == 0:NEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, object_pos_goal, o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, args2)NEWLINE pi = actor_network_approach(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINENEWLINE elif action_out == 1:NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, objectPos, o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, args2)NEWLINE pi = actor_network_manipulate(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE else: NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, goal, o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, args2)NEWLINE pi = actor_network_retract(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE actions[3] = -0.01NEWLINE NEWLINE observation_new, _, _, info = env.step(actions)NEWLINE obs = observation_new["observation"]NEWLINE objectPos = observation_new["observation"][3:6]NEWLINE object_rel_pos = observation_new["observation"][6:9]NEWLINE NEWLINE grip_pos_new = -object_rel_pos + objectPosNEWLINE grip_pos = grip_pos_newNEWLINENEWLINE timeStep += 1NEWLINE state_inp = torch.from_numpy(env2.observation(observation_new)).type(FloatTensor)NEWLINE if timeStep >= env._max_episode_steps: NEWLINE breakNEWLINE NEWLINE NEWLINE reward = torch.Tensor([-1.0]).type(FloatTensor)NEWLINE rewards.append(reward)NEWLINENEWLINE value, y, (hx, cx) = hlc(state_inp, hx, cx)NEWLINE prob = F.softmax(y)NEWLINE log_prob = F.log_softmax(y, dim=-1)NEWLINE act_model = prob.max(-1, keepdim=True)[1].dataNEWLINE entropy = -(log_prob * prob).sum(-1, keepdim=True)NEWLINE log_prob = log_prob.gather(-1, Variable(act_model))NEWLINE action_out = act_model.to(torch.device("cpu"))NEWLINE entropies.append(entropy), log_probs.append(log_prob), values.append(value)NEWLINE #action_out = torch.tensor([[2]])NEWLINENEWLINE while np.linalg.norm(goal - objectPos) >= 0.01 and timeStep < env._max_episode_steps:NEWLINE actions = [0, 0, 0, 0]NEWLINE if action_out == 0:NEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, object_pos_goal, o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, args2)NEWLINE pi = actor_network_approach(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINENEWLINE elif action_out == 1:NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, objectPos, o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, args2)NEWLINE pi = actor_network_manipulate(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE else: NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, goal, o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, args2)NEWLINE pi = actor_network_retract(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE actions[3] = -0.01NEWLINENEWLINE # put actions into the environmentNEWLINE observation_new, _, _, info = env.step(actions)NEWLINE obs = observation_new['observation']NEWLINE #inputs = process_inputs(obs, g, o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, args)NEWLINE timeStep += 1NEWLINE state_inp = torch.from_numpy(env2.observation(observation_new)).type(FloatTensor)NEWLINE objectPos = observation_new['observation'][3:6]NEWLINE object_rel_pos = observation_new['observation'][6:9]NEWLINE if timeStep >= env._max_episode_steps: NEWLINE breakNEWLINENEWLINE while True: #limit the number of timesteps in the episode to a fixed durationNEWLINE #env.render()NEWLINE action = [0, 0, 0, 0]NEWLINE action[3] = -0.01 # keep the gripper closedNEWLINENEWLINE obsDataNew, reward, done, info = env.step(action)NEWLINE timeStep += 1NEWLINENEWLINE objectPos = obsDataNew['observation'][3:6]NEWLINE object_rel_pos = obsDataNew['observation'][6:9]NEWLINENEWLINE if timeStep >= env._max_episode_steps: breakNEWLINE NEWLINE if info['is_success'] == 1.0:NEWLINE reward = torch.Tensor([10.0]).type(FloatTensor)NEWLINE else:NEWLINE reward = torch.Tensor([-1.0]).type(FloatTensor)NEWLINE rewards.append(reward)NEWLINE NEWLINE R = torch.zeros(1, 1)NEWLINE values.append(Variable(R).type(FloatTensor))NEWLINE policy_loss = 0NEWLINE value_loss = 0NEWLINE R = Variable(R).type(FloatTensor)NEWLINE gae = torch.zeros(1, 1).type(FloatTensor)NEWLINENEWLINE for i in reversed(range(len(rewards))):NEWLINE R = args.gamma * R + rewards[i]NEWLINE advantage = R - values[i]NEWLINE value_loss = value_loss + 0.5 * advantage.pow(2)NEWLINENEWLINE delta_t = rewards[i] + args.gamma * values[i + 1].data - values[i].dataNEWLINE gae = gae * args.gamma * args.tau + delta_tNEWLINENEWLINE policy_loss = policy_loss - log_probs[i] * Variable(gae).type(FloatTensor)NEWLINENEWLINE total_loss = policy_loss + args.value_loss_coef * value_lossNEWLINE optimizer.zero_grad()NEWLINENEWLINE (total_loss).backward(retain_graph=True)NEWLINE torch.nn.utils.clip_grad_norm_(hlc.parameters(), args.max_grad_norm)NEWLINENEWLINE ensure_shared_grads(hlc, shared_model)NEWLINE optimizer.step()NEWLINENEWLINEdef test(rank, args, shared_model, counter):NEWLINE NEWLINE args2 = get_args()NEWLINE # load the model paramNEWLINE model_path_approach = args2.save_dir + args2.env_name + '/approach.pt'NEWLINE o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, model_approach = torch.load(model_path_approach, map_location=lambda storage, loc: storage)NEWLINE model_path_manipulate = args2.save_dir + args2.env_name + '/manipulate.pt'NEWLINE o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, model_manipulate = torch.load(model_path_manipulate, map_location=lambda storage, loc: storage)NEWLINE model_path_retract = args2.save_dir + args2.env_name + '/retract.pt'NEWLINE o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, model_retract = torch.load(model_path_retract, map_location=lambda storage, loc: storage)NEWLINENEWLINE FloatTensor = torch.cuda.FloatTensor if args.use_cuda else torch.FloatTensorNEWLINE NEWLINE env = gym.make("FetchPickAndPlace-v1")NEWLINE env2 = gym.wrappers.FlattenDictWrapper(env, dict_keys=['observation', 'desired_goal'])NEWLINE observation = env.reset()NEWLINENEWLINE env_params = {'obs': observation['observation'].shape[0], NEWLINE 'goal': observation['desired_goal'].shape[0], NEWLINE 'action': env.action_space.shape[0], NEWLINE 'action_max': env.action_space.high[0],NEWLINE }NEWLINE hlc = Actor()NEWLINE # create the actor networkNEWLINE actor_network_approach = actor(env_params)NEWLINE actor_network_approach.load_state_dict(model_approach)NEWLINE actor_network_approach.eval()NEWLINE actor_network_manipulate = actor(env_params)NEWLINE actor_network_manipulate.load_state_dict(model_manipulate)NEWLINE actor_network_manipulate.eval()NEWLINE actor_network_retract = actor(env_params)NEWLINE actor_network_retract.load_state_dict(model_retract)NEWLINE actor_network_retract.eval()NEWLINE if args.use_cuda:NEWLINE hlc.cuda()NEWLINE NEWLINE done = True NEWLINENEWLINE savefile = os.getcwd() + '/train/mario_curves.csv'NEWLINE title = ['No. episodes', 'No. of success']NEWLINE with open(savefile, 'a', newline='') as sfile:NEWLINE writer = csv.writer(sfile)NEWLINE writer.writerow(title) NEWLINENEWLINE hlc.eval()NEWLINE while True:NEWLINE hlc.load_state_dict(shared_model.state_dict())NEWLINE hlc.eval()NEWLINE ep_num = 0NEWLINE success = 0NEWLINE num_ep = counter.valueNEWLINE while ep_num < 50:NEWLINE ep_num +=1NEWLINE observation = env.reset() NEWLINE #lastObs = observationNEWLINE goal = observation['desired_goal']NEWLINE objectPos = observation['observation'][3:6]NEWLINE object_rel_pos = observation['observation'][6:9]NEWLINE object_oriented_goal = object_rel_pos.copy()NEWLINE object_oriented_goal[2] += 0.03 # first make the gripper go slightly above the object NEWLINE timeStep = 0NEWLINE grip_pos = -object_rel_pos + objectPosNEWLINE NEWLINE object_pos_goal = objectPos.copy()NEWLINE if grip_pos[0] > objectPos[0]:NEWLINE object_pos_goal[0] += 0.003NEWLINE else:NEWLINE object_pos_goal[0] -= 0.003NEWLINENEWLINE if grip_pos[1] > objectPos[1]:NEWLINE object_pos_goal[1] += 0.002NEWLINE else:NEWLINE object_pos_goal[1] -= 0.002NEWLINENEWLINE object_pos_goal[2] -= -0.031NEWLINENEWLINE if done:NEWLINE cx = Variable(torch.zeros(1, 32)).type(FloatTensor)NEWLINE hx = Variable(torch.zeros(1, 32)).type(FloatTensor)NEWLINE else:NEWLINE cx = Variable(cx.data).type(FloatTensor)NEWLINE hx = Variable(hx.data).type(FloatTensor)NEWLINENEWLINE state_inp = torch.from_numpy(env2.observation(observation)).type(FloatTensor)NEWLINE value, y, (hx, cx) = hlc(state_inp, hx, cx)NEWLINE prob = F.softmax(y)NEWLINE act_model = prob.max(-1, keepdim=True)[1].dataNEWLINE action_out = act_model.to(torch.device("cpu"))NEWLINENEWLINENEWLINE #print('action_out before approach:', action_out)NEWLINE obs = observation["observation"]NEWLINE while np.linalg.norm(grip_pos - object_pos_goal) >= 0.031 and timeStep <= 20:NEWLINE #env.render()NEWLINE actions = [0, 0, 0, 0]NEWLINE if action_out == 0:NEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, object_pos_goal, o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, args2)NEWLINE pi = actor_network_approach(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINENEWLINE elif action_out == 1:NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, objectPos, o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, args2)NEWLINE pi = actor_network_manipulate(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE else: NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, goal, o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, args2)NEWLINE pi = actor_network_retract(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINENEWLINE actions[3] = 0.05NEWLINENEWLINE observation_new, _, _, info = env.step(actions)NEWLINE obs = observation_new["observation"]NEWLINE g = observation_new["desired_goal"]NEWLINENEWLINE objectPos_new = observation_new["observation"][3:6]NEWLINE object_rel_pos_new = observation_new["observation"][6:9]NEWLINE objectPos = objectPos_newNEWLINE grip_pos_new = -object_rel_pos_new + objectPos_newNEWLINENEWLINE grip_pos = grip_pos_newNEWLINE object_oriented_goal = object_rel_pos_newNEWLINE NEWLINE #print('timestep: {},reward eval: {}'.format(timeStep, reward))NEWLINE timeStep += 1NEWLINE state_inp = torch.from_numpy(env2.observation(observation_new)).type(FloatTensor)NEWLINE NEWLINE NEWLINENEWLINE value, y, (hx, cx) = hlc(state_inp, hx, cx)NEWLINE prob = F.softmax(y)NEWLINE act_model = prob.max(-1, keepdim=True)[1].dataNEWLINE action_out = act_model.to(torch.device("cpu"))NEWLINE NEWLINE while np.linalg.norm(grip_pos - objectPos) >= 0.015 and timeStep < env._max_episode_steps:NEWLINE #env.render()NEWLINE actions = [0, 0, 0, 0]NEWLINE if action_out == 0:NEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, object_pos_goal, o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, args2)NEWLINE pi = actor_network_approach(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINENEWLINE elif action_out == 1:NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, objectPos, o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, args2)NEWLINE pi = actor_network_manipulate(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE else: NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, goal, o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, args2)NEWLINE pi = actor_network_retract(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE NEWLINE actions[3] = -0.01NEWLINE NEWLINE observation_new, _, _, info = env.step(actions)NEWLINE obs = observation_new["observation"]NEWLINE objectPos = observation_new["observation"][3:6]NEWLINE object_rel_pos = observation_new["observation"][6:9]NEWLINE NEWLINE grip_pos_new = -object_rel_pos + objectPosNEWLINE grip_pos = grip_pos_newNEWLINENEWLINE timeStep += 1NEWLINE state_inp = torch.from_numpy(env2.observation(observation_new)).type(FloatTensor)NEWLINE if timeStep >= env._max_episode_steps: NEWLINE breakNEWLINE NEWLINE value, y, (hx, cx) = hlc(state_inp, hx, cx)NEWLINE prob = F.softmax(y) NEWLINE act_model = prob.max(-1, keepdim=True)[1].data NEWLINE action_out = act_model.to(torch.device("cpu"))NEWLINE NEWLINE NEWLINE while np.linalg.norm(goal - objectPos) >= 0.01 and timeStep < env._max_episode_steps:NEWLINE #env.render()NEWLINE actions = [0, 0, 0, 0]NEWLINE if action_out == 0:NEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, object_pos_goal, o_mean_approach, o_std_approach, g_mean_approach, g_std_approach, args2)NEWLINE pi = actor_network_approach(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINENEWLINE elif action_out == 1:NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, objectPos, o_mean_manipulate, o_std_manipulate, g_mean_manipulate, g_std_manipulate, args2)NEWLINE pi = actor_network_manipulate(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE else: NEWLINENEWLINE with torch.no_grad():NEWLINE #input_tensor = _preproc_inputs(obs, objectPos)NEWLINE input_tensor = process_inputs(obs, goal, o_mean_retract, o_std_retract, g_mean_retract, g_std_retract, args2)NEWLINE pi = actor_network_retract(input_tensor)NEWLINE # convert the actionsNEWLINE actions = pi.detach().cpu().numpy().squeeze()NEWLINE NEWLINE actions[3] = -0.01NEWLINENEWLINE # put actions into the environmentNEWLINE observation_new, _, _, info = env.step(actions)NEWLINE obs = observation_new['observation']NEWLINE NEWLINE timeStep += 1NEWLINE state_inp = torch.from_numpy(env2.observation(observation_new)).type(FloatTensor)NEWLINE objectPos = observation_new['observation'][3:6]NEWLINE object_rel_pos = observation_new['observation'][6:9]NEWLINE if timeStep >= env._max_episode_steps: NEWLINE breakNEWLINE NEWLINE while True: #limit the number of timesteps in the episode to a fixed durationNEWLINE #env.render()NEWLINE action = [0, 0, 0, 0]NEWLINE action[3] = -0.01 # keep the gripper closedNEWLINENEWLINE obsDataNew, reward, done, info = env.step(action)NEWLINE timeStep += 1NEWLINENEWLINE objectPos = obsDataNew['observation'][3:6]NEWLINE object_rel_pos = obsDataNew['observation'][6:9]NEWLINE if timeStep >= env._max_episode_steps: breakNEWLINE NEWLINE if info['is_success'] == 1.0:NEWLINE success +=1NEWLINE NEWLINE if ep_num % 49==0: NEWLINE print("num episodes {}, success {}".format(num_ep, success*2))NEWLINE data = [counter.value, success*2]NEWLINE with open(savefile, 'a', newline='') as sfile:NEWLINE writer = csv.writer(sfile)NEWLINE writer.writerows([data])NEWLINE #time.sleep(15)NEWLINE # -*- coding: utf-8 -*-NEWLINE# Copyright 2020 Google Inc.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINE# Make sure that your AWS credentials are configured correclty, seeNEWLINE# https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html #pylint: disable=line-too-longNEWLINE"""Demo CLI tool for AWS."""NEWLINENEWLINEfrom datetime import datetimeNEWLINEfrom typing import TYPE_CHECKINGNEWLINENEWLINEfrom libcloudforensics.providers.aws.internal import accountNEWLINEfrom libcloudforensics.providers.aws.internal import log as aws_logNEWLINEfrom libcloudforensics.providers.aws import forensicsNEWLINENEWLINEif TYPE_CHECKING:NEWLINE import argparseNEWLINENEWLINENEWLINEdef ListInstances(args: 'argparse.Namespace') -> None:NEWLINE """List EC2 instances in AWS account.NEWLINENEWLINE Args:NEWLINE args (argparse.Namespace): Arguments from ArgumentParser.NEWLINE """NEWLINENEWLINE aws_account = account.AWSAccount(args.zone)NEWLINE instances = aws_account.ListInstances()NEWLINENEWLINE print('Instances found:')NEWLINE for instance in instances:NEWLINE boot_volume = instances[instance].GetBootVolume().volume_idNEWLINE print('Name: {0:s}, Boot volume: {1:s}'.format(instance, boot_volume))NEWLINENEWLINENEWLINEdef ListVolumes(args: 'argparse.Namespace') -> None:NEWLINE """List EBS volumes in AWS account.NEWLINENEWLINE Args:NEWLINE args (argparse.Namespace): Arguments from ArgumentParser.NEWLINE """NEWLINENEWLINE aws_account = account.AWSAccount(args.zone)NEWLINE volumes = aws_account.ListVolumes()NEWLINENEWLINE print('Volumes found:')NEWLINE for volume in volumes:NEWLINE print('Name: {0:s}, Zone: {1:s}'.format(NEWLINE volume, volumes[volume].availability_zone))NEWLINENEWLINENEWLINEdef CreateVolumeCopy(args: 'argparse.Namespace') -> None:NEWLINE """Create a AWS Volume copy.NEWLINENEWLINE Args:NEWLINE args (argparse.Namespace): Arguments from ArgumentParser.NEWLINE """NEWLINE print('Starting volume copy...')NEWLINE volume_copy = forensics.CreateVolumeCopy(args.zone,NEWLINE dst_zone=args.dst_zone,NEWLINE instance_id=args.instance_id,NEWLINE volume_id=args.volume_id,NEWLINE src_profile=args.src_profile,NEWLINE dst_profile=args.dst_profile)NEWLINE print(NEWLINE 'Done! Volume {0:s} successfully created. You will find it in 'NEWLINE 'your AWS account under the name {1:s}.'.format(NEWLINE volume_copy.volume_id, volume_copy.name))NEWLINENEWLINENEWLINEdef QueryLogs(args: 'argparse.Namespace') -> None:NEWLINE """Query AWS CloudTrail log events.NEWLINENEWLINE Args:NEWLINE args (argparse.Namespace): Arguments from ArgumentParser.NEWLINE """NEWLINE ct = aws_log.AWSCloudTrail(account.AWSAccount(args.zone))NEWLINENEWLINE params = {}NEWLINE if args.filter:NEWLINE params['qfilter'] = args.filterNEWLINE if args.start:NEWLINE params['starttime'] = datetime.strptime(args.start, '%Y-%m-%d %H:%M:%S')NEWLINE if args.end:NEWLINE params['endtime'] = datetime.strptime(args.end, '%Y-%m-%d %H:%M:%S')NEWLINENEWLINE result = ct.LookupEvents(**params)NEWLINENEWLINE if result:NEWLINE print('Log events found: {0:d}'.format(len(result)))NEWLINE for event in result:NEWLINE print(event)NEWLINE #!/usr/bin/env pythonNEWLINE__author__ = 'mike knowles'NEWLINENEWLINEif __name__ == '__main__':NEWLINE pass # -*- coding: utf-8 -*-NEWLINENEWLINEimport ioNEWLINEimport reNEWLINENEWLINEimport demjsonNEWLINEimport requestsNEWLINEimport pandas as pdNEWLINENEWLINEfrom zvt.api.common import china_stock_code_to_idNEWLINEfrom zvt.api.technical import init_securities, df_to_dbNEWLINEfrom zvt.domain import Provider, StockIndex, StockCategoryNEWLINEfrom zvt.recorders.consts import DEFAULT_SH_ETF_LIST_HEADERNEWLINEfrom zvt.recorders.recorder import RecorderNEWLINENEWLINENEWLINEclass ChinaETFListSpider(Recorder):NEWLINE data_schema = StockIndexNEWLINENEWLINE def __init__(self, batch_size=10, force_update=False, sleeping_time=10.0, provider=Provider.EXCHANGE) -> None:NEWLINE self.provider = providerNEWLINE super().__init__(batch_size, force_update, sleeping_time)NEWLINENEWLINE def run(self):NEWLINE # 抓取沪市 ETF 列表NEWLINE url = 'http://query.sse.com.cn/commonQuery.do?sqlId=COMMON_SSE_ZQPZ_ETFLB_L_NEW'NEWLINE response = requests.get(url, headers=DEFAULT_SH_ETF_LIST_HEADER)NEWLINE response_dict = demjson.decode(response.text)NEWLINENEWLINE df = pd.DataFrame(response_dict.get('result', []))NEWLINE self.persist_etf_list(df, exchange='sh')NEWLINE self.logger.info('沪市 ETF 列表抓取完成...')NEWLINENEWLINE # 抓取沪市 ETF 成分股NEWLINE self.download_sh_etf_component(df)NEWLINE self.logger.info('沪市 ETF 成分股抓取完成...')NEWLINENEWLINE # 抓取深市 ETF 列表NEWLINE url = 'http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1945'NEWLINE response = requests.get(url)NEWLINENEWLINE df = pd.read_excel(io.BytesIO(response.content), dtype=str)NEWLINE self.persist_etf_list(df, exchange='sz')NEWLINE self.logger.info('深市 ETF 列表抓取完成...')NEWLINENEWLINE # 抓取深市 ETF 成分股NEWLINE self.download_sz_etf_component(df)NEWLINE self.logger.info('深市 ETF 成分股抓取完成...')NEWLINENEWLINE def persist_etf_list(self, df: pd.DataFrame, exchange: str):NEWLINE if df is None:NEWLINE returnNEWLINENEWLINE df = df.copy()NEWLINE if exchange == 'sh':NEWLINE df = df[['FUND_ID', 'FUND_NAME']]NEWLINE elif exchange == 'sz':NEWLINE df = df[['证券代码', '证券简称']]NEWLINENEWLINE df.columns = ['code', 'name']NEWLINE df['id'] = df['code'].apply(lambda code: f'index_{exchange}_{code}')NEWLINE df['exchange'] = exchangeNEWLINE df['type'] = 'index'NEWLINE df['category'] = StockCategory.etf.valueNEWLINENEWLINE df = df.dropna(axis=0, how='any')NEWLINE df = df.drop_duplicates(subset='id', keep='last')NEWLINENEWLINE init_securities(df, security_type='index', provider=self.provider)NEWLINENEWLINE def download_sh_etf_component(self, df: pd.DataFrame):NEWLINE """NEWLINE ETF_CLASS => 1. 单市场 ETF 2.跨市场 ETF 3. 跨境 ETFNEWLINE 5. 债券 ETF 6. 黄金 ETFNEWLINE :param df: ETF 列表数据NEWLINE :return: NoneNEWLINE """NEWLINE query_url = 'http://query.sse.com.cn/infodisplay/queryConstituentStockInfo.do?' \NEWLINE 'isPagination=false&type={}&etfClass={}'NEWLINENEWLINE etf_df = df[(df['ETF_CLASS'] == '1') | (df['ETF_CLASS'] == '2')]NEWLINE etf_df = self.populate_sh_etf_type(etf_df)NEWLINENEWLINE for _, etf in etf_df.iterrows():NEWLINE url = query_url.format(etf['ETF_TYPE'], etf['ETF_CLASS'])NEWLINE response = requests.get(url, headers=DEFAULT_SH_ETF_LIST_HEADER)NEWLINE response_dict = demjson.decode(response.text)NEWLINE response_df = pd.DataFrame(response_dict.get('result', []))NEWLINENEWLINE etf_code = etf['FUND_ID']NEWLINE index_id = f'index_sh_{etf_code}'NEWLINE response_df = response_df[['instrumentId']]NEWLINE response_df['id'] = response_df['instrumentId'].apply(lambda code: f'{index_id}_{china_stock_code_to_id(code)}')NEWLINE response_df['stock_id'] = response_df['instrumentId'].apply(lambda code: china_stock_code_to_id(code))NEWLINE response_df['index_id'] = index_idNEWLINE response_df.drop('instrumentId', axis=1, inplace=True)NEWLINENEWLINE df_to_db(data_schema=self.data_schema, df=response_df, provider=self.provider)NEWLINE self.logger.info(f'{etf["FUND_NAME"]} - {etf_code} 成分股抓取完成...')NEWLINENEWLINE self.sleep()NEWLINENEWLINE def download_sz_etf_component(self, df: pd.DataFrame):NEWLINE query_url = 'http://vip.stock.finance.sina.com.cn/corp/go.php/vII_NewestComponent/indexid/{}.phtml'NEWLINENEWLINE self.parse_sz_etf_underlying_index(df)NEWLINE for _, etf in df.iterrows():NEWLINE underlying_index = etf['拟合指数']NEWLINE etf_code = etf['证券代码']NEWLINENEWLINE if len(underlying_index) == 0:NEWLINE self.logger.info(f'{etf["证券简称"]} - {etf_code} 非 A 股市场指数,跳过...')NEWLINE continueNEWLINENEWLINE url = query_url.format(underlying_index)NEWLINE response = requests.get(url)NEWLINE response.encoding = 'gbk'NEWLINENEWLINE try:NEWLINE dfs = pd.read_html(response.text, header=1)NEWLINE except ValueError as error:NEWLINE self.logger.error(f'HTML parse error: {error}, response: {response.text}')NEWLINE continueNEWLINENEWLINE if len(dfs) < 4:NEWLINE continueNEWLINENEWLINE response_df = dfs[3].copy()NEWLINE response_df = response_df.dropna(axis=1, how='any')NEWLINE response_df['品种代码'] = response_df['品种代码'].apply(lambda x: f'{x:06d}')NEWLINENEWLINE index_id = f'index_sz_{etf_code}'NEWLINE response_df = response_df[['品种代码']]NEWLINENEWLINE response_df['id'] = response_df['品种代码'].apply(lambda code: f'{index_id}_{china_stock_code_to_id(code)}')NEWLINE response_df['stock_id'] = response_df['品种代码'].apply(lambda code: china_stock_code_to_id(code))NEWLINE response_df['index_id'] = index_idNEWLINE response_df.drop('品种代码', axis=1, inplace=True)NEWLINENEWLINE df_to_db(data_schema=self.data_schema, df=response_df, provider=self.provider)NEWLINE self.logger.info(f'{etf["证券简称"]} - {etf_code} 成分股抓取完成...')NEWLINENEWLINE self.sleep()NEWLINENEWLINE @staticmethodNEWLINE def populate_sh_etf_type(df: pd.DataFrame):NEWLINE """NEWLINE 填充沪市 ETF 代码对应的 TYPE 到列表数据中NEWLINE :param df: ETF 列表数据NEWLINE :return: 包含 ETF 对应 TYPE 的列表数据NEWLINE """NEWLINE query_url = 'http://query.sse.com.cn/infodisplay/queryETFNewAllInfo.do?' \NEWLINE 'isPagination=false&type={}&pageHelp.pageSize=25'NEWLINENEWLINE type_df = pd.DataFrame()NEWLINE for etf_class in [1, 2]:NEWLINE url = query_url.format(etf_class)NEWLINE response = requests.get(url, headers=DEFAULT_SH_ETF_LIST_HEADER)NEWLINE response_dict = demjson.decode(response.text)NEWLINE response_df = pd.DataFrame(response_dict.get('result', []))NEWLINE response_df = response_df[['fundid1', 'etftype']]NEWLINENEWLINE type_df = pd.concat([type_df, response_df])NEWLINENEWLINE result_df = df.copy()NEWLINE result_df = result_df.sort_values(by='FUND_ID').reset_index(drop=True)NEWLINE type_df = type_df.sort_values(by='fundid1').reset_index(drop=True)NEWLINENEWLINE result_df['ETF_TYPE'] = type_df['etftype']NEWLINENEWLINE return result_dfNEWLINENEWLINE @staticmethodNEWLINE def parse_sz_etf_underlying_index(df: pd.DataFrame):NEWLINE """NEWLINE 解析深市 ETF 对应跟踪的指数代码NEWLINE :param df: ETF 列表数据NEWLINE :return: 解析完成 ETF 对应指数代码的列表数据NEWLINE """NEWLINE def parse_index(text):NEWLINE if len(text) == 0:NEWLINE return ''NEWLINENEWLINE result = re.search(r"(\d+).*", text)NEWLINE if result is None:NEWLINE return ''NEWLINE else:NEWLINE return result.group(1)NEWLINENEWLINE df['拟合指数'] = df['拟合指数'].apply(parse_index)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE spider = ChinaETFListSpider(provider=Provider.EXCHANGE)NEWLINE spider.run()NEWLINE from __future__ import divisionNEWLINENEWLINEimport numpy as npNEWLINEfrom skimage.util.dtype import dtype_rangeNEWLINEfrom skimage import drawNEWLINEfrom skimage import measureNEWLINENEWLINEfrom .plotplugin import PlotPluginNEWLINEfrom ..canvastools import ThickLineToolNEWLINENEWLINENEWLINE__all__ = ['LineProfile']NEWLINENEWLINENEWLINEclass LineProfile(PlotPlugin):NEWLINE """Plugin to compute interpolated intensity under a scan line on an image.NEWLINENEWLINE See PlotPlugin and Plugin classes for additional details.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE maxdist : floatNEWLINE Maximum pixel distance allowed when selecting end point of scan line.NEWLINE limits : tuple or {None, 'image', 'dtype'}NEWLINE (minimum, maximum) intensity limits for plotted profile. The followingNEWLINE special values are defined:NEWLINENEWLINE None : rescale based on min/max intensity along selected scan line.NEWLINE 'image' : fixed scale based on min/max intensity in image.NEWLINE 'dtype' : fixed scale based on min/max intensity of image dtype.NEWLINE """NEWLINE name = 'Line Profile'NEWLINENEWLINE def __init__(self, maxdist=10, epsilon='deprecated',NEWLINE limits='image', **kwargs):NEWLINE super(LineProfile, self).__init__(**kwargs)NEWLINE self.maxdist = maxdistNEWLINE self._limit_type = limitsNEWLINE print(self.help())NEWLINENEWLINE def attach(self, image_viewer):NEWLINE super(LineProfile, self).attach(image_viewer)NEWLINENEWLINE image = image_viewer.original_imageNEWLINENEWLINE if self._limit_type == 'image':NEWLINE self.limits = (np.min(image), np.max(image))NEWLINE elif self._limit_type == 'dtype':NEWLINE self._limit_type = dtype_range[image.dtype.type]NEWLINE elif self._limit_type is None or len(self._limit_type) == 2:NEWLINE self.limits = self._limit_typeNEWLINE else:NEWLINE raise ValueError("Unrecognized `limits`: %s" % self._limit_type)NEWLINENEWLINE if not self._limit_type is None:NEWLINE self.ax.set_ylim(self.limits)NEWLINENEWLINE h, w = image.shape[0:2]NEWLINE x = [w / 3, 2 * w / 3]NEWLINE y = [h / 2] * 2NEWLINENEWLINE self.line_tool = ThickLineTool(self.image_viewer.ax,NEWLINE maxdist=self.maxdist,NEWLINE on_move=self.line_changed,NEWLINE on_change=self.line_changed)NEWLINE self.line_tool.end_points = np.transpose([x, y])NEWLINENEWLINE scan_data = measure.profile_line(image, NEWLINE *self.line_tool.end_points[:, ::-1])NEWLINE self.scan_data = scan_dataNEWLINE if scan_data.ndim == 1:NEWLINE scan_data = scan_data[:, np.newaxis]NEWLINENEWLINE self.reset_axes(scan_data)NEWLINENEWLINE self._autoscale_view()NEWLINENEWLINE def help(self):NEWLINE helpstr = ("Line profile tool",NEWLINE "+ and - keys or mouse scroll changes width of scan line.",NEWLINE "Select and drag ends of the scan line to adjust it.")NEWLINE return '\n'.join(helpstr)NEWLINENEWLINE def get_profiles(self):NEWLINE """Return intensity profile of the selected line.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE end_points: (2, 2) arrayNEWLINE The positions ((x1, y1), (x2, y2)) of the line ends.NEWLINE profile: list of 1d arraysNEWLINE Profile of intensity values. Length 1 (grayscale) or 3 (rgb).NEWLINE """NEWLINE profiles = [data.get_ydata() for data in self.profile]NEWLINE return self.line_tool.end_points, profilesNEWLINENEWLINE def _autoscale_view(self):NEWLINE if self.limits is None:NEWLINE self.ax.autoscale_view(tight=True)NEWLINE else:NEWLINE self.ax.autoscale_view(scaley=False, tight=True)NEWLINENEWLINE def line_changed(self, end_points):NEWLINE x, y = np.transpose(end_points)NEWLINE self.line_tool.end_points = end_pointsNEWLINE scan = measure.profile_line(self.image_viewer.original_image,NEWLINE *end_points[:, ::-1],NEWLINE linewidth=self.line_tool.linewidth)NEWLINE self.scan_data = scanNEWLINE if scan.ndim == 1:NEWLINE scan = scan[:, np.newaxis]NEWLINENEWLINE if scan.shape[1] != len(self.profile):NEWLINE self.reset_axes(scan)NEWLINENEWLINE for i in range(len(scan[0])):NEWLINE self.profile[i].set_xdata(np.arange(scan.shape[0]))NEWLINE self.profile[i].set_ydata(scan[:, i])NEWLINENEWLINE self.ax.relim()NEWLINENEWLINE self._autoscale_view()NEWLINE self.redraw()NEWLINENEWLINE def reset_axes(self, scan_data):NEWLINE # Clear lines outNEWLINE for line in self.ax.lines:NEWLINE self.ax.lines = []NEWLINENEWLINE if scan_data.shape[1] == 1:NEWLINE self.profile = self.ax.plot(scan_data, 'k-')NEWLINE else:NEWLINE self.profile = self.ax.plot(scan_data[:, 0], 'r-',NEWLINE scan_data[:, 1], 'g-',NEWLINE scan_data[:, 2], 'b-')NEWLINENEWLINE def output(self):NEWLINE """Return the drawn line and the resulting scan.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE line_image : (M, N) uint8 array, same shape as imageNEWLINE An array of 0s with the scanned line set to 255.NEWLINE If the linewidth of the line tool is greater than 1,NEWLINE sets the values within the profiled polygon to 128.NEWLINE scan : (P,) or (P, 3) array of int or floatNEWLINE The line scan values across the image.NEWLINE """NEWLINE end_points = self.line_tool.end_pointsNEWLINE line_image = np.zeros(self.image_viewer.original_image.shape[:2],NEWLINE np.uint8)NEWLINE width = self.line_tool.linewidthNEWLINE if width > 1:NEWLINE rp, cp = measure.profile._line_profile_coordinates(NEWLINE *end_points[:, ::-1], linewidth=width)NEWLINE # the points are aliased, so create a polygon using the cornersNEWLINE yp = np.rint(rp[[0, 0, -1, -1],[0, -1, -1, 0]]).astype(int)NEWLINE xp = np.rint(cp[[0, 0, -1, -1],[0, -1, -1, 0]]).astype(int)NEWLINE rp, cp = draw.polygon(yp, xp, line_image.shape)NEWLINE line_image[rp, cp] = 128NEWLINE (x1, y1), (x2, y2) = end_points.astype(int)NEWLINE rr, cc = draw.line(y1, x1, y2, x2)NEWLINE line_image[rr, cc] = 255NEWLINE return line_image, self.scan_dataNEWLINENEWLINE # -*- coding: utf-8 -*-NEWLINE#NEWLINE# Copyright 2020 Google LLCNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# https://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINE"""Accesses the google.cloud.irm.v1alpha2 IncidentService API."""NEWLINENEWLINEimport functoolsNEWLINEimport pkg_resourcesNEWLINEimport warningsNEWLINENEWLINEfrom google.oauth2 import service_accountNEWLINEimport google.api_core.client_optionsNEWLINEimport google.api_core.gapic_v1.client_infoNEWLINEimport google.api_core.gapic_v1.configNEWLINEimport google.api_core.gapic_v1.methodNEWLINEimport google.api_core.gapic_v1.routing_headerNEWLINEimport google.api_core.grpc_helpersNEWLINEimport google.api_core.page_iteratorNEWLINEimport google.api_core.path_templateNEWLINEimport google.api_core.protobuf_helpersNEWLINEimport grpcNEWLINENEWLINEfrom google.cloud.irm_v1alpha2.gapic import enumsNEWLINEfrom google.cloud.irm_v1alpha2.gapic import incident_service_client_configNEWLINEfrom google.cloud.irm_v1alpha2.gapic.transports import incident_service_grpc_transportNEWLINEfrom google.cloud.irm_v1alpha2.proto import incidents_pb2NEWLINEfrom google.cloud.irm_v1alpha2.proto import incidents_service_pb2NEWLINEfrom google.cloud.irm_v1alpha2.proto import incidents_service_pb2_grpcNEWLINEfrom google.protobuf import empty_pb2NEWLINEfrom google.protobuf import field_mask_pb2NEWLINENEWLINENEWLINE_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-irm",).versionNEWLINENEWLINENEWLINEclass IncidentServiceClient(object):NEWLINE """The Incident API for Incident Response & Management."""NEWLINENEWLINE SERVICE_ADDRESS = "irm.googleapis.com:443"NEWLINE """The default address of the service."""NEWLINENEWLINE # The name of the interface for this client. This is the key used toNEWLINE # find the method configuration in the client_config dictionary.NEWLINE _INTERFACE_NAME = "google.cloud.irm.v1alpha2.IncidentService"NEWLINENEWLINE @classmethodNEWLINE def from_service_account_file(cls, filename, *args, **kwargs):NEWLINE """Creates an instance of this client using the provided credentialsNEWLINE file.NEWLINENEWLINE Args:NEWLINE filename (str): The path to the service account private key jsonNEWLINE file.NEWLINE args: Additional arguments to pass to the constructor.NEWLINE kwargs: Additional arguments to pass to the constructor.NEWLINENEWLINE Returns:NEWLINE IncidentServiceClient: The constructed client.NEWLINE """NEWLINE credentials = service_account.Credentials.from_service_account_file(filename)NEWLINE kwargs["credentials"] = credentialsNEWLINE return cls(*args, **kwargs)NEWLINENEWLINE from_service_account_json = from_service_account_fileNEWLINENEWLINE @classmethodNEWLINE def annotation_path(cls, project, incident, annotation):NEWLINE """Return a fully-qualified annotation string."""NEWLINE return google.api_core.path_template.expand(NEWLINE "projects/{project}/incidents/{incident}/annotations/{annotation}",NEWLINE project=project,NEWLINE incident=incident,NEWLINE annotation=annotation,NEWLINE )NEWLINENEWLINE @classmethodNEWLINE def artifact_path(cls, project, incident, artifact):NEWLINE """Return a fully-qualified artifact string."""NEWLINE return google.api_core.path_template.expand(NEWLINE "projects/{project}/incidents/{incident}/artifacts/{artifact}",NEWLINE project=project,NEWLINE incident=incident,NEWLINE artifact=artifact,NEWLINE )NEWLINENEWLINE @classmethodNEWLINE def incident_path(cls, project, incident):NEWLINE """Return a fully-qualified incident string."""NEWLINE return google.api_core.path_template.expand(NEWLINE "projects/{project}/incidents/{incident}",NEWLINE project=project,NEWLINE incident=incident,NEWLINE )NEWLINENEWLINE @classmethodNEWLINE def incident_role_assignment_path(cls, project_id_or_number, incident_id, role_id):NEWLINE """Return a fully-qualified incident_role_assignment string."""NEWLINE return google.api_core.path_template.expand(NEWLINE "projects/{project_id_or_number}/incidents/{incident_id}/role_assignments/{role_id}",NEWLINE project_id_or_number=project_id_or_number,NEWLINE incident_id=incident_id,NEWLINE role_id=role_id,NEWLINE )NEWLINENEWLINE @classmethodNEWLINE def project_path(cls, project):NEWLINE """Return a fully-qualified project string."""NEWLINE return google.api_core.path_template.expand(NEWLINE "projects/{project}", project=project,NEWLINE )NEWLINENEWLINE @classmethodNEWLINE def signal_path(cls, project, signal):NEWLINE """Return a fully-qualified signal string."""NEWLINE return google.api_core.path_template.expand(NEWLINE "projects/{project}/signals/{signal}", project=project, signal=signal,NEWLINE )NEWLINENEWLINE @classmethodNEWLINE def subscription_path(cls, project, incident, subscription):NEWLINE """Return a fully-qualified subscription string."""NEWLINE return google.api_core.path_template.expand(NEWLINE "projects/{project}/incidents/{incident}/subscriptions/{subscription}",NEWLINE project=project,NEWLINE incident=incident,NEWLINE subscription=subscription,NEWLINE )NEWLINENEWLINE @classmethodNEWLINE def tag_path(cls, project, incident, tag):NEWLINE """Return a fully-qualified tag string."""NEWLINE return google.api_core.path_template.expand(NEWLINE "projects/{project}/incidents/{incident}/tags/{tag}",NEWLINE project=project,NEWLINE incident=incident,NEWLINE tag=tag,NEWLINE )NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE transport=None,NEWLINE channel=None,NEWLINE credentials=None,NEWLINE client_config=None,NEWLINE client_info=None,NEWLINE client_options=None,NEWLINE ):NEWLINE """Constructor.NEWLINENEWLINE Args:NEWLINE transport (Union[~.IncidentServiceGrpcTransport,NEWLINE Callable[[~.Credentials, type], ~.IncidentServiceGrpcTransport]): A transportNEWLINE instance, responsible for actually making the API calls.NEWLINE The default transport uses the gRPC protocol.NEWLINE This argument may also be a callable which returns aNEWLINE transport instance. Callables will be sent the credentialsNEWLINE as the first argument and the default transport class asNEWLINE the second argument.NEWLINE channel (grpc.Channel): DEPRECATED. A ``Channel`` instanceNEWLINE through which to make calls. This argument is mutually exclusiveNEWLINE with ``credentials``; providing both will raise an exception.NEWLINE credentials (google.auth.credentials.Credentials): TheNEWLINE authorization credentials to attach to requests. TheseNEWLINE credentials identify this application to the service. If noneNEWLINE are specified, the client will attempt to ascertain theNEWLINE credentials from the environment.NEWLINE This argument is mutually exclusive with providing aNEWLINE transport instance to ``transport``; doing so will raiseNEWLINE an exception.NEWLINE client_config (dict): DEPRECATED. A dictionary of call options forNEWLINE each method. If not specified, the default configuration is used.NEWLINE client_info (google.api_core.gapic_v1.client_info.ClientInfo):NEWLINE The client info used to send a user-agent string along withNEWLINE API requests. If ``None``, then default info will be used.NEWLINE Generally, you only need to set this if you're developingNEWLINE your own client library.NEWLINE client_options (Union[dict, google.api_core.client_options.ClientOptions]):NEWLINE Client options used to set user options on the client. API EndpointNEWLINE should be set through client_options.NEWLINE """NEWLINE # Raise deprecation warnings for things we want to go away.NEWLINE if client_config is not None:NEWLINE warnings.warn(NEWLINE "The `client_config` argument is deprecated.",NEWLINE PendingDeprecationWarning,NEWLINE stacklevel=2,NEWLINE )NEWLINE else:NEWLINE client_config = incident_service_client_config.configNEWLINENEWLINE if channel:NEWLINE warnings.warn(NEWLINE "The `channel` argument is deprecated; use " "`transport` instead.",NEWLINE PendingDeprecationWarning,NEWLINE stacklevel=2,NEWLINE )NEWLINENEWLINE api_endpoint = self.SERVICE_ADDRESSNEWLINE if client_options:NEWLINE if type(client_options) == dict:NEWLINE client_options = google.api_core.client_options.from_dict(NEWLINE client_optionsNEWLINE )NEWLINE if client_options.api_endpoint:NEWLINE api_endpoint = client_options.api_endpointNEWLINENEWLINE # Instantiate the transport.NEWLINE # The transport is responsible for handling serialization andNEWLINE # deserialization and actually sending data to the service.NEWLINE if transport:NEWLINE if callable(transport):NEWLINE self.transport = transport(NEWLINE credentials=credentials,NEWLINE default_class=incident_service_grpc_transport.IncidentServiceGrpcTransport,NEWLINE address=api_endpoint,NEWLINE )NEWLINE else:NEWLINE if credentials:NEWLINE raise ValueError(NEWLINE "Received both a transport instance and "NEWLINE "credentials; these are mutually exclusive."NEWLINE )NEWLINE self.transport = transportNEWLINE else:NEWLINE self.transport = incident_service_grpc_transport.IncidentServiceGrpcTransport(NEWLINE address=api_endpoint, channel=channel, credentials=credentials,NEWLINE )NEWLINENEWLINE if client_info is None:NEWLINE client_info = google.api_core.gapic_v1.client_info.ClientInfo(NEWLINE gapic_version=_GAPIC_LIBRARY_VERSION,NEWLINE )NEWLINE else:NEWLINE client_info.gapic_version = _GAPIC_LIBRARY_VERSIONNEWLINE self._client_info = client_infoNEWLINENEWLINE # Parse out the default settings for retry and timeout for each RPCNEWLINE # from the client configuration.NEWLINE # (Ordinarily, these are the defaults specified in the `*_config.py`NEWLINE # file next to this one.)NEWLINE self._method_configs = google.api_core.gapic_v1.config.parse_method_configs(NEWLINE client_config["interfaces"][self._INTERFACE_NAME],NEWLINE )NEWLINENEWLINE # Save a dictionary of cached API call functions.NEWLINE # These are the actual callables which invoke the properNEWLINE # transport methods, wrapped with `wrap_method` to add retry,NEWLINE # timeout, and the like.NEWLINE self._inner_api_calls = {}NEWLINENEWLINE # Service callsNEWLINE def delete_artifact(NEWLINE self,NEWLINE name,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Deletes an existing artifact.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> name = client.artifact_path('[PROJECT]', '[INCIDENT]', '[ARTIFACT]')NEWLINE >>>NEWLINE >>> client.delete_artifact(name)NEWLINENEWLINE Args:NEWLINE name (str): Required. Resource name of the artifact.NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "delete_artifact" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "delete_artifact"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.delete_artifact,NEWLINE default_retry=self._method_configs["DeleteArtifact"].retry,NEWLINE default_timeout=self._method_configs["DeleteArtifact"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.DeleteArtifactRequest(name=name,)NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("name", name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE self._inner_api_calls["delete_artifact"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def request_incident_role_handover(NEWLINE self,NEWLINE name,NEWLINE new_assignee,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Starts a role handover. The proposed assignee will receive an emailNEWLINE notifying them of the assignment. This will fail if a role handover isNEWLINE already pending.NEWLINE Handover to an oncall ladder is not permitted. UseNEWLINE CreateIncidentRoleAssignment instead.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> # TODO: Initialize `name`:NEWLINE >>> name = ''NEWLINE >>>NEWLINE >>> # TODO: Initialize `new_assignee`:NEWLINE >>> new_assignee = {}NEWLINE >>>NEWLINE >>> response = client.request_incident_role_handover(name, new_assignee)NEWLINENEWLINE Args:NEWLINE name (str): Required. Resource name of the role assignment.NEWLINE new_assignee (Union[dict, ~google.cloud.irm_v1alpha2.types.User]): Required. The proposed assignee.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.User`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "request_incident_role_handover" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "request_incident_role_handover"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.request_incident_role_handover,NEWLINE default_retry=self._method_configs["RequestIncidentRoleHandover"].retry,NEWLINE default_timeout=self._method_configs[NEWLINE "RequestIncidentRoleHandover"NEWLINE ].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.RequestIncidentRoleHandoverRequest(NEWLINE name=name, new_assignee=new_assignee,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("name", name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["request_incident_role_handover"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def confirm_incident_role_handover(NEWLINE self,NEWLINE name,NEWLINE new_assignee,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Confirms a role handover. This will fail if the 'proposed_assignee'NEWLINE field of the IncidentRoleAssignment is not equal to the 'new_assignee'NEWLINE field of the request. If the caller is not the new_assignee,NEWLINE ForceIncidentRoleHandover should be used instead.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> name = client.incident_role_assignment_path('[PROJECT_ID_OR_NUMBER]', '[INCIDENT_ID]', '[ROLE_ID]')NEWLINE >>>NEWLINE >>> # TODO: Initialize `new_assignee`:NEWLINE >>> new_assignee = {}NEWLINE >>>NEWLINE >>> response = client.confirm_incident_role_handover(name, new_assignee)NEWLINENEWLINE Args:NEWLINE name (str): Required. Resource name of the role assignment.NEWLINE new_assignee (Union[dict, ~google.cloud.irm_v1alpha2.types.User]): Required. The proposed assignee, who will now be the assignee. This should be theNEWLINE current user; otherwise ForceRoleHandover should be called.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.User`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "confirm_incident_role_handover" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "confirm_incident_role_handover"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.confirm_incident_role_handover,NEWLINE default_retry=self._method_configs["ConfirmIncidentRoleHandover"].retry,NEWLINE default_timeout=self._method_configs[NEWLINE "ConfirmIncidentRoleHandover"NEWLINE ].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.ConfirmIncidentRoleHandoverRequest(NEWLINE name=name, new_assignee=new_assignee,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("name", name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["confirm_incident_role_handover"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def force_incident_role_handover(NEWLINE self,NEWLINE name,NEWLINE new_assignee,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Forces a role handover. This will fail if the 'proposed_assignee'NEWLINE field of the IncidentRoleAssignment is not equal to the 'new_assignee'NEWLINE field of the request. If the caller is the new_assignee,NEWLINE ConfirmIncidentRoleHandover should be used instead.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> name = client.incident_role_assignment_path('[PROJECT_ID_OR_NUMBER]', '[INCIDENT_ID]', '[ROLE_ID]')NEWLINE >>>NEWLINE >>> # TODO: Initialize `new_assignee`:NEWLINE >>> new_assignee = {}NEWLINE >>>NEWLINE >>> response = client.force_incident_role_handover(name, new_assignee)NEWLINENEWLINE Args:NEWLINE name (str): Required. Resource name of the role assignment.NEWLINE new_assignee (Union[dict, ~google.cloud.irm_v1alpha2.types.User]): Required. The proposed assignee, who will now be the assignee. This should not beNEWLINE the current user; otherwise ConfirmRoleHandover should be called.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.User`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "force_incident_role_handover" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "force_incident_role_handover"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.force_incident_role_handover,NEWLINE default_retry=self._method_configs["ForceIncidentRoleHandover"].retry,NEWLINE default_timeout=self._method_configs[NEWLINE "ForceIncidentRoleHandover"NEWLINE ].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.ForceIncidentRoleHandoverRequest(NEWLINE name=name, new_assignee=new_assignee,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("name", name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["force_incident_role_handover"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def create_incident(NEWLINE self,NEWLINE incident,NEWLINE parent,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Creates a new incident.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> # TODO: Initialize `incident`:NEWLINE >>> incident = {}NEWLINE >>> parent = client.project_path('[PROJECT]')NEWLINE >>>NEWLINE >>> response = client.create_incident(incident, parent)NEWLINENEWLINE Args:NEWLINE incident (Union[dict, ~google.cloud.irm_v1alpha2.types.Incident]): Required. The incident to create.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Incident`NEWLINE parent (str): Required. The resource name of the hosting Stackdriver project whichNEWLINE the incident belongs to. The name is of the formNEWLINE ``projects/{project_id_or_number}`` .NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.Incident` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "create_incident" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "create_incident"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.create_incident,NEWLINE default_retry=self._method_configs["CreateIncident"].retry,NEWLINE default_timeout=self._method_configs["CreateIncident"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.CreateIncidentRequest(NEWLINE incident=incident, parent=parent,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("parent", parent)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["create_incident"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def get_incident(NEWLINE self,NEWLINE name,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Returns an incident by name.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> name = client.incident_path('[PROJECT]', '[INCIDENT]')NEWLINE >>>NEWLINE >>> response = client.get_incident(name)NEWLINENEWLINE Args:NEWLINE name (str): Required. Resource name of the incident, for example,NEWLINE "projects/{project_id_or_number}/incidents/{incident_id}".NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.Incident` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "get_incident" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "get_incident"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.get_incident,NEWLINE default_retry=self._method_configs["GetIncident"].retry,NEWLINE default_timeout=self._method_configs["GetIncident"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.GetIncidentRequest(name=name,)NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("name", name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["get_incident"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def search_incidents(NEWLINE self,NEWLINE parent,NEWLINE query=None,NEWLINE page_size=None,NEWLINE time_zone=None,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Returns a list of incidents.NEWLINE Incidents are ordered by start time, with the most recent incidents first.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> parent = client.project_path('[PROJECT]')NEWLINE >>>NEWLINE >>> # Iterate over all resultsNEWLINE >>> for element in client.search_incidents(parent):NEWLINE ... # process elementNEWLINE ... passNEWLINE >>>NEWLINE >>>NEWLINE >>> # Alternatively:NEWLINE >>>NEWLINE >>> # Iterate over results one page at a timeNEWLINE >>> for page in client.search_incidents(parent).pages:NEWLINE ... for element in page:NEWLINE ... # process elementNEWLINE ... passNEWLINENEWLINE Args:NEWLINE parent (str): Required. The resource name of the hosting Stackdriver project which requestedNEWLINE incidents belong to.NEWLINE query (str): An expression that defines which incidents to return.NEWLINENEWLINE Search atoms can be used to match certain specific fields. Otherwise,NEWLINE plain text will match text fields in the incident.NEWLINENEWLINE Search atoms:NEWLINENEWLINE - ``start`` - (timestamp) The time the incident started.NEWLINE - ``stage`` - The stage of the incident, one of detected, triaged,NEWLINE mitigated, resolved, documented, or duplicate (which correspond toNEWLINE values in the Incident.Stage enum). These are ordered, soNEWLINE ``stagemedium``, ``severity<=minor``, etc.).NEWLINENEWLINE Timestamp formats:NEWLINENEWLINE - yyyy-MM-dd - an absolute date, treated as a calendar-day-wide window.NEWLINE In other words, the "<" operator will match dates before that date,NEWLINE the ">" operator will match dates after that date, and the ":" or "="NEWLINE operators will match the entire day.NEWLINE - Nd (for example, 7d) - a relative number of days ago, treated as aNEWLINE moment in time (as opposed to a day-wide span). A multiple of 24NEWLINE hours ago (as opposed to calendar days). In the case of daylightNEWLINE savings time, it will apply the current timezone to both ends of theNEWLINE range. Note that exact matching (for example, ``start:7d``) isNEWLINE unlikely to be useful because that would only match incidents createdNEWLINE precisely at a particular instant in time.NEWLINENEWLINE Examples:NEWLINENEWLINE - ``foo`` - matches incidents containing the word "foo"NEWLINE - ``"foo bar"`` - matches incidents containing the phrase "foo bar"NEWLINE - ``foo bar`` or ``foo AND bar`` - matches incidents containing theNEWLINE words "foo" and "bar"NEWLINE - ``foo -bar`` or ``foo AND NOT bar`` - matches incidents containingNEWLINE the word "foo" but not the word "bar"NEWLINE - ``foo OR bar`` - matches incidents containing the word "foo" or theNEWLINE word "bar"NEWLINE - ``start>2018-11-28`` - matches incidents which started after NovemberNEWLINE 11, 2018.NEWLINE - ``start<=2018-11-28`` - matches incidents which started on or beforeNEWLINE November 11, 2018.NEWLINE - ``start:2018-11-28`` - matches incidents which started on NovemberNEWLINE 11, 2018.NEWLINE - ``start>7d`` - matches incidents which started after the point inNEWLINE time 7*24 hours agoNEWLINE - ``start>180d`` - similar to 7d, but likely to cross the daylightNEWLINE savings time boundary, so the end time will be 1 hour different fromNEWLINE "now."NEWLINE - ``foo AND start>90d AND stage>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> # TODO: Initialize `incident`:NEWLINE >>> incident = {}NEWLINE >>>NEWLINE >>> response = client.update_incident(incident)NEWLINENEWLINE Args:NEWLINE incident (Union[dict, ~google.cloud.irm_v1alpha2.types.Incident]): Required. The incident to update with the new values.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Incident`NEWLINE update_mask (Union[dict, ~google.cloud.irm_v1alpha2.types.FieldMask]): List of fields that should be updated.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.FieldMask`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.Incident` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "update_incident" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "update_incident"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.update_incident,NEWLINE default_retry=self._method_configs["UpdateIncident"].retry,NEWLINE default_timeout=self._method_configs["UpdateIncident"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.UpdateIncidentRequest(NEWLINE incident=incident, update_mask=update_mask,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("incident.name", incident.name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["update_incident"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def search_similar_incidents(NEWLINE self,NEWLINE name,NEWLINE page_size=None,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Returns a list of incidents that are "similar" to the specified incidentNEWLINE or signal. This functionality is provided on a best-effort basis and theNEWLINE definition of "similar" is subject to change.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> name = client.incident_path('[PROJECT]', '[INCIDENT]')NEWLINE >>>NEWLINE >>> # Iterate over all resultsNEWLINE >>> for element in client.search_similar_incidents(name):NEWLINE ... # process elementNEWLINE ... passNEWLINE >>>NEWLINE >>>NEWLINE >>> # Alternatively:NEWLINE >>>NEWLINE >>> # Iterate over results one page at a timeNEWLINE >>> for page in client.search_similar_incidents(name).pages:NEWLINE ... for element in page:NEWLINE ... # process elementNEWLINE ... passNEWLINENEWLINE Args:NEWLINE name (str): Required. Resource name of the incident or signal, for example,NEWLINE "projects/{project_id_or_number}/incidents/{incident_id}".NEWLINE page_size (int): The maximum number of resources contained in theNEWLINE underlying API response. If page streaming is performed per-NEWLINE resource, this parameter does not affect the return value. If pageNEWLINE streaming is performed per-page, this determines the maximum numberNEWLINE of resources in a page.NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.api_core.page_iterator.PageIterator` instance.NEWLINE An iterable of :class:`~google.cloud.irm_v1alpha2.types.Result` instances.NEWLINE You can also iterate over the pages of the responseNEWLINE using its `pages` property.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "search_similar_incidents" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "search_similar_incidents"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.search_similar_incidents,NEWLINE default_retry=self._method_configs["SearchSimilarIncidents"].retry,NEWLINE default_timeout=self._method_configs["SearchSimilarIncidents"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.SearchSimilarIncidentsRequest(NEWLINE name=name, page_size=page_size,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("name", name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE iterator = google.api_core.page_iterator.GRPCIterator(NEWLINE client=None,NEWLINE method=functools.partial(NEWLINE self._inner_api_calls["search_similar_incidents"],NEWLINE retry=retry,NEWLINE timeout=timeout,NEWLINE metadata=metadata,NEWLINE ),NEWLINE request=request,NEWLINE items_field="results",NEWLINE request_token_field="page_token",NEWLINE response_token_field="next_page_token",NEWLINE )NEWLINE return iteratorNEWLINENEWLINE def create_annotation(NEWLINE self,NEWLINE parent,NEWLINE annotation,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Creates an annotation on an existing incident. Only 'text/plain' andNEWLINE 'text/markdown' annotations can be created via this method.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> parent = client.incident_path('[PROJECT]', '[INCIDENT]')NEWLINE >>>NEWLINE >>> # TODO: Initialize `annotation`:NEWLINE >>> annotation = {}NEWLINE >>>NEWLINE >>> response = client.create_annotation(parent, annotation)NEWLINENEWLINE Args:NEWLINE parent (str): Required. Resource name of the incident, for example,NEWLINE "projects/{project_id_or_number}/incidents/{incident_id}".NEWLINE annotation (Union[dict, ~google.cloud.irm_v1alpha2.types.Annotation]): Required. Only annotation.content is an input argument.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Annotation`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.Annotation` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "create_annotation" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "create_annotation"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.create_annotation,NEWLINE default_retry=self._method_configs["CreateAnnotation"].retry,NEWLINE default_timeout=self._method_configs["CreateAnnotation"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.CreateAnnotationRequest(NEWLINE parent=parent, annotation=annotation,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("parent", parent)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["create_annotation"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def list_annotations(NEWLINE self,NEWLINE parent,NEWLINE page_size=None,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Lists annotations that are part of an incident. No assumptions should beNEWLINE made on the content-type of the annotation returned.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> parent = client.incident_path('[PROJECT]', '[INCIDENT]')NEWLINE >>>NEWLINE >>> # Iterate over all resultsNEWLINE >>> for element in client.list_annotations(parent):NEWLINE ... # process elementNEWLINE ... passNEWLINE >>>NEWLINE >>>NEWLINE >>> # Alternatively:NEWLINE >>>NEWLINE >>> # Iterate over results one page at a timeNEWLINE >>> for page in client.list_annotations(parent).pages:NEWLINE ... for element in page:NEWLINE ... # process elementNEWLINE ... passNEWLINENEWLINE Args:NEWLINE parent (str): Required. Resource name of the incident, for example,NEWLINE "projects/{project_id_or_number}/incidents/{incident_id}".NEWLINE page_size (int): The maximum number of resources contained in theNEWLINE underlying API response. If page streaming is performed per-NEWLINE resource, this parameter does not affect the return value. If pageNEWLINE streaming is performed per-page, this determines the maximum numberNEWLINE of resources in a page.NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.api_core.page_iterator.PageIterator` instance.NEWLINE An iterable of :class:`~google.cloud.irm_v1alpha2.types.Annotation` instances.NEWLINE You can also iterate over the pages of the responseNEWLINE using its `pages` property.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "list_annotations" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "list_annotations"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.list_annotations,NEWLINE default_retry=self._method_configs["ListAnnotations"].retry,NEWLINE default_timeout=self._method_configs["ListAnnotations"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.ListAnnotationsRequest(NEWLINE parent=parent, page_size=page_size,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("parent", parent)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE iterator = google.api_core.page_iterator.GRPCIterator(NEWLINE client=None,NEWLINE method=functools.partial(NEWLINE self._inner_api_calls["list_annotations"],NEWLINE retry=retry,NEWLINE timeout=timeout,NEWLINE metadata=metadata,NEWLINE ),NEWLINE request=request,NEWLINE items_field="annotations",NEWLINE request_token_field="page_token",NEWLINE response_token_field="next_page_token",NEWLINE )NEWLINE return iteratorNEWLINENEWLINE def create_tag(NEWLINE self,NEWLINE parent,NEWLINE tag,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Creates a tag on an existing incident.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> parent = client.incident_path('[PROJECT]', '[INCIDENT]')NEWLINE >>>NEWLINE >>> # TODO: Initialize `tag`:NEWLINE >>> tag = {}NEWLINE >>>NEWLINE >>> response = client.create_tag(parent, tag)NEWLINENEWLINE Args:NEWLINE parent (str): Required. Resource name of the incident, for example,NEWLINE "projects/{project_id_or_number}/incidents/{incident_id}".NEWLINE tag (Union[dict, ~google.cloud.irm_v1alpha2.types.Tag]): Required. Tag to create. Only tag.display_name is an input argument.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Tag`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.Tag` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "create_tag" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "create_tag"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.create_tag,NEWLINE default_retry=self._method_configs["CreateTag"].retry,NEWLINE default_timeout=self._method_configs["CreateTag"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.CreateTagRequest(parent=parent, tag=tag,)NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("parent", parent)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["create_tag"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def delete_tag(NEWLINE self,NEWLINE name,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Deletes an existing tag.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> name = client.tag_path('[PROJECT]', '[INCIDENT]', '[TAG]')NEWLINE >>>NEWLINE >>> client.delete_tag(name)NEWLINENEWLINE Args:NEWLINE name (str): Required. Resource name of the tag.NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "delete_tag" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "delete_tag"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.delete_tag,NEWLINE default_retry=self._method_configs["DeleteTag"].retry,NEWLINE default_timeout=self._method_configs["DeleteTag"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.DeleteTagRequest(name=name,)NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("name", name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE self._inner_api_calls["delete_tag"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def list_tags(NEWLINE self,NEWLINE parent,NEWLINE page_size=None,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Lists tags that are part of an incident.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> parent = client.incident_path('[PROJECT]', '[INCIDENT]')NEWLINE >>>NEWLINE >>> # Iterate over all resultsNEWLINE >>> for element in client.list_tags(parent):NEWLINE ... # process elementNEWLINE ... passNEWLINE >>>NEWLINE >>>NEWLINE >>> # Alternatively:NEWLINE >>>NEWLINE >>> # Iterate over results one page at a timeNEWLINE >>> for page in client.list_tags(parent).pages:NEWLINE ... for element in page:NEWLINE ... # process elementNEWLINE ... passNEWLINENEWLINE Args:NEWLINE parent (str): Required. Resource name of the incident, for example,NEWLINE "projects/{project_id_or_number}/incidents/{incident_id}".NEWLINE page_size (int): The maximum number of resources contained in theNEWLINE underlying API response. If page streaming is performed per-NEWLINE resource, this parameter does not affect the return value. If pageNEWLINE streaming is performed per-page, this determines the maximum numberNEWLINE of resources in a page.NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.api_core.page_iterator.PageIterator` instance.NEWLINE An iterable of :class:`~google.cloud.irm_v1alpha2.types.Tag` instances.NEWLINE You can also iterate over the pages of the responseNEWLINE using its `pages` property.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "list_tags" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "list_tags"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.list_tags,NEWLINE default_retry=self._method_configs["ListTags"].retry,NEWLINE default_timeout=self._method_configs["ListTags"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.ListTagsRequest(NEWLINE parent=parent, page_size=page_size,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("parent", parent)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE iterator = google.api_core.page_iterator.GRPCIterator(NEWLINE client=None,NEWLINE method=functools.partial(NEWLINE self._inner_api_calls["list_tags"],NEWLINE retry=retry,NEWLINE timeout=timeout,NEWLINE metadata=metadata,NEWLINE ),NEWLINE request=request,NEWLINE items_field="tags",NEWLINE request_token_field="page_token",NEWLINE response_token_field="next_page_token",NEWLINE )NEWLINE return iteratorNEWLINENEWLINE def create_signal(NEWLINE self,NEWLINE parent,NEWLINE signal,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Creates a new signal.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> parent = client.project_path('[PROJECT]')NEWLINE >>>NEWLINE >>> # TODO: Initialize `signal`:NEWLINE >>> signal = {}NEWLINE >>>NEWLINE >>> response = client.create_signal(parent, signal)NEWLINENEWLINE Args:NEWLINE parent (str): Required. The resource name of the hosting Stackdriver project which requestedNEWLINE signal belongs to.NEWLINE signal (Union[dict, ~google.cloud.irm_v1alpha2.types.Signal]): Required. The signal to create.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Signal`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.Signal` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "create_signal" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "create_signal"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.create_signal,NEWLINE default_retry=self._method_configs["CreateSignal"].retry,NEWLINE default_timeout=self._method_configs["CreateSignal"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.CreateSignalRequest(NEWLINE parent=parent, signal=signal,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("parent", parent)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["create_signal"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def search_signals(NEWLINE self,NEWLINE parent,NEWLINE query=None,NEWLINE page_size=None,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Lists signals that are part of an incident.NEWLINE Signals are returned in reverse chronological order.NEWLINE Note that search should not be relied on for critical functionality. ItNEWLINE has lower availability guarantees and might fail to return valid results.NEWLINE Returned results might include stale or extraneous entries.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> parent = client.project_path('[PROJECT]')NEWLINE >>>NEWLINE >>> # Iterate over all resultsNEWLINE >>> for element in client.search_signals(parent):NEWLINE ... # process elementNEWLINE ... passNEWLINE >>>NEWLINE >>>NEWLINE >>> # Alternatively:NEWLINE >>>NEWLINE >>> # Iterate over results one page at a timeNEWLINE >>> for page in client.search_signals(parent).pages:NEWLINE ... for element in page:NEWLINE ... # process elementNEWLINE ... passNEWLINENEWLINE Args:NEWLINE parent (str): Required. The resource name of the hosting Stackdriver project which requestedNEWLINE incidents belong to.NEWLINE query (str): An expression that defines which signals to return.NEWLINENEWLINE Search atoms can be used to match certain specific fields. Otherwise,NEWLINE plain text will match text fields in the signal.NEWLINENEWLINE Search atoms:NEWLINENEWLINE - ``start`` - (timestamp) The time the signal was created.NEWLINE - ``title`` - The title of the signal.NEWLINE - ``signal_state`` - ``open`` or ``closed``. State of the signal.NEWLINE (e.g., ``signal_state:open``)NEWLINENEWLINE Timestamp formats:NEWLINENEWLINE - yyyy-MM-dd - an absolute date, treated as a calendar-day-wide window.NEWLINE In other words, the "<" operator will match dates before that date,NEWLINE the ">" operator will match dates after that date, and the ":"NEWLINE operator will match the entire day.NEWLINE - yyyy-MM-ddTHH:mm - Same as above, but with minute resolution.NEWLINE - yyyy-MM-ddTHH:mm:ss - Same as above, but with second resolution.NEWLINE - Nd (e.g. 7d) - a relative number of days ago, treated as a moment inNEWLINE time (as opposed to a day-wide span) a multiple of 24 hours ago (asNEWLINE opposed to calendar days). In the case of daylight savings time, itNEWLINE will apply the current timezone to both ends of the range. Note thatNEWLINE exact matching (e.g. ``start:7d``) is unlikely to be useful becauseNEWLINE that would only match signals created precisely at a particularNEWLINE instant in time.NEWLINENEWLINE The absolute timestamp formats (everything starting with a year) canNEWLINE optionally be followed with a UTC offset in +/-hh:mm format. Also, theNEWLINE 'T' separating dates and times can optionally be replaced with a space.NEWLINE Note that any timestamp containing a space or colon will need to beNEWLINE quoted.NEWLINENEWLINE Examples:NEWLINENEWLINE - ``foo`` - matches signals containing the word "foo"NEWLINE - ``"foo bar"`` - matches signals containing the phrase "foo bar"NEWLINE - ``foo bar`` or ``foo AND bar`` - matches signals containing the wordsNEWLINE "foo" and "bar"NEWLINE - ``foo -bar`` or ``foo AND NOT bar`` - matches signals containing theNEWLINE word "foo" but not the word "bar"NEWLINE - ``foo OR bar`` - matches signals containing the word "foo" or theNEWLINE word "bar"NEWLINE - ``start>2018-11-28`` - matches signals which started after NovemberNEWLINE 11, 2018.NEWLINE - ``start<=2018-11-28`` - matches signals which started on or beforeNEWLINE November 11, 2018.NEWLINE - ``start:2018-11-28`` - matches signals which started on November 11,NEWLINE 2018.NEWLINE - ``start>"2018-11-28 01:02:03+04:00"`` - matches signals which startedNEWLINE after November 11, 2018 at 1:02:03 AM according to the UTC+04 timeNEWLINE zone.NEWLINE - ``start>7d`` - matches signals which started after the point in timeNEWLINE 7*24 hours agoNEWLINE - ``start>180d`` - similar to 7d, but likely to cross the daylightNEWLINE savings time boundary, so the end time will be 1 hour different fromNEWLINE "now."NEWLINE - ``foo AND start>90d AND stage>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> response = client.lookup_signal()NEWLINENEWLINE Args:NEWLINE cscc_finding (str): Required. Full resource name of the CSCC finding id this signal refers to (e.g.NEWLINE "organizations/abc/sources/123/findings/xyz")NEWLINE stackdriver_notification_id (str): The ID from the Stackdriver Alerting notification.NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.Signal` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "lookup_signal" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "lookup_signal"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.lookup_signal,NEWLINE default_retry=self._method_configs["LookupSignal"].retry,NEWLINE default_timeout=self._method_configs["LookupSignal"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE # Sanity check: We have some fields which are mutually exclusive;NEWLINE # raise ValueError if more than one is sent.NEWLINE google.api_core.protobuf_helpers.check_oneof(NEWLINE cscc_finding=cscc_finding,NEWLINE stackdriver_notification_id=stackdriver_notification_id,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.LookupSignalRequest(NEWLINE cscc_finding=cscc_finding,NEWLINE stackdriver_notification_id=stackdriver_notification_id,NEWLINE )NEWLINE return self._inner_api_calls["lookup_signal"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def get_signal(NEWLINE self,NEWLINE name,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Returns a signal by name.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> name = client.signal_path('[PROJECT]', '[SIGNAL]')NEWLINE >>>NEWLINE >>> response = client.get_signal(name)NEWLINENEWLINE Args:NEWLINE name (str): Required. Resource name of the Signal resource, for example,NEWLINE "projects/{project_id_or_number}/signals/{signal_id}".NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.Signal` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "get_signal" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "get_signal"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.get_signal,NEWLINE default_retry=self._method_configs["GetSignal"].retry,NEWLINE default_timeout=self._method_configs["GetSignal"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.GetSignalRequest(name=name,)NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("name", name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["get_signal"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def update_signal(NEWLINE self,NEWLINE signal,NEWLINE update_mask=None,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Updates an existing signal (for example, to assign/unassign it to anNEWLINE incident).NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> # TODO: Initialize `signal`:NEWLINE >>> signal = {}NEWLINE >>>NEWLINE >>> response = client.update_signal(signal)NEWLINENEWLINE Args:NEWLINE signal (Union[dict, ~google.cloud.irm_v1alpha2.types.Signal]): Required. The signal to update with the new values.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Signal`NEWLINE update_mask (Union[dict, ~google.cloud.irm_v1alpha2.types.FieldMask]): List of fields that should be updated.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.FieldMask`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.Signal` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "update_signal" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "update_signal"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.update_signal,NEWLINE default_retry=self._method_configs["UpdateSignal"].retry,NEWLINE default_timeout=self._method_configs["UpdateSignal"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.UpdateSignalRequest(NEWLINE signal=signal, update_mask=update_mask,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("signal.name", signal.name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["update_signal"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def escalate_incident(NEWLINE self,NEWLINE incident,NEWLINE update_mask=None,NEWLINE subscriptions=None,NEWLINE tags=None,NEWLINE roles=None,NEWLINE artifacts=None,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Escalates an incident.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> # TODO: Initialize `incident`:NEWLINE >>> incident = {}NEWLINE >>>NEWLINE >>> response = client.escalate_incident(incident)NEWLINENEWLINE Args:NEWLINE incident (Union[dict, ~google.cloud.irm_v1alpha2.types.Incident]): Required. The incident to escalate with the new values.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Incident`NEWLINE update_mask (Union[dict, ~google.cloud.irm_v1alpha2.types.FieldMask]): List of fields that should be updated.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.FieldMask`NEWLINE subscriptions (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Subscription]]): Subscriptions to add or update. Existing subscriptions with the sameNEWLINE channel and address as a subscription in the list will be updated.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Subscription`NEWLINE tags (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Tag]]): Tags to add. Tags identical to existing tags will be ignored.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Tag`NEWLINE roles (list[Union[dict, ~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment]]): Roles to add or update. Existing roles with the same type (andNEWLINE title, for TYPE_OTHER roles) will be updated.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment`NEWLINE artifacts (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Artifact]]): Artifacts to add. All artifacts are added without checking for duplicates.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Artifact`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.EscalateIncidentResponse` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "escalate_incident" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "escalate_incident"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.escalate_incident,NEWLINE default_retry=self._method_configs["EscalateIncident"].retry,NEWLINE default_timeout=self._method_configs["EscalateIncident"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.EscalateIncidentRequest(NEWLINE incident=incident,NEWLINE update_mask=update_mask,NEWLINE subscriptions=subscriptions,NEWLINE tags=tags,NEWLINE roles=roles,NEWLINE artifacts=artifacts,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("incident.name", incident.name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["escalate_incident"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def create_artifact(NEWLINE self,NEWLINE parent,NEWLINE artifact,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Creates a new artifact.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> parent = client.incident_path('[PROJECT]', '[INCIDENT]')NEWLINE >>>NEWLINE >>> # TODO: Initialize `artifact`:NEWLINE >>> artifact = {}NEWLINE >>>NEWLINE >>> response = client.create_artifact(parent, artifact)NEWLINENEWLINE Args:NEWLINE parent (str): Required. Resource name of the incident, for example,NEWLINE "projects/{project_id_or_number}/incidents/{incident_id}".NEWLINE artifact (Union[dict, ~google.cloud.irm_v1alpha2.types.Artifact]): Required. The artifact to create.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Artifact`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.Artifact` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "create_artifact" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "create_artifact"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.create_artifact,NEWLINE default_retry=self._method_configs["CreateArtifact"].retry,NEWLINE default_timeout=self._method_configs["CreateArtifact"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.CreateArtifactRequest(NEWLINE parent=parent, artifact=artifact,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("parent", parent)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["create_artifact"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def list_artifacts(NEWLINE self,NEWLINE parent,NEWLINE page_size=None,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Returns a list of artifacts for an incident.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> parent = client.incident_path('[PROJECT]', '[INCIDENT]')NEWLINE >>>NEWLINE >>> # Iterate over all resultsNEWLINE >>> for element in client.list_artifacts(parent):NEWLINE ... # process elementNEWLINE ... passNEWLINE >>>NEWLINE >>>NEWLINE >>> # Alternatively:NEWLINE >>>NEWLINE >>> # Iterate over results one page at a timeNEWLINE >>> for page in client.list_artifacts(parent).pages:NEWLINE ... for element in page:NEWLINE ... # process elementNEWLINE ... passNEWLINENEWLINE Args:NEWLINE parent (str): Required. Resource name of the incident, for example,NEWLINE "projects/{project_id_or_number}/incidents/{incident_id}".NEWLINE page_size (int): The maximum number of resources contained in theNEWLINE underlying API response. If page streaming is performed per-NEWLINE resource, this parameter does not affect the return value. If pageNEWLINE streaming is performed per-page, this determines the maximum numberNEWLINE of resources in a page.NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.api_core.page_iterator.PageIterator` instance.NEWLINE An iterable of :class:`~google.cloud.irm_v1alpha2.types.Artifact` instances.NEWLINE You can also iterate over the pages of the responseNEWLINE using its `pages` property.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "list_artifacts" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "list_artifacts"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.list_artifacts,NEWLINE default_retry=self._method_configs["ListArtifacts"].retry,NEWLINE default_timeout=self._method_configs["ListArtifacts"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.ListArtifactsRequest(NEWLINE parent=parent, page_size=page_size,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("parent", parent)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE iterator = google.api_core.page_iterator.GRPCIterator(NEWLINE client=None,NEWLINE method=functools.partial(NEWLINE self._inner_api_calls["list_artifacts"],NEWLINE retry=retry,NEWLINE timeout=timeout,NEWLINE metadata=metadata,NEWLINE ),NEWLINE request=request,NEWLINE items_field="artifacts",NEWLINE request_token_field="page_token",NEWLINE response_token_field="next_page_token",NEWLINE )NEWLINE return iteratorNEWLINENEWLINE def update_artifact(NEWLINE self,NEWLINE artifact,NEWLINE update_mask=None,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Updates an existing artifact.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> # TODO: Initialize `artifact`:NEWLINE >>> artifact = {}NEWLINE >>>NEWLINE >>> response = client.update_artifact(artifact)NEWLINENEWLINE Args:NEWLINE artifact (Union[dict, ~google.cloud.irm_v1alpha2.types.Artifact]): Required. The artifact to update with the new values.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Artifact`NEWLINE update_mask (Union[dict, ~google.cloud.irm_v1alpha2.types.FieldMask]): List of fields that should be updated.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.FieldMask`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.Artifact` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "update_artifact" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "update_artifact"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.update_artifact,NEWLINE default_retry=self._method_configs["UpdateArtifact"].retry,NEWLINE default_timeout=self._method_configs["UpdateArtifact"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.UpdateArtifactRequest(NEWLINE artifact=artifact, update_mask=update_mask,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("artifact.name", artifact.name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["update_artifact"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def send_shift_handoff(NEWLINE self,NEWLINE parent,NEWLINE recipients,NEWLINE subject,NEWLINE cc=None,NEWLINE notes_content_type=None,NEWLINE notes_content=None,NEWLINE incidents=None,NEWLINE preview_only=None,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Sends a summary of the shift for oncall handoff.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> parent = client.project_path('[PROJECT]')NEWLINE >>>NEWLINE >>> # TODO: Initialize `recipients`:NEWLINE >>> recipients = []NEWLINE >>>NEWLINE >>> # TODO: Initialize `subject`:NEWLINE >>> subject = ''NEWLINE >>>NEWLINE >>> response = client.send_shift_handoff(parent, recipients, subject)NEWLINENEWLINE Args:NEWLINE parent (str): Required. The resource name of the Stackdriver project that theNEWLINE handoff is being sent from. for example,NEWLINE ``projects/{project_id_or_number}``NEWLINE recipients (list[str]): Required. Email addresses of the recipients of the handoff, for example,NEWLINE "user@example.com". Must contain at least one entry.NEWLINE subject (str): Required. The subject of the email.NEWLINE cc (list[str]): Optional. Email addresses that should be CC'd on the handoff.NEWLINE notes_content_type (str): Content type string, for example, 'text/plain' or 'text/html'.NEWLINE notes_content (str): Optional. Additional notes to be included in the handoff.NEWLINE incidents (list[Union[dict, ~google.cloud.irm_v1alpha2.types.Incident]]): Optional. The set of incidents that should be included in the handoff.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Incident`NEWLINE preview_only (bool): If set to true a ShiftHandoffResponse will be returned but the handoffNEWLINE will not actually be sent.NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.SendShiftHandoffResponse` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "send_shift_handoff" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "send_shift_handoff"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.send_shift_handoff,NEWLINE default_retry=self._method_configs["SendShiftHandoff"].retry,NEWLINE default_timeout=self._method_configs["SendShiftHandoff"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.SendShiftHandoffRequest(NEWLINE parent=parent,NEWLINE recipients=recipients,NEWLINE subject=subject,NEWLINE cc=cc,NEWLINE notes_content_type=notes_content_type,NEWLINE notes_content=notes_content,NEWLINE incidents=incidents,NEWLINE preview_only=preview_only,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("parent", parent)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["send_shift_handoff"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def create_subscription(NEWLINE self,NEWLINE parent,NEWLINE subscription,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Creates a new subscription.NEWLINE This will fail if:NEWLINE a. there are too many (50) subscriptions in the incident alreadyNEWLINE b. a subscription using the given channel already existsNEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> parent = client.incident_path('[PROJECT]', '[INCIDENT]')NEWLINE >>>NEWLINE >>> # TODO: Initialize `subscription`:NEWLINE >>> subscription = {}NEWLINE >>>NEWLINE >>> response = client.create_subscription(parent, subscription)NEWLINENEWLINE Args:NEWLINE parent (str): Required. Resource name of the incident, for example,NEWLINE "projects/{project_id_or_number}/incidents/{incident_id}".NEWLINE subscription (Union[dict, ~google.cloud.irm_v1alpha2.types.Subscription]): Required. The subscription to create.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Subscription`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.Subscription` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "create_subscription" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "create_subscription"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.create_subscription,NEWLINE default_retry=self._method_configs["CreateSubscription"].retry,NEWLINE default_timeout=self._method_configs["CreateSubscription"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.CreateSubscriptionRequest(NEWLINE parent=parent, subscription=subscription,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("parent", parent)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["create_subscription"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def update_subscription(NEWLINE self,NEWLINE subscription,NEWLINE update_mask=None,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Updates a subscription.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> # TODO: Initialize `subscription`:NEWLINE >>> subscription = {}NEWLINE >>>NEWLINE >>> response = client.update_subscription(subscription)NEWLINENEWLINE Args:NEWLINE subscription (Union[dict, ~google.cloud.irm_v1alpha2.types.Subscription]): Required. The subscription to update, with new values.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.Subscription`NEWLINE update_mask (Union[dict, ~google.cloud.irm_v1alpha2.types.FieldMask]): List of fields that should be updated.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.FieldMask`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.Subscription` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "update_subscription" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "update_subscription"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.update_subscription,NEWLINE default_retry=self._method_configs["UpdateSubscription"].retry,NEWLINE default_timeout=self._method_configs["UpdateSubscription"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.UpdateSubscriptionRequest(NEWLINE subscription=subscription, update_mask=update_mask,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("subscription.name", subscription.name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["update_subscription"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def list_subscriptions(NEWLINE self,NEWLINE parent,NEWLINE page_size=None,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Returns a list of subscriptions for an incident.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> parent = client.incident_path('[PROJECT]', '[INCIDENT]')NEWLINE >>>NEWLINE >>> # Iterate over all resultsNEWLINE >>> for element in client.list_subscriptions(parent):NEWLINE ... # process elementNEWLINE ... passNEWLINE >>>NEWLINE >>>NEWLINE >>> # Alternatively:NEWLINE >>>NEWLINE >>> # Iterate over results one page at a timeNEWLINE >>> for page in client.list_subscriptions(parent).pages:NEWLINE ... for element in page:NEWLINE ... # process elementNEWLINE ... passNEWLINENEWLINE Args:NEWLINE parent (str): Required. Resource name of the incident, for example,NEWLINE "projects/{project_id_or_number}/incidents/{incident_id}".NEWLINE page_size (int): The maximum number of resources contained in theNEWLINE underlying API response. If page streaming is performed per-NEWLINE resource, this parameter does not affect the return value. If pageNEWLINE streaming is performed per-page, this determines the maximum numberNEWLINE of resources in a page.NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.api_core.page_iterator.PageIterator` instance.NEWLINE An iterable of :class:`~google.cloud.irm_v1alpha2.types.Subscription` instances.NEWLINE You can also iterate over the pages of the responseNEWLINE using its `pages` property.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "list_subscriptions" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "list_subscriptions"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.list_subscriptions,NEWLINE default_retry=self._method_configs["ListSubscriptions"].retry,NEWLINE default_timeout=self._method_configs["ListSubscriptions"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.ListSubscriptionsRequest(NEWLINE parent=parent, page_size=page_size,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("parent", parent)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE iterator = google.api_core.page_iterator.GRPCIterator(NEWLINE client=None,NEWLINE method=functools.partial(NEWLINE self._inner_api_calls["list_subscriptions"],NEWLINE retry=retry,NEWLINE timeout=timeout,NEWLINE metadata=metadata,NEWLINE ),NEWLINE request=request,NEWLINE items_field="subscriptions",NEWLINE request_token_field="page_token",NEWLINE response_token_field="next_page_token",NEWLINE )NEWLINE return iteratorNEWLINENEWLINE def delete_subscription(NEWLINE self,NEWLINE name,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Deletes an existing subscription.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> name = client.subscription_path('[PROJECT]', '[INCIDENT]', '[SUBSCRIPTION]')NEWLINE >>>NEWLINE >>> client.delete_subscription(name)NEWLINENEWLINE Args:NEWLINE name (str): Required. Resource name of the subscription.NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "delete_subscription" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "delete_subscription"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.delete_subscription,NEWLINE default_retry=self._method_configs["DeleteSubscription"].retry,NEWLINE default_timeout=self._method_configs["DeleteSubscription"].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.DeleteSubscriptionRequest(name=name,)NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("name", name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE self._inner_api_calls["delete_subscription"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def create_incident_role_assignment(NEWLINE self,NEWLINE parent,NEWLINE incident_role_assignment,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Creates a role assignment on an existing incident. Normally, the user fieldNEWLINE will be set when assigning a role to oneself, and the next field will beNEWLINE set when proposing another user as the assignee. Setting the next fieldNEWLINE directly to a user other than oneself is equivalent to proposing andNEWLINE force-assigning the role to the user.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> parent = client.incident_path('[PROJECT]', '[INCIDENT]')NEWLINE >>>NEWLINE >>> # TODO: Initialize `incident_role_assignment`:NEWLINE >>> incident_role_assignment = {}NEWLINE >>>NEWLINE >>> response = client.create_incident_role_assignment(parent, incident_role_assignment)NEWLINENEWLINE Args:NEWLINE parent (str): Required. Resource name of the incident, for example,NEWLINE "projects/{project_id_or_number}/incidents/{incident_id}".NEWLINE incident_role_assignment (Union[dict, ~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment]): Required. Role assignment to create.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "create_incident_role_assignment" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "create_incident_role_assignment"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.create_incident_role_assignment,NEWLINE default_retry=self._method_configs[NEWLINE "CreateIncidentRoleAssignment"NEWLINE ].retry,NEWLINE default_timeout=self._method_configs[NEWLINE "CreateIncidentRoleAssignment"NEWLINE ].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.CreateIncidentRoleAssignmentRequest(NEWLINE parent=parent, incident_role_assignment=incident_role_assignment,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("parent", parent)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["create_incident_role_assignment"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def delete_incident_role_assignment(NEWLINE self,NEWLINE name,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Deletes an existing role assignment.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> name = client.incident_path('[PROJECT]', '[INCIDENT]')NEWLINE >>>NEWLINE >>> client.delete_incident_role_assignment(name)NEWLINENEWLINE Args:NEWLINE name (str): Required. Resource name of the role assignment.NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "delete_incident_role_assignment" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "delete_incident_role_assignment"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.delete_incident_role_assignment,NEWLINE default_retry=self._method_configs[NEWLINE "DeleteIncidentRoleAssignment"NEWLINE ].retry,NEWLINE default_timeout=self._method_configs[NEWLINE "DeleteIncidentRoleAssignment"NEWLINE ].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.DeleteIncidentRoleAssignmentRequest(name=name,)NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("name", name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE self._inner_api_calls["delete_incident_role_assignment"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINENEWLINE def list_incident_role_assignments(NEWLINE self,NEWLINE parent,NEWLINE page_size=None,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Lists role assignments that are part of an incident.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> parent = client.incident_path('[PROJECT]', '[INCIDENT]')NEWLINE >>>NEWLINE >>> # Iterate over all resultsNEWLINE >>> for element in client.list_incident_role_assignments(parent):NEWLINE ... # process elementNEWLINE ... passNEWLINE >>>NEWLINE >>>NEWLINE >>> # Alternatively:NEWLINE >>>NEWLINE >>> # Iterate over results one page at a timeNEWLINE >>> for page in client.list_incident_role_assignments(parent).pages:NEWLINE ... for element in page:NEWLINE ... # process elementNEWLINE ... passNEWLINENEWLINE Args:NEWLINE parent (str): Required. Resource name of the incident, for example,NEWLINE "projects/{project_id_or_number}/incidents/{incident_id}".NEWLINE page_size (int): The maximum number of resources contained in theNEWLINE underlying API response. If page streaming is performed per-NEWLINE resource, this parameter does not affect the return value. If pageNEWLINE streaming is performed per-page, this determines the maximum numberNEWLINE of resources in a page.NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.api_core.page_iterator.PageIterator` instance.NEWLINE An iterable of :class:`~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment` instances.NEWLINE You can also iterate over the pages of the responseNEWLINE using its `pages` property.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "list_incident_role_assignments" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "list_incident_role_assignments"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.list_incident_role_assignments,NEWLINE default_retry=self._method_configs["ListIncidentRoleAssignments"].retry,NEWLINE default_timeout=self._method_configs[NEWLINE "ListIncidentRoleAssignments"NEWLINE ].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.ListIncidentRoleAssignmentsRequest(NEWLINE parent=parent, page_size=page_size,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("parent", parent)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE iterator = google.api_core.page_iterator.GRPCIterator(NEWLINE client=None,NEWLINE method=functools.partial(NEWLINE self._inner_api_calls["list_incident_role_assignments"],NEWLINE retry=retry,NEWLINE timeout=timeout,NEWLINE metadata=metadata,NEWLINE ),NEWLINE request=request,NEWLINE items_field="incident_role_assignments",NEWLINE request_token_field="page_token",NEWLINE response_token_field="next_page_token",NEWLINE )NEWLINE return iteratorNEWLINENEWLINE def cancel_incident_role_handover(NEWLINE self,NEWLINE name,NEWLINE new_assignee,NEWLINE retry=google.api_core.gapic_v1.method.DEFAULT,NEWLINE timeout=google.api_core.gapic_v1.method.DEFAULT,NEWLINE metadata=None,NEWLINE ):NEWLINE """NEWLINE Cancels a role handover. This will fail if the 'proposed_assignee'NEWLINE field of the IncidentRoleAssignment is not equal to the 'new_assignee'NEWLINE field of the request.NEWLINENEWLINE Example:NEWLINE >>> from google.cloud import irm_v1alpha2NEWLINE >>>NEWLINE >>> client = irm_v1alpha2.IncidentServiceClient()NEWLINE >>>NEWLINE >>> name = client.incident_role_assignment_path('[PROJECT_ID_OR_NUMBER]', '[INCIDENT_ID]', '[ROLE_ID]')NEWLINE >>>NEWLINE >>> # TODO: Initialize `new_assignee`:NEWLINE >>> new_assignee = {}NEWLINE >>>NEWLINE >>> response = client.cancel_incident_role_handover(name, new_assignee)NEWLINENEWLINE Args:NEWLINE name (str): Required. Resource name of the role assignment.NEWLINE new_assignee (Union[dict, ~google.cloud.irm_v1alpha2.types.User]): Required. Person who was proposed as the next assignee (i.e.NEWLINE IncidentRoleAssignment.proposed_assignee) and whose proposal is beingNEWLINE cancelled.NEWLINENEWLINE If a dict is provided, it must be of the same form as the protobufNEWLINE message :class:`~google.cloud.irm_v1alpha2.types.User`NEWLINE retry (Optional[google.api_core.retry.Retry]): A retry object usedNEWLINE to retry requests. If ``None`` is specified, requests willNEWLINE be retried using a default configuration.NEWLINE timeout (Optional[float]): The amount of time, in seconds, to waitNEWLINE for the request to complete. Note that if ``retry`` isNEWLINE specified, the timeout applies to each individual attempt.NEWLINE metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadataNEWLINE that is provided to the method.NEWLINENEWLINE Returns:NEWLINE A :class:`~google.cloud.irm_v1alpha2.types.IncidentRoleAssignment` instance.NEWLINENEWLINE Raises:NEWLINE google.api_core.exceptions.GoogleAPICallError: If the requestNEWLINE failed for any reason.NEWLINE google.api_core.exceptions.RetryError: If the request failed dueNEWLINE to a retryable error and retry attempts failed.NEWLINE ValueError: If the parameters are invalid.NEWLINE """NEWLINE # Wrap the transport method to add retry and timeout logic.NEWLINE if "cancel_incident_role_handover" not in self._inner_api_calls:NEWLINE self._inner_api_calls[NEWLINE "cancel_incident_role_handover"NEWLINE ] = google.api_core.gapic_v1.method.wrap_method(NEWLINE self.transport.cancel_incident_role_handover,NEWLINE default_retry=self._method_configs["CancelIncidentRoleHandover"].retry,NEWLINE default_timeout=self._method_configs[NEWLINE "CancelIncidentRoleHandover"NEWLINE ].timeout,NEWLINE client_info=self._client_info,NEWLINE )NEWLINENEWLINE request = incidents_service_pb2.CancelIncidentRoleHandoverRequest(NEWLINE name=name, new_assignee=new_assignee,NEWLINE )NEWLINE if metadata is None:NEWLINE metadata = []NEWLINE metadata = list(metadata)NEWLINE try:NEWLINE routing_header = [("name", name)]NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(NEWLINE routing_headerNEWLINE )NEWLINE metadata.append(routing_metadata)NEWLINENEWLINE return self._inner_api_calls["cancel_incident_role_handover"](NEWLINE request, retry=retry, timeout=timeout, metadata=metadataNEWLINE )NEWLINE import osNEWLINEimport matplotlib.pyplot as pltNEWLINEimport numpy as npNEWLINEimport subprocessNEWLINEfrom tempfile import TemporaryDirectoryNEWLINENEWLINESEMIHDP_HOME_DIR = os.path.dirname(os.path.realpath(__file__))NEWLINESEMIHDP_EXEC = os.path.join(SEMIHDP_HOME_DIR, 'build/run_from_file')NEWLINEBASE_CMD = SEMIHDP_EXEC + ' ' + "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11}"NEWLINEPARAMS_FILE = os.path.join(SEMIHDP_HOME_DIR, 'semihdp_params.asciipb')NEWLINENEWLINENEWLINEdef run_mcmc_from_files(data_path, dens_grid_path, output_path, seed,NEWLINE niter, nburn, thin, update_c="full"):NEWLINE chainfile = os.path.join(output_path, "chains.recordio")NEWLINE c_file = os.path.join(output_path, "c.txt")NEWLINE latent_vars_file = os.path.join(output_path, "latent_vars.txt")NEWLINE dens_path = os.path.join(output_path, "dens/")NEWLINE os.makedirs(dens_path)NEWLINE cmd = BASE_CMD.format(NEWLINE data_path, PARAMS_FILE, chainfile, c_file,NEWLINE latent_vars_file, dens_grid_path, NEWLINE dens_path, seed, niter, nburn, thin, update_c)NEWLINE NEWLINE cmd = cmd.split(" ")NEWLINE subprocess.call(cmd, cwd=SEMIHDP_HOME_DIR)NEWLINE return NEWLINENEWLINENEWLINEdef load_output(output_path, ngroups):NEWLINE c_file = os.path.join(output_path, "c.txt")NEWLINE latent_vars_file = os.path.join(output_path, "latent_vars.txt")NEWLINE dens_path = os.path.join(output_path, "dens/")NEWLINENEWLINE c = np.loadtxt(c_file, delimiter=",")NEWLINE latent_vars = np.loadtxt(latent_vars_file, delimiter=",")NEWLINE log_dens = []NEWLINE for i in range(ngroups):NEWLINE fname = os.path.join(dens_path, "group_{0}.csv".format(i))NEWLINE log_dens.append(np.loadtxt(fname, delimiter=","))NEWLINE return c, latent_vars, log_dens NEWLINENEWLINENEWLINEdef run_mcmc(data: list, dens_grid: np.array, seed: int,NEWLINE niter=1000, nburn=1000, thin=10, update_c="full"):NEWLINE """NEWLINE Runs the semihpd sampler by calling the executable from a subprocess.NEWLINE ArgumentsNEWLINE ---------NEWLINE data: list of np.arrays, each entry is the data in one of the groupsNEWLINE dens_grid: np.array, the grid on which to evaluate the density of all the groupsNEWLINE seed: int, the seed for the random number generatorNEWLINE niter: int, number of iterations to run the samplerNEWLINE nburn: int, number of burn-in iterations NEWLINE thin: int, thinning factorNEWLINE update_c: str, either "full", "metro_base" or "metro_dist". NEWLINE The update rule for the restourants allocationsNEWLINENEWLINE The sampler will be ran for niter + nburn iterations.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE rest_allocs: np.array, of dimension [num_iter, num_groups]NEWLINE The parameters c_i's for each iterationNEWLINE latent_vars: np.array, of dimension [num_iter, 4] the colums areNEWLINE group_id, datum_id, mean (resp. variance) of the latent variable NEWLINE associated to the observationNEWLINE log_dens: list of np.arrays, each entry is the evaluation of log_density of NEWLINE one of the groups in each of the mcmc iterationsNEWLINE """NEWLINENEWLINE ngroups = len(data)NEWLINE data_ = np.vstack([NEWLINE np.column_stack([np.ones_like(x) * i, x]) for i, x in enumerate(data)])NEWLINE with TemporaryDirectory(prefix=SEMIHDP_HOME_DIR+"/") as tmpdir:NEWLINE data_path = os.path.join(tmpdir, 'data.txt')NEWLINE np.savetxt(data_path, data_, delimiter=",")NEWLINE grid_path = os.path.join(tmpdir, 'grid.txt')NEWLINE np.savetxt(grid_path, dens_grid, delimiter=",")NEWLINENEWLINE run_mcmc_from_files(data_path, grid_path, tmpdir, niter, NEWLINE nburn, thin, update_c)NEWLINENEWLINE return load_output(tmpdir, ngroups)NEWLINENEWLINE NEWLINEif __name__ == "__main__":NEWLINE seed = 132312NEWLINE data = [np.random.normal(0, 1, size=100),NEWLINE np.random.normal(0, 1, size=100)]NEWLINE dens_grid = np.linspace(-5, 5, 100)NEWLINE c, latent_vars, log_dens = run_mcmc(data, dens_grid, seed)NEWLINE plt.plot(dens_grid, np.exp(np.mean(log_dens[0], axis=0)))NEWLINE plt.show()NEWLINENEWLINE #!/usr/bin/env python3NEWLINENEWLINE"""NEWLINEIf we list all the natural numbers below 10 that are multiples of 3 or 5,NEWLINEwe get 3, 5, 6 and 9. The sum of these multiples is 23.NEWLINENEWLINEFind the sum of all the multiples of 3 or 5 below 1000.NEWLINENEWLINEhttps://projecteuler.net/problem=1NEWLINENEWLINE"""NEWLINENEWLINEinput = [x for x in range(0, 10)]NEWLINEtest = [x for x in range(0, 1000)]NEWLINENEWLINENEWLINEdef multiple3or5(input):NEWLINE if not input:NEWLINE return 0NEWLINE else:NEWLINE agg = 0NEWLINE for digit in input:NEWLINE print("digit {0}".format(digit))NEWLINE if digit % 3 == 0 or digit % 5 == 0:NEWLINE agg += digitNEWLINE print("agg: {0}".format(agg))NEWLINE else:NEWLINE continueNEWLINE return aggNEWLINENEWLINENEWLINEdef sum_of_sequence(n):NEWLINE """NEWLINE Using N(N+1)/ 2NEWLINE """NEWLINE if not input:NEWLINE return 0NEWLINE else:NEWLINE return (n*(n+1))/2NEWLINENEWLINENEWLINEprint(multiple3or5(input))NEWLINEprint(multiple3or5(test))NEWLINENEWLINEprint("Using Arithmetic")NEWLINEprint(int(3*sum_of_sequence(999//3) + 5*sum_of_sequence(999//5) -NEWLINE 15*sum_of_sequence(999//15)))NEWLINE import osNEWLINEimport pickleNEWLINEimport uuidNEWLINENEWLINEimport dagstermillNEWLINEfrom dagstermill.io_managers import local_output_notebook_io_managerNEWLINENEWLINEfrom dagster import (NEWLINE Field,NEWLINE FileHandle,NEWLINE InputDefinition,NEWLINE Int,NEWLINE List,NEWLINE ModeDefinition,NEWLINE OutputDefinition,NEWLINE ResourceDefinition,NEWLINE String,NEWLINE composite_solid,NEWLINE fs_io_manager,NEWLINE job,NEWLINE pipeline,NEWLINE repository,NEWLINE resource,NEWLINE solid,NEWLINE)NEWLINEfrom dagster.core.storage.file_manager import local_file_managerNEWLINEfrom dagster.utils import PICKLE_PROTOCOL, file_relative_pathNEWLINENEWLINEtry:NEWLINE from dagster_pandas import DataFrameNEWLINENEWLINE DAGSTER_PANDAS_PRESENT = TrueNEWLINEexcept ImportError:NEWLINE DAGSTER_PANDAS_PRESENT = FalseNEWLINENEWLINEtry:NEWLINE import sklearn as _NEWLINENEWLINE SKLEARN_PRESENT = TrueNEWLINEexcept ImportError:NEWLINE SKLEARN_PRESENT = FalseNEWLINENEWLINEtry:NEWLINE import matplotlib as _NEWLINENEWLINE MATPLOTLIB_PRESENT = TrueNEWLINEexcept ImportError:NEWLINE MATPLOTLIB_PRESENT = FalseNEWLINENEWLINENEWLINEclass BasicTest:NEWLINE def __init__(self, x):NEWLINE self.x = xNEWLINENEWLINE def __repr__(self):NEWLINE return "BasicTest: {x}".format(x=str(self.x))NEWLINENEWLINENEWLINEdef nb_test_path(name):NEWLINE return file_relative_path(__file__, f"notebooks/{name}.ipynb")NEWLINENEWLINENEWLINEdef test_nb_solid(name, **kwargs):NEWLINE output_defs = kwargs.pop("output_defs", [OutputDefinition(is_required=False)])NEWLINENEWLINE return dagstermill.define_dagstermill_solid(NEWLINE name=name,NEWLINE notebook_path=nb_test_path(name),NEWLINE output_notebook_name="notebook",NEWLINE output_defs=output_defs,NEWLINE **kwargs,NEWLINE )NEWLINENEWLINENEWLINEdef test_nb_op(name, path, **kwargs):NEWLINE output_defs = kwargs.pop("output_defs", [OutputDefinition(is_required=False)])NEWLINENEWLINE return dagstermill.define_dagstermill_op(NEWLINE name=name,NEWLINE notebook_path=path,NEWLINE output_notebook_name="notebook",NEWLINE output_defs=output_defs,NEWLINE **kwargs,NEWLINE )NEWLINENEWLINENEWLINEdefault_mode_defs = [NEWLINE ModeDefinition(NEWLINE resource_defs={NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE "io_manager": fs_io_manager,NEWLINE }NEWLINE )NEWLINE]NEWLINENEWLINENEWLINEhello_world = test_nb_solid("hello_world", output_defs=[])NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_world_pipeline():NEWLINE hello_world()NEWLINENEWLINENEWLINEhello_world_op = test_nb_op(NEWLINE "hello_world_op",NEWLINE nb_test_path("hello_world"),NEWLINE output_defs=[],NEWLINE)NEWLINENEWLINENEWLINEdef build_hello_world_job():NEWLINE @job(NEWLINE resource_defs={NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE }NEWLINE )NEWLINE def hello_world_job():NEWLINE hello_world_op()NEWLINENEWLINE return hello_world_jobNEWLINENEWLINENEWLINEhello_world_with_custom_tags_and_description = dagstermill.define_dagstermill_solid(NEWLINE name="hello_world_custom",NEWLINE notebook_path=nb_test_path("hello_world"),NEWLINE output_notebook_name="notebook",NEWLINE tags={"foo": "bar"},NEWLINE description="custom description",NEWLINE)NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_world_with_custom_tags_and_description_pipeline():NEWLINE hello_world_with_custom_tags_and_description()NEWLINENEWLINENEWLINEhello_world_config = test_nb_solid(NEWLINE "hello_world_config",NEWLINE config_schema={"greeting": Field(String, is_required=False, default_value="hello")},NEWLINE)NEWLINENEWLINENEWLINEgoodbye_config = dagstermill.define_dagstermill_solid(NEWLINE name="goodbye_config",NEWLINE notebook_path=nb_test_path("print_dagstermill_context_solid_config"),NEWLINE output_notebook_name="notebook",NEWLINE config_schema={"farewell": Field(String, is_required=False, default_value="goodbye")},NEWLINE)NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_world_config_pipeline():NEWLINE hello_world_config()NEWLINE goodbye_config()NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef alias_config_pipeline():NEWLINE hello_world_config.alias("aliased_greeting")()NEWLINE goodbye_config.alias("aliased_goodbye")()NEWLINENEWLINENEWLINE@solid(input_defs=[InputDefinition("notebook")])NEWLINEdef load_notebook(notebook):NEWLINE return notebookNEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_world_with_output_notebook_pipeline():NEWLINE notebook = hello_world()NEWLINE load_notebook(notebook)NEWLINENEWLINENEWLINEhello_world_no_output_notebook_no_file_manager = dagstermill.define_dagstermill_solid(NEWLINE name="hello_world_no_output_notebook_no_file_manager",NEWLINE notebook_path=nb_test_path("hello_world"),NEWLINE)NEWLINENEWLINENEWLINE@pipelineNEWLINEdef hello_world_no_output_notebook_no_file_manager_pipeline():NEWLINE hello_world_no_output_notebook_no_file_manager()NEWLINENEWLINENEWLINEhello_world_no_output_notebook = dagstermill.define_dagstermill_solid(NEWLINE name="hello_world_no_output_notebook",NEWLINE notebook_path=nb_test_path("hello_world"),NEWLINE)NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_world_no_output_notebook_pipeline():NEWLINE hello_world_no_output_notebook()NEWLINENEWLINENEWLINEhello_world_output = test_nb_solid("hello_world_output", output_defs=[OutputDefinition(str)])NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_world_output_pipeline():NEWLINE hello_world_output()NEWLINENEWLINENEWLINEhello_world_explicit_yield = test_nb_solid(NEWLINE "hello_world_explicit_yield", output_defs=[OutputDefinition(str)]NEWLINE)NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_world_explicit_yield_pipeline():NEWLINE hello_world_explicit_yield()NEWLINENEWLINENEWLINEhello_logging = test_nb_solid("hello_logging")NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_logging_pipeline():NEWLINE hello_logging()NEWLINENEWLINENEWLINEadd_two_numbers = test_nb_solid(NEWLINE "add_two_numbers",NEWLINE input_defs=[NEWLINE InputDefinition(name="a", dagster_type=Int),NEWLINE InputDefinition(name="b", dagster_type=Int),NEWLINE ],NEWLINE output_defs=[OutputDefinition(Int)],NEWLINE)NEWLINENEWLINENEWLINEmult_two_numbers = test_nb_solid(NEWLINE "mult_two_numbers",NEWLINE input_defs=[NEWLINE InputDefinition(name="a", dagster_type=Int),NEWLINE InputDefinition(name="b", dagster_type=Int),NEWLINE ],NEWLINE output_defs=[OutputDefinition(Int)],NEWLINE)NEWLINENEWLINENEWLINE@solidNEWLINEdef return_one():NEWLINE return 1NEWLINENEWLINENEWLINE@solidNEWLINEdef return_two():NEWLINE return 2NEWLINENEWLINENEWLINE@solidNEWLINEdef return_three():NEWLINE return 3NEWLINENEWLINENEWLINE@solidNEWLINEdef return_four():NEWLINE return 4NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef add_pipeline():NEWLINE add_two_numbers(return_one(), return_two())NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef double_add_pipeline():NEWLINE add_two_numbers.alias("add_two_numbers_1")(return_one(), return_two())NEWLINE add_two_numbers.alias("add_two_numbers_2")(return_three(), return_four())NEWLINENEWLINENEWLINE@solid(input_defs=[], config_schema=Int)NEWLINEdef load_constant(context):NEWLINE return context.solid_configNEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef notebook_dag_pipeline():NEWLINE a = load_constant.alias("load_a")()NEWLINE b = load_constant.alias("load_b")()NEWLINE num, _ = add_two_numbers(a, b)NEWLINE mult_two_numbers(num, b)NEWLINENEWLINENEWLINEerror_notebook = test_nb_solid("error_notebook")NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef error_pipeline():NEWLINE error_notebook()NEWLINENEWLINENEWLINEif DAGSTER_PANDAS_PRESENT and SKLEARN_PRESENT and MATPLOTLIB_PRESENT:NEWLINENEWLINE clean_data = test_nb_solid("clean_data", output_defs=[OutputDefinition(DataFrame)])NEWLINENEWLINE # FIXME add an output to thisNEWLINE tutorial_LR = test_nb_solid(NEWLINE "tutorial_LR",NEWLINE input_defs=[InputDefinition(name="df", dagster_type=DataFrame)],NEWLINE )NEWLINENEWLINE tutorial_RF = test_nb_solid(NEWLINE "tutorial_RF",NEWLINE input_defs=[InputDefinition(name="df", dagster_type=DataFrame)],NEWLINE )NEWLINENEWLINE @pipeline(mode_defs=default_mode_defs)NEWLINE def tutorial_pipeline():NEWLINE dfr, _ = clean_data()NEWLINE # FIXME get better names for theseNEWLINE tutorial_LR(dfr)NEWLINE tutorial_RF(dfr)NEWLINENEWLINENEWLINE@solid("resource_solid", required_resource_keys={"list"})NEWLINEdef resource_solid(context):NEWLINE context.resources.list.append("Hello, solid!")NEWLINE return TrueNEWLINENEWLINENEWLINEhello_world_resource = test_nb_solid(NEWLINE "hello_world_resource",NEWLINE input_defs=[InputDefinition("nonce")],NEWLINE required_resource_keys={"list"},NEWLINE)NEWLINENEWLINEhello_world_resource_with_exception = test_nb_solid(NEWLINE "hello_world_resource_with_exception",NEWLINE input_defs=[InputDefinition("nonce")],NEWLINE required_resource_keys={"list"},NEWLINE)NEWLINENEWLINENEWLINEclass FilePickleList:NEWLINE # This is not thread- or anything else-safeNEWLINE def __init__(self, path):NEWLINE self.closed = FalseNEWLINE self.id = str(uuid.uuid4())[-6:]NEWLINE self.path = pathNEWLINE self.list = []NEWLINE if not os.path.exists(self.path):NEWLINE self.write()NEWLINE self.read()NEWLINE self.open()NEWLINENEWLINE def open(self):NEWLINE self.read()NEWLINE self.append("Opened")NEWLINENEWLINE def append(self, obj):NEWLINE self.read()NEWLINE self.list.append(self.id + ": " + obj)NEWLINE self.write()NEWLINENEWLINE def read(self):NEWLINE with open(self.path, "rb") as fd:NEWLINE self.list = pickle.load(fd)NEWLINE return self.listNEWLINENEWLINE def write(self):NEWLINE with open(self.path, "wb") as fd:NEWLINE pickle.dump(self.list, fd, protocol=PICKLE_PROTOCOL)NEWLINENEWLINE def close(self):NEWLINE self.append("Closed")NEWLINE self.closed = TrueNEWLINENEWLINENEWLINE@resource(config_schema=Field(String))NEWLINEdef filepicklelist_resource(init_context):NEWLINE filepicklelist = FilePickleList(init_context.resource_config)NEWLINE try:NEWLINE yield filepicklelistNEWLINE finally:NEWLINE filepicklelist.close()NEWLINENEWLINENEWLINE@pipeline(NEWLINE mode_defs=[NEWLINE ModeDefinition(NEWLINE name="test",NEWLINE resource_defs={NEWLINE "list": ResourceDefinition(lambda _: []),NEWLINE "io_manager": fs_io_manager,NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE },NEWLINE ),NEWLINE ModeDefinition(NEWLINE name="prod",NEWLINE resource_defs={NEWLINE "list": filepicklelist_resource,NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE "io_manager": fs_io_manager,NEWLINE },NEWLINE ),NEWLINE ]NEWLINE)NEWLINEdef resource_pipeline():NEWLINE hello_world_resource(resource_solid())NEWLINENEWLINENEWLINE@pipeline(NEWLINE mode_defs=[NEWLINE ModeDefinition(NEWLINE resource_defs={NEWLINE "list": filepicklelist_resource,NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE "io_manager": fs_io_manager,NEWLINE }NEWLINE )NEWLINE ]NEWLINE)NEWLINEdef resource_with_exception_pipeline():NEWLINE hello_world_resource_with_exception(resource_solid())NEWLINENEWLINENEWLINEbad_kernel = test_nb_solid("bad_kernel")NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef bad_kernel_pipeline():NEWLINE bad_kernel()NEWLINENEWLINENEWLINEreimport = test_nb_solid(NEWLINE "reimport", input_defs=[InputDefinition("l", List[int])], output_defs=[OutputDefinition(int)]NEWLINE)NEWLINENEWLINENEWLINE@solidNEWLINEdef lister():NEWLINE return [1, 2, 3]NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef reimport_pipeline():NEWLINE reimport(lister())NEWLINENEWLINENEWLINEyield_3 = test_nb_solid("yield_3", output_defs=[OutputDefinition(Int)])NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef yield_3_pipeline():NEWLINE yield_3()NEWLINENEWLINENEWLINEyield_obj = test_nb_solid("yield_obj")NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef yield_obj_pipeline():NEWLINE yield_obj()NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef retries_pipeline():NEWLINE test_nb_solid("raise_retry")()NEWLINE test_nb_solid("yield_retry")()NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef failure_pipeline():NEWLINE test_nb_solid("raise_failure")()NEWLINE test_nb_solid("yield_failure")()NEWLINENEWLINENEWLINEyield_something = test_nb_solid(NEWLINE "yield_something",NEWLINE input_defs=[InputDefinition("obj", str)],NEWLINE output_defs=[OutputDefinition(str, "result")],NEWLINE)NEWLINENEWLINENEWLINE@solidNEWLINEdef fan_in(a, b):NEWLINE return f"{a} {b}"NEWLINENEWLINENEWLINE@pipeline(NEWLINE mode_defs=[NEWLINE ModeDefinition(NEWLINE resource_defs={NEWLINE "io_manager": fs_io_manager,NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE }NEWLINE )NEWLINE ]NEWLINE)NEWLINEdef fan_in_notebook_pipeline():NEWLINE val_a, _ = yield_something.alias("solid_1")()NEWLINE val_b, _ = yield_something.alias("solid_2")()NEWLINE fan_in(val_a, val_b)NEWLINENEWLINENEWLINE@pipeline(NEWLINE mode_defs=[NEWLINE ModeDefinition(NEWLINE resource_defs={NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE }NEWLINE )NEWLINE ]NEWLINE)NEWLINEdef fan_in_notebook_pipeline_in_mem():NEWLINE val_a, _ = yield_something.alias("solid_1")()NEWLINE val_b, _ = yield_something.alias("solid_2")()NEWLINE fan_in(val_a, val_b)NEWLINENEWLINENEWLINE@composite_solidNEWLINEdef outer():NEWLINE yield_something()NEWLINENEWLINENEWLINE@pipeline(NEWLINE mode_defs=[NEWLINE ModeDefinition(NEWLINE resource_defs={NEWLINE "io_manager": fs_io_manager,NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE }NEWLINE )NEWLINE ]NEWLINE)NEWLINEdef composite_pipeline():NEWLINE outer()NEWLINENEWLINENEWLINE###################################################################################################NEWLINE# Back compatNEWLINE###################################################################################################NEWLINENEWLINEhello_world_legacy = dagstermill.define_dagstermill_solid(NEWLINE name="hello_world_legacy",NEWLINE notebook_path=nb_test_path("hello_world"),NEWLINE output_notebook="notebook",NEWLINE)NEWLINENEWLINENEWLINE@solid(input_defs=[InputDefinition("notebook", dagster_type=FileHandle)])NEWLINEdef load_notebook_legacy(notebook):NEWLINE return os.path.exists(notebook.path_desc)NEWLINENEWLINENEWLINE@pipeline(NEWLINE mode_defs=[NEWLINE ModeDefinition(NEWLINE resource_defs={NEWLINE "io_manager": fs_io_manager,NEWLINE "file_manager": local_file_manager,NEWLINE }NEWLINE )NEWLINE ]NEWLINE)NEWLINEdef hello_world_with_output_notebook_pipeline_legacy():NEWLINE notebook = hello_world_legacy()NEWLINE load_notebook_legacy(notebook)NEWLINENEWLINENEWLINE@repositoryNEWLINEdef notebook_repo():NEWLINE pipelines = [NEWLINE bad_kernel_pipeline,NEWLINE error_pipeline,NEWLINE hello_world_pipeline,NEWLINE hello_world_with_custom_tags_and_description_pipeline,NEWLINE hello_world_config_pipeline,NEWLINE hello_world_explicit_yield_pipeline,NEWLINE hello_world_output_pipeline,NEWLINE hello_world_with_output_notebook_pipeline,NEWLINE hello_logging_pipeline,NEWLINE resource_pipeline,NEWLINE resource_with_exception_pipeline,NEWLINE add_pipeline,NEWLINE notebook_dag_pipeline,NEWLINE reimport_pipeline,NEWLINE yield_3_pipeline,NEWLINE yield_obj_pipeline,NEWLINE retries_pipeline,NEWLINE failure_pipeline,NEWLINE fan_in_notebook_pipeline_in_mem,NEWLINE fan_in_notebook_pipeline,NEWLINE hello_world_no_output_notebook_no_file_manager_pipeline,NEWLINE hello_world_with_output_notebook_pipeline_legacy,NEWLINE ]NEWLINE if DAGSTER_PANDAS_PRESENT and SKLEARN_PRESENT and MATPLOTLIB_PRESENT:NEWLINE pipelines += [tutorial_pipeline]NEWLINENEWLINE return pipelinesNEWLINE # -*- coding: utf-8 -*-NEWLINE"""NEWLINETests for the Py2-like class:`basestring` type.NEWLINE"""NEWLINENEWLINEfrom __future__ import absolute_import, unicode_literals, print_functionNEWLINEimport osNEWLINENEWLINEfrom past import utilsNEWLINEfrom future.tests.base import unittestNEWLINEfrom past.builtins import basestring, str as oldstrNEWLINENEWLINENEWLINEclass TestBaseString(unittest.TestCase):NEWLINENEWLINE def test_isinstance(self):NEWLINE s = b'abc'NEWLINE self.assertTrue(isinstance(s, basestring))NEWLINE s2 = oldstr(b'abc')NEWLINE self.assertTrue(isinstance(s2, basestring))NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE unittest.main()NEWLINE from django.core.files.base import ContentFileNEWLINENEWLINEfrom readable.models import DocumentsNEWLINENEWLINEfrom .utils import TestCaseNEWLINENEWLINENEWLINEclass TestDocuments(TestCase):NEWLINE def setUp(self) -> None:NEWLINE super(TestDocuments, self).setUp()NEWLINE self.user = self.create_user("staff", self.get_random_string())NEWLINE self.staff = self.create_staff(self.user)NEWLINE self.lorem = ContentFile("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "lorem.txt")NEWLINENEWLINE def test_upload_directory(self) -> None:NEWLINE document: Documents = Documents.objects.create(filename=self.lorem, uploaded_by=self.staff)NEWLINE self.assertEqual(document.realname, self.lorem.name)NEWLINE self.assertEqual(document.filename, f"{document.id!s}{document.path.suffix}")NEWLINENEWLINE self.assertTrue(document.unavailable)NEWLINE document.status = Documents.Status.FINISHEDNEWLINE document.save(update_fields=["status"])NEWLINE self.assertFalse(document.unavailable)NEWLINE # coding=utf-8NEWLINE# Copyright 2020 The HuggingFace NLP Authors.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE""" BLEU metric. """NEWLINENEWLINEimport nlpNEWLINENEWLINEfrom .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.pyNEWLINENEWLINENEWLINE_CITATION = """\NEWLINE@INPROCEEDINGS{Papineni02bleu:a,NEWLINE author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},NEWLINE title = {BLEU: a Method for Automatic Evaluation of Machine Translation},NEWLINE booktitle = {},NEWLINE year = {2002},NEWLINE pages = {311--318}NEWLINE}NEWLINE@inproceedings{lin-och-2004-orange,NEWLINE title = "{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation",NEWLINE author = "Lin, Chin-Yew andNEWLINE Och, Franz Josef",NEWLINE booktitle = "{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics",NEWLINE month = "aug 23{--}aug 27",NEWLINE year = "2004",NEWLINE address = "Geneva, Switzerland",NEWLINE publisher = "COLING",NEWLINE url = "https://www.aclweb.org/anthology/C04-1072",NEWLINE pages = "501--507",NEWLINE}NEWLINE"""NEWLINENEWLINE_DESCRIPTION = """\NEWLINEBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.NEWLINEQuality is considered to be the correspondence between a machine's output and that of a human: "the closer a machine translation is to a professional human translation,NEWLINEthe better it is" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, andNEWLINEremains one of the most popular automated and inexpensive metrics.NEWLINENEWLINEScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.NEWLINEThose scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctnessNEWLINEare not taken into account[citation needed].NEWLINENEWLINEBLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1NEWLINErepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of theNEWLINEreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additionalNEWLINEreference translations will increase the BLEU score.NEWLINE"""NEWLINENEWLINE_KWARGS_DESCRIPTION = """NEWLINEComputes BLEU score of translated segments against one or more references.NEWLINEArgs:NEWLINE predictions: list of translations to score.NEWLINE Each translation should be tokenized into a list of tokens.NEWLINE references: list of lists of references for each translation.NEWLINE Each reference should be tokenized into a list of tokens.NEWLINE max_order: Maximum n-gram order to use when computing BLEU score.NEWLINE smooth: Whether or not to apply Lin et al. 2004 smoothing.NEWLINEReturns:NEWLINE 'bleu': bleu score,NEWLINE 'precisions': geometric mean of n-gram precisions,NEWLINE 'brevity_penalty': brevity penalty,NEWLINE 'length_ratio': ratio of lengths,NEWLINE 'translation_length': translation_length,NEWLINE 'reference_length': reference_lengthNEWLINE"""NEWLINENEWLINEclass Bleu(nlp.Metric):NEWLINE def _info(self):NEWLINE return nlp.MetricInfo(NEWLINE description=_DESCRIPTION,NEWLINE citation=_CITATION,NEWLINE inputs_description=_KWARGS_DESCRIPTION,NEWLINE features=nlp.Features({NEWLINE 'predictions': nlp.Sequence(nlp.Value('string', id='token'), id='sequence'),NEWLINE 'references': nlp.Sequence(nlp.Sequence(nlp.Value('string', id='token'), id='sequence'), id='references'),NEWLINE }),NEWLINE codebase_urls=["https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py"],NEWLINE reference_urls=["https://en.wikipedia.org/wiki/BLEU",NEWLINE "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213"]NEWLINE )NEWLINENEWLINE def _compute(self, predictions, references, max_order=4, smooth=False):NEWLINE score = compute_bleu(reference_corpus=references, translation_corpus=predictions, max_order=max_order, smooth=smooth)NEWLINE (bleu, precisions, bp, ratio, translation_length, reference_length) = scoreNEWLINE return {'bleu': bleu,NEWLINE 'precisions': precisions,NEWLINE 'brevity_penalty': bp,NEWLINE 'length_ratio': ratio,NEWLINE 'translation_length': translation_length,NEWLINE 'reference_length': reference_length}NEWLINE import rlkit.misc.hyperparameter as hypNEWLINEfrom rlkit.demos.source.dict_to_mdp_path_loader import EncoderDictToMDPPathLoaderNEWLINEfrom rlkit.launchers.experiments.ashvin.awac_rig import awac_rig_experimentNEWLINEfrom rlkit.launchers.launcher_util import run_experimentNEWLINEfrom rlkit.launchers.arglauncher import run_variantsNEWLINEfrom rlkit.torch.sac.policies import GaussianPolicy, GaussianMixturePolicyNEWLINEfrom rlkit.envs.encoder_wrappers import ConditionalEncoderWrappedEnvNEWLINEfrom sawyer_control.envs.sawyer_grip import SawyerGripEnvNEWLINE#from sawyer_control.envs.sawyer_grip_stub import SawyerGripEnvNEWLINEfrom rlkit.torch.networks import ClampNEWLINEfrom rlkit.torch.vae.vq_vae import VQ_VAENEWLINEfrom rlkit.torch.vae.vq_vae_trainer import VQ_VAETrainerNEWLINEfrom rlkit.torch.grill.common import train_vqvaeNEWLINENEWLINEpath_func = lambda name: '/media/ashvin/data2/data/baseline/'+ nameNEWLINENEWLINEall_demos = [NEWLINE dict(path=path_func('fixed_drawer_demos.npy'), obs_dict=True, is_demo=True, data_split=0.2),NEWLINE dict(path=path_func('fixed_pot_demos.npy'), obs_dict=True, is_demo=True, data_split=0.2),NEWLINE dict(path=path_func('fixed_pot_extra1_demos.npy'), obs_dict=True, is_demo=True, data_split=0.2),NEWLINE dict(path=path_func('fixed_pnp_demos.npy'), obs_dict=True, is_demo=True, data_split=0.2),NEWLINE dict(path=path_func('fixed_tray_demos.npy'), obs_dict=True, is_demo=True, data_split=0.2),NEWLINE]NEWLINENEWLINENEWLINEall_demos = [NEWLINE dict(path=path_func('fixed_drawer_demos.npy'), obs_dict=True, is_demo=True,),NEWLINE dict(path=path_func('fixed_pot_demos.npy'), obs_dict=True, is_demo=True,),NEWLINE dict(path=path_func('fixed_pot_extra1_demos.npy'), obs_dict=True, is_demo=True,),NEWLINE dict(path=path_func('fixed_pnp_demos.npy'), obs_dict=True, is_demo=True,),NEWLINE dict(path=path_func('fixed_tray_demos.npy'), obs_dict=True, is_demo=True,),NEWLINE]NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE variant = dict(NEWLINE imsize=48,NEWLINE env_class=SawyerGripEnv,NEWLINE env_kwargs=dict(NEWLINE action_mode='position',NEWLINE config_name='ashvin_config',NEWLINE reset_free=False,NEWLINE position_action_scale=0.05,NEWLINE max_speed=0.4,NEWLINE step_sleep_time=0.2,NEWLINE crop_version_str="crop_val_torch",NEWLINE ),NEWLINE policy_class=GaussianPolicy,NEWLINE policy_kwargs=dict(NEWLINE hidden_sizes=[256, 256, 256, 256, ],NEWLINE max_log_std=0,NEWLINE min_log_std=-6,NEWLINE std_architecture="values",NEWLINE ),NEWLINENEWLINE qf_kwargs=dict(NEWLINE hidden_sizes=[256, 256],NEWLINE ),NEWLINENEWLINE trainer_kwargs=dict(NEWLINE discount=0.99,NEWLINE soft_target_tau=5e-3,NEWLINE target_update_period=1,NEWLINE policy_lr=3e-4,NEWLINE qf_lr=3E-4,NEWLINE reward_scale=1,NEWLINE beta=1,NEWLINE use_automatic_entropy_tuning=False,NEWLINE alpha=0,NEWLINENEWLINE bc_num_pretrain_steps=0,NEWLINE q_num_pretrain1_steps=0,NEWLINE q_num_pretrain2_steps=25001, #25001 #HERENEWLINE policy_weight_decay=1e-4,NEWLINE q_weight_decay=0,NEWLINENEWLINE rl_weight=1.0,NEWLINE use_awr_update=True,NEWLINE use_reparam_update=False,NEWLINE compute_bc=True,NEWLINE reparam_weight=0.0,NEWLINE awr_weight=1.0,NEWLINE bc_weight=0.0,NEWLINENEWLINE reward_transform_kwargs=None,NEWLINE terminal_transform_kwargs=None,NEWLINE ),NEWLINENEWLINE max_path_length=75, #50NEWLINE algo_kwargs=dict(NEWLINE batch_size=1024, #1024NEWLINE num_epochs=101, #1001NEWLINE num_eval_steps_per_epoch=150, #500NEWLINE num_expl_steps_per_train_loop=600, #500NEWLINE num_trains_per_train_loop=600, #500NEWLINE min_num_steps_before_training=150, #4000NEWLINE ),NEWLINE replay_buffer_kwargs=dict(NEWLINE fraction_future_context=0.6,NEWLINE fraction_distribution_context=0.1, # TODO: Try less?NEWLINE max_size=int(5E5), # HERE# HERE# HERE# HERE# HERE# HERE# HERE# HERE# HERE (DOUBLE CHECK THAT DEMOS FIT!!!!)NEWLINE ),NEWLINE demo_replay_buffer_kwargs=dict(NEWLINE fraction_future_context=0.6,NEWLINE fraction_distribution_context=0.1, # TODO: Try less?NEWLINE ),NEWLINE reward_kwargs=dict(NEWLINE reward_type='sparse',NEWLINE epsilon=1.0,NEWLINE ),NEWLINENEWLINE observation_key='latent_observation',NEWLINE desired_goal_key='latent_desired_goal',NEWLINE save_video=True,NEWLINE save_video_kwargs=dict(NEWLINE save_video_period=1,NEWLINE pad_color=0,NEWLINE ),NEWLINE NEWLINE encoder_wrapper=ConditionalEncoderWrappedEnv,NEWLINE reset_keys_map=dict(NEWLINE image_observation="initial_latent_state"NEWLINE ),NEWLINENEWLINE path_loader_class=EncoderDictToMDPPathLoader,NEWLINE path_loader_kwargs=dict(NEWLINE recompute_reward=True,NEWLINE ),NEWLINENEWLINE renderer_kwargs=dict(NEWLINE create_image_format='HWC',NEWLINE output_image_format='CWH',NEWLINE flatten_image=True,NEWLINE width=48,NEWLINE height=48,NEWLINE ),NEWLINENEWLINE add_env_demos=False,NEWLINE add_env_offpolicy_data=False,NEWLINENEWLINE load_demos=True,NEWLINE pretrain_policy=True,NEWLINE pretrain_rl=True,NEWLINENEWLINE evaluation_goal_sampling_mode="presampled_images",NEWLINE exploration_goal_sampling_mode="conditional_vae_prior",NEWLINE train_vae_kwargs=dict(NEWLINE imsize=48,NEWLINE beta=1,NEWLINE beta_schedule_kwargs=dict(NEWLINE x_values=(0, 250),NEWLINE y_values=(0, 100),NEWLINE ),NEWLINE num_epochs=1501, #1501NEWLINE embedding_dim=5,NEWLINE dump_skew_debug_plots=False,NEWLINE decoder_activation='sigmoid',NEWLINE use_linear_dynamics=False,NEWLINE generate_vae_dataset_kwargs=dict(NEWLINE N=1000,NEWLINE n_random_steps=2,NEWLINE test_p=.9,NEWLINE dataset_path={NEWLINE 'train': 'demos/icra2021/dataset_v1_train.npy',NEWLINE 'test': 'demos/icra2021/dataset_v1_test.npy',NEWLINE },NEWLINE augment_data=False,NEWLINE use_cached=False,NEWLINE show=False,NEWLINE oracle_dataset=False,NEWLINE oracle_dataset_using_set_to_goal=False,NEWLINE non_presampled_goal_img_is_garbage=False,NEWLINE random_rollout_data=True,NEWLINE random_rollout_data_set_to_goal=True,NEWLINE conditional_vae_dataset=True,NEWLINE save_trajectories=False,NEWLINE enviorment_dataset=False,NEWLINE tag="ccrig_tuning_orig_network",NEWLINE ),NEWLINE vae_trainer_class=VQ_VAETrainer,NEWLINE vae_class=VQ_VAE,NEWLINE vae_kwargs=dict(NEWLINE input_channels=3,NEWLINE imsize=48,NEWLINE ),NEWLINE algo_kwargs=dict(NEWLINE key_to_reconstruct='x_t',NEWLINE start_skew_epoch=5000,NEWLINE is_auto_encoder=False,NEWLINE batch_size=128,NEWLINE lr=1e-3,NEWLINE skew_config=dict(NEWLINE method='vae_prob',NEWLINE power=0,NEWLINE ),NEWLINE weight_decay=0.0,NEWLINE skew_dataset=False,NEWLINE priority_function_kwargs=dict(NEWLINE decoder_distribution='gaussian_identity_variance',NEWLINE sampling_method='importance_sampling',NEWLINE num_latents_to_sample=10,NEWLINE ),NEWLINE use_parallel_dataloading=False,NEWLINE ),NEWLINENEWLINE save_period=10,NEWLINE ),NEWLINE train_model_func=train_vqvae,NEWLINENEWLINE presampled_goal_kwargs=dict(NEWLINE eval_goals='/media/ashvin/data2/data/val/v1/ccvae_pot1_eval_goals.pkl',NEWLINE expl_goals=None,NEWLINE ),NEWLINE launcher_config=dict(NEWLINE unpack_variant=True,NEWLINE region='us-west-1',NEWLINE ),NEWLINE logger_config=dict(NEWLINE snapshot_mode='gap',NEWLINE snapshot_gap=1,NEWLINE ),NEWLINE ccvae_or_cbigan_exp=True,NEWLINE pickle_paths=True,NEWLINE NEWLINE pretrained_vae_path=path_func('vae.pt'),NEWLINE pretrained_algo_path=path_func('agent_sparse_1.pt'), #agent_sparse_1.pt, agent_sparse_2.pt, agent_dense.ptNEWLINE )NEWLINENEWLINE search_space = {NEWLINE "seed": range(1),NEWLINE 'path_loader_kwargs.demo_paths': [all_demos], #CHANGEDNEWLINENEWLINE 'reward_kwargs.reward_type': ['sparse',], # TRY SPARSE (EPS=1), SPARSE (EPS=2), DENSE (PROB NOT GONNA WORK)NEWLINE 'trainer_kwargs.beta': [0.3],NEWLINE 'num_pybullet_objects':[None],NEWLINENEWLINE 'policy_kwargs.min_log_std': [-6],NEWLINE 'trainer_kwargs.awr_weight': [1.0],NEWLINE 'trainer_kwargs.awr_use_mle_for_vf': [True],NEWLINE 'trainer_kwargs.awr_sample_actions': [False],NEWLINE 'trainer_kwargs.clip_score': [2],NEWLINE 'trainer_kwargs.awr_min_q': [True],NEWLINE 'trainer_kwargs.reward_transform_kwargs': [None, ],NEWLINE 'trainer_kwargs.terminal_transform_kwargs': [dict(m=0, b=0)],NEWLINE #'qf_kwargs.output_activation': [Clamp(max=0)],NEWLINE }NEWLINE sweeper = hyp.DeterministicHyperparameterSweeper(NEWLINE search_space, default_parameters=variant,NEWLINE )NEWLINENEWLINE variants = []NEWLINE for variant in sweeper.iterate_hyperparameters():NEWLINE if 'sparse' in variant['pretrained_algo_path']:NEWLINE variant['qf_kwargs']['output_activation'] = Clamp(max=0)NEWLINENEWLINE if variant['pretrained_algo_path'] == path_func('agent_sparse_1.pt'):NEWLINE variant['reward_kwargs'] == dict(reward_type='sparse', epsilon=1.0)NEWLINE if variant['pretrained_algo_path'] == path_func('agent_sparse_2.pt'):NEWLINE variant['reward_kwargs'] == dict(reward_type='sparse', epsilon=2.0)NEWLINE if variant['pretrained_algo_path'] == path_func('agent_dense.pt'):NEWLINE variant['reward_kwargs'] == dict(reward_type='dense', epsilon=1.0)NEWLINE NEWLINE variants.append(variant)NEWLINENEWLINE run_variants(awac_rig_experiment, variants, run_id=10) #HERENEWLINE # -*- coding: utf-8 -*-NEWLINENEWLINE# Form implementation generated from reading ui file '/media/raul/OS/Users/king_/Desktop/carrera/curso2018-2019/2oCuatri/TFG/gui_dbjudge/sql_judge/view/qt_view/custom_types/custom_type_row.ui'NEWLINE#NEWLINE# Created by: PyQt5 UI code generator 5.13.2NEWLINE#NEWLINE# WARNING! All changes made in this file will be lost!NEWLINENEWLINENEWLINEfrom PyQt5 import QtCore, QtGui, QtWidgetsNEWLINENEWLINENEWLINEclass Ui_Form(object):NEWLINE def setupUi(self, CustomTypeRow):NEWLINE CustomTypeRow.setObjectName("CustomTypeRow")NEWLINE CustomTypeRow.setGeometry(QtCore.QRect(0, 0, 195, 61))NEWLINE sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)NEWLINE sizePolicy.setHorizontalStretch(0)NEWLINE sizePolicy.setVerticalStretch(0)NEWLINE sizePolicy.setHeightForWidth(CustomTypeRow.sizePolicy().hasHeightForWidth())NEWLINE CustomTypeRow.setSizePolicy(sizePolicy)NEWLINE self.horizontalLayout_2 = QtWidgets.QHBoxLayout(CustomTypeRow)NEWLINE self.horizontalLayout_2.setObjectName("horizontalLayout_2")NEWLINE self.horizontalLayout = QtWidgets.QHBoxLayout()NEWLINE self.horizontalLayout.setObjectName("horizontalLayout")NEWLINE self.data_label = QtWidgets.QLabel(CustomTypeRow)NEWLINE self.data_label.setObjectName("data_label")NEWLINE self.horizontalLayout.addWidget(self.data_label)NEWLINE spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)NEWLINE self.horizontalLayout.addItem(spacerItem)NEWLINE self.delete_sample_button = QtWidgets.QPushButton(CustomTypeRow)NEWLINE self.delete_sample_button.setText("")NEWLINE icon = QtGui.QIcon()NEWLINE icon.addPixmap(QtGui.QPixmap(":/icons/trash-26.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)NEWLINE self.delete_sample_button.setIcon(icon)NEWLINE self.delete_sample_button.setObjectName("delete_sample_button")NEWLINE self.horizontalLayout.addWidget(self.delete_sample_button)NEWLINE self.horizontalLayout_2.addLayout(self.horizontalLayout)NEWLINENEWLINE self.retranslateUi(CustomTypeRow)NEWLINE QtCore.QMetaObject.connectSlotsByName(CustomTypeRow)NEWLINENEWLINE def retranslateUi(self, CustomTypeRow):NEWLINE _translate = QtCore.QCoreApplication.translateNEWLINE CustomTypeRow.setWindowTitle(_translate("Form", "Form"))NEWLINE self.data_label.setText(_translate("Form", "data"))NEWLINEfrom . import resourcesNEWLINE """This module contains miscellaneous utilities."""NEWLINENEWLINE__author__ = "Damián Silvani"NEWLINE__copyright__ = "Dymaxion Labs"NEWLINE__license__ = "MIT"NEWLINENEWLINENEWLINEdef flatten(list):NEWLINE return [item for sublist in list for item in sublist]NEWLINE import argparseNEWLINEimport torchNEWLINEimport numpy as npNEWLINEimport osNEWLINEimport pickleNEWLINEfrom post_process.kcenter_greedy import kCenterGreedyNEWLINEfrom sklearn.random_projection import SparseRandomProjectionNEWLINENEWLINEfrom data_loader.one_class_dataset import get_train_dataloaderNEWLINEfrom model.one_class.models import STPMNEWLINEfrom inference import OneClassInferenceNEWLINEfrom utils import reshape_embeddingNEWLINENEWLINENEWLINEclass OneClassTest():NEWLINE def __init__(self, args):NEWLINE self.embedding_dir_path = "./embeddings"NEWLINE if not os.path.exists(self.embedding_dir_path):NEWLINE os.mkdir(self.embedding_dir_path)NEWLINENEWLINE self.embedding_list = []NEWLINE self.train_loader = get_train_dataloader(args.dataset_path, args.load_size, args.input_size, args.batch_size)NEWLINE self.model = STPM()NEWLINE self.model.eval()NEWLINE self.inference = OneClassInference(args)NEWLINENEWLINE def test(self):NEWLINE for index, batch_data in enumerate(self.train_loader):NEWLINE prediction = self.inference.infer(batch_data)NEWLINE self.embedding_list.extend(reshape_embedding(np.array(prediction)))NEWLINE self.computer_embedding()NEWLINENEWLINE def computer_embedding(self):NEWLINE total_embeddings = np.array(self.embedding_list)NEWLINE # Random projectionNEWLINE randomprojector = SparseRandomProjection(n_components='auto',NEWLINE eps=0.9) # 'auto' => Johnson-Lindenstrauss lemmaNEWLINE randomprojector.fit(total_embeddings)NEWLINE # Coreset SubsamplingNEWLINE selector = kCenterGreedy(total_embeddings, 0, 0)NEWLINE selected_idx = selector.select_batch(model=randomprojector, already_selected=[],NEWLINE N=int(total_embeddings.shape[0] * float(args.coreset_sampling_ratio)))NEWLINE self.embedding_coreset = total_embeddings[selected_idx]NEWLINENEWLINE print('initial embedding size : ', total_embeddings.shape)NEWLINE print('final embedding size : ', self.embedding_coreset.shape)NEWLINE with open(os.path.join(self.embedding_dir_path, 'embedding.pickle'), 'wb') as f:NEWLINE pickle.dump(self.embedding_coreset, f)NEWLINENEWLINENEWLINEdef get_args():NEWLINE parser = argparse.ArgumentParser(description='ANOMALYDETECTION')NEWLINE parser.add_argument('--dataset_path',NEWLINE default=r'/home/changwoo/hdd/datasets/mvtec_anomaly_detection') # 'D:\Dataset\mvtec_anomaly_detection')#NEWLINE parser.add_argument('--batch_size', default=32)NEWLINE parser.add_argument('--load_size', default=256) # 256NEWLINE parser.add_argument('--input_size', default=224)NEWLINE parser.add_argument('--coreset_sampling_ratio', default=0.01)NEWLINE parser.add_argument('--project_root_path',NEWLINE default=r'/home/changwoo/hdd/project_results/patchcore/test')NEWLINE parser.add_argument('--method', default=r'NN')NEWLINE parser.add_argument('--n_neighbors', type=int, default=9)NEWLINE args = parser.parse_args()NEWLINE return argsNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE device = torch.device("cuda" if torch.cuda.is_available() else "cpu")NEWLINE args = get_args()NEWLINENEWLINE one_class_test = OneClassTest(args)NEWLINE one_class_test.test()NEWLINE # -*- coding: utf-8 -*-NEWLINE#NEWLINE# Copyright (C) 2021 Graz University of Technology.NEWLINE# Copyright (C) 2021 CERN.NEWLINE# Copyright (C) 2021 TU Wien.NEWLINE#NEWLINE# Invenio-Records-Permissions is free software; you can redistribute itNEWLINE# and/or modify it under the terms of the MIT License; see LICENSE file forNEWLINE# more details.NEWLINENEWLINE"""Pytest configuration.NEWLINENEWLINESee https://pytest-invenio.readthedocs.io/ for documentation on which testNEWLINEfixtures are available.NEWLINE"""NEWLINENEWLINEfrom typing import PatternNEWLINENEWLINEimport pytestNEWLINEfrom flask_principal import Identity, UserNeedNEWLINEfrom invenio_access.permissions import any_user, authenticated_user, \NEWLINE system_processNEWLINEfrom invenio_db import dbNEWLINEfrom invenio_pidstore.models import PersistentIdentifier, PIDStatusNEWLINEfrom invenio_records_permissions.generators import AnyUser, \NEWLINE AuthenticatedUser, SystemProcessNEWLINENEWLINEfrom invenio_rdm_records.records import RDMParent, RDMRecordNEWLINEfrom invenio_rdm_records.services.generators import IfRestricted, RecordOwnersNEWLINENEWLINENEWLINEdef _public_record():NEWLINE record = RDMRecord({}, access={})NEWLINE record.access.protection.set("public", "public")NEWLINE return recordNEWLINENEWLINENEWLINEdef _restricted_record():NEWLINE record = RDMRecord({}, access={})NEWLINE record.access.protection.set("restricted", "restricted")NEWLINE return recordNEWLINENEWLINENEWLINEdef _owned_record():NEWLINE parent = RDMParent.create({})NEWLINE parent.access.owners.add({"user": 16})NEWLINE parent.access.owners.add({"user": 17})NEWLINE record = RDMRecord.create({}, parent=parent)NEWLINE return recordNEWLINENEWLINENEWLINEdef _then_needs():NEWLINE return {authenticated_user, system_process}NEWLINENEWLINENEWLINEdef _else_needs():NEWLINE return {any_user, system_process}NEWLINENEWLINENEWLINE#NEWLINE# TestsNEWLINE#NEWLINE@pytest.mark.parametrize(NEWLINE "field,record_fun,expected_needs_fun", [NEWLINE ("record", _public_record, _else_needs),NEWLINE ("record", _restricted_record, _then_needs),NEWLINE ("files", _public_record, _else_needs),NEWLINE ("files", _restricted_record, _then_needs),NEWLINE ]NEWLINE)NEWLINEdef test_ifrestricted_needs(field, record_fun, expected_needs_fun):NEWLINE """Test the IfRestricted generator."""NEWLINE generator = IfRestricted(NEWLINE field,NEWLINE then_=[AuthenticatedUser(), SystemProcess()],NEWLINE else_=[AnyUser(), SystemProcess()]NEWLINE )NEWLINE assert generator.needs(record=record_fun()) == expected_needs_fun()NEWLINE assert generator.excludes(record=record_fun()) == set()NEWLINENEWLINENEWLINEdef test_ifrestricted_query():NEWLINE """Test the query generation."""NEWLINE generator = IfRestricted(NEWLINE "record",NEWLINE then_=[AuthenticatedUser()],NEWLINE else_=[AnyUser()]NEWLINE )NEWLINE assert generator.query_filter(identity=any_user).to_dict() == {NEWLINE 'bool': {NEWLINE 'should': [NEWLINE {'match': {'access.record': 'restricted'}},NEWLINE {'match': {'access.record': 'public'}}NEWLINE ]NEWLINE }NEWLINE }NEWLINENEWLINENEWLINEdef test_record_owner(app, mocker):NEWLINE generator = RecordOwners()NEWLINE record = _owned_record()NEWLINENEWLINE assert generator.needs(record=record) == [NEWLINE UserNeed(16),NEWLINE UserNeed(17),NEWLINE ]NEWLINENEWLINE assert generator.excludes(record=record) == []NEWLINENEWLINE # Anonymous identity.NEWLINE assert not generator.query_filter(identity=mocker.Mock(provides=[]))NEWLINENEWLINE # Authenticated identityNEWLINE query_filter = generator.query_filter(NEWLINE identity=mocker.Mock(NEWLINE provides=[mocker.Mock(method='id', value=15)]NEWLINE )NEWLINE )NEWLINENEWLINE expected_query_filter = {NEWLINE "terms": {NEWLINE "parent.access.owned_by.user": [15]NEWLINE }NEWLINE }NEWLINE assert query_filter.to_dict() == expected_query_filterNEWLINE import sys, os, reNEWLINEimport timeNEWLINENEWLINEsys.path.append("lib")NEWLINEimport utilsNEWLINENEWLINEimport requestsNEWLINEfrom bs4 import BeautifulSoupNEWLINENEWLINEtail_number_records = utils.read_json_lines_file('data/tail_numbers.jsonl')NEWLINENEWLINEaircraft_records = []NEWLINE# Loop through the tail numbers, fetchingNEWLINEfor tail_number_record in tail_number_records:NEWLINE time.sleep(0.1) # essential to sleep FIRST in loop or you will flood sitesNEWLINE NEWLINE # Parameterize the URL with the tail numberNEWLINE BASE_URL = 'http://registry.faa.gov/aircraftinquiry/NNum_Results.aspx?NNumbertxt={}'NEWLINE tail_number = tail_number_record['TailNum']NEWLINE url = BASE_URL.format(tail_number)NEWLINENEWLINE # Fetch the page, parse the HTMLNEWLINE r = requests.get(url)NEWLINE NEWLINE html = r.textNEWLINE soup = BeautifulSoup(html)NEWLINE NEWLINE # The table structure is constant for all pages that contain dataNEWLINE try:NEWLINE aircraft_description = soup.find_all('table')[4]NEWLINE craft_tds = aircraft_description.find_all('td')NEWLINE serial_number = craft_tds[1].text.strip()NEWLINE manufacturer = craft_tds[5].text.strip()NEWLINE model = craft_tds[9].text.strip()NEWLINE mfr_year = craft_tds[25].text.strip()NEWLINENEWLINE registered_owner = soup.find_all('table')[5]NEWLINE reg_tds = registered_owner.find_all('td')NEWLINE owner = reg_tds[1].text.strip()NEWLINE owner_state = reg_tds[9].text.strip()NEWLINENEWLINE airworthiness = soup.find_all('table')[6]NEWLINE worthy_tds = airworthiness.find_all('td')NEWLINE engine_manufacturer = worthy_tds[1].text.strip()NEWLINE engine_model = worthy_tds[5].text.strip()NEWLINENEWLINE aircraft_record = {NEWLINE 'TailNum': tail_number,NEWLINE 'serial_number': serial_number,NEWLINE 'manufacturer': manufacturer,NEWLINE 'model': model,NEWLINE 'mfr_year': mfr_year,NEWLINE 'owner': owner,NEWLINE 'owner_state': owner_state,NEWLINE 'engine_manufacturer': engine_manufacturer,NEWLINE 'engine_model': engine_model,NEWLINE }NEWLINE aircraft_records.append(NEWLINE aircraft_recordNEWLINE )NEWLINE print(aircraft_record)NEWLINE NEWLINE except IndexError as e:NEWLINE print("Missing {} record: {}".format(tail_number, e))NEWLINENEWLINEutils.write_json_lines_file(NEWLINE aircraft_records, 'data/faa_tail_number_inquiry.jsonl'NEWLINE)NEWLINE import importlibNEWLINEimport inspectNEWLINEimport osNEWLINEimport pathlibNEWLINENEWLINEimport pkg_resourcesNEWLINEfrom clvm_tools.clvmc import compile_clvm as compile_clvm_pyNEWLINEfrom flax.types.blockchain_format.program import Program, SerializedProgramNEWLINENEWLINEcompile_clvm = compile_clvm_pyNEWLINENEWLINE# Handle optional use of clvm_tools_rs if available and requestedNEWLINEif "CLVM_TOOLS_RS" in os.environ:NEWLINE try:NEWLINENEWLINE def sha256file(f):NEWLINE import hashlibNEWLINENEWLINE m = hashlib.sha256()NEWLINE m.update(open(f).read().encode("utf8"))NEWLINE return m.hexdigest()NEWLINENEWLINE from clvm_tools_rs import compile_clvm as compile_clvm_rsNEWLINENEWLINE def translate_path(p_):NEWLINE p = str(p_)NEWLINE if os.path.isdir(p):NEWLINE return pNEWLINE else:NEWLINE module_object = importlib.import_module(p)NEWLINE return os.path.dirname(inspect.getfile(module_object))NEWLINENEWLINE def rust_compile_clvm(full_path, output, search_paths=[]):NEWLINE treated_include_paths = list(map(translate_path, search_paths))NEWLINE print("compile_clvm_rs", full_path, output, treated_include_paths)NEWLINE compile_clvm_rs(str(full_path), str(output), treated_include_paths)NEWLINENEWLINE if os.environ["CLVM_TOOLS_RS"] == "check":NEWLINE orig = str(output) + ".orig"NEWLINE compile_clvm_py(full_path, orig, search_paths=search_paths)NEWLINE orig256 = sha256file(orig)NEWLINE rs256 = sha256file(output)NEWLINENEWLINE if orig256 != rs256:NEWLINE print("Compiled %s: %s vs %s\n" % (full_path, orig256, rs256))NEWLINE print("Aborting compilation due to mismatch with rust")NEWLINE assert orig256 == rs256NEWLINENEWLINE compile_clvm = rust_compile_clvmNEWLINE finally:NEWLINE passNEWLINENEWLINENEWLINEdef load_serialized_clvm(clvm_filename, package_or_requirement=__name__) -> SerializedProgram:NEWLINE """NEWLINE This function takes a .clvm file in the given package and compiles it to aNEWLINE .clvm.hex file if the .hex file is missing or older than the .clvm file, thenNEWLINE returns the contents of the .hex file as a `Program`.NEWLINENEWLINE clvm_filename: file nameNEWLINE package_or_requirement: usually `__name__` if the clvm file is in the same packageNEWLINE """NEWLINENEWLINE hex_filename = f"{clvm_filename}.hex"NEWLINENEWLINE try:NEWLINE if pkg_resources.resource_exists(package_or_requirement, clvm_filename):NEWLINE full_path = pathlib.Path(pkg_resources.resource_filename(package_or_requirement, clvm_filename))NEWLINE output = full_path.parent / hex_filenameNEWLINE compile_clvm(full_path, output, search_paths=[full_path.parent])NEWLINE except NotImplementedError:NEWLINE # pyinstaller doesn't support `pkg_resources.resource_exists`NEWLINE # so we just fall through to loading the hex clvmNEWLINE passNEWLINENEWLINE clvm_hex = pkg_resources.resource_string(package_or_requirement, hex_filename).decode("utf8")NEWLINE clvm_blob = bytes.fromhex(clvm_hex)NEWLINE return SerializedProgram.from_bytes(clvm_blob)NEWLINENEWLINENEWLINEdef load_clvm(clvm_filename, package_or_requirement=__name__) -> Program:NEWLINE return Program.from_bytes(bytes(load_serialized_clvm(clvm_filename, package_or_requirement=package_or_requirement)))NEWLINE """NEWLINEtorch.multiprocessing is a wrapper around the native :mod:`multiprocessing`NEWLINEmodule. It registers custom reducers, that use shared memory to provide sharedNEWLINEviews on the same data in different processes. Once the tensor/storage is movedNEWLINEto shared_memory (see :func:`~torch.Tensor.share_memory_`), it will be possibleNEWLINEto send it to other processes without making any copies.NEWLINENEWLINEThe API is 100% compatible with the original module - it's enough to changeNEWLINE``import multiprocessing`` to ``import torch.multiprocessing`` to have all theNEWLINEtensors sent through the queues or shared via other mechanisms, moved to sharedNEWLINEmemory.NEWLINENEWLINEBecause of the similarity of APIs we do not document most of this packageNEWLINEcontents, and we recommend referring to very good docs of the original module.NEWLINE"""NEWLINEimport torchNEWLINEimport sysNEWLINEfrom .reductions import init_reductionsNEWLINEimport multiprocessingNEWLINENEWLINE__all__ = ['set_sharing_strategy', 'get_sharing_strategy',NEWLINE 'get_all_sharing_strategies']NEWLINENEWLINENEWLINEfrom multiprocessing import *NEWLINENEWLINENEWLINE__all__ += multiprocessing.__all__NEWLINENEWLINENEWLINE# This call adds a Linux specific prctl(2) wrapper function to this module.NEWLINE# See https://github.com/pytorch/pytorch/pull/14391 for more information.NEWLINEtorch._C._multiprocessing_init()NEWLINENEWLINENEWLINEif sys.version_info < (3, 3):NEWLINE """Override basic classes in Python 2.7 and Python 3.3 to use ForkingPicklerNEWLINE for serialization. Later versions of Python already use ForkingPickler."""NEWLINE from .queue import Queue, SimpleQueueNEWLINE from .pool import PoolNEWLINENEWLINENEWLINE"""Add helper function to spawn N processes and wait for completion of any ofNEWLINEthem. This depends `mp.get_context` which was added in Python 3.4."""NEWLINEfrom .spawn import spawn, SpawnContext, _supports_context, start_processes, ProcessContextNEWLINENEWLINENEWLINEif sys.platform == 'darwin' or sys.platform == 'win32':NEWLINE _sharing_strategy = 'file_system'NEWLINE _all_sharing_strategies = {'file_system'}NEWLINEelse:NEWLINE _sharing_strategy = 'file_descriptor'NEWLINE _all_sharing_strategies = {'file_descriptor', 'file_system'}NEWLINENEWLINENEWLINEdef set_sharing_strategy(new_strategy):NEWLINE """Sets the strategy for sharing CPU tensors.NEWLINENEWLINE Arguments:NEWLINE new_strategy (str): Name of the selected strategy. Should be one ofNEWLINE the values returned by :func:`get_all_sharing_strategies()`.NEWLINE """NEWLINE global _sharing_strategyNEWLINE assert new_strategy in _all_sharing_strategiesNEWLINE _sharing_strategy = new_strategyNEWLINENEWLINENEWLINEdef get_sharing_strategy():NEWLINE """Returns the current strategy for sharing CPU tensors."""NEWLINE return _sharing_strategyNEWLINENEWLINENEWLINEdef get_all_sharing_strategies():NEWLINE """Returns a set of sharing strategies supported on a current system."""NEWLINE return _all_sharing_strategiesNEWLINENEWLINENEWLINEinit_reductions()NEWLINE import argparseNEWLINEimport jsonNEWLINEimport pandas as pdNEWLINEpd.options.display.float_format = '{:,.2f}'.formatNEWLINEimport randomNEWLINEimport numpy as npNEWLINEimport tqdmNEWLINENEWLINEfrom src.sim import SimNEWLINENEWLINEdef run(params):NEWLINE """simulates the investment on the S&P500 index similar toNEWLINE investing on index fundsNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE params : dictNEWLINE contrain the parameters to run the simulationNEWLINE """NEWLINE #load data sourceNEWLINE data = pd.read_csv('./data/sp500.csv')NEWLINENEWLINE #create empty dataframe to store resultsNEWLINE res = pd.DataFrame(NEWLINE columns=['length','mean','median','std','iqr',NEWLINE 'wins','losses','zero','total','wins/losses',NEWLINE 'a_r_mean','a_r_median','a_r_std'])NEWLINE res_all = pd.DataFrame(NEWLINE columns=['len', 'year', 'month',NEWLINE 'gain', 'annualized_returns'])NEWLINE NEWLINE for i_l, length in enumerate(params['lengths']):NEWLINE for i_y, year in enumerate(params['years']):NEWLINE for i_m, month in enumerate(params['months']):NEWLINE try:NEWLINE config={'buy': params['buy'],NEWLINE 'buy_year': year,NEWLINE 'buy_month': month,NEWLINE 'sell_year': year+length,NEWLINE 'sell_month': month,NEWLINE 'dividends': params['dividends'],NEWLINE 'inflation_corrected': False}NEWLINE NEWLINE sim = Sim(config, data)NEWLINE sim.run()NEWLINE # calculates right row to store resultsNEWLINE i_res_all = i_l*len(params['years'])*len(params['months']) + \NEWLINE i_y*len(params['months']) + i_mNEWLINE res_all.at[i_res_all, 'len'] = lengthNEWLINE res_all.at[i_res_all, 'year'] = yearNEWLINE res_all.at[i_res_all, 'month'] = monthNEWLINE res_all.at[i_res_all, 'gain'] = sim.gainNEWLINE res_all.at[i_res_all, 'annualized_returns'] = sim.annualized_returnsNEWLINE except Exception as e:NEWLINE # happes usually when the length goes beyond the data (2021+)NEWLINE print(length, year, month, e)NEWLINE res_all.at[i_res_all, :] = np.nanNEWLINE NEWLINE res.at[i_l, 'length'] = lengthNEWLINE res.at[i_l, 'mean'] = np.mean(res_all[res_all['len']==length]['gain'])NEWLINE res.at[i_l, 'median'] = np.median(res_all[res_all['len']==length]['gain'])NEWLINE res.at[i_l, 'std'] = np.std(res_all[res_all['len']==length]['gain'])NEWLINE res.at[i_l, 'iqr'] = np.quantile(NEWLINE res_all[res_all['len']==length]['gain'], 0.75) - \NEWLINE np.quantile(res_all[res_all['len']==length]['gain'], 0.25)NEWLINE res.at[i_l, 'wins'] = np.sum(res_all[res_all['len']==length]['gain'] > 0)NEWLINE res.at[i_l, 'losses'] = np.sum(res_all[res_all['len']==length]['gain'] < 0)NEWLINE res.at[i_l, 'zero'] = np.sum(res_all[res_all['len']==length]['gain'] == 0)NEWLINE res.at[i_l, 'total'] = res.at[i_l, 'wins'] + res.at[i_l, 'losses'] + res.at[i_l, 'zero']NEWLINE res.at[i_l, 'wins/losses'] = res.at[i_l, 'wins'] / res.at[i_l, 'losses']NEWLINE res.at[i_l, 'a_r_mean'] = np.mean(np.vstack(res_all[res_all['len']==length]['annualized_returns']))NEWLINE res.at[i_l, 'a_r_median'] = np.median(np.vstack(res_all[res_all['len']==length]['annualized_returns']))NEWLINE res.at[i_l, 'a_r_std'] = np.std(np.vstack(res_all[res_all['len']==length]['annualized_returns']))NEWLINE res_all.to_csv(f'./results/res_all_buy_{params["buy"]}_dividends_{params["dividends"]}.csv')NEWLINE res.to_csv(f'./results/res_buy_{params["buy"]}_dividends_{params["dividends"]}.csv')NEWLINENEWLINEif __name__ == '__main__':NEWLINE NEWLINE parser = argparse.ArgumentParser()NEWLINE parser.add_argument("config_file", help="path to config file")NEWLINE args = parser.parse_args()NEWLINE params = json.load(open('./config/'+args.config_file+'.json', 'r'))NEWLINE run(params) import osNEWLINEimport matplotlib.pyplot as pltNEWLINEimport numpy as npNEWLINEimport subprocessNEWLINEfrom tempfile import TemporaryDirectoryNEWLINENEWLINESEMIHDP_HOME_DIR = os.path.dirname(os.path.realpath(__file__))NEWLINESEMIHDP_EXEC = os.path.join(SEMIHDP_HOME_DIR, 'build/run_from_file')NEWLINEBASE_CMD = SEMIHDP_EXEC + ' ' + "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11}"NEWLINEPARAMS_FILE = os.path.join(SEMIHDP_HOME_DIR, 'semihdp_params.asciipb')NEWLINENEWLINENEWLINEdef run_mcmc_from_files(data_path, dens_grid_path, output_path, seed,NEWLINE niter, nburn, thin, update_c="full"):NEWLINE chainfile = os.path.join(output_path, "chains.recordio")NEWLINE c_file = os.path.join(output_path, "c.txt")NEWLINE latent_vars_file = os.path.join(output_path, "latent_vars.txt")NEWLINE dens_path = os.path.join(output_path, "dens/")NEWLINE os.makedirs(dens_path)NEWLINE cmd = BASE_CMD.format(NEWLINE data_path, PARAMS_FILE, chainfile, c_file,NEWLINE latent_vars_file, dens_grid_path, NEWLINE dens_path, seed, niter, nburn, thin, update_c)NEWLINE NEWLINE cmd = cmd.split(" ")NEWLINE subprocess.call(cmd, cwd=SEMIHDP_HOME_DIR)NEWLINE return NEWLINENEWLINENEWLINEdef load_output(output_path, ngroups):NEWLINE c_file = os.path.join(output_path, "c.txt")NEWLINE latent_vars_file = os.path.join(output_path, "latent_vars.txt")NEWLINE dens_path = os.path.join(output_path, "dens/")NEWLINENEWLINE c = np.loadtxt(c_file, delimiter=",")NEWLINE latent_vars = np.loadtxt(latent_vars_file, delimiter=",")NEWLINE log_dens = []NEWLINE for i in range(ngroups):NEWLINE fname = os.path.join(dens_path, "group_{0}.csv".format(i))NEWLINE log_dens.append(np.loadtxt(fname, delimiter=","))NEWLINE return c, latent_vars, log_dens NEWLINENEWLINENEWLINEdef run_mcmc(data: list, dens_grid: np.array, seed: int,NEWLINE niter=1000, nburn=1000, thin=10, update_c="full"):NEWLINE """NEWLINE Runs the semihpd sampler by calling the executable from a subprocess.NEWLINE ArgumentsNEWLINE ---------NEWLINE data: list of np.arrays, each entry is the data in one of the groupsNEWLINE dens_grid: np.array, the grid on which to evaluate the density of all the groupsNEWLINE seed: int, the seed for the random number generatorNEWLINE niter: int, number of iterations to run the samplerNEWLINE nburn: int, number of burn-in iterations NEWLINE thin: int, thinning factorNEWLINE update_c: str, either "full", "metro_base" or "metro_dist". NEWLINE The update rule for the restourants allocationsNEWLINENEWLINE The sampler will be ran for niter + nburn iterations.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE rest_allocs: np.array, of dimension [num_iter, num_groups]NEWLINE The parameters c_i's for each iterationNEWLINE latent_vars: np.array, of dimension [num_iter, 4] the colums areNEWLINE group_id, datum_id, mean (resp. variance) of the latent variable NEWLINE associated to the observationNEWLINE log_dens: list of np.arrays, each entry is the evaluation of log_density of NEWLINE one of the groups in each of the mcmc iterationsNEWLINE """NEWLINENEWLINE ngroups = len(data)NEWLINE data_ = np.vstack([NEWLINE np.column_stack([np.ones_like(x) * i, x]) for i, x in enumerate(data)])NEWLINE with TemporaryDirectory(prefix=SEMIHDP_HOME_DIR+"/") as tmpdir:NEWLINE data_path = os.path.join(tmpdir, 'data.txt')NEWLINE np.savetxt(data_path, data_, delimiter=",")NEWLINE grid_path = os.path.join(tmpdir, 'grid.txt')NEWLINE np.savetxt(grid_path, dens_grid, delimiter=",")NEWLINENEWLINE run_mcmc_from_files(data_path, grid_path, tmpdir, niter, NEWLINE nburn, thin, update_c)NEWLINENEWLINE return load_output(tmpdir, ngroups)NEWLINENEWLINE NEWLINEif __name__ == "__main__":NEWLINE seed = 132312NEWLINE data = [np.random.normal(0, 1, size=100),NEWLINE np.random.normal(0, 1, size=100)]NEWLINE dens_grid = np.linspace(-5, 5, 100)NEWLINE c, latent_vars, log_dens = run_mcmc(data, dens_grid, seed)NEWLINE plt.plot(dens_grid, np.exp(np.mean(log_dens[0], axis=0)))NEWLINE plt.show()NEWLINENEWLINE from os import mkdirNEWLINEfrom os.path import existsNEWLINENEWLINEfrom .dist_tree import DistTreeNEWLINEfrom ...typehint import *NEWLINENEWLINENEWLINEdef main(conf: TConf):NEWLINE """ Create dist-side tree (all empty folders under `dst_root`) """NEWLINE _precheck(conf)NEWLINE NEWLINE # create main folders under dst_root.NEWLINE mkdir(conf['build']['dist_dir'])NEWLINE mkdir(conf['build']['dist_dir'] + '/' + 'build')NEWLINE mkdir(conf['build']['dist_dir'] + '/' + 'lib')NEWLINE mkdir(conf['build']['dist_dir'] + '/' + 'src')NEWLINE mkdir(conf['build']['dist_dir'] + '/' + 'src' + '/' + '.pylauncher_conf')NEWLINE NEWLINE dist_tree = DistTree()NEWLINE NEWLINE """NEWLINE Add to source dirs list:NEWLINE conf:NEWLINE build:NEWLINE + proj_dirNEWLINE + targetNEWLINE + attachmentsNEWLINENEWLINE Do not add to source dirs list:NEWLINE conf:NEWLINE build:NEWLINE - dist_dirNEWLINE - iconNEWLINE - readmeNEWLINE - module_pathsNEWLINE """NEWLINE dist_tree.add_src_dirs(NEWLINE conf['build']['proj_dir'],NEWLINE *(v['file'] for v in conf['build']['launchers'].values()),NEWLINE *(k for k, v in conf['build']['attachments'].items()NEWLINE if v['path'] == ''),NEWLINE )NEWLINE NEWLINE src_root = dist_tree.suggest_src_root()NEWLINE dst_root = conf['build']['dist_dir']NEWLINE print(f'the suggested source root directory is: {src_root}', ':v2')NEWLINE NEWLINE dist_tree.build_dst_dirs(src_root, f'{dst_root}/src')NEWLINE NEWLINE # init global path modelsNEWLINE _init_path_models(src_root, dst_root, conf)NEWLINE NEWLINE return src_root, dst_rootNEWLINENEWLINENEWLINEdef _precheck(conf: TConf):NEWLINE assert not exists(d := conf['build']['dist_dir']), (NEWLINE 'The target distribution directory ({}) already exists, please appoint 'NEWLINE 'another (non-existent) folder to distribute.'.format(d)NEWLINE )NEWLINE NEWLINE paths_not_exist = []NEWLINE for src_path in conf['build']['attachments']:NEWLINE if not exists(src_path):NEWLINE paths_not_exist.append(src_path)NEWLINE if paths_not_exist:NEWLINE print(':l', paths_not_exist)NEWLINE raise FileNotFoundError(NEWLINE 'Please make sure all required paths in `conf["build"]'NEWLINE '["attachments"]` are existed.'NEWLINE )NEWLINE NEWLINE # if conf['build']['venv']['enabled']:NEWLINE # from .embed_python import EmbedPythonManagerNEWLINE # builder = EmbedPythonManager(NEWLINE # pyversion=conf['build']['venv']['python_version']NEWLINE # )NEWLINE # # try to get a valid embed python path, if failed, this method willNEWLINE # # raise an exception to terminate process.NEWLINE # builder.get_embed_python_dir()NEWLINE #NEWLINE # mode = conf['build']['venv']['mode']NEWLINE # if mode == 'source_venv':NEWLINE # if venv_path := conf['build']['venv']['options'][mode]['path']:NEWLINE # if venv_path.startswith(src_path := conf['build']['proj_dir']):NEWLINE # lk.logt('[W2015]', f'''NEWLINE # Please do not put the Python virtual environment folderNEWLINE # in your source code folder! This will make the third-NEWLINE # party libraries to be encrypted, which usually leads toNEWLINE # unpredicatable errors.NEWLINE # You can put venv aside with the source code dir, thisNEWLINE # is the recommended parctice.NEWLINE #NEWLINE # Current venv dir: {venv_path}NEWLINE # Suggest moved to: {ospath.dirname(src_path)}/venvNEWLINE # ''')NEWLINE # if input('Continue the process? (y/n): ').lower() != 'y':NEWLINE # raise SystemExitNEWLINENEWLINENEWLINEdef _init_path_models(src_root, dst_root, conf: TConf):NEWLINE from ...path_model import dst_modelNEWLINE from ...path_model import src_modelNEWLINE from ...path_model import relpathNEWLINE NEWLINE src_model.init(NEWLINE src_root=src_root, prj_root=conf['build']['proj_dir'],NEWLINE readme=conf['build']['readme']NEWLINE )NEWLINE dst_model.init(NEWLINE dst_root=dst_root,NEWLINE prj_relroot=relpath(src_model.prj_root, src_model.src_root),NEWLINE launcher_name=conf['build']['launcher_name'],NEWLINE readme=conf['build']['readme']NEWLINE )NEWLINE NEWLINE"""NEWLINEPERIODSNEWLINE"""NEWLINENEWLINEnumPeriods = 60NEWLINENEWLINE"""NEWLINESTOPSNEWLINE"""NEWLINENEWLINEnumStations = 6NEWLINENEWLINEstation_names = (NEWLINE "Hamburg Hbf", # 0NEWLINE "Landwehr", # 1NEWLINE "Hasselbrook", # 2NEWLINE "Wansbeker Chaussee*", # 3NEWLINE "Friedrichsberg*", # 4NEWLINE "Barmbek*", # 5NEWLINE )NEWLINENEWLINEnumStops = 12NEWLINENEWLINEstops_position = (NEWLINE (0, 0), # Stop 0NEWLINE (2, 0), # Stop 1NEWLINE (3, 0), # Stop 2NEWLINE (4, 0), # Stop 3NEWLINE (5, 0), # Stop 4NEWLINE (7, 0), # Stop 5NEWLINE (7, 1), # Stop 6NEWLINE (15, 1), # Stop 7NEWLINE (13, 1), # Stop 8NEWLINE (12, 1), # Stop 9NEWLINE (11, 1), # Stop 10NEWLINE (10, 1), # Stop 11NEWLINE )NEWLINENEWLINEstops_distance = (NEWLINE (0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 0NEWLINE (0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 1NEWLINE (0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 2NEWLINE (0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0), # Stop 3NEWLINE (0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0), # Stop 4NEWLINE (0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0), # Stop 5NEWLINE (0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0), # Stop 6NEWLINE (0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0), # Stop 7NEWLINE (0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0), # Stop 8NEWLINE (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0), # Stop 9NEWLINE (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2), # Stop 10NEWLINE (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 11NEWLINE )NEWLINENEWLINEstation_start = 0NEWLINENEWLINE"""NEWLINETRAMSNEWLINE"""NEWLINENEWLINEnumTrams = 6NEWLINENEWLINEtram_capacity = 514NEWLINENEWLINEtram_capacity_cargo = 304NEWLINENEWLINEtram_capacity_min_passenger = 208NEWLINENEWLINEtram_capacity_min_cargo = 0NEWLINENEWLINEtram_speed = 1NEWLINENEWLINEtram_headway = 1NEWLINENEWLINEtram_min_service = 1NEWLINENEWLINEtram_max_service = 10NEWLINENEWLINEmin_time_next_tram = 0.333NEWLINENEWLINEtram_travel_deviation = 0.167NEWLINENEWLINE"""NEWLINEPASSENGERSNEWLINE"""NEWLINENEWLINEpassenger_set = "pas-20210421-2109-int6000000000000001e-1"NEWLINENEWLINEpassenger_service_time_board = 0.0145NEWLINENEWLINEpassenger_service_time_alight = 0.0145NEWLINENEWLINE"""NEWLINECARGONEWLINE"""NEWLINENEWLINEnumCargo = 50NEWLINENEWLINEcargo_size = 4NEWLINENEWLINEcargo_station_destination = (NEWLINE 4, # 0NEWLINE 4, # 1NEWLINE 4, # 2NEWLINE 4, # 3NEWLINE 3, # 4NEWLINE 3, # 5NEWLINE 4, # 6NEWLINE 4, # 7NEWLINE 3, # 8NEWLINE 3, # 9NEWLINE 5, # 10NEWLINE 4, # 11NEWLINE 5, # 12NEWLINE 4, # 13NEWLINE 4, # 14NEWLINE 5, # 15NEWLINE 3, # 16NEWLINE 5, # 17NEWLINE 3, # 18NEWLINE 4, # 19NEWLINE 4, # 20NEWLINE 3, # 21NEWLINE 5, # 22NEWLINE 5, # 23NEWLINE 4, # 24NEWLINE 3, # 25NEWLINE 4, # 26NEWLINE 5, # 27NEWLINE 4, # 28NEWLINE 3, # 29NEWLINE 3, # 30NEWLINE 5, # 31NEWLINE 5, # 32NEWLINE 5, # 33NEWLINE 5, # 34NEWLINE 3, # 35NEWLINE 3, # 36NEWLINE 3, # 37NEWLINE 3, # 38NEWLINE 5, # 39NEWLINE 3, # 40NEWLINE 4, # 41NEWLINE 3, # 42NEWLINE 5, # 43NEWLINE 4, # 44NEWLINE 5, # 45NEWLINE 5, # 46NEWLINE 4, # 47NEWLINE 5, # 48NEWLINE 3, # 49NEWLINE )NEWLINENEWLINEcargo_release = (NEWLINE 0, # 0NEWLINE 0, # 1NEWLINE 0, # 2NEWLINE 1, # 3NEWLINE 1, # 4NEWLINE 1, # 5NEWLINE 1, # 6NEWLINE 1, # 7NEWLINE 1, # 8NEWLINE 1, # 9NEWLINE 2, # 10NEWLINE 2, # 11NEWLINE 2, # 12NEWLINE 2, # 13NEWLINE 2, # 14NEWLINE 3, # 15NEWLINE 3, # 16NEWLINE 4, # 17NEWLINE 4, # 18NEWLINE 4, # 19NEWLINE 5, # 20NEWLINE 5, # 21NEWLINE 5, # 22NEWLINE 5, # 23NEWLINE 6, # 24NEWLINE 6, # 25NEWLINE 6, # 26NEWLINE 6, # 27NEWLINE 7, # 28NEWLINE 7, # 29NEWLINE 7, # 30NEWLINE 7, # 31NEWLINE 7, # 32NEWLINE 9, # 33NEWLINE 9, # 34NEWLINE 9, # 35NEWLINE 9, # 36NEWLINE 9, # 37NEWLINE 9, # 38NEWLINE 9, # 39NEWLINE 10, # 40NEWLINE 10, # 41NEWLINE 10, # 42NEWLINE 10, # 43NEWLINE 11, # 44NEWLINE 11, # 45NEWLINE 11, # 46NEWLINE 11, # 47NEWLINE 11, # 48NEWLINE 11, # 49NEWLINE )NEWLINENEWLINEcargo_station_deadline = (NEWLINE 24, # 0NEWLINE 14, # 1NEWLINE 11, # 2NEWLINE 36, # 3NEWLINE 17, # 4NEWLINE 11, # 5NEWLINE 41, # 6NEWLINE 43, # 7NEWLINE 19, # 8NEWLINE 49, # 9NEWLINE 46, # 10NEWLINE 39, # 11NEWLINE 49, # 12NEWLINE 46, # 13NEWLINE 58, # 14NEWLINE 13, # 15NEWLINE 35, # 16NEWLINE 45, # 17NEWLINE 19, # 18NEWLINE 14, # 19NEWLINE 29, # 20NEWLINE 48, # 21NEWLINE 44, # 22NEWLINE 22, # 23NEWLINE 16, # 24NEWLINE 16, # 25NEWLINE 46, # 26NEWLINE 40, # 27NEWLINE 29, # 28NEWLINE 17, # 29NEWLINE 25, # 30NEWLINE 17, # 31NEWLINE 50, # 32NEWLINE 56, # 33NEWLINE 32, # 34NEWLINE 37, # 35NEWLINE 33, # 36NEWLINE 39, # 37NEWLINE 19, # 38NEWLINE 19, # 39NEWLINE 20, # 40NEWLINE 20, # 41NEWLINE 57, # 42NEWLINE 57, # 43NEWLINE 22, # 44NEWLINE 56, # 45NEWLINE 21, # 46NEWLINE 21, # 47NEWLINE 21, # 48NEWLINE 51, # 49NEWLINE )NEWLINENEWLINEcargo_max_delay = 3NEWLINENEWLINEcargo_service_time_load = 0.3333333333333333NEWLINENEWLINEcargo_service_time_unload = 0.25NEWLINENEWLINE"""NEWLINEparameters for reproducibiliy. More information: https://numpy.org/doc/stable/reference/random/parallel.htmlNEWLINE"""NEWLINENEWLINE#initial entropyNEWLINEentropy = 258194110137029475889902652135037600173NEWLINENEWLINE#index for seed sequence childNEWLINEchild_seed_index = (NEWLINE 0, # 0NEWLINE )NEWLINENEWLINE"""NEWLINEResults from timetablingNEWLINE"""NEWLINENEWLINEscheme = "SV"NEWLINENEWLINEmethod = "timetabling_benchmark"NEWLINENEWLINEpassengerData = "0-rep"NEWLINENEWLINEdownstream_cargo = FalseNEWLINENEWLINEdelivery_optional = TrueNEWLINENEWLINEassignment_method = "timetabling_benchmark"NEWLINENEWLINEoperating = (NEWLINE True, # 0NEWLINE True, # 1NEWLINE True, # 2NEWLINE True, # 3NEWLINE True, # 4NEWLINE True, # 5NEWLINE )NEWLINENEWLINEtram_tour = (NEWLINE (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), # 0NEWLINE (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), # 1NEWLINE (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), # 2NEWLINE (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), # 3NEWLINE (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), # 4NEWLINE (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), # 5NEWLINE )NEWLINENEWLINEtram_time_arrival = (NEWLINE (2, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 37), # 0NEWLINE (6, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 41), # 1NEWLINE (10, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 45), # 2NEWLINE (14, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 49), # 3NEWLINE (18, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49, 53), # 4NEWLINE (22, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 57), # 5NEWLINE )NEWLINENEWLINEtram_time_departure = (NEWLINE (4, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 39), # 0NEWLINE (8, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 43), # 1NEWLINE (12, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 47), # 2NEWLINE (16, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 51), # 3NEWLINE (20, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 55), # 4NEWLINE (24, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55, 59), # 5NEWLINE )NEWLINENEWLINEcargo_tram_assignment = (NEWLINE 0, # 0NEWLINE 0, # 1NEWLINE 0, # 2NEWLINE 0, # 3NEWLINE 0, # 4NEWLINE 0, # 5NEWLINE 0, # 6NEWLINE 0, # 7NEWLINE 0, # 8NEWLINE 0, # 9NEWLINE 0, # 10NEWLINE 0, # 11NEWLINE 0, # 12NEWLINE 0, # 13NEWLINE 0, # 14NEWLINE 0, # 15NEWLINE 0, # 16NEWLINE 1, # 17NEWLINE 1, # 18NEWLINE 1, # 19NEWLINE 1, # 20NEWLINE 1, # 21NEWLINE 1, # 22NEWLINE 1, # 23NEWLINE 1, # 24NEWLINE 1, # 25NEWLINE 1, # 26NEWLINE 1, # 27NEWLINE 1, # 28NEWLINE 1, # 29NEWLINE 1, # 30NEWLINE 1, # 31NEWLINE 1, # 32NEWLINE 2, # 33NEWLINE 2, # 34NEWLINE 2, # 35NEWLINE 2, # 36NEWLINE 2, # 37NEWLINE 2, # 38NEWLINE 2, # 39NEWLINE 2, # 40NEWLINE 2, # 41NEWLINE 2, # 42NEWLINE 2, # 43NEWLINE 2, # 44NEWLINE 2, # 45NEWLINE 2, # 46NEWLINE 2, # 47NEWLINE 2, # 48NEWLINE 2, # 49NEWLINE )NEWLINE #!/usr/bin/env/ pythonNEWLINEprint ("Hola mundo")NEWLINENEWLINE# TIPOS DE DATOSNEWLINENEWLINE# Esto e unha cadeaNEWLINEc = "Hola mundo"NEWLINENEWLINE# Esto e un enteiroNEWLINEe = 23NEWLINENEWLINE# Esto e un longNEWLINElong = 23NEWLINENEWLINE# Numero en octalNEWLINEoctal = 0o27NEWLINENEWLINE# Numero en HexadecimalNEWLINEhexDecimal = 0x3452334NEWLINENEWLINE# Numero con decimalesNEWLINEreal = 23.334223NEWLINENEWLINE# Numero con decimales en notacion cientificaNEWLINEcientifico = 0.1e-3NEWLINENEWLINE# Podese comprobar coa funcion typeNEWLINEprint(type(c))NEWLINEprint(type(e))NEWLINEprint(type(long))NEWLINEprint(octal)NEWLINEprint(hexDecimal)NEWLINENEWLINENEWLINE # Third-partyNEWLINEimport astropy.units as uNEWLINENEWLINENEWLINEdef quantity_from_hdf5(dset):NEWLINE """NEWLINE Return an Astropy Quantity object from a key in an HDF5 file,NEWLINE group, or dataset. This checks to see if the input file/group/datasetNEWLINE contains a ``'unit'`` attribute (e.g., in `f.attrs`).NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE dset : :class:`h5py.DataSet`NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE q : `astropy.units.Quantity`, `numpy.ndarray`NEWLINE If a unit attribute exists, this returns a Quantity. Otherwise, itNEWLINE returns a numpy array.NEWLINE """NEWLINE if 'unit' in dset.attrs and dset.attrs['unit'] is not None:NEWLINE unit = u.Unit(dset.attrs['unit'])NEWLINE else:NEWLINE unit = 1.NEWLINENEWLINE return dset[:] * unitNEWLINENEWLINENEWLINEdef quantity_to_hdf5(f, key, q):NEWLINE """NEWLINE Turn an Astropy Quantity object into something we can write out toNEWLINE an HDF5 file.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE f : :class:`h5py.File`, :class:`h5py.Group`, :class:`h5py.DataSet`NEWLINE key : strNEWLINE The name.NEWLINE q : float, `astropy.units.Quantity`NEWLINE The quantity.NEWLINENEWLINE """NEWLINENEWLINE if hasattr(q, 'unit'):NEWLINE f[key] = q.valueNEWLINE f[key].attrs['unit'] = str(q.unit)NEWLINENEWLINE else:NEWLINE f[key] = qNEWLINE f[key].attrs['unit'] = ""NEWLINE # Twitter AUTH:NEWLINEAPP_KEY = 'APP_KEY_HERE' NEWLINEAPP_SECRET = 'APP_SECRET_HERE' NEWLINEOAUTH_TOKEN = 'TOKEN_HERE'NEWLINEOAUTH_TOKEN_SECRET = 'TOKEN_SECRET_HERE'NEWLINENEWLINE# Telegram options:NEWLINETELEGRAM_CHANNEL = 'CHANNEL_NAME_HERE'NEWLINETELEGRAM_TOKEN = 'TOKEN_HERE'NEWLINENEWLINE# Misc:NEWLINETWITTER_USER_NAME = 'USER_NAME_HERE'NEWLINEMSG = '{NAME}:\n{TEXT}\n\nSource'NEWLINENEWLINE# Technical stuff:NEWLINETWEET_BASE_URL = 'https://twitter.com/i/web/status/'NEWLINESTATE_FILE = 'state.p'NEWLINESLEEP = 3NEWLINETG_LINK = 'https://api.telegram.org/bot{TOKEN}/sendMessage?chat_id=@{CHANNEL}&text={MESSAGE}&parse_mode=html'NEWLINEUNSUPPORTED_TAGS = ['', '', '', 'class="twython-url"', 'class="twython-media"', 'class="twython-mention"', 'class="twython-hashtag"', 'class="twython-symbol"', ]NEWLINE # Copyright (c) 2017-present, Facebook, Inc.NEWLINE# All rights reserved.NEWLINE#NEWLINE# This source code is licensed under the license found in the LICENSE file inNEWLINE# the root directory of this source tree. An additional grant of patent rightsNEWLINE# can be found in the PATENTS file in the same directory.NEWLINENEWLINEfrom .dictionary import Dictionary, TruncatedDictionaryNEWLINEfrom .fairseq_dataset import FairseqDatasetNEWLINEfrom .backtranslation_dataset import BacktranslationDatasetNEWLINEfrom .concat_dataset import ConcatDatasetNEWLINEfrom .indexed_dataset import IndexedCachedDataset, IndexedDataset, IndexedRawTextDatasetNEWLINEfrom .language_pair_dataset import LanguagePairDataset, LanguagePairDatasetWithIndexNEWLINEfrom .lm_context_window_dataset import LMContextWindowDatasetNEWLINEfrom .monolingual_dataset import MonolingualDatasetNEWLINEfrom .noising import NoisingDatasetNEWLINEfrom .round_robin_zip_datasets import RoundRobinZipDatasetsNEWLINEfrom .token_block_dataset import TokenBlockDatasetNEWLINEfrom .transform_eos_dataset import TransformEosDatasetNEWLINEfrom .transform_eos_lang_pair_dataset import TransformEosLangPairDatasetNEWLINENEWLINEfrom .iterators import (NEWLINE CountingIterator,NEWLINE EpochBatchIterator,NEWLINE GroupedIterator,NEWLINE ShardedIterator,NEWLINE)NEWLINENEWLINE__all__ = [NEWLINE 'BacktranslationDataset',NEWLINE 'ConcatDataset',NEWLINE 'CountingIterator',NEWLINE 'Dictionary',NEWLINE 'EpochBatchIterator',NEWLINE 'FairseqDataset',NEWLINE 'GroupedIterator',NEWLINE 'IndexedCachedDataset',NEWLINE 'IndexedDataset',NEWLINE 'IndexedRawTextDataset',NEWLINE 'LanguagePairDataset',NEWLINE 'LanguagePairDatasetWithIndex'NEWLINE 'LMContextWindowDataset',NEWLINE 'MonolingualDataset',NEWLINE 'NoisingDataset',NEWLINE 'RoundRobinZipDatasets',NEWLINE 'ShardedIterator',NEWLINE 'TokenBlockDataset',NEWLINE 'TransformEosDataset',NEWLINE 'TransformEosLangPairDataset',NEWLINE]NEWLINE # encoding: utf-8NEWLINE"""Event loop integration for the ZeroMQ-based kernels."""NEWLINENEWLINE# Copyright (c) IPython Development Team.NEWLINE# Distributed under the terms of the Modified BSD License.NEWLINENEWLINEfrom functools import partialNEWLINEimport osNEWLINEimport sysNEWLINEimport platformNEWLINENEWLINEimport zmqNEWLINENEWLINEfrom distutils.version import LooseVersion as VNEWLINEfrom traitlets.config.application import ApplicationNEWLINENEWLINENEWLINEdef _use_appnope():NEWLINE """Should we use appnope for dealing with OS X app nap?NEWLINENEWLINE Checks if we are on OS X 10.9 or greater.NEWLINE """NEWLINE return sys.platform == 'darwin' and V(platform.mac_ver()[0]) >= V('10.9')NEWLINENEWLINENEWLINEdef _notify_stream_qt(kernel, stream):NEWLINENEWLINE from IPython.external.qt_for_kernel import QtCoreNEWLINENEWLINE def process_stream_events():NEWLINE """fall back to main loop when there's a socket event"""NEWLINE # call flush to ensure that the stream doesn't lose eventsNEWLINE # due to our consuming of the edge-triggered FDNEWLINE # flush returns the number of events consumed.NEWLINE # if there were any, wake it upNEWLINE if stream.flush(limit=1):NEWLINE notifier.setEnabled(False)NEWLINE kernel.app.quit()NEWLINENEWLINE fd = stream.getsockopt(zmq.FD)NEWLINE notifier = QtCore.QSocketNotifier(fd, QtCore.QSocketNotifier.Read, kernel.app)NEWLINE notifier.activated.connect(process_stream_events)NEWLINE # there may already be unprocessed events waiting.NEWLINE # these events will not wake zmq's edge-triggered FDNEWLINE # since edge-triggered notification only occurs on new i/o activity.NEWLINE # process all the waiting events immediatelyNEWLINE # so we start in a clean state ensuring that any new i/o events will notify.NEWLINE # schedule first call on the eventloop as soon as it's running,NEWLINE # so we don't block here processing eventsNEWLINE timer = QtCore.QTimer(kernel.app)NEWLINE timer.setSingleShot(True)NEWLINE timer.timeout.connect(process_stream_events)NEWLINE timer.start(0)NEWLINENEWLINE# mapping of keys to loop functionsNEWLINEloop_map = {NEWLINE 'inline': None,NEWLINE 'nbagg': None,NEWLINE 'notebook': None,NEWLINE 'ipympl': None,NEWLINE 'widget': None,NEWLINE None: None,NEWLINE}NEWLINENEWLINEdef register_integration(*toolkitnames):NEWLINE """Decorator to register an event loop to integrate with the IPython kernelNEWLINENEWLINE The decorator takes names to register the event loop as for the %gui magic.NEWLINE You can provide alternative names for the same toolkit.NEWLINENEWLINE The decorated function should take a single argument, the IPython kernelNEWLINE instance, arrange for the event loop to call ``kernel.do_one_iteration()``NEWLINE at least every ``kernel._poll_interval`` seconds, and start the event loop.NEWLINENEWLINE :mod:`ipykernel.eventloops` provides and registers such functionsNEWLINE for a few common event loops.NEWLINE """NEWLINE def decorator(func):NEWLINE for name in toolkitnames:NEWLINE loop_map[name] = funcNEWLINENEWLINE func.exit_hook = lambda kernel: NoneNEWLINENEWLINE def exit_decorator(exit_func):NEWLINE """@func.exit is now a decoratorNEWLINENEWLINE to register a function to be called on exitNEWLINE """NEWLINE func.exit_hook = exit_funcNEWLINE return exit_funcNEWLINENEWLINE func.exit = exit_decoratorNEWLINE return funcNEWLINENEWLINE return decoratorNEWLINENEWLINENEWLINEdef _loop_qt(app):NEWLINE """Inner-loop for running the Qt eventloopNEWLINENEWLINE Pulled from guisupport.start_event_loop in IPython < 5.2,NEWLINE since IPython 5.2 only checks `get_ipython().active_eventloop` is defined,NEWLINE rather than if the eventloop is actually running.NEWLINE """NEWLINE app._in_event_loop = TrueNEWLINE app.exec_()NEWLINE app._in_event_loop = FalseNEWLINENEWLINENEWLINE@register_integration('qt4')NEWLINEdef loop_qt4(kernel):NEWLINE """Start a kernel with PyQt4 event loop integration."""NEWLINENEWLINE from IPython.lib.guisupport import get_app_qt4NEWLINENEWLINE kernel.app = get_app_qt4([" "])NEWLINE kernel.app.setQuitOnLastWindowClosed(False)NEWLINENEWLINE # Only register the eventloop for the shell stream because doingNEWLINE # it for the control stream is generating a bunch of unnecessaryNEWLINE # warnings on Windows.NEWLINE _notify_stream_qt(kernel, kernel.shell_streams[0])NEWLINENEWLINE _loop_qt(kernel.app)NEWLINENEWLINENEWLINE@register_integration('qt', 'qt5')NEWLINEdef loop_qt5(kernel):NEWLINE """Start a kernel with PyQt5 event loop integration."""NEWLINE os.environ['QT_API'] = 'pyqt5'NEWLINE return loop_qt4(kernel)NEWLINENEWLINENEWLINE# exit and watch are the same for qt 4 and 5NEWLINE@loop_qt4.exitNEWLINE@loop_qt5.exitNEWLINEdef loop_qt_exit(kernel):NEWLINE kernel.app.exit()NEWLINENEWLINENEWLINEdef _loop_wx(app):NEWLINE """Inner-loop for running the Wx eventloopNEWLINENEWLINE Pulled from guisupport.start_event_loop in IPython < 5.2,NEWLINE since IPython 5.2 only checks `get_ipython().active_eventloop` is defined,NEWLINE rather than if the eventloop is actually running.NEWLINE """NEWLINE app._in_event_loop = TrueNEWLINE app.MainLoop()NEWLINE app._in_event_loop = FalseNEWLINENEWLINENEWLINE@register_integration('wx')NEWLINEdef loop_wx(kernel):NEWLINE """Start a kernel with wx event loop support."""NEWLINENEWLINE import wxNEWLINENEWLINE # Wx uses millisecondsNEWLINE poll_interval = int(1000 * kernel._poll_interval)NEWLINENEWLINE def wake():NEWLINE """wake from wx"""NEWLINE for stream in kernel.shell_streams:NEWLINE if stream.flush(limit=1):NEWLINE kernel.app.ExitMainLoop()NEWLINE returnNEWLINENEWLINE # We have to put the wx.Timer in a wx.Frame for it to fire properly.NEWLINE # We make the Frame hidden when we create it in the main app below.NEWLINE class TimerFrame(wx.Frame):NEWLINE def __init__(self, func):NEWLINE wx.Frame.__init__(self, None, -1)NEWLINE self.timer = wx.Timer(self)NEWLINE # Units for the timer are in millisecondsNEWLINE self.timer.Start(poll_interval)NEWLINE self.Bind(wx.EVT_TIMER, self.on_timer)NEWLINE self.func = funcNEWLINENEWLINE def on_timer(self, event):NEWLINE self.func()NEWLINENEWLINE # We need a custom wx.App to create our Frame subclass that has theNEWLINE # wx.Timer to defer back to the tornado event loop.NEWLINE class IPWxApp(wx.App):NEWLINE def OnInit(self):NEWLINE self.frame = TimerFrame(wake)NEWLINE self.frame.Show(False)NEWLINE return TrueNEWLINENEWLINE # The redirect=False here makes sure that wx doesn't replaceNEWLINE # sys.stdout/stderr with its own classes.NEWLINE if not (NEWLINE getattr(kernel, 'app', None)NEWLINE and isinstance(kernel.app, wx.App)NEWLINE ):NEWLINE kernel.app = IPWxApp(redirect=False)NEWLINENEWLINE # The import of wx on Linux sets the handler for signal.SIGINTNEWLINE # to 0. This is a bug in wx or gtk. We fix by just setting itNEWLINE # back to the Python default.NEWLINE import signalNEWLINE if not callable(signal.getsignal(signal.SIGINT)):NEWLINE signal.signal(signal.SIGINT, signal.default_int_handler)NEWLINENEWLINE _loop_wx(kernel.app)NEWLINENEWLINENEWLINE@loop_wx.exitNEWLINEdef loop_wx_exit(kernel):NEWLINE import wxNEWLINE wx.Exit()NEWLINENEWLINENEWLINE@register_integration('tk')NEWLINEdef loop_tk(kernel):NEWLINE """Start a kernel with the Tk event loop."""NEWLINENEWLINE from tkinter import Tk, READABLENEWLINENEWLINE app = Tk()NEWLINE # Capability detection:NEWLINE # per https://docs.python.org/3/library/tkinter.html#file-handlersNEWLINE # file handlers are not available on WindowsNEWLINE if hasattr(app, 'createfilehandler'):NEWLINE # A basic wrapper for structural similarity with the Windows versionNEWLINE class BasicAppWrapper(object):NEWLINE def __init__(self, app):NEWLINE self.app = appNEWLINE self.app.withdraw()NEWLINENEWLINE def process_stream_events(stream, *a, **kw):NEWLINE """fall back to main loop when there's a socket event"""NEWLINE if stream.flush(limit=1):NEWLINE app.tk.deletefilehandler(stream.getsockopt(zmq.FD))NEWLINE app.quit()NEWLINENEWLINE # For Tkinter, we create a Tk object and call its withdraw method.NEWLINE kernel.app_wrapper = BasicAppWrapper(app)NEWLINENEWLINE for stream in kernel.shell_streams:NEWLINE notifier = partial(process_stream_events, stream)NEWLINE # seems to be needed for tkNEWLINE notifier.__name__ = "notifier"NEWLINE app.tk.createfilehandler(stream.getsockopt(zmq.FD), READABLE, notifier)NEWLINE # schedule initial call after startNEWLINE app.after(0, notifier)NEWLINENEWLINE app.mainloop()NEWLINENEWLINE else:NEWLINE doi = kernel.do_one_iterationNEWLINE # Tk uses millisecondsNEWLINE poll_interval = int(1000 * kernel._poll_interval)NEWLINENEWLINE class TimedAppWrapper(object):NEWLINE def __init__(self, app, func):NEWLINE self.app = appNEWLINE self.app.withdraw()NEWLINE self.func = funcNEWLINENEWLINE def on_timer(self):NEWLINE self.func()NEWLINE self.app.after(poll_interval, self.on_timer)NEWLINENEWLINE def start(self):NEWLINE self.on_timer() # Call it once to get things going.NEWLINE self.app.mainloop()NEWLINENEWLINE kernel.app_wrapper = TimedAppWrapper(app, doi)NEWLINE kernel.app_wrapper.start()NEWLINENEWLINENEWLINE@loop_tk.exitNEWLINEdef loop_tk_exit(kernel):NEWLINE kernel.app_wrapper.app.destroy()NEWLINENEWLINENEWLINE@register_integration('gtk')NEWLINEdef loop_gtk(kernel):NEWLINE """Start the kernel, coordinating with the GTK event loop"""NEWLINE from .gui.gtkembed import GTKEmbedNEWLINENEWLINE gtk_kernel = GTKEmbed(kernel)NEWLINE gtk_kernel.start()NEWLINE kernel._gtk = gtk_kernelNEWLINENEWLINENEWLINE@loop_gtk.exitNEWLINEdef loop_gtk_exit(kernel):NEWLINE kernel._gtk.stop()NEWLINENEWLINENEWLINE@register_integration('gtk3')NEWLINEdef loop_gtk3(kernel):NEWLINE """Start the kernel, coordinating with the GTK event loop"""NEWLINE from .gui.gtk3embed import GTKEmbedNEWLINENEWLINE gtk_kernel = GTKEmbed(kernel)NEWLINE gtk_kernel.start()NEWLINE kernel._gtk = gtk_kernelNEWLINENEWLINENEWLINE@loop_gtk3.exitNEWLINEdef loop_gtk3_exit(kernel):NEWLINE kernel._gtk.stop()NEWLINENEWLINENEWLINE@register_integration('osx')NEWLINEdef loop_cocoa(kernel):NEWLINE """Start the kernel, coordinating with the Cocoa CFRunLoop event loopNEWLINE via the matplotlib MacOSX backend.NEWLINE """NEWLINE from ._eventloop_macos import mainloop, stopNEWLINENEWLINE real_excepthook = sys.excepthookNEWLINE def handle_int(etype, value, tb):NEWLINE """don't let KeyboardInterrupts look like crashes"""NEWLINE # wake the eventloop when we get a signalNEWLINE stop()NEWLINE if etype is KeyboardInterrupt:NEWLINE print("KeyboardInterrupt caught in CFRunLoop", file=sys.__stdout__)NEWLINE else:NEWLINE real_excepthook(etype, value, tb)NEWLINENEWLINE while not kernel.shell.exit_now:NEWLINE try:NEWLINE # double nested try/except, to properly catch KeyboardInterruptNEWLINE # due to pyzmq Issue #130NEWLINE try:NEWLINE # don't let interrupts during mainloop invoke crash_handler:NEWLINE sys.excepthook = handle_intNEWLINE mainloop(kernel._poll_interval)NEWLINE for stream in kernel.shell_streams:NEWLINE if stream.flush(limit=1):NEWLINE # events to process, return control to kernelNEWLINE returnNEWLINE except:NEWLINE raiseNEWLINE except KeyboardInterrupt:NEWLINE # Ctrl-C shouldn't crash the kernelNEWLINE print("KeyboardInterrupt caught in kernel", file=sys.__stdout__)NEWLINE finally:NEWLINE # ensure excepthook is restoredNEWLINE sys.excepthook = real_excepthookNEWLINENEWLINENEWLINE@loop_cocoa.exitNEWLINEdef loop_cocoa_exit(kernel):NEWLINE from ._eventloop_macos import stopNEWLINE stop()NEWLINENEWLINENEWLINE@register_integration('asyncio')NEWLINEdef loop_asyncio(kernel):NEWLINE '''Start a kernel with asyncio event loop support.'''NEWLINE import asyncioNEWLINE loop = asyncio.get_event_loop()NEWLINE # loop is already running (e.g. tornado 5), nothing left to doNEWLINE if loop.is_running():NEWLINE returnNEWLINENEWLINE if loop.is_closed():NEWLINE # main loop is closed, create a new oneNEWLINE loop = asyncio.new_event_loop()NEWLINE asyncio.set_event_loop(loop)NEWLINE loop._should_close = FalseNEWLINENEWLINE # pause eventloop when there's an event on a zmq socketNEWLINE def process_stream_events(stream):NEWLINE """fall back to main loop when there's a socket event"""NEWLINE if stream.flush(limit=1):NEWLINE loop.stop()NEWLINENEWLINE for stream in kernel.shell_streams:NEWLINE fd = stream.getsockopt(zmq.FD)NEWLINE notifier = partial(process_stream_events, stream)NEWLINE loop.add_reader(fd, notifier)NEWLINE loop.call_soon(notifier)NEWLINENEWLINE while True:NEWLINE error = NoneNEWLINE try:NEWLINE loop.run_forever()NEWLINE except KeyboardInterrupt:NEWLINE continueNEWLINE except Exception as e:NEWLINE error = eNEWLINE if loop._should_close:NEWLINE loop.close()NEWLINE if error is not None:NEWLINE raise errorNEWLINE breakNEWLINENEWLINENEWLINE@loop_asyncio.exitNEWLINEdef loop_asyncio_exit(kernel):NEWLINE """Exit hook for asyncio"""NEWLINE import asyncioNEWLINE loop = asyncio.get_event_loop()NEWLINENEWLINE @asyncio.coroutineNEWLINE def close_loop():NEWLINE if hasattr(loop, 'shutdown_asyncgens'):NEWLINE yield from loop.shutdown_asyncgens()NEWLINE loop._should_close = TrueNEWLINE loop.stop()NEWLINENEWLINE if loop.is_running():NEWLINE close_loop()NEWLINENEWLINE elif not loop.is_closed():NEWLINE loop.run_until_complete(close_loop)NEWLINE loop.close()NEWLINENEWLINENEWLINEdef enable_gui(gui, kernel=None):NEWLINE """Enable integration with a given GUI"""NEWLINE if gui not in loop_map:NEWLINE e = "Invalid GUI request %r, valid ones are:%s" % (gui, loop_map.keys())NEWLINE raise ValueError(e)NEWLINE if kernel is None:NEWLINE if Application.initialized():NEWLINE kernel = getattr(Application.instance(), 'kernel', None)NEWLINE if kernel is None:NEWLINE raise RuntimeError("You didn't specify a kernel,"NEWLINE " and no IPython Application with a kernel appears to be running."NEWLINE )NEWLINE loop = loop_map[gui]NEWLINE if loop and kernel.eventloop is not None and kernel.eventloop is not loop:NEWLINE raise RuntimeError("Cannot activate multiple GUI eventloops")NEWLINE kernel.eventloop = loopNEWLINE from __future__ import divisionNEWLINENEWLINEimport numpy as npNEWLINEfrom skimage.util.dtype import dtype_rangeNEWLINEfrom skimage import drawNEWLINEfrom skimage import measureNEWLINENEWLINEfrom .plotplugin import PlotPluginNEWLINEfrom ..canvastools import ThickLineToolNEWLINENEWLINENEWLINE__all__ = ['LineProfile']NEWLINENEWLINENEWLINEclass LineProfile(PlotPlugin):NEWLINE """Plugin to compute interpolated intensity under a scan line on an image.NEWLINENEWLINE See PlotPlugin and Plugin classes for additional details.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE maxdist : floatNEWLINE Maximum pixel distance allowed when selecting end point of scan line.NEWLINE limits : tuple or {None, 'image', 'dtype'}NEWLINE (minimum, maximum) intensity limits for plotted profile. The followingNEWLINE special values are defined:NEWLINENEWLINE None : rescale based on min/max intensity along selected scan line.NEWLINE 'image' : fixed scale based on min/max intensity in image.NEWLINE 'dtype' : fixed scale based on min/max intensity of image dtype.NEWLINE """NEWLINE name = 'Line Profile'NEWLINENEWLINE def __init__(self, maxdist=10, epsilon='deprecated',NEWLINE limits='image', **kwargs):NEWLINE super(LineProfile, self).__init__(**kwargs)NEWLINE self.maxdist = maxdistNEWLINE self._limit_type = limitsNEWLINE print(self.help())NEWLINENEWLINE def attach(self, image_viewer):NEWLINE super(LineProfile, self).attach(image_viewer)NEWLINENEWLINE image = image_viewer.original_imageNEWLINENEWLINE if self._limit_type == 'image':NEWLINE self.limits = (np.min(image), np.max(image))NEWLINE elif self._limit_type == 'dtype':NEWLINE self._limit_type = dtype_range[image.dtype.type]NEWLINE elif self._limit_type is None or len(self._limit_type) == 2:NEWLINE self.limits = self._limit_typeNEWLINE else:NEWLINE raise ValueError("Unrecognized `limits`: %s" % self._limit_type)NEWLINENEWLINE if not self._limit_type is None:NEWLINE self.ax.set_ylim(self.limits)NEWLINENEWLINE h, w = image.shape[0:2]NEWLINE x = [w / 3, 2 * w / 3]NEWLINE y = [h / 2] * 2NEWLINENEWLINE self.line_tool = ThickLineTool(self.image_viewer.ax,NEWLINE maxdist=self.maxdist,NEWLINE on_move=self.line_changed,NEWLINE on_change=self.line_changed)NEWLINE self.line_tool.end_points = np.transpose([x, y])NEWLINENEWLINE scan_data = measure.profile_line(image, NEWLINE *self.line_tool.end_points[:, ::-1])NEWLINE self.scan_data = scan_dataNEWLINE if scan_data.ndim == 1:NEWLINE scan_data = scan_data[:, np.newaxis]NEWLINENEWLINE self.reset_axes(scan_data)NEWLINENEWLINE self._autoscale_view()NEWLINENEWLINE def help(self):NEWLINE helpstr = ("Line profile tool",NEWLINE "+ and - keys or mouse scroll changes width of scan line.",NEWLINE "Select and drag ends of the scan line to adjust it.")NEWLINE return '\n'.join(helpstr)NEWLINENEWLINE def get_profiles(self):NEWLINE """Return intensity profile of the selected line.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE end_points: (2, 2) arrayNEWLINE The positions ((x1, y1), (x2, y2)) of the line ends.NEWLINE profile: list of 1d arraysNEWLINE Profile of intensity values. Length 1 (grayscale) or 3 (rgb).NEWLINE """NEWLINE profiles = [data.get_ydata() for data in self.profile]NEWLINE return self.line_tool.end_points, profilesNEWLINENEWLINE def _autoscale_view(self):NEWLINE if self.limits is None:NEWLINE self.ax.autoscale_view(tight=True)NEWLINE else:NEWLINE self.ax.autoscale_view(scaley=False, tight=True)NEWLINENEWLINE def line_changed(self, end_points):NEWLINE x, y = np.transpose(end_points)NEWLINE self.line_tool.end_points = end_pointsNEWLINE scan = measure.profile_line(self.image_viewer.original_image,NEWLINE *end_points[:, ::-1],NEWLINE linewidth=self.line_tool.linewidth)NEWLINE self.scan_data = scanNEWLINE if scan.ndim == 1:NEWLINE scan = scan[:, np.newaxis]NEWLINENEWLINE if scan.shape[1] != len(self.profile):NEWLINE self.reset_axes(scan)NEWLINENEWLINE for i in range(len(scan[0])):NEWLINE self.profile[i].set_xdata(np.arange(scan.shape[0]))NEWLINE self.profile[i].set_ydata(scan[:, i])NEWLINENEWLINE self.ax.relim()NEWLINENEWLINE self._autoscale_view()NEWLINE self.redraw()NEWLINENEWLINE def reset_axes(self, scan_data):NEWLINE # Clear lines outNEWLINE for line in self.ax.lines:NEWLINE self.ax.lines = []NEWLINENEWLINE if scan_data.shape[1] == 1:NEWLINE self.profile = self.ax.plot(scan_data, 'k-')NEWLINE else:NEWLINE self.profile = self.ax.plot(scan_data[:, 0], 'r-',NEWLINE scan_data[:, 1], 'g-',NEWLINE scan_data[:, 2], 'b-')NEWLINENEWLINE def output(self):NEWLINE """Return the drawn line and the resulting scan.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE line_image : (M, N) uint8 array, same shape as imageNEWLINE An array of 0s with the scanned line set to 255.NEWLINE If the linewidth of the line tool is greater than 1,NEWLINE sets the values within the profiled polygon to 128.NEWLINE scan : (P,) or (P, 3) array of int or floatNEWLINE The line scan values across the image.NEWLINE """NEWLINE end_points = self.line_tool.end_pointsNEWLINE line_image = np.zeros(self.image_viewer.original_image.shape[:2],NEWLINE np.uint8)NEWLINE width = self.line_tool.linewidthNEWLINE if width > 1:NEWLINE rp, cp = measure.profile._line_profile_coordinates(NEWLINE *end_points[:, ::-1], linewidth=width)NEWLINE # the points are aliased, so create a polygon using the cornersNEWLINE yp = np.rint(rp[[0, 0, -1, -1],[0, -1, -1, 0]]).astype(int)NEWLINE xp = np.rint(cp[[0, 0, -1, -1],[0, -1, -1, 0]]).astype(int)NEWLINE rp, cp = draw.polygon(yp, xp, line_image.shape)NEWLINE line_image[rp, cp] = 128NEWLINE (x1, y1), (x2, y2) = end_points.astype(int)NEWLINE rr, cc = draw.line(y1, x1, y2, x2)NEWLINE line_image[rr, cc] = 255NEWLINE return line_image, self.scan_dataNEWLINENEWLINE NEWLINEimport numpy as npNEWLINENEWLINEclass Variable():NEWLINENEWLINE def __init__(self, data, creator=None):NEWLINENEWLINE if data is None:NEWLINE raise ValueError("data is not allowed to be None.")NEWLINE if not isinstance(data, np.ndarray):NEWLINE data = np.array(data)NEWLINE NEWLINE self.data = dataNEWLINE self.grad = np.zeros_like(self.data)NEWLINE self.creator = creatorNEWLINENEWLINE def backward(self, init=True):NEWLINE NEWLINE if init is True:NEWLINE self.grad = np.ones_like(self.data)NEWLINENEWLINE funcs = [self.creator] if self.creator is not None else NoneNEWLINE while funcs:NEWLINE f = funcs.pop()NEWLINE y, x = f.output, f.inputNEWLINE x.grad += f.backward(y.grad)NEWLINE if x.creator is not None:NEWLINE funcs.append(x.creator)NEWLINE NEWLINENEWLINE NEWLINENEWLINE import pytestNEWLINEimport osNEWLINEimport numpy as npNEWLINENEWLINEfrom .utils import get_dataNEWLINEfrom ..wb_attack_data_generator import WBAttackGeneratorNEWLINENEWLINENEWLINEdef test_data():NEWLINE """NEWLINE The Data Generator should not crashNEWLINE """NEWLINE model, x_train, x_test, y_train, y_test = get_data()NEWLINE X = np.concatenate((x_train, x_test))NEWLINE Y = np.concatenate((y_train, y_test))NEWLINE wb_generator_train = WBAttackGenerator(model, X, Y,NEWLINE range(0, len(x_train) // 2), range(len(x_train) // 2, len(x_train)),NEWLINE 10, 10, last_layer_only=True)NEWLINE wb_generator_train.write_attack_info(f'{os.getcwd()}/libs/MIA/tests/fixtures/', "mnist_train")NEWLINENEWLINE assert os.path.exists(f'{os.getcwd()}/libs/MIA/tests/fixtures/mnist_train_data_inf.json')NEWLINE assert os.path.exists(f'{os.getcwd()}/libs/MIA/tests/fixtures/mnist_train_target_train_attack_data.h5')NEWLINE assert os.path.exists(f'{os.getcwd()}/libs/MIA/tests/fixtures/mnist_train_target_test_attack_data.h5')NEWLINE #!/usr/bin/env python3NEWLINE# -*- coding: utf-8 -*-NEWLINENEWLINE# Licensed to the Apache Software Foundation (ASF) under oneNEWLINE# or more contributor license agreements. See the NOTICE fileNEWLINE# distributed with this work for additional informationNEWLINE# regarding copyright ownership. The ASF licenses this fileNEWLINE# to you under the Apache License, Version 2.0 (theNEWLINE# "License"); you may not use this file except in complianceNEWLINE# with the License. You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing,NEWLINE# software distributed under the License is distributed on anNEWLINE# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANYNEWLINE# KIND, either express or implied. See the License for theNEWLINE# specific language governing permissions and limitationsNEWLINE# under the License.NEWLINENEWLINE"""Multi arch dockerized build tool.NEWLINENEWLINE"""NEWLINENEWLINE__author__ = 'Pedro Larroy'NEWLINE__version__ = '0.1'NEWLINENEWLINEimport osNEWLINEimport sysNEWLINEimport subprocessNEWLINEimport loggingNEWLINEimport argparseNEWLINEfrom subprocess import check_callNEWLINEimport globNEWLINEimport reNEWLINENEWLINEclass CmdResult(object):NEWLINE def __init__(self, std_out, std_err, status_code):NEWLINE self.std_out = std_outNEWLINE self.std_err = std_errNEWLINE self.status_code = status_code if status_code is not None else 0NEWLINENEWLINE def __str__(self):NEWLINE return "%s, %s, %s" % (self.std_out, self.std_err, self.status_code)NEWLINENEWLINEdef run(cmd, fail_on_error=True):NEWLINE logging.debug("executing shell command:\n" + cmd)NEWLINE proc = subprocess.Popen(NEWLINE cmd,NEWLINE shell=True,NEWLINE stdout=subprocess.PIPE,NEWLINE stderr=subprocess.PIPE,NEWLINE )NEWLINE std_out, std_err = proc.communicate()NEWLINE if fail_on_error:NEWLINE if proc.returncode != 0:NEWLINE logging.warn('Error running command: {}'.format(cmd))NEWLINE assert proc.returncode == 0, std_errNEWLINE res = CmdResult(std_out.decode('utf-8'), std_err.decode('utf-8'), proc.returncode)NEWLINE return resNEWLINENEWLINENEWLINEdef mkdir_p(d):NEWLINE rev_path_list = list()NEWLINE head = dNEWLINE while len(head) and head != os.sep:NEWLINE rev_path_list.append(head)NEWLINE (head, tail) = os.path.split(head)NEWLINENEWLINE rev_path_list.reverse()NEWLINE for p in rev_path_list:NEWLINE try:NEWLINE os.mkdir(p)NEWLINE except OSError as e:NEWLINE if e.errno != 17:NEWLINE raiseNEWLINENEWLINEdef get_arches():NEWLINE """Get a list of architectures given our dockerfiles"""NEWLINE dockerfiles = glob.glob("Dockerfile.build.*")NEWLINE dockerfiles = list(filter(lambda x: x[-1] != '~', dockerfiles))NEWLINE arches = list(map(lambda x: re.sub(r"Dockerfile.build.(.*)", r"\1", x), dockerfiles))NEWLINE arches.sort()NEWLINE return archesNEWLINENEWLINEdef sync_source():NEWLINE logging.info("Copying sources")NEWLINE check_call(["rsync","-a","--delete","--exclude=\".git/\"",'--exclude=/docker_multiarch/',"../","mxnet"])NEWLINENEWLINEdef get_docker_tag(arch):NEWLINE return "mxnet.build.{0}".format(arch)NEWLINENEWLINEdef get_dockerfile(arch):NEWLINE return "Dockerfile.build.{0}".format(arch)NEWLINENEWLINEdef build(arch):NEWLINE """Build the given architecture in the container"""NEWLINE assert arch in get_arches(), "No such architecture {0}, Dockerfile.build.{0} not found".format(arch)NEWLINE logging.info("Building for target platform {0}".format(arch))NEWLINE check_call(["docker", "build",NEWLINE "-f", get_dockerfile(arch),NEWLINE "-t", get_docker_tag(arch),NEWLINE "."])NEWLINENEWLINEdef collect_artifacts(arch):NEWLINE """Collects the artifacts built inside the docker container to the local fs"""NEWLINE def artifact_path(arch):NEWLINE return "{}/build/{}".format(os.getcwd(), arch)NEWLINE logging.info("Collect artifacts from build in {0}".format(artifact_path(arch)))NEWLINE mkdir_p("build/{}".format(arch))NEWLINENEWLINE # Mount artifact_path on /$arch inside the container and copy the build output so we can accessNEWLINE # locally from the host fsNEWLINE check_call(["docker","run",NEWLINE "-v", "{}:/{}".format(artifact_path(arch), arch),NEWLINE get_docker_tag(arch),NEWLINE "bash", "-c", "cp -r /work/build/* /{}".format(arch)])NEWLINENEWLINEdef main():NEWLINE logging.getLogger().setLevel(logging.INFO)NEWLINE logging.basicConfig(format='%(asctime)-15s %(message)s')NEWLINENEWLINE parser = argparse.ArgumentParser()NEWLINE parser.add_argument("-a", "--arch",NEWLINE help="Architecture",NEWLINE type=str)NEWLINENEWLINE parser.add_argument("-l", "--list_arch",NEWLINE help="List architectures",NEWLINE action='store_true')NEWLINE args = parser.parse_args()NEWLINENEWLINE if args.list_arch:NEWLINE arches = get_arches()NEWLINE print(arches)NEWLINENEWLINE elif args.arch:NEWLINE sync_source()NEWLINE build(args.arch)NEWLINE collect_artifacts(args.arch)NEWLINENEWLINE else:NEWLINE arches = get_arches()NEWLINE logging.info("Building for all architectures: {}".format(arches))NEWLINE logging.info("Artifacts will be produced in the build/ directory.")NEWLINE sync_source()NEWLINE for arch in arches:NEWLINE build(arch)NEWLINE collect_artifacts(arch)NEWLINENEWLINE return 0NEWLINENEWLINEif __name__ == '__main__':NEWLINE sys.exit(main())NEWLINENEWLINE """Support to select a date and/or a time."""NEWLINEimport datetimeNEWLINEimport loggingNEWLINEimport typingNEWLINENEWLINEimport voluptuous as volNEWLINENEWLINEfrom homeassistant.const import (NEWLINE ATTR_DATE,NEWLINE ATTR_EDITABLE,NEWLINE ATTR_TIME,NEWLINE CONF_ICON,NEWLINE CONF_ID,NEWLINE CONF_NAME,NEWLINE SERVICE_RELOAD,NEWLINE)NEWLINEfrom homeassistant.core import callbackNEWLINEfrom homeassistant.helpers import collectionNEWLINEimport homeassistant.helpers.config_validation as cvNEWLINEfrom homeassistant.helpers.entity_component import EntityComponentNEWLINEfrom homeassistant.helpers.restore_state import RestoreEntityNEWLINEimport homeassistant.helpers.serviceNEWLINEfrom homeassistant.helpers.storage import StoreNEWLINEfrom homeassistant.helpers.typing import ConfigType, HomeAssistantType, ServiceCallTypeNEWLINEfrom homeassistant.util import dt as dt_utilNEWLINENEWLINE_LOGGER = logging.getLogger(__name__)NEWLINENEWLINEDOMAIN = "input_datetime"NEWLINENEWLINECONF_HAS_DATE = "has_date"NEWLINECONF_HAS_TIME = "has_time"NEWLINECONF_INITIAL = "initial"NEWLINENEWLINEDEFAULT_VALUE = "1970-01-01 00:00:00"NEWLINEDEFAULT_DATE = datetime.date(1970, 1, 1)NEWLINEDEFAULT_TIME = datetime.time(0, 0, 0)NEWLINENEWLINEATTR_DATETIME = "datetime"NEWLINENEWLINESERVICE_SET_DATETIME = "set_datetime"NEWLINESTORAGE_KEY = DOMAINNEWLINESTORAGE_VERSION = 1NEWLINENEWLINECREATE_FIELDS = {NEWLINE vol.Required(CONF_NAME): vol.All(str, vol.Length(min=1)),NEWLINE vol.Optional(CONF_HAS_DATE, default=False): cv.boolean,NEWLINE vol.Optional(CONF_HAS_TIME, default=False): cv.boolean,NEWLINE vol.Optional(CONF_ICON): cv.icon,NEWLINE vol.Optional(CONF_INITIAL): cv.string,NEWLINE}NEWLINEUPDATE_FIELDS = {NEWLINE vol.Optional(CONF_NAME): cv.string,NEWLINE vol.Optional(CONF_HAS_DATE): cv.boolean,NEWLINE vol.Optional(CONF_HAS_TIME): cv.boolean,NEWLINE vol.Optional(CONF_ICON): cv.icon,NEWLINE vol.Optional(CONF_INITIAL): cv.string,NEWLINE}NEWLINENEWLINENEWLINEdef has_date_or_time(conf):NEWLINE """Check at least date or time is true."""NEWLINE if conf[CONF_HAS_DATE] or conf[CONF_HAS_TIME]:NEWLINE return confNEWLINENEWLINE raise vol.Invalid("Entity needs at least a date or a time")NEWLINENEWLINENEWLINECONFIG_SCHEMA = vol.Schema(NEWLINE {NEWLINE DOMAIN: cv.schema_with_slug_keys(NEWLINE vol.All(NEWLINE {NEWLINE vol.Optional(CONF_NAME): cv.string,NEWLINE vol.Optional(CONF_HAS_DATE, default=False): cv.boolean,NEWLINE vol.Optional(CONF_HAS_TIME, default=False): cv.boolean,NEWLINE vol.Optional(CONF_ICON): cv.icon,NEWLINE vol.Optional(CONF_INITIAL): cv.string,NEWLINE },NEWLINE has_date_or_time,NEWLINE )NEWLINE )NEWLINE },NEWLINE extra=vol.ALLOW_EXTRA,NEWLINE)NEWLINERELOAD_SERVICE_SCHEMA = vol.Schema({})NEWLINENEWLINENEWLINEasync def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:NEWLINE """Set up an input datetime."""NEWLINE component = EntityComponent(_LOGGER, DOMAIN, hass)NEWLINE id_manager = collection.IDManager()NEWLINENEWLINE yaml_collection = collection.YamlCollection(NEWLINE logging.getLogger(f"{__name__}.yaml_collection"), id_managerNEWLINE )NEWLINE collection.attach_entity_component_collection(NEWLINE component, yaml_collection, InputDatetime.from_yamlNEWLINE )NEWLINENEWLINE storage_collection = DateTimeStorageCollection(NEWLINE Store(hass, STORAGE_VERSION, STORAGE_KEY),NEWLINE logging.getLogger(f"{__name__}.storage_collection"),NEWLINE id_manager,NEWLINE )NEWLINE collection.attach_entity_component_collection(NEWLINE component, storage_collection, InputDatetimeNEWLINE )NEWLINENEWLINE await yaml_collection.async_load(NEWLINE [{CONF_ID: id_, **cfg} for id_, cfg in config.get(DOMAIN, {}).items()]NEWLINE )NEWLINE await storage_collection.async_load()NEWLINENEWLINE collection.StorageCollectionWebsocket(NEWLINE storage_collection, DOMAIN, DOMAIN, CREATE_FIELDS, UPDATE_FIELDSNEWLINE ).async_setup(hass)NEWLINENEWLINE collection.attach_entity_registry_cleaner(hass, DOMAIN, DOMAIN, yaml_collection)NEWLINE collection.attach_entity_registry_cleaner(hass, DOMAIN, DOMAIN, storage_collection)NEWLINENEWLINE async def reload_service_handler(service_call: ServiceCallType) -> None:NEWLINE """Reload yaml entities."""NEWLINE conf = await component.async_prepare_reload(skip_reset=True)NEWLINE if conf is None:NEWLINE conf = {DOMAIN: {}}NEWLINE await yaml_collection.async_load(NEWLINE [{CONF_ID: id_, **cfg} for id_, cfg in conf.get(DOMAIN, {}).items()]NEWLINE )NEWLINENEWLINE homeassistant.helpers.service.async_register_admin_service(NEWLINE hass,NEWLINE DOMAIN,NEWLINE SERVICE_RELOAD,NEWLINE reload_service_handler,NEWLINE schema=RELOAD_SERVICE_SCHEMA,NEWLINE )NEWLINENEWLINE async def async_set_datetime_service(entity, call):NEWLINE """Handle a call to the input datetime 'set datetime' service."""NEWLINE time = call.data.get(ATTR_TIME)NEWLINE date = call.data.get(ATTR_DATE)NEWLINE dttm = call.data.get(ATTR_DATETIME)NEWLINE if (NEWLINE dttmNEWLINE and (date or time)NEWLINE or entity.has_dateNEWLINE and not (date or dttm)NEWLINE or entity.has_timeNEWLINE and not (time or dttm)NEWLINE ):NEWLINE _LOGGER.error(NEWLINE "Invalid service data for %s input_datetime.set_datetime: %s",NEWLINE entity.entity_id,NEWLINE str(call.data),NEWLINE )NEWLINE returnNEWLINENEWLINE if dttm:NEWLINE date = dttm.date()NEWLINE time = dttm.time()NEWLINE entity.async_set_datetime(date, time)NEWLINENEWLINE component.async_register_entity_service(NEWLINE SERVICE_SET_DATETIME,NEWLINE {NEWLINE vol.Optional(ATTR_DATE): cv.date,NEWLINE vol.Optional(ATTR_TIME): cv.time,NEWLINE vol.Optional(ATTR_DATETIME): cv.datetime,NEWLINE },NEWLINE async_set_datetime_service,NEWLINE )NEWLINENEWLINE return TrueNEWLINENEWLINENEWLINEclass DateTimeStorageCollection(collection.StorageCollection):NEWLINE """Input storage based collection."""NEWLINENEWLINE CREATE_SCHEMA = vol.Schema(vol.All(CREATE_FIELDS, has_date_or_time))NEWLINE UPDATE_SCHEMA = vol.Schema(UPDATE_FIELDS)NEWLINENEWLINE async def _process_create_data(self, data: typing.Dict) -> typing.Dict:NEWLINE """Validate the config is valid."""NEWLINE return self.CREATE_SCHEMA(data)NEWLINENEWLINE @callbackNEWLINE def _get_suggested_id(self, info: typing.Dict) -> str:NEWLINE """Suggest an ID based on the config."""NEWLINE return info[CONF_NAME]NEWLINENEWLINE async def _update_data(self, data: dict, update_data: typing.Dict) -> typing.Dict:NEWLINE """Return a new updated data object."""NEWLINE update_data = self.UPDATE_SCHEMA(update_data)NEWLINE return has_date_or_time({**data, **update_data})NEWLINENEWLINENEWLINEclass InputDatetime(RestoreEntity):NEWLINE """Representation of a datetime input."""NEWLINENEWLINE def __init__(self, config: typing.Dict) -> None:NEWLINE """Initialize a select input."""NEWLINE self._config = configNEWLINE self.editable = TrueNEWLINE self._current_datetime = NoneNEWLINE initial = config.get(CONF_INITIAL)NEWLINE if initial:NEWLINE if self.has_date and self.has_time:NEWLINE self._current_datetime = dt_util.parse_datetime(initial)NEWLINE elif self.has_date:NEWLINE date = dt_util.parse_date(initial)NEWLINE self._current_datetime = datetime.datetime.combine(date, DEFAULT_TIME)NEWLINE else:NEWLINE time = dt_util.parse_time(initial)NEWLINE self._current_datetime = datetime.datetime.combine(DEFAULT_DATE, time)NEWLINENEWLINE @classmethodNEWLINE def from_yaml(cls, config: typing.Dict) -> "InputDatetime":NEWLINE """Return entity instance initialized from yaml storage."""NEWLINE input_dt = cls(config)NEWLINE input_dt.entity_id = f"{DOMAIN}.{config[CONF_ID]}"NEWLINE input_dt.editable = FalseNEWLINE return input_dtNEWLINENEWLINE async def async_added_to_hass(self):NEWLINE """Run when entity about to be added."""NEWLINE await super().async_added_to_hass()NEWLINENEWLINE # Priority 1: Initial valueNEWLINE if self.state is not None:NEWLINE returnNEWLINENEWLINE # Priority 2: Old stateNEWLINE old_state = await self.async_get_last_state()NEWLINE if old_state is None:NEWLINE self._current_datetime = dt_util.parse_datetime(DEFAULT_VALUE)NEWLINE returnNEWLINENEWLINE if self.has_date and self.has_time:NEWLINE date_time = dt_util.parse_datetime(old_state.state)NEWLINE if date_time is None:NEWLINE self._current_datetime = dt_util.parse_datetime(DEFAULT_VALUE)NEWLINE returnNEWLINE self._current_datetime = date_timeNEWLINE elif self.has_date:NEWLINE date = dt_util.parse_date(old_state.state)NEWLINE if date is None:NEWLINE self._current_datetime = dt_util.parse_datetime(DEFAULT_VALUE)NEWLINE returnNEWLINE self._current_datetime = datetime.datetime.combine(date, DEFAULT_TIME)NEWLINE else:NEWLINE time = dt_util.parse_time(old_state.state)NEWLINE if time is None:NEWLINE self._current_datetime = dt_util.parse_datetime(DEFAULT_VALUE)NEWLINE returnNEWLINE self._current_datetime = datetime.datetime.combine(DEFAULT_DATE, time)NEWLINENEWLINE @propertyNEWLINE def should_poll(self):NEWLINE """If entity should be polled."""NEWLINE return FalseNEWLINENEWLINE @propertyNEWLINE def name(self):NEWLINE """Return the name of the select input."""NEWLINE return self._config.get(CONF_NAME)NEWLINENEWLINE @propertyNEWLINE def has_date(self) -> bool:NEWLINE """Return True if entity has date."""NEWLINE return self._config[CONF_HAS_DATE]NEWLINENEWLINE @propertyNEWLINE def has_time(self) -> bool:NEWLINE """Return True if entity has time."""NEWLINE return self._config[CONF_HAS_TIME]NEWLINENEWLINE @propertyNEWLINE def icon(self):NEWLINE """Return the icon to be used for this entity."""NEWLINE return self._config.get(CONF_ICON)NEWLINENEWLINE @propertyNEWLINE def state(self):NEWLINE """Return the state of the component."""NEWLINE if self._current_datetime is None:NEWLINE return NoneNEWLINENEWLINE if self.has_date and self.has_time:NEWLINE return self._current_datetimeNEWLINE if self.has_date:NEWLINE return self._current_datetime.date()NEWLINE return self._current_datetime.time()NEWLINENEWLINE @propertyNEWLINE def state_attributes(self):NEWLINE """Return the state attributes."""NEWLINE attrs = {NEWLINE ATTR_EDITABLE: self.editable,NEWLINE CONF_HAS_DATE: self.has_date,NEWLINE CONF_HAS_TIME: self.has_time,NEWLINE }NEWLINENEWLINE if self._current_datetime is None:NEWLINE return attrsNEWLINENEWLINE if self.has_date and self._current_datetime is not None:NEWLINE attrs["year"] = self._current_datetime.yearNEWLINE attrs["month"] = self._current_datetime.monthNEWLINE attrs["day"] = self._current_datetime.dayNEWLINENEWLINE if self.has_time and self._current_datetime is not None:NEWLINE attrs["hour"] = self._current_datetime.hourNEWLINE attrs["minute"] = self._current_datetime.minuteNEWLINE attrs["second"] = self._current_datetime.secondNEWLINENEWLINE if not self.has_date:NEWLINE attrs["timestamp"] = (NEWLINE self._current_datetime.hour * 3600NEWLINE + self._current_datetime.minute * 60NEWLINE + self._current_datetime.secondNEWLINE )NEWLINE elif not self.has_time:NEWLINE extended = datetime.datetime.combine(NEWLINE self._current_datetime, datetime.time(0, 0)NEWLINE )NEWLINE attrs["timestamp"] = extended.timestamp()NEWLINE else:NEWLINE attrs["timestamp"] = self._current_datetime.timestamp()NEWLINENEWLINE return attrsNEWLINENEWLINE @propertyNEWLINE def unique_id(self) -> typing.Optional[str]:NEWLINE """Return unique id of the entity."""NEWLINE return self._config[CONF_ID]NEWLINENEWLINE @callbackNEWLINE def async_set_datetime(self, date_val, time_val):NEWLINE """Set a new date / time."""NEWLINE if self.has_date and self.has_time and date_val and time_val:NEWLINE self._current_datetime = datetime.datetime.combine(date_val, time_val)NEWLINE elif self.has_date and not self.has_time and date_val:NEWLINE self._current_datetime = datetime.datetime.combine(NEWLINE date_val, self._current_datetime.time()NEWLINE )NEWLINE if self.has_time and not self.has_date and time_val:NEWLINE self._current_datetime = datetime.datetime.combine(NEWLINE self._current_datetime.date(), time_valNEWLINE )NEWLINENEWLINE self.async_write_ha_state()NEWLINENEWLINE async def async_update_config(self, config: typing.Dict) -> None:NEWLINE """Handle when the config is updated."""NEWLINE self._config = configNEWLINE self.async_write_ha_state()NEWLINE from abc import ABCNEWLINEimport loggingNEWLINENEWLINEimport ci_sdrNEWLINEimport fast_bss_evalNEWLINEimport torchNEWLINENEWLINENEWLINEfrom espnet2.enh.loss.criterions.abs_loss import AbsEnhLossNEWLINENEWLINENEWLINEclass TimeDomainLoss(AbsEnhLoss, ABC):NEWLINE """Base class for all time-domain Enhancement loss modules."""NEWLINENEWLINE passNEWLINENEWLINENEWLINEEPS = torch.finfo(torch.get_default_dtype()).epsNEWLINENEWLINENEWLINEclass CISDRLoss(TimeDomainLoss):NEWLINE """CI-SDR lossNEWLINENEWLINE Reference:NEWLINE Convolutive Transfer Function Invariant SDR TrainingNEWLINE Criteria for Multi-Channel Reverberant Speech Separation;NEWLINE C. Boeddeker et al., 2021;NEWLINE https://arxiv.org/abs/2011.15003NEWLINE Args:NEWLINE ref: (Batch, samples)NEWLINE inf: (Batch, samples)NEWLINE filter_length (int): a time-invariant filter that allowsNEWLINE slight distortion via filteringNEWLINE Returns:NEWLINE loss: (Batch,)NEWLINE """NEWLINENEWLINE def __init__(self, filter_length=512, name=None):NEWLINE super().__init__()NEWLINE self.filter_length = filter_lengthNEWLINENEWLINE self._name = "ci_sdr_loss" if name is None else nameNEWLINENEWLINE @propertyNEWLINE def name(self) -> str:NEWLINE return self._nameNEWLINENEWLINE def forward(NEWLINE self,NEWLINE ref: torch.Tensor,NEWLINE inf: torch.Tensor,NEWLINE ) -> torch.Tensor:NEWLINENEWLINE assert ref.shape == inf.shape, (ref.shape, inf.shape)NEWLINENEWLINE return ci_sdr.pt.ci_sdr_loss(NEWLINE inf, ref, compute_permutation=False, filter_length=self.filter_lengthNEWLINE )NEWLINENEWLINENEWLINEclass SNRLoss(TimeDomainLoss):NEWLINE def __init__(self, eps=EPS, name=None):NEWLINE super().__init__()NEWLINE self.eps = float(eps)NEWLINENEWLINE self._name = "snr_loss" if name is None else nameNEWLINENEWLINE @propertyNEWLINE def name(self) -> str:NEWLINE return self._nameNEWLINENEWLINE def forward(NEWLINE self,NEWLINE ref: torch.Tensor,NEWLINE inf: torch.Tensor,NEWLINE ) -> torch.Tensor:NEWLINE # the return tensor should be shape of (batch,)NEWLINENEWLINE noise = inf - refNEWLINENEWLINE snr = 20 * (NEWLINE torch.log10(torch.norm(ref, p=2, dim=1).clamp(min=self.eps))NEWLINE - torch.log10(torch.norm(noise, p=2, dim=1).clamp(min=self.eps))NEWLINE )NEWLINE return -snrNEWLINENEWLINENEWLINEclass SDRLoss(TimeDomainLoss):NEWLINE """SDR loss.NEWLINENEWLINE filter_length: intNEWLINE The length of the distortion filter allowed (default: ``512``)NEWLINE use_cg_iter:NEWLINE If provided, an iterative method is used to solve for the distortionNEWLINE filter coefficients instead of direct Gaussian elimination.NEWLINE This can speed up the computation of the metrics in case the filtersNEWLINE are long. Using a value of 10 here has been shown to provideNEWLINE good accuracy in most cases and is sufficient when using thisNEWLINE loss to train neural separation networks.NEWLINE clamp_db: floatNEWLINE clamp the output value in [-clamp_db, clamp_db]NEWLINE zero_mean: boolNEWLINE When set to True, the mean of all signals is subtracted prior.NEWLINE load_diag:NEWLINE If provided, this small value is added to the diagonal coefficients ofNEWLINE the system metrics when solving for the filter coefficients.NEWLINE This can help stabilize the metric in the case where some of the referenceNEWLINE signals may sometimes be zeroNEWLINE """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE filter_length=512,NEWLINE use_cg_iter=None,NEWLINE clamp_db=None,NEWLINE zero_mean=True,NEWLINE load_diag=None,NEWLINE name=None,NEWLINE ):NEWLINE super().__init__()NEWLINENEWLINE self.filter_length = filter_lengthNEWLINE self.use_cg_iter = use_cg_iterNEWLINE self.clamp_db = clamp_dbNEWLINE self.zero_mean = zero_meanNEWLINE self.load_diag = load_diagNEWLINENEWLINE self._name = "sdr_loss" if name is None else nameNEWLINENEWLINE @propertyNEWLINE def name(self) -> str:NEWLINE return self._nameNEWLINENEWLINE def forward(NEWLINE self,NEWLINE ref: torch.Tensor,NEWLINE est: torch.Tensor,NEWLINE ) -> torch.Tensor:NEWLINE """SDR forward.NEWLINENEWLINE Args:NEWLINE ref: Tensor, (..., n_samples)NEWLINE reference signalNEWLINE est: Tensor (..., n_samples)NEWLINE estimated signalNEWLINENEWLINE Returns:NEWLINE loss: (...,)NEWLINE the SDR loss (negative sdr)NEWLINE """NEWLINENEWLINE sdr_loss = fast_bss_eval.sdr_loss(NEWLINE est=est,NEWLINE ref=ref,NEWLINE filter_length=self.filter_length,NEWLINE use_cg_iter=self.use_cg_iter,NEWLINE zero_mean=self.zero_mean,NEWLINE clamp_db=self.clamp_db,NEWLINE load_diag=self.load_diag,NEWLINE pairwise=False,NEWLINE )NEWLINENEWLINE return sdr_lossNEWLINENEWLINENEWLINEclass SISNRLoss(TimeDomainLoss):NEWLINE """SI-SNR (or named SI-SDR) lossNEWLINENEWLINE A more stable SI-SNR loss with clamp from `fast_bss_eval`.NEWLINENEWLINE Attributes:NEWLINE clamp_db: floatNEWLINE clamp the output value in [-clamp_db, clamp_db]NEWLINE zero_mean: boolNEWLINE When set to True, the mean of all signals is subtracted prior.NEWLINE eps: floatNEWLINE Deprecated. Keeped for compatibility.NEWLINE """NEWLINENEWLINE def __init__(self, clamp_db=None, zero_mean=True, eps=None, name=None):NEWLINE super().__init__()NEWLINE self.clamp_db = clamp_dbNEWLINE self.zero_mean = zero_meanNEWLINE if eps is not None:NEWLINE logging.warning("Eps is deprecated in si_snr loss, set clamp_db instead.")NEWLINENEWLINE self._name = "si_snr_loss" if name is None else nameNEWLINENEWLINE @propertyNEWLINE def name(self) -> str:NEWLINE return self._nameNEWLINENEWLINE def forward(NEWLINE self,NEWLINE ref: torch.Tensor,NEWLINE est: torch.Tensor,NEWLINE ) -> torch.Tensor:NEWLINE """SI-SNR forward.NEWLINENEWLINE Args:NEWLINENEWLINE ref: Tensor, (..., n_samples)NEWLINE reference signalNEWLINE est: Tensor (..., n_samples)NEWLINE estimated signalNEWLINENEWLINE Returns:NEWLINE loss: (...,)NEWLINE the SI-SDR loss (negative si-sdr)NEWLINE """NEWLINENEWLINE si_snr = fast_bss_eval.si_sdr_loss(NEWLINE est=est,NEWLINE ref=ref,NEWLINE zero_mean=self.zero_mean,NEWLINE clamp_db=self.clamp_db,NEWLINE pairwise=False,NEWLINE )NEWLINENEWLINE return si_snrNEWLINENEWLINENEWLINEclass TimeDomainMSE(TimeDomainLoss):NEWLINE def __init__(self, name=None):NEWLINE super().__init__()NEWLINE self._name = "TD_MSE_loss" if name is None else nameNEWLINENEWLINE @propertyNEWLINE def name(self) -> str:NEWLINE return self._nameNEWLINENEWLINE def forward(self, ref, inf) -> torch.Tensor:NEWLINE """Time-domain MSE loss forward.NEWLINENEWLINE Args:NEWLINE ref: (Batch, T) or (Batch, T, C)NEWLINE inf: (Batch, T) or (Batch, T, C)NEWLINE Returns:NEWLINE loss: (Batch,)NEWLINE """NEWLINE assert ref.shape == inf.shape, (ref.shape, inf.shape)NEWLINENEWLINE mseloss = (ref - inf).pow(2)NEWLINE if ref.dim() == 3:NEWLINE mseloss = mseloss.mean(dim=[1, 2])NEWLINE elif ref.dim() == 2:NEWLINE mseloss = mseloss.mean(dim=1)NEWLINE else:NEWLINE raise ValueError(NEWLINE "Invalid input shape: ref={}, inf={}".format(ref.shape, inf.shape)NEWLINE )NEWLINE return mselossNEWLINENEWLINENEWLINEclass TimeDomainL1(TimeDomainLoss):NEWLINE def __init__(self, name=None):NEWLINE super().__init__()NEWLINE self._name = "TD_L1_loss" if name is None else nameNEWLINENEWLINE @propertyNEWLINE def name(self) -> str:NEWLINE return self._nameNEWLINENEWLINE def forward(self, ref, inf) -> torch.Tensor:NEWLINE """Time-domain L1 loss forward.NEWLINENEWLINE Args:NEWLINE ref: (Batch, T) or (Batch, T, C)NEWLINE inf: (Batch, T) or (Batch, T, C)NEWLINE Returns:NEWLINE loss: (Batch,)NEWLINE """NEWLINE assert ref.shape == inf.shape, (ref.shape, inf.shape)NEWLINENEWLINE l1loss = abs(ref - inf)NEWLINE if ref.dim() == 3:NEWLINE l1loss = l1loss.mean(dim=[1, 2])NEWLINE elif ref.dim() == 2:NEWLINE l1loss = l1loss.mean(dim=1)NEWLINE else:NEWLINE raise ValueError(NEWLINE "Invalid input shape: ref={}, inf={}".format(ref.shape, inf.shape)NEWLINE )NEWLINE return l1lossNEWLINE from decimal import DecimalNEWLINENEWLINEimport jsonNEWLINEimport requestsNEWLINENEWLINEfrom cypherpunkpay.prices.price_source import PriceSourceNEWLINENEWLINENEWLINEclass CwatchCoinPriceSource(PriceSource):NEWLINENEWLINE def get(self, coin: str, fiat: str) -> [Decimal, None]:NEWLINE if fiat != 'usd':NEWLINE raise Exception(f'Unsupported fiat {fiat}')NEWLINE try:NEWLINE parsed_json = self._http_client.get_accepting_linkability(f'https://billboard.service.cryptowat.ch/assets?quote=usd&limit=50&sort=marketcap').json()NEWLINE except requests.exceptions.RequestException:NEWLINE return NoneNEWLINE except json.decoder.JSONDecodeError:NEWLINE return NoneNEWLINENEWLINE coins_json = parsed_json['result']['rows']NEWLINE for coin_json in coins_json:NEWLINE if coin_json['symbol'].casefold() == coin:NEWLINE return Decimal(coin_json['price'])NEWLINE def map_list(list, key, default=None):NEWLINE return filter(None, (item.get(key, default) for item in list))NEWLINENEWLINENEWLINEclass FilterModule(object):NEWLINE def filters(self):NEWLINE return {NEWLINE 'select': map_listNEWLINE }NEWLINE import osNEWLINEimport numpy as npNEWLINEimport cv2NEWLINEimport torchNEWLINEimport torchvisionNEWLINEimport carlaNEWLINENEWLINEfrom PIL import Image, ImageDrawNEWLINENEWLINEfrom carla_project.src.image_model import ImageModelNEWLINEfrom carla_project.src.converter import ConverterNEWLINENEWLINEfrom team_code.base_agent import BaseAgentNEWLINEfrom team_code.pid_controller import PIDControllerNEWLINE# additionNEWLINEimport datetimeNEWLINEimport pathlibNEWLINENEWLINEDEBUG = int(os.environ.get('HAS_DISPLAY', 0))NEWLINENEWLINE# additionNEWLINEfrom carla_project.src.carla_env import draw_traffic_lights, get_nearby_lightsNEWLINEfrom carla_project.src.common import CONVERTER, COLORNEWLINEfrom srunner.scenariomanager.carla_data_provider import CarlaDataProviderNEWLINEfrom local_planner import LocalPlannerNEWLINEimport jsonNEWLINEdef get_entry_point():NEWLINE return 'ImageAgent'NEWLINENEWLINENEWLINEdef debug_display(tick_data, target_cam, out, steer, throttle, brake, desired_speed, step):NEWLINE # modificationNEWLINENEWLINE # rgb = np.hstack((tick_data['rgb_left'], tick_data['rgb'], tick_data['rgb_right']))NEWLINENEWLINENEWLINE _rgb = Image.fromarray(tick_data['rgb'])NEWLINE _draw_rgb = ImageDraw.Draw(_rgb)NEWLINE _draw_rgb.ellipse((target_cam[0]-3,target_cam[1]-3,target_cam[0]+3,target_cam[1]+3), (255, 255, 255))NEWLINENEWLINE for x, y in out:NEWLINE x = (x + 1) / 2 * 256NEWLINE y = (y + 1) / 2 * 144NEWLINENEWLINE _draw_rgb.ellipse((x-2, y-2, x+2, y+2), (0, 0, 255))NEWLINENEWLINE _combined = Image.fromarray(np.hstack([tick_data['rgb_left'], _rgb, tick_data['rgb_right']]))NEWLINENEWLINE _combined = _combined.resize((int(256 / _combined.size[1] * _combined.size[0]), 256))NEWLINE _topdown = Image.fromarray(COLOR[CONVERTER[tick_data['topdown']]])NEWLINE _topdown.thumbnail((256, 256))NEWLINE _combined = Image.fromarray(np.hstack((_combined, _topdown)))NEWLINENEWLINENEWLINE _draw = ImageDraw.Draw(_combined)NEWLINE _draw.text((5, 10), 'Steer: %.3f' % steer)NEWLINE _draw.text((5, 30), 'Throttle: %.3f' % throttle)NEWLINE _draw.text((5, 50), 'Brake: %s' % brake)NEWLINE _draw.text((5, 70), 'Speed: %.3f' % tick_data['speed'])NEWLINE _draw.text((5, 90), 'Desired: %.3f' % desired_speed)NEWLINE _draw.text((5, 110), 'Far Command: %s' % str(tick_data['far_command']))NEWLINENEWLINE cv2.imshow('map', cv2.cvtColor(np.array(_combined), cv2.COLOR_BGR2RGB))NEWLINE cv2.waitKey(1)NEWLINENEWLINENEWLINEclass ImageAgent(BaseAgent):NEWLINE def setup(self, path_to_conf_file):NEWLINE super().setup(path_to_conf_file)NEWLINENEWLINE self.converter = Converter()NEWLINE self.net = ImageModel.load_from_checkpoint(path_to_conf_file)NEWLINE self.net.cuda()NEWLINE self.net.eval()NEWLINENEWLINENEWLINENEWLINENEWLINE # addition: modified from leaderboard/team_code/auto_pilot.pyNEWLINE def save(self, steer, throttle, brake, tick_data):NEWLINE # frame = self.step // 10NEWLINE frame = self.stepNEWLINENEWLINE pos = self._get_position(tick_data)NEWLINE far_command = tick_data['far_command']NEWLINE speed = tick_data['speed']NEWLINENEWLINENEWLINENEWLINE center = os.path.join('rgb', ('%04d.png' % frame))NEWLINE left = os.path.join('rgb_left', ('%04d.png' % frame))NEWLINE right = os.path.join('rgb_right', ('%04d.png' % frame))NEWLINE topdown = os.path.join('topdown', ('%04d.png' % frame))NEWLINE rgb_with_car = os.path.join('rgb_with_car', ('%04d.png' % frame))NEWLINENEWLINE data_row = ','.join([str(i) for i in [frame, far_command, speed, steer, throttle, brake, str(center), str(left), str(right)]])NEWLINE with (self.save_path / 'measurements.csv' ).open("a") as f_out:NEWLINE f_out.write(data_row+'\n')NEWLINENEWLINENEWLINE Image.fromarray(tick_data['rgb']).save(self.save_path / center)NEWLINE Image.fromarray(tick_data['rgb_left']).save(self.save_path / left)NEWLINE Image.fromarray(tick_data['rgb_right']).save(self.save_path / right)NEWLINENEWLINE # additionNEWLINE Image.fromarray(COLOR[CONVERTER[tick_data['topdown']]]).save(self.save_path / topdown)NEWLINE Image.fromarray(tick_data['rgb_with_car']).save(self.save_path / rgb_with_car)NEWLINENEWLINENEWLINENEWLINE ########################################################################NEWLINE # log necessary info for action-basedNEWLINE if self.args.save_action_based_measurements:NEWLINE from affordances import get_driving_affordancesNEWLINENEWLINE self._pedestrian_forbidden_distance = 10.0NEWLINE self._pedestrian_max_detected_distance = 50.0NEWLINE self._vehicle_forbidden_distance = 10.0NEWLINE self._vehicle_max_detected_distance = 50.0NEWLINE self._tl_forbidden_distance = 10.0NEWLINE self._tl_max_detected_distance = 50.0NEWLINE self._speed_detected_distance = 10.0NEWLINENEWLINE self._default_target_speed = 10NEWLINE self._angle = NoneNEWLINENEWLINE current_affordances = get_driving_affordances(self, self._pedestrian_forbidden_distance, self._pedestrian_max_detected_distance, self._vehicle_forbidden_distance, self._vehicle_max_detected_distance, self._tl_forbidden_distance, self._tl_max_detected_distance, self._angle_rad, self._default_target_speed, self._target_speed, self._speed_detected_distance, angle=True)NEWLINENEWLINE is_vehicle_hazard = current_affordances['is_vehicle_hazard']NEWLINE is_red_tl_hazard = current_affordances['is_red_tl_hazard']NEWLINE is_pedestrian_hazard = current_affordances['is_pedestrian_hazard']NEWLINE forward_speed = current_affordances['forward_speed']NEWLINE relative_angle = current_affordances['relative_angle']NEWLINE target_speed = current_affordances['target_speed']NEWLINE closest_pedestrian_distance = current_affordances['closest_pedestrian_distance']NEWLINE closest_vehicle_distance = current_affordances['closest_vehicle_distance']NEWLINE closest_red_tl_distance = current_affordances['closest_red_tl_distance']NEWLINENEWLINENEWLINENEWLINE log_folder = str(self.save_path / 'affordance_measurements')NEWLINE if not os.path.exists(log_folder):NEWLINE os.mkdir(log_folder)NEWLINE log_path = os.path.join(log_folder, f'{self.step:06}.json')NEWLINENEWLINENEWLINE ego_transform = self._vehicle.get_transform()NEWLINE ego_location = ego_transform.locationNEWLINE ego_rotation = ego_transform.rotationNEWLINE ego_velocity = self._vehicle.get_velocity()NEWLINENEWLINE brake_noise = 0.0NEWLINE throttle_noise = 0.0 # 1.0 -> 0.0NEWLINE steer_noise = 0.0 # NaN -> 0.0NEWLINENEWLINE # class RoadOptionNEWLINE map_roadoption_to_action_based_roadoption = {-1:2, 1:3, 2:4, 3:5, 4:2, 5:2, 6:2}NEWLINENEWLINE # save info for action-based repNEWLINE json_log_data = {NEWLINE "brake": float(brake),NEWLINE "closest_red_tl_distance": closest_red_tl_distance,NEWLINE "throttle": throttle,NEWLINE "directions": float(map_roadoption_to_action_based_roadoption[far_command.value]),NEWLINE "brake_noise": brake_noise,NEWLINE "is_red_tl_hazard": is_red_tl_hazard,NEWLINE "opponents": {},NEWLINE "closest_pedestrian_distance": closest_pedestrian_distance,NEWLINE "is_pedestrian_hazard": is_pedestrian_hazard,NEWLINE "lane": {},NEWLINE "is_vehicle_hazard": is_vehicle_hazard,NEWLINE "throttle_noise": throttle_noise,NEWLINE "ego_actor": {NEWLINE "velocity": [NEWLINE ego_velocity.x,NEWLINE ego_velocity.y,NEWLINE ego_velocity.zNEWLINE ],NEWLINE "position": [NEWLINE ego_location.x,NEWLINE ego_location.y,NEWLINE ego_location.zNEWLINE ],NEWLINE "orientation": [NEWLINE ego_rotation.roll,NEWLINE ego_rotation.pitch,NEWLINE ego_rotation.yawNEWLINE ]NEWLINE },NEWLINE "hand_brake": False,NEWLINE "steer_noise": steer_noise,NEWLINE "reverse": False,NEWLINE "relative_angle": relative_angle,NEWLINE "closest_vehicle_distance": closest_vehicle_distance,NEWLINE "walkers": {},NEWLINE "forward_speed": forward_speed,NEWLINE "steer": steer,NEWLINE "target_speed": target_speedNEWLINE }NEWLINENEWLINE with open(log_path, 'w') as f_out:NEWLINE json.dump(json_log_data, f_out, indent=4)NEWLINENEWLINENEWLINE def _init(self):NEWLINE super()._init()NEWLINENEWLINE self._turn_controller = PIDController(K_P=1.25, K_I=0.75, K_D=0.3, n=40)NEWLINE self._speed_controller = PIDController(K_P=5.0, K_I=0.5, K_D=1.0, n=40)NEWLINENEWLINE # addition:NEWLINE self._vehicle = CarlaDataProvider.get_hero_actor()NEWLINE self._world = self._vehicle.get_world()NEWLINENEWLINENEWLINE # -------------------------------------------------------NEWLINE # add a local_planner in order to estimate relative angleNEWLINE # self.target_speed = 10NEWLINE # args_lateral_dict = {NEWLINE # 'K_P': 1,NEWLINE # 'K_D': 0.4,NEWLINE # 'K_I': 0,NEWLINE # 'dt': 1.0/10.0}NEWLINE # self._local_planner = LocalPlanner(NEWLINE # self._vehicle, opt_dict={'target_speed' : self.target_speed,NEWLINE # 'lateral_control_dict':args_lateral_dict})NEWLINE # self._hop_resolution = 2.0NEWLINE # self._path_seperation_hop = 2NEWLINE # self._path_seperation_threshold = 0.5NEWLINE # self._grp = NoneNEWLINE #NEWLINE # self._map = CarlaDataProvider.get_map()NEWLINE # route = [(self._map.get_waypoint(x[0].location), x[1]) for x in self._global_plan_world_coord]NEWLINE #NEWLINE # self._local_planner.set_global_plan(route)NEWLINENEWLINENEWLINE def tick(self, input_data):NEWLINENEWLINENEWLINENEWLINE result = super().tick(input_data)NEWLINE result['image'] = np.concatenate(tuple(result[x] for x in ['rgb', 'rgb_left', 'rgb_right']), -1)NEWLINENEWLINENEWLINE rgb_with_car = cv2.cvtColor(input_data['rgb_with_car'][1][:, :, :3], cv2.COLOR_BGR2RGB)NEWLINE result['rgb_with_car'] = rgb_with_carNEWLINENEWLINE result['radar_central'] = input_data['radar_central']NEWLINENEWLINE theta = result['compass']NEWLINE theta = 0.0 if np.isnan(theta) else thetaNEWLINE theta = theta + np.pi / 2NEWLINE R = np.array([NEWLINE [np.cos(theta), -np.sin(theta)],NEWLINE [np.sin(theta), np.cos(theta)],NEWLINE ])NEWLINENEWLINE gps = self._get_position(result)NEWLINE # modificationNEWLINE far_node, far_command = self._command_planner.run_step(gps)NEWLINE target = R.T.dot(far_node - gps)NEWLINE target *= 5.5NEWLINE target += [128, 256]NEWLINE target = np.clip(target, 0, 256)NEWLINENEWLINE result['target'] = targetNEWLINE # addition:NEWLINE self._actors = self._world.get_actors()NEWLINE self._traffic_lights = get_nearby_lights(self._vehicle, self._actors.filter('*traffic_light*'))NEWLINE result['far_command'] = far_commandNEWLINE topdown = input_data['map'][1][:, :, 2]NEWLINE topdown = draw_traffic_lights(topdown, self._vehicle, self._traffic_lights)NEWLINE result['topdown'] = topdownNEWLINENEWLINENEWLINE return resultNEWLINENEWLINE @torch.no_grad()NEWLINE def run_step_using_learned_controller(self, input_data, timestamp):NEWLINE if not self.initialized:NEWLINE self._init()NEWLINENEWLINE tick_data = self.tick(input_data)NEWLINENEWLINE img = torchvision.transforms.functional.to_tensor(tick_data['image'])NEWLINE img = img[None].cuda()NEWLINENEWLINE target = torch.from_numpy(tick_data['target'])NEWLINE target = target[None].cuda()NEWLINENEWLINE import randomNEWLINE torch.manual_seed(2)NEWLINE torch.cuda.manual_seed_all(2)NEWLINE torch.backends.cudnn.deterministic = TrueNEWLINE np.random.seed(1)NEWLINE random.seed(1)NEWLINE device = torch.device('cuda')NEWLINE torch.backends.cudnn.benchmark = FalseNEWLINENEWLINE points, (target_cam, _) = self.net.forward(img, target)NEWLINE control = self.net.controller(points).cpu().squeeze()NEWLINENEWLINE steer = control[0].item()NEWLINE desired_speed = control[1].item()NEWLINE speed = tick_data['speed']NEWLINENEWLINE brake = desired_speed < 0.4 or (speed / desired_speed) > 1.1NEWLINENEWLINE delta = np.clip(desired_speed - speed, 0.0, 0.25)NEWLINE throttle = self._speed_controller.step(delta)NEWLINE throttle = np.clip(throttle, 0.0, 0.75)NEWLINE throttle = throttle if not brake else 0.0NEWLINENEWLINE control = carla.VehicleControl()NEWLINE control.steer = steerNEWLINE control.throttle = throttleNEWLINE control.brake = float(brake)NEWLINENEWLINE if DEBUG:NEWLINE debug_display(NEWLINE tick_data, target_cam.squeeze(), points.cpu().squeeze(),NEWLINE steer, throttle, brake, desired_speed,NEWLINE self.step)NEWLINENEWLINE return controlNEWLINENEWLINE @torch.no_grad()NEWLINE def run_step(self, input_data, timestamp):NEWLINE if not self.initialized:NEWLINE self._init()NEWLINENEWLINE tick_data = self.tick(input_data)NEWLINE radar_data = tick_data['radar_central'][1]NEWLINENEWLINENEWLINENEWLINE img = torchvision.transforms.functional.to_tensor(tick_data['image'])NEWLINE img = img[None].cuda()NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE target = torch.from_numpy(tick_data['target'])NEWLINE target = target[None].cuda()NEWLINENEWLINE points, (target_cam, _) = self.net.forward(img, target)NEWLINE points_cam = points.clone().cpu()NEWLINENEWLINE if self.step == 0:NEWLINE print('\n'*5)NEWLINE print('step :', self.step)NEWLINE # print('radar')NEWLINE # print(radar_data.shape)NEWLINE # print(radar_data)NEWLINE # print(np.max(radar_data, axis=0))NEWLINE print('image', np.sum(tick_data['image']))NEWLINE # print('img', torch.sum(img))NEWLINE # print('target', target)NEWLINE # print('points', points)NEWLINE print('\n'*5)NEWLINENEWLINE points_cam[..., 0] = (points_cam[..., 0] + 1) / 2 * img.shape[-1]NEWLINE points_cam[..., 1] = (points_cam[..., 1] + 1) / 2 * img.shape[-2]NEWLINE points_cam = points_cam.squeeze()NEWLINE points_world = self.converter.cam_to_world(points_cam).numpy()NEWLINENEWLINENEWLINE aim = (points_world[1] + points_world[0]) / 2.0NEWLINE angle = np.degrees(np.pi / 2 - np.arctan2(aim[1], aim[0]))NEWLINE self._angle_rad = np.radians(angle)NEWLINE angle = angle / 90NEWLINE steer = self._turn_controller.step(angle)NEWLINE steer = np.clip(steer, -1.0, 1.0)NEWLINENEWLINE desired_speed = np.linalg.norm(points_world[0] - points_world[1]) * 2.0NEWLINE # desired_speed *= (1 - abs(angle)) ** 2NEWLINE self._target_speed = desired_speedNEWLINE speed = tick_data['speed']NEWLINENEWLINE brake = desired_speed < 0.4 or (speed / desired_speed) > 1.1NEWLINENEWLINE delta = np.clip(desired_speed - speed, 0.0, 0.25)NEWLINE throttle = self._speed_controller.step(delta)NEWLINE throttle = np.clip(throttle, 0.0, 0.75)NEWLINE throttle = throttle if not brake else 0.0NEWLINENEWLINE control = carla.VehicleControl()NEWLINE control.steer = steerNEWLINE control.throttle = throttleNEWLINE control.brake = float(brake)NEWLINENEWLINE if DEBUG:NEWLINE debug_display(tick_data, target_cam.squeeze(), points.cpu().squeeze(), steer, throttle, brake, desired_speed, self.step)NEWLINENEWLINE # addition: from leaderboard/team_code/auto_pilot.pyNEWLINE if self.step == 0:NEWLINE title_row = ','.join(['frame_id', 'far_command', 'speed', 'steering', 'throttle', 'brake', 'center', 'left', 'right'])NEWLINE with (self.save_path / 'measurements.csv' ).open("a") as f_out:NEWLINE f_out.write(title_row+'\n')NEWLINE if self.step % 1 == 0:NEWLINE self.gather_info((steer, throttle, float(brake), speed))NEWLINENEWLINE record_every_n_steps = self.record_every_n_stepNEWLINE if self.step % record_every_n_steps == 0:NEWLINE self.save(steer, throttle, brake, tick_data)NEWLINE return controlNEWLINE # Author: Steven J. Bethard .NEWLINENEWLINE"""Command-line parsing libraryNEWLINENEWLINEThis module is an optparse-inspired command-line parsing library that:NEWLINENEWLINE - handles both optional and positional argumentsNEWLINE - produces highly informative usage messagesNEWLINE - supports parsers that dispatch to sub-parsersNEWLINENEWLINEThe following is a simple usage example that sums integers from theNEWLINEcommand-line and writes the result to a file::NEWLINENEWLINE parser = argparse.ArgumentParser(NEWLINE description='sum the integers at the command line')NEWLINE parser.add_argument(NEWLINE 'integers', metavar='int', nargs='+', type=int,NEWLINE help='an integer to be summed')NEWLINE parser.add_argument(NEWLINE '--log', default=sys.stdout, type=argparse.FileType('w'),NEWLINE help='the file where the sum should be written')NEWLINE args = parser.parse_args()NEWLINE args.log.write('%s' % sum(args.integers))NEWLINE args.log.close()NEWLINENEWLINEThe module contains the following public classes:NEWLINENEWLINE - ArgumentParser -- The main entry point for command-line parsing. As theNEWLINE example above shows, the add_argument() method is used to populateNEWLINE the parser with actions for optional and positional arguments. ThenNEWLINE the parse_args() method is invoked to convert the args at theNEWLINE command-line into an object with attributes.NEWLINENEWLINE - ArgumentError -- The exception raised by ArgumentParser objects whenNEWLINE there are errors with the parser's actions. Errors raised whileNEWLINE parsing the command-line are caught by ArgumentParser and emittedNEWLINE as command-line messages.NEWLINENEWLINE - FileType -- A factory for defining types of files to be created. As theNEWLINE example above shows, instances of FileType are typically passed asNEWLINE the type= argument of add_argument() calls.NEWLINENEWLINE - Action -- The base class for parser actions. Typically actions areNEWLINE selected by passing strings like 'store_true' or 'append_const' toNEWLINE the action= argument of add_argument(). However, for greaterNEWLINE customization of ArgumentParser actions, subclasses of Action mayNEWLINE be defined and passed as the action= argument.NEWLINENEWLINE - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,NEWLINE ArgumentDefaultsHelpFormatter -- Formatter classes whichNEWLINE may be passed as the formatter_class= argument to theNEWLINE ArgumentParser constructor. HelpFormatter is the default,NEWLINE RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parserNEWLINE not to change the formatting for help text, andNEWLINE ArgumentDefaultsHelpFormatter adds information about argument defaultsNEWLINE to the help.NEWLINENEWLINEAll other classes in this module are considered implementation details.NEWLINE(Also note that HelpFormatter and RawDescriptionHelpFormatter are onlyNEWLINEconsidered public as object names -- the API of the formatter objects isNEWLINEstill considered an implementation detail.)NEWLINE"""NEWLINENEWLINE__version__ = '1.1'NEWLINE__all__ = [NEWLINE 'ArgumentParser',NEWLINE 'ArgumentError',NEWLINE 'ArgumentTypeError',NEWLINE 'FileType',NEWLINE 'HelpFormatter',NEWLINE 'ArgumentDefaultsHelpFormatter',NEWLINE 'RawDescriptionHelpFormatter',NEWLINE 'RawTextHelpFormatter',NEWLINE 'Namespace',NEWLINE 'Action',NEWLINE 'ONE_OR_MORE',NEWLINE 'OPTIONAL',NEWLINE 'PARSER',NEWLINE 'REMAINDER',NEWLINE 'SUPPRESS',NEWLINE 'ZERO_OR_MORE',NEWLINE]NEWLINENEWLINENEWLINEimport collections as _collectionsNEWLINEimport copy as _copyNEWLINEimport os as _osNEWLINEimport re as _reNEWLINEimport sys as _sysNEWLINEimport textwrap as _textwrapNEWLINENEWLINEfrom gettext import gettext as _NEWLINENEWLINENEWLINEdef _callable(obj):NEWLINE return hasattr(obj, '__call__') or hasattr(obj, '__bases__')NEWLINENEWLINENEWLINESUPPRESS = '==SUPPRESS=='NEWLINENEWLINEOPTIONAL = '?'NEWLINEZERO_OR_MORE = '*'NEWLINEONE_OR_MORE = '+'NEWLINEPARSER = 'A...'NEWLINEREMAINDER = '...'NEWLINE_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'NEWLINENEWLINE# =============================NEWLINE# Utility functions and classesNEWLINE# =============================NEWLINENEWLINEclass _AttributeHolder(object):NEWLINE """Abstract base class that provides __repr__.NEWLINENEWLINE The __repr__ method returns a string in the format::NEWLINE ClassName(attr=name, attr=name, ...)NEWLINE The attributes are determined either by a class-level attribute,NEWLINE '_kwarg_names', or by inspecting the instance __dict__.NEWLINE """NEWLINENEWLINE def __repr__(self):NEWLINE type_name = type(self).__name__NEWLINE arg_strings = []NEWLINE for arg in self._get_args():NEWLINE arg_strings.append(repr(arg))NEWLINE for name, value in self._get_kwargs():NEWLINE arg_strings.append('%s=%r' % (name, value))NEWLINE return '%s(%s)' % (type_name, ', '.join(arg_strings))NEWLINENEWLINE def _get_kwargs(self):NEWLINE return sorted(self.__dict__.items())NEWLINENEWLINE def _get_args(self):NEWLINE return []NEWLINENEWLINENEWLINEdef _ensure_value(namespace, name, value):NEWLINE if getattr(namespace, name, None) is None:NEWLINE setattr(namespace, name, value)NEWLINE return getattr(namespace, name)NEWLINENEWLINENEWLINE# ===============NEWLINE# Formatting HelpNEWLINE# ===============NEWLINENEWLINEclass HelpFormatter(object):NEWLINE """Formatter for generating usage messages and argument help strings.NEWLINENEWLINE Only the name of this class is considered a public API. All the methodsNEWLINE provided by the class are considered an implementation detail.NEWLINE """NEWLINENEWLINE def __init__(self,NEWLINE prog,NEWLINE indent_increment=2,NEWLINE max_help_position=24,NEWLINE width=None):NEWLINENEWLINE # default setting for widthNEWLINE if width is None:NEWLINE try:NEWLINE width = int(_os.environ['COLUMNS'])NEWLINE except (KeyError, ValueError):NEWLINE width = 80NEWLINE width -= 2NEWLINENEWLINE self._prog = progNEWLINE self._indent_increment = indent_incrementNEWLINE self._max_help_position = max_help_positionNEWLINE self._max_help_position = min(max_help_position,NEWLINE max(width - 20, indent_increment * 2))NEWLINE self._width = widthNEWLINENEWLINE self._current_indent = 0NEWLINE self._level = 0NEWLINE self._action_max_length = 0NEWLINENEWLINE self._root_section = self._Section(self, None)NEWLINE self._current_section = self._root_sectionNEWLINENEWLINE self._whitespace_matcher = _re.compile(r'\s+')NEWLINE self._long_break_matcher = _re.compile(r'\n\n\n+')NEWLINENEWLINE # ===============================NEWLINE # Section and indentation methodsNEWLINE # ===============================NEWLINE def _indent(self):NEWLINE self._current_indent += self._indent_incrementNEWLINE self._level += 1NEWLINENEWLINE def _dedent(self):NEWLINE self._current_indent -= self._indent_incrementNEWLINE assert self._current_indent >= 0, 'Indent decreased below 0.'NEWLINE self._level -= 1NEWLINENEWLINE class _Section(object):NEWLINENEWLINE def __init__(self, formatter, parent, heading=None):NEWLINE self.formatter = formatterNEWLINE self.parent = parentNEWLINE self.heading = headingNEWLINE self.items = []NEWLINENEWLINE def format_help(self):NEWLINE # format the indented sectionNEWLINE if self.parent is not None:NEWLINE self.formatter._indent()NEWLINE join = self.formatter._join_partsNEWLINE for func, args in self.items:NEWLINE func(*args)NEWLINE item_help = join([func(*args) for func, args in self.items])NEWLINE if self.parent is not None:NEWLINE self.formatter._dedent()NEWLINENEWLINE # return nothing if the section was emptyNEWLINE if not item_help:NEWLINE return ''NEWLINENEWLINE # add the heading if the section was non-emptyNEWLINE if self.heading is not SUPPRESS and self.heading is not None:NEWLINE current_indent = self.formatter._current_indentNEWLINE heading = '%*s%s:\n' % (current_indent, '', self.heading)NEWLINE else:NEWLINE heading = ''NEWLINENEWLINE # join the section-initial newline, the heading and the helpNEWLINE return join(['\n', heading, item_help, '\n'])NEWLINENEWLINE def _add_item(self, func, args):NEWLINE self._current_section.items.append((func, args))NEWLINENEWLINE # ========================NEWLINE # Message building methodsNEWLINE # ========================NEWLINE def start_section(self, heading):NEWLINE self._indent()NEWLINE section = self._Section(self, self._current_section, heading)NEWLINE self._add_item(section.format_help, [])NEWLINE self._current_section = sectionNEWLINENEWLINE def end_section(self):NEWLINE self._current_section = self._current_section.parentNEWLINE self._dedent()NEWLINENEWLINE def add_text(self, text):NEWLINE if text is not SUPPRESS and text is not None:NEWLINE self._add_item(self._format_text, [text])NEWLINENEWLINE def add_usage(self, usage, actions, groups, prefix=None):NEWLINE if usage is not SUPPRESS:NEWLINE args = usage, actions, groups, prefixNEWLINE self._add_item(self._format_usage, args)NEWLINENEWLINE def add_argument(self, action):NEWLINE if action.help is not SUPPRESS:NEWLINENEWLINE # find all invocationsNEWLINE get_invocation = self._format_action_invocationNEWLINE invocations = [get_invocation(action)]NEWLINE for subaction in self._iter_indented_subactions(action):NEWLINE invocations.append(get_invocation(subaction))NEWLINENEWLINE # update the maximum item lengthNEWLINE invocation_length = max([len(s) for s in invocations])NEWLINE action_length = invocation_length + self._current_indentNEWLINE self._action_max_length = max(self._action_max_length,NEWLINE action_length)NEWLINENEWLINE # add the item to the listNEWLINE self._add_item(self._format_action, [action])NEWLINENEWLINE def add_arguments(self, actions):NEWLINE for action in actions:NEWLINE self.add_argument(action)NEWLINENEWLINE # =======================NEWLINE # Help-formatting methodsNEWLINE # =======================NEWLINE def format_help(self):NEWLINE help = self._root_section.format_help()NEWLINE if help:NEWLINE help = self._long_break_matcher.sub('\n\n', help)NEWLINE help = help.strip('\n') + '\n'NEWLINE return helpNEWLINENEWLINE def _join_parts(self, part_strings):NEWLINE return ''.join([partNEWLINE for part in part_stringsNEWLINE if part and part is not SUPPRESS])NEWLINENEWLINE def _format_usage(self, usage, actions, groups, prefix):NEWLINE if prefix is None:NEWLINE prefix = _('usage: ')NEWLINENEWLINE # if usage is specified, use thatNEWLINE if usage is not None:NEWLINE usage = usage % dict(prog=self._prog)NEWLINENEWLINE # if no optionals or positionals are available, usage is just progNEWLINE elif usage is None and not actions:NEWLINE usage = '%(prog)s' % dict(prog=self._prog)NEWLINENEWLINE # if optionals and positionals are available, calculate usageNEWLINE elif usage is None:NEWLINE prog = '%(prog)s' % dict(prog=self._prog)NEWLINENEWLINE # split optionals from positionalsNEWLINE optionals = []NEWLINE positionals = []NEWLINE for action in actions:NEWLINE if action.option_strings:NEWLINE optionals.append(action)NEWLINE else:NEWLINE positionals.append(action)NEWLINENEWLINE # build full usage stringNEWLINE format = self._format_actions_usageNEWLINE action_usage = format(optionals + positionals, groups)NEWLINE usage = ' '.join([s for s in [prog, action_usage] if s])NEWLINENEWLINE # wrap the usage parts if it's too longNEWLINE text_width = self._width - self._current_indentNEWLINE if len(prefix) + len(usage) > text_width:NEWLINENEWLINE # break usage into wrappable partsNEWLINE part_regexp = (NEWLINE r'\(.*?\)+(?=\s|$)|'NEWLINE r'\[.*?\]+(?=\s|$)|'NEWLINE r'\S+'NEWLINE )NEWLINE opt_usage = format(optionals, groups)NEWLINE pos_usage = format(positionals, groups)NEWLINE opt_parts = _re.findall(part_regexp, opt_usage)NEWLINE pos_parts = _re.findall(part_regexp, pos_usage)NEWLINE assert ' '.join(opt_parts) == opt_usageNEWLINE assert ' '.join(pos_parts) == pos_usageNEWLINENEWLINE # helper for wrapping linesNEWLINE def get_lines(parts, indent, prefix=None):NEWLINE lines = []NEWLINE line = []NEWLINE if prefix is not None:NEWLINE line_len = len(prefix) - 1NEWLINE else:NEWLINE line_len = len(indent) - 1NEWLINE for part in parts:NEWLINE if line_len + 1 + len(part) > text_width and line:NEWLINE lines.append(indent + ' '.join(line))NEWLINE line = []NEWLINE line_len = len(indent) - 1NEWLINE line.append(part)NEWLINE line_len += len(part) + 1NEWLINE if line:NEWLINE lines.append(indent + ' '.join(line))NEWLINE if prefix is not None:NEWLINE lines[0] = lines[0][len(indent):]NEWLINE return linesNEWLINENEWLINE # if prog is short, follow it with optionals or positionalsNEWLINE if len(prefix) + len(prog) <= 0.75 * text_width:NEWLINE indent = ' ' * (len(prefix) + len(prog) + 1)NEWLINE if opt_parts:NEWLINE lines = get_lines([prog] + opt_parts, indent, prefix)NEWLINE lines.extend(get_lines(pos_parts, indent))NEWLINE elif pos_parts:NEWLINE lines = get_lines([prog] + pos_parts, indent, prefix)NEWLINE else:NEWLINE lines = [prog]NEWLINENEWLINE # if prog is long, put it on its own lineNEWLINE else:NEWLINE indent = ' ' * len(prefix)NEWLINE parts = opt_parts + pos_partsNEWLINE lines = get_lines(parts, indent)NEWLINE if len(lines) > 1:NEWLINE lines = []NEWLINE lines.extend(get_lines(opt_parts, indent))NEWLINE lines.extend(get_lines(pos_parts, indent))NEWLINE lines = [prog] + linesNEWLINENEWLINE # join lines into usageNEWLINE usage = '\n'.join(lines)NEWLINENEWLINE # prefix with 'usage:'NEWLINE return '%s%s\n\n' % (prefix, usage)NEWLINENEWLINE def _format_actions_usage(self, actions, groups):NEWLINE # find group indices and identify actions in groupsNEWLINE group_actions = set()NEWLINE inserts = {}NEWLINE for group in groups:NEWLINE try:NEWLINE start = actions.index(group._group_actions[0])NEWLINE except ValueError:NEWLINE continueNEWLINE else:NEWLINE end = start + len(group._group_actions)NEWLINE if actions[start:end] == group._group_actions:NEWLINE for action in group._group_actions:NEWLINE group_actions.add(action)NEWLINE if not group.required:NEWLINE if start in inserts:NEWLINE inserts[start] += ' ['NEWLINE else:NEWLINE inserts[start] = '['NEWLINE inserts[end] = ']'NEWLINE else:NEWLINE if start in inserts:NEWLINE inserts[start] += ' ('NEWLINE else:NEWLINE inserts[start] = '('NEWLINE inserts[end] = ')'NEWLINE for i in range(start + 1, end):NEWLINE inserts[i] = '|'NEWLINENEWLINE # collect all actions format stringsNEWLINE parts = []NEWLINE for i, action in enumerate(actions):NEWLINENEWLINE # suppressed arguments are marked with NoneNEWLINE # remove | separators for suppressed argumentsNEWLINE if action.help is SUPPRESS:NEWLINE parts.append(None)NEWLINE if inserts.get(i) == '|':NEWLINE inserts.pop(i)NEWLINE elif inserts.get(i + 1) == '|':NEWLINE inserts.pop(i + 1)NEWLINENEWLINE # produce all arg stringsNEWLINE elif not action.option_strings:NEWLINE part = self._format_args(action, action.dest)NEWLINENEWLINE # if it's in a group, strip the outer []NEWLINE if action in group_actions:NEWLINE if part[0] == '[' and part[-1] == ']':NEWLINE part = part[1:-1]NEWLINENEWLINE # add the action string to the listNEWLINE parts.append(part)NEWLINENEWLINE # produce the first way to invoke the option in bracketsNEWLINE else:NEWLINE option_string = action.option_strings[0]NEWLINENEWLINE # if the Optional doesn't take a value, format is:NEWLINE # -s or --longNEWLINE if action.nargs == 0:NEWLINE part = '%s' % option_stringNEWLINENEWLINE # if the Optional takes a value, format is:NEWLINE # -s ARGS or --long ARGSNEWLINE else:NEWLINE default = action.dest.upper()NEWLINE args_string = self._format_args(action, default)NEWLINE part = '%s %s' % (option_string, args_string)NEWLINENEWLINE # make it look optional if it's not required or in a groupNEWLINE if not action.required and action not in group_actions:NEWLINE part = '[%s]' % partNEWLINENEWLINE # add the action string to the listNEWLINE parts.append(part)NEWLINENEWLINE # insert things at the necessary indicesNEWLINE for i in sorted(inserts, reverse=True):NEWLINE parts[i:i] = [inserts[i]]NEWLINENEWLINE # join all the action items with spacesNEWLINE text = ' '.join([item for item in parts if item is not None])NEWLINENEWLINE # clean up separators for mutually exclusive groupsNEWLINE open = r'[\[(]'NEWLINE close = r'[\])]'NEWLINE text = _re.sub(r'(%s) ' % open, r'\1', text)NEWLINE text = _re.sub(r' (%s)' % close, r'\1', text)NEWLINE text = _re.sub(r'%s *%s' % (open, close), r'', text)NEWLINE text = _re.sub(r'\(([^|]*)\)', r'\1', text)NEWLINE text = text.strip()NEWLINENEWLINE # return the textNEWLINE return textNEWLINENEWLINE def _format_text(self, text):NEWLINE if '%(prog)' in text:NEWLINE text = text % dict(prog=self._prog)NEWLINE text_width = max(self._width - self._current_indent, 11)NEWLINE indent = ' ' * self._current_indentNEWLINE return self._fill_text(text, text_width, indent) + '\n\n'NEWLINENEWLINE def _format_action(self, action):NEWLINE # determine the required width and the entry labelNEWLINE help_position = min(self._action_max_length + 2,NEWLINE self._max_help_position)NEWLINE help_width = max(self._width - help_position, 11)NEWLINE action_width = help_position - self._current_indent - 2NEWLINE action_header = self._format_action_invocation(action)NEWLINENEWLINE # ho nelp; start on same line and add a final newlineNEWLINE if not action.help:NEWLINE tup = self._current_indent, '', action_headerNEWLINE action_header = '%*s%s\n' % tupNEWLINENEWLINE # short action name; start on the same line and pad two spacesNEWLINE elif len(action_header) <= action_width:NEWLINE tup = self._current_indent, '', action_width, action_headerNEWLINE action_header = '%*s%-*s ' % tupNEWLINE indent_first = 0NEWLINENEWLINE # long action name; start on the next lineNEWLINE else:NEWLINE tup = self._current_indent, '', action_headerNEWLINE action_header = '%*s%s\n' % tupNEWLINE indent_first = help_positionNEWLINENEWLINE # collect the pieces of the action helpNEWLINE parts = [action_header]NEWLINENEWLINE # if there was help for the action, add lines of help textNEWLINE if action.help:NEWLINE help_text = self._expand_help(action)NEWLINE help_lines = self._split_lines(help_text, help_width)NEWLINE parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))NEWLINE for line in help_lines[1:]:NEWLINE parts.append('%*s%s\n' % (help_position, '', line))NEWLINENEWLINE # or add a newline if the description doesn't end with oneNEWLINE elif not action_header.endswith('\n'):NEWLINE parts.append('\n')NEWLINENEWLINE # if there are any sub-actions, add their help as wellNEWLINE for subaction in self._iter_indented_subactions(action):NEWLINE parts.append(self._format_action(subaction))NEWLINENEWLINE # return a single stringNEWLINE return self._join_parts(parts)NEWLINENEWLINE def _format_action_invocation(self, action):NEWLINE if not action.option_strings:NEWLINE metavar, = self._metavar_formatter(action, action.dest)(1)NEWLINE return metavarNEWLINENEWLINE else:NEWLINE parts = []NEWLINENEWLINE # if the Optional doesn't take a value, format is:NEWLINE # -s, --longNEWLINE if action.nargs == 0:NEWLINE parts.extend(action.option_strings)NEWLINENEWLINE # if the Optional takes a value, format is:NEWLINE # -s ARGS, --long ARGSNEWLINE else:NEWLINE default = action.dest.upper()NEWLINE args_string = self._format_args(action, default)NEWLINE for option_string in action.option_strings:NEWLINE parts.append('%s %s' % (option_string, args_string))NEWLINENEWLINE return ', '.join(parts)NEWLINENEWLINE def _metavar_formatter(self, action, default_metavar):NEWLINE if action.metavar is not None:NEWLINE result = action.metavarNEWLINE elif action.choices is not None:NEWLINE choice_strs = [str(choice) for choice in action.choices]NEWLINE result = '{%s}' % ','.join(choice_strs)NEWLINE else:NEWLINE result = default_metavarNEWLINENEWLINE def format(tuple_size):NEWLINE if isinstance(result, tuple):NEWLINE return resultNEWLINE else:NEWLINE return (result, ) * tuple_sizeNEWLINE return formatNEWLINENEWLINE def _format_args(self, action, default_metavar):NEWLINE get_metavar = self._metavar_formatter(action, default_metavar)NEWLINE if action.nargs is None:NEWLINE result = '%s' % get_metavar(1)NEWLINE elif action.nargs == OPTIONAL:NEWLINE result = '[%s]' % get_metavar(1)NEWLINE elif action.nargs == ZERO_OR_MORE:NEWLINE result = '[%s [%s ...]]' % get_metavar(2)NEWLINE elif action.nargs == ONE_OR_MORE:NEWLINE result = '%s [%s ...]' % get_metavar(2)NEWLINE elif action.nargs == REMAINDER:NEWLINE result = '...'NEWLINE elif action.nargs == PARSER:NEWLINE result = '%s ...' % get_metavar(1)NEWLINE else:NEWLINE formats = ['%s' for _ in range(action.nargs)]NEWLINE result = ' '.join(formats) % get_metavar(action.nargs)NEWLINE return resultNEWLINENEWLINE def _expand_help(self, action):NEWLINE params = dict(vars(action), prog=self._prog)NEWLINE for name in list(params):NEWLINE if params[name] is SUPPRESS:NEWLINE del params[name]NEWLINE for name in list(params):NEWLINE if hasattr(params[name], '__name__'):NEWLINE params[name] = params[name].__name__NEWLINE if params.get('choices') is not None:NEWLINE choices_str = ', '.join([str(c) for c in params['choices']])NEWLINE params['choices'] = choices_strNEWLINE return self._get_help_string(action) % paramsNEWLINENEWLINE def _iter_indented_subactions(self, action):NEWLINE try:NEWLINE get_subactions = action._get_subactionsNEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE self._indent()NEWLINE for subaction in get_subactions():NEWLINE yield subactionNEWLINE self._dedent()NEWLINENEWLINE def _split_lines(self, text, width):NEWLINE text = self._whitespace_matcher.sub(' ', text).strip()NEWLINE return _textwrap.wrap(text, width)NEWLINENEWLINE def _fill_text(self, text, width, indent):NEWLINE text = self._whitespace_matcher.sub(' ', text).strip()NEWLINE return _textwrap.fill(text, width, initial_indent=indent,NEWLINE subsequent_indent=indent)NEWLINENEWLINE def _get_help_string(self, action):NEWLINE return action.helpNEWLINENEWLINENEWLINEclass RawDescriptionHelpFormatter(HelpFormatter):NEWLINE """Help message formatter which retains any formatting in descriptions.NEWLINENEWLINE Only the name of this class is considered a public API. All the methodsNEWLINE provided by the class are considered an implementation detail.NEWLINE """NEWLINENEWLINE def _fill_text(self, text, width, indent):NEWLINE return ''.join([indent + line for line in text.splitlines(True)])NEWLINENEWLINENEWLINEclass RawTextHelpFormatter(RawDescriptionHelpFormatter):NEWLINE """Help message formatter which retains formatting of all help text.NEWLINENEWLINE Only the name of this class is considered a public API. All the methodsNEWLINE provided by the class are considered an implementation detail.NEWLINE """NEWLINENEWLINE def _split_lines(self, text, width):NEWLINE return text.splitlines()NEWLINENEWLINENEWLINEclass ArgumentDefaultsHelpFormatter(HelpFormatter):NEWLINE """Help message formatter which adds default values to argument help.NEWLINENEWLINE Only the name of this class is considered a public API. All the methodsNEWLINE provided by the class are considered an implementation detail.NEWLINE """NEWLINENEWLINE def _get_help_string(self, action):NEWLINE help = action.helpNEWLINE if '%(default)' not in action.help:NEWLINE if action.default is not SUPPRESS:NEWLINE defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]NEWLINE if action.option_strings or action.nargs in defaulting_nargs:NEWLINE help += ' (default: %(default)s)'NEWLINE return helpNEWLINENEWLINENEWLINE# =====================NEWLINE# Options and ArgumentsNEWLINE# =====================NEWLINENEWLINEdef _get_action_name(argument):NEWLINE if argument is None:NEWLINE return NoneNEWLINE elif argument.option_strings:NEWLINE return '/'.join(argument.option_strings)NEWLINE elif argument.metavar not in (None, SUPPRESS):NEWLINE return argument.metavarNEWLINE elif argument.dest not in (None, SUPPRESS):NEWLINE return argument.destNEWLINE else:NEWLINE return NoneNEWLINENEWLINENEWLINEclass ArgumentError(Exception):NEWLINE """An error from creating or using an argument (optional or positional).NEWLINENEWLINE The string value of this exception is the message, augmented withNEWLINE information about the argument that caused it.NEWLINE """NEWLINENEWLINE def __init__(self, argument, message):NEWLINE self.argument_name = _get_action_name(argument)NEWLINE self.message = messageNEWLINENEWLINE def __str__(self):NEWLINE if self.argument_name is None:NEWLINE format = '%(message)s'NEWLINE else:NEWLINE format = 'argument %(argument_name)s: %(message)s'NEWLINE return format % dict(message=self.message,NEWLINE argument_name=self.argument_name)NEWLINENEWLINENEWLINEclass ArgumentTypeError(Exception):NEWLINE """An error from trying to convert a command line string to a type."""NEWLINE passNEWLINENEWLINENEWLINE# ==============NEWLINE# Action classesNEWLINE# ==============NEWLINENEWLINEclass Action(_AttributeHolder):NEWLINE """Information about how to convert command line strings to Python objects.NEWLINENEWLINE Action objects are used by an ArgumentParser to represent the informationNEWLINE needed to parse a single argument from one or more strings from theNEWLINE command line. The keyword arguments to the Action constructor are alsoNEWLINE all attributes of Action instances.NEWLINENEWLINE Keyword Arguments:NEWLINENEWLINE - option_strings -- A list of command-line option strings whichNEWLINE should be associated with this action.NEWLINENEWLINE - dest -- The name of the attribute to hold the created object(s)NEWLINENEWLINE - nargs -- The number of command-line arguments that should beNEWLINE consumed. By default, one argument will be consumed and a singleNEWLINE value will be produced. Other values include:NEWLINE - N (an integer) consumes N arguments (and produces a list)NEWLINE - '?' consumes zero or one argumentsNEWLINE - '*' consumes zero or more arguments (and produces a list)NEWLINE - '+' consumes one or more arguments (and produces a list)NEWLINE Note that the difference between the default and nargs=1 is thatNEWLINE with the default, a single value will be produced, while withNEWLINE nargs=1, a list containing a single value will be produced.NEWLINENEWLINE - const -- The value to be produced if the option is specified and theNEWLINE option uses an action that takes no values.NEWLINENEWLINE - default -- The value to be produced if the option is not specified.NEWLINENEWLINE - type -- A callable that accepts a single string argument, andNEWLINE returns the converted value. The standard Python types str, int,NEWLINE float, and complex are useful examples of such callables. If None,NEWLINE str is used.NEWLINENEWLINE - choices -- A container of values that should be allowed. If not None,NEWLINE after a command-line argument has been converted to the appropriateNEWLINE type, an exception will be raised if it is not a member of thisNEWLINE collection.NEWLINENEWLINE - required -- True if the action must always be specified at theNEWLINE command line. This is only meaningful for optional command-lineNEWLINE arguments.NEWLINENEWLINE - help -- The help string describing the argument.NEWLINENEWLINE - metavar -- The name to be used for the option's argument with theNEWLINE help string. If None, the 'dest' value will be used as the name.NEWLINE """NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE nargs=None,NEWLINE const=None,NEWLINE default=None,NEWLINE type=None,NEWLINE choices=None,NEWLINE required=False,NEWLINE help=None,NEWLINE metavar=None):NEWLINE self.option_strings = option_stringsNEWLINE self.dest = destNEWLINE self.nargs = nargsNEWLINE self.const = constNEWLINE self.default = defaultNEWLINE self.type = typeNEWLINE self.choices = choicesNEWLINE self.required = requiredNEWLINE self.help = helpNEWLINE self.metavar = metavarNEWLINENEWLINE def _get_kwargs(self):NEWLINE names = [NEWLINE 'option_strings',NEWLINE 'dest',NEWLINE 'nargs',NEWLINE 'const',NEWLINE 'default',NEWLINE 'type',NEWLINE 'choices',NEWLINE 'help',NEWLINE 'metavar',NEWLINE ]NEWLINE return [(name, getattr(self, name)) for name in names]NEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE raise NotImplementedError(_('.__call__() not defined'))NEWLINENEWLINENEWLINEclass _StoreAction(Action):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE nargs=None,NEWLINE const=None,NEWLINE default=None,NEWLINE type=None,NEWLINE choices=None,NEWLINE required=False,NEWLINE help=None,NEWLINE metavar=None):NEWLINE if nargs == 0:NEWLINE raise ValueError('nargs for store actions must be > 0; if you 'NEWLINE 'have nothing to store, actions such as store 'NEWLINE 'true or store const may be more appropriate')NEWLINE if const is not None and nargs != OPTIONAL:NEWLINE raise ValueError('nargs must be %r to supply const' % OPTIONAL)NEWLINE super(_StoreAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE nargs=nargs,NEWLINE const=const,NEWLINE default=default,NEWLINE type=type,NEWLINE choices=choices,NEWLINE required=required,NEWLINE help=help,NEWLINE metavar=metavar)NEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE setattr(namespace, self.dest, values)NEWLINENEWLINENEWLINEclass _StoreConstAction(Action):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE const,NEWLINE default=None,NEWLINE required=False,NEWLINE help=None,NEWLINE metavar=None):NEWLINE super(_StoreConstAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE nargs=0,NEWLINE const=const,NEWLINE default=default,NEWLINE required=required,NEWLINE help=help)NEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE setattr(namespace, self.dest, self.const)NEWLINENEWLINENEWLINEclass _StoreTrueAction(_StoreConstAction):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE default=False,NEWLINE required=False,NEWLINE help=None):NEWLINE super(_StoreTrueAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE const=True,NEWLINE default=default,NEWLINE required=required,NEWLINE help=help)NEWLINENEWLINENEWLINEclass _StoreFalseAction(_StoreConstAction):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE default=True,NEWLINE required=False,NEWLINE help=None):NEWLINE super(_StoreFalseAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE const=False,NEWLINE default=default,NEWLINE required=required,NEWLINE help=help)NEWLINENEWLINENEWLINEclass _AppendAction(Action):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE nargs=None,NEWLINE const=None,NEWLINE default=None,NEWLINE type=None,NEWLINE choices=None,NEWLINE required=False,NEWLINE help=None,NEWLINE metavar=None):NEWLINE if nargs == 0:NEWLINE raise ValueError('nargs for append actions must be > 0; if arg 'NEWLINE 'strings are not supplying the value to append, 'NEWLINE 'the append const action may be more appropriate')NEWLINE if const is not None and nargs != OPTIONAL:NEWLINE raise ValueError('nargs must be %r to supply const' % OPTIONAL)NEWLINE super(_AppendAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE nargs=nargs,NEWLINE const=const,NEWLINE default=default,NEWLINE type=type,NEWLINE choices=choices,NEWLINE required=required,NEWLINE help=help,NEWLINE metavar=metavar)NEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE items = _copy.copy(_ensure_value(namespace, self.dest, []))NEWLINE items.append(values)NEWLINE setattr(namespace, self.dest, items)NEWLINENEWLINENEWLINEclass _AppendConstAction(Action):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE const,NEWLINE default=None,NEWLINE required=False,NEWLINE help=None,NEWLINE metavar=None):NEWLINE super(_AppendConstAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE nargs=0,NEWLINE const=const,NEWLINE default=default,NEWLINE required=required,NEWLINE help=help,NEWLINE metavar=metavar)NEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE items = _copy.copy(_ensure_value(namespace, self.dest, []))NEWLINE items.append(self.const)NEWLINE setattr(namespace, self.dest, items)NEWLINENEWLINENEWLINEclass _CountAction(Action):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest,NEWLINE default=None,NEWLINE required=False,NEWLINE help=None):NEWLINE super(_CountAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE nargs=0,NEWLINE default=default,NEWLINE required=required,NEWLINE help=help)NEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE new_count = _ensure_value(namespace, self.dest, 0) + 1NEWLINE setattr(namespace, self.dest, new_count)NEWLINENEWLINENEWLINEclass _HelpAction(Action):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE dest=SUPPRESS,NEWLINE default=SUPPRESS,NEWLINE help=None):NEWLINE super(_HelpAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE default=default,NEWLINE nargs=0,NEWLINE help=help)NEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE parser.print_help()NEWLINE parser.exit()NEWLINENEWLINENEWLINEclass _VersionAction(Action):NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE version=None,NEWLINE dest=SUPPRESS,NEWLINE default=SUPPRESS,NEWLINE help="show program's version number and exit"):NEWLINE super(_VersionAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE default=default,NEWLINE nargs=0,NEWLINE help=help)NEWLINE self.version = versionNEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE version = self.versionNEWLINE if version is None:NEWLINE version = parser.versionNEWLINE formatter = parser._get_formatter()NEWLINE formatter.add_text(version)NEWLINE parser.exit(message=formatter.format_help())NEWLINENEWLINENEWLINEclass _SubParsersAction(Action):NEWLINENEWLINE class _ChoicesPseudoAction(Action):NEWLINENEWLINE def __init__(self, name, help):NEWLINE sup = super(_SubParsersAction._ChoicesPseudoAction, self)NEWLINE sup.__init__(option_strings=[], dest=name, help=help)NEWLINENEWLINE def __init__(self,NEWLINE option_strings,NEWLINE prog,NEWLINE parser_class,NEWLINE dest=SUPPRESS,NEWLINE help=None,NEWLINE metavar=None):NEWLINENEWLINE self._prog_prefix = progNEWLINE self._parser_class = parser_classNEWLINE self._name_parser_map = _collections.OrderedDict()NEWLINE self._choices_actions = []NEWLINENEWLINE super(_SubParsersAction, self).__init__(NEWLINE option_strings=option_strings,NEWLINE dest=dest,NEWLINE nargs=PARSER,NEWLINE choices=self._name_parser_map,NEWLINE help=help,NEWLINE metavar=metavar)NEWLINENEWLINE def add_parser(self, name, **kwargs):NEWLINE # set prog from the existing prefixNEWLINE if kwargs.get('prog') is None:NEWLINE kwargs['prog'] = '%s %s' % (self._prog_prefix, name)NEWLINENEWLINE # create a pseudo-action to hold the choice helpNEWLINE if 'help' in kwargs:NEWLINE help = kwargs.pop('help')NEWLINE choice_action = self._ChoicesPseudoAction(name, help)NEWLINE self._choices_actions.append(choice_action)NEWLINENEWLINE # create the parser and add it to the mapNEWLINE parser = self._parser_class(**kwargs)NEWLINE self._name_parser_map[name] = parserNEWLINE return parserNEWLINENEWLINE def _get_subactions(self):NEWLINE return self._choices_actionsNEWLINENEWLINE def __call__(self, parser, namespace, values, option_string=None):NEWLINE parser_name = values[0]NEWLINE arg_strings = values[1:]NEWLINENEWLINE # set the parser name if requestedNEWLINE if self.dest is not SUPPRESS:NEWLINE setattr(namespace, self.dest, parser_name)NEWLINENEWLINE # select the parserNEWLINE try:NEWLINE parser = self._name_parser_map[parser_name]NEWLINE except KeyError:NEWLINE tup = parser_name, ', '.join(self._name_parser_map)NEWLINE msg = _('unknown parser %r (choices: %s)') % tupNEWLINE raise ArgumentError(self, msg)NEWLINENEWLINE # parse all the remaining options into the namespaceNEWLINE # store any unrecognized options on the object, so that the topNEWLINE # level parser can decide what to do with themNEWLINENEWLINE # In case this subparser defines new defaults, we parse themNEWLINE # in a new namespace object and then update the originalNEWLINE # namespace for the relevant parts.NEWLINE subnamespace, arg_strings = parser.parse_known_args(arg_strings, None)NEWLINE for key, value in vars(subnamespace).items():NEWLINE setattr(namespace, key, value)NEWLINENEWLINE if arg_strings:NEWLINE vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])NEWLINE getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)NEWLINENEWLINENEWLINE# ==============NEWLINE# Type classesNEWLINE# ==============NEWLINENEWLINEclass FileType(object):NEWLINE """Factory for creating file object typesNEWLINENEWLINE Instances of FileType are typically passed as type= arguments to theNEWLINE ArgumentParser add_argument() method.NEWLINENEWLINE Keyword Arguments:NEWLINE - mode -- A string indicating how the file is to be opened. Accepts theNEWLINE same values as the builtin open() function.NEWLINE - bufsize -- The file's desired buffer size. Accepts the same values asNEWLINE the builtin open() function.NEWLINE """NEWLINENEWLINE def __init__(self, mode='r', bufsize=-1):NEWLINE self._mode = modeNEWLINE self._bufsize = bufsizeNEWLINENEWLINE def __call__(self, string):NEWLINE # the special argument "-" means sys.std{in,out}NEWLINE if string == '-':NEWLINE if 'r' in self._mode:NEWLINE return _sys.stdinNEWLINE elif 'w' in self._mode:NEWLINE return _sys.stdoutNEWLINE else:NEWLINE msg = _('argument "-" with mode %r') % self._modeNEWLINE raise ValueError(msg)NEWLINENEWLINE # all other arguments are used as file namesNEWLINE try:NEWLINE return open(string, self._mode, self._bufsize)NEWLINE except IOError as e:NEWLINE message = _("can't open '%s': %s")NEWLINE raise ArgumentTypeError(message % (string, e))NEWLINENEWLINE def __repr__(self):NEWLINE args = self._mode, self._bufsizeNEWLINE args_str = ', '.join(repr(arg) for arg in args if arg != -1)NEWLINE return '%s(%s)' % (type(self).__name__, args_str)NEWLINENEWLINE# ===========================NEWLINE# Optional and Positional ParsingNEWLINE# ===========================NEWLINENEWLINEclass Namespace(_AttributeHolder):NEWLINE """Simple object for storing attributes.NEWLINENEWLINE Implements equality by attribute names and values, and provides a simpleNEWLINE string representation.NEWLINE """NEWLINENEWLINE def __init__(self, **kwargs):NEWLINE for name in kwargs:NEWLINE setattr(self, name, kwargs[name])NEWLINENEWLINE __hash__ = NoneNEWLINENEWLINE def __eq__(self, other):NEWLINE if not isinstance(other, Namespace):NEWLINE return NotImplementedNEWLINE return vars(self) == vars(other)NEWLINENEWLINE def __ne__(self, other):NEWLINE if not isinstance(other, Namespace):NEWLINE return NotImplementedNEWLINE return not (self == other)NEWLINENEWLINE def __contains__(self, key):NEWLINE return key in self.__dict__NEWLINENEWLINENEWLINEclass _ActionsContainer(object):NEWLINENEWLINE def __init__(self,NEWLINE description,NEWLINE prefix_chars,NEWLINE argument_default,NEWLINE conflict_handler):NEWLINE super(_ActionsContainer, self).__init__()NEWLINENEWLINE self.description = descriptionNEWLINE self.argument_default = argument_defaultNEWLINE self.prefix_chars = prefix_charsNEWLINE self.conflict_handler = conflict_handlerNEWLINENEWLINE # set up registriesNEWLINE self._registries = {}NEWLINENEWLINE # register actionsNEWLINE self.register('action', None, _StoreAction)NEWLINE self.register('action', 'store', _StoreAction)NEWLINE self.register('action', 'store_const', _StoreConstAction)NEWLINE self.register('action', 'store_true', _StoreTrueAction)NEWLINE self.register('action', 'store_false', _StoreFalseAction)NEWLINE self.register('action', 'append', _AppendAction)NEWLINE self.register('action', 'append_const', _AppendConstAction)NEWLINE self.register('action', 'count', _CountAction)NEWLINE self.register('action', 'help', _HelpAction)NEWLINE self.register('action', 'version', _VersionAction)NEWLINE self.register('action', 'parsers', _SubParsersAction)NEWLINENEWLINE # raise an exception if the conflict handler is invalidNEWLINE self._get_handler()NEWLINENEWLINE # action storageNEWLINE self._actions = []NEWLINE self._option_string_actions = {}NEWLINENEWLINE # groupsNEWLINE self._action_groups = []NEWLINE self._mutually_exclusive_groups = []NEWLINENEWLINE # defaults storageNEWLINE self._defaults = {}NEWLINENEWLINE # determines whether an "option" looks like a negative numberNEWLINE self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')NEWLINENEWLINE # whether or not there are any optionals that look like negativeNEWLINE # numbers -- uses a list so it can be shared and editedNEWLINE self._has_negative_number_optionals = []NEWLINENEWLINE # ====================NEWLINE # Registration methodsNEWLINE # ====================NEWLINE def register(self, registry_name, value, object):NEWLINE registry = self._registries.setdefault(registry_name, {})NEWLINE registry[value] = objectNEWLINENEWLINE def _registry_get(self, registry_name, value, default=None):NEWLINE return self._registries[registry_name].get(value, default)NEWLINENEWLINE # ==================================NEWLINE # Namespace default accessor methodsNEWLINE # ==================================NEWLINE def set_defaults(self, **kwargs):NEWLINE self._defaults.update(kwargs)NEWLINENEWLINE # if these defaults match any existing arguments, replaceNEWLINE # the previous default on the object with the new oneNEWLINE for action in self._actions:NEWLINE if action.dest in kwargs:NEWLINE action.default = kwargs[action.dest]NEWLINENEWLINE def get_default(self, dest):NEWLINE for action in self._actions:NEWLINE if action.dest == dest and action.default is not None:NEWLINE return action.defaultNEWLINE return self._defaults.get(dest, None)NEWLINENEWLINENEWLINE # =======================NEWLINE # Adding argument actionsNEWLINE # =======================NEWLINE def add_argument(self, *args, **kwargs):NEWLINE """NEWLINE add_argument(dest, ..., name=value, ...)NEWLINE add_argument(option_string, option_string, ..., name=value, ...)NEWLINE """NEWLINENEWLINE # if no positional args are supplied or only one is supplied andNEWLINE # it doesn't look like an option string, parse a positionalNEWLINE # argumentNEWLINE chars = self.prefix_charsNEWLINE if not args or len(args) == 1 and args[0][0] not in chars:NEWLINE if args and 'dest' in kwargs:NEWLINE raise ValueError('dest supplied twice for positional argument')NEWLINE kwargs = self._get_positional_kwargs(*args, **kwargs)NEWLINENEWLINE # otherwise, we're adding an optional argumentNEWLINE else:NEWLINE kwargs = self._get_optional_kwargs(*args, **kwargs)NEWLINENEWLINE # if no default was supplied, use the parser-level defaultNEWLINE if 'default' not in kwargs:NEWLINE dest = kwargs['dest']NEWLINE if dest in self._defaults:NEWLINE kwargs['default'] = self._defaults[dest]NEWLINE elif self.argument_default is not None:NEWLINE kwargs['default'] = self.argument_defaultNEWLINENEWLINE # create the action object, and add it to the parserNEWLINE action_class = self._pop_action_class(kwargs)NEWLINE if not _callable(action_class):NEWLINE raise ValueError('unknown action "%s"' % (action_class,))NEWLINE action = action_class(**kwargs)NEWLINENEWLINE # raise an error if the action type is not callableNEWLINE type_func = self._registry_get('type', action.type, action.type)NEWLINE if not _callable(type_func):NEWLINE raise ValueError('%r is not callable' % (type_func,))NEWLINENEWLINE # raise an error if the metavar does not match the typeNEWLINE if hasattr(self, "_get_formatter"):NEWLINE try:NEWLINE self._get_formatter()._format_args(action, None)NEWLINE except TypeError:NEWLINE raise ValueError("length of metavar tuple does not match nargs")NEWLINENEWLINE return self._add_action(action)NEWLINENEWLINE def add_argument_group(self, *args, **kwargs):NEWLINE group = _ArgumentGroup(self, *args, **kwargs)NEWLINE self._action_groups.append(group)NEWLINE return groupNEWLINENEWLINE def add_mutually_exclusive_group(self, **kwargs):NEWLINE group = _MutuallyExclusiveGroup(self, **kwargs)NEWLINE self._mutually_exclusive_groups.append(group)NEWLINE return groupNEWLINENEWLINE def _add_action(self, action):NEWLINE # resolve any conflictsNEWLINE self._check_conflict(action)NEWLINENEWLINE # add to actions listNEWLINE self._actions.append(action)NEWLINE action.container = selfNEWLINENEWLINE # index the action by any option strings it hasNEWLINE for option_string in action.option_strings:NEWLINE self._option_string_actions[option_string] = actionNEWLINENEWLINE # set the flag if any option strings look like negative numbersNEWLINE for option_string in action.option_strings:NEWLINE if self._negative_number_matcher.match(option_string):NEWLINE if not self._has_negative_number_optionals:NEWLINE self._has_negative_number_optionals.append(True)NEWLINENEWLINE # return the created actionNEWLINE return actionNEWLINENEWLINE def _remove_action(self, action):NEWLINE self._actions.remove(action)NEWLINENEWLINE def _add_container_actions(self, container):NEWLINE # collect groups by titlesNEWLINE title_group_map = {}NEWLINE for group in self._action_groups:NEWLINE if group.title in title_group_map:NEWLINE msg = _('cannot merge actions - two groups are named %r')NEWLINE raise ValueError(msg % (group.title))NEWLINE title_group_map[group.title] = groupNEWLINENEWLINE # map each action to its groupNEWLINE group_map = {}NEWLINE for group in container._action_groups:NEWLINENEWLINE # if a group with the title exists, use that, otherwiseNEWLINE # create a new group matching the container's groupNEWLINE if group.title not in title_group_map:NEWLINE title_group_map[group.title] = self.add_argument_group(NEWLINE title=group.title,NEWLINE description=group.description,NEWLINE conflict_handler=group.conflict_handler)NEWLINENEWLINE # map the actions to their new groupNEWLINE for action in group._group_actions:NEWLINE group_map[action] = title_group_map[group.title]NEWLINENEWLINE # add container's mutually exclusive groupsNEWLINE # NOTE: if add_mutually_exclusive_group ever gains title= andNEWLINE # description= then this code will need to be expanded as aboveNEWLINE for group in container._mutually_exclusive_groups:NEWLINE mutex_group = self.add_mutually_exclusive_group(NEWLINE required=group.required)NEWLINENEWLINE # map the actions to their new mutex groupNEWLINE for action in group._group_actions:NEWLINE group_map[action] = mutex_groupNEWLINENEWLINE # add all actions to this container or their groupNEWLINE for action in container._actions:NEWLINE group_map.get(action, self)._add_action(action)NEWLINENEWLINE def _get_positional_kwargs(self, dest, **kwargs):NEWLINE # make sure required is not specifiedNEWLINE if 'required' in kwargs:NEWLINE msg = _("'required' is an invalid argument for positionals")NEWLINE raise TypeError(msg)NEWLINENEWLINE # mark positional arguments as required if at least one isNEWLINE # always requiredNEWLINE if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:NEWLINE kwargs['required'] = TrueNEWLINE if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:NEWLINE kwargs['required'] = TrueNEWLINENEWLINE # return the keyword arguments with no option stringsNEWLINE return dict(kwargs, dest=dest, option_strings=[])NEWLINENEWLINE def _get_optional_kwargs(self, *args, **kwargs):NEWLINE # determine short and long option stringsNEWLINE option_strings = []NEWLINE long_option_strings = []NEWLINE for option_string in args:NEWLINE # error on strings that don't start with an appropriate prefixNEWLINE if not option_string[0] in self.prefix_chars:NEWLINE msg = _('invalid option string %r: 'NEWLINE 'must start with a character %r')NEWLINE tup = option_string, self.prefix_charsNEWLINE raise ValueError(msg % tup)NEWLINENEWLINE # strings starting with two prefix characters are long optionsNEWLINE option_strings.append(option_string)NEWLINE if option_string[0] in self.prefix_chars:NEWLINE if len(option_string) > 1:NEWLINE if option_string[1] in self.prefix_chars:NEWLINE long_option_strings.append(option_string)NEWLINENEWLINE # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'NEWLINE dest = kwargs.pop('dest', None)NEWLINE if dest is None:NEWLINE if long_option_strings:NEWLINE dest_option_string = long_option_strings[0]NEWLINE else:NEWLINE dest_option_string = option_strings[0]NEWLINE dest = dest_option_string.lstrip(self.prefix_chars)NEWLINE if not dest:NEWLINE msg = _('dest= is required for options like %r')NEWLINE raise ValueError(msg % option_string)NEWLINE dest = dest.replace('-', '_')NEWLINENEWLINE # return the updated keyword argumentsNEWLINE return dict(kwargs, dest=dest, option_strings=option_strings)NEWLINENEWLINE def _pop_action_class(self, kwargs, default=None):NEWLINE action = kwargs.pop('action', default)NEWLINE return self._registry_get('action', action, action)NEWLINENEWLINE def _get_handler(self):NEWLINE # determine function from conflict handler stringNEWLINE handler_func_name = '_handle_conflict_%s' % self.conflict_handlerNEWLINE try:NEWLINE return getattr(self, handler_func_name)NEWLINE except AttributeError:NEWLINE msg = _('invalid conflict_resolution value: %r')NEWLINE raise ValueError(msg % self.conflict_handler)NEWLINENEWLINE def _check_conflict(self, action):NEWLINENEWLINE # find all options that conflict with this optionNEWLINE confl_optionals = []NEWLINE for option_string in action.option_strings:NEWLINE if option_string in self._option_string_actions:NEWLINE confl_optional = self._option_string_actions[option_string]NEWLINE confl_optionals.append((option_string, confl_optional))NEWLINENEWLINE # resolve any conflictsNEWLINE if confl_optionals:NEWLINE conflict_handler = self._get_handler()NEWLINE conflict_handler(action, confl_optionals)NEWLINENEWLINE def _handle_conflict_error(self, action, conflicting_actions):NEWLINE message = _('conflicting option string(s): %s')NEWLINE conflict_string = ', '.join([option_stringNEWLINE for option_string, actionNEWLINE in conflicting_actions])NEWLINE raise ArgumentError(action, message % conflict_string)NEWLINENEWLINE def _handle_conflict_resolve(self, action, conflicting_actions):NEWLINENEWLINE # remove all conflicting optionsNEWLINE for option_string, action in conflicting_actions:NEWLINENEWLINE # remove the conflicting optionNEWLINE action.option_strings.remove(option_string)NEWLINE self._option_string_actions.pop(option_string, None)NEWLINENEWLINE # if the option now has no option string, remove it from theNEWLINE # container holding itNEWLINE if not action.option_strings:NEWLINE action.container._remove_action(action)NEWLINENEWLINENEWLINEclass _ArgumentGroup(_ActionsContainer):NEWLINENEWLINE def __init__(self, container, title=None, description=None, **kwargs):NEWLINE # add any missing keyword arguments by checking the containerNEWLINE update = kwargs.setdefaultNEWLINE update('conflict_handler', container.conflict_handler)NEWLINE update('prefix_chars', container.prefix_chars)NEWLINE update('argument_default', container.argument_default)NEWLINE super_init = super(_ArgumentGroup, self).__init__NEWLINE super_init(description=description, **kwargs)NEWLINENEWLINE # group attributesNEWLINE self.title = titleNEWLINE self._group_actions = []NEWLINENEWLINE # share most attributes with the containerNEWLINE self._registries = container._registriesNEWLINE self._actions = container._actionsNEWLINE self._option_string_actions = container._option_string_actionsNEWLINE self._defaults = container._defaultsNEWLINE self._has_negative_number_optionals = \NEWLINE container._has_negative_number_optionalsNEWLINE self._mutually_exclusive_groups = container._mutually_exclusive_groupsNEWLINENEWLINE def _add_action(self, action):NEWLINE action = super(_ArgumentGroup, self)._add_action(action)NEWLINE self._group_actions.append(action)NEWLINE return actionNEWLINENEWLINE def _remove_action(self, action):NEWLINE super(_ArgumentGroup, self)._remove_action(action)NEWLINE self._group_actions.remove(action)NEWLINENEWLINENEWLINEclass _MutuallyExclusiveGroup(_ArgumentGroup):NEWLINENEWLINE def __init__(self, container, required=False):NEWLINE super(_MutuallyExclusiveGroup, self).__init__(container)NEWLINE self.required = requiredNEWLINE self._container = containerNEWLINENEWLINE def _add_action(self, action):NEWLINE if action.required:NEWLINE msg = _('mutually exclusive arguments must be optional')NEWLINE raise ValueError(msg)NEWLINE action = self._container._add_action(action)NEWLINE self._group_actions.append(action)NEWLINE return actionNEWLINENEWLINE def _remove_action(self, action):NEWLINE self._container._remove_action(action)NEWLINE self._group_actions.remove(action)NEWLINENEWLINENEWLINEclass ArgumentParser(_AttributeHolder, _ActionsContainer):NEWLINE """Object for parsing command line strings into Python objects.NEWLINENEWLINE Keyword Arguments:NEWLINE - prog -- The name of the program (default: sys.argv[0])NEWLINE - usage -- A usage message (default: auto-generated from arguments)NEWLINE - description -- A description of what the program doesNEWLINE - epilog -- Text following the argument descriptionsNEWLINE - parents -- Parsers whose arguments should be copied into this oneNEWLINE - formatter_class -- HelpFormatter class for printing help messagesNEWLINE - prefix_chars -- Characters that prefix optional argumentsNEWLINE - fromfile_prefix_chars -- Characters that prefix files containingNEWLINE additional argumentsNEWLINE - argument_default -- The default value for all argumentsNEWLINE - conflict_handler -- String indicating how to handle conflictsNEWLINE - add_help -- Add a -h/-help optionNEWLINE """NEWLINENEWLINE def __init__(self,NEWLINE prog=None,NEWLINE usage=None,NEWLINE description=None,NEWLINE epilog=None,NEWLINE version=None,NEWLINE parents=[],NEWLINE formatter_class=HelpFormatter,NEWLINE prefix_chars='-',NEWLINE fromfile_prefix_chars=None,NEWLINE argument_default=None,NEWLINE conflict_handler='error',NEWLINE add_help=True):NEWLINENEWLINE if version is not None:NEWLINE import warningsNEWLINE warnings.warn(NEWLINE """The "version" argument to ArgumentParser is deprecated. """NEWLINE """Please use """NEWLINE """"add_argument(..., action='version', version="N", ...)" """NEWLINE """instead""", DeprecationWarning)NEWLINENEWLINE superinit = super(ArgumentParser, self).__init__NEWLINE superinit(description=description,NEWLINE prefix_chars=prefix_chars,NEWLINE argument_default=argument_default,NEWLINE conflict_handler=conflict_handler)NEWLINENEWLINE # default setting for progNEWLINE if prog is None:NEWLINE prog = _os.path.basename(_sys.argv[0])NEWLINENEWLINE self.prog = progNEWLINE self.usage = usageNEWLINE self.epilog = epilogNEWLINE self.version = versionNEWLINE self.formatter_class = formatter_classNEWLINE self.fromfile_prefix_chars = fromfile_prefix_charsNEWLINE self.add_help = add_helpNEWLINENEWLINE add_group = self.add_argument_groupNEWLINE self._positionals = add_group(_('positional arguments'))NEWLINE self._optionals = add_group(_('optional arguments'))NEWLINE self._subparsers = NoneNEWLINENEWLINE # register typesNEWLINE def identity(string):NEWLINE return stringNEWLINE self.register('type', None, identity)NEWLINENEWLINE # add help and version arguments if necessaryNEWLINE # (using explicit default to override global argument_default)NEWLINE default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]NEWLINE if self.add_help:NEWLINE self.add_argument(NEWLINE default_prefix+'h', default_prefix*2+'help',NEWLINE action='help', default=SUPPRESS,NEWLINE help=_('show this help message and exit'))NEWLINE if self.version:NEWLINE self.add_argument(NEWLINE default_prefix+'v', default_prefix*2+'version',NEWLINE action='version', default=SUPPRESS,NEWLINE version=self.version,NEWLINE help=_("show program's version number and exit"))NEWLINENEWLINE # add parent arguments and defaultsNEWLINE for parent in parents:NEWLINE self._add_container_actions(parent)NEWLINE try:NEWLINE defaults = parent._defaultsNEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE self._defaults.update(defaults)NEWLINENEWLINE # =======================NEWLINE # Pretty __repr__ methodsNEWLINE # =======================NEWLINE def _get_kwargs(self):NEWLINE names = [NEWLINE 'prog',NEWLINE 'usage',NEWLINE 'description',NEWLINE 'version',NEWLINE 'formatter_class',NEWLINE 'conflict_handler',NEWLINE 'add_help',NEWLINE ]NEWLINE return [(name, getattr(self, name)) for name in names]NEWLINENEWLINE # ==================================NEWLINE # Optional/Positional adding methodsNEWLINE # ==================================NEWLINE def add_subparsers(self, **kwargs):NEWLINE if self._subparsers is not None:NEWLINE self.error(_('cannot have multiple subparser arguments'))NEWLINENEWLINE # add the parser class to the arguments if it's not presentNEWLINE kwargs.setdefault('parser_class', type(self))NEWLINENEWLINE if 'title' in kwargs or 'description' in kwargs:NEWLINE title = _(kwargs.pop('title', 'subcommands'))NEWLINE description = _(kwargs.pop('description', None))NEWLINE self._subparsers = self.add_argument_group(title, description)NEWLINE else:NEWLINE self._subparsers = self._positionalsNEWLINENEWLINE # prog defaults to the usage message of this parser, skippingNEWLINE # optional arguments and with no "usage:" prefixNEWLINE if kwargs.get('prog') is None:NEWLINE formatter = self._get_formatter()NEWLINE positionals = self._get_positional_actions()NEWLINE groups = self._mutually_exclusive_groupsNEWLINE formatter.add_usage(self.usage, positionals, groups, '')NEWLINE kwargs['prog'] = formatter.format_help().strip()NEWLINENEWLINE # create the parsers action and add it to the positionals listNEWLINE parsers_class = self._pop_action_class(kwargs, 'parsers')NEWLINE action = parsers_class(option_strings=[], **kwargs)NEWLINE self._subparsers._add_action(action)NEWLINENEWLINE # return the created parsers actionNEWLINE return actionNEWLINENEWLINE def _add_action(self, action):NEWLINE if action.option_strings:NEWLINE self._optionals._add_action(action)NEWLINE else:NEWLINE self._positionals._add_action(action)NEWLINE return actionNEWLINENEWLINE def _get_optional_actions(self):NEWLINE return [actionNEWLINE for action in self._actionsNEWLINE if action.option_strings]NEWLINENEWLINE def _get_positional_actions(self):NEWLINE return [actionNEWLINE for action in self._actionsNEWLINE if not action.option_strings]NEWLINENEWLINE # =====================================NEWLINE # Command line argument parsing methodsNEWLINE # =====================================NEWLINE def parse_args(self, args=None, namespace=None):NEWLINE args, argv = self.parse_known_args(args, namespace)NEWLINE if argv:NEWLINE msg = _('unrecognized arguments: %s')NEWLINE self.error(msg % ' '.join(argv))NEWLINE return argsNEWLINENEWLINE def parse_known_args(self, args=None, namespace=None):NEWLINE if args is None:NEWLINE # args default to the system argsNEWLINE args = _sys.argv[1:]NEWLINE else:NEWLINE # make sure that args are mutableNEWLINE args = list(args)NEWLINENEWLINE # default Namespace built from parser defaultsNEWLINE if namespace is None:NEWLINE namespace = Namespace()NEWLINENEWLINE # add any action defaults that aren't presentNEWLINE for action in self._actions:NEWLINE if action.dest is not SUPPRESS:NEWLINE if not hasattr(namespace, action.dest):NEWLINE if action.default is not SUPPRESS:NEWLINE setattr(namespace, action.dest, action.default)NEWLINENEWLINE # add any parser defaults that aren't presentNEWLINE for dest in self._defaults:NEWLINE if not hasattr(namespace, dest):NEWLINE setattr(namespace, dest, self._defaults[dest])NEWLINENEWLINE # parse the arguments and exit if there are any errorsNEWLINE try:NEWLINE namespace, args = self._parse_known_args(args, namespace)NEWLINE if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):NEWLINE args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))NEWLINE delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)NEWLINE return namespace, argsNEWLINE except ArgumentError:NEWLINE err = _sys.exc_info()[1]NEWLINE self.error(str(err))NEWLINENEWLINE def _parse_known_args(self, arg_strings, namespace):NEWLINE # replace arg strings that are file referencesNEWLINE if self.fromfile_prefix_chars is not None:NEWLINE arg_strings = self._read_args_from_files(arg_strings)NEWLINENEWLINE # map all mutually exclusive arguments to the other argumentsNEWLINE # they can't occur withNEWLINE action_conflicts = {}NEWLINE for mutex_group in self._mutually_exclusive_groups:NEWLINE group_actions = mutex_group._group_actionsNEWLINE for i, mutex_action in enumerate(mutex_group._group_actions):NEWLINE conflicts = action_conflicts.setdefault(mutex_action, [])NEWLINE conflicts.extend(group_actions[:i])NEWLINE conflicts.extend(group_actions[i + 1:])NEWLINENEWLINE # find all option indices, and determine the arg_string_patternNEWLINE # which has an 'O' if there is an option at an index,NEWLINE # an 'A' if there is an argument, or a '-' if there is a '--'NEWLINE option_string_indices = {}NEWLINE arg_string_pattern_parts = []NEWLINE arg_strings_iter = iter(arg_strings)NEWLINE for i, arg_string in enumerate(arg_strings_iter):NEWLINENEWLINE # all args after -- are non-optionsNEWLINE if arg_string == '--':NEWLINE arg_string_pattern_parts.append('-')NEWLINE for arg_string in arg_strings_iter:NEWLINE arg_string_pattern_parts.append('A')NEWLINENEWLINE # otherwise, add the arg to the arg stringsNEWLINE # and note the index if it was an optionNEWLINE else:NEWLINE option_tuple = self._parse_optional(arg_string)NEWLINE if option_tuple is None:NEWLINE pattern = 'A'NEWLINE else:NEWLINE option_string_indices[i] = option_tupleNEWLINE pattern = 'O'NEWLINE arg_string_pattern_parts.append(pattern)NEWLINENEWLINE # join the pieces together to form the patternNEWLINE arg_strings_pattern = ''.join(arg_string_pattern_parts)NEWLINENEWLINE # converts arg strings to the appropriate and then takes the actionNEWLINE seen_actions = set()NEWLINE seen_non_default_actions = set()NEWLINENEWLINE def take_action(action, argument_strings, option_string=None):NEWLINE seen_actions.add(action)NEWLINE argument_values = self._get_values(action, argument_strings)NEWLINENEWLINE # error if this argument is not allowed with other previouslyNEWLINE # seen arguments, assuming that actions that use the defaultNEWLINE # value don't really count as "present"NEWLINE if argument_values is not action.default:NEWLINE seen_non_default_actions.add(action)NEWLINE for conflict_action in action_conflicts.get(action, []):NEWLINE if conflict_action in seen_non_default_actions:NEWLINE msg = _('not allowed with argument %s')NEWLINE action_name = _get_action_name(conflict_action)NEWLINE raise ArgumentError(action, msg % action_name)NEWLINENEWLINE # take the action if we didn't receive a SUPPRESS valueNEWLINE # (e.g. from a default)NEWLINE if argument_values is not SUPPRESS:NEWLINE action(self, namespace, argument_values, option_string)NEWLINENEWLINE # function to convert arg_strings into an optional actionNEWLINE def consume_optional(start_index):NEWLINENEWLINE # get the optional identified at this indexNEWLINE option_tuple = option_string_indices[start_index]NEWLINE action, option_string, explicit_arg = option_tupleNEWLINENEWLINE # identify additional optionals in the same arg stringNEWLINE # (e.g. -xyz is the same as -x -y -z if no args are required)NEWLINE match_argument = self._match_argumentNEWLINE action_tuples = []NEWLINE while True:NEWLINENEWLINE # if we found no optional action, skip itNEWLINE if action is None:NEWLINE extras.append(arg_strings[start_index])NEWLINE return start_index + 1NEWLINENEWLINE # if there is an explicit argument, try to match theNEWLINE # optional's string arguments to only thisNEWLINE if explicit_arg is not None:NEWLINE arg_count = match_argument(action, 'A')NEWLINENEWLINE # if the action is a single-dash option and takes noNEWLINE # arguments, try to parse more single-dash options outNEWLINE # of the tail of the option stringNEWLINE chars = self.prefix_charsNEWLINE if arg_count == 0 and option_string[1] not in chars:NEWLINE action_tuples.append((action, [], option_string))NEWLINE char = option_string[0]NEWLINE option_string = char + explicit_arg[0]NEWLINE new_explicit_arg = explicit_arg[1:] or NoneNEWLINE optionals_map = self._option_string_actionsNEWLINE if option_string in optionals_map:NEWLINE action = optionals_map[option_string]NEWLINE explicit_arg = new_explicit_argNEWLINE else:NEWLINE msg = _('ignored explicit argument %r')NEWLINE raise ArgumentError(action, msg % explicit_arg)NEWLINENEWLINE # if the action expect exactly one argument, we'veNEWLINE # successfully matched the option; exit the loopNEWLINE elif arg_count == 1:NEWLINE stop = start_index + 1NEWLINE args = [explicit_arg]NEWLINE action_tuples.append((action, args, option_string))NEWLINE breakNEWLINENEWLINE # error if a double-dash option did not use theNEWLINE # explicit argumentNEWLINE else:NEWLINE msg = _('ignored explicit argument %r')NEWLINE raise ArgumentError(action, msg % explicit_arg)NEWLINENEWLINE # if there is no explicit argument, try to match theNEWLINE # optional's string arguments with the following stringsNEWLINE # if successful, exit the loopNEWLINE else:NEWLINE start = start_index + 1NEWLINE selected_patterns = arg_strings_pattern[start:]NEWLINE arg_count = match_argument(action, selected_patterns)NEWLINE stop = start + arg_countNEWLINE args = arg_strings[start:stop]NEWLINE action_tuples.append((action, args, option_string))NEWLINE breakNEWLINENEWLINE # add the Optional to the list and return the index at whichNEWLINE # the Optional's string args stoppedNEWLINE assert action_tuplesNEWLINE for action, args, option_string in action_tuples:NEWLINE take_action(action, args, option_string)NEWLINE return stopNEWLINENEWLINE # the list of Positionals left to be parsed; this is modifiedNEWLINE # by consume_positionals()NEWLINE positionals = self._get_positional_actions()NEWLINENEWLINE # function to convert arg_strings into positional actionsNEWLINE def consume_positionals(start_index):NEWLINE # match as many Positionals as possibleNEWLINE match_partial = self._match_arguments_partialNEWLINE selected_pattern = arg_strings_pattern[start_index:]NEWLINE arg_counts = match_partial(positionals, selected_pattern)NEWLINENEWLINE # slice off the appropriate arg strings for each PositionalNEWLINE # and add the Positional and its args to the listNEWLINE for action, arg_count in zip(positionals, arg_counts):NEWLINE args = arg_strings[start_index: start_index + arg_count]NEWLINE start_index += arg_countNEWLINE take_action(action, args)NEWLINENEWLINE # slice off the Positionals that we just parsed and return theNEWLINE # index at which the Positionals' string args stoppedNEWLINE positionals[:] = positionals[len(arg_counts):]NEWLINE return start_indexNEWLINENEWLINE # consume Positionals and Optionals alternately, until we haveNEWLINE # passed the last option stringNEWLINE extras = []NEWLINE start_index = 0NEWLINE if option_string_indices:NEWLINE max_option_string_index = max(option_string_indices)NEWLINE else:NEWLINE max_option_string_index = -1NEWLINE while start_index <= max_option_string_index:NEWLINENEWLINE # consume any Positionals preceding the next optionNEWLINE next_option_string_index = min([NEWLINE indexNEWLINE for index in option_string_indicesNEWLINE if index >= start_index])NEWLINE if start_index != next_option_string_index:NEWLINE positionals_end_index = consume_positionals(start_index)NEWLINENEWLINE # only try to parse the next optional if we didn't consumeNEWLINE # the option string during the positionals parsingNEWLINE if positionals_end_index > start_index:NEWLINE start_index = positionals_end_indexNEWLINE continueNEWLINE else:NEWLINE start_index = positionals_end_indexNEWLINENEWLINE # if we consumed all the positionals we could and we're notNEWLINE # at the index of an option string, there were extra argumentsNEWLINE if start_index not in option_string_indices:NEWLINE strings = arg_strings[start_index:next_option_string_index]NEWLINE extras.extend(strings)NEWLINE start_index = next_option_string_indexNEWLINENEWLINE # consume the next optional and any arguments for itNEWLINE start_index = consume_optional(start_index)NEWLINENEWLINE # consume any positionals following the last OptionalNEWLINE stop_index = consume_positionals(start_index)NEWLINENEWLINE # if we didn't consume all the argument strings, there were extrasNEWLINE extras.extend(arg_strings[stop_index:])NEWLINENEWLINE # if we didn't use all the Positional objects, there were too fewNEWLINE # arg strings supplied.NEWLINE if positionals:NEWLINE self.error(_('too few arguments'))NEWLINENEWLINE # make sure all required actions were present, and convert defaults.NEWLINE for action in self._actions:NEWLINE if action not in seen_actions:NEWLINE if action.required:NEWLINE name = _get_action_name(action)NEWLINE self.error(_('argument %s is required') % name)NEWLINE else:NEWLINE # Convert action default now instead of doing it beforeNEWLINE # parsing arguments to avoid calling convert functionsNEWLINE # twice (which may fail) if the argument was given, butNEWLINE # only if it was defined already in the namespaceNEWLINE if (action.default is not None andNEWLINE isinstance(action.default, basestring) andNEWLINE hasattr(namespace, action.dest) andNEWLINE action.default is getattr(namespace, action.dest)):NEWLINE setattr(namespace, action.dest,NEWLINE self._get_value(action, action.default))NEWLINENEWLINE # make sure all required groups had one option presentNEWLINE for group in self._mutually_exclusive_groups:NEWLINE if group.required:NEWLINE for action in group._group_actions:NEWLINE if action in seen_non_default_actions:NEWLINE breakNEWLINENEWLINE # if no actions were used, report the errorNEWLINE else:NEWLINE names = [_get_action_name(action)NEWLINE for action in group._group_actionsNEWLINE if action.help is not SUPPRESS]NEWLINE msg = _('one of the arguments %s is required')NEWLINE self.error(msg % ' '.join(names))NEWLINENEWLINE # return the updated namespace and the extra argumentsNEWLINE return namespace, extrasNEWLINENEWLINE def _read_args_from_files(self, arg_strings):NEWLINE # expand arguments referencing filesNEWLINE new_arg_strings = []NEWLINE for arg_string in arg_strings:NEWLINENEWLINE # for regular arguments, just add them back into the listNEWLINE if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:NEWLINE new_arg_strings.append(arg_string)NEWLINENEWLINE # replace arguments referencing files with the file contentNEWLINE else:NEWLINE try:NEWLINE args_file = open(arg_string[1:])NEWLINE try:NEWLINE arg_strings = []NEWLINE for arg_line in args_file.read().splitlines():NEWLINE for arg in self.convert_arg_line_to_args(arg_line):NEWLINE arg_strings.append(arg)NEWLINE arg_strings = self._read_args_from_files(arg_strings)NEWLINE new_arg_strings.extend(arg_strings)NEWLINE finally:NEWLINE args_file.close()NEWLINE except IOError:NEWLINE err = _sys.exc_info()[1]NEWLINE self.error(str(err))NEWLINENEWLINE # return the modified argument listNEWLINE return new_arg_stringsNEWLINENEWLINE def convert_arg_line_to_args(self, arg_line):NEWLINE return [arg_line]NEWLINENEWLINE def _match_argument(self, action, arg_strings_pattern):NEWLINE # match the pattern for this action to the arg stringsNEWLINE nargs_pattern = self._get_nargs_pattern(action)NEWLINE match = _re.match(nargs_pattern, arg_strings_pattern)NEWLINENEWLINE # raise an exception if we weren't able to find a matchNEWLINE if match is None:NEWLINE nargs_errors = {NEWLINE None: _('expected one argument'),NEWLINE OPTIONAL: _('expected at most one argument'),NEWLINE ONE_OR_MORE: _('expected at least one argument'),NEWLINE }NEWLINE default = _('expected %s argument(s)') % action.nargsNEWLINE msg = nargs_errors.get(action.nargs, default)NEWLINE raise ArgumentError(action, msg)NEWLINENEWLINE # return the number of arguments matchedNEWLINE return len(match.group(1))NEWLINENEWLINE def _match_arguments_partial(self, actions, arg_strings_pattern):NEWLINE # progressively shorten the actions list by slicing off theNEWLINE # final actions until we find a matchNEWLINE result = []NEWLINE for i in range(len(actions), 0, -1):NEWLINE actions_slice = actions[:i]NEWLINE pattern = ''.join([self._get_nargs_pattern(action)NEWLINE for action in actions_slice])NEWLINE match = _re.match(pattern, arg_strings_pattern)NEWLINE if match is not None:NEWLINE result.extend([len(string) for string in match.groups()])NEWLINE breakNEWLINENEWLINE # return the list of arg string countsNEWLINE return resultNEWLINENEWLINE def _parse_optional(self, arg_string):NEWLINE # if it's an empty string, it was meant to be a positionalNEWLINE if not arg_string:NEWLINE return NoneNEWLINENEWLINE # if it doesn't start with a prefix, it was meant to be positionalNEWLINE if not arg_string[0] in self.prefix_chars:NEWLINE return NoneNEWLINENEWLINE # if the option string is present in the parser, return the actionNEWLINE if arg_string in self._option_string_actions:NEWLINE action = self._option_string_actions[arg_string]NEWLINE return action, arg_string, NoneNEWLINENEWLINE # if it's just a single character, it was meant to be positionalNEWLINE if len(arg_string) == 1:NEWLINE return NoneNEWLINENEWLINE # if the option string before the "=" is present, return the actionNEWLINE if '=' in arg_string:NEWLINE option_string, explicit_arg = arg_string.split('=', 1)NEWLINE if option_string in self._option_string_actions:NEWLINE action = self._option_string_actions[option_string]NEWLINE return action, option_string, explicit_argNEWLINENEWLINE # search through all possible prefixes of the option stringNEWLINE # and all actions in the parser for possible interpretationsNEWLINE option_tuples = self._get_option_tuples(arg_string)NEWLINENEWLINE # if multiple actions match, the option string was ambiguousNEWLINE if len(option_tuples) > 1:NEWLINE options = ', '.join([option_stringNEWLINE for action, option_string, explicit_arg in option_tuples])NEWLINE tup = arg_string, optionsNEWLINE self.error(_('ambiguous option: %s could match %s') % tup)NEWLINENEWLINE # if exactly one action matched, this segmentation is good,NEWLINE # so return the parsed actionNEWLINE elif len(option_tuples) == 1:NEWLINE option_tuple, = option_tuplesNEWLINE return option_tupleNEWLINENEWLINE # if it was not found as an option, but it looks like a negativeNEWLINE # number, it was meant to be positionalNEWLINE # unless there are negative-number-like optionsNEWLINE if self._negative_number_matcher.match(arg_string):NEWLINE if not self._has_negative_number_optionals:NEWLINE return NoneNEWLINENEWLINE # if it contains a space, it was meant to be a positionalNEWLINE if ' ' in arg_string:NEWLINE return NoneNEWLINENEWLINE # it was meant to be an optional but there is no such optionNEWLINE # in this parser (though it might be a valid option in a subparser)NEWLINE return None, arg_string, NoneNEWLINENEWLINE def _get_option_tuples(self, option_string):NEWLINE result = []NEWLINENEWLINE # option strings starting with two prefix characters are onlyNEWLINE # split at the '='NEWLINE chars = self.prefix_charsNEWLINE if option_string[0] in chars and option_string[1] in chars:NEWLINE if '=' in option_string:NEWLINE option_prefix, explicit_arg = option_string.split('=', 1)NEWLINE else:NEWLINE option_prefix = option_stringNEWLINE explicit_arg = NoneNEWLINE for option_string in self._option_string_actions:NEWLINE if option_string.startswith(option_prefix):NEWLINE action = self._option_string_actions[option_string]NEWLINE tup = action, option_string, explicit_argNEWLINE result.append(tup)NEWLINENEWLINE # single character options can be concatenated with their argumentsNEWLINE # but multiple character options always have to have their argumentNEWLINE # separateNEWLINE elif option_string[0] in chars and option_string[1] not in chars:NEWLINE option_prefix = option_stringNEWLINE explicit_arg = NoneNEWLINE short_option_prefix = option_string[:2]NEWLINE short_explicit_arg = option_string[2:]NEWLINENEWLINE for option_string in self._option_string_actions:NEWLINE if option_string == short_option_prefix:NEWLINE action = self._option_string_actions[option_string]NEWLINE tup = action, option_string, short_explicit_argNEWLINE result.append(tup)NEWLINE elif option_string.startswith(option_prefix):NEWLINE action = self._option_string_actions[option_string]NEWLINE tup = action, option_string, explicit_argNEWLINE result.append(tup)NEWLINENEWLINE # shouldn't ever get hereNEWLINE else:NEWLINE self.error(_('unexpected option string: %s') % option_string)NEWLINENEWLINE # return the collected option tuplesNEWLINE return resultNEWLINENEWLINE def _get_nargs_pattern(self, action):NEWLINE # in all examples below, we have to allow for '--' argsNEWLINE # which are represented as '-' in the patternNEWLINE nargs = action.nargsNEWLINENEWLINE # the default (None) is assumed to be a single argumentNEWLINE if nargs is None:NEWLINE nargs_pattern = '(-*A-*)'NEWLINENEWLINE # allow zero or one argumentsNEWLINE elif nargs == OPTIONAL:NEWLINE nargs_pattern = '(-*A?-*)'NEWLINENEWLINE # allow zero or more argumentsNEWLINE elif nargs == ZERO_OR_MORE:NEWLINE nargs_pattern = '(-*[A-]*)'NEWLINENEWLINE # allow one or more argumentsNEWLINE elif nargs == ONE_OR_MORE:NEWLINE nargs_pattern = '(-*A[A-]*)'NEWLINENEWLINE # allow any number of options or argumentsNEWLINE elif nargs == REMAINDER:NEWLINE nargs_pattern = '([-AO]*)'NEWLINENEWLINE # allow one argument followed by any number of options or argumentsNEWLINE elif nargs == PARSER:NEWLINE nargs_pattern = '(-*A[-AO]*)'NEWLINENEWLINE # all others should be integersNEWLINE else:NEWLINE nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)NEWLINENEWLINE # if this is an optional action, -- is not allowedNEWLINE if action.option_strings:NEWLINE nargs_pattern = nargs_pattern.replace('-*', '')NEWLINE nargs_pattern = nargs_pattern.replace('-', '')NEWLINENEWLINE # return the patternNEWLINE return nargs_patternNEWLINENEWLINE # ========================NEWLINE # Value conversion methodsNEWLINE # ========================NEWLINE def _get_values(self, action, arg_strings):NEWLINE # for everything but PARSER, REMAINDER args, strip out first '--'NEWLINE if action.nargs not in [PARSER, REMAINDER]:NEWLINE try:NEWLINE arg_strings.remove('--')NEWLINE except ValueError:NEWLINE passNEWLINENEWLINE # optional argument produces a default when not presentNEWLINE if not arg_strings and action.nargs == OPTIONAL:NEWLINE if action.option_strings:NEWLINE value = action.constNEWLINE else:NEWLINE value = action.defaultNEWLINE if isinstance(value, basestring):NEWLINE value = self._get_value(action, value)NEWLINE self._check_value(action, value)NEWLINENEWLINE # when nargs='*' on a positional, if there were no command-lineNEWLINE # args, use the default if it is anything other than NoneNEWLINE elif (not arg_strings and action.nargs == ZERO_OR_MORE andNEWLINE not action.option_strings):NEWLINE if action.default is not None:NEWLINE value = action.defaultNEWLINE else:NEWLINE value = arg_stringsNEWLINE self._check_value(action, value)NEWLINENEWLINE # single argument or optional argument produces a single valueNEWLINE elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:NEWLINE arg_string, = arg_stringsNEWLINE value = self._get_value(action, arg_string)NEWLINE self._check_value(action, value)NEWLINENEWLINE # REMAINDER arguments convert all values, checking noneNEWLINE elif action.nargs == REMAINDER:NEWLINE value = [self._get_value(action, v) for v in arg_strings]NEWLINENEWLINE # PARSER arguments convert all values, but check only the firstNEWLINE elif action.nargs == PARSER:NEWLINE value = [self._get_value(action, v) for v in arg_strings]NEWLINE self._check_value(action, value[0])NEWLINENEWLINE # all other types of nargs produce a listNEWLINE else:NEWLINE value = [self._get_value(action, v) for v in arg_strings]NEWLINE for v in value:NEWLINE self._check_value(action, v)NEWLINENEWLINE # return the converted valueNEWLINE return valueNEWLINENEWLINE def _get_value(self, action, arg_string):NEWLINE type_func = self._registry_get('type', action.type, action.type)NEWLINE if not _callable(type_func):NEWLINE msg = _('%r is not callable')NEWLINE raise ArgumentError(action, msg % type_func)NEWLINENEWLINE # convert the value to the appropriate typeNEWLINE try:NEWLINE result = type_func(arg_string)NEWLINENEWLINE # ArgumentTypeErrors indicate errorsNEWLINE except ArgumentTypeError:NEWLINE name = getattr(action.type, '__name__', repr(action.type))NEWLINE msg = str(_sys.exc_info()[1])NEWLINE raise ArgumentError(action, msg)NEWLINENEWLINE # TypeErrors or ValueErrors also indicate errorsNEWLINE except (TypeError, ValueError):NEWLINE name = getattr(action.type, '__name__', repr(action.type))NEWLINE msg = _('invalid %s value: %r')NEWLINE raise ArgumentError(action, msg % (name, arg_string))NEWLINENEWLINE # return the converted valueNEWLINE return resultNEWLINENEWLINE def _check_value(self, action, value):NEWLINE # converted value must be one of the choices (if specified)NEWLINE if action.choices is not None and value not in action.choices:NEWLINE tup = value, ', '.join(map(repr, action.choices))NEWLINE msg = _('invalid choice: %r (choose from %s)') % tupNEWLINE raise ArgumentError(action, msg)NEWLINENEWLINE # =======================NEWLINE # Help-formatting methodsNEWLINE # =======================NEWLINE def format_usage(self):NEWLINE formatter = self._get_formatter()NEWLINE formatter.add_usage(self.usage, self._actions,NEWLINE self._mutually_exclusive_groups)NEWLINE return formatter.format_help()NEWLINENEWLINE def format_help(self):NEWLINE formatter = self._get_formatter()NEWLINENEWLINE # usageNEWLINE formatter.add_usage(self.usage, self._actions,NEWLINE self._mutually_exclusive_groups)NEWLINENEWLINE # descriptionNEWLINE formatter.add_text(self.description)NEWLINENEWLINE # positionals, optionals and user-defined groupsNEWLINE for action_group in self._action_groups:NEWLINE formatter.start_section(action_group.title)NEWLINE formatter.add_text(action_group.description)NEWLINE formatter.add_arguments(action_group._group_actions)NEWLINE formatter.end_section()NEWLINENEWLINE # epilogNEWLINE formatter.add_text(self.epilog)NEWLINENEWLINE # determine help from format aboveNEWLINE return formatter.format_help()NEWLINENEWLINE def format_version(self):NEWLINE import warningsNEWLINE warnings.warn(NEWLINE 'The format_version method is deprecated -- the "version" 'NEWLINE 'argument to ArgumentParser is no longer supported.',NEWLINE DeprecationWarning)NEWLINE formatter = self._get_formatter()NEWLINE formatter.add_text(self.version)NEWLINE return formatter.format_help()NEWLINENEWLINE def _get_formatter(self):NEWLINE return self.formatter_class(prog=self.prog)NEWLINENEWLINE # =====================NEWLINE # Help-printing methodsNEWLINE # =====================NEWLINE def print_usage(self, file=None):NEWLINE if file is None:NEWLINE file = _sys.stdoutNEWLINE self._print_message(self.format_usage(), file)NEWLINENEWLINE def print_help(self, file=None):NEWLINE if file is None:NEWLINE file = _sys.stdoutNEWLINE self._print_message(self.format_help(), file)NEWLINENEWLINE def print_version(self, file=None):NEWLINE import warningsNEWLINE warnings.warn(NEWLINE 'The print_version method is deprecated -- the "version" 'NEWLINE 'argument to ArgumentParser is no longer supported.',NEWLINE DeprecationWarning)NEWLINE self._print_message(self.format_version(), file)NEWLINENEWLINE def _print_message(self, message, file=None):NEWLINE if message:NEWLINE if file is None:NEWLINE file = _sys.stderrNEWLINE file.write(message)NEWLINENEWLINE # ===============NEWLINE # Exiting methodsNEWLINE # ===============NEWLINE def exit(self, status=0, message=None):NEWLINE if message:NEWLINE self._print_message(message, _sys.stderr)NEWLINE _sys.exit(status)NEWLINENEWLINE def error(self, message):NEWLINE """error(message: string)NEWLINENEWLINE Prints a usage message incorporating the message to stderr andNEWLINE exits.NEWLINENEWLINE If you override this in a subclass, it should not return -- itNEWLINE should either exit or raise an exception.NEWLINE """NEWLINE self.print_usage(_sys.stderr)NEWLINE self.exit(2, _('%s: error: %s\n') % (self.prog, message))NEWLINE """NEWLINE OpenVINO DL WorkbenchNEWLINE Dataset annotator moduleNEWLINENEWLINE Copyright (c) 2021 Intel CorporationNEWLINENEWLINE Licensed under the Apache License, Version 2.0 (the "License");NEWLINE you may not use this file except in compliance with the License.NEWLINE You may obtain a copy of the License atNEWLINE http://www.apache.org/licenses/LICENSE-2.0NEWLINE Unless required by applicable law or agreed to in writing, softwareNEWLINE distributed under the License is distributed on an "AS IS" BASIS,NEWLINE WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE See the License for the specific language governing permissions andNEWLINE limitations under the License.NEWLINE"""NEWLINEfrom wb.main.scripts.dataset_annotator.dataset_annotator import DatasetAnnotatorNEWLINEfrom wb.main.scripts.dataset_annotator.task_to_auto_annotated_dataset_type_mapper import \NEWLINE TaskToAutoAnnotatedDatasetTypeMapperNEWLINE # Copyright (C) 2018-2021 Intel CorporationNEWLINE# SPDX-License-Identifier: Apache-2.0NEWLINENEWLINEimport numpy as npNEWLINENEWLINEfrom openvino.tools.mo.ops.splice import SpliceNEWLINEfrom openvino.tools.mo.front.common.partial_infer.utils import int64_arrayNEWLINEfrom openvino.tools.mo.graph.graph import Graph, NodeNEWLINEfrom openvino.tools.mo.middle.replacement import MiddleReplacementPatternNEWLINEfrom openvino.tools.mo.ops.assign import AssignNEWLINEfrom openvino.tools.mo.ops.concat import ConcatNEWLINEfrom openvino.tools.mo.ops.const import ConstNEWLINEfrom openvino.tools.mo.ops.crop import CropNEWLINEfrom openvino.tools.mo.ops.read_value import ReadValueNEWLINEfrom openvino.tools.mo.ops.result import ResultNEWLINEfrom openvino.tools.mo.utils.error import ErrorNEWLINENEWLINENEWLINEclass ReplaceMemoryOffsetNodePattern(MiddleReplacementPattern):NEWLINE """NEWLINE Replace MemoryOffset with SpliceNEWLINE """NEWLINE enabled = TrueNEWLINENEWLINE def run_before(self):NEWLINE from openvino.tools.mo.middle.RemoveDuplicationMemory import RemoveMemoryDuplicationPatternNEWLINE return [RemoveMemoryDuplicationPattern]NEWLINENEWLINE def run_after(self):NEWLINE from openvino.tools.mo.middle.split_tdnn_memoryoffset import SplitTdnnMemoryOffsetNEWLINE return [SplitTdnnMemoryOffset]NEWLINENEWLINE @staticmethodNEWLINE def pattern():NEWLINE return dict(NEWLINE nodes=[('op', dict(op='MemoryOffset', has_default=False))],NEWLINE edges=[])NEWLINENEWLINE @staticmethodNEWLINE def replace_pattern(graph: Graph, match: dict):NEWLINE node = match['op']NEWLINE pair_node = Node(graph, node.pair_name)NEWLINENEWLINE if pair_node.has_default:NEWLINE returnNEWLINENEWLINE if node.in_port(0).get_source() is not None:NEWLINE input_node_out_port = node.in_port(0).get_source()NEWLINE op_output_id = node.out_port(0).get_destination().node.idNEWLINE out_node_in_ports = pair_node.out_port(0).get_destinations()NEWLINE else:NEWLINE input_node_out_port = pair_node.in_port(0).get_source()NEWLINE op_output_id = pair_node.out_port(0).get_destination().node.idNEWLINE out_node_in_ports = node.out_port(0).get_destinations()NEWLINENEWLINE in_shape = input_node_out_port.data.get_shape().copy()NEWLINENEWLINE node_id = node.idNEWLINE node_name = node.nameNEWLINE node_t = node.tNEWLINENEWLINE splice = Splice(graph, {'name': node_name,NEWLINE 'id': node_id,NEWLINE 'context': int64_array(range(node_t, 1))NEWLINE if node_t < 0 else int64_array(range(0, node_t+1))}).create_node()NEWLINE splice.in_port(0).connect(input_node_out_port)NEWLINENEWLINE # offset of Crop will be 0 (first element) if node_t < 0 and in_shape[1]*node_t (last element) if node_t > 0NEWLINE crop = Crop(graph, {'name': 'Splice_Crop',NEWLINE 'axis': int64_array([1]),NEWLINE 'offset': int64_array([max(0, in_shape[1] * node_t)]),NEWLINE 'dim': int64_array([in_shape[1]])}).create_node()NEWLINENEWLINE splice.out_port(0).connect(crop.in_port(0))NEWLINE splice.out_port(0).data.set_shape(int64_array([in_shape[0], (abs(node_t) + 1) * in_shape[1]]))NEWLINENEWLINE outs = input_node_out_port.get_destinations()NEWLINE for in_port in outs:NEWLINE out_ = in_port.nodeNEWLINE if out_.op == 'Concat' and out_ == out_node_in_ports[0].node:NEWLINE crop_input = Crop(graph, {'name': 'Splice_Crop',NEWLINE 'axis': int64_array([1]),NEWLINE 'offset': int64_array([-min(0, in_shape[1] * node_t)]),NEWLINE 'dim': int64_array([in_shape[1]])}).create_node()NEWLINE splice.out_port(0).connect(crop_input.in_port(0))NEWLINENEWLINE in_port.disconnect()NEWLINE crop_input.out_port(0).connect(in_port)NEWLINE crop_input.out_port(0).data.set_shape(in_shape)NEWLINENEWLINE for dest_port in out_node_in_ports:NEWLINE dest_port.connect(crop.out_port(0))NEWLINENEWLINE graph.remove_node(op_output_id)NEWLINE graph.remove_node(node.id)NEWLINE graph.remove_node(pair_node.id)NEWLINENEWLINENEWLINEclass ReplaceMemoryOffsetWithMemoryNodePattern(MiddleReplacementPattern):NEWLINE """NEWLINE Replace MemoryOffset with Memory if IfDefined used with it to avoid cyclesNEWLINE """NEWLINE enabled = TrueNEWLINE force_shape_inference = TrueNEWLINENEWLINE def run_before(self):NEWLINE from openvino.tools.mo.middle.RemoveDuplicationMemory import RemoveMemoryDuplicationPatternNEWLINE return [RemoveMemoryDuplicationPattern]NEWLINENEWLINE @staticmethodNEWLINE def pattern():NEWLINE return dict(NEWLINE nodes=[('op', dict(op='MemoryOffset', has_default=True))],NEWLINE edges=[])NEWLINENEWLINE @staticmethodNEWLINE def replace_pattern(graph: Graph, match: dict):NEWLINE node = match['op']NEWLINE pair_node = Node(graph, node.pair_name)NEWLINENEWLINE if node.t >= 0:NEWLINE raise Error('Does not support IfDefined with t > 0')NEWLINENEWLINE if node.in_port(0).get_source() is not None:NEWLINE input_port = node.in_port(0).get_source()NEWLINE op_output_id = node.out_port(0).get_destination().node.idNEWLINE out_port = pair_node.out_port(0)NEWLINE node_name = node.nameNEWLINE pair_name = pair_node.nameNEWLINE else:NEWLINE input_port = pair_node.in_port(0).get_source()NEWLINE op_output_id = pair_node.out_port(0).get_destination().node.idNEWLINE out_port = node.out_port(0)NEWLINE node_name = pair_node.nameNEWLINE pair_name = node.nameNEWLINENEWLINE in_shape = input_port.data.get_shape()NEWLINE node_t = abs(node.t)NEWLINENEWLINE init_value_memory_out = Const(graph, {'name': 'init_value_' + pair_name,NEWLINE 'value': np.zeros(int64_array([in_shape[0], in_shape[1]*node_t])),NEWLINE 'shape': int64_array([in_shape[0], in_shape[1]*node_t])}).create_node()NEWLINE memory_out = ReadValue(graph, {'name': pair_name, 'variable_id': node_name+pair_name}).create_node()NEWLINE init_value_memory_out.out_port(0).connect(memory_out.in_port(0))NEWLINENEWLINE if node_t > 1:NEWLINE crop_concat = Crop(graph, {'name': 'Memory_crop', 'dim': np.array([in_shape[1]*(node_t-1)]),NEWLINE 'offset': np.array([in_shape[1]]), 'axis': np.array([1])}).create_node()NEWLINE memory_out.out_port(0).connect(crop_concat.in_port(0))NEWLINE concat = Concat(graph, {'name': 'Memory_concat'}).create_node()NEWLINE concat.add_sequence_of_ports('in', range(2))NEWLINE crop_concat.out_port(0).connect(concat.in_port(0))NEWLINE concat.in_port(1).connect(input_port)NEWLINENEWLINE memory_in = Assign(graph, {'name': node_name, 'variable_id': node_name + pair_name}).create_node()NEWLINE concat.out_port(0).connect(memory_in.in_port(0))NEWLINE out = Result(graph, {'name': 'Memory_output'}).create_node()NEWLINE memory_in.out_port(0).connect(out.in_port(0))NEWLINENEWLINE crop_out = Crop(graph, {'name': 'Memory_crop_out', 'dim': np.array([in_shape[1]]),NEWLINE 'offset': np.array([0]), 'axis': np.array([1])}).create_node()NEWLINE memory_out.out_port(0).connect(crop_out.in_port(0))NEWLINE out_port.get_connection().set_source(crop_out.out_port(0))NEWLINE else:NEWLINE memory_in = Assign(graph, {'name': node_name, 'variable_id': node_name + pair_name}).create_node()NEWLINE memory_in.in_port(0).connect(input_port)NEWLINE out = Result(graph, {'name': 'Memory_output'}).create_node()NEWLINE memory_in.out_port(0).connect(out.in_port(0))NEWLINE out_port.get_connection().set_source(memory_out.out_port(0))NEWLINENEWLINE graph.remove_node(op_output_id)NEWLINE graph.remove_node(node.id)NEWLINE graph.remove_node(pair_node.id)NEWLINE import osNEWLINEimport shutilNEWLINENEWLINEimport mathNEWLINEimport sysNEWLINENEWLINEANSI_ESCAPE_SEQUENCE_START = '\x1b'NEWLINEANSI_ESCAPE_SEQUENCE_END = 'm'NEWLINENEWLINENEWLINEdef get_terminal_width():NEWLINE # when piping stdout linux is executing commands in separate process (terminal-less), that's why shutil won't workNEWLINE # so instead of "echo x | program.py | cat" you should use "echo x | (export COLUMNS; program.py | cat"NEWLINENEWLINE # because PyCharm is using separate process for execution, shutil.get_terminal_size() is giving 80, 24NEWLINE if "PYCHARM_HOSTED" in os.environ:NEWLINE return 210NEWLINENEWLINE return shutil.get_terminal_size().columnsNEWLINENEWLINENEWLINEdef get_terminal_height():NEWLINE # when piping stdout linux is executing commands in separate process (terminal-less), that's why shutil won't workNEWLINE # so instead of "echo x | program.py | cat" you should use "echo x | (export COLUMNS; program.py | cat"NEWLINENEWLINE # because PyCharm is using separate process for execution, shutil.get_terminal_size() is giving 80, 24NEWLINE if "PYCHARM_HOSTED" in os.environ:NEWLINE return 40NEWLINENEWLINE return shutil.get_terminal_size().linesNEWLINENEWLINENEWLINEdef fit_text(text, width=None, already_used_characters=0, postfix='...'):NEWLINE width = width or get_terminal_width()NEWLINE if already_used_characters + len(text) > width - len(postfix):NEWLINE return text[:width - already_used_characters - len(postfix)] + postfixNEWLINE else:NEWLINE return textNEWLINENEWLINENEWLINE# TODO: instead of three letter "..." use one character elypsisis: "…" (few places here and maybe another elsewhere?)NEWLINEdef fit_text_printable_part_only(text, width=None, already_used_characters=0, postfix_if_cant_fit='...'):NEWLINE width = width or get_terminal_width()NEWLINE return get_printable_text_substring(text, 0, width - already_used_characters,NEWLINE postfix_if_cant_fit=postfix_if_cant_fit)NEWLINENEWLINENEWLINEdef get_printable_text_substring(text, _from, _len, postfix_if_cant_fit='...'):NEWLINE # print(f'get_printable_text_substring({repr(text)}, {_from}, {_len})')NEWLINE # TODO: https://unix.stackexchange.com/questions/111899/how-to-strip-color-codes-out-of-stdout-and-pipe-to-file-and-stdoutNEWLINE escape_sequence_in_progress = FalseNEWLINE printable_characters = 0NEWLINE output = []NEWLINE flags = []NEWLINE characters_to_skip = _fromNEWLINE characters_skipped = 0NEWLINE for character in text:NEWLINE if character == ANSI_ESCAPE_SEQUENCE_START:NEWLINE escape_sequence_in_progress = TrueNEWLINENEWLINE if printable_characters >= _len and not escape_sequence_in_progress: # text is longer than we can fitNEWLINE if len(postfix_if_cant_fit) > 0:NEWLINE removed_so_far = 0NEWLINE for i in range(len(output) - 1, 0, -1):NEWLINE if not flags[i]: # not non-printable = printableNEWLINE removed_so_far += 1NEWLINE del output[i]NEWLINE if removed_so_far == len(postfix_if_cant_fit):NEWLINE breakNEWLINENEWLINE output.extend(list(postfix_if_cant_fit))NEWLINE breakNEWLINENEWLINE if characters_skipped < characters_to_skip: # if we still skipping X printable charactersNEWLINE if not escape_sequence_in_progress:NEWLINE characters_skipped += 1NEWLINE else: # normal mode (after skipping)NEWLINE output.append(character)NEWLINE flags.append(escape_sequence_in_progress)NEWLINENEWLINE if not escape_sequence_in_progress:NEWLINE printable_characters += 1NEWLINENEWLINE if escape_sequence_in_progress and character == ANSI_ESCAPE_SEQUENCE_END:NEWLINE escape_sequence_in_progress = FalseNEWLINENEWLINE return ''.join(output)NEWLINENEWLINENEWLINEdef get_printable_text_length(text):NEWLINE escape_sequence_in_progress = FalseNEWLINE printable_characters = 0NEWLINE current_sequence_length = 0NEWLINE for character in text.rstrip():NEWLINE if character == ANSI_ESCAPE_SEQUENCE_START:NEWLINE escape_sequence_in_progress = TrueNEWLINE current_sequence_length = 0NEWLINENEWLINE if not escape_sequence_in_progress:NEWLINE printable_characters += 1NEWLINE else:NEWLINE current_sequence_length += 1NEWLINENEWLINE if escape_sequence_in_progress and character == ANSI_ESCAPE_SEQUENCE_END:NEWLINE escape_sequence_in_progress = FalseNEWLINE current_sequence_length = 0NEWLINENEWLINE printable_characters += current_sequence_lengthNEWLINENEWLINE return printable_charactersNEWLINENEWLINENEWLINEdef get_last_ansi_sequence(text):NEWLINE starting_pos = text.rfind(ANSI_ESCAPE_SEQUENCE_START)NEWLINE if starting_pos == -1:NEWLINE return ''NEWLINE ending_pos = text.find(ANSI_ESCAPE_SEQUENCE_END, starting_pos)NEWLINE if ending_pos == -1:NEWLINE return ''NEWLINENEWLINE return text[starting_pos:ending_pos + 1]NEWLINENEWLINENEWLINEdef colorized_center(text, width, fill_char, left_color, middle_color, right_color, rainbow=False):NEWLINE output = ''NEWLINE text_len = len(str(text))NEWLINE remaining_len = width - text_lenNEWLINE for i in range(int(math.floor(remaining_len / 2))):NEWLINE cur_color_index = left_color if not rainbow else i % 16NEWLINE output += colorize_text(fill_char, cur_color_index)NEWLINE output += colorize_text(text, middle_color)NEWLINE for i in range(int(math.ceil(remaining_len / 2))):NEWLINE cur_color_index = right_color if not rainbow else i % 16NEWLINE output += colorize_text(fill_char, cur_color_index)NEWLINE output += colorize_text('', 255)NEWLINE return outputNEWLINENEWLINENEWLINE# TODO: split into color_start, color_end then implement:NEWLINE# def colorize_text(text, color, normal_color):NEWLINE# return color_start(color) + text + color_end(normal_color)NEWLINENEWLINENEWLINEdef colorize_text(text, color):NEWLINE return f'\x1b[38;5;{color}m{text}'NEWLINENEWLINENEWLINEdef reset_color():NEWLINE return '\x1b[39m'NEWLINENEWLINENEWLINEdef clear_to_end_of_line():NEWLINE return '\x1b[K'NEWLINENEWLINENEWLINEdef clear_to_end_of_screen():NEWLINE return '\x1b[J'NEWLINENEWLINENEWLINEdef get_underscore_start():NEWLINE return '\x1b[4m'NEWLINENEWLINENEWLINEdef get_underscore_end():NEWLINE return '\x1b[24m'NEWLINENEWLINENEWLINEdef get_move_left(character_count):NEWLINE if character_count > 0:NEWLINE return f'\x1b[{character_count}D'NEWLINE else:NEWLINE return ''NEWLINENEWLINENEWLINEdef get_move_up(lines):NEWLINE return f'\x1b[{lines}A'NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE orig = '12345\x1b[38;5;m1'NEWLINE for i in range(4, 6 + 1):NEWLINE out_dots = get_printable_text_substring(orig, 0, i)NEWLINE out_empty = get_printable_text_substring(orig, 0, i, postfix_if_cant_fit="")NEWLINE print(f'{i}# {orig} + "..." -> {out_dots} ({len(out_dots)}:{get_printable_text_length(out_dots)})')NEWLINE print(f'{i}# {orig} + "" -> {out_empty} ({len(out_empty)}:{get_printable_text_length(out_empty)})')NEWLINENEWLINENEWLINEdef replace_whitespace_characters_by_their_representations(original_lines):NEWLINE # TODO: use string.translateNEWLINE replace_pairs = [['\n', '\\n'], ['\t', '\\t'], ['\r', '\\r'], ['\f', '\\f'], ['\b', '\\b'], ['\x0b', '\\x0b']]NEWLINE text = original_linesNEWLINE for replace_from, replace_to in replace_pairs:NEWLINE text = text.replace(replace_from, replace_to)NEWLINE return textNEWLINENEWLINENEWLINEdef is_piping_text():NEWLINE return not os.isatty(sys.stdin.fileno())NEWLINENEWLINENEWLINEdef read_text_from_pipe(encoding='utf8', errors='replace'):NEWLINE return sys.stdin.buffer.read().decode(encoding, errors)NEWLINE # coding=utf-8NEWLINE# --------------------------------------------------------------------------NEWLINE# Copyright (c) Microsoft Corporation. All rights reserved.NEWLINE# Licensed under the MIT License. See License.txt in the project root for license information.NEWLINE# Code generated by Microsoft (R) AutoRest Code Generator.NEWLINE# Changes may cause incorrect behavior and will be lost if the code is regenerated.NEWLINE# --------------------------------------------------------------------------NEWLINEfrom typing import TYPE_CHECKINGNEWLINEimport warningsNEWLINENEWLINEfrom azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_errorNEWLINEfrom azure.core.paging import ItemPagedNEWLINEfrom azure.core.pipeline import PipelineResponseNEWLINEfrom azure.core.pipeline.transport import HttpRequest, HttpResponseNEWLINEfrom azure.core.polling import LROPoller, NoPolling, PollingMethodNEWLINEfrom azure.mgmt.core.exceptions import ARMErrorFormatNEWLINEfrom azure.mgmt.core.polling.arm_polling import ARMPollingNEWLINENEWLINEfrom .. import models as _modelsNEWLINENEWLINEif TYPE_CHECKING:NEWLINE # pylint: disable=unused-import,ungrouped-importsNEWLINE from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, UnionNEWLINENEWLINE T = TypeVar('T')NEWLINE ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]NEWLINENEWLINEclass StorageAccountsOperations(object):NEWLINE """StorageAccountsOperations operations.NEWLINENEWLINE You should not instantiate this class directly. Instead, you should create a Client instance thatNEWLINE instantiates it for you and attaches it as an attribute.NEWLINENEWLINE :ivar models: Alias to model classes used in this operation group.NEWLINE :type models: ~azure.mgmt.storage.v2018_07_01.modelsNEWLINE :param client: Client for service requests.NEWLINE :param config: Configuration of service client.NEWLINE :param serializer: An object model serializer.NEWLINE :param deserializer: An object model deserializer.NEWLINE """NEWLINENEWLINE models = _modelsNEWLINENEWLINE def __init__(self, client, config, serializer, deserializer):NEWLINE self._client = clientNEWLINE self._serialize = serializerNEWLINE self._deserialize = deserializerNEWLINE self._config = configNEWLINENEWLINE def check_name_availability(NEWLINE self,NEWLINE account_name, # type: "_models.StorageAccountCheckNameAvailabilityParameters"NEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> "_models.CheckNameAvailabilityResult"NEWLINE """Checks that the storage account name is valid and is not already in use.NEWLINENEWLINE :param account_name: The name of the storage account within the specified resource group.NEWLINE Storage account names must be between 3 and 24 characters in length and use numbers andNEWLINE lower-case letters only.NEWLINE :type account_name: ~azure.mgmt.storage.v2018_07_01.models.StorageAccountCheckNameAvailabilityParametersNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: CheckNameAvailabilityResult, or the result of cls(response)NEWLINE :rtype: ~azure.mgmt.storage.v2018_07_01.models.CheckNameAvailabilityResultNEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameAvailabilityResult"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2018-07-01"NEWLINE content_type = kwargs.pop("content_type", "application/json")NEWLINE accept = "application/json"NEWLINENEWLINE # Construct URLNEWLINE url = self.check_name_availability.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINENEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINE header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')NEWLINE header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')NEWLINENEWLINE body_content_kwargs = {} # type: Dict[str, Any]NEWLINE body_content = self._serialize.body(account_name, 'StorageAccountCheckNameAvailabilityParameters')NEWLINE body_content_kwargs['content'] = body_contentNEWLINE request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)NEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE deserialized = self._deserialize('CheckNameAvailabilityResult', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINENEWLINE return deserializedNEWLINE check_name_availability.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Storage/checkNameAvailability'} # type: ignoreNEWLINENEWLINE def _create_initial(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE account_name, # type: strNEWLINE parameters, # type: "_models.StorageAccountCreateParameters"NEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> Optional["_models.StorageAccount"]NEWLINE cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.StorageAccount"]]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2018-07-01"NEWLINE content_type = kwargs.pop("content_type", "application/json")NEWLINE accept = "application/json"NEWLINENEWLINE # Construct URLNEWLINE url = self._create_initial.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),NEWLINE 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINENEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINE header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')NEWLINE header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')NEWLINENEWLINE body_content_kwargs = {} # type: Dict[str, Any]NEWLINE body_content = self._serialize.body(parameters, 'StorageAccountCreateParameters')NEWLINE body_content_kwargs['content'] = body_contentNEWLINE request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)NEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200, 202]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE deserialized = NoneNEWLINE if response.status_code == 200:NEWLINE deserialized = self._deserialize('StorageAccount', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINENEWLINE return deserializedNEWLINE _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}'} # type: ignoreNEWLINENEWLINE def begin_create(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE account_name, # type: strNEWLINE parameters, # type: "_models.StorageAccountCreateParameters"NEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> LROPoller["_models.StorageAccount"]NEWLINE """Asynchronously creates a new storage account with the specified parameters. If an account isNEWLINE already created and a subsequent create request is issued with different properties, theNEWLINE account properties will be updated. If an account is already created and a subsequent create orNEWLINE update request is issued with the exact same set of properties, the request will succeed.NEWLINENEWLINE :param resource_group_name: The name of the resource group within the user's subscription. TheNEWLINE name is case insensitive.NEWLINE :type resource_group_name: strNEWLINE :param account_name: The name of the storage account within the specified resource group.NEWLINE Storage account names must be between 3 and 24 characters in length and use numbers andNEWLINE lower-case letters only.NEWLINE :type account_name: strNEWLINE :param parameters: The parameters to provide for the created account.NEWLINE :type parameters: ~azure.mgmt.storage.v2018_07_01.models.StorageAccountCreateParametersNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :keyword str continuation_token: A continuation token to restart a poller from a saved state.NEWLINE :keyword polling: By default, your polling method will be ARMPolling.NEWLINE Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.NEWLINE :paramtype polling: bool or ~azure.core.polling.PollingMethodNEWLINE :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.NEWLINE :return: An instance of LROPoller that returns either StorageAccount or the result of cls(response)NEWLINE :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.storage.v2018_07_01.models.StorageAccount]NEWLINE :raises ~azure.core.exceptions.HttpResponseError:NEWLINE """NEWLINE polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.StorageAccount"]NEWLINE lro_delay = kwargs.pop(NEWLINE 'polling_interval',NEWLINE self._config.polling_intervalNEWLINE )NEWLINE cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]NEWLINE if cont_token is None:NEWLINE raw_result = self._create_initial(NEWLINE resource_group_name=resource_group_name,NEWLINE account_name=account_name,NEWLINE parameters=parameters,NEWLINE cls=lambda x,y,z: x,NEWLINE **kwargsNEWLINE )NEWLINENEWLINE kwargs.pop('error_map', None)NEWLINE kwargs.pop('content_type', None)NEWLINENEWLINE def get_long_running_output(pipeline_response):NEWLINE deserialized = self._deserialize('StorageAccount', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINE return deserializedNEWLINENEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),NEWLINE 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),NEWLINE }NEWLINENEWLINE if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)NEWLINE elif polling is False: polling_method = NoPolling()NEWLINE else: polling_method = pollingNEWLINE if cont_token:NEWLINE return LROPoller.from_continuation_token(NEWLINE polling_method=polling_method,NEWLINE continuation_token=cont_token,NEWLINE client=self._client,NEWLINE deserialization_callback=get_long_running_outputNEWLINE )NEWLINE else:NEWLINE return LROPoller(self._client, raw_result, get_long_running_output, polling_method)NEWLINE begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}'} # type: ignoreNEWLINENEWLINE def delete(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE account_name, # type: strNEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> NoneNEWLINE """Deletes a storage account in Microsoft Azure.NEWLINENEWLINE :param resource_group_name: The name of the resource group within the user's subscription. TheNEWLINE name is case insensitive.NEWLINE :type resource_group_name: strNEWLINE :param account_name: The name of the storage account within the specified resource group.NEWLINE Storage account names must be between 3 and 24 characters in length and use numbers andNEWLINE lower-case letters only.NEWLINE :type account_name: strNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: None, or the result of cls(response)NEWLINE :rtype: NoneNEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE cls = kwargs.pop('cls', None) # type: ClsType[None]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2018-07-01"NEWLINENEWLINE # Construct URLNEWLINE url = self.delete.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),NEWLINE 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINENEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINENEWLINE request = self._client.delete(url, query_parameters, header_parameters)NEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200, 204]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, None, {})NEWLINENEWLINE delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}'} # type: ignoreNEWLINENEWLINE def get_properties(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE account_name, # type: strNEWLINE expand="geoReplicationStats", # type: Optional[str]NEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> "_models.StorageAccount"NEWLINE """Returns the properties for the specified storage account including but not limited to name, SKUNEWLINE name, location, and account status. The ListKeys operation should be used to retrieve storageNEWLINE keys.NEWLINENEWLINE :param resource_group_name: The name of the resource group within the user's subscription. TheNEWLINE name is case insensitive.NEWLINE :type resource_group_name: strNEWLINE :param account_name: The name of the storage account within the specified resource group.NEWLINE Storage account names must be between 3 and 24 characters in length and use numbers andNEWLINE lower-case letters only.NEWLINE :type account_name: strNEWLINE :param expand: May be used to expand the properties within account's properties. By default,NEWLINE data is not included when fetching properties. Currently we only support geoReplicationStats.NEWLINE :type expand: strNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: StorageAccount, or the result of cls(response)NEWLINE :rtype: ~azure.mgmt.storage.v2018_07_01.models.StorageAccountNEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.StorageAccount"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2018-07-01"NEWLINE accept = "application/json"NEWLINENEWLINE # Construct URLNEWLINE url = self.get_properties.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),NEWLINE 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINENEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINE if expand is not None:NEWLINE query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')NEWLINENEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINE header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')NEWLINENEWLINE request = self._client.get(url, query_parameters, header_parameters)NEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE deserialized = self._deserialize('StorageAccount', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINENEWLINE return deserializedNEWLINE get_properties.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}'} # type: ignoreNEWLINENEWLINE def update(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE account_name, # type: strNEWLINE parameters, # type: "_models.StorageAccountUpdateParameters"NEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> "_models.StorageAccount"NEWLINE """The update operation can be used to update the SKU, encryption, access tier, or tags for aNEWLINE storage account. It can also be used to map the account to a custom domain. Only one customNEWLINE domain is supported per storage account; the replacement/change of custom domain is notNEWLINE supported. In order to replace an old custom domain, the old value must be cleared/unregisteredNEWLINE before a new value can be set. The update of multiple properties is supported. This call doesNEWLINE not change the storage keys for the account. If you want to change the storage account keys,NEWLINE use the regenerate keys operation. The location and name of the storage account cannot beNEWLINE changed after creation.NEWLINENEWLINE :param resource_group_name: The name of the resource group within the user's subscription. TheNEWLINE name is case insensitive.NEWLINE :type resource_group_name: strNEWLINE :param account_name: The name of the storage account within the specified resource group.NEWLINE Storage account names must be between 3 and 24 characters in length and use numbers andNEWLINE lower-case letters only.NEWLINE :type account_name: strNEWLINE :param parameters: The parameters to provide for the updated account.NEWLINE :type parameters: ~azure.mgmt.storage.v2018_07_01.models.StorageAccountUpdateParametersNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: StorageAccount, or the result of cls(response)NEWLINE :rtype: ~azure.mgmt.storage.v2018_07_01.models.StorageAccountNEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.StorageAccount"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2018-07-01"NEWLINE content_type = kwargs.pop("content_type", "application/json")NEWLINE accept = "application/json"NEWLINENEWLINE # Construct URLNEWLINE url = self.update.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),NEWLINE 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINENEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINE header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')NEWLINE header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')NEWLINENEWLINE body_content_kwargs = {} # type: Dict[str, Any]NEWLINE body_content = self._serialize.body(parameters, 'StorageAccountUpdateParameters')NEWLINE body_content_kwargs['content'] = body_contentNEWLINE request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)NEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE deserialized = self._deserialize('StorageAccount', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINENEWLINE return deserializedNEWLINE update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}'} # type: ignoreNEWLINENEWLINE def list(NEWLINE self,NEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> Iterable["_models.StorageAccountListResult"]NEWLINE """Lists all the storage accounts available under the subscription. Note that storage keys are notNEWLINE returned; use the ListKeys operation for this.NEWLINENEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: An iterator like instance of either StorageAccountListResult or the result of cls(response)NEWLINE :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.storage.v2018_07_01.models.StorageAccountListResult]NEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.StorageAccountListResult"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2018-07-01"NEWLINE accept = "application/json"NEWLINENEWLINE def prepare_request(next_link=None):NEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINE header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')NEWLINENEWLINE if not next_link:NEWLINE # Construct URLNEWLINE url = self.list.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE request = self._client.get(url, query_parameters, header_parameters)NEWLINE else:NEWLINE url = next_linkNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE request = self._client.get(url, query_parameters, header_parameters)NEWLINE return requestNEWLINENEWLINE def extract_data(pipeline_response):NEWLINE deserialized = self._deserialize('StorageAccountListResult', pipeline_response)NEWLINE list_of_elem = deserialized.valueNEWLINE if cls:NEWLINE list_of_elem = cls(list_of_elem)NEWLINE return None, iter(list_of_elem)NEWLINENEWLINE def get_next(next_link=None):NEWLINE request = prepare_request(next_link)NEWLINENEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE return pipeline_responseNEWLINENEWLINE return ItemPaged(NEWLINE get_next, extract_dataNEWLINE )NEWLINE list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Storage/storageAccounts'} # type: ignoreNEWLINENEWLINE def list_by_resource_group(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> Iterable["_models.StorageAccountListResult"]NEWLINE """Lists all the storage accounts available under the given resource group. Note that storage keysNEWLINE are not returned; use the ListKeys operation for this.NEWLINENEWLINE :param resource_group_name: The name of the resource group within the user's subscription. TheNEWLINE name is case insensitive.NEWLINE :type resource_group_name: strNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: An iterator like instance of either StorageAccountListResult or the result of cls(response)NEWLINE :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.storage.v2018_07_01.models.StorageAccountListResult]NEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.StorageAccountListResult"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2018-07-01"NEWLINE accept = "application/json"NEWLINENEWLINE def prepare_request(next_link=None):NEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINE header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')NEWLINENEWLINE if not next_link:NEWLINE # Construct URLNEWLINE url = self.list_by_resource_group.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE request = self._client.get(url, query_parameters, header_parameters)NEWLINE else:NEWLINE url = next_linkNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE request = self._client.get(url, query_parameters, header_parameters)NEWLINE return requestNEWLINENEWLINE def extract_data(pipeline_response):NEWLINE deserialized = self._deserialize('StorageAccountListResult', pipeline_response)NEWLINE list_of_elem = deserialized.valueNEWLINE if cls:NEWLINE list_of_elem = cls(list_of_elem)NEWLINE return None, iter(list_of_elem)NEWLINENEWLINE def get_next(next_link=None):NEWLINE request = prepare_request(next_link)NEWLINENEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE return pipeline_responseNEWLINENEWLINE return ItemPaged(NEWLINE get_next, extract_dataNEWLINE )NEWLINE list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts'} # type: ignoreNEWLINENEWLINE def list_keys(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE account_name, # type: strNEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> "_models.StorageAccountListKeysResult"NEWLINE """Lists the access keys for the specified storage account.NEWLINENEWLINE :param resource_group_name: The name of the resource group within the user's subscription. TheNEWLINE name is case insensitive.NEWLINE :type resource_group_name: strNEWLINE :param account_name: The name of the storage account within the specified resource group.NEWLINE Storage account names must be between 3 and 24 characters in length and use numbers andNEWLINE lower-case letters only.NEWLINE :type account_name: strNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: StorageAccountListKeysResult, or the result of cls(response)NEWLINE :rtype: ~azure.mgmt.storage.v2018_07_01.models.StorageAccountListKeysResultNEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.StorageAccountListKeysResult"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2018-07-01"NEWLINE accept = "application/json"NEWLINENEWLINE # Construct URLNEWLINE url = self.list_keys.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),NEWLINE 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINENEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINE header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')NEWLINENEWLINE request = self._client.post(url, query_parameters, header_parameters)NEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE deserialized = self._deserialize('StorageAccountListKeysResult', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINENEWLINE return deserializedNEWLINE list_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/listKeys'} # type: ignoreNEWLINENEWLINE def regenerate_key(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE account_name, # type: strNEWLINE regenerate_key, # type: "_models.StorageAccountRegenerateKeyParameters"NEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> "_models.StorageAccountListKeysResult"NEWLINE """Regenerates one of the access keys for the specified storage account.NEWLINENEWLINE :param resource_group_name: The name of the resource group within the user's subscription. TheNEWLINE name is case insensitive.NEWLINE :type resource_group_name: strNEWLINE :param account_name: The name of the storage account within the specified resource group.NEWLINE Storage account names must be between 3 and 24 characters in length and use numbers andNEWLINE lower-case letters only.NEWLINE :type account_name: strNEWLINE :param regenerate_key: Specifies name of the key which should be regenerated -- key1 or key2.NEWLINE :type regenerate_key: ~azure.mgmt.storage.v2018_07_01.models.StorageAccountRegenerateKeyParametersNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: StorageAccountListKeysResult, or the result of cls(response)NEWLINE :rtype: ~azure.mgmt.storage.v2018_07_01.models.StorageAccountListKeysResultNEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.StorageAccountListKeysResult"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2018-07-01"NEWLINE content_type = kwargs.pop("content_type", "application/json")NEWLINE accept = "application/json"NEWLINENEWLINE # Construct URLNEWLINE url = self.regenerate_key.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),NEWLINE 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINENEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINE header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')NEWLINE header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')NEWLINENEWLINE body_content_kwargs = {} # type: Dict[str, Any]NEWLINE body_content = self._serialize.body(regenerate_key, 'StorageAccountRegenerateKeyParameters')NEWLINE body_content_kwargs['content'] = body_contentNEWLINE request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)NEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE deserialized = self._deserialize('StorageAccountListKeysResult', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINENEWLINE return deserializedNEWLINE regenerate_key.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/regenerateKey'} # type: ignoreNEWLINENEWLINE def list_account_sas(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE account_name, # type: strNEWLINE parameters, # type: "_models.AccountSasParameters"NEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> "_models.ListAccountSasResponse"NEWLINE """List SAS credentials of a storage account.NEWLINENEWLINE :param resource_group_name: The name of the resource group within the user's subscription. TheNEWLINE name is case insensitive.NEWLINE :type resource_group_name: strNEWLINE :param account_name: The name of the storage account within the specified resource group.NEWLINE Storage account names must be between 3 and 24 characters in length and use numbers andNEWLINE lower-case letters only.NEWLINE :type account_name: strNEWLINE :param parameters: The parameters to provide to list SAS credentials for the storage account.NEWLINE :type parameters: ~azure.mgmt.storage.v2018_07_01.models.AccountSasParametersNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: ListAccountSasResponse, or the result of cls(response)NEWLINE :rtype: ~azure.mgmt.storage.v2018_07_01.models.ListAccountSasResponseNEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.ListAccountSasResponse"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2018-07-01"NEWLINE content_type = kwargs.pop("content_type", "application/json")NEWLINE accept = "application/json"NEWLINENEWLINE # Construct URLNEWLINE url = self.list_account_sas.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),NEWLINE 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINENEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINE header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')NEWLINE header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')NEWLINENEWLINE body_content_kwargs = {} # type: Dict[str, Any]NEWLINE body_content = self._serialize.body(parameters, 'AccountSasParameters')NEWLINE body_content_kwargs['content'] = body_contentNEWLINE request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)NEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE deserialized = self._deserialize('ListAccountSasResponse', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINENEWLINE return deserializedNEWLINE list_account_sas.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/ListAccountSas'} # type: ignoreNEWLINENEWLINE def list_service_sas(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE account_name, # type: strNEWLINE parameters, # type: "_models.ServiceSasParameters"NEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> "_models.ListServiceSasResponse"NEWLINE """List service SAS credentials of a specific resource.NEWLINENEWLINE :param resource_group_name: The name of the resource group within the user's subscription. TheNEWLINE name is case insensitive.NEWLINE :type resource_group_name: strNEWLINE :param account_name: The name of the storage account within the specified resource group.NEWLINE Storage account names must be between 3 and 24 characters in length and use numbers andNEWLINE lower-case letters only.NEWLINE :type account_name: strNEWLINE :param parameters: The parameters to provide to list service SAS credentials.NEWLINE :type parameters: ~azure.mgmt.storage.v2018_07_01.models.ServiceSasParametersNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: ListServiceSasResponse, or the result of cls(response)NEWLINE :rtype: ~azure.mgmt.storage.v2018_07_01.models.ListServiceSasResponseNEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.ListServiceSasResponse"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2018-07-01"NEWLINE content_type = kwargs.pop("content_type", "application/json")NEWLINE accept = "application/json"NEWLINENEWLINE # Construct URLNEWLINE url = self.list_service_sas.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),NEWLINE 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINENEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINE header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')NEWLINE header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')NEWLINENEWLINE body_content_kwargs = {} # type: Dict[str, Any]NEWLINE body_content = self._serialize.body(parameters, 'ServiceSasParameters')NEWLINE body_content_kwargs['content'] = body_contentNEWLINE request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)NEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE deserialized = self._deserialize('ListServiceSasResponse', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINENEWLINE return deserializedNEWLINE list_service_sas.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/ListServiceSas'} # type: ignoreNEWLINENEWLINE def _failover_initial(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE account_name, # type: strNEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> NoneNEWLINE cls = kwargs.pop('cls', None) # type: ClsType[None]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2018-07-01"NEWLINENEWLINE # Construct URLNEWLINE url = self._failover_initial.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),NEWLINE 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINENEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINENEWLINE request = self._client.post(url, query_parameters, header_parameters)NEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200, 202]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, None, {})NEWLINENEWLINE _failover_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/failover'} # type: ignoreNEWLINENEWLINE def begin_failover(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE account_name, # type: strNEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> LROPoller[None]NEWLINE """Failover request can be triggered for a storage account in case of availability issues. TheNEWLINE failover occurs from the storage account's primary cluster to secondary cluster for RA-GRSNEWLINE accounts. The secondary cluster will become primary after failover.NEWLINENEWLINE :param resource_group_name: The name of the resource group within the user's subscription. TheNEWLINE name is case insensitive.NEWLINE :type resource_group_name: strNEWLINE :param account_name: The name of the storage account within the specified resource group.NEWLINE Storage account names must be between 3 and 24 characters in length and use numbers andNEWLINE lower-case letters only.NEWLINE :type account_name: strNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :keyword str continuation_token: A continuation token to restart a poller from a saved state.NEWLINE :keyword polling: By default, your polling method will be ARMPolling.NEWLINE Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.NEWLINE :paramtype polling: bool or ~azure.core.polling.PollingMethodNEWLINE :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.NEWLINE :return: An instance of LROPoller that returns either None or the result of cls(response)NEWLINE :rtype: ~azure.core.polling.LROPoller[None]NEWLINE :raises ~azure.core.exceptions.HttpResponseError:NEWLINE """NEWLINE polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]NEWLINE cls = kwargs.pop('cls', None) # type: ClsType[None]NEWLINE lro_delay = kwargs.pop(NEWLINE 'polling_interval',NEWLINE self._config.polling_intervalNEWLINE )NEWLINE cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]NEWLINE if cont_token is None:NEWLINE raw_result = self._failover_initial(NEWLINE resource_group_name=resource_group_name,NEWLINE account_name=account_name,NEWLINE cls=lambda x,y,z: x,NEWLINE **kwargsNEWLINE )NEWLINENEWLINE kwargs.pop('error_map', None)NEWLINE kwargs.pop('content_type', None)NEWLINENEWLINE def get_long_running_output(pipeline_response):NEWLINE if cls:NEWLINE return cls(pipeline_response, None, {})NEWLINENEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),NEWLINE 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),NEWLINE }NEWLINENEWLINE if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)NEWLINE elif polling is False: polling_method = NoPolling()NEWLINE else: polling_method = pollingNEWLINE if cont_token:NEWLINE return LROPoller.from_continuation_token(NEWLINE polling_method=polling_method,NEWLINE continuation_token=cont_token,NEWLINE client=self._client,NEWLINE deserialization_callback=get_long_running_outputNEWLINE )NEWLINE else:NEWLINE return LROPoller(self._client, raw_result, get_long_running_output, polling_method)NEWLINE begin_failover.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/failover'} # type: ignoreNEWLINE import unittestNEWLINENEWLINEfrom tests.mapreduce import MapReduceTestCaseNEWLINENEWLINENEWLINEdef all_tests():NEWLINE suite = unittest.TestSuite()NEWLINE suite.addTest(unittest.makeSuite(MapReduceTestCase))NEWLINE return suiteNEWLINE # Copyright 2019 kubeflow.org.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINEfrom http import HTTPStatusNEWLINENEWLINEimport tornado.ioloopNEWLINEimport tornado.webNEWLINEimport tornado.httpserverNEWLINEimport argparseNEWLINEimport osNEWLINEimport loggingNEWLINEimport jsonNEWLINEfrom enum import EnumNEWLINEfrom kfserving.model import KFModelNEWLINEfrom typing import List, Dict, Optional, AnyNEWLINEfrom kfserving.protocols.request_handler import RequestHandlerNEWLINEfrom kfserving.protocols.tensorflow_http import TensorflowRequestHandlerNEWLINEfrom kfserving.protocols.seldon_http import SeldonRequestHandlerNEWLINENEWLINEDEFAULT_HTTP_PORT = 8080NEWLINEDEFAULT_GRPC_PORT = 8081NEWLINENEWLINENEWLINEclass Protocol(Enum):NEWLINE tensorflow_http = "tensorflow.http"NEWLINE seldon_http = "seldon.http"NEWLINENEWLINE def __str__(self):NEWLINE return self.valueNEWLINENEWLINENEWLINEparser = argparse.ArgumentParser(add_help=False)NEWLINEparser.add_argument('--http_port', default=DEFAULT_HTTP_PORT, type=int,NEWLINE help='The HTTP Port listened to by the model server.')NEWLINEparser.add_argument('--grpc_port', default=DEFAULT_GRPC_PORT, type=int,NEWLINE help='The GRPC Port listened to by the model server.')NEWLINEparser.add_argument('--protocol', type=Protocol, choices=list(Protocol),NEWLINE default="tensorflow.http",NEWLINE help='The protocol served by the model server')NEWLINEargs, _ = parser.parse_known_args()NEWLINENEWLINEKFSERVER_LOGLEVEL = os.environ.get('KFSERVER_LOGLEVEL', 'INFO').upper()NEWLINElogging.basicConfig(level=KFSERVER_LOGLEVEL)NEWLINENEWLINEPREDICTOR_URL_FORMAT = "http://{0}/v1/models/{1}:predict"NEWLINENEWLINENEWLINEclass KFServer(object):NEWLINE def __init__(self, protocol: Protocol = args.protocol, http_port: int = args.http_port,NEWLINE grpc_port: int = args.grpc_port):NEWLINE self.registered_models: Dict[str, KFModel] = {}NEWLINE self.http_port = http_portNEWLINE self.grpc_port = grpc_portNEWLINE self.protocol = protocolNEWLINE self._http_server: Optional[tornado.httpserver.HTTPServer] = NoneNEWLINENEWLINE def create_application(self):NEWLINE return tornado.web.Application([NEWLINE # Server Liveness API returns 200 if server is alive.NEWLINE (r"/", LivenessHandler),NEWLINE # Protocol Discovery API that returns the serving protocol supported by this server.NEWLINE (r"/protocol", ProtocolHandler, dict(protocol=self.protocol)),NEWLINE # Prometheus Metrics API that returns metrics for model serversNEWLINE (r"/v1/metrics", MetricsHandler, dict(models=self.registered_models)),NEWLINE # Model Health API returns 200 if model is ready to serve.NEWLINE (r"/v1/models/([a-zA-Z0-9_-]+)",NEWLINE ModelHealthHandler, dict(models=self.registered_models)),NEWLINE # Predict API executes executes predict on input tensorsNEWLINE (r"/v1/models/([a-zA-Z0-9_-]+)",NEWLINE ModelPredictHandler, dict(protocol=self.protocol, models=self.registered_models)),NEWLINE # Optional Custom Predict Verb for Tensorflow compatibilityNEWLINE (r"/v1/models/([a-zA-Z0-9_-]+):predict",NEWLINE ModelPredictHandler, dict(protocol=self.protocol, models=self.registered_models)),NEWLINE (r"/v1/models/([a-zA-Z0-9_-]+):explain",NEWLINE ModelExplainHandler, dict(protocol=self.protocol, models=self.registered_models)),NEWLINE ])NEWLINENEWLINE def start(self, models: List[KFModel] = []):NEWLINE # TODO add a GRPC serverNEWLINE for model in models:NEWLINE self.register_model(model)NEWLINENEWLINE self._http_server = tornado.httpserver.HTTPServer(self.create_application())NEWLINENEWLINE logging.info("Listening on port %s" % self.http_port)NEWLINE self._http_server.bind(self.http_port)NEWLINE self._http_server.start(0) # Forks workers equal to host's coresNEWLINE tornado.ioloop.IOLoop.current().start()NEWLINENEWLINE def register_model(self, model: KFModel):NEWLINE if not model.name:NEWLINE raise Exception("Failed to register model, model.name must be provided.")NEWLINE self.registered_models[model.name] = modelNEWLINE logging.info("Registering model:" + model.name)NEWLINENEWLINENEWLINEdef get_request_handler(protocol, request: Dict) -> RequestHandler:NEWLINE if protocol == Protocol.tensorflow_http:NEWLINE return TensorflowRequestHandler(request)NEWLINE else:NEWLINE return SeldonRequestHandler(request)NEWLINENEWLINENEWLINEclass ModelExplainHandler(tornado.web.RequestHandler):NEWLINENEWLINE def initialize(self, protocol: str, models: Dict[str, KFModel]):NEWLINE self.protocol = protocolNEWLINE self.models = modelsNEWLINENEWLINE def post(self, name: str):NEWLINENEWLINE # TODO Add metricsNEWLINE if name not in self.models:NEWLINE raise tornado.web.HTTPError(NEWLINE status_code=HTTPStatus.NOT_FOUND,NEWLINE reason="Model with name %s does not exist." % nameNEWLINE )NEWLINENEWLINE model = self.models[name]NEWLINE if not model.ready:NEWLINE model.load()NEWLINENEWLINE try:NEWLINE body = json.loads(self.request.body)NEWLINE except json.decoder.JSONDecodeError as e:NEWLINE raise tornado.web.HTTPError(NEWLINE status_code=HTTPStatus.BAD_REQUEST,NEWLINE reason="Unrecognized request format: %s" % eNEWLINE )NEWLINENEWLINE request_handler: RequestHandler = get_request_handler(self.protocol, body)NEWLINE request_handler.validate()NEWLINE request = request_handler.extract_request()NEWLINE explanation = model.explain(request)NEWLINENEWLINE self.write(explanation)NEWLINENEWLINENEWLINEclass ModelPredictHandler(tornado.web.RequestHandler):NEWLINE def initialize(self, protocol: str, models: Dict[str, KFModel]):NEWLINE self.protocol = protocolNEWLINE self.models = modelsNEWLINENEWLINE def post(self, name: str):NEWLINE # TODO Add metricsNEWLINE if name not in self.models:NEWLINE raise tornado.web.HTTPError(NEWLINE status_code=HTTPStatus.NOT_FOUND,NEWLINE reason="Model with name %s does not exist." % nameNEWLINE )NEWLINENEWLINE model = self.models[name]NEWLINE if not model.ready:NEWLINE model.load()NEWLINENEWLINE try:NEWLINE body = json.loads(self.request.body)NEWLINE except json.decoder.JSONDecodeError as e:NEWLINE raise tornado.web.HTTPError(NEWLINE status_code=HTTPStatus.BAD_REQUEST,NEWLINE reason="Unrecognized request format: %s" % eNEWLINE )NEWLINENEWLINE # for predictor this is noopNEWLINE # for transformer the preprocess step transforms the body to request that is conforming to data plane protocolNEWLINE request = model.preprocess(body)NEWLINE # validate if the request to predictor is conforming to data plane protocolNEWLINE request_handler: RequestHandler = get_request_handler(self.protocol, request)NEWLINE request_handler.validate()NEWLINE inputs = request_handler.extract_request()NEWLINE # for predictor this does in-place predictionNEWLINE # for transformer it calls out to predictorNEWLINE results = model.predict(inputs)NEWLINE # for predictor this is noopNEWLINE # for transformer the postprocess step transforms the result to what user expectsNEWLINE outputs = model.postprocess(results)NEWLINE response = request_handler.wrap_response(outputs)NEWLINENEWLINE self.write(response)NEWLINENEWLINENEWLINEclass LivenessHandler(tornado.web.RequestHandler):NEWLINE def get(self):NEWLINE self.write("Alive")NEWLINENEWLINENEWLINEclass ProtocolHandler(tornado.web.RequestHandler):NEWLINE def initialize(self, protocol: Protocol):NEWLINE self.protocol = protocolNEWLINENEWLINE def get(self):NEWLINE self.write(str(self.protocol.value))NEWLINENEWLINENEWLINEclass MetricsHandler(tornado.web.RequestHandler):NEWLINE def get(self):NEWLINE self.write("Not Implemented")NEWLINENEWLINENEWLINEclass ModelHealthHandler(tornado.web.RequestHandler):NEWLINE def initialize(self, models: Dict[str, KFModel]):NEWLINE self.models = modelsNEWLINENEWLINE def get(self, name: str):NEWLINE if name not in self.models:NEWLINE raise tornado.web.HTTPError(NEWLINE status_code=404,NEWLINE reason="Model with name %s does not exist." % nameNEWLINE )NEWLINENEWLINE model = self.models[name]NEWLINE self.write(json.dumps({NEWLINE "name": model.name,NEWLINE "ready": model.readyNEWLINE }))NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE s = KFServer()NEWLINE s.start()NEWLINE # by Kami BigdelyNEWLINE# Extract classNEWLINEWELL_DONE = 3000NEWLINEMEDIUM = 2500NEWLINECOOKED_CONSTANT = 0.05NEWLINENEWLINENEWLINEdef is_cookeding_criteria_satisfied(food):NEWLINE return is_well_done(NEWLINE food.time, NEWLINE food.temperature, NEWLINE food.pressure, NEWLINE food.desired_stateNEWLINE ) orNEWLINE is_medium(NEWLINE food.time, NEWLINE food.temperature, NEWLINE food.pressure, NEWLINE food.desired_stateNEWLINE )NEWLINENEWLINENEWLINEdef is_well_done(food): NEWLINE return get_cooking_progress(NEWLINE food.time, NEWLINE food.temperature, NEWLINE food.pressure) >= WELL_DONENEWLINENEWLINENEWLINEdef is_medium(food):NEWLINE return get_cooking_progress(NEWLINE food.time, NEWLINE food.temperature, NEWLINE food.pressureNEWLINE ) >= MEDIUMNEWLINENEWLINEdef get_cooking_progress(food):NEWLINE return food.time * food.temperature * food.pressure * food.COOKED_CONSTANTNEWLINENEWLINENEWLINEmy_steak = {NEWLINE time: 30NEWLINE temp: 103NEWLINE pressue: 20NEWLINE desired_state: 'well-done'NEWLINE}NEWLINENEWLINEif is_cookeding_criteria_satisfied(my_steak):NEWLINE print('cooking is done.')NEWLINEelse:NEWLINE print('ongoing cooking.') # Copyright 2019 The Vitess Authors.NEWLINE# NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE# NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE# NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINE"""Kubernetes environment."""NEWLINENEWLINEimport getpassNEWLINEimport jsonNEWLINEimport loggingNEWLINEimport osNEWLINEimport subprocessNEWLINEimport timeNEWLINENEWLINEfrom sandbox import kubernetes_componentsNEWLINEfrom vtproto import topodata_pb2NEWLINEfrom vtdb import vtgate_clientNEWLINEimport base_environmentNEWLINEimport protocols_flavorNEWLINEimport vtctl_helperNEWLINENEWLINENEWLINEclass K8sEnvironment(base_environment.BaseEnvironment):NEWLINE """Environment for kubernetes clusters on Google Compute Engine."""NEWLINENEWLINE def __init__(self):NEWLINE super(K8sEnvironment, self).__init__()NEWLINENEWLINE def use_named(self, instance_name):NEWLINE # Check to make sure kubectl existsNEWLINE try:NEWLINE subprocess.check_output(['kubectl'])NEWLINE except OSError:NEWLINE raise base_environment.VitessEnvironmentError(NEWLINE 'kubectl not found, please install by visiting kubernetes.io or 'NEWLINE 'running gcloud components update kubectl if using compute engine.')NEWLINENEWLINE vtctld_ip = kubernetes_components.get_forwarded_ip(NEWLINE 'vtctld', instance_name)NEWLINE self.vtctl_addr = '%s:15999' % vtctld_ipNEWLINENEWLINE self.vtctl_helper = vtctl_helper.VtctlHelper('grpc', self.vtctl_addr)NEWLINE self.cluster_name = instance_nameNEWLINENEWLINE keyspaces = self.vtctl_helper.execute_vtctl_command(['GetKeyspaces'])NEWLINE self.mobs = filter(None, keyspaces.split('\n'))NEWLINE self.keyspaces = self.mobsNEWLINENEWLINE if not self.keyspaces:NEWLINE raise base_environment.VitessEnvironmentError(NEWLINE 'Invalid environment, no keyspaces found')NEWLINENEWLINE self.num_shards = []NEWLINE self.shards = []NEWLINENEWLINE for keyspace in self.keyspaces:NEWLINE shards = json.loads(self.vtctl_helper.execute_vtctl_command(NEWLINE ['FindAllShardsInKeyspace', keyspace]))NEWLINE self.shards.append(shards)NEWLINE self.num_shards.append(len(shards))NEWLINENEWLINE # This assumes that all keyspaces use the same set of cellsNEWLINE self.cells = json.loads(self.vtctl_helper.execute_vtctl_command(NEWLINE ['GetShard', '%s/%s' % (self.keyspaces[0], self.shards[0].keys()[0])]NEWLINE ))['cells']NEWLINENEWLINE self.primary_cells = self.cellsNEWLINE self.replica_instances = []NEWLINE self.rdonly_instances = []NEWLINENEWLINE # This assumes that all cells are equivalent for k8s environments.NEWLINE all_tablets_in_a_cell = self.vtctl_helper.execute_vtctl_command(NEWLINE ['ListAllTablets', self.cells[0]])NEWLINE all_tablets_in_a_cell = [x.split(' ') for x inNEWLINE filter(None, all_tablets_in_a_cell.split('\n'))]NEWLINENEWLINE for index, keyspace in enumerate(self.keyspaces):NEWLINE keyspace_tablets_in_cell = [NEWLINE tablet for tablet in all_tablets_in_a_cell if tablet[1] == keyspace]NEWLINE replica_tablets_in_cell = [NEWLINE tablet for tablet in keyspace_tablets_in_cellNEWLINE if tablet[3] == 'master' or tablet[3] == 'replica']NEWLINE replica_instances = len(replica_tablets_in_cell) / self.num_shards[index]NEWLINE self.replica_instances.append(replica_instances)NEWLINE self.rdonly_instances.append(NEWLINE (len(keyspace_tablets_in_cell) / self.num_shards[index]) -NEWLINE replica_instances)NEWLINENEWLINE # Converts keyspace name and alias to number of instancesNEWLINE self.keyspace_alias_to_num_instances_dict = {}NEWLINE for index, keyspace in enumerate(self.keyspaces):NEWLINE self.keyspace_alias_to_num_instances_dict[keyspace] = {NEWLINE 'replica': int(self.replica_instances[index]),NEWLINE 'rdonly': int(self.rdonly_instances[index])NEWLINE }NEWLINENEWLINE self.vtgate_addrs = {}NEWLINE for cell in self.cells:NEWLINE vtgate_ip = kubernetes_components.get_forwarded_ip(NEWLINE 'vtgate-%s' % cell, instance_name)NEWLINE self.vtgate_addrs[cell] = '%s:15991' % vtgate_ipNEWLINE super(K8sEnvironment, self).use_named(instance_name)NEWLINENEWLINE def create(self, **kwargs):NEWLINE self.create_gke_cluster = (NEWLINE kwargs.get('create_gke_cluster', 'false').lower() != 'false')NEWLINE if self.create_gke_cluster and 'GKE_NUM_NODES' not in kwargs:NEWLINE raise base_environment.VitessEnvironmentError(NEWLINE 'Must specify GKE_NUM_NODES')NEWLINE if 'GKE_CLUSTER_NAME' not in kwargs:NEWLINE kwargs['GKE_CLUSTER_NAME'] = getpass.getuser()NEWLINE if 'VITESS_NAME' not in kwargs:NEWLINE kwargs['VITESS_NAME'] = getpass.getuser()NEWLINE kwargs['TEST_MODE'] = '1'NEWLINE self.script_dir = os.path.join(os.environ['VTROOT'], 'examples/kubernetes')NEWLINE try:NEWLINE subprocess.check_output(['gcloud', 'config', 'list'])NEWLINE except OSError:NEWLINE raise base_environment.VitessEnvironmentError(NEWLINE 'gcloud not found, please install by visiting cloud.google.com')NEWLINE if 'project' in kwargs:NEWLINE logging.info('Setting project to %s', kwargs['project'])NEWLINE subprocess.check_output(NEWLINE ['gcloud', 'config', 'set', 'project', kwargs['project']])NEWLINE project_name_json = json.loads(subprocess.check_output(NEWLINE ['gcloud', 'config', 'list', 'project', '--format', 'json']))NEWLINE project_name = project_name_json['core']['project']NEWLINE logging.info('Current project name: %s', project_name)NEWLINE for k, v in kwargs.iteritems():NEWLINE os.environ[k] = vNEWLINE if self.create_gke_cluster:NEWLINE cluster_up_txt = subprocess.check_output(NEWLINE [os.path.join(self.script_dir, 'cluster-up.sh')],NEWLINE cwd=self.script_dir, stderr=subprocess.STDOUT)NEWLINE logging.info(cluster_up_txt)NEWLINE vitess_up_output = subprocess.check_output(NEWLINE [os.path.join(self.script_dir, 'vitess-up.sh')],NEWLINE cwd=self.script_dir, stderr=subprocess.STDOUT)NEWLINE logging.info(vitess_up_output)NEWLINE self.use_named(kwargs['VITESS_NAME'])NEWLINENEWLINE def destroy(self):NEWLINE vitess_down_output = subprocess.check_output(NEWLINE [os.path.join(self.script_dir, 'vitess-down.sh')],NEWLINE cwd=self.script_dir, stderr=subprocess.STDOUT)NEWLINE logging.info(vitess_down_output)NEWLINE if self.create_gke_cluster:NEWLINE cluster_down_output = subprocess.check_output(NEWLINE [os.path.join(self.script_dir, 'cluster-down.sh')],NEWLINE cwd=self.script_dir, stderr=subprocess.STDOUT)NEWLINE logging.info(cluster_down_output)NEWLINENEWLINE def get_vtgate_conn(self, cell):NEWLINE return vtgate_client.connect(NEWLINE protocols_flavor.protocols_flavor().vtgate_python_protocol(),NEWLINE self.vtgate_addrs[cell], 60)NEWLINENEWLINE def restart_mysql_task(self, tablet_name, task_name, is_alloc=False):NEWLINE # Delete the whole pod, which deletes mysql + vttablet tasks.NEWLINE os.system('kubectl delete pod %s --namespace=%s' % (NEWLINE self.get_tablet_pod_name(tablet_name), self.cluster_name))NEWLINE return 0NEWLINENEWLINE def wait_for_good_failover_status(NEWLINE self, keyspace, shard_name, failover_completion_timeout_s=60):NEWLINE return 0NEWLINENEWLINE def poll_for_varz(self, tablet_name, varz, timeout=60.0,NEWLINE condition_fn=None, converter=str, condition_msg=None):NEWLINE """Polls for varz to exist, or match specific conditions, within a timeout.NEWLINENEWLINE Args:NEWLINE tablet_name: the name of the process that we're trying to poll vars from.NEWLINE varz: name of the vars to fetch from varzNEWLINE timeout: number of seconds that we should attempt to poll for.NEWLINE condition_fn: a function that takes the var as input, and returns a truthyNEWLINE value if it matches the success conditions.NEWLINE converter: function to convert varz valueNEWLINE condition_msg: string describing the conditions that we're polling for,NEWLINE used for error messaging.NEWLINENEWLINE Raises:NEWLINE VitessEnvironmentError: Raised if the varz conditions aren't met withinNEWLINE the given timeout.NEWLINENEWLINE Returns:NEWLINE dict of requested varz.NEWLINE """NEWLINE start_time = time.time()NEWLINE while True:NEWLINE if (time.time() - start_time) >= timeout:NEWLINE timeout_error_msg = 'Timed out polling for varz.'NEWLINE if condition_fn and condition_msg:NEWLINE timeout_error_msg += ' Condition "%s" not met.' % condition_msgNEWLINE raise base_environment.VitessEnvironmentError(timeout_error_msg)NEWLINE hostname = self.get_tablet_ip_port(tablet_name)NEWLINE host_varz = subprocess.check_output([NEWLINE 'kubectl', 'exec', '-ti', self.get_tablet_pod_name(tablet_name),NEWLINE '--namespace=%s' % self.cluster_name,NEWLINE 'curl', '%s/debug/vars' % hostname])NEWLINE if not host_varz:NEWLINE continueNEWLINE host_varz = json.loads(host_varz)NEWLINE if condition_fn is None or condition_fn(host_varz):NEWLINE return host_varzNEWLINENEWLINE def wait_for_healthy_tablets(self):NEWLINE return 0NEWLINENEWLINE def get_tablet_pod_name(self, tablet_name):NEWLINE tablet_info = json.loads(self.vtctl_helper.execute_vtctl_command(NEWLINE ['GetTablet', tablet_name]))NEWLINE # Hostname is .vttabletNEWLINE return tablet_info['hostname'].split('.')[0]NEWLINENEWLINE def get_tablet_task_number(self, tablet_name):NEWLINE # Tablet pod name under StatefulSet isNEWLINE # "----"NEWLINE # Example: test1-foo-0-replica-0.NEWLINE return int(self.get_tablet_pod_name(tablet_name).split('-')[-1])NEWLINENEWLINE def automatic_reparent_available(self):NEWLINE """Checks if the environment can automatically reparent."""NEWLINE p1 = subprocess.Popen(NEWLINE ['kubectl', 'get', 'pods', '--namespace=%s' % self.cluster_name],NEWLINE stdout=subprocess.PIPE)NEWLINE p2 = subprocess.Popen(NEWLINE ['grep', 'orchestrator'], stdin=p1.stdout, stdout=subprocess.PIPE)NEWLINE output = p2.communicate()[0]NEWLINE return bool(output)NEWLINENEWLINE def internal_reparent(self, keyspace, shard_name, new_master_uid,NEWLINE emergency=False):NEWLINE reparent_command = (NEWLINE 'EmergencyReparentShard' if emergency else 'PlannedReparentShard')NEWLINE self.vtctl_helper.execute_vtctl_command(NEWLINE [reparent_command, '-keyspace_shard', '%s/%s' % (keyspace, shard_name),NEWLINE '-new_master', new_master_uid])NEWLINE self.vtctl_helper.execute_vtctl_command(['RebuildKeyspaceGraph', keyspace])NEWLINE return 0, 'No output'NEWLINENEWLINE def backup(self, tablet_name):NEWLINE logging.info('Backing up tablet %s', tablet_name)NEWLINE self.vtctl_helper.execute_vtctl_command(['Backup', tablet_name])NEWLINENEWLINE def drain_tablet(self, tablet_name, duration_s=600):NEWLINE self.vtctl_helper.execute_vtctl_command(['StopSlave', tablet_name])NEWLINE self.vtctl_helper.execute_vtctl_command(NEWLINE ['ChangeSlaveType', tablet_name, 'drained'])NEWLINENEWLINE def is_tablet_drained(self, tablet_name):NEWLINE return self.get_tablet_type(tablet_name) == topodata_pb2.DRAINEDNEWLINENEWLINE def undrain_tablet(self, tablet_name):NEWLINE self.vtctl_helper.execute_vtctl_command(NEWLINE ['ChangeSlaveType', tablet_name, 'replica'])NEWLINE self.vtctl_helper.execute_vtctl_command(['StartSlave', tablet_name])NEWLINENEWLINE def is_tablet_undrained(self, tablet_name):NEWLINE return not self.is_tablet_drained(tablet_name)NEWLINENEWLINE def get_tablet_query_total_count(self, tablet_name):NEWLINE return self.poll_for_varz(NEWLINE tablet_name, ['Queries'])['Queries']['TotalCount']NEWLINENEWLINE '''NEWLINEWSGI config for server project.NEWLINENEWLINEIt exposes the WSGI callable as a module-level variable named ``application``.NEWLINENEWLINEFor more information on this file, seeNEWLINEhttps://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/NEWLINE'''NEWLINENEWLINEimport osNEWLINENEWLINEfrom django.core.wsgi import get_wsgi_applicationNEWLINENEWLINEos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings')NEWLINENEWLINEapplication = get_wsgi_application()NEWLINE import osNEWLINEfrom pathlib import PathNEWLINEimport reNEWLINEimport dbusNEWLINEimport psutilNEWLINEfrom .bash import exec_bash, BashErrorNEWLINEfrom .log_utils import get_loggerNEWLINENEWLINENEWLINEclass CheckError(Exception):NEWLINE passNEWLINENEWLINENEWLINEdef is_ac_power_connected():NEWLINENEWLINE for power_source_path in Path("/sys/class/power_supply/").iterdir():NEWLINENEWLINE try:NEWLINENEWLINE with open(power_source_path / "type", 'r') as f:NEWLINE if f.read().strip() != "Mains":NEWLINE continueNEWLINENEWLINE with open(power_source_path / "online", 'r') as f:NEWLINE if f.read(1) == "1":NEWLINE return TrueNEWLINENEWLINE except IOError:NEWLINE continueNEWLINENEWLINE return FalseNEWLINENEWLINENEWLINEdef is_pat_available():NEWLINE try:NEWLINE exec_bash("grep -E '^flags.+ pat( |$)' /proc/cpuinfo")NEWLINE return TrueNEWLINE except BashError:NEWLINE return FalseNEWLINENEWLINENEWLINEdef get_active_renderer():NEWLINENEWLINE if _is_gl_provider_nvidia():NEWLINE return "nvidia"NEWLINE else:NEWLINE return "integrated"NEWLINENEWLINENEWLINEdef is_module_available(module_name):NEWLINENEWLINE logger = get_logger()NEWLINENEWLINE try:NEWLINE exec_bash("/usr/sbin/modinfo %s" % module_name)NEWLINE except BashError:NEWLINE logger.info("NOT Get modinfo %s" % module_name)NEWLINE return FalseNEWLINE else:NEWLINE logger.info("Get True modinfo %s" % module_name)NEWLINE return TrueNEWLINENEWLINEdef is_module_loaded_available(module_name):NEWLINENEWLINE logger = get_logger()NEWLINENEWLINE try:NEWLINE exec_bash("/usr/sbin/lsmod | grep %s" % module_name)NEWLINE except BashError:NEWLINE logger.warning("Not lsmod: %s" % module_name)NEWLINE return FalseNEWLINE else:NEWLINE logger.warning("True lsmod %s" % module_name)NEWLINE return TrueNEWLINENEWLINEdef is_module_loaded(module_name):NEWLINENEWLINE try:NEWLINE exec_bash("/usr/sbin/lsmod | grep -E \"^%s \"" % module_name)NEWLINE except BashError:NEWLINE return FalseNEWLINE else:NEWLINE return TrueNEWLINENEWLINEdef get_current_display_manager():NEWLINENEWLINE if not os.path.isfile("/etc/systemd/system/display-manager.service"):NEWLINE raise CheckError("No display-manager.service file found")NEWLINENEWLINE dm_service_path = os.path.realpath("/etc/systemd/system/display-manager.service")NEWLINE dm_service_filename = os.path.split(dm_service_path)[-1]NEWLINE dm_name = os.path.splitext(dm_service_filename)[0]NEWLINENEWLINE return dm_nameNEWLINENEWLINEdef _get_openrc_display_manager(init):NEWLINENEWLINE if not init == "openrc":NEWLINE return using_patched_GDM()NEWLINE else:NEWLINE passNEWLINENEWLINE if not os.path.isfile("/etc/init.d/xdm"):NEWLINE raise CheckError("No xdm init script fle found")NEWLINENEWLINE dm_service_path = os.path.realpath("/etc/init.d/xdm")NEWLINE dm_service_filename = os.path.split(dm_service_path)[-1]NEWLINE dm_name = os.path.splitext(dm_service_filename)[0]NEWLINENEWLINE return dm_nameNEWLINENEWLINEdef using_patched_GDM():NEWLINENEWLINE folder_path_1 = "/etc/gdm/Prime"NEWLINE folder_path_2 = "/etc/gdm3/Prime"NEWLINENEWLINE return os.path.isdir(folder_path_1) or os.path.isdir(folder_path_2)NEWLINENEWLINEdef check_offloading_available():NEWLINENEWLINE try:NEWLINE out = exec_bash("/usr/bin/xrandr --listproviders")NEWLINE except BashError as e:NEWLINE raise CheckError("Cannot list xrandr providers : %s" % str(e))NEWLINENEWLINE for line in out.splitlines():NEWLINE if re.search("^Provider [0-9]+:", line) and "name:NVIDIA-G0" in line:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINEdef get_integrated_provider():NEWLINENEWLINE try:NEWLINE provider = exec_bash("xrandr --listproviders | egrep -io \"name:.*AMD.*|name:.*Intel.*\" | sed 's/name://;s/^/\"/;s/$/\"/'")NEWLINE except BashError as e:NEWLINE raise CheckError("Cannot find Intel or AMD in xrandr providers : %s" % str(e))NEWLINE return providerNEWLINENEWLINEdef is_xorg_intel_module_available():NEWLINE return os.path.isfile("/usr/lib64/xorg/modules/drivers/intel_drv.so")NEWLINENEWLINEdef is_xorg_amdgpu_module_available():NEWLINE return os.path.isfile("/usr/lib64/xorg/modules/drivers/amdgpu_drv.so")NEWLINENEWLINENEWLINEdef is_login_manager_active():NEWLINE return _is_service_active("display-manager")NEWLINENEWLINENEWLINEdef is_daemon_active():NEWLINE return _is_service_active("optimus-manager")NEWLINENEWLINENEWLINEdef is_bumblebeed_service_active():NEWLINE return _is_service_active("bumblebeed")NEWLINENEWLINEdef list_processes_on_nvidia(bus_ids):NEWLINENEWLINE nvidia_id = bus_ids["nvidia"]NEWLINENEWLINE paths = [NEWLINE "/dev/nvidia",NEWLINE os.path.realpath(f"/dev/dri/by-path/pci-0000:{nvidia_id}-card"),NEWLINE os.path.realpath(f"/dev/dri/by-path/pci-0000:{nvidia_id}-render")NEWLINE ]NEWLINENEWLINE def _check_holds_nvidia(pid):NEWLINENEWLINE for fd_path in Path(f"/proc/{pid}/fd").iterdir():NEWLINE try:NEWLINE target = os.readlink(fd_path)NEWLINE for p in paths:NEWLINE if p in target:NEWLINE return TrueNEWLINE except FileNotFoundError:NEWLINE passNEWLINENEWLINE return FalseNEWLINENEWLINE processes = []NEWLINENEWLINE for proc in psutil.process_iter(["pid", "cmdline"]):NEWLINE try:NEWLINE if _check_holds_nvidia(proc.pid):NEWLINE cmdline = proc.cmdline()NEWLINE cmdline = cmdline[0] if len(cmdline) > 0 else ""NEWLINE processes.append({NEWLINE "pid": proc.pid,NEWLINE "cmdline":cmdlineNEWLINE })NEWLINE except PermissionError:NEWLINE passNEWLINENEWLINE return processesNEWLINENEWLINENEWLINEdef _is_gl_provider_nvidia():NEWLINENEWLINE try:NEWLINE out = exec_bash("__NV_PRIME_RENDER_OFFLOAD=0 glxinfo")NEWLINE except BashError as e:NEWLINE raise CheckError("Cannot run glxinfo : %s" % str(e))NEWLINENEWLINE for line in out.splitlines():NEWLINE if "server glx vendor string: NVIDIA Corporation" in line:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINEdef get_integrated_gpu():NEWLINENEWLINE try:NEWLINE exec_bash("glxinfo | awk '/Vendor:/{print $2}'| grep 'X.Org'")NEWLINE return "amd"NEWLINE except BashError:NEWLINE return "intel"NEWLINENEWLINEdef _is_service_active(service_name):NEWLINENEWLINE logger = get_logger()NEWLINENEWLINE try:NEWLINE system_bus = dbus.SystemBus()NEWLINE except dbus.exceptions.DBusException:NEWLINE logger.warning(NEWLINE "Cannot communicate with the DBus system bus to check status of %s."NEWLINE " Is DBus running ? Falling back to bash commands", service_name)NEWLINE return _is_service_active_bash(service_name)NEWLINE else:NEWLINE return _is_service_active_dbus(system_bus, service_name)NEWLINENEWLINEdef _is_service_active_dbus(system_bus, service_name):NEWLINENEWLINE systemd = system_bus.get_object("org.freedesktop.systemd1", "/org/freedesktop/systemd1")NEWLINENEWLINE try:NEWLINE unit_path = systemd.GetUnit("%s.service" % service_name, dbus_interface="org.freedesktop.systemd1.Manager")NEWLINE except dbus.exceptions.DBusException:NEWLINE return FalseNEWLINENEWLINE optimus_manager_interface = system_bus.get_object("org.freedesktop.systemd1", unit_path)NEWLINE properties_manager = dbus.Interface(optimus_manager_interface, 'org.freedesktop.DBus.Properties')NEWLINE state = properties_manager.Get("org.freedesktop.systemd1.Unit", "SubState")NEWLINENEWLINE return state == "running"NEWLINENEWLINENEWLINEdef _is_service_active_bash(service_name):NEWLINENEWLINE try:NEWLINE exec_bash("systemctl is-active %s" % service_name)NEWLINE except BashError:NEWLINE return FalseNEWLINE else:NEWLINE return TrueNEWLINE # -*- coding: utf-8 -*-NEWLINENEWLINE"""NEWLINEtaiga_ncurses.ui.signalsNEWLINE~~~~~~~~~~~~~~~~~~~~~~~~NEWLINE"""NEWLINENEWLINEimport urwidNEWLINENEWLINEconnect = urwid.connect_signalNEWLINEdisconnect = urwid.disconnect_signalNEWLINENEWLINEdef emit(widget, signal):NEWLINE widget._emit(signal)NEWLINE from django.core.cache import get_cacheNEWLINEfrom avocado.conf import settingsNEWLINEfrom .model import instance_cache_key, NEVER_EXPIRENEWLINENEWLINENEWLINEdef post_save_cache(sender, instance, **kwargs):NEWLINE """General post-save handler for caching model instances. NOTE: This mustNEWLINE be used in conjunction with the `pre_delete_uncache` since the cache is setNEWLINE to never expire.NEWLINE """NEWLINE cache = get_cache(settings.DATA_CACHE)NEWLINE cache.set(instance_cache_key(instance), instance, timeout=NEVER_EXPIRE)NEWLINENEWLINENEWLINEdef pre_delete_uncache(sender, instance, **kwargs):NEWLINE "General post-delete handler for removing cache for model instances."NEWLINE cache = get_cache(settings.DATA_CACHE)NEWLINE cache.delete(instance_cache_key(instance))NEWLINE try:NEWLINE from django.conf.urls import url, includeNEWLINEexcept ImportError:NEWLINE from django.urls import url, includeNEWLINENEWLINEurlpatterns = [NEWLINE url(r'^', include('notify.urls', namespace='notifications')),NEWLINE]NEWLINE from __future__ import print_function, absolute_import, divisionNEWLINENEWLINEfrom timeit import default_timer as timerNEWLINEimport numpy as npNEWLINENEWLINEfrom .reduction import device_reduce_sumNEWLINENEWLINENEWLINEdef benchmark_intp(nelem):NEWLINE data = np.random.randint(0, 100, nelem).astype(np.intp)NEWLINENEWLINE ts = timer()NEWLINE expected_res = data.sum()NEWLINE cpu_time = timer() - tsNEWLINENEWLINE ts = timer()NEWLINE got_res = device_reduce_sum(data)NEWLINE gpu_time = timer() - tsNEWLINENEWLINE assert got_res == expected_resNEWLINE return cpu_time, gpu_timeNEWLINENEWLINENEWLINEdef benchmark_float64(nelem):NEWLINE data = np.random.random(nelem).astype(np.float64)NEWLINENEWLINE ts = timer()NEWLINE expected_res = data.sum()NEWLINE cpu_time = timer() - tsNEWLINENEWLINE ts = timer()NEWLINE got_res = device_reduce_sum(data)NEWLINE gpu_time = timer() - tsNEWLINENEWLINE np.allclose(got_res, expected_res)NEWLINE return cpu_time, gpu_timeNEWLINENEWLINENEWLINEdef main():NEWLINE print('benchmark intp'.center(80, '='))NEWLINE for n in [100, 1000, 10000, 100000, 1000000, 10000000]:NEWLINE print('n = {0}'.format(n))NEWLINE for t in range(3):NEWLINE print(benchmark_intp(n))NEWLINENEWLINE print('benchmark float64'.center(80, '='))NEWLINE for n in [100, 1000, 10000, 100000, 1000000, 10000000]:NEWLINE print('n = {0}'.format(n))NEWLINE for t in range(3):NEWLINE print(benchmark_float64(n))NEWLINENEWLINE # Note: On Carrizo, speedup is attained at n=1,000,000NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE main()NEWLINE #Escreva um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o último nome separadamente.NEWLINE#Ex.: Ana Maria de SouzaNEWLINE#primeiro = AnaNEWLINE#último = SouzaNEWLINEnome = str(input('Digite seu nome: ')).strip()NEWLINEs = nome.split()NEWLINEprint('Seu primeiro nome é {}'.format(s[0]))NEWLINE#print('Seu último nome é {}'.format(s[len(s)-1]))NEWLINEprint('Seu último nome é {}'.format(s[-1]))NEWLINE # model settingsNEWLINEmodel = dict(NEWLINE type="RPN",NEWLINE pretrained="open-mmlab://resnet50_caffe",NEWLINE backbone=dict(NEWLINE type="ResNet",NEWLINE depth=50,NEWLINE num_stages=4,NEWLINE out_indices=(0, 1, 2, 3),NEWLINE frozen_stages=1,NEWLINE norm_cfg=dict(type="BN", requires_grad=False),NEWLINE norm_eval=True,NEWLINE style="caffe",NEWLINE ),NEWLINE neck=dict(NEWLINE type="FPN", in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5NEWLINE ),NEWLINE rpn_head=dict(NEWLINE type="GARPNHead",NEWLINE in_channels=256,NEWLINE feat_channels=256,NEWLINE octave_base_scale=8,NEWLINE scales_per_octave=3,NEWLINE octave_ratios=[0.5, 1.0, 2.0],NEWLINE anchor_strides=[4, 8, 16, 32, 64],NEWLINE anchor_base_sizes=None,NEWLINE anchoring_means=[0.0, 0.0, 0.0, 0.0],NEWLINE anchoring_stds=[0.07, 0.07, 0.14, 0.14],NEWLINE target_means=(0.0, 0.0, 0.0, 0.0),NEWLINE target_stds=[0.07, 0.07, 0.11, 0.11],NEWLINE loc_filter_thr=0.01,NEWLINE loss_loc=dict(NEWLINE type="FocalLoss", use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0NEWLINE ),NEWLINE loss_shape=dict(type="BoundedIoULoss", beta=0.2, loss_weight=1.0),NEWLINE loss_cls=dict(type="CrossEntropyLoss", use_sigmoid=True, loss_weight=1.0),NEWLINE loss_bbox=dict(type="SmoothL1Loss", beta=1.0, loss_weight=1.0),NEWLINE ),NEWLINE)NEWLINE# model training and testing settingsNEWLINEtrain_cfg = dict(NEWLINE rpn=dict(NEWLINE ga_assigner=dict(NEWLINE type="ApproxMaxIoUAssigner",NEWLINE pos_iou_thr=0.7,NEWLINE neg_iou_thr=0.3,NEWLINE min_pos_iou=0.3,NEWLINE ignore_iof_thr=-1,NEWLINE ),NEWLINE ga_sampler=dict(NEWLINE type="RandomSampler",NEWLINE num=256,NEWLINE pos_fraction=0.5,NEWLINE neg_pos_ub=-1,NEWLINE add_gt_as_proposals=False,NEWLINE ),NEWLINE assigner=dict(NEWLINE type="MaxIoUAssigner",NEWLINE pos_iou_thr=0.7,NEWLINE neg_iou_thr=0.3,NEWLINE min_pos_iou=0.3,NEWLINE ignore_iof_thr=-1,NEWLINE ),NEWLINE sampler=dict(NEWLINE type="RandomSampler",NEWLINE num=256,NEWLINE pos_fraction=0.5,NEWLINE neg_pos_ub=-1,NEWLINE add_gt_as_proposals=False,NEWLINE ),NEWLINE allowed_border=-1,NEWLINE pos_weight=-1,NEWLINE center_ratio=0.2,NEWLINE ignore_ratio=0.5,NEWLINE debug=False,NEWLINE )NEWLINE)NEWLINEtest_cfg = dict(NEWLINE rpn=dict(NEWLINE nms_across_levels=False,NEWLINE nms_pre=2000,NEWLINE nms_post=2000,NEWLINE max_num=2000,NEWLINE nms_thr=0.7,NEWLINE min_bbox_size=0,NEWLINE )NEWLINE)NEWLINE# dataset settingsNEWLINEdataset_type = "CocoDataset"NEWLINEdata_root = "data/coco/"NEWLINEimg_norm_cfg = dict(NEWLINE mean=[102.9801, 115.9465, 122.7717], std=[1.0, 1.0, 1.0], to_rgb=FalseNEWLINE)NEWLINEtrain_pipeline = [NEWLINE dict(type="LoadImageFromFile"),NEWLINE dict(type="LoadAnnotations", with_bbox=True, with_label=False),NEWLINE dict(type="Resize", img_scale=(1333, 800), keep_ratio=True),NEWLINE dict(type="RandomFlip", flip_ratio=0.5),NEWLINE dict(type="Normalize", **img_norm_cfg),NEWLINE dict(type="Pad", size_divisor=32),NEWLINE dict(type="DefaultFormatBundle"),NEWLINE dict(type="Collect", keys=["img", "gt_bboxes"]),NEWLINE]NEWLINEtest_pipeline = [NEWLINE dict(type="LoadImageFromFile"),NEWLINE dict(NEWLINE type="MultiScaleFlipAug",NEWLINE img_scale=(1333, 800),NEWLINE flip=False,NEWLINE transforms=[NEWLINE dict(type="Resize", keep_ratio=True),NEWLINE dict(type="RandomFlip"),NEWLINE dict(type="Normalize", **img_norm_cfg),NEWLINE dict(type="Pad", size_divisor=32),NEWLINE dict(type="ImageToTensor", keys=["img"]),NEWLINE dict(type="Collect", keys=["img"]),NEWLINE ],NEWLINE ),NEWLINE]NEWLINEdata = dict(NEWLINE imgs_per_gpu=2,NEWLINE workers_per_gpu=2,NEWLINE train=dict(NEWLINE type=dataset_type,NEWLINE ann_file=data_root + "annotations/instances_train2017.json",NEWLINE img_prefix=data_root + "train2017/",NEWLINE pipeline=train_pipeline,NEWLINE ),NEWLINE val=dict(NEWLINE type=dataset_type,NEWLINE ann_file=data_root + "annotations/instances_val2017.json",NEWLINE img_prefix=data_root + "val2017/",NEWLINE pipeline=test_pipeline,NEWLINE ),NEWLINE test=dict(NEWLINE type=dataset_type,NEWLINE ann_file=data_root + "annotations/instances_val2017.json",NEWLINE img_prefix=data_root + "val2017/",NEWLINE pipeline=test_pipeline,NEWLINE ),NEWLINE)NEWLINEevaluation = dict(interval=1, metric="proposal_fast")NEWLINE# optimizerNEWLINEoptimizer = dict(type="SGD", lr=0.02, momentum=0.9, weight_decay=0.0001)NEWLINE# runner configsNEWLINEoptimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))NEWLINElr_config = dict(NEWLINE policy="step", warmup="linear", warmup_iters=500, warmup_ratio=1.0 / 3, step=[8, 11]NEWLINE)NEWLINEcheckpoint_config = dict(interval=1)NEWLINE# yapf:disableNEWLINElog_config = dict(NEWLINE interval=50,NEWLINE hooks=[NEWLINE dict(type="TextLoggerHook"),NEWLINE # dict(type='TensorboardLoggerHook')NEWLINE ],NEWLINE)NEWLINE# yapf:enableNEWLINE# runtime settingsNEWLINEtotal_epochs = 12NEWLINEdist_params = dict(backend="nccl")NEWLINElog_level = "INFO"NEWLINEwork_dir = "./work_dirs/ga_rpn_r50_caffe_fpn_1x"NEWLINEload_from = NoneNEWLINEresume_from = NoneNEWLINEworkflow = [("train", 1)]NEWLINE """NEWLINEDataset module for managing text datasets.NEWLINE"""NEWLINE__author__ = 'victor'NEWLINEfrom collections import OrderedDictNEWLINEimport randomNEWLINEimport numpy as npNEWLINENEWLINENEWLINEclass InvalidFieldsException(Exception):NEWLINE passNEWLINENEWLINENEWLINEclass Dataset(object):NEWLINE """NEWLINE Generic Dataset object that encapsulates a list of instances.NEWLINENEWLINE The dataset stores the instances in an ordered dictionary of fields.NEWLINE Each field maps to a list, the ith element of the list for field 'foo' corresponds to the attribute 'foo' for the ith instance in the dataset.NEWLINENEWLINE The dataset object supports indexing, iterating, slicing (eg. for iterating over batches), shuffling,NEWLINE conversion to/from CONLL format, among others.NEWLINENEWLINE Example:NEWLINENEWLINE .. code-block:: pythonNEWLINENEWLINE d = Dataset({'Name': ['Alice', 'Bob', 'Carol', 'David', 'Ellen'], 'SSN': [1, 23, 45, 56, 7890]})NEWLINE print(d) # Dataset(Name, SSN)NEWLINE print(d[2]) # OrderedDict([('SSN', 45), ('Name', 'Carol')])NEWLINE print(d[1:3]) # OrderedDict([('SSN', [23, 45]), ('Name', ['Bob', 'Carol'])])NEWLINENEWLINE for e in d:NEWLINE print(e) # OrderedDict([('SSN', 1), ('Name', 'Alice')]) ...NEWLINE """NEWLINENEWLINE def __init__(self, fields):NEWLINE """NEWLINE :param fields: An ordered dictionary in which a key is the name of an attribute and a value is a list of the values of the instances in the dataset.NEWLINENEWLINE :return: A Dataset objectNEWLINE """NEWLINE self.fields = OrderedDict(fields)NEWLINE length = NoneNEWLINE length_field = NoneNEWLINE for name, d in fields.items():NEWLINE if length is None:NEWLINE length = len(d)NEWLINE length_field = nameNEWLINE else:NEWLINE if len(d) != length:NEWLINE raise InvalidFieldsException('field {} has length {} but field {} has length {}'.format(length_field, length, name, len(d)))NEWLINENEWLINE def __len__(self):NEWLINE """NEWLINE :return: The number of instances in the dataset.NEWLINE """NEWLINE if len(self.fields) == 0:NEWLINE return 0NEWLINE return len(self.fields.values()[0])NEWLINENEWLINE def __repr__(self):NEWLINE return "{}({})".format(self.__class__.__name__, ', '.join(self.fields.keys()))NEWLINENEWLINE @classmethodNEWLINE def load_conll(cls, fname):NEWLINE """NEWLINE The CONLL file must have a tab delimited header, for example::NEWLINENEWLINE # description tagsNEWLINE AliceNEWLINE Hello t1NEWLINE my t2NEWLINE name t3NEWLINE is t4NEWLINE alice t5NEWLINENEWLINE BobNEWLINE I'm t1NEWLINE bob t2NEWLINENEWLINE Here, the fields are `description` and `tags`. The first instance has the label `Alice` and theNEWLINE description `['Hello', 'my', 'name', 'is', 'alice']` and the tags `['t1', 't2', 't3', 't4', 't5']`.NEWLINE The second instance has the label `Bob` and the description `["I'm", 'bob']` and the tags `['t1', 't2']`.NEWLINENEWLINE :param fname: The CONLL formatted file from which to load the datasetNEWLINENEWLINE :return: loaded Dataset instanceNEWLINE """NEWLINE def process_cache(cache, fields):NEWLINE cache = [l.split() for l in cache if l]NEWLINE if not cache:NEWLINE return NoneNEWLINE fields['label'].append(cache[0][0])NEWLINE instance = {k: [] for k in fields if k != 'label'}NEWLINE for l in cache[1:]:NEWLINE for i, k in enumerate(fields):NEWLINE if k != 'label':NEWLINE instance[k].append(None if l[i] == '-' else l[i])NEWLINE for k, v in instance.items():NEWLINE fields[k].append(v)NEWLINENEWLINE cache = []NEWLINENEWLINE with open(fname) as f:NEWLINE header = f.next().strip().split('\t')NEWLINE header[0] = header[0].lstrip('# ')NEWLINE fields = OrderedDict([(head, []) for head in header])NEWLINE fields['label'] = []NEWLINE for line in f:NEWLINE line = line.strip()NEWLINE if line:NEWLINE cache.append(line)NEWLINE else:NEWLINE # met empty line, process cacheNEWLINE process_cache(cache, fields)NEWLINE cache = []NEWLINE if cache:NEWLINE process_cache(cache, fields)NEWLINE return cls(fields)NEWLINENEWLINE def write_conll(self, fname):NEWLINE """NEWLINE Serializes the dataset in CONLL format to fnameNEWLINE """NEWLINE if 'label' not in self.fields:NEWLINE raise InvalidFieldsException("dataset is not in CONLL format: missing label field")NEWLINENEWLINE def instance_to_conll(inst):NEWLINE tab = [v for k, v in inst.items() if k != 'label']NEWLINE return '{}\n{}'.format(inst['label'], '\n'.join(['\t'.join(['-' if e is None else str(e) for e in row]) for row in zip(*tab)]))NEWLINENEWLINE with open(fname, 'wb') as f:NEWLINE f.write('# {}'.format('\t'.join([k for k in self.fields if k != 'label'])))NEWLINE for i, d in enumerate(self):NEWLINE f.write('\n{}'.format(instance_to_conll(d)))NEWLINE if i != len(self) - 1:NEWLINE f.write('\n')NEWLINENEWLINE def convert(self, converters, in_place=False):NEWLINE """NEWLINE Applies transformations to the dataset.NEWLINENEWLINE :param converters: A dictionary specifying the function to apply to each field. If a field is missing from the dictionary, then it will not be transformed.NEWLINENEWLINE :param in_place: Whether to perform the transformation in place or create a new dataset instanceNEWLINENEWLINE :return: the transformed dataset instanceNEWLINE """NEWLINE dataset = self if in_place else self.__class__(OrderedDict([(name, data[:]) for name, data in self.fields.items()]))NEWLINE for name, convert in converters.items():NEWLINE if name not in self.fields.keys():NEWLINE raise InvalidFieldsException('Converter specified for non-existent field {}'.format(name))NEWLINE for i, d in enumerate(dataset.fields[name]):NEWLINE dataset.fields[name][i] = convert(d)NEWLINE return datasetNEWLINENEWLINE def shuffle(self):NEWLINE """NEWLINE Re-indexes the dataset in random orderNEWLINENEWLINE :return: the shuffled dataset instanceNEWLINE """NEWLINE order = range(len(self))NEWLINE random.shuffle(order)NEWLINE for name, data in self.fields.items():NEWLINE reindexed = []NEWLINE for _, i in enumerate(order):NEWLINE reindexed.append(data[i])NEWLINE self.fields[name] = reindexedNEWLINE return selfNEWLINENEWLINE def __getitem__(self, item):NEWLINE """NEWLINE :param item: An integer index or a slice (eg. 2, 1:, 1:5)NEWLINENEWLINE :return: an ordered dictionary of the instance(s) at index/indices `item`.NEWLINE """NEWLINE return OrderedDict([(name, data[item]) for name, data in self.fields.items()])NEWLINENEWLINE def __setitem__(self, key, value):NEWLINE """NEWLINE :param key: An integer index or a slice (eg. 2, 1:, 1:5)NEWLINENEWLINE :param value: Sets the instances at index/indices `key` to the instances(s) `value`NEWLINE """NEWLINE for name, data in self.fields.items():NEWLINE if name not in value:NEWLINE raise InvalidFieldsException('field {} is missing in input data: {}'.format(name, value))NEWLINE data[key] = value[name]NEWLINENEWLINE def __iter__(self):NEWLINE """NEWLINE :return: A iterator over the instances in the datasetNEWLINE """NEWLINE for i in xrange(len(self)):NEWLINE yield self[i]NEWLINENEWLINE def copy(self, keep_fields=None):NEWLINE """NEWLINE :param keep_fields: if specified, then only the given fields will be keptNEWLINE :return: A deep copy of the dataset (each instance is copied).NEWLINE """NEWLINE keep_fields = self.fields.keys() or keep_fieldsNEWLINE return self.__class__(OrderedDict([(name, data[:]) for name, data in self.fields.items() if name in keep_fields]))NEWLINENEWLINE @classmethodNEWLINE def pad(cls, sequences, padding, pad_len=None):NEWLINE """NEWLINE Pads a list of sequences such that they form a matrix.NEWLINENEWLINE :param sequences: a list of sequences of varying lengths.NEWLINE :param padding: the value of padded cells.NEWLINE :param pad_len: the length of the maximum padded sequence.NEWLINE """NEWLINE max_len = max([len(s) for s in sequences])NEWLINE pad_len = pad_len or max_lenNEWLINE assert pad_len >= max_len, 'pad_len {} must be greater or equal to the longest sequence {}'.format(pad_len, max_len)NEWLINE for i, s in enumerate(sequences):NEWLINE sequences[i] = [padding] * (pad_len - len(s)) + sNEWLINE return np.array(sequences)NEWLINE from Find_the_last_Fibonacci_digit_hardcore_version_6_kyu import last_fib_digitNEWLINEimport unittestNEWLINENEWLINEclass Fibonacci(unittest.TestCase):NEWLINE def test_1(self):NEWLINE n = 7000006NEWLINE result = 3NEWLINE self.assertEqual(last_fib_digit(n), result)NEWLINE def test_1(self):NEWLINE n = 9000000008NEWLINE result = 4NEWLINE self.assertEqual(last_fib_digit(n), result) NEWLINENEWLINEif __name__ == "__main__":NEWLINE unittest.main() from typing import ListNEWLINENEWLINEfrom bleak.backends.service import BleakGATTServiceNEWLINEfrom bleak.backends.bluezdbus.characteristic import BleakGATTCharacteristicBlueZDBusNEWLINENEWLINENEWLINEclass BleakGATTServiceBlueZDBus(BleakGATTService):NEWLINE """GATT Service implementation for the BlueZ DBus backend"""NEWLINENEWLINE def __init__(self, obj, path):NEWLINE super().__init__(obj)NEWLINE self.__characteristics = []NEWLINE self.__path = pathNEWLINENEWLINE @propertyNEWLINE def uuid(self) -> str:NEWLINE """The UUID to this service"""NEWLINE return self.obj["UUID"]NEWLINENEWLINE @propertyNEWLINE def characteristics(self) -> List[BleakGATTCharacteristicBlueZDBus]:NEWLINE """List of characteristics for this service"""NEWLINE return self.__characteristicsNEWLINENEWLINE def add_characteristic(self, characteristic: BleakGATTCharacteristicBlueZDBus):NEWLINE """Add a :py:class:`~BleakGATTCharacteristicBlueZDBus` to the service.NEWLINENEWLINE Should not be used by end user, but rather by `bleak` itself.NEWLINE """NEWLINE self.__characteristics.append(characteristic)NEWLINENEWLINE @propertyNEWLINE def path(self):NEWLINE """The DBus path. Mostly needed by `bleak`, not by end user"""NEWLINE return self.__pathNEWLINE # Generated by Django 2.2.8 on 2019-12-23 10:46NEWLINENEWLINEimport datetimeNEWLINEfrom django.db import migrations, modelsNEWLINEfrom django.utils.timezone import utcNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE initial = TrueNEWLINENEWLINE dependencies = [NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.CreateModel(NEWLINE name='BulletinUpdate',NEWLINE fields=[NEWLINE ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),NEWLINE ('time_of_quake', models.DateTimeField(default=datetime.datetime(1900, 1, 1, 0, 0, tzinfo=utc))),NEWLINE ('url', models.URLField(unique=True)),NEWLINE ('latitude', models.DecimalField(decimal_places=2, max_digits=5)),NEWLINE ('longitude', models.DecimalField(decimal_places=2, max_digits=5)),NEWLINE ('depth', models.DecimalField(decimal_places=1, max_digits=4)),NEWLINE ('magnitude', models.DecimalField(decimal_places=1, max_digits=3)),NEWLINE ('location', models.CharField(default='', max_length=2048)),NEWLINE ],NEWLINE options={NEWLINE 'ordering': ['-time_of_quake'],NEWLINE },NEWLINE ),NEWLINE migrations.AddIndex(NEWLINE model_name='bulletinupdate',NEWLINE index=models.Index(fields=['time_of_quake'], name='bulletin_bu_time_of_9e0643_idx'),NEWLINE ),NEWLINE migrations.AddIndex(NEWLINE model_name='bulletinupdate',NEWLINE index=models.Index(fields=['url'], name='bulletin_bu_url_4b9def_idx'),NEWLINE ),NEWLINE ]NEWLINE from functools import wrapsNEWLINENEWLINEfrom flask import Flask, render_template, url_for, redirect, request, session, flash, get_flashed_messages, abort, BlueprintNEWLINEfrom sqlalchemy import create_engine, or_, and_NEWLINEfrom sqlalchemy.orm import sessionmakerNEWLINEfrom werkzeug.security import check_password_hash, generate_password_hashNEWLINENEWLINEfrom db_models import User, BookNEWLINENEWLINENEWLINEapp = Flask(__name__)NEWLINEapp.config.from_object("config.ProductionConfig")NEWLINENEWLINENEWLINEdef redirect_url(default='index'):NEWLINE return request.args.get('next') or \NEWLINE request.referrer or \NEWLINE url_for(default)NEWLINENEWLINENEWLINEdef get_session(echo=False):NEWLINE engine = create_engine('sqlite:///db/database.db', echo=echo)NEWLINE db_session = sessionmaker(bind=engine)NEWLINE return db_session()NEWLINENEWLINENEWLINEdef get_default_context():NEWLINE permission_lvl = get_user_auth_lvl()NEWLINE context = {'permission_lvl': permission_lvl,NEWLINE 'user_id': session.get('user_id'),NEWLINE 'username': session.get('username')}NEWLINE return contextNEWLINENEWLINENEWLINEdef get_user_auth_lvl():NEWLINE if not session.get('user_id'):NEWLINE return 3NEWLINENEWLINE db_session = get_session()NEWLINE user_data = db_session.query(User.permission_lvl) \NEWLINE .filter(User.username == session.get('username')) \NEWLINE .one()NEWLINE return user_data.permission_lvlNEWLINENEWLINENEWLINEdef get_borrow_limit(username):NEWLINE db_session = get_session()NEWLINE user_data = db_session.query(User.book_limit) \NEWLINE .filter(User.username == username) \NEWLINE .one()NEWLINE return user_data.book_limitNEWLINENEWLINENEWLINEdef get_borrowed(username):NEWLINE db_session = get_session()NEWLINE return db_session.query(Book).join(User).filter(User.username == username).all()NEWLINENEWLINENEWLINEdef count_borrowed(username):NEWLINE return len(get_borrowed(username))NEWLINENEWLINENEWLINEdef user_exists(username):NEWLINE db_session = get_session()NEWLINE return db_session.query(User.id).filter_by(username=username).scalar() is not NoneNEWLINENEWLINENEWLINEdef is_able_to_borrow(username):NEWLINE borrow_limit = get_borrow_limit(username)NEWLINE if borrow_limit == 0:NEWLINE return TrueNEWLINE if count_borrowed(username) < borrow_limit:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINEdef is_borrowed(book_id):NEWLINE db_session = get_session()NEWLINE result = db_session.query(Book) \NEWLINE .filter(and_(Book.id == book_id, Book.user_id == None)) \NEWLINE .scalar()NEWLINENEWLINE return True if result is None else FalseNEWLINENEWLINENEWLINEdef login_required(lvl=3):NEWLINE def frame(func):NEWLINE @wraps(func)NEWLINE def wrapped_func(*args, **kwargs):NEWLINE if get_user_auth_lvl() <= lvl:NEWLINE return func(*args, **kwargs)NEWLINE else:NEWLINE flash('Access denied')NEWLINE return redirect('/login')NEWLINE return wrapped_funcNEWLINENEWLINE return frameNEWLINENEWLINENEWLINE@app.route('/')NEWLINE@app.route('/index')NEWLINEdef index():NEWLINE context = get_default_context()NEWLINE return render_template('index.html', **context)NEWLINENEWLINENEWLINE@app.route('/catalog/books')NEWLINEdef books():NEWLINE db_session = get_session()NEWLINE all_books = db_session.query(Book).all()NEWLINENEWLINE context = get_default_context()NEWLINE context['books'] = all_booksNEWLINENEWLINE return render_template('catalog.html', **context)NEWLINENEWLINENEWLINE@app.route('/catalog/books/')NEWLINEdef book(book_id):NEWLINE db_session = get_session()NEWLINE mybook = db_session.query(Book).filter(Book.id == book_id).scalar()NEWLINENEWLINE if not mybook:NEWLINE abort(404)NEWLINENEWLINE context = get_default_context()NEWLINE context['book'] = mybookNEWLINE return render_template('book.html', **context)NEWLINENEWLINENEWLINE@app.route('/catalog/books/add_book', methods=['GET', 'POST'])NEWLINE@login_required(lvl=1)NEWLINEdef add_book():NEWLINE if request.method == 'GET':NEWLINE context = get_default_context()NEWLINE return render_template('add_book.html', **context)NEWLINENEWLINE if request.method == 'POST':NEWLINE db_session = get_session()NEWLINENEWLINE new_book = Book()NEWLINE new_book.isbn = request.form['isbn']NEWLINE new_book.author = request.form['author']NEWLINE new_book.description = request.form['description']NEWLINE new_book.isbn = request.form['isbn']NEWLINE new_book.pages = request.form['pages']NEWLINE new_book.published = request.form['published']NEWLINE new_book.publisher = request.form['publisher']NEWLINE new_book.subtitle = request.form['subtitle']NEWLINE new_book.title = request.form['title']NEWLINE new_book.website = request.form['website']NEWLINENEWLINE db_session.add(new_book)NEWLINE db_session.commit()NEWLINENEWLINE return redirect(url_for('books'))NEWLINENEWLINENEWLINE@app.route('/catalog/books//edit', methods=['GET', 'POST'])NEWLINE@login_required(lvl=1)NEWLINEdef edit_book(book_id):NEWLINE if request.method == 'GET':NEWLINE db_session = get_session()NEWLINE mybook = db_session.query(Book).filter(Book.id == book_id).scalar()NEWLINENEWLINE if not mybook:NEWLINE abort(404)NEWLINENEWLINE context = get_default_context()NEWLINE context['book'] = mybookNEWLINE return render_template('edit_book.html', **context)NEWLINENEWLINE if request.method == 'POST':NEWLINE db_session = get_session()NEWLINENEWLINE book = db_session.query(Book).filter(Book.id == book_id).one()NEWLINE book.isbn = request.form['isbn']NEWLINE book.author = request.form['author']NEWLINE book.description = request.form['description']NEWLINE book.isbn = request.form['isbn']NEWLINE book.pages = request.form['pages']NEWLINE book.published = request.form['published']NEWLINE book.publisher = request.form['publisher']NEWLINE book.subtitle = request.form['subtitle']NEWLINE book.title = request.form['title']NEWLINE book.website = request.form['website']NEWLINENEWLINE db_session.commit()NEWLINENEWLINE return redirect(f'/catalog/books/{book_id}')NEWLINENEWLINENEWLINE@app.route('/catalog/books/remove_book', methods=['GET', 'POST'])NEWLINE@login_required(lvl=1)NEWLINEdef remove_book():NEWLINE if request.method == 'GET':NEWLINE context = get_default_context()NEWLINE return render_template('remove_book.html', **context)NEWLINENEWLINE if request.method == 'POST':NEWLINE book_id = request.form['book_id']NEWLINENEWLINE db_session = get_session()NEWLINE db_session.query(Book). \NEWLINE filter(Book.id == book_id) \NEWLINE .delete()NEWLINENEWLINE db_session.commit()NEWLINENEWLINE return redirect(url_for('books'))NEWLINENEWLINENEWLINE@app.route('/login', methods=['GET', 'POST'])NEWLINEdef login():NEWLINE if request.method == 'GET':NEWLINE context = get_default_context()NEWLINE context['messages'] = get_flashed_messages()NEWLINENEWLINE return render_template('login.html', **context)NEWLINENEWLINE if request.method == 'POST':NEWLINE db_session = get_session()NEWLINENEWLINE username = request.form['username']NEWLINE pwd = request.form['password']NEWLINENEWLINE user_data = db_session.query(User).filter(User.username == username).scalar()NEWLINENEWLINE if user_data:NEWLINE hashed_password = user_data.passwordNEWLINENEWLINE if check_password_hash(hashed_password, pwd):NEWLINE session['user_id'] = user_data.idNEWLINE session['username'] = user_data.usernameNEWLINE return redirect(url_for('index'))NEWLINENEWLINE flash('Wrong email or password.')NEWLINE return redirect(url_for('login'))NEWLINENEWLINENEWLINE@app.route('/register', methods=['GET', 'POST'])NEWLINEdef register():NEWLINE if request.method == 'GET':NEWLINE context = get_default_context()NEWLINE context['messages'] = get_flashed_messages()NEWLINENEWLINE return render_template('register.html', **context)NEWLINENEWLINE if request.method == 'POST':NEWLINE db_session = get_session()NEWLINENEWLINE username = request.form['username']NEWLINE pwd = request.form['password']NEWLINE pwd_repeat = request.form['repeat_password']NEWLINE email = request.form['email']NEWLINE permission_lvl = 2NEWLINE book_limit = 5NEWLINENEWLINE if db_session.query(User).filter(User.username == username).scalar():NEWLINE flash('User already exists')NEWLINE return redirect(url_for('register'))NEWLINENEWLINE if db_session.query(User).filter(User.email == email).scalar():NEWLINE flash('Email already exists')NEWLINE return redirect(url_for('register'))NEWLINENEWLINE if pwd != pwd_repeat:NEWLINE flash('Password doesn\'t match')NEWLINE return redirect(url_for('register'))NEWLINENEWLINE new_user = User()NEWLINE new_user.username = usernameNEWLINE new_user.password = generate_password_hash(pwd)NEWLINE new_user.email = emailNEWLINE new_user.permission_lvl = permission_lvlNEWLINE new_user.book_limit = book_limitNEWLINENEWLINE db_session.add(new_user)NEWLINE db_session.commit()NEWLINENEWLINE return redirect(url_for('login'))NEWLINENEWLINENEWLINE@app.route('/logout')NEWLINEdef logout():NEWLINE session.clear()NEWLINE return redirect(url_for('login'))NEWLINENEWLINENEWLINE@app.route('/page_not_found')NEWLINEdef page_not_found():NEWLINE return render_template('404.html')NEWLINENEWLINENEWLINE@app.route('/catalog/books/borrow', methods=["POST"])NEWLINE@login_required(lvl=2)NEWLINEdef borrow_book():NEWLINE db_session = get_session()NEWLINE book_id = request.form['borrow_book_id']NEWLINENEWLINE if is_borrowed(book_id):NEWLINE return redirect(url_for('book', book_id=book_id))NEWLINENEWLINE if not is_able_to_borrow(session.get('username')):NEWLINE return redirect(url_for('book', book_id=book_id))NEWLINENEWLINE db_session.query(Book) \NEWLINE .filter(Book.id == book_id) \NEWLINE .update({'user_id': session.get('user_id')})NEWLINE db_session.commit()NEWLINENEWLINE return redirect(redirect_url())NEWLINENEWLINENEWLINE@app.route('/catalog/books/return', methods=["POST"])NEWLINE@login_required(lvl=2)NEWLINEdef return_book():NEWLINE db_session = get_session()NEWLINE book_id = request.form['return_book_id']NEWLINENEWLINE db_session.query(Book) \NEWLINE .filter(Book.id == book_id) \NEWLINE .update({'user_id': None})NEWLINE db_session.commit()NEWLINENEWLINE return redirect(redirect_url())NEWLINENEWLINENEWLINE@app.route('/users')NEWLINE@login_required(lvl=1)NEWLINEdef users():NEWLINE db_session = get_session()NEWLINE users = []NEWLINENEWLINE all_users = db_session.query(User).all()NEWLINE for user in all_users:NEWLINE count_books = db_session.query(Book).filter(Book.user_id == user.id).count()NEWLINE users.append({'username': user.username, 'count_books': count_books})NEWLINENEWLINE context = get_default_context()NEWLINE context['users'] = usersNEWLINENEWLINE return render_template('users.html', **context)NEWLINENEWLINENEWLINE@app.route('/users/user/')NEWLINE@login_required(lvl=2)NEWLINEdef user_profile(username):NEWLINE context = get_default_context()NEWLINENEWLINE if context['permission_lvl'] == 1:NEWLINE passNEWLINE elif username != context['username']:NEWLINE abort(401)NEWLINENEWLINE if not user_exists(username):NEWLINE abort(404)NEWLINENEWLINE context['profile_username'] = usernameNEWLINE context['borrowed_books'] = get_borrowed(username)NEWLINE context['current_user'] = username == session.get('username')NEWLINE return render_template('user_profile.html', **context)NEWLINENEWLINENEWLINE@app.route('/users/user//edit', methods=["GET", "POST"])NEWLINE@login_required(lvl=2)NEWLINEdef user_profile_edit(username):NEWLINE if request.method == 'GET':NEWLINE context = get_default_context()NEWLINE context['messages'] = get_flashed_messages()NEWLINENEWLINE if context['permission_lvl'] == 1:NEWLINE passNEWLINE elif username != context['username']:NEWLINE abort(401)NEWLINENEWLINE if not user_exists(username):NEWLINE abort(404)NEWLINENEWLINE db_session = get_session()NEWLINE user = db_session.query(User).filter(User.username == username).one()NEWLINENEWLINE context['user'] = userNEWLINENEWLINE return render_template('user_profile_edit.html', **context)NEWLINENEWLINE if request.method == 'POST':NEWLINE db_session = get_session()NEWLINENEWLINE email = request.form['email']NEWLINE book_limit = request.form.get('book_limit')NEWLINE permission_lvl = request.form.get('permission_lvl')NEWLINENEWLINE user = db_session.query(User).filter(User.username == username).one()NEWLINENEWLINE user.email = emailNEWLINE if permission_lvl:NEWLINE user.permission_lvl = permission_lvlNEWLINE if book_limit:NEWLINE user.book_limit = book_limitNEWLINENEWLINE db_session.commit()NEWLINENEWLINE flash('Changes saved')NEWLINENEWLINE return redirect(f'/users/user/{username}/edit')NEWLINENEWLINENEWLINE@app.route('/search_results')NEWLINEdef search_results():NEWLINE arg = request.args.get('query')NEWLINE db_session = get_session()NEWLINE context = get_default_context()NEWLINENEWLINE books = db_session.query(Book).filter(NEWLINE or_(NEWLINE Book.title.contains(arg),NEWLINE Book.author.contains(arg)NEWLINE )NEWLINE ).all()NEWLINENEWLINE context['books'] = booksNEWLINENEWLINE return render_template('search_results.html', **context)NEWLINENEWLINENEWLINE@app.route('/test')NEWLINEdef t_page():NEWLINE result = session.get('username')NEWLINE return str(result)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE app.run()NEWLINE # -*- coding: utf-8 -*-NEWLINE# Generated by Django 1.10.5 on 2017-04-11 07:35NEWLINEfrom __future__ import unicode_literalsNEWLINENEWLINEfrom django.conf import settingsNEWLINEfrom django.db import migrations, modelsNEWLINEimport django.db.models.deletionNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ('vdnapp', '0015_auto_20170411_0735'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.AlterField(NEWLINE model_name='organization',NEWLINE name='user',NEWLINE field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),NEWLINE ),NEWLINE ]NEWLINE from django.contrib import adminNEWLINEfrom .models import OrderItem,orderNEWLINEfrom import_export.admin import ImportExportActionModelAdminNEWLINEfrom django.urls import reverseNEWLINEfrom django.utils.safestring import mark_safeNEWLINENEWLINENEWLINEdef order_pdf(obj):NEWLINE return mark_safe('PDF'.format(reverse('orders:admin_order_pdf',args=[obj.id])))NEWLINENEWLINEorder_pdf.short_description = 'Order PDF'NEWLINENEWLINENEWLINENEWLINEclass OrderItemAdmin(admin.TabularInline):NEWLINE '''NEWLINE Admin View for OrderItemNEWLINE '''NEWLINE model = OrderItemNEWLINE raw_id_fields = ['product']NEWLINENEWLINENEWLINEclass OrderAdmin(ImportExportActionModelAdmin):NEWLINE '''NEWLINE Admin View for OrderNEWLINE '''NEWLINE list_display = ('id','first_name','last_name','address','email','city','postal_code','paid',order_pdf,)NEWLINE list_filter = ('paid','created','updated',)NEWLINE search_fields = ['first_name','last_name','email']NEWLINE inlines = [NEWLINE OrderItemAdmin,NEWLINE ]NEWLINENEWLINEadmin.site.register(order, OrderAdmin) """NEWLINE==============================NEWLINEWFIRST Instruments (pre-alpha)NEWLINE==============================NEWLINENEWLINEWARNING: This model has not yet been validated against other PSFNEWLINE simulations, and uses several approximations (e.g. forNEWLINE mirror polishing errors, which are taken from HST).NEWLINE"""NEWLINENEWLINEimport os.pathNEWLINEimport poppyNEWLINEimport numpy as npNEWLINEfrom . import webbpsf_coreNEWLINEfrom scipy.interpolate import griddataNEWLINEfrom astropy.io import fitsNEWLINEimport loggingNEWLINENEWLINE_log = logging.getLogger('webbpsf')NEWLINEimport pprintNEWLINENEWLINENEWLINEclass WavelengthDependenceInterpolator(object):NEWLINE """WavelengthDependenceInterpolator can be configured withNEWLINE `n_zernikes` worth of Zernike coefficients at up to `n_wavelengths`NEWLINE wavelengths, and will let you `get_aberration_terms` for anyNEWLINE wavelength in range interpolated linearly between measured/knownNEWLINE pointsNEWLINE """NEWLINENEWLINE def __init__(self, n_wavelengths=16, n_zernikes=22):NEWLINE self._n_wavelengths = n_wavelengthsNEWLINE self._n_zernikes = n_zernikesNEWLINE self._aberration_terms = np.zeros((n_wavelengths, n_zernikes), dtype=np.float64)NEWLINE self._wavelengths = []NEWLINENEWLINE def set_aberration_terms(self, wavelength, zernike_array):NEWLINE """Supply a reference `wavelength` and a `zernike_array`NEWLINE (of length `n_zernikes`) where the aberration is knownNEWLINE """NEWLINE n_wavelengths_set = len(self._wavelengths)NEWLINE if wavelength not in self._wavelengths and n_wavelengths_set < self._n_wavelengths:NEWLINE self._wavelengths.append(wavelength)NEWLINE aberration_row_idx = n_wavelengths_set # which is now index of last rowNEWLINE elif wavelength in self._wavelengths:NEWLINE aberration_row_idx = self._wavelengths.index(wavelength)NEWLINE else:NEWLINE # can't add more wavelengths without allocating new _aberration_terms arrayNEWLINE raise ValueError("Already have information at {} wavelengths "NEWLINE "(pass larger n_wavelengths to __init__?)".format(self._n_wavelengths))NEWLINE if len(zernike_array) != self._n_zernikes:NEWLINE raise ValueError("Expected {} aberration terms (pass different "NEWLINE "n_zernikes to __init__?)".format(self._n_zernikes))NEWLINE self._aberration_terms[aberration_row_idx] = zernike_arrayNEWLINENEWLINE def get_aberration_terms(self, wavelength):NEWLINE """Return the Zernike coefficients as interpolated for thisNEWLINE `wavelength`"""NEWLINE # return array of length n_zernikes interpolated for this wavelengthNEWLINE if wavelength in self._wavelengths:NEWLINE # aberration known exactly for this wavelengthNEWLINE aberration_row_idx = self._wavelengths.index(wavelength)NEWLINE return self._aberration_terms[aberration_row_idx]NEWLINE else:NEWLINE # we have to interpolate @ this wavelengthNEWLINE aberration_terms = griddata(self._wavelengths, self._aberration_terms, wavelength, method='linear')NEWLINE if np.any(np.isnan(aberration_terms)):NEWLINE raise RuntimeError("Attempted to get aberrations at wavelength "NEWLINE "outside the range of the reference data")NEWLINE return aberration_termsNEWLINENEWLINENEWLINEclass FieldDependentAberration(poppy.ZernikeWFE):NEWLINE """FieldDependentAberration incorporates aberrations thatNEWLINE are interpolated in wavelength, x, and y pixel positions byNEWLINE computing the Zernike coefficients for a particular wavelengthNEWLINE and position.NEWLINE """NEWLINENEWLINE """By default, `get_aberration_terms` will zero out Z1, Z2, and Z3NEWLINE (piston, tip, and tilt) as they are not meaningful for telescopeNEWLINE PSF calculations (the former is irrelevant, the latter two wouldNEWLINE be handled by a distortion solution). ChangeNEWLINE `_omit_piston_tip_tilt` to False to include the Z1-3 terms."""NEWLINE _omit_piston_tip_tilt = TrueNEWLINE _field_position = NoneNEWLINENEWLINE def __init__(self, pixel_width, pixel_height,NEWLINE name="Field-dependent Aberration", radius=1.0, oversample=1, interp_order=3):NEWLINE self.pixel_width, self.pixel_height = pixel_width, pixel_heightNEWLINE self.field_position = pixel_width // 2, pixel_height // 2NEWLINE self._wavelength_interpolators = {}NEWLINE self.pupil_diam = radius * 2.0NEWLINE super(FieldDependentAberration, self).__init__(NEWLINE name=name,NEWLINE verbose=True,NEWLINE radius=radius,NEWLINE oversample=oversample,NEWLINE interp_order=interp_orderNEWLINE )NEWLINENEWLINE def get_opd(self, wave, units='meters'):NEWLINE """Set the Zernike coefficients (for ZernikeWFE.getOPD) basedNEWLINE on the wavelength of the incoming wavefront and the pixelNEWLINE positionNEWLINE """NEWLINE if not isinstance(wave, poppy.Wavefront):NEWLINE wavelength = waveNEWLINE else:NEWLINE wavelength = wave.wavelengthNEWLINE self.coefficients = wavelength * self.get_aberration_terms(wavelength)NEWLINE return super(FieldDependentAberration, self).get_opd(wave, units=units)NEWLINENEWLINE @propertyNEWLINE def field_position(self):NEWLINE return self._field_positionNEWLINENEWLINE @field_position.setterNEWLINE def field_position(self, position):NEWLINE """Set the x and y pixel position on the detector for which toNEWLINE interpolate aberrations"""NEWLINE x_pixel, y_pixel = positionNEWLINE if x_pixel > self.pixel_width or x_pixel < 0:NEWLINE raise ValueError("Requested pixel_x position lies outside "NEWLINE "the detector width ({})".format(x_pixel))NEWLINE if y_pixel > self.pixel_height or y_pixel < 0:NEWLINE raise ValueError("Requested pixel_y position lies outside "NEWLINE "the detector height ({})".format(y_pixel))NEWLINENEWLINE self._field_position = x_pixel, y_pixelNEWLINENEWLINE def add_field_point(self, x_pixel, y_pixel, interpolator):NEWLINE """Supply a wavelength-space interpolator for a pixel positionNEWLINE on the detector"""NEWLINE self._wavelength_interpolators[(x_pixel, y_pixel)] = interpolatorNEWLINENEWLINE def get_aberration_terms(self, wavelength):NEWLINE """Supply the Zernike coefficients for the aberration based onNEWLINE the wavelength and pixel position on the detector"""NEWLINE if self.field_position in self._wavelength_interpolators:NEWLINE # short path: this is a known pointNEWLINE interpolator = self._wavelength_interpolators[self.field_position]NEWLINE coefficients = interpolator.get_aberration_terms(wavelength)NEWLINE else:NEWLINE # get aberrations at all field pointsNEWLINE field_points, aberration_terms = [], []NEWLINE for field_point_coords, point_interpolator in self._wavelength_interpolators.items():NEWLINE field_points.append(field_point_coords)NEWLINE aberration_terms.append(point_interpolator.get_aberration_terms(wavelength))NEWLINE aberration_array = np.asarray(aberration_terms)NEWLINE assert len(aberration_array.shape) == 2, "computed aberration array is not 2D " \NEWLINE "(inconsistent number of Zernike terms " \NEWLINE "at each point?)"NEWLINE coefficients = griddata(NEWLINE np.asarray(field_points),NEWLINE np.asarray(aberration_terms),NEWLINE self.field_position,NEWLINE method='linear'NEWLINE )NEWLINE if np.any(np.isnan(coefficients)):NEWLINE raise RuntimeError("Attempted to get aberrations for an out-of-bounds field point")NEWLINE if self._omit_piston_tip_tilt:NEWLINE _log.debug("Omitting piston/tip/tilt")NEWLINE coefficients[:3] = 0.0 # omit piston, tip, and tilt ZernikesNEWLINE return coefficientsNEWLINENEWLINENEWLINEdef _load_wfi_detector_aberrations(filename):NEWLINE from astropy.io import asciiNEWLINE zernike_table = ascii.read(filename)NEWLINE detectors = {}NEWLINENEWLINE def build_detector_from_table(number, zernike_table):NEWLINE """Build a FieldDependentAberration optic for a detector usingNEWLINE Zernikes Z1-Z22 at various wavelengths and field points"""NEWLINE single_detector_info = zernike_table[zernike_table['sca'] == number]NEWLINE field_points = set(single_detector_info['field_point'])NEWLINE interpolators = {}NEWLINE detector = FieldDependentAberration(NEWLINE 4096,NEWLINE 4096,NEWLINE radius=WFIRSTInstrument.PUPIL_RADIUS,NEWLINE name="Field Dependent Aberration (SCA{:02})".format(number)NEWLINE )NEWLINE for field_id in field_points:NEWLINE field_point_rows = single_detector_info[single_detector_info['field_point'] == field_id]NEWLINE local_x, local_y = field_point_rows[0]['local_x'], field_point_rows[0]['local_y']NEWLINE interpolator = build_wavelength_dependence(field_point_rows)NEWLINENEWLINE midpoint_pixel = 4096 / 2NEWLINE # (local_x in mm / 10 um pixel size) -> * 1e2NEWLINE # local_x and _y range from -20.44 to +20.44, so adding to the midpoint pixelNEWLINE # makes sense to place (-20.44, -20.44) at (4, 4)NEWLINE pixx, pixy = (round(midpoint_pixel + local_x * 1e2),NEWLINE round(midpoint_pixel + local_y * 1e2))NEWLINENEWLINE detector.add_field_point(pixx, pixy, interpolator)NEWLINE return detectorNEWLINENEWLINE def build_wavelength_dependence(rows):NEWLINE """Build an interpolator object that interpolates Z1-Z22 inNEWLINE wavelength space"""NEWLINE wavelengths = set(rows['wavelength'])NEWLINE interpolator = WavelengthDependenceInterpolator(n_wavelengths=len(wavelengths),NEWLINE n_zernikes=22)NEWLINE for row in rows:NEWLINE z = np.zeros(22)NEWLINE for idx in range(22):NEWLINE z[idx] = row['Z{}'.format(idx + 1)]NEWLINE interpolator.set_aberration_terms(row['wavelength'] * 1e-6, z)NEWLINENEWLINE return interpolatorNEWLINENEWLINE detector_ids = set(zernike_table['sca'])NEWLINE for detid in detector_ids:NEWLINE detectors["SCA{:02}".format(detid)] = build_detector_from_table(detid, zernike_table)NEWLINENEWLINE return detectorsNEWLINENEWLINENEWLINEclass WFIRSTInstrument(webbpsf_core.SpaceTelescopeInstrument):NEWLINE PUPIL_RADIUS = 2.4 / 2.0NEWLINE """NEWLINE WFIRSTInstrument contains data and functionality common to WFIRSTNEWLINE instruments, such as setting the pupil shapeNEWLINE """NEWLINE telescope = "WFIRST"NEWLINENEWLINE def __init__(self, *args, **kwargs):NEWLINE super(WFIRSTInstrument, self).__init__(*args, **kwargs)NEWLINENEWLINE # slightly different versions of the following two functionsNEWLINE # from the parent superclassNEWLINE # in order to interface with the FieldDependentAberration classNEWLINE @propertyNEWLINE def detector_position(self):NEWLINE """The pixel position in (X, Y) on the detector"""NEWLINE return self._detectors[self._detector].field_positionNEWLINENEWLINE @detector_position.setterNEWLINE def detector_position(self, position):NEWLINE # exact copy of superclass function except we save theNEWLINE # into a different location.NEWLINE try:NEWLINE x, y = map(int, position)NEWLINE except ValueError:NEWLINE raise ValueError("Detector pixel coordinates must be pairs of nonnegative numbers, "NEWLINE "not {}".format(position))NEWLINE if x < 0 or y < 0:NEWLINE raise ValueError("Detector pixel coordinates must be nonnegative integers")NEWLINE if x > self._detector_npixels - 1 or y > self._detector_npixels - 1:NEWLINE raise ValueError("The maximum allowed detector pixel "NEWLINE "coordinate value is {}".format(self._detector_npixels - 1))NEWLINENEWLINE self._detectors[self._detector].field_position = (int(position[0]), int(position[1]))NEWLINENEWLINE def _get_aberrations(self):NEWLINE """Get the OpticalElement that applies the field-dependentNEWLINE optical aberrations. (Called in _getOpticalSystem.)"""NEWLINE return self._detectors[self._detector]NEWLINENEWLINE def _get_fits_header(self, result, options):NEWLINE """Populate FITS Header keywords"""NEWLINE super(WFIRSTInstrument, self)._get_fits_header(result, options)NEWLINE result[0].header['DETXPIXL'] = (self.detector_position[0],NEWLINE 'X pixel position (for field dependent aberrations)')NEWLINE result[0].header['DETYPIXL'] = (self.detector_position[1],NEWLINE 'Y pixel position (for field dependent aberrations)')NEWLINE result[0].header['DETECTOR'] = (self.detector, 'Detector selected')NEWLINENEWLINENEWLINEclass WFI(WFIRSTInstrument):NEWLINE """NEWLINE WFI represents to the to-be-named wide field imagerNEWLINE for the WFIRST missionNEWLINENEWLINE WARNING: This model has not yet been validated against other PSFNEWLINE simulations, and uses several approximations (e.g. forNEWLINE mirror polishing errors, which are taken from HST).NEWLINE """NEWLINE # "The H158, F184 and W149 filters and the grism are mounted with proximate cold pupil masks"NEWLINE # from the final draft of the SDT report, page 92, table 3-2NEWLINE UNMASKED_PUPIL_WAVELENGTH_MIN, UNMASKED_PUPIL_WAVELENGTH_MAX = 0.760e-6, 1.454e-6NEWLINE MASKED_PUPIL_WAVELENGTH_MIN, MASKED_PUPIL_WAVELENGTH_MAX = 1.380e-6, 2.000e-6NEWLINENEWLINE def __init__(self, set_pupil_mask_on=None):NEWLINE """NEWLINE Initiate WFINEWLINENEWLINE ParametersNEWLINE -----------NEWLINE set_pupil_mask_on : bool or NoneNEWLINE Set to True or False to force using or not using the cold pupil mask,NEWLINE or to None for the automatic behavior.NEWLINE """NEWLINE pixelscale = 110e-3 # arcsec/px, WFIRST-AFTA SDT report final version (p. 91)NEWLINE super(WFI, self).__init__("WFI", pixelscale=pixelscale)NEWLINENEWLINE self._detector_npixels = 4096NEWLINE self._detectors = _load_wfi_detector_aberrations(os.path.join(self._datapath, 'wim_zernikes_cycle7.csv'))NEWLINE assert len(self._detectors.keys()) > 0NEWLINE self.detector = 'SCA01'NEWLINENEWLINE # Paths to the two possible pupils. The correct one is selected based on requestedNEWLINE # wavelengths in _validate_config()NEWLINE self._unmasked_pupil_path = os.path.join(self._WebbPSF_basepath,NEWLINE 'WFIRST_SRR_WFC_Pupil_Mask_Shortwave_2048.fits')NEWLINE self._masked_pupil_path = os.path.join(self._WebbPSF_basepath,NEWLINE 'WFIRST_SRR_WFC_Pupil_Mask_Longwave_2048.fits')NEWLINENEWLINE # Flag to en-/disable automatic selection of the appropriate pupil_maskNEWLINE self.auto_pupil = TrueNEWLINENEWLINE self._pupil_mask = "AUTO"NEWLINE self.pupil_mask_list = ['AUTO', 'COLD_PUPIL', 'UNMASKED']NEWLINENEWLINE self.pupil = self._unmasked_pupil_pathNEWLINE if set_pupil_mask_on is not None:NEWLINE if isinstance(set_pupil_mask_on, bool):NEWLINE self.auto_pupil = FalseNEWLINE _log.info("Using custom pupil mask")NEWLINE if set_pupil_mask_on:NEWLINE self.pupil = self._masked_pupil_pathNEWLINE else:NEWLINE raise TypeError("set_pupil_mask_on parameter must be boolean")NEWLINENEWLINE self.opd_list = [NEWLINE os.path.join(self._WebbPSF_basepath, 'upscaled_HST_OPD.fits'),NEWLINE ]NEWLINE self.pupilopd = self.opd_list[-1]NEWLINENEWLINE def _validate_config(self, **kwargs):NEWLINE """Validates that the WFI is configured sensiblyNEWLINENEWLINE This mainly consists of selecting the masked or unmasked pupilNEWLINE appropriately based on the wavelengths requested.NEWLINE """NEWLINE if self.auto_pupil and self.pupil in (self._unmasked_pupil_path, self._masked_pupil_path):NEWLINE # Does the wavelength range fit entirely in an unmasked filter?NEWLINE wavelengths = np.array(kwargs['wavelengths'])NEWLINE wl_min, wl_max = np.min(wavelengths), np.max(wavelengths)NEWLINE # test shorter filters first; if wl range fits entirely in one of them, it's not goingNEWLINE # to be the (masked) wideband filterNEWLINE if wl_max <= self.UNMASKED_PUPIL_WAVELENGTH_MAX:NEWLINE # use unmasked pupil opticNEWLINE self.pupil = self._unmasked_pupil_pathNEWLINE _log.info("Using the unmasked WFI pupil shape based on wavelengths requested")NEWLINE else:NEWLINE if wl_max > self.MASKED_PUPIL_WAVELENGTH_MAX:NEWLINE _log.warn("Requested wavelength is > 2e-6 m, defaulting to masked pupil shape")NEWLINE # use masked pupil opticNEWLINE self.pupil = self._masked_pupil_pathNEWLINE _log.info("Using the masked WFI pupil shape based on wavelengths requested")NEWLINE else:NEWLINE # If the user has set the pupil to a custom value, let them worry about theNEWLINE # correct shape it should haveNEWLINE passNEWLINE super(WFI, self)._validate_config(**kwargs)NEWLINENEWLINE @propertyNEWLINE def pupil_mask(self):NEWLINE return self._pupil_maskNEWLINENEWLINE @pupil_mask.setterNEWLINE def pupil_mask(self, name):NEWLINE """ Set the pupil maskNEWLINENEWLINE ParametersNEWLINE ------------NEWLINE name : stringNEWLINE Name of setting.NEWLINE Settings:NEWLINE - "AUTO":NEWLINE Automatically select pupilNEWLINE - "COLD_PUPIL":NEWLINE Masked pupil overrideNEWLINE - "UNMASKED":NEWLINE Unmasked pupil overrideNEWLINE """NEWLINENEWLINE if name and isinstance(name, str):NEWLINE name = name.upper()NEWLINE if "AUTO" == name:NEWLINE self.auto_pupil = TrueNEWLINE _log.info("Using default pupil mask.")NEWLINE elif "COLD_PUPIL" == name:NEWLINE self.auto_pupil = FalseNEWLINE _log.info("Using custom pupil mask: Masked Pupil.")NEWLINE self.pupil = self._masked_pupil_pathNEWLINE elif "UNMASKED" == name:NEWLINE self.auto_pupil = FalseNEWLINE _log.info("Using custom pupil mask: Unmasked Pupil.")NEWLINE self.pupil = self._unmasked_pupil_pathNEWLINE else:NEWLINE raise ValueError("Instrument {0} doesn't have a pupil mask called '{1}'.".format(self.name, name))NEWLINE else:NEWLINE raise ValueError("Pupil mask setting is not valid or empty.")NEWLINE self._pupil_mask = nameNEWLINENEWLINE def _addAdditionalOptics(self, optsys, **kwargs):NEWLINE return optsys, False, NoneNEWLINENEWLINENEWLINEclass CGI(WFIRSTInstrument):NEWLINE """NEWLINE WFIRST Coronagraph InstrumentNEWLINENEWLINE Simulates the PSF of the WFIRST coronagraph.NEWLINENEWLINE Current functionality is limited to the Shaped Pupil Coronagraph (SPC)NEWLINE observing modes, and these modes are only simulated with static, unaberratedNEWLINE wavefronts, without relay optics and without DM control. The designNEWLINE respresented here is an approximation to a baseline concept, and will beNEWLINE subject to change based on trades studies and technology development.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE mode : strNEWLINE CGI observing mode. If not specified, the __init__ functionNEWLINE will set this to a default mode 'CHARSPC_F660'NEWLINE pixelscale : floatNEWLINE Detector pixelscale. If not specified, the pixelscale will default toNEWLINE 0.02 arcsec for configurations usint the IMAGER camera and 0.025 arcsecNEWLINE for the IFS.NEWLINE fov_arcsec : floatNEWLINE Field of view in arcseconds. If not specified, the field of view willNEWLINE default to 3.20 arcsec for the IMAGER camera and 1.76 arcsec for the IFS.NEWLINENEWLINE """NEWLINENEWLINE camera_list = ['IMAGER', 'IFS']NEWLINE filter_list = ['F660', 'F721', 'F770', 'F890']NEWLINE apodizer_list = ['CHARSPC', 'DISKSPC']NEWLINE fpm_list = ['CHARSPC_F660_BOWTIE', 'CHARSPC_F770_BOWTIE', 'CHARSPC_F890_BOWTIE', 'DISKSPC_F721_ANNULUS']NEWLINE lyotstop_list = ['LS30D88']NEWLINENEWLINE _mode_table = { # MODE CAMERA FILTER APODIZER FPM LYOT STOPNEWLINE 'CHARSPC_F660': ('IFS', 'F660', 'CHARSPC', 'CHARSPC_F660_BOWTIE', 'LS30D88'),NEWLINE 'CHARSPC_F770': ('IFS', 'F770', 'CHARSPC', 'CHARSPC_F770_BOWTIE', 'LS30D88'),NEWLINE 'CHARSPC_F890': ('IFS', 'F890', 'CHARSPC', 'CHARSPC_F890_BOWTIE', 'LS30D88'),NEWLINE 'DISKSPC_F721': ('IMAGER', 'F721', 'DISKSPC', 'DISKSPC_F721_ANNULUS', 'LS30D88')}NEWLINENEWLINE def __init__(self, mode=None, pixelscale=None, fov_arcsec=None, apply_static_opd=False):NEWLINE super(CGI, self).__init__("CGI", pixelscale=pixelscale)NEWLINENEWLINE self._detector_npixels = 1024NEWLINE self._detectors = {camera: 'placeholder' for camera in self.camera_list}NEWLINENEWLINE self.pupil_mask_list = self.lyotstop_list # alias for use in webbpsf_coreNEWLINE self.image_mask_list = self.fpm_list # alias for use in webbpsf_coreNEWLINE self.pupil = os.path.join(self._WebbPSF_basepath, 'AFTA_CGI_C5_Pupil_onax_256px_flip.fits')NEWLINE if apply_static_opd:NEWLINE self.pupilopd = os.path.join(self._WebbPSF_basepath, 'CGI', 'OPD', 'CGI_static_OPD.fits')NEWLINE else:NEWLINE self.pupilopd = NoneNEWLINE self.aberration_optic = NoneNEWLINE self.options = {'force_coron': True}NEWLINE # Allow the user to pre-emptively override the default instrument FoV and pixel scaleNEWLINE if fov_arcsec is not None:NEWLINE self.fov_arcsec = fov_arcsecNEWLINE self._override_fov = TrueNEWLINE else:NEWLINE self._override_fov = FalseNEWLINE if pixelscale is not None:NEWLINE self._pixelscale = pixelscaleNEWLINE self._override_pixelscale = TrueNEWLINE else:NEWLINE self._override_pixelscale = FalseNEWLINENEWLINE if mode is None:NEWLINE self.print_mode_table()NEWLINE _log.info("Since the mode was not specified at instantiation, defaulting to CHARSPC_F660")NEWLINE self.mode = 'CHARSPC_F660'NEWLINE else:NEWLINE self.mode = modeNEWLINENEWLINE @propertyNEWLINE def camera(self):NEWLINE """Currently selected camera name"""NEWLINE return self._cameraNEWLINENEWLINE @camera.setterNEWLINE def camera(self, value):NEWLINE value = value.upper() # force to uppercaseNEWLINE if value not in self.camera_list:NEWLINE raise ValueError("Instrument {0} doesn't have a camera called {1}.".format(self.name, value))NEWLINE self._camera = valueNEWLINE if value == 'IMAGER':NEWLINE if not hasattr(self, 'fov_arcsec') or not self._override_fov:NEWLINE self.fov_arcsec = 3.2NEWLINE if not hasattr(self, 'pixelscale') or not self._override_pixelscale:NEWLINE self.pixelscale = 0.020 # Nyquist at 465 nmNEWLINE else: # default to 'IFS'NEWLINE if not hasattr(self, 'fov_arcsec') or not self._override_fov:NEWLINE self.fov_arcsec = 2 * 0.82 # 2015 SDT report, Section 3.4.1.1.1:NEWLINE # IFS has 76 lenslets across the (2 x 0.82) arcsec FoV.NEWLINE if not hasattr(self, 'pixelscale') or not self._override_pixelscale:NEWLINE self.pixelscale = 0.025 # Nyquist at 600 nmNEWLINENEWLINE # for CGI, there is one detector per camera and it should be set automatically.NEWLINE @propertyNEWLINE def detector(self):NEWLINE return self.cameraNEWLINENEWLINE @detector.setterNEWLINE def detector(self, value):NEWLINE raise RuntimeError("Can't set detector directly for CGI; set camera instead.")NEWLINENEWLINE @propertyNEWLINE def filter(self):NEWLINE """Currently selected filter name"""NEWLINE return self._filterNEWLINENEWLINE @filter.setterNEWLINE def filter(self, value):NEWLINE value = value.upper() # force to uppercaseNEWLINE if value not in self.filter_list:NEWLINE raise ValueError("Instrument {0} doesn't have a filter called {1}.".format(self.name, value))NEWLINE self._filter = valueNEWLINENEWLINE @propertyNEWLINE def apodizer(self):NEWLINE """Currently selected apodizer name"""NEWLINE return self._apodizerNEWLINENEWLINE @apodizer.setterNEWLINE def apodizer(self, value):NEWLINE value = value.upper() # force to uppercaseNEWLINE if value not in self.apodizer_list:NEWLINE raise ValueError("Instrument {0} doesn't have a apodizer called {1}.".format(self.name, value))NEWLINE self._apodizer = valueNEWLINE if value == 'DISKSPC':NEWLINE self._apodizer_fname = \NEWLINE os.path.join(self._datapath, "optics/DISKSPC_SP_256pix.fits.gz")NEWLINE else: # for now, default to CHARSPCNEWLINE self._apodizer_fname = \NEWLINE os.path.join(self._datapath, "optics/CHARSPC_SP_256pix.fits.gz")NEWLINENEWLINE @propertyNEWLINE def fpm(self):NEWLINE """Currently selected FPM name"""NEWLINE return self._fpmNEWLINENEWLINE @fpm.setterNEWLINE def fpm(self, value):NEWLINE value = value.upper() # force to uppercaseNEWLINE if value not in self.fpm_list:NEWLINE raise ValueError("Instrument {0} doesn't have a FPM called {1}.".format(self.name, value))NEWLINE self._fpm = valueNEWLINE if value.startswith('DISKSPC'):NEWLINE self._fpmres = 3NEWLINE self._owa = 20.NEWLINE self._Mfpm = int(np.ceil(self._fpmres * self._owa))NEWLINE self._fpm_fname = \NEWLINE os.path.join(self._datapath,NEWLINE "optics/DISKSPC_FPM_65WA200_360deg_-_FP1res{0:d}_evensamp_D{1:03d}_{2:s}.fits.gz".format(NEWLINE self._fpmres, 2 * self._Mfpm, self.filter))NEWLINE else:NEWLINE self._fpmres = 4NEWLINE self._owa = 9.NEWLINE self._Mfpm = int(np.ceil(self._fpmres * self._owa))NEWLINE self._fpm_fname = \NEWLINE os.path.join(self._datapath,NEWLINE "optics/CHARSPC_FPM_25WA90_2x65deg_-_FP1res{0:d}_evensamp_D{1:03d}_{2:s}.fits.gz".format(NEWLINE self._fpmres, 2 * self._Mfpm, self.filter))NEWLINENEWLINE @propertyNEWLINE def lyotstop(self):NEWLINE """Currently selected Lyot stop name"""NEWLINE return self._lyotstopNEWLINENEWLINE @lyotstop.setterNEWLINE def lyotstop(self, value):NEWLINE # preserve case for this one since we're used to that with the lyot mask namesNEWLINE if value not in self.lyotstop_list:NEWLINE raise ValueError("Instrument {0} doesn't have a Lyot mask called {1}.".format(self.name, value))NEWLINE self._lyotstop = valueNEWLINE self._lyotstop_fname = os.path.join(self._datapath, "optics/SPC_LS_30D88_256pix.fits.gz")NEWLINENEWLINE @propertyNEWLINE def mode_list(self):NEWLINE """Available Observation Modes"""NEWLINE keys = self._mode_table.keys()NEWLINE keys = sorted(keys)NEWLINE return keysNEWLINENEWLINE # mode works differently since it's a meta-property that affects the other ones:NEWLINE @propertyNEWLINE def mode(self):NEWLINE """Currently selected mode name"""NEWLINE for modename, settings in self._mode_table.items():NEWLINE if (self.camera == settings[0].upper() and self.filter == settings[1].upper() andNEWLINE self.apodizer == settings[2].upper() and self.fpm == settings[3].upper() andNEWLINE self.lyotstop == settings[4]):NEWLINE return modenameNEWLINE return 'Custom'NEWLINENEWLINE @mode.setterNEWLINE def mode(self, value):NEWLINE if value not in self.mode_list:NEWLINE raise ValueError("Instrument {0} doesn't have a mode called {1}.".format(self.name, value))NEWLINE settings = self._mode_table[value]NEWLINE self.camera = settings[0]NEWLINE self.filter = settings[1]NEWLINE self.apodizer = settings[2]NEWLINE self.fpm = settings[3]NEWLINE self.lyotstop = settings[4]NEWLINE _log.info('Set the following optical configuration:')NEWLINE _log.info('camera = {0}, filter = {1}, apodizer = {2}, fpm = {3}, lyotstop = {4}'.format(\NEWLINE self.camera, self.filter, self.apodizer, self.fpm, self.lyotstop))NEWLINENEWLINE def print_mode_table(self):NEWLINE """Print the table of observing mode options and their associated optical configuration"""NEWLINE _log.info("Printing the table of WFIRST CGI observing modes supported by WebbPSF.")NEWLINE _log.info("Each is defined by a combo of camera, filter, apodizer, "NEWLINE "focal plane mask (FPM), and Lyot stop settings:")NEWLINE _log.info(pprint.pformat(self._mode_table))NEWLINENEWLINE @propertyNEWLINE def detector_position(self):NEWLINE """The pixel position in (X, Y) on the detector"""NEWLINE return 512, 512NEWLINENEWLINE @detector_position.setterNEWLINE def detector_position(self, position):NEWLINE raise RuntimeError("Detector position not adjustable for CGI")NEWLINENEWLINE def _validate_config(self, **kwargs):NEWLINE super(CGI, self)._validate_config(**kwargs)NEWLINENEWLINE def _addAdditionalOptics(self, optsys, oversample=4):NEWLINE """Add coronagraphic or spectrographic optics for WFIRST CGI."""NEWLINENEWLINE trySAM = FalseNEWLINENEWLINE if ('pupil_shift_x' in self.options and self.options['pupil_shift_x'] != 0) or \NEWLINE ('pupil_shift_y' in self.options and self.options['pupil_shift_y'] != 0):NEWLINE shift = (self.options['pupil_shift_x'], self.options['pupil_shift_y'])NEWLINE else:NEWLINE shift = NoneNEWLINENEWLINE # Add the shaped pupil apodizerNEWLINE optsys.add_pupil(transmission=self._apodizer_fname, name=self.apodizer, shift=None)NEWLINENEWLINE # Add the FPMNEWLINE optsys.add_image(transmission=self._fpm_fname, name=self.fpm)NEWLINENEWLINE # Add Lyot stopNEWLINE self.pupil_mask = self.lyotstopNEWLINE optsys.add_pupil(transmission=self._lyotstop_fname, name=self.lyotstop, shift=shift)NEWLINENEWLINE # Cast as MatrixFTCoronagraph; this configures the detectorNEWLINE occ_box_size = 1.NEWLINE mft_optsys = poppy.MatrixFTCoronagraph(optsys, oversample=oversample, occulter_box=occ_box_size)NEWLINENEWLINE return mft_optsys, trySAM, occ_box_sizeNEWLINENEWLINE def _get_aberrations(self):NEWLINE """Get the OpticalElement that applies the field-dependentNEWLINE optical aberrations. (Called in _getOpticalSystem.)"""NEWLINE return NoneNEWLINENEWLINE def _get_fits_header(self, result, options):NEWLINE """Populate FITS Header keywords"""NEWLINE super(WFIRSTInstrument, self)._get_fits_header(result, options)NEWLINE pupil_hdr = fits.getheader(self.pupil)NEWLINE apodizer_hdr = fits.getheader(self._apodizer_fname)NEWLINE fpm_hdr = fits.getheader(self._fpm_fname)NEWLINE lyotstop_hdr = fits.getheader(self._lyotstop_fname)NEWLINENEWLINE result[0].header.set('MODE', self.mode, comment='Observing mode')NEWLINE result[0].header.set('CAMERA', self.camera, comment='Imager or IFS')NEWLINE result[0].header.set('APODIZER', self.apodizer, comment='Apodizer')NEWLINE result[0].header.set('APODTRAN', os.path.basename(self._apodizer_fname),NEWLINE comment='Apodizer transmission')NEWLINE result[0].header.set('PUPLSCAL', apodizer_hdr['PUPLSCAL'],NEWLINE comment='Apodizer pixel scale in m/pixel')NEWLINE result[0].header.set('PUPLDIAM', apodizer_hdr['PUPLDIAM'],NEWLINE comment='Full apodizer array size, incl padding.')NEWLINE result[0].header.set('FPM', self.fpm, comment='Focal plane mask')NEWLINE result[0].header.set('FPMTRAN', os.path.basename(self._fpm_fname),NEWLINE comment='FPM transmission')NEWLINE result[0].header.set('FPMSCAL', fpm_hdr['PIXSCALE'], comment='FPM spatial sampling, arcsec/pix')NEWLINE result[0].header.set('LYOTSTOP', self.lyotstop, comment='Lyot stop')NEWLINE result[0].header.set('LSTRAN', os.path.basename(self._lyotstop_fname),NEWLINE comment='Lyot stop transmission')NEWLINE result[0].header.set('PUPLSCAL', lyotstop_hdr['PUPLSCAL'],NEWLINE comment='Lyot stop pixel scale in m/pixel')NEWLINE result[0].header.set('PUPLDIAM', lyotstop_hdr['PUPLDIAM'],NEWLINE comment='Lyot stop array size, incl padding.')NEWLINE # Copyright 2021 Google LLCNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE"""Module for running fuzzers."""NEWLINEimport enumNEWLINEimport loggingNEWLINEimport osNEWLINEimport shutilNEWLINEimport sysNEWLINEimport timeNEWLINENEWLINEimport clusterfuzz_deploymentNEWLINEimport fuzz_targetNEWLINEimport stack_parserNEWLINENEWLINE# pylint: disable=wrong-import-position,import-errorNEWLINEsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))NEWLINENEWLINEimport utilsNEWLINENEWLINENEWLINEclass RunFuzzersResult(enum.Enum):NEWLINE """Enum result from running fuzzers."""NEWLINE ERROR = 0NEWLINE BUG_FOUND = 1NEWLINE NO_BUG_FOUND = 2NEWLINENEWLINENEWLINEclass BaseFuzzTargetRunner:NEWLINE """Base class for fuzzer runners."""NEWLINENEWLINE def __init__(self, config):NEWLINE self.config = configNEWLINE self.clusterfuzz_deployment = (NEWLINE clusterfuzz_deployment.get_clusterfuzz_deployment(self.config))NEWLINE # Set by the initialize method.NEWLINE self.out_dir = NoneNEWLINE self.fuzz_target_paths = NoneNEWLINE self.artifacts_dir = NoneNEWLINENEWLINE def initialize(self):NEWLINE """Initialization method. Must be called before calling run_fuzz_targets.NEWLINE Returns True on success."""NEWLINE # Use a seperate initialization function so we can return False on failureNEWLINE # instead of exceptioning like we need to do if this were done in theNEWLINE # __init__ method.NEWLINENEWLINE logging.info('Using %s sanitizer.', self.config.sanitizer)NEWLINENEWLINE # TODO(metzman) Add a check to ensure we aren't over time limit.NEWLINE if not self.config.fuzz_seconds or self.config.fuzz_seconds < 1:NEWLINE logging.error(NEWLINE 'Fuzz_seconds argument must be greater than 1, but was: %s.',NEWLINE self.config.fuzz_seconds)NEWLINE return FalseNEWLINENEWLINE self.out_dir = os.path.join(self.config.workspace, 'out')NEWLINE if not os.path.exists(self.out_dir):NEWLINE logging.error('Out directory: %s does not exist.', self.out_dir)NEWLINE return FalseNEWLINENEWLINE self.artifacts_dir = os.path.join(self.out_dir, 'artifacts')NEWLINE if not os.path.exists(self.artifacts_dir):NEWLINE os.mkdir(self.artifacts_dir)NEWLINE elif (not os.path.isdir(self.artifacts_dir) orNEWLINE os.listdir(self.artifacts_dir)):NEWLINE logging.error('Artifacts path: %s exists and is not an empty directory.',NEWLINE self.artifacts_dir)NEWLINE return FalseNEWLINENEWLINE self.fuzz_target_paths = utils.get_fuzz_targets(self.out_dir)NEWLINE logging.info('Fuzz targets: %s', self.fuzz_target_paths)NEWLINE if not self.fuzz_target_paths:NEWLINE logging.error('No fuzz targets were found in out directory: %s.',NEWLINE self.out_dir)NEWLINE return FalseNEWLINENEWLINE return TrueNEWLINENEWLINE def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-useNEWLINE """Fuzzes with |fuzz_target_obj| and returns the result."""NEWLINE # TODO(metzman): Make children implement this so that the batch runner canNEWLINE # do things differently.NEWLINE result = fuzz_target_obj.fuzz()NEWLINE fuzz_target_obj.free_disk_if_needed()NEWLINE return resultNEWLINENEWLINE @propertyNEWLINE def quit_on_bug_found(self):NEWLINE """Property that is checked to determine if fuzzing should quit after firstNEWLINE bug is found."""NEWLINE raise NotImplementedError('Child class must implement method')NEWLINENEWLINE def get_fuzz_target_artifact(self, target, artifact_name):NEWLINE """Returns the path of a fuzzing artifact named |artifact_name| forNEWLINE |fuzz_target|."""NEWLINE artifact_name = '{target_name}-{sanitizer}-{artifact_name}'.format(NEWLINE target_name=target.target_name,NEWLINE sanitizer=self.config.sanitizer,NEWLINE artifact_name=artifact_name)NEWLINE return os.path.join(self.artifacts_dir, artifact_name)NEWLINENEWLINE def create_fuzz_target_obj(self, target_path, run_seconds):NEWLINE """Returns a fuzz target object."""NEWLINE return fuzz_target.FuzzTarget(target_path, run_seconds, self.out_dir,NEWLINE self.clusterfuzz_deployment, self.config)NEWLINENEWLINE def run_fuzz_targets(self):NEWLINE """Runs fuzz targets. Returns True if a bug was found."""NEWLINE fuzzers_left_to_run = len(self.fuzz_target_paths)NEWLINENEWLINE # Make a copy since we will mutate it.NEWLINE fuzz_seconds = self.config.fuzz_secondsNEWLINENEWLINE min_seconds_per_fuzzer = fuzz_seconds // fuzzers_left_to_runNEWLINE bug_found = FalseNEWLINE for target_path in self.fuzz_target_paths:NEWLINE # By doing this, we can ensure that every fuzz target runs for at leastNEWLINE # min_seconds_per_fuzzer, but that other fuzzers will have longer to runNEWLINE # if one ends early.NEWLINE run_seconds = max(fuzz_seconds // fuzzers_left_to_run,NEWLINE min_seconds_per_fuzzer)NEWLINENEWLINE target = self.create_fuzz_target_obj(target_path, run_seconds)NEWLINE start_time = time.time()NEWLINE result = self.run_fuzz_target(target)NEWLINENEWLINE # It's OK if this goes negative since we take max when determiningNEWLINE # run_seconds.NEWLINE fuzz_seconds -= time.time() - start_timeNEWLINENEWLINE fuzzers_left_to_run -= 1NEWLINE if not result.testcase or not result.stacktrace:NEWLINE logging.info('Fuzzer %s finished running without crashes.',NEWLINE target.target_name)NEWLINE continueNEWLINENEWLINE # We found a bug in the fuzz target.NEWLINE utils.binary_print(b'Fuzzer: %s. Detected bug:\n%s' %NEWLINE (target.target_name.encode(), result.stacktrace))NEWLINENEWLINE # TODO(metzman): Do this with filestore.NEWLINE testcase_artifact_path = self.get_fuzz_target_artifact(NEWLINE target, os.path.basename(result.testcase))NEWLINE shutil.move(result.testcase, testcase_artifact_path)NEWLINE bug_summary_artifact_path = self.get_fuzz_target_artifact(NEWLINE target, 'bug-summary.txt')NEWLINE stack_parser.parse_fuzzer_output(result.stacktrace,NEWLINE bug_summary_artifact_path)NEWLINENEWLINE bug_found = TrueNEWLINE if self.quit_on_bug_found:NEWLINE logging.info('Bug found. Stopping fuzzing.')NEWLINE return bug_foundNEWLINENEWLINE return bug_foundNEWLINENEWLINENEWLINEclass CiFuzzTargetRunner(BaseFuzzTargetRunner):NEWLINE """Runner for fuzz targets used in CI (patch-fuzzing) context."""NEWLINENEWLINE @propertyNEWLINE def quit_on_bug_found(self):NEWLINE return TrueNEWLINENEWLINENEWLINEclass BatchFuzzTargetRunner(BaseFuzzTargetRunner):NEWLINE """Runner for fuzz targets used in batch fuzzing context."""NEWLINENEWLINE @propertyNEWLINE def quit_on_bug_found(self):NEWLINE return FalseNEWLINENEWLINENEWLINEdef get_fuzz_target_runner(config):NEWLINE """Returns a fuzz target runner object based on the run_fuzzers_mode ofNEWLINE |config|."""NEWLINE logging.info('RUN_FUZZERS_MODE is: %s', config.run_fuzzers_mode)NEWLINE if config.run_fuzzers_mode == 'batch':NEWLINE return BatchFuzzTargetRunner(config)NEWLINE return CiFuzzTargetRunner(config)NEWLINENEWLINENEWLINEdef run_fuzzers(config): # pylint: disable=too-many-localsNEWLINE """Runs fuzzers for a specific OSS-Fuzz project.NEWLINENEWLINE Args:NEWLINE config: A RunFuzzTargetsConfig.NEWLINENEWLINE Returns:NEWLINE A RunFuzzersResult enum value indicating what happened during fuzzing.NEWLINE """NEWLINE fuzz_target_runner = get_fuzz_target_runner(config)NEWLINE if not fuzz_target_runner.initialize():NEWLINE # We didn't fuzz at all because of internal (CIFuzz) errors. And we didn'tNEWLINE # find any bugs.NEWLINE return RunFuzzersResult.ERRORNEWLINENEWLINE if not fuzz_target_runner.run_fuzz_targets():NEWLINE # We fuzzed successfully, but didn't find any bugs (in the fuzz target).NEWLINE return RunFuzzersResult.NO_BUG_FOUNDNEWLINENEWLINE # We fuzzed successfully and found bug(s) in the fuzz targets.NEWLINE return RunFuzzersResult.BUG_FOUNDNEWLINE import boto3NEWLINEimport sysNEWLINEfrom st2actions.runners.pythonrunner import ActionNEWLINENEWLINEclass GetStackBuildStatus(Action):NEWLINE def run(self, stack_name_or_id):NEWLINE region = self.config['region']NEWLINENEWLINE stack_states = ['CREATE_COMPLETE', 'CREATE_FAILED', 'ROLLBACK_COMPLETE']NEWLINENEWLINE client = boto3.client('cloudformation', region_name=region)NEWLINENEWLINE try:NEWLINE stack_status = client.describe_stacks(StackName=stack_name_or_id)['Stacks'][0]['StackStatus']NEWLINENEWLINE except Exception as err:NEWLINE sys.stderr.write('ERROR: %s\n' % str(err))NEWLINE raiseNEWLINENEWLINE if stack_status not in stack_states:NEWLINE sys.stderr.write('Current state: %s\n' % stack_status)NEWLINE sys.exit(2)NEWLINENEWLINE return TrueNEWLINE import plataNEWLINENEWLINENEWLINEdef plata_context(request):NEWLINE """NEWLINE Adds a few variables from Plata to the context if they are available:NEWLINENEWLINE * ``plata.shop``: The current :class:`plata.shop.views.Shop` instanceNEWLINE * ``plata.order``: The current orderNEWLINE * ``plata.contact``: The current contact instanceNEWLINE * ``plata.price_includes_tax``: Whether prices include tax or notNEWLINE """NEWLINENEWLINE shop = plata.shop_instance()NEWLINE return {'plata': {NEWLINE 'shop': shop,NEWLINE 'order': shop.order_from_request(request),NEWLINE 'contact': (shop.contact_from_user(request.user)NEWLINE if hasattr(request, 'user') else None),NEWLINE 'price_includes_tax': shop.price_includes_tax(request),NEWLINE }} if shop else {}NEWLINE # -*- coding: utf-8 -*-NEWLINE"""The app module, containing the app factory function."""NEWLINEfrom flask import Flask, render_templateNEWLINENEWLINEfrom hamcwebc import commands, public, userNEWLINEfrom hamcwebc.assets import assetsNEWLINEfrom hamcwebc.extensions import bcrypt, cache, csrf_protect, db, debug_toolbar, login_manager, migrate, celeryNEWLINEfrom hamcwebc.settings import ProdConfigNEWLINENEWLINENEWLINEdef create_app(config_object=ProdConfig):NEWLINE """An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/.NEWLINE :param config_object: The configuration object to use.NEWLINE """NEWLINE app = Flask(__name__)NEWLINE app.config.from_object(config_object)NEWLINE register_extensions(app)NEWLINE register_blueprints(app)NEWLINE register_errorhandlers(app)NEWLINE register_shellcontext(app)NEWLINE register_commands(app)NEWLINE return appNEWLINENEWLINENEWLINEdef register_extensions(app):NEWLINE """Register Flask extensions."""NEWLINE assets.init_app(app)NEWLINE bcrypt.init_app(app)NEWLINE cache.init_app(app)NEWLINE db.init_app(app)NEWLINE csrf_protect.init_app(app)NEWLINE login_manager.init_app(app)NEWLINE debug_toolbar.init_app(app)NEWLINE migrate.init_app(app, db)NEWLINE celery.conf.update(app.config)NEWLINE return NoneNEWLINENEWLINENEWLINEdef register_blueprints(app):NEWLINE """Register Flask blueprints."""NEWLINE app.register_blueprint(public.views.blueprint)NEWLINE app.register_blueprint(user.views.blueprint)NEWLINE return NoneNEWLINENEWLINENEWLINEdef register_errorhandlers(app):NEWLINE """Register error handlers."""NEWLINE def render_error(error):NEWLINE """Render error template."""NEWLINE # If a HTTPException, pull the `code` attribute; default to 500NEWLINE error_code = getattr(error, 'code', 500)NEWLINE return render_template('{0}.html'.format(error_code)), error_codeNEWLINE for errcode in [401, 404, 500]:NEWLINE app.errorhandler(errcode)(render_error)NEWLINE return NoneNEWLINENEWLINENEWLINEdef register_shellcontext(app):NEWLINE """Register shell context objects."""NEWLINE def shell_context():NEWLINE """Shell context objects."""NEWLINE return {NEWLINE 'db': db,NEWLINE 'celery': celery,NEWLINE 'User': user.models.User}NEWLINENEWLINE app.shell_context_processor(shell_context)NEWLINENEWLINENEWLINEdef register_commands(app):NEWLINE """Register Click commands."""NEWLINE app.cli.add_command(commands.test)NEWLINE app.cli.add_command(commands.lint)NEWLINE app.cli.add_command(commands.clean)NEWLINE app.cli.add_command(commands.urls)NEWLINE '''NEWLINEFile name: common_utils.pyNEWLINEProgrammed by: Mike BernardNEWLINEDate: 2019-11-08NEWLINENEWLINECommon helper functions used in multiple scripts.NEWLINE'''NEWLINENEWLINEfrom nav.utils.constants import PASSNEWLINENEWLINENEWLINEdef weighted_avg(values, weights):NEWLINE '''NEWLINE Takes a list of values and a list of weights associatedNEWLINE with those values (index-to-index) and returns a weightedNEWLINE averaged of those values as a float.NEWLINENEWLINE :param values: `list` of values to be averagedNEWLINE :param weights: `list` of weights for each value (index-to-index)NEWLINENEWLINE :return: `float` The weighted average of the valuesNEWLINE '''NEWLINE denom = sum([1 / w ** 2 for w in weights])NEWLINE num = sum([1 / w ** 2 * v for v, w in zip(values, weights)])NEWLINENEWLINE return num / denomNEWLINENEWLINENEWLINEdef unit_test(module_name, tests):NEWLINE '''NEWLINE Run a set of test functions and print out the results.NEWLINE See test directory for examples of how to structure these testsNEWLINE and how to set up calling this function.NEWLINE NEWLINE :param module_name: `str` the name of the module being testedNEWLINE :param tests: `list` of functions to test as objectsNEWLINE '''NEWLINE passed = 0NEWLINE failed = 0NEWLINE fail_messages = []NEWLINENEWLINE for test in tests:NEWLINE status, description = test()NEWLINE if status == PASS:NEWLINE passed += 1NEWLINE else:NEWLINE failed += 1NEWLINE fail_messages.append(description)NEWLINENEWLINE print(module_name, 'unit test results: ', end='')NEWLINE print('{} out of {} tests passed.'.format(passed, len(tests)))NEWLINE if len(fail_messages) > 0:NEWLINE print('Failed tests:')NEWLINE for msg in fail_messages:NEWLINE print('\t' + msg)NEWLINE # coding: utf-8NEWLINENEWLINE"""NEWLINE FlashBlade REST APINEWLINENEWLINE A lightweight client for FlashBlade REST API 2.3, developed by Pure Storage, Inc. (http://www.purestorage.com/).NEWLINENEWLINE OpenAPI spec version: 2.3NEWLINE NEWLINE Generated by: https://github.com/swagger-api/swagger-codegen.gitNEWLINE"""NEWLINENEWLINENEWLINEimport pprintNEWLINEimport reNEWLINENEWLINEimport sixNEWLINEimport typingNEWLINENEWLINEfrom ....properties import PropertyNEWLINEif typing.TYPE_CHECKING:NEWLINE from pypureclient.flashblade.FB_2_3 import modelsNEWLINENEWLINEclass CertificateUse(object):NEWLINE """NEWLINE Attributes:NEWLINE swagger_types (dict): The key is attribute nameNEWLINE and the value is attribute type.NEWLINE attribute_map (dict): The key is attribute nameNEWLINE and the value is json key in definition.NEWLINE """NEWLINE swagger_types = {NEWLINE 'name': 'str',NEWLINE 'id': 'str',NEWLINE 'group': 'FixedReference',NEWLINE 'use': 'FixedReferenceWithRemote'NEWLINE }NEWLINENEWLINE attribute_map = {NEWLINE 'name': 'name',NEWLINE 'id': 'id',NEWLINE 'group': 'group',NEWLINE 'use': 'use'NEWLINE }NEWLINENEWLINE required_args = {NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE name=None, # type: strNEWLINE id=None, # type: strNEWLINE group=None, # type: models.FixedReferenceNEWLINE use=None, # type: models.FixedReferenceWithRemoteNEWLINE ):NEWLINE """NEWLINE Keyword args:NEWLINE name (str): Name of the object (e.g., a file system or snapshot).NEWLINE id (str): A non-modifiable, globally unique ID chosen by the system.NEWLINE group (FixedReference): A reference to a certificate group that is being used, if any, where this certificate is a member of the certificate-group. This field is `null` if the referenced use object is not using a group, but is rather using this certificate directly.NEWLINE use (FixedReferenceWithRemote): A reference to an object using this certificate.NEWLINE """NEWLINE if name is not None:NEWLINE self.name = nameNEWLINE if id is not None:NEWLINE self.id = idNEWLINE if group is not None:NEWLINE self.group = groupNEWLINE if use is not None:NEWLINE self.use = useNEWLINENEWLINE def __setattr__(self, key, value):NEWLINE if key not in self.attribute_map:NEWLINE raise KeyError("Invalid key `{}` for `CertificateUse`".format(key))NEWLINE self.__dict__[key] = valueNEWLINENEWLINE def __getattribute__(self, item):NEWLINE value = object.__getattribute__(self, item)NEWLINE if isinstance(value, Property):NEWLINE return NoneNEWLINE else:NEWLINE return valueNEWLINENEWLINE def to_dict(self):NEWLINE """Returns the model properties as a dict"""NEWLINE result = {}NEWLINENEWLINE for attr, _ in six.iteritems(self.swagger_types):NEWLINE if hasattr(self, attr):NEWLINE value = getattr(self, attr)NEWLINE if isinstance(value, list):NEWLINE result[attr] = list(map(NEWLINE lambda x: x.to_dict() if hasattr(x, "to_dict") else x,NEWLINE valueNEWLINE ))NEWLINE elif hasattr(value, "to_dict"):NEWLINE result[attr] = value.to_dict()NEWLINE elif isinstance(value, dict):NEWLINE result[attr] = dict(map(NEWLINE lambda item: (item[0], item[1].to_dict())NEWLINE if hasattr(item[1], "to_dict") else item,NEWLINE value.items()NEWLINE ))NEWLINE else:NEWLINE result[attr] = valueNEWLINE if issubclass(CertificateUse, dict):NEWLINE for key, value in self.items():NEWLINE result[key] = valueNEWLINENEWLINE return resultNEWLINENEWLINE def to_str(self):NEWLINE """Returns the string representation of the model"""NEWLINE return pprint.pformat(self.to_dict())NEWLINENEWLINE def __repr__(self):NEWLINE """For `print` and `pprint`"""NEWLINE return self.to_str()NEWLINENEWLINE def __eq__(self, other):NEWLINE """Returns true if both objects are equal"""NEWLINE if not isinstance(other, CertificateUse):NEWLINE return FalseNEWLINENEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Returns true if both objects are not equal"""NEWLINE return not self == otherNEWLINE #NEWLINE# Autogenerated by Thrift Compiler (0.11.0)NEWLINE#NEWLINE# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOINGNEWLINE#NEWLINE# options string: pyNEWLINE#NEWLINENEWLINEfrom thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationExceptionNEWLINEfrom thrift.protocol.TProtocol import TProtocolExceptionNEWLINEfrom thrift.TRecursive import fix_specNEWLINENEWLINEimport sysNEWLINEimport loggingNEWLINEfrom .ttypes import *NEWLINEfrom thrift.Thrift import TProcessorNEWLINEfrom thrift.transport import TTransportNEWLINENEWLINEall_structs = []NEWLINENEWLINENEWLINEclass Iface(object):NEWLINE def call(self, body):NEWLINE """NEWLINE Parameters:NEWLINE - bodyNEWLINE """NEWLINE passNEWLINENEWLINENEWLINEclass Client(Iface):NEWLINE def __init__(self, iprot, oprot=None):NEWLINE self._iprot = self._oprot = iprotNEWLINE if oprot is not None:NEWLINE self._oprot = oprotNEWLINE self._seqid = 0NEWLINENEWLINE def call(self, body):NEWLINE """NEWLINE Parameters:NEWLINE - bodyNEWLINE """NEWLINE self.send_call(body)NEWLINE return self.recv_call()NEWLINENEWLINE def send_call(self, body):NEWLINE self._oprot.writeMessageBegin("call", TMessageType.CALL, self._seqid)NEWLINE args = call_args()NEWLINE args.body = bodyNEWLINE args.write(self._oprot)NEWLINE self._oprot.writeMessageEnd()NEWLINE self._oprot.trans.flush()NEWLINENEWLINE def recv_call(self):NEWLINE iprot = self._iprotNEWLINE (fname, mtype, rseqid) = iprot.readMessageBegin()NEWLINE if mtype == TMessageType.EXCEPTION:NEWLINE x = TApplicationException()NEWLINE x.read(iprot)NEWLINE iprot.readMessageEnd()NEWLINE raise xNEWLINE result = call_result()NEWLINE result.read(iprot)NEWLINE iprot.readMessageEnd()NEWLINE if result.success is not None:NEWLINE return result.successNEWLINE raise TApplicationException(TApplicationException.MISSING_RESULT, "call failed: unknown result")NEWLINENEWLINENEWLINEclass Processor(Iface, TProcessor):NEWLINE def __init__(self, handler):NEWLINE self._handler = handlerNEWLINE self._processMap = {}NEWLINE self._processMap["call"] = Processor.process_callNEWLINENEWLINE def process(self, iprot, oprot):NEWLINE (name, type, seqid) = iprot.readMessageBegin()NEWLINE if name not in self._processMap:NEWLINE iprot.skip(TType.STRUCT)NEWLINE iprot.readMessageEnd()NEWLINE x = TApplicationException(TApplicationException.UNKNOWN_METHOD, "Unknown function %s" % (name))NEWLINE oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid)NEWLINE x.write(oprot)NEWLINE oprot.writeMessageEnd()NEWLINE oprot.trans.flush()NEWLINE returnNEWLINE else:NEWLINE self._processMap[name](self, seqid, iprot, oprot)NEWLINE return TrueNEWLINENEWLINE def process_call(self, seqid, iprot, oprot):NEWLINE args = call_args()NEWLINE args.read(iprot)NEWLINE iprot.readMessageEnd()NEWLINE result = call_result()NEWLINE try:NEWLINE result.success = self._handler.call(args.body)NEWLINE msg_type = TMessageType.REPLYNEWLINE except TTransport.TTransportException:NEWLINE raiseNEWLINE except TApplicationException as ex:NEWLINE logging.exception("TApplication exception in handler")NEWLINE msg_type = TMessageType.EXCEPTIONNEWLINE result = exNEWLINE except Exception:NEWLINE logging.exception("Unexpected exception in handler")NEWLINE msg_type = TMessageType.EXCEPTIONNEWLINE result = TApplicationException(TApplicationException.INTERNAL_ERROR, "Internal error")NEWLINE oprot.writeMessageBegin("call", msg_type, seqid)NEWLINE result.write(oprot)NEWLINE oprot.writeMessageEnd()NEWLINE oprot.trans.flush()NEWLINENEWLINENEWLINE# HELPER FUNCTIONS AND STRUCTURESNEWLINENEWLINENEWLINEclass call_args(object):NEWLINE """NEWLINE Attributes:NEWLINE - bodyNEWLINE """NEWLINENEWLINE def __init__(self, body=None, ):NEWLINE self.body = bodyNEWLINENEWLINE def read(self, iprot):NEWLINE if iprot._fast_decode is not None and isinstance(iprot.trans,NEWLINE TTransport.CReadableTransport) and self.thrift_spec is not None:NEWLINE iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec])NEWLINE returnNEWLINE iprot.readStructBegin()NEWLINE while True:NEWLINE (fname, ftype, fid) = iprot.readFieldBegin()NEWLINE if ftype == TType.STOP:NEWLINE breakNEWLINE if fid == 1:NEWLINE if ftype == TType.STRING:NEWLINE self.body = iprot.readString().decode("utf-8") if sys.version_info[0] == 2 else iprot.readString()NEWLINE else:NEWLINE iprot.skip(ftype)NEWLINE else:NEWLINE iprot.skip(ftype)NEWLINE iprot.readFieldEnd()NEWLINE iprot.readStructEnd()NEWLINENEWLINE def write(self, oprot):NEWLINE if oprot._fast_encode is not None and self.thrift_spec is not None:NEWLINE oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec]))NEWLINE returnNEWLINE oprot.writeStructBegin("call_args")NEWLINE if self.body is not None:NEWLINE oprot.writeFieldBegin("body", TType.STRING, 1)NEWLINE oprot.writeString(self.body.encode("utf-8") if sys.version_info[0] == 2 else self.body)NEWLINE oprot.writeFieldEnd()NEWLINE oprot.writeFieldStop()NEWLINE oprot.writeStructEnd()NEWLINENEWLINE def validate(self):NEWLINE returnNEWLINENEWLINE def __repr__(self):NEWLINE L = ["%s=%r" % (key, value)NEWLINE for key, value in self.__dict__.items()]NEWLINE return "%s(%s)" % (self.__class__.__name__, ", ".join(L))NEWLINENEWLINE def __eq__(self, other):NEWLINE return isinstance(other, self.__class__) and self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE return not (self == other)NEWLINENEWLINENEWLINEall_structs.append(call_args)NEWLINEcall_args.thrift_spec = (NEWLINE None, # 0NEWLINE (1, TType.STRING, "body", "UTF8", None,), # 1NEWLINE)NEWLINENEWLINENEWLINEclass call_result(object):NEWLINE """NEWLINE Attributes:NEWLINE - successNEWLINE """NEWLINENEWLINE def __init__(self, success=None, ):NEWLINE self.success = successNEWLINENEWLINE def read(self, iprot):NEWLINE if iprot._fast_decode is not None and isinstance(iprot.trans,NEWLINE TTransport.CReadableTransport) and self.thrift_spec is not None:NEWLINE iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec])NEWLINE returnNEWLINE iprot.readStructBegin()NEWLINE while True:NEWLINE (fname, ftype, fid) = iprot.readFieldBegin()NEWLINE if ftype == TType.STOP:NEWLINE breakNEWLINE if fid == 0:NEWLINE if ftype == TType.STRING:NEWLINE self.success = iprot.readString().decode("utf-8") if sys.version_info[NEWLINE 0] == 2 else iprot.readString()NEWLINE else:NEWLINE iprot.skip(ftype)NEWLINE else:NEWLINE iprot.skip(ftype)NEWLINE iprot.readFieldEnd()NEWLINE iprot.readStructEnd()NEWLINENEWLINE def write(self, oprot):NEWLINE if oprot._fast_encode is not None and self.thrift_spec is not None:NEWLINE oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec]))NEWLINE returnNEWLINE oprot.writeStructBegin("call_result")NEWLINE if self.success is not None:NEWLINE oprot.writeFieldBegin("success", TType.STRING, 0)NEWLINE oprot.writeString(self.success.encode("utf-8") if sys.version_info[0] == 2 else self.success)NEWLINE oprot.writeFieldEnd()NEWLINE oprot.writeFieldStop()NEWLINE oprot.writeStructEnd()NEWLINENEWLINE def validate(self):NEWLINE returnNEWLINENEWLINE def __repr__(self):NEWLINE L = ["%s=%r" % (key, value)NEWLINE for key, value in self.__dict__.items()]NEWLINE return "%s(%s)" % (self.__class__.__name__, ", ".join(L))NEWLINENEWLINE def __eq__(self, other):NEWLINE return isinstance(other, self.__class__) and self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE return not (self == other)NEWLINENEWLINENEWLINEall_structs.append(call_result)NEWLINEcall_result.thrift_spec = (NEWLINE (0, TType.STRING, "success", "UTF8", None,), # 0NEWLINE)NEWLINEfix_spec(all_structs)NEWLINEdel all_structsNEWLINE #!/usr/bin/env pythonNEWLINENEWLINEimport numpy as npNEWLINEimport roslibNEWLINEimport rospyNEWLINEimport mathNEWLINEimport tfNEWLINEimport timeNEWLINEfrom nav_msgs.msg import OdometryNEWLINEfrom asv_msgs.msg import RobotGoal, SonarData, SonarDataListNEWLINEfrom asv_msgs.srv import SetRobotPath, SetRobotPathResponseNEWLINEfrom std_srvs.srv import SetBool, SetBoolResponseNEWLINEfrom geometry_msgs.msg import PoseNEWLINEfrom visualization_msgs.msg import Marker, MarkerArrayNEWLINENEWLINEclass OBS_AVOIDANCE():NEWLINE def __init__(self):NEWLINE self.node_name = rospy.get_name()NEWLINE self.dis_threshold = 2.0NEWLINE self.goal = NoneNEWLINE self.robot_pose = Pose()NEWLINE self.robot_orig = []NEWLINE self.r_goal = None # relative goal positionNEWLINE self.get_goal = FalseNEWLINE self.get_odom = FalseNEWLINE rospy.loginfo("[%s] Initializing " %(self.node_name))NEWLINENEWLINE self.pub_sonar_marker = rospy.Publisher('sonar_marker', MarkerArray, queue_size=1)NEWLINE self.pub_new_goal_marker = rospy.Publisher("new_goal_marker",Marker, queue_size=1)NEWLINENEWLINE self.pub_robot_goal = rospy.Publisher("robot_goal/obs", RobotGoal, queue_size = 1)NEWLINE rospy.Subscriber("robot_goal", RobotGoal, self.goal_cb, queue_size = 1, buff_size = 2**24)NEWLINE rospy.Subscriber("sonar", SonarDataList, self.sonar_cb, queue_size = 1, buff_size = 2**24)NEWLINE rospy.Subscriber('odometry', Odometry, self.odom_cb, queue_size = 1, buff_size = 2**24)NEWLINE NEWLINE def odom_cb(self, msg):NEWLINE self.get_odom = TrueNEWLINE robot_pose = Pose()NEWLINE robot_pose.position.x = msg.pose.pose.position.xNEWLINE robot_pose.position.y = msg.pose.pose.position.yNEWLINE quat = (msg.pose.pose.orientation.x,\NEWLINE msg.pose.pose.orientation.y,\NEWLINE msg.pose.pose.orientation.z,\NEWLINE msg.pose.pose.orientation.w)NEWLINENEWLINE self.robot_pose = robot_poseNEWLINENEWLINE def sonar_cb(self, msg):NEWLINE # 0 : downNEWLINE # 1 : leftNEWLINE # 2 : frontNEWLINE # 3 : rightNEWLINENEWLINE if len(msg.list) != 4 or self.get_odom == False:NEWLINE returnNEWLINENEWLINE marker_array = MarkerArray()NEWLINE for i in range(1, 4):NEWLINE marker = Marker()NEWLINE marker.header.frame_id = "map"NEWLINE marker.id = iNEWLINE marker.header.stamp = rospy.Time.now()NEWLINE marker.type = Marker.CUBENEWLINE marker.action = Marker.ADDNEWLINE marker.lifetime = rospy.Duration(0.5)NEWLINE marker.pose.position.x = self.robot_pose.position.xNEWLINE marker.pose.position.y = self.robot_pose.position.yNEWLINE marker.pose.position.z = self.robot_pose.position.zNEWLINE if i == 1:NEWLINE marker.pose.position.y = self.robot_pose.position.y + msg.list[i].distance/1000.NEWLINE marker.color.r = 1NEWLINE marker.color.g = 0NEWLINE marker.color.b = 0NEWLINE elif i == 2:NEWLINE marker.pose.position.x = self.robot_pose.position.x + msg.list[i].distance/1000.NEWLINE marker.color.r = 0NEWLINE marker.color.g = 1NEWLINE marker.color.b = 0NEWLINE elif i == 3:NEWLINE marker.pose.position.y = self.robot_pose.position.y - msg.list[i].distance/1000.NEWLINE marker.color.r = 0NEWLINE marker.color.g = 0NEWLINE marker.color.b = 1NEWLINE marker.pose.orientation.x = 0.0NEWLINE marker.pose.orientation.y = 0.0NEWLINE marker.pose.orientation.z = 0.0NEWLINE marker.pose.orientation.w = 1.0NEWLINE marker.scale.x = 0.3NEWLINE marker.scale.y = 0.3NEWLINE marker.scale.z = 0.3NEWLINE marker.color.a = 1NEWLINE marker_array.markers.append(marker)NEWLINE self.pub_sonar_marker.publish(marker_array)NEWLINENEWLINE '''new_goal = []NEWLINE new_goal = self.r_goal[:]NEWLINENEWLINE left_safe_dis = msg.list[1].distance - self.dis_thresholdNEWLINE front_safe_dis = msg.list[2].distance - self.dis_thresholdNEWLINE right_safe_dis = msg.list[3].distance - self.dis_thresholdNEWLINENEWLINE if front_safe_dis < new_goal[0]:NEWLINE new_goal[0] = front_safe_disNEWLINENEWLINE if right_safe_dis < new_goal[1]:NEWLINE if left_safe_dis < - new_goal[1]:NEWLINE new_goal[1] = (right_safe_dis - left_safe_dis)/2.NEWLINE else:NEWLINE new_goal[1] = right_safe_disNEWLINE elif left_safe_dis < - new_goal[1]:NEWLINE new_goal[1] = left_safe_disNEWLINENEWLINE rg = RobotGoal()NEWLINE rg.goal.position.x = new_goal[0] + self.robot_pose.position.xNEWLINE rg.goal.position.y = new_goal[1] + self.robot_pose.position.yNEWLINE rg.robot = self.robot_poseNEWLINE self.pub_robot_goal.publish(rg)'''NEWLINENEWLINE def goal_cb(self, msg):NEWLINE self.get_goal = TrueNEWLINE self.goal = [msg.goal.position.x, msg.goal.position.y]NEWLINE self.robot_position = [msg.robot.position.x, msg.robot.position.y]NEWLINE self.robot_pose = msg.robotNEWLINE quat = (msg.robot.orientation.x,\NEWLINE msg.robot.orientation.y,\NEWLINE msg.robot.orientation.z,\NEWLINE msg.robot.orientation.w)NEWLINE _, _, yaw = tf.transformations.euler_from_quaternion(quat)NEWLINENEWLINE if len(self.goal) == 0 or len(self.robot_position) == 0: # if the robot hasn't recieve any goalNEWLINE returnNEWLINENEWLINE self.r_goal = [self.goal[0] - self.robot_position[0], self.goal[1] - self.robot_position[1]]NEWLINENEWLINE def get_distance(self, p1, p2):NEWLINE return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)NEWLINENEWLINEif __name__ == '__main__':NEWLINE rospy.init_node('OBS_AVOIDANCE')NEWLINE foo = OBS_AVOIDANCE()NEWLINE rospy.spin() # SPDX-License-Identifier: MITNEWLINENEWLINE""":class:`~calingen.interfaces.plugin_api.LayoutProvider` implementation for a simple event list.NEWLINENEWLINEWarningsNEWLINE--------NEWLINEThis layout is included in **django-calingen**'s CI test setup, mainly to verifyNEWLINEthat the :func:`TeX escaping `NEWLINEis working.NEWLINENEWLINEThis may be object to future changes.NEWLINE"""NEWLINENEWLINE# app importsNEWLINEfrom calingen.interfaces.plugin_api import LayoutProviderNEWLINENEWLINENEWLINEclass SimpleEventList(LayoutProvider):NEWLINE """The actual implementation of the layout.NEWLINENEWLINE Nothing fancy here,NEWLINE :meth:`~calingen.contrib.layouts.simple_event_list.simple_event_list.SimpleEventList.prepare_context`NEWLINE is just used to group the providedNEWLINE :class:`calingen.interfaces.data_exchange.CalendarEntryList` by month.NEWLINENEWLINE WarningsNEWLINE --------NEWLINE The provided templates create a document targeted at German users. You mayNEWLINE override the templates to (fully) support other languages.NEWLINENEWLINE NotesNEWLINE -----NEWLINE To customize the generated TeX-sources, the following templates may beNEWLINE overridden:NEWLINENEWLINE - ``simple_event_list/tex/base.tex``: Speaking in TeX-terms: the preamble ofNEWLINE the document, including package definitions.NEWLINE - ``simple_event_list/tex/simple_event_list.tex``: Speaking in TeX-terms:NEWLINE the document's body.NEWLINE - ``simple_event_list/tex/single_entry_line.tex``: The actualNEWLINE TeX-representation of aNEWLINE :class:`calingen.interfaces.data_exchange.CalendarEntry`.NEWLINE """NEWLINENEWLINE name = "Simple Event List"NEWLINE paper_size = "a4"NEWLINE orientation = "portrait"NEWLINE layout_type = "tex"NEWLINE _template = "simple_event_list/tex/simple_event_list.tex"NEWLINENEWLINE @classmethodNEWLINE def prepare_context(cls, context):NEWLINE """Pre-process the ``entries`` to group them by month."""NEWLINE entries = context.pop("entries", [])NEWLINENEWLINE # put each month's entries in a dedicated listNEWLINE processed_entries = []NEWLINE try:NEWLINE loop_month = entries[0].timestamp.monthNEWLINE except IndexError:NEWLINE loop_month = "No Entries"NEWLINENEWLINE month_list = []NEWLINE for entry in entries:NEWLINE if entry.timestamp.month != loop_month:NEWLINE processed_entries.append(month_list)NEWLINE month_list = []NEWLINE loop_month = entry.timestamp.monthNEWLINE month_list.append(entry)NEWLINE if month_list:NEWLINE processed_entries.append(month_list)NEWLINENEWLINE context["entries"] = processed_entriesNEWLINE return contextNEWLINE """NEWLINEProcess missing data within a dataset. NEWLINE"""NEWLINEimport missingno as msnoNEWLINEfrom pandas import DataFrameNEWLINEfrom pandas import SeriesNEWLINEfrom typing import ListNEWLINENEWLINENEWLINEdef visualize(df):NEWLINE """Plot missing cells heatmap"""NEWLINE msno.matrix(df)NEWLINENEWLINENEWLINEdef removeRows(df: DataFrame) -> DataFrame:NEWLINE """Removes all rows with NaN cells"""NEWLINE return(df.dropna().reset_index(drop=True))NEWLINENEWLINENEWLINEdef removeRowsByCol(df: DataFrame, col: str) -> DataFrame:NEWLINE """Removes all rows with missing cells in specified column"""NEWLINE return(df[~df[col].isna()].reset_index(drop=True))NEWLINENEWLINENEWLINEdef impute(df: DataFrame, col: str, strategy: str = "zero") -> DataFrame:NEWLINE """NEWLINE Impute missing data in column.NEWLINE df - data dataframeNEWLINE col - target column labelNEWLINE strategy - imputation strategyNEWLINE zero: replaces NA with 0NEWLINE mean: replaces NA with the meanNEWLINE median: replaces NA with the medianNEWLINE most frequent: replaces NA with one the modeNEWLINE empty: replaces NA with an empty str i.e. ""NEWLINE hot deck: replaces NA with a random sample of non-NA dataNEWLINE """NEWLINE data = df.copy()NEWLINENEWLINE if strategy == "zero":NEWLINE # works only with quant dataNEWLINE filler_data = 0NEWLINE elif strategy == "mean":NEWLINE # works only with quant dataNEWLINE filler_data = data[col].mean()NEWLINE elif strategy == "median":NEWLINE # works only with quant dataNEWLINE filler_data = data[col].median()NEWLINE elif strategy == "most frequent":NEWLINE filler_data = data[col].mode().sample()NEWLINE elif strategy == "empty":NEWLINE filler_data = ""NEWLINE elif strategy == "hot deck":NEWLINE # replaces NaNs with random samples from the valid data pool.NEWLINE # The sampling is with replacement incase the valid sampleNEWLINE # size is too smallNEWLINE valid_data = data[col][~data[col].isnull()]NEWLINE sample_len = len(data[col][data[col].isnull()])NEWLINE filler_data = valid_data.sample(sample_len, replace=True).valuesNEWLINE else:NEWLINE raise Exception("Not a valid impute strategy")NEWLINE data[col][data[col].isnull()] = filler_dataNEWLINE return(data)NEWLINENEWLINENEWLINEdef generateBinaries(df:DataFrame, cols: List[str]) -> DataFrame:NEWLINE """Add binary variables to specify whether cell is na"""NEWLINE data = df.copy()NEWLINE for col in cols:NEWLINE data[col+"_na"] = ~data[col].isnull()NEWLINE return(data)NEWLINENEWLINENEWLINEdef noMissingByCol(df: DataFrame) -> Series:NEWLINE """Count the number of missing cells in each column"""NEWLINE return(df.isna().sum())NEWLINENEWLINENEWLINEdef replaceDefects(df: DataFrame, col: str, replacement_pairs: dict) -> DataFrame:NEWLINE """Row replacement for str based columns"""NEWLINE data = df.copy()NEWLINE for key, item in replacement_pairs.items():NEWLINE data[col] = data[col].apply(lambda x: x.replace(key, item))NEWLINE return(data)NEWLINE #NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE#NEWLINENEWLINEimport pprintNEWLINENEWLINEfrom pystachio.naming import frozendictNEWLINEfrom twitter.common import appNEWLINENEWLINEfrom apache.thermos.cli.common import get_task_from_optionsNEWLINEfrom apache.thermos.common.options import add_binding_to, add_port_toNEWLINENEWLINENEWLINEdef inspect_unwrap(obj):NEWLINE if isinstance(obj, frozendict):NEWLINE return dict((key, inspect_unwrap(val)) for (key, val) in obj.items())NEWLINE if isinstance(obj, (list, tuple, set)):NEWLINE return tuple(inspect_unwrap(val) for val in obj)NEWLINE return objNEWLINENEWLINENEWLINE@app.commandNEWLINE@app.command_option("--task", metavar="TASKNAME", default=None, dest='task',NEWLINE help="The thermos task within the config that should be inspected. Only "NEWLINE "required if there are multiple tasks exported from the thermos "NEWLINE "configuration.")NEWLINE@app.command_option("--json", default=False, action='store_true', dest='json',NEWLINE help="Read the source file in json format instead of pystachio.")NEWLINE@app.command_option("-P", "--port", type="string", nargs=1, action="callback",NEWLINE callback=add_port_to('prebound_ports'), dest="prebound_ports", default=[],NEWLINE metavar="NAME:PORT", help="bind named PORT to NAME.")NEWLINE@app.command_option("-E", "--environment", type="string", nargs=1, action="callback",NEWLINE callback=add_binding_to('bindings'), default=[], dest="bindings",NEWLINE metavar="NAME=VALUE",NEWLINE help="bind the configuration environment variable NAME to VALUE.")NEWLINEdef inspect(args, options):NEWLINE """Inspect a thermos config and display the evaluated taskNEWLINENEWLINE Usage: thermos inspect [options] configNEWLINE """NEWLINE thermos_task = get_task_from_options(args, options)NEWLINE ti, _ = thermos_task.task().interpolate()NEWLINE pprint.pprint(inspect_unwrap(ti.get()), indent=4)NEWLINE #!/usr/bin/env python3NEWLINE# -*- coding:utf-8 -*-NEWLINE"""NEWLINEreceive_logs_direct.py published log messages are going to be broadcast to all the receivesNEWLINE"""NEWLINE# Pika is a pure-Python implementation of the AMQP 0-9-1 protocolNEWLINEimport pikaNEWLINEimport sysNEWLINENEWLINENEWLINE# guest user can only connect via localhostNEWLINE#credentials = pika.PlainCredentials('guest', 'guest')NEWLINEcredentials = pika.PlainCredentials('pi', 'macintosh')NEWLINEconnection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.31.156',NEWLINE port=5672,NEWLINE virtual_host='/',NEWLINE credentials=credentials))NEWLINEchannel = connection.channel()NEWLINE# declare the exchangeNEWLINEchannel.exchange_declare(exchange='direct_logs',NEWLINE exchange_type='direct')NEWLINENEWLINEresult = channel.queue_declare(exclusive=True)NEWLINEqueue_name = result.method.queueNEWLINENEWLINEseverities = sys.argv[1:]NEWLINENEWLINEif not severities:NEWLINE sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])NEWLINE sys.exit(1)NEWLINENEWLINEfor severity in severities:NEWLINE channel.queue_bind(exchange='direct_logs',NEWLINE queue=queue_name,NEWLINE routing_key=severity)NEWLINENEWLINENEWLINEprint(" [*] Waiting for logs. To exit press CTRL+C")NEWLINENEWLINENEWLINEdef callback(ch, method, properties, body):NEWLINE print(" [x] %r:%r" % (method.routing_key, body))NEWLINENEWLINENEWLINEchannel.basic_consume(callback,NEWLINE queue=queue_name,NEWLINE no_ack=True)NEWLINENEWLINEchannel.start_consuming()NEWLINE"""NEWLINEPlease keep in mind that this and other tutorials are, well, tutorials, They demonstrate one new concept at a time and mayNEWLINEintentionally oversimplify some things and leave out others. For example topics such as connection management, error handling,NEWLINEconnection recovery, concurrency and metric collection are largely omitted for the sake of brevity. Such simplified code NEWLINEshould not be considered production ready.NEWLINENEWLINE""" import disnakeNEWLINEfrom replit import dbNEWLINEfrom disnake.ext import commandsNEWLINEimport randomNEWLINEimport asyncioNEWLINEimport requestsNEWLINEimport jsonNEWLINEimport timeNEWLINEimport osNEWLINEapikey = os.environ['perapi']NEWLINENEWLINEfrom pyspective import pyspectiveNEWLINENEWLINEperspective = pyspective.PyspectiveAPI(apikey)NEWLINENEWLINEcashE = '<:YeetCoin:899166414546559056>'NEWLINENEWLINEclass SlashCommands(commands.Cog, name='Slash commands'):NEWLINE '''These are the slash commands'''NEWLINE def __init__(self, bot):NEWLINE self.bot = botNEWLINE NEWLINE @commands.slash_command(name='nsfw',description="It's not")NEWLINE async def nsfw(self, inter):NEWLINE await inter.response.send_message('https://tenor.com/view/rick-astly-rick-rolled-gif-22755440')NEWLINENEWLINE #economyNEWLINE global cashENEWLINENEWLINE @commands.slash_command(name='cash',description='Your cash')NEWLINE async def cash(self, inter,user:disnake.Member=None):NEWLINE if user is None:NEWLINE try:NEWLINE value = db[f'{inter.author.id}']NEWLINE await inter.response.send_message(f'You currently have {value} {cashE}')NEWLINE except KeyError:NEWLINE value = db[inter.author.id]='0'NEWLINE await inter.response.send_message(f'You currently have {value} {cashE}')NEWLINE else:NEWLINE try:NEWLINE value = db[f'{user.id}']NEWLINE await inter.response.send_message(f'{user.mention} currently have {value} {cashE}')NEWLINE except KeyError:NEWLINE value = db[f'{user.id}']='0'NEWLINE await inter.response.send_message(f'{user.mention} currently have {value} {cashE}')NEWLINENEWLINE NEWLINE @commands.slash_command(name='work',description='Work to get more coins')NEWLINE @commands.cooldown(rate=1, per=600)NEWLINE async def work(self, inter):NEWLINE e = random.randint(-250,250)NEWLINE try:NEWLINE value = int(db[f'{inter.author.id}'])NEWLINE value += eNEWLINE db[f'{inter.author.id}'] = f'{value}'NEWLINE if e<0:NEWLINE await inter.response.send_message(f'You messed things up! You spend {-e}{cashE} to make things back.')NEWLINE elif e>=0 and e<=50:NEWLINE await inter.response.send_message(f"What a lazy guy. You didn't work enough. That is why you only get {e}{cashE}.")NEWLINE else:NEWLINE await inter.response.send_message(f'You did a great job. You get {e}{cashE} for that.')NEWLINE except KeyError:NEWLINE db[inter.author.id]=f'{e}'NEWLINE if e<0:NEWLINE await inter.response.send_message(f'You messed things up! You spend {-e}{cashE} to make things back.')NEWLINE elif e<=0 and e<50:NEWLINE await inter.response.send_message(f"What a lazy guy. You didn't work enough. That is why you only get {e}{cashE}.")NEWLINE else:NEWLINE await inter.response.send_message(f'You did a great job. You get {e}{cashE} for that.')NEWLINENEWLINE NEWLINE @commands.slash_command(name='transfer',description='Give someone your cash with a little tax')NEWLINE async def give(self, inter,user:disnake.User,cash:int):NEWLINE try:NEWLINE value1 = int(db[f'{inter.author.id}'])NEWLINE value2 = int(db[f'{user.id}'])NEWLINE if value1 > cash:NEWLINE e=cash/100*80NEWLINE value1 -= cashNEWLINE db[f'{inter.author.id}'] = f'{value1}'NEWLINE value2 += eNEWLINE db[f'{user.id}'] = f'{value2}'NEWLINE await inter.response.send_message(f'You gave {e} to {user.mention} after 20% tax. Now, you have {value1} and they got {value2}.')NEWLINE else:NEWLINE await inter.response.send_message("You don't have enough cash to do it.")NEWLINE except KeyError:NEWLINE db[f'{user.id}'] = '0'NEWLINE value1 = int(db[f'{inter.author.id}'])NEWLINE value2 = int(db[f'{user.id}'])NEWLINE if value1 > cash:NEWLINE e=cash/100*80NEWLINE value1 -= cashNEWLINE db[f'{inter.author.id}'] = f'{value1}'NEWLINE value2 += eNEWLINE db[f'{user.id}'] = f'{value2}'NEWLINE await inter.response.send_message(f'You gave {e} to {user.mention} after 20% tax. Now, you have {value1} and they got {value2}.')NEWLINENEWLINE else:NEWLINE await inter.response.send_message("You don't have enough cash to do it.")NEWLINENEWLINE NEWLINE @commands.slash_command(name='test')NEWLINE async def test(self, inter):NEWLINE if inter.author.id == 832264231617167381 or inter.author.id == 543656290468102174:NEWLINE E = db[f'{inter.author.id}']NEWLINE e = int(E)NEWLINE e += 50000NEWLINE db[f'{inter.author.id}'] = f'{e}'NEWLINE await inter.response.send_message('Dev powah >:)')NEWLINENEWLINE NEWLINE @commands.slash_command(name='clear')NEWLINE async def clear(self, inter,user:disnake.User):NEWLINE if inter.author.id == 832264231617167381 or inter.author.id == 543656290468102174:NEWLINE db[f'{inter.author.id}'] = '0'NEWLINE await inter.response.send_message('Dev powah >>:)')NEWLINENEWLINENEWLINE @commands.slash_command(name='leaderboard',description='Show the top 20 richest users')NEWLINE async def lb(self, inter):NEWLINE e = {}NEWLINE high = {}NEWLINE for x in inter.guild.members:NEWLINE try:NEWLINE e.update({x.name: int(db[str(x.id)])})NEWLINE except KeyError:NEWLINE db[f"{x.id}"]='0'NEWLINE e.update({x.name: 0})NEWLINE high=dict(sorted(e.items(),key= lambda x:x[1], reverse = True))NEWLINE text = ''NEWLINE e = 0NEWLINE for x in high:NEWLINE if e == 20:NEWLINE returnNEWLINE else:NEWLINE text += f'{x}: {high[x]}\n'NEWLINE e+=1NEWLINE embed = disnake.Embed(title=f'Top highest in {inter.guild.name}',description=text,color=0x6ba4ff)NEWLINE await inter.response.send_message(embed=embed)NEWLINENEWLINE #GiveawayNEWLINENEWLINE @commands.slash_command(name='create_giveaway')NEWLINE @commands.has_permissions(manage_guild=True)NEWLINE async def cgw(self, inter,times:int,winners,*,prize):NEWLINE eh = time.time()NEWLINE x=0NEWLINE for x in range(0,times):NEWLINE eh+=1NEWLINE x+=1NEWLINE eh=int(eh)NEWLINE print(x)NEWLINE embed=disnake.Embed()NEWLINE embed.add_field(name=prize,value=f'React with 🎉 to enter!\nTime: \nHosted by: {inter.author.mention}')NEWLINE embed.set_footer(text = f'{winners} winner(s)')NEWLINE gwlink = await inter.response.send_message(embed=embed)NEWLINE await gwlink.add_reaction('🎉')NEWLINE await asyncio.sleep(x)NEWLINE for s in gwlink.reactions:NEWLINE if s.emoji.name == "tada":NEWLINE users = await s.users().flatten()NEWLINE winner = random.choice(users)NEWLINE await gwlink.channel.response.send_message(f'{winner.mention} has won the raffle.')NEWLINENEWLINE #Mod NEWLINENEWLINE @commands.slash_command(name='ban',description='Ban user')NEWLINE @commands.has_permissions(ban_members=True)NEWLINE async def ban(self, inter, user: disnake.Member, *, reason=None):NEWLINENEWLINE await inter.response.send_message(f'{user.mention} was banned. Reason: {reason}')NEWLINE await inter.guild.ban(user, reason=reason)NEWLINENEWLINE @commands.slash_command(name='kick',description='Kick user')NEWLINE @commands.has_permissions(kick_members=True)NEWLINE async def kick(self, inter, user: disnake.Member, *, reason=None):NEWLINENEWLINE await inter.guild.kick(user, reason=reason)NEWLINE await user.response.send_message(NEWLINE f'You got banned from {user.guild.name}. Reason:{reason} ')NEWLINE await inter.response.send_message(f'{user.mention} was banned. Reason: ')NEWLINENEWLINE @commands.slash_command(name='ban_list',description='Get the banned users list')NEWLINE @commands.has_permissions(ban_members=True)NEWLINE async def banList(self, inter):NEWLINENEWLINE embed = disnake.Embed(title=f'Banned user in {inter.guild.name}')NEWLINE bans = await inter.guild.bans()NEWLINE for x in bans:NEWLINE embed.add_field(NEWLINE name=NEWLINE f'User {x.user.name}#{x.user.discriminator} with ID: {x.user.id}',NEWLINE value=f'Reason: {x.reason}')NEWLINE await inter.author.response.send_message(embed=embed)NEWLINE await inter.response.send_message('Sent. Check your DM')NEWLINENEWLINE @commands.slash_command(name='unban',description='Unban user')NEWLINE @commands.has_permissions(ban_members=True)NEWLINE async def unban(self, inter, *, userid):NEWLINE userid = int(userid)NEWLINE user = await self.bot.fetch_user(userid)NEWLINE await inter.guild.unban(user)NEWLINE await inter.response.send_message(f'{user.mention} is unbanned!')NEWLINENEWLINE @commands.slash_command(name='nuke', description='Clone and delete a channel')NEWLINE @commands.has_permissions(manage_channels=True)NEWLINE async def nuke(self, inter):NEWLINE m = inter.channel.positionNEWLINE e = await inter.channel.clone()NEWLINE await inter.channel.delete()NEWLINE await e.edit(position=m)NEWLINE await e.response.send_message(f'{inter.message.author.mention} nuked the channel')NEWLINENEWLINE @commands.slash_command(name='check_toxicity',description='Check the toxicity of a word/sentence')NEWLINE async def ct(self, inter, *, other):NEWLINE scores = perspective.score(other)NEWLINE My_Attribute = scores["TOXICITY"]NEWLINE await inter.response.send_message(NEWLINE f"Toxicity test for {other} completed.\nIt's toxicity is {My_Attribute.score*100}"NEWLINE )NEWLINENEWLINE @commands.slash_command(name='mute', description='Mute user')NEWLINE @commands.has_permissions(manage_messages=True)NEWLINE async def mute(self, inter, user: disnake.Member, *, reson=None):NEWLINENEWLINE overwrite = disnake.PermissionOverwrite()NEWLINE overwrite.response.send_message_messages = FalseNEWLINE overwrite.read_messages = TrueNEWLINE breh = disnake.utils.get(inter.guild.roles, name="Muted by YAIS")NEWLINE if breh == None:NEWLINE await inter.guild.create_role(name="Muted by YAIS")NEWLINE await self.bot.add_roles(member=user, role=breh)NEWLINE for x in inter.guild.text_channels:NEWLINE await x.set_permissions(breh, overwrite=overwrite)NEWLINE await inter.response.send_message('Muted')NEWLINE else:NEWLINE await user.add_roles(breh)NEWLINE for x in inter.guild.text_channels:NEWLINE await x.set_permissions(breh, overwrite=overwrite)NEWLINE await inter.response.send_message(f'User {user} has been muted. Reason: {reson}')NEWLINENEWLINE @commands.slash_command(name='unmute',description='Unmute user')NEWLINE @commands.has_permissions(manage_messages=True)NEWLINE async def unmute(self, inter, user: disnake.Member, *, reson=None):NEWLINENEWLINE overwrite = disnake.PermissionOverwrite()NEWLINE overwrite.response.send_message_messages = FalseNEWLINE overwrite.read_messages = TrueNEWLINE breh = disnake.utils.get(inter.guild.roles, name="Muted by YAIS")NEWLINE if breh == None:NEWLINE await inter.guild.create_role(name="Muted by YAIS")NEWLINE await self.bot.remove_roles(member=user, role=breh)NEWLINE for x in inter.guild.text_channels:NEWLINE await x.set_permissions(breh, overwrite=overwrite)NEWLINE await inter.response.send_message('Muted')NEWLINE else:NEWLINE await user.remove_roles(breh)NEWLINE for x in inter.guild.text_channels:NEWLINE await x.set_permissions(breh, overwrite=overwrite)NEWLINE await inter.response.send_message(f'User {user} has been unmuted. Reason: {reson}')NEWLINENEWLINE @commands.slash_command(name='purge', description='Delete a number of messages')NEWLINE @commands.has_permissions(manage_messages=True)NEWLINE async def purge(self, inter, count: int):NEWLINENEWLINE count += 1NEWLINE deleted = await inter.channel.purge(limit=count)NEWLINE await inter.response.send_message(f'Deleted {len(deleted)-1} message', delete_after=3)NEWLINENEWLINE @commands.slash_command(name='role',description='Give/remove role from an user')NEWLINE @commands.has_permissions(manage_roles=True)NEWLINE async def role(self, inter, user: disnake.Member, role: disnake.Role):NEWLINENEWLINE if role in user.roles:NEWLINE await user.remove_roles(role)NEWLINE await inter.response.send_message(NEWLINE f'Successfully removed {user.mention} {role.mention}')NEWLINE else:NEWLINE await user.add_roles(role)NEWLINE await inter.response.send_message(f'Successfully added {user.mention} {role.mention}')NEWLINENEWLINE @commands.slash_command(name='is_scammer',description='Check is a user a scammer. Not always true')NEWLINE async def isScammer(self, inter, user: disnake.User):NEWLINE r = requests.get(NEWLINE f"https://disnakescammers.com/api/v1/search/{user.id}",NEWLINE verify=False)NEWLINE response = r.json()NEWLINE print(response['status'])NEWLINE if response['status'] == 'not_found':NEWLINE await inter.response.send_message('That user **might** not a scammer.')NEWLINE else:NEWLINE await inter.response.send_message('That user is a scammer.')NEWLINENEWLINE @commands.slash_command(name='report_scammer',description='Report scammer')NEWLINE async def reportScammer(self, inter, user: disnake.User, *, info):NEWLINE daata = {NEWLINE 'ScammerID': f"{user.id}",NEWLINE 'ScammerUsername': f"{user.name}",NEWLINE 'AdditionalInfo': infoNEWLINE }NEWLINE postME = json.dumps(daata)NEWLINE requests.post('https://disnakescammers.com/api/v1/report',NEWLINE data=postME,NEWLINE verify=False)NEWLINE await inter.response.send_message('Reported!')NEWLINENEWLINE #SuggestNEWLINENEWLINE @commands.slash_command(name='suggest', description='Suggest a idea')NEWLINE async def suggest(self, inter,*,idea):NEWLINE embedVar = disnake.Embed(title=f"Suggest from user with ID: {inter.author.id}", description=f'{idea}', color=0x6FB9FF)NEWLINE with open('cogs/isban.txt')as file:NEWLINE for isBanned in file:NEWLINE isBanned = int(isBanned)NEWLINE if inter.author.id != isBanned:NEWLINE with open('cogs/channel.txt')as f:NEWLINE for hey in f:NEWLINE hey=int(hey)NEWLINE channel = inter.guild.get_channel(hey)NEWLINE if channel is not None:NEWLINE hmm = await channel.response.send_message(content=inter.author.id,embed=embedVar)NEWLINE cross = '\N{THUMBS DOWN SIGN}'NEWLINE checkM = '\N{THUMBS UP SIGN}'NEWLINE await hmm.add_reaction(checkM)NEWLINE await hmm.add_reaction(cross)NEWLINE embedBreh = disnake.Embed(title='Sent',value='Your suggestion has been sent!')NEWLINE await inter.response.send_message(embed=embedBreh)NEWLINE else:NEWLINE inter.response.send_message("You have been banned from our system.")NEWLINE return 0NEWLINE @commands.slash_command(name='approve', description='Approve a suggestion')NEWLINE @commands.has_permissions(manage_messages=True)NEWLINE async def _approve(self, inter,id):NEWLINE id=int(id)NEWLINE global yayNEWLINE huh = await inter.channel.fetch_message(id)NEWLINE member = huh.contentNEWLINE member = int(member)NEWLINE user = await inter.bot.fetch_user(member)NEWLINE await huh.response.send_message(f'Suggest is approved!')NEWLINE await huh.edit(content=f'{user.mention} Your suggest has been approved!')NEWLINE NEWLINENEWLINE @commands.slash_command(name='decline', description='Decline a suggestion',)NEWLINE @commands.has_permissions(manage_messages=True)NEWLINE async def _decline(self, inter,id):NEWLINE id=int(id)NEWLINE global yayNEWLINE huh = await inter.fetch_message(id)NEWLINE await huh.response.send_message(f'{huh.author.mention} Your suggest has been declined!')NEWLINE await huh.edit(content='Declined.')NEWLINENEWLINE NEWLINENEWLINE @commands.slash_command(name='setup', description='Set up channel that suggestions will be sent to it')NEWLINE @commands.has_permissions(manage_channels=True)NEWLINE async def _setup(self, inter,id=None):NEWLINE if id is None:NEWLINE with open('cogs/channel.txt','a') as f:NEWLINE f.write('\n')NEWLINE f.write(str(inter.channel.id))NEWLINE else:NEWLINE with open('cogs/channel.txt','a') as f:NEWLINE f.write('\n')NEWLINE f.write(id)NEWLINE embedVar = disnake.Embed(title="Set up done!",color=0x85C4FF)NEWLINE await inter.response.send_message(embed=embedVar)NEWLINENEWLINE @commands.slash_command(name='report',description='Report a suggestion')NEWLINE async def _report(self, inter,messagelink):NEWLINE re = await inter.bot.fetch_channel(883956344472895529)NEWLINE await re.response.send_message(content=messagelink)NEWLINE await inter.response.send_message(content='Sent')NEWLINENEWLINEdef setup(bot):NEWLINE bot.add_cog(SlashCommands(bot)) from django.db import migrationsNEWLINENEWLINENEWLINEdef create_site(apps, schema_editor):NEWLINE Site = apps.get_model("sites", "Site")NEWLINE custom_domain = "app-1-33544.botics.co"NEWLINENEWLINE site_params = {NEWLINE "name": "App 1",NEWLINE }NEWLINE if custom_domain:NEWLINE site_params["domain"] = custom_domainNEWLINENEWLINE Site.objects.update_or_create(defaults=site_params, id=1)NEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ("sites", "0002_alter_domain_unique"),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.RunPython(create_site),NEWLINE ]NEWLINE import pytestNEWLINEfrom click.testing import CliRunnerNEWLINEfrom nest import trans_cliNEWLINENEWLINENEWLINEclass TestTranslate:NEWLINENEWLINE @pytest.fixture(autouse=True)NEWLINE def setup(self):NEWLINE self.runner = CliRunner()NEWLINENEWLINE def test_trans_cli(self):NEWLINE result = self.runner.invoke(trans_cli, ['hello'])NEWLINE assert result.exit_code == 0NEWLINE assert '你好' in result.outputNEWLINE NEWLINE def test_trans_cli_engine(self):NEWLINE result = self.runner.invoke(trans_cli, ['hello', '--engine=youdao'])NEWLINE assert 'youdao' in result.outputNEWLINENEWLINE def test_trans_cli_source_and_to(self):NEWLINE passNEWLINE from datetime import dateNEWLINENEWLINEimport database.db_actions_general as db_genNEWLINEfrom database.db_connect import CURSOR, DBNEWLINENEWLINENEWLINE############################NEWLINE# Add bookreadNEWLINE############################NEWLINEdef add_bookread_to_db(NEWLINE bookread_id: str,NEWLINE book_id: int,NEWLINE start_date: date,NEWLINE end_date: date,NEWLINE days: int,NEWLINE score: int = None,NEWLINE comment: str = None,NEWLINE) -> None:NEWLINE """Log information about a read book into the DB"""NEWLINENEWLINE content = (book_id, start_date, end_date, days, score, comment, bookread_id)NEWLINE addition_query = """NEWLINE INSERT INTO Bookread (book_id, start_reading_date, end_reading_date,NEWLINE days_passed, out_of_ten_score, comment, bookread_pk)NEWLINE VALUES (%s, %s, %s, %s, %s, %s, %s)NEWLINE """NEWLINE CURSOR.execute(addition_query, content)NEWLINE DB.commit()NEWLINENEWLINENEWLINE############################NEWLINE# Delete bookreadNEWLINE############################NEWLINEdef remove_bookread_given_id(bookread_id: str) -> None:NEWLINE """Remove a book from the DB given its ID"""NEWLINE db_gen.validate_input_type(bookread_id, str)NEWLINE query = where_equal_bookreadid(bookread_id)NEWLINE remove_bookread_general(query)NEWLINENEWLINENEWLINEdef remove_bookread_general(delete_condition_query: str) -> None:NEWLINE """Remove a bookread info from the DB given a general conditional query"""NEWLINE db_gen.remove_general(CURSOR, DB, "Bookread", delete_condition_query)NEWLINENEWLINENEWLINE############################NEWLINE# Retrive last bookreadNEWLINE############################NEWLINEdef get_last_bookread(fields: db_gen.FieldsInput = "All") -> tuple:NEWLINE """Retrive the last bookread info added to the database"""NEWLINE fields = db_gen.parse_field_input(fields)NEWLINE last_id = get_last_bookread_id()NEWLINE query = (NEWLINE f"SELECT {fields} FROM Bookread "NEWLINE + where_equal_bookreadid(last_id)NEWLINE + " LIMIT 0, 1"NEWLINE )NEWLINE CURSOR.execute(query)NEWLINE return CURSOR.fetchone()NEWLINENEWLINENEWLINEdef get_last_bookread_id() -> str:NEWLINE """Retrive the ID of the last book added in the DB"""NEWLINE return db_gen.get_last_id_general(CURSOR, "Bookread", "bookread_pk")NEWLINENEWLINENEWLINE############################NEWLINE# Conditions for WHERE statementsNEWLINE############################NEWLINEdef where_equal_bookreadid(bookread_id: str) -> str:NEWLINE return f"WHERE bookread_pk = '{bookread_id}'"NEWLINE import pendulumNEWLINEfrom dagster.core.scheduler.job import JobStatusNEWLINEfrom dagster_graphql.test.utils import (NEWLINE execute_dagster_graphql,NEWLINE infer_repository_selector,NEWLINE infer_schedule_selector,NEWLINE main_repo_location_name,NEWLINE main_repo_name,NEWLINE)NEWLINENEWLINEGET_SCHEDULES_QUERY = """NEWLINEquery SchedulesQuery($repositorySelector: RepositorySelector!) {NEWLINE schedulesOrError(repositorySelector: $repositorySelector) {NEWLINE __typenameNEWLINE ... on PythonError {NEWLINE messageNEWLINE stackNEWLINE }NEWLINE ... on Schedules {NEWLINE results {NEWLINE nameNEWLINE cronScheduleNEWLINE pipelineNameNEWLINE solidSelectionNEWLINE modeNEWLINE executionTimezoneNEWLINE }NEWLINE }NEWLINE }NEWLINE}NEWLINE"""NEWLINENEWLINEGET_SCHEDULE_QUERY = """NEWLINEquery getSchedule($scheduleSelector: ScheduleSelector!, $ticksAfter: Float) {NEWLINE scheduleOrError(scheduleSelector: $scheduleSelector) {NEWLINE __typenameNEWLINE ... on PythonError {NEWLINE messageNEWLINE stackNEWLINE }NEWLINE ... on Schedule {NEWLINE nameNEWLINE partitionSet {NEWLINE nameNEWLINE }NEWLINE executionTimezoneNEWLINE futureTicks(limit: 3, cursor: $ticksAfter) {NEWLINE results {NEWLINE timestampNEWLINE }NEWLINE cursorNEWLINE }NEWLINE }NEWLINE }NEWLINE}NEWLINE"""NEWLINENEWLINERECONCILE_SCHEDULER_STATE_QUERY = """NEWLINEmutation(NEWLINE $repositorySelector: RepositorySelector!NEWLINE) {NEWLINE reconcileSchedulerState(NEWLINE repositorySelector: $repositorySelector,NEWLINE ) {NEWLINE ... on PythonError {NEWLINE messageNEWLINE stackNEWLINE }NEWLINE ... on ReconcileSchedulerStateSuccess {NEWLINE messageNEWLINE }NEWLINE }NEWLINE}NEWLINE"""NEWLINENEWLINENEWLINESTART_SCHEDULES_QUERY = """NEWLINEmutation(NEWLINE $scheduleSelector: ScheduleSelector!NEWLINE) {NEWLINE startSchedule(NEWLINE scheduleSelector: $scheduleSelector,NEWLINE ) {NEWLINE ... on PythonError {NEWLINE messageNEWLINE classNameNEWLINE stackNEWLINE }NEWLINE ... on ScheduleStateResult {NEWLINE scheduleState {NEWLINE idNEWLINE statusNEWLINE }NEWLINE }NEWLINE }NEWLINE}NEWLINE"""NEWLINENEWLINENEWLINESTOP_SCHEDULES_QUERY = """NEWLINEmutation(NEWLINE $scheduleOriginId: String!NEWLINE) {NEWLINE stopRunningSchedule(NEWLINE scheduleOriginId: $scheduleOriginId,NEWLINE ) {NEWLINE ... on PythonError {NEWLINE messageNEWLINE classNameNEWLINE stackNEWLINE }NEWLINE ... on ScheduleStateResult {NEWLINE scheduleState {NEWLINE idNEWLINE statusNEWLINE }NEWLINE }NEWLINE }NEWLINE}NEWLINE"""NEWLINENEWLINENEWLINEdef default_execution_params():NEWLINE return {NEWLINE "runConfigData": {"intermediate_storage": {"filesystem": None}},NEWLINE "selector": {"name": "no_config_pipeline", "solidSelection": None},NEWLINE "mode": "default",NEWLINE }NEWLINENEWLINENEWLINEdef test_get_schedule_definitions_for_repository(graphql_context):NEWLINE selector = infer_repository_selector(graphql_context)NEWLINE result = execute_dagster_graphql(NEWLINE graphql_context, GET_SCHEDULES_QUERY, variables={"repositorySelector": selector},NEWLINE )NEWLINENEWLINE assert result.dataNEWLINE assert result.data["schedulesOrError"]NEWLINE assert result.data["schedulesOrError"]["__typename"] == "Schedules"NEWLINENEWLINE external_repository = graphql_context.get_repository_location(NEWLINE main_repo_location_name()NEWLINE ).get_repository(main_repo_name())NEWLINENEWLINE results = result.data["schedulesOrError"]["results"]NEWLINE assert len(results) == len(external_repository.get_external_schedules())NEWLINENEWLINE for schedule in results:NEWLINE if schedule["name"] == "timezone_schedule":NEWLINE assert schedule["executionTimezone"] == "US/Central"NEWLINENEWLINENEWLINEdef test_start_and_stop_schedule(graphql_context):NEWLINE external_repository = graphql_context.get_repository_location(NEWLINE main_repo_location_name()NEWLINE ).get_repository(main_repo_name())NEWLINE graphql_context.instance.reconcile_scheduler_state(external_repository)NEWLINENEWLINE schedule_selector = infer_schedule_selector(NEWLINE graphql_context, "no_config_pipeline_hourly_schedule"NEWLINE )NEWLINENEWLINE # Start a single scheduleNEWLINE start_result = execute_dagster_graphql(NEWLINE graphql_context, START_SCHEDULES_QUERY, variables={"scheduleSelector": schedule_selector},NEWLINE )NEWLINE assert start_result.data["startSchedule"]["scheduleState"]["status"] == JobStatus.RUNNING.valueNEWLINENEWLINE schedule_origin_id = start_result.data["startSchedule"]["scheduleState"]["id"]NEWLINENEWLINE # Stop a single scheduleNEWLINE stop_result = execute_dagster_graphql(NEWLINE graphql_context, STOP_SCHEDULES_QUERY, variables={"scheduleOriginId": schedule_origin_id},NEWLINE )NEWLINE assert (NEWLINE stop_result.data["stopRunningSchedule"]["scheduleState"]["status"]NEWLINE == JobStatus.STOPPED.valueNEWLINE )NEWLINENEWLINENEWLINEdef test_get_single_schedule_definition(graphql_context):NEWLINE context = graphql_contextNEWLINE instance = context.instanceNEWLINENEWLINE instance.reconcile_scheduler_state(NEWLINE external_repository=context.get_repository_location(NEWLINE main_repo_location_name()NEWLINE ).get_repository(main_repo_name()),NEWLINE )NEWLINENEWLINE schedule_selector = infer_schedule_selector(context, "partition_based_multi_mode_decorator")NEWLINENEWLINE result = execute_dagster_graphql(NEWLINE context, GET_SCHEDULE_QUERY, variables={"scheduleSelector": schedule_selector}NEWLINE )NEWLINENEWLINE assert result.dataNEWLINENEWLINE assert result.data["scheduleOrError"]["__typename"] == "Schedule"NEWLINE assert result.data["scheduleOrError"]["partitionSet"]NEWLINE assert result.data["scheduleOrError"]["executionTimezone"] == pendulum.now().timezone.nameNEWLINENEWLINE future_ticks = result.data["scheduleOrError"]["futureTicks"]NEWLINE assert future_ticksNEWLINE assert len(future_ticks["results"]) == 3NEWLINENEWLINE schedule_selector = infer_schedule_selector(context, "timezone_schedule")NEWLINENEWLINE future_ticks_start_time = pendulum.create(2019, 2, 27, tz="US/Central").timestamp()NEWLINENEWLINE result = execute_dagster_graphql(NEWLINE context,NEWLINE GET_SCHEDULE_QUERY,NEWLINE variables={"scheduleSelector": schedule_selector, "ticksAfter": future_ticks_start_time},NEWLINE )NEWLINENEWLINE assert result.dataNEWLINE assert result.data["scheduleOrError"]["__typename"] == "Schedule"NEWLINE assert result.data["scheduleOrError"]["executionTimezone"] == "US/Central"NEWLINENEWLINE future_ticks = result.data["scheduleOrError"]["futureTicks"]NEWLINE assert future_ticksNEWLINE assert len(future_ticks["results"]) == 3NEWLINE timestamps = [future_tick["timestamp"] for future_tick in future_ticks["results"]]NEWLINENEWLINE assert timestamps == [NEWLINE pendulum.create(2019, 2, 27, tz="US/Central").timestamp(),NEWLINE pendulum.create(2019, 2, 28, tz="US/Central").timestamp(),NEWLINE pendulum.create(2019, 3, 1, tz="US/Central").timestamp(),NEWLINE ]NEWLINENEWLINE cursor = future_ticks["cursor"]NEWLINENEWLINE assert future_ticks["cursor"] == (pendulum.create(2019, 3, 1, tz="US/Central").timestamp() + 1)NEWLINENEWLINE result = execute_dagster_graphql(NEWLINE context,NEWLINE GET_SCHEDULE_QUERY,NEWLINE variables={"scheduleSelector": schedule_selector, "ticksAfter": cursor},NEWLINE )NEWLINENEWLINE future_ticks = result.data["scheduleOrError"]["futureTicks"]NEWLINENEWLINE assert future_ticksNEWLINE assert len(future_ticks["results"]) == 3NEWLINE timestamps = [future_tick["timestamp"] for future_tick in future_ticks["results"]]NEWLINENEWLINE assert timestamps == [NEWLINE pendulum.create(2019, 3, 2, tz="US/Central").timestamp(),NEWLINE pendulum.create(2019, 3, 3, tz="US/Central").timestamp(),NEWLINE pendulum.create(2019, 3, 4, tz="US/Central").timestamp(),NEWLINE ]NEWLINE import _plotly_utils.basevalidatorsNEWLINENEWLINENEWLINEclass LenValidator(_plotly_utils.basevalidators.NumberValidator):NEWLINE def __init__(NEWLINE self, plotly_name="len", parent_name="scatterpolargl.marker.colorbar", **kwargsNEWLINE ):NEWLINE super(LenValidator, self).__init__(NEWLINE plotly_name=plotly_name,NEWLINE parent_name=parent_name,NEWLINE edit_type=kwargs.pop("edit_type", "calc"),NEWLINE min=kwargs.pop("min", 0),NEWLINE **kwargsNEWLINE )NEWLINE #!/usr/bin/env python3NEWLINE# -*- coding: utf-8 -*-NEWLINENEWLINE# @author Copyright (c) 2022 Damir Dzeko AnticNEWLINE# @license MIT No AttributionNEWLINE# @version 0.1.2NEWLINE# @lastUpdate 2022-02-05NEWLINENEWLINE# ChangeLog:NEWLINE# - can be tested with: python3 -m unittest tomtomLookup.pyNEWLINE# - added object destructor to close the session/socketNEWLINENEWLINENEWLINEimport sysNEWLINEtry:NEWLINE assert (sys.version_info.major == 3 and sys.version_info.minor >= 7), "Python version must be 3.7 or newer"NEWLINEexcept Exception as e:NEWLINE print (e)NEWLINE sys.exit(1)NEWLINENEWLINEimport timeNEWLINEfrom os import environNEWLINENEWLINEfrom datetime import timedeltaNEWLINENEWLINEfrom requests_cache import CachedSessionNEWLINEimport unittestNEWLINEimport jsonNEWLINENEWLINENEWLINETOMTOM_AUTH_KEY = environ.get("TOMTOM_AUTH_KEY")NEWLINENEWLINEdef tomtom_url(gps_od, gps_do):NEWLINE def prefix():NEWLINE return 'https://api.tomtom.com/routing/1/calculateRoute/'NEWLINE def suffix():NEWLINE return (f'/json?key={TOMTOM_AUTH_KEY}&routeRepresentation=summaryOnly&maxAlternatives=0' + NEWLINE '&computeTravelTimeFor=none&routeType=fastest&traffic=false&travelMode=car')NEWLINE return f'{prefix()}{",".join(gps_od)}:{",".join(gps_do)}{suffix()}'NEWLINENEWLINENEWLINEclass TomTomLookup():NEWLINENEWLINE def _make_throttle_hook(timeout=1.0):NEWLINE """Make a request hook function that adds a custom delay for non-cached requests"""NEWLINE def hook(response, *args, **kwargs):NEWLINE if not getattr(response, 'from_cache', False):NEWLINE # print('sleeping')NEWLINE time.sleep(timeout)NEWLINE return responseNEWLINE return hookNEWLINENEWLINE def __init__(self):NEWLINE session = CachedSession('./requests_cache.db', NEWLINE backend='sqlite', NEWLINE timeout=30, NEWLINE expire_after=timedelta(days=30),NEWLINE old_data_on_error=True,NEWLINE serializer='json')NEWLINE session.hooks['response'].append(TomTomLookup._make_throttle_hook(1.25))NEWLINE self.session = sessionNEWLINENEWLINE def getUrl(self, url):NEWLINE response = self.session.get(url)NEWLINE if response.status_code != 200:NEWLINE raise Exception("TomTomLookup: GET call returned invalid response")NEWLINE return response.textNEWLINENEWLINE def getDistance_from_resp(self, response_text):NEWLINE try:NEWLINE json_obj = json.loads(response_text)NEWLINE return json_obj['routes'][0]['summary']['lengthInMeters']NEWLINE except:NEWLINE raise Exception("TomTomLookup: Failed to decode REST API response")NEWLINENEWLINE def getDistance_from_url(self, url):NEWLINE response_text = self.getUrl(url)NEWLINE return self.getDistance_from_resp(response_text)NEWLINENEWLINE def __del__(self):NEWLINE self.session.close()NEWLINENEWLINEclass TestTomTomLookup(unittest.TestCase):NEWLINE def setUp(self):NEWLINE self.tomtom = TomTomLookup()NEWLINENEWLINE def test_one_url(self):NEWLINE response_text = self.tomtom.getUrl('http://httpbin.org/delay/3')NEWLINE response_obj = json.loads(response_text)NEWLINE self.assertTrue(response_obj['url'] is not None)NEWLINENEWLINENEWLINEdef main():NEWLINE print(f'{__file__} should not be run as stand-alone program')NEWLINE return 2NEWLINENEWLINEif __name__ == '__main__':NEWLINE sys.exit(main()) # coding: utf-8NEWLINENEWLINE"""NEWLINE KubernetesNEWLINENEWLINE No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)NEWLINENEWLINE OpenAPI spec version: v1.13.5NEWLINE NEWLINE Generated by: https://github.com/swagger-api/swagger-codegen.gitNEWLINE"""NEWLINENEWLINENEWLINEfrom __future__ import absolute_importNEWLINENEWLINEimport osNEWLINEimport sysNEWLINEimport unittestNEWLINENEWLINEimport kubernetes.clientNEWLINEfrom kubernetes.client.rest import ApiExceptionNEWLINEfrom kubernetes.client.models.v1_rolling_update_stateful_set_strategy import V1RollingUpdateStatefulSetStrategyNEWLINENEWLINENEWLINEclass TestV1RollingUpdateStatefulSetStrategy(unittest.TestCase):NEWLINE """ V1RollingUpdateStatefulSetStrategy unit test stubs """NEWLINENEWLINE def setUp(self):NEWLINE passNEWLINENEWLINE def tearDown(self):NEWLINE passNEWLINENEWLINE def testV1RollingUpdateStatefulSetStrategy(self):NEWLINE """NEWLINE Test V1RollingUpdateStatefulSetStrategyNEWLINE """NEWLINE # FIXME: construct object with mandatory attributes with example valuesNEWLINE #model = kubernetes.client.models.v1_rolling_update_stateful_set_strategy.V1RollingUpdateStatefulSetStrategy()NEWLINE passNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE unittest.main()NEWLINE #!/usr/bin/python3NEWLINE# -*- coding: utf-8 -*-NEWLINENEWLINE#NEWLINE# Copyright (C) 2017 Kévin MathieuNEWLINE#NEWLINE# This software may be modified and distributed under the termsNEWLINE# of the MIT license. See the LICENSE file for details.NEWLINE#NEWLINENEWLINEimport requestsNEWLINENEWLINENEWLINEclass URL:NEWLINE def __init__(self, url):NEWLINE self.baseUrl = urlNEWLINENEWLINE def call(self, params = None):NEWLINE req = requests.get(self.baseUrl, params=params)NEWLINENEWLINE return reqNEWLINE from sympy.sets import (ConditionSet, Intersection, FiniteSet,NEWLINE EmptySet, Union, Contains, imageset)NEWLINEfrom sympy import (Symbol, Eq, S, Abs, sin, asin, pi, Interval,NEWLINE And, Mod, oo, Function, Lambda)NEWLINEfrom sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympyNEWLINENEWLINENEWLINEw = Symbol('w')NEWLINEx = Symbol('x')NEWLINEy = Symbol('y')NEWLINEz = Symbol('z')NEWLINEL = Symbol('lambda')NEWLINEf = Function('f')NEWLINENEWLINENEWLINEdef test_CondSet():NEWLINE sin_sols_principal = ConditionSet(x, Eq(sin(x), 0),NEWLINE Interval(0, 2*pi, False, True))NEWLINE assert pi in sin_sols_principalNEWLINE assert pi/2 not in sin_sols_principalNEWLINE assert 3*pi not in sin_sols_principalNEWLINE assert 5 in ConditionSet(x, x**2 > 4, S.Reals)NEWLINE assert 1 not in ConditionSet(x, x**2 > 4, S.Reals)NEWLINE # in this case, 0 is not part of the base set soNEWLINE # it can't be in any subset selected by the conditionNEWLINE assert 0 not in ConditionSet(x, y > 5, Interval(1, 7))NEWLINE # since 'in' requires a true/false, the following raisesNEWLINE # an error because the given value provides no informationNEWLINE # for the condition to evaluate (since the condition doesNEWLINE # not depend on the dummy symbol): the result is `y > 5`.NEWLINE # In this case, ConditionSet is just acting likeNEWLINE # Piecewise((Interval(1, 7), y > 5), (S.EmptySet, True)).NEWLINE raises(TypeError, lambda: 6 in ConditionSet(x, y > 5, Interval(1, 7)))NEWLINENEWLINE assert isinstance(ConditionSet(x, x < 1, {x, y}).base_set, FiniteSet)NEWLINE raises(TypeError, lambda: ConditionSet(x, x + 1, {x, y}))NEWLINE raises(TypeError, lambda: ConditionSet(x, x, 1))NEWLINENEWLINE I = S.IntegersNEWLINE C = ConditionSetNEWLINE assert C(x, x < 1, C(x, x < 2, I)NEWLINE ) == C(x, (x < 1) & (x < 2), I)NEWLINE assert C(y, y < 1, C(x, y < 2, I)NEWLINE ) == C(x, (x < 1) & (y < 2), I)NEWLINE assert C(y, y < 1, C(x, x < 2, I)NEWLINE ) == C(y, (y < 1) & (y < 2), I)NEWLINE assert C(y, y < 1, C(x, y < x, I)NEWLINE ) == C(x, (x < 1) & (y < x), I)NEWLINE assert C(y, x < 1, C(x, y < x, I)NEWLINE ) == C(L, (x < 1) & (y < L), I)NEWLINE c = C(y, x < 1, C(x, L < y, I))NEWLINE assert c == C(c.sym, (L < y) & (x < 1), I)NEWLINE assert c.sym not in (x, y, L)NEWLINE c = C(y, x < 1, C(x, y < x, FiniteSet(L)))NEWLINE assert c == C(L, And(x < 1, y < L), FiniteSet(L))NEWLINENEWLINENEWLINEdef test_CondSet_intersect():NEWLINE input_conditionset = ConditionSet(x, x**2 > 4, Interval(1, 4, False, False))NEWLINE other_domain = Interval(0, 3, False, False)NEWLINE output_conditionset = ConditionSet(x, x**2 > 4, Interval(1, 3, False, False))NEWLINE assert Intersection(input_conditionset, other_domain) == output_conditionsetNEWLINENEWLINENEWLINEdef test_issue_9849():NEWLINE assert ConditionSet(x, Eq(x, x), S.Naturals) == S.NaturalsNEWLINE assert ConditionSet(x, Eq(Abs(sin(x)), -1), S.Naturals) == S.EmptySetNEWLINENEWLINENEWLINEdef test_simplified_FiniteSet_in_CondSet():NEWLINE assert ConditionSet(x, And(x < 1, x > -3), FiniteSet(0, 1, 2)) == FiniteSet(0)NEWLINE assert ConditionSet(x, x < 0, FiniteSet(0, 1, 2)) == EmptySetNEWLINE assert ConditionSet(x, And(x < -3), EmptySet) == EmptySetNEWLINE y = Symbol('y')NEWLINE assert (ConditionSet(x, And(x > 0), FiniteSet(-1, 0, 1, y)) ==NEWLINE Union(FiniteSet(1), ConditionSet(x, And(x > 0), FiniteSet(y))))NEWLINE assert (ConditionSet(x, Eq(Mod(x, 3), 1), FiniteSet(1, 4, 2, y)) ==NEWLINE Union(FiniteSet(1, 4), ConditionSet(x, Eq(Mod(x, 3), 1), FiniteSet(y))))NEWLINENEWLINENEWLINEdef test_free_symbols():NEWLINE assert ConditionSet(x, Eq(y, 0), FiniteSet(z)NEWLINE ).free_symbols == {y, z}NEWLINE assert ConditionSet(x, Eq(x, 0), FiniteSet(z)NEWLINE ).free_symbols == {z}NEWLINE assert ConditionSet(x, Eq(x, 0), FiniteSet(x, z)NEWLINE ).free_symbols == {x, z}NEWLINENEWLINENEWLINEdef test_subs_CondSet():NEWLINE s = FiniteSet(z, y)NEWLINE c = ConditionSet(x, x < 2, s)NEWLINE # you can only replace sym with a symbol that is not inNEWLINE # the free symbolsNEWLINE assert c.subs(x, 1) == cNEWLINE assert c.subs(x, y) == ConditionSet(y, y < 2, s)NEWLINENEWLINE # double subs needed to change dummy if the base setNEWLINE # also contains the dummyNEWLINE orig = ConditionSet(y, y < 2, s)NEWLINE base = orig.subs(y, w)NEWLINE and_dummy = base.subs(y, w)NEWLINE assert base == ConditionSet(y, y < 2, {w, z})NEWLINE assert and_dummy == ConditionSet(w, w < 2, {w, z})NEWLINENEWLINE assert c.subs(x, w) == ConditionSet(w, w < 2, s)NEWLINE assert ConditionSet(x, x < y, sNEWLINE ).subs(y, w) == ConditionSet(x, x < w, s.subs(y, w))NEWLINE # if the user uses assumptions that cause the conditionNEWLINE # to evaluate, that can't be helped from SymPy's endNEWLINE n = Symbol('n', negative=True)NEWLINE assert ConditionSet(n, 0 < n, S.Integers) is S.EmptySetNEWLINE p = Symbol('p', positive=True)NEWLINE assert ConditionSet(n, n < y, S.IntegersNEWLINE ).subs(n, x) == ConditionSet(x, x < y, S.Integers)NEWLINE nc = Symbol('nc', commutative=False)NEWLINE raises(ValueError, lambda: ConditionSet(NEWLINE x, x < p, S.Integers).subs(x, nc))NEWLINE raises(ValueError, lambda: ConditionSet(NEWLINE x, x < p, S.Integers).subs(x, n))NEWLINE raises(ValueError, lambda: ConditionSet(NEWLINE x + 1, x < 1, S.Integers))NEWLINE raises(ValueError, lambda: ConditionSet(NEWLINE x + 1, x < 1, s))NEWLINE assert ConditionSet(NEWLINE n, n < x, Interval(0, oo)).subs(x, p) == Interval(0, oo)NEWLINE assert ConditionSet(NEWLINE n, n < x, Interval(-oo, 0)).subs(x, p) == Interval(-oo, 0)NEWLINENEWLINE assert ConditionSet(f(x), f(x) < 1, {w, z}NEWLINE ).subs(f(x), y) == ConditionSet(y, y < 1, {w, z})NEWLINENEWLINE # issue 17341NEWLINE k = Symbol('k')NEWLINE img1 = imageset(Lambda(k, 2*k*pi + asin(y)), S.Integers)NEWLINE img2 = imageset(Lambda(k, 2*k*pi + asin(S.One/3)), S.Integers)NEWLINE assert ConditionSet(x, Contains(NEWLINE y, Interval(-1,1)), img1).subs(y, S.One/3).dummy_eq(img2)NEWLINENEWLINENEWLINEdef test_subs_CondSet_tebr():NEWLINE with warns_deprecated_sympy():NEWLINE assert ConditionSet((x, y), {x + 1, x + y}, S.Reals) == \NEWLINE ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals)NEWLINENEWLINE c = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals)NEWLINE assert c.subs(x, z) == cNEWLINENEWLINENEWLINEdef test_dummy_eq():NEWLINE C = ConditionSetNEWLINE I = S.IntegersNEWLINE c = C(x, x < 1, I)NEWLINE assert c.dummy_eq(C(y, y < 1, I))NEWLINE assert c.dummy_eq(1) == FalseNEWLINE assert c.dummy_eq(C(x, x < 1, S.Reals)) == FalseNEWLINE raises(ValueError, lambda: c.dummy_eq(C(x, x < 1, S.Reals), z))NEWLINENEWLINE c1 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals)NEWLINE c2 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals)NEWLINE c3 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Complexes)NEWLINE assert c1.dummy_eq(c2)NEWLINE assert c1.dummy_eq(c3) is FalseNEWLINE assert c.dummy_eq(c1) is FalseNEWLINE assert c1.dummy_eq(c) is FalseNEWLINENEWLINENEWLINEdef test_contains():NEWLINE assert 6 in ConditionSet(x, x > 5, Interval(1, 7))NEWLINE assert (8 in ConditionSet(x, y > 5, Interval(1, 7))) is FalseNEWLINE # `in` should give True or False; in this case there is notNEWLINE # enough information for that resultNEWLINE raises(TypeError,NEWLINE lambda: 6 in ConditionSet(x, y > 5, Interval(1, 7)))NEWLINE assert ConditionSet(x, y > 5, Interval(1, 7)NEWLINE ).contains(6) == (y > 5)NEWLINE assert ConditionSet(x, y > 5, Interval(1, 7)NEWLINE ).contains(8) is S.falseNEWLINE assert ConditionSet(x, y > 5, Interval(1, 7)NEWLINE ).contains(w) == And(Contains(w, Interval(1, 7)), y > 5)NEWLINENEWLINE@XFAILNEWLINEdef test_failing_contains():NEWLINE # XXX This may have to return unevaluated Contains objectNEWLINE # because 1/0 should not be defined for 1 and 0 in the context ofNEWLINE # reals, but there is a nonsensical evaluation to ComplexInfinityNEWLINE # and the comparison is giving an error.NEWLINE assert ConditionSet(x, 1/x >= 0, S.Reals).contains(0) == \NEWLINE Contains(0, ConditionSet(x, 1/x >= 0, S.Reals), evaluate=False)NEWLINE #!/usr/bin/env pythonNEWLINE# Jonas Schnelli, 2013NEWLINE# make sure the Lissomcoin-Qt.app contains the right plist (including the right version)NEWLINE# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)NEWLINENEWLINEfrom string import TemplateNEWLINEfrom datetime import dateNEWLINENEWLINEbitcoinDir = "./";NEWLINENEWLINEinFile = bitcoinDir+"/share/qt/Info.plist"NEWLINEoutFile = "Lissomcoin-Qt.app/Contents/Info.plist"NEWLINEversion = "unknown";NEWLINENEWLINEfileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro"NEWLINEfor line in open(fileForGrabbingVersion):NEWLINE lineArr = line.replace(" ", "").split("=");NEWLINE if lineArr[0].startswith("VERSION"):NEWLINE version = lineArr[1].replace("\n", "");NEWLINENEWLINEfIn = open(inFile, "r")NEWLINEfileContent = fIn.read()NEWLINEs = Template(fileContent)NEWLINEnewFileContent = s.substitute(VERSION=version,YEAR=date.today().year)NEWLINENEWLINEfOut = open(outFile, "w");NEWLINEfOut.write(newFileContent);NEWLINENEWLINEprint "Info.plist fresh created"NEWLINE import taichi as tiNEWLINENEWLINEti.init()NEWLINENEWLINEn = 512NEWLINEx = ti.field(dtype=ti.f32, shape=(n, n))NEWLINENEWLINENEWLINE@ti.kernelNEWLINEdef paint():NEWLINE for i, j in ti.ndrange(n * 4, n * 4):NEWLINE # 4x4 super sampling:NEWLINE ret = ti.taichi_logo(ti.Vector([i, j]) / (n * 4))NEWLINE x[i // 4, j // 4] += ret / 16NEWLINENEWLINENEWLINEdef main():NEWLINE paint()NEWLINENEWLINE gui = ti.GUI('Logo', (n, n))NEWLINE while gui.running:NEWLINE gui.set_image(x)NEWLINE gui.show()NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE main()NEWLINE # vim: tabstop=4 shiftwidth=4 softtabstop=4NEWLINENEWLINE# Copyright 2011 OpenStack FoundationNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License"); you mayNEWLINE# not use this file except in compliance with the License. You may obtainNEWLINE# a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS, WITHOUTNEWLINE# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See theNEWLINE# License for the specific language governing permissions and limitationsNEWLINE# under the License.NEWLINE"""NEWLINEA module where we define some basic units for use across Cinder.NEWLINE"""NEWLINENEWLINEKiB = 1024NEWLINEMiB = KiB * 1024NEWLINEGiB = MiB * 1024NEWLINE #!/usr/bin/env pythonNEWLINENEWLINEfrom __future__ import print_functionNEWLINENEWLINEfrom builtins import rangeNEWLINEimport osNEWLINEimport reNEWLINEimport sysNEWLINEimport globNEWLINEimport jsonNEWLINEimport mathNEWLINEimport bisectNEWLINEimport randomNEWLINEimport signalNEWLINEif sys.version_info[0]>2:NEWLINE import _pickle as cPickleNEWLINEelse:NEWLINE import cPickleNEWLINEimport difflibNEWLINEimport argparseNEWLINEimport functoolsNEWLINEimport itertoolsNEWLINEimport subprocessNEWLINEimport collectionsNEWLINEimport multiprocessingNEWLINEimport FWCore.PythonUtilities.LumiList as LumiListNEWLINEimport Utilities.General.cmssw_das_client as cmssw_das_clientNEWLINEimport Alignment.MillePedeAlignmentAlgorithm.mpslib.tools as mps_toolsNEWLINENEWLINENEWLINE################################################################################NEWLINEdef main(argv = None):NEWLINE """NEWLINE Main routine. Not called, if this module is loaded via `import`.NEWLINENEWLINE Arguments:NEWLINE - `argv`: Command line arguments passed to the script.NEWLINE """NEWLINENEWLINE if argv == None:NEWLINE argv = sys.argv[1:]NEWLINENEWLINE file_list_creator = FileListCreator(argv)NEWLINE file_list_creator.create()NEWLINENEWLINENEWLINE################################################################################NEWLINEclass FileListCreator(object):NEWLINE """Create file lists for alignment and validation for a given dataset.NEWLINE """NEWLINENEWLINE def __init__(self, argv):NEWLINE """Constructor taking the command line arguments.NEWLINENEWLINE Arguments:NEWLINE - `args`: command line argumentsNEWLINE """NEWLINENEWLINE self._first_dataset_ini = TrueNEWLINE self._parser = self._define_parser()NEWLINE self._args = self._parser.parse_args(argv)NEWLINENEWLINE if not mps_tools.check_proxy():NEWLINE print_msg(NEWLINE "Please create proxy via 'voms-proxy-init -voms cms -rfc'.")NEWLINE sys.exit(1)NEWLINENEWLINE self._dataset_regex = re.compile(r"^/([^/]+)/([^/]+)/([^/]+)$")NEWLINE self._validate_input()NEWLINENEWLINE if self._args.test_mode:NEWLINE import Configuration.PyReleaseValidation.relval_steps as rvsNEWLINE import Configuration.PyReleaseValidation.relval_production as rvpNEWLINE self._args.datasets = [rvs.steps[rvp.workflows[1000][1][0]]["INPUT"].dataSet]NEWLINE self._validate_input() # ensure that this change is validNEWLINENEWLINE self._datasets = sorted([datasetNEWLINE for pattern in self._args.datasetsNEWLINE for dataset in get_datasets(pattern)NEWLINE if re.search(self._args.dataset_filter, dataset)])NEWLINE if len(self._datasets) == 0:NEWLINE print_msg("Found no dataset matching the pattern(s):")NEWLINE for d in self._args.datasets: print_msg("\t"+d)NEWLINE sys.exit(1)NEWLINENEWLINE self._formatted_dataset = merge_strings(NEWLINE [re.sub(self._dataset_regex, r"\1_\2_\3", dataset)NEWLINE for dataset in self._datasets])NEWLINE self._output_dir = os.path.join(self._args.output_dir,NEWLINE self._formatted_dataset)NEWLINE self._output_dir = os.path.abspath(self._output_dir)NEWLINE self._cache = _DasCache(self._output_dir)NEWLINE self._prepare_iov_datastructures()NEWLINE self._prepare_run_datastructures()NEWLINENEWLINE try:NEWLINE os.makedirs(self._output_dir)NEWLINE except OSError as e:NEWLINE if e.args == (17, "File exists"):NEWLINE if self._args.force:NEWLINE pass # do nothing, just clear the existing outputNEWLINE elif self._args.use_cache:NEWLINE self._cache.load() # load cache before clearing the outputNEWLINE else:NEWLINE print_msg("Directory '{}' already exists from previous runs"NEWLINE " of the script. Use '--use-cache' if you want to"NEWLINE " use the cached DAS-query results Or use "NEWLINE "'--force' to remove it."NEWLINE .format(self._output_dir))NEWLINE sys.exit(1)NEWLINE files = glob.glob(os.path.join(self._output_dir, "*"))NEWLINE for f in files: os.remove(f)NEWLINE else:NEWLINE raiseNEWLINENEWLINENEWLINE def create(self):NEWLINE """Creates file list. To be called by user of the class."""NEWLINENEWLINE self._request_dataset_information()NEWLINE self._create_file_lists()NEWLINE self._print_eventcounts()NEWLINE self._write_file_lists()NEWLINENEWLINENEWLINE _event_count_log = "event_count_info.log"NEWLINENEWLINENEWLINE def _define_parser(self):NEWLINE """Definition of command line argument parser."""NEWLINENEWLINE parser = argparse.ArgumentParser(NEWLINE description = "Create file lists for alignment",NEWLINE epilog = ("The tool will create a directory containing all file "NEWLINE "lists and a log file with all relevant event counts "NEWLINE "('{}').".format(FileListCreator._event_count_log)))NEWLINE parser.add_argument("-i", "--input", dest = "datasets", required = True,NEWLINE metavar = "DATASET", action = "append",NEWLINE help = ("CMS dataset name; supports wildcards; "NEWLINE "use multiple times for multiple datasets"))NEWLINE parser.add_argument("--dataset-filter", default = "",NEWLINE help = "regex to match within in the datasets matched,"NEWLINE "in case the wildcard isn't flexible enough")NEWLINE parser.add_argument("-j", "--json", dest = "json", metavar = "PATH",NEWLINE help = "path to JSON file (optional)")NEWLINE parser.add_argument("-f", "--fraction", dest = "fraction",NEWLINE type = float, default = 1,NEWLINE help = "max. fraction of files used for alignment")NEWLINE parser.add_argument("--iov", dest = "iovs", metavar = "RUN", type = int,NEWLINE action = "append", default = [],NEWLINE help = ("define IOV by specifying first run; for "NEWLINE "multiple IOVs use this option multiple "NEWLINE "times; files from runs before the lowest "NEWLINE "IOV are discarded (default: 1)"))NEWLINE parser.add_argument("--miniiov", dest="miniiovs", metavar="RUN", type=int,NEWLINE action="append", default=[],NEWLINE help=("in addition to the standard IOVs, break up hippy jobs "NEWLINE "at these points, so that jobs from before and after "NEWLINE "these runs are not in the same job"))NEWLINE parser.add_argument("-r", "--random", action = "store_true",NEWLINE default = False, help = "select files randomly")NEWLINE parser.add_argument("-n", "--events-for-alignment", "--maxevents",NEWLINE dest = "events", type = int, metavar = "NUMBER",NEWLINE help = ("number of events needed for alignment; the"NEWLINE " remaining events in the dataset are used "NEWLINE "for validation; if n<=0, all events are "NEWLINE "used for validation"))NEWLINE parser.add_argument("--all-events", action = "store_true",NEWLINE help = "Use all events for alignment")NEWLINE parser.add_argument("--tracks-for-alignment", dest = "tracks",NEWLINE type = int, metavar = "NUMBER",NEWLINE help = "number of tracks needed for alignment")NEWLINE parser.add_argument("--track-rate", dest = "rate", type = float,NEWLINE metavar = "NUMBER",NEWLINE help = "number of tracks per event")NEWLINE parser.add_argument("--run-by-run", dest = "run_by_run",NEWLINE action = "store_true", default = False,NEWLINE help = "create validation file list for each run")NEWLINE parser.add_argument("--minimum-events-in-iov",NEWLINE dest = "minimum_events_in_iov", metavar = "NUMBER",NEWLINE type = int, default = 100000,NEWLINE help = ("minimum number of events for alignment per"NEWLINE " IOV; this option has a higher priority "NEWLINE "than '-f/--fraction' "NEWLINE "(default: %(default)s)"))NEWLINE parser.add_argument("--minimum-events-validation",NEWLINE dest = "minimum_events_validation",NEWLINE metavar = "NUMBER", type = int, default = 1,NEWLINE help = ("minimum number of events for validation; "NEWLINE "applies to IOVs; in case of --run-by-run "NEWLINE "it applies to runs runs "NEWLINE "(default: %(default)s)"))NEWLINE parser.add_argument("--use-cache", dest = "use_cache",NEWLINE action = "store_true", default = False,NEWLINE help = "use DAS-query results of previous run")NEWLINE parser.add_argument("-o", "--output-dir", dest = "output_dir",NEWLINE metavar = "PATH", default = os.getcwd(),NEWLINE help = "output base directory (default: %(default)s)")NEWLINE parser.add_argument("--create-ini", dest = "create_ini",NEWLINE action = "store_true", default = False,NEWLINE help = ("create dataset ini file based on the "NEWLINE "created file lists"))NEWLINE parser.add_argument("--force", action = "store_true", default = False,NEWLINE help = ("remove output directory from previous "NEWLINE "runs, if existing"))NEWLINE parser.add_argument("--hippy-events-per-job", type = int, default = 1,NEWLINE help = ("approximate number of events in each job for HipPy"))NEWLINE parser.add_argument("--test-mode", dest = "test_mode",NEWLINE action = "store_true", default = False,NEWLINE help = argparse.SUPPRESS) # hidden optionNEWLINE return parserNEWLINENEWLINENEWLINE def _validate_input(self):NEWLINE """Validate command line arguments."""NEWLINENEWLINE if self._args.events is None:NEWLINE if self._args.all_events:NEWLINE self._args.events = float("inf")NEWLINE print_msg("Using all tracks for alignment")NEWLINE elif (self._args.tracks is None) and (self._args.rate is None):NEWLINE msg = ("either -n/--events-for-alignment, --all-events, or both of "NEWLINE "--tracks-for-alignment and --track-rate are required")NEWLINE self._parser.error(msg)NEWLINE elif (((self._args.tracks is not None) and (self._args.rate is None)) orNEWLINE ((self._args.rate is not None)and (self._args.tracks is None))):NEWLINE msg = ("--tracks-for-alignment and --track-rate must be used "NEWLINE "together")NEWLINE self._parser.error(msg)NEWLINE else:NEWLINE self._args.events = int(math.ceil(self._args.tracks /NEWLINE self._args.rate))NEWLINE print_msg("Requested {0:d} tracks with {1:.2f} tracks/event "NEWLINE "-> {2:d} events for alignment."NEWLINE .format(self._args.tracks, self._args.rate,NEWLINE self._args.events))NEWLINE else:NEWLINE if (self._args.tracks is not None) or (self._args.rate is not None) or self._args.all_events:NEWLINE msg = ("-n/--events-for-alignment must not be used with "NEWLINE "--tracks-for-alignment, --track-rate, or --all-events")NEWLINE self._parser.error(msg)NEWLINE print_msg("Requested {0:d} events for alignment."NEWLINE .format(self._args.events))NEWLINENEWLINE for dataset in self._args.datasets:NEWLINE if not re.match(self._dataset_regex, dataset):NEWLINE print_msg("Dataset pattern '"+dataset+"' is not in CMS format.")NEWLINE sys.exit(1)NEWLINENEWLINE nonzero_events_per_iov = (self._args.minimum_events_in_iov > 0)NEWLINE if nonzero_events_per_iov and self._args.fraction <= 0:NEWLINE print_msg("Setting minimum number of events per IOV for alignment "NEWLINE "to 0 because a non-positive fraction of alignment events"NEWLINE " is chosen: {}".format(self._args.fraction))NEWLINE nonzero_events_per_iov = FalseNEWLINE self._args.minimum_events_in_iov = 0NEWLINE if nonzero_events_per_iov and self._args.events <= 0:NEWLINE print_msg("Setting minimum number of events per IOV for alignment "NEWLINE "to 0 because a non-positive number of alignment events"NEWLINE " is chosen: {}".format(self._args.events))NEWLINE nonzero_events_per_iov = FalseNEWLINE self._args.minimum_events_in_iov = 0NEWLINENEWLINENEWLINE def _prepare_iov_datastructures(self):NEWLINE """Create the needed objects for IOV handling."""NEWLINENEWLINE self._iovs = sorted(set(self._args.iovs))NEWLINE if len(self._iovs) == 0: self._iovs.append(1)NEWLINE self._iov_info_alignment = {iov: {"events": 0, "files": []}NEWLINE for iov in self._iovs}NEWLINE self._iov_info_validation = {iov: {"events": 0, "files": []}NEWLINE for iov in self._iovs}NEWLINENEWLINE self._miniiovs = sorted(set(self._iovs) | set(self._args.miniiovs))NEWLINENEWLINENEWLINE def _get_iovs(self, runs, useminiiovs=False):NEWLINE """NEWLINE Return the IOV start for `run`. Returns 'None' if the run is before anyNEWLINE defined IOV.NEWLINENEWLINE Arguments:NEWLINE - `runs`: run numbersNEWLINE """NEWLINENEWLINE iovlist = self._miniiovs if useminiiovs else self._iovsNEWLINENEWLINE iovs = []NEWLINE for run in runs:NEWLINE iov_index = bisect.bisect(iovlist, run)NEWLINE if iov_index > 0: iovs.append(iovlist[iov_index-1])NEWLINE return iovsNEWLINENEWLINENEWLINE def _prepare_run_datastructures(self):NEWLINE """Create the needed objects for run-by-run validation file lists."""NEWLINENEWLINE self._run_info = {}NEWLINENEWLINENEWLINE def _add_file_info(self, container, keys, fileinfo):NEWLINE """Add file with `file_name` to `container` using `key`.NEWLINENEWLINE Arguments:NEWLINE - `container`: dictionary holding information on files and event countsNEWLINE - `keys`: keys to which the info should be added; will be created if notNEWLINE existingNEWLINE - `file_name`: name of a dataset fileNEWLINE """NEWLINENEWLINE for key in keys:NEWLINE if key not in container:NEWLINE container[key] = {"events": 0,NEWLINE "files": []}NEWLINE container[key]["events"] += fileinfo.nevents / len(keys)NEWLINE if fileinfo not in container[key]["files"]:NEWLINE container[key]["files"].append(fileinfo)NEWLINENEWLINENEWLINE def _remove_file_info(self, container, keys, fileinfo):NEWLINE """Remove file with `file_name` to `container` using `key`.NEWLINENEWLINE Arguments:NEWLINE - `container`: dictionary holding information on files and event countsNEWLINE - `keys`: keys from which the info should be removedNEWLINE - `file_name`: name of a dataset fileNEWLINE - `event_count`: number of events in `file_name`NEWLINE """NEWLINENEWLINE for key in keys:NEWLINE if key not in container: continueNEWLINE try:NEWLINE index = container[key]["files"].index(fileinfo)NEWLINE except ValueError: # file not foundNEWLINE returnNEWLINE del container[key]["files"][index]NEWLINE container[key]["events"] -= fileinfo.nevents / len(keys)NEWLINENEWLINENEWLINE def _request_dataset_information(self):NEWLINE """Retrieve general dataset information and create file list."""NEWLINENEWLINE if not self._cache.empty:NEWLINE print_msg("Using cached information.")NEWLINE (self._events_in_dataset,NEWLINE self._files,NEWLINE self._file_info,NEWLINE self._max_run) = self._cache.get()NEWLINE self.rereco = any(len(fileinfo.runs)>1 for fileinfo in self._file_info)NEWLINE if self._args.random: random.shuffle(self._files)NEWLINE returnNEWLINENEWLINE # workaround to deal with KeyboardInterrupts in the worker processes:NEWLINE # - ignore interrupt signals in workers (see initializer)NEWLINE # - use a timeout of size sys.maxsize to avoid a bug in multiprocessingNEWLINE number_of_processes = multiprocessing.cpu_count() - 1NEWLINE number_of_processes = (number_of_processesNEWLINE if number_of_processes > 0NEWLINE else 1)NEWLINE pool = multiprocessing.Pool(NEWLINE processes = number_of_processes,NEWLINE initializer = lambda: signal.signal(signal.SIGINT, signal.SIG_IGN))NEWLINENEWLINE print_msg("Requesting information for the following dataset(s):")NEWLINE for d in self._datasets: print_msg("\t"+d)NEWLINE print_msg("This may take a while...")NEWLINENEWLINE result = pool.map_async(get_events_per_dataset, self._datasets).get(3600)NEWLINE self._events_in_dataset = sum(result)NEWLINENEWLINE result = pool.map_async(get_max_run, self._datasets).get(3600)NEWLINE self._max_run = max(result)NEWLINENEWLINE result = sum(pool.map_async(get_file_info, self._datasets).get(3600), [])NEWLINE files = pool.map_async(_make_file_info, result).get(3600)NEWLINE self._file_info = sorted(fileinfo for fileinfo in files)NEWLINENEWLINE self.rereco = any(len(fileinfo.runs)>1 for fileinfo in self._file_info)NEWLINENEWLINE if self._args.test_mode:NEWLINE self._file_info = self._file_info[-200:] # take only last chunk of filesNEWLINE self._files = [fileinfo.name for fileinfo in self._file_info]NEWLINENEWLINE # write information to cacheNEWLINE self._cache.set(self._events_in_dataset, self._files, self._file_info,NEWLINE self._max_run)NEWLINE self._cache.dump()NEWLINE if self._args.random:NEWLINE random.shuffle(self._file_info)NEWLINE self._files = [fileinfo.name for fileinfo in self._file_info]NEWLINENEWLINE def _create_file_lists(self):NEWLINE """Create file lists for alignment and validation."""NEWLINENEWLINE # collect files for alignment until minimal requirements are fulfilledNEWLINE self._files_alignment = []NEWLINE self._files_validation = []NEWLINE self._events_for_alignment = 0NEWLINE self._events_for_validation = 0NEWLINENEWLINE max_range = (0NEWLINE if self._args.events <= 0NEWLINE else int(math.ceil(len(self._files)*self._args.fraction)))NEWLINE use_for_alignment = TrueNEWLINE for i, fileinfo in enumerate(self._file_info):NEWLINE enough_events = self._events_for_alignment >= self._args.eventsNEWLINE fraction_exceeded = i >= max_rangeNEWLINE if enough_events or fraction_exceeded: use_for_alignment = FalseNEWLINENEWLINE dataset, f, number_of_events, runs = fileinfoNEWLINENEWLINE iovs = self._get_iovs(runs)NEWLINE if use_for_alignment:NEWLINE if iovs:NEWLINE self._events_for_alignment += number_of_eventsNEWLINE self._files_alignment.append(fileinfo)NEWLINE self._add_file_info(self._iov_info_alignment, iovs, fileinfo)NEWLINE else:NEWLINE max_range += 1 # not used -> discard in fraction calculationNEWLINE else:NEWLINE if iovs:NEWLINE self._events_for_validation += number_of_eventsNEWLINE self._files_validation.append(fileinfo)NEWLINE self._add_file_info(self._iov_info_validation, iovs, fileinfo)NEWLINE if self._args.run_by_run:NEWLINE self._add_file_info(self._run_info, runs, fileinfo)NEWLINENEWLINE self._fulfill_iov_eventcount()NEWLINENEWLINE self._split_hippy_jobs()NEWLINENEWLINENEWLINE def _fulfill_iov_eventcount(self):NEWLINE """NEWLINE Try to fulfill the requirement on the minimum number of events per IOVNEWLINE in the alignment file list by picking files from the validation list.NEWLINE """NEWLINENEWLINE for iov in self._iovs:NEWLINE if self._iov_info_alignment[iov]["events"] >= self._args.minimum_events_in_iov: continueNEWLINE for fileinfo in self._files_validation[:]:NEWLINE dataset, f, number_of_events, runs = fileinfoNEWLINE iovs = self._get_iovs(runs)NEWLINE if iov in iovs:NEWLINE self._files_alignment.append(fileinfo)NEWLINE self._events_for_alignment += number_of_eventsNEWLINE self._add_file_info(self._iov_info_alignment, iovs, fileinfo)NEWLINENEWLINE self._events_for_validation -= number_of_eventsNEWLINE self._remove_file_info(self._iov_info_validation, iovs, fileinfo)NEWLINE if self._args.run_by_run:NEWLINE self._remove_file_info(self._run_info, runs, fileinfo)NEWLINE self._files_validation.remove(fileinfo)NEWLINENEWLINE if (self._iov_info_alignment[iov]["events"]NEWLINE >= self._args.minimum_events_in_iov):NEWLINE break # break the file loop if already enough eventsNEWLINENEWLINE def _split_hippy_jobs(self):NEWLINE hippyjobs = {}NEWLINE for dataset, miniiov in itertools.product(self._datasets, self._miniiovs):NEWLINE jobsforminiiov = []NEWLINE hippyjobs[dataset,miniiov] = jobsforminiiovNEWLINE eventsinthisjob = float("inf")NEWLINE for fileinfo in self._files_alignment:NEWLINE if fileinfo.dataset != dataset: continueNEWLINE miniiovs = set(self._get_iovs(fileinfo.runs, useminiiovs=True))NEWLINE if miniiov not in miniiovs: continueNEWLINE if len(miniiovs) > 1:NEWLINE hippyjobs[dataset,miniiov] = []NEWLINE if eventsinthisjob >= self._args.hippy_events_per_job:NEWLINE currentjob = []NEWLINE jobsforminiiov.append(currentjob)NEWLINE eventsinthisjob = 0NEWLINE currentjob.append(fileinfo)NEWLINE currentjob.sort()NEWLINE eventsinthisjob += fileinfo.neventsNEWLINENEWLINE self._hippy_jobs = {NEWLINE (dataset, iov): sum((hippyjobs[dataset, miniiov]NEWLINE for miniiov in self._miniiovsNEWLINE if iov == max(_ for _ in self._iovs if _ <= miniiov)), []NEWLINE )NEWLINE for dataset, iov in itertools.product(self._datasets, self._iovs)NEWLINE }NEWLINENEWLINE def _print_eventcounts(self):NEWLINE """Print the event counts per file list and per IOV."""NEWLINENEWLINE log = os.path.join(self._output_dir, FileListCreator._event_count_log)NEWLINENEWLINE print_msg("Using {0:d} events for alignment ({1:.2f}%)."NEWLINE .format(self._events_for_alignment,NEWLINE 100.0*NEWLINE self._events_for_alignment/self._events_in_dataset),NEWLINE log_file = log)NEWLINE for iov in sorted(self._iov_info_alignment):NEWLINE print_msg(("Approximate events" if self.rereco else "Events") + " for alignment in IOV since {0:f}: {1:f}"NEWLINE .format(iov, self._iov_info_alignment[iov]["events"]),NEWLINE log_file = log)NEWLINENEWLINE print_msg("Using {0:d} events for validation ({1:.2f}%)."NEWLINE .format(self._events_for_validation,NEWLINE 100.0*NEWLINE self._events_for_validation/self._events_in_dataset),NEWLINE log_file = log)NEWLINENEWLINE for iov in sorted(self._iov_info_validation):NEWLINE msg = ("Approximate events" if self.rereco else "Events") + " for validation in IOV since {0:f}: {1:f}".format(NEWLINE iov, self._iov_info_validation[iov]["events"])NEWLINE if (self._iov_info_validation[iov]["events"]NEWLINE < self._args.minimum_events_validation):NEWLINE msg += " (not enough events -> no dataset file will be created)"NEWLINE print_msg(msg, log_file = log)NEWLINENEWLINE for run in sorted(self._run_info):NEWLINE msg = ("Approximate events" if self.rereco else "Events") + " for validation in run {0:f}: {1:f}".format(NEWLINE run, self._run_info[run]["events"])NEWLINE if (self._run_info[run]["events"]NEWLINE < self._args.minimum_events_validation):NEWLINE msg += " (not enough events -> no dataset file will be created)"NEWLINE print_msg(msg, log_file = log)NEWLINENEWLINE unused_events = (self._events_in_datasetNEWLINE - self._events_for_validationNEWLINE - self._events_for_alignment)NEWLINE if unused_events > 0 != self._events_in_dataset:NEWLINE print_msg("Unused events: {0:d} ({1:.2f}%)"NEWLINE .format(unused_events,NEWLINE 100.0*unused_events/self._events_in_dataset),NEWLINE log_file = log)NEWLINENEWLINENEWLINE def _create_dataset_ini_section(self, name, collection, json_file = None):NEWLINE """Write dataset ini snippet.NEWLINENEWLINE Arguments:NEWLINE - `name`: name of the dataset sectionNEWLINE - `collection`: track collection of this datasetNEWLINE - `json_file`: JSON file to be used for this dataset (optional)NEWLINE """NEWLINENEWLINE if json_file:NEWLINE splitted = name.split("_since")NEWLINE file_list = "_since".join(splitted[:-1]NEWLINE if len(splitted) > 1NEWLINE else splitted)NEWLINE else:NEWLINE file_list = nameNEWLINE output = "[dataset:{}]\n".format(name)NEWLINE output += "collection = {}\n".format(collection)NEWLINE output += "inputFileList = ${{datasetdir}}/{}.txt\n".format(file_list)NEWLINE output += "json = ${{datasetdir}}/{}\n".format(json_file) if json_file else ""NEWLINENEWLINE if collection in ("ALCARECOTkAlCosmicsCTF0T",NEWLINE "ALCARECOTkAlCosmicsInCollisions"):NEWLINE if self._first_dataset_ini:NEWLINE print_msg("\tDetermined cosmics dataset, i.e. please replace "NEWLINE "'DUMMY_DECO_MODE_FLAG' and 'DUMMY_ZERO_TESLA_FLAG' "NEWLINE "with the correct values.")NEWLINE self._first_dataset_ini = FalseNEWLINE output += "cosmicsDecoMode = DUMMY_DECO_MODE_FLAG\n"NEWLINE output += "cosmicsZeroTesla = DUMMY_ZERO_TESLA_FLAG\n"NEWLINE output += "\n"NEWLINENEWLINE return outputNEWLINENEWLINENEWLINE def _create_json_file(self, name, first, last = None):NEWLINE """NEWLINE Create JSON file with `name` covering runs from `first` to `last`. If aNEWLINE global JSON is provided, the resulting file is the intersection of theNEWLINE file created here and the global one.NEWLINE Returns the name of the created JSON file.NEWLINENEWLINE Arguments:NEWLINE - `name`: name of the creted JSON fileNEWLINE - `first`: first run covered by the JSON fileNEWLINE - `last`: last run covered by the JSON fileNEWLINENEWLINE """NEWLINENEWLINE if last is None: last = self._max_runNEWLINE name += "_JSON.txt"NEWLINE print_msg("Creating JSON file: "+name)NEWLINENEWLINE json_file = LumiList.LumiList(runs = range(first, last+1))NEWLINE if self._args.json:NEWLINE global_json = LumiList.LumiList(filename = self._args.json)NEWLINE json_file = json_file & global_jsonNEWLINE json_file.writeJSON(os.path.join(self._output_dir, name))NEWLINENEWLINE return nameNEWLINENEWLINENEWLINE def _get_track_collection(self, edm_file):NEWLINE """Extract track collection from given `edm_file`.NEWLINENEWLINE Arguments:NEWLINE - `edm_file`: CMSSW dataset fileNEWLINE """NEWLINENEWLINE # use global redirector to allow also files not yet at your site:NEWLINE cmd = ["edmDumpEventContent", r"root://cms-xrd-global.cern.ch/"+edm_file]NEWLINE try:NEWLINE event_content = subprocess.check_output(cmd).split("\n")NEWLINE except subprocess.CalledProcessError as e:NEWLINE splitted = edm_file.split("/")NEWLINE try:NEWLINE alcareco = splitted[splitted.index("ALCARECO")+1].split("-")[0]NEWLINE alcareco = alcareco.replace("TkAlCosmics0T", "TkAlCosmicsCTF0T")NEWLINE alcareco = "ALCARECO" + alcarecoNEWLINE print_msg("\tDetermined track collection as '{}'.".format(alcareco))NEWLINE return alcarecoNEWLINE except ValueError:NEWLINE if "RECO" in splitted:NEWLINE print_msg("\tDetermined track collection as 'generalTracks'.")NEWLINE return "generalTracks"NEWLINE else:NEWLINE print_msg("\tCould not determine track collection "NEWLINE "automatically.")NEWLINE print_msg("\tPlease replace 'DUMMY_TRACK_COLLECTION' with "NEWLINE "the correct value.")NEWLINE return "DUMMY_TRACK_COLLECTION"NEWLINENEWLINE track_collections = []NEWLINE for line in event_content:NEWLINE splitted = line.split()NEWLINE if len(splitted) > 0 and splitted[0] == r"vector":NEWLINE track_collections.append(splitted[1].strip().strip('"'))NEWLINE if len(track_collections) == 0:NEWLINE print_msg("No track collection found in file '{}'.".format(edm_file))NEWLINE sys.exit(1)NEWLINE elif len(track_collections) == 1:NEWLINE print_msg("\tDetermined track collection as "NEWLINE "'{}'.".format(track_collections[0]))NEWLINE return track_collections[0]NEWLINE else:NEWLINE alcareco_tracks = filter(lambda x: x.startswith("ALCARECO"),NEWLINE track_collections)NEWLINE if len(alcareco_tracks) == 0 and "generalTracks" in track_collections:NEWLINE print_msg("\tDetermined track collection as 'generalTracks'.")NEWLINE return "generalTracks"NEWLINE elif len(alcareco_tracks) == 1:NEWLINE print_msg("\tDetermined track collection as "NEWLINE "'{}'.".format(alcareco_tracks[0]))NEWLINE return alcareco_tracks[0]NEWLINE print_msg("\tCould not unambiguously determine track collection in "NEWLINE "file '{}':".format(edm_file))NEWLINE print_msg("\tPlease replace 'DUMMY_TRACK_COLLECTION' with "NEWLINE "the correct value from the following list.")NEWLINE for collection in track_collections:NEWLINE print_msg("\t - "+collection)NEWLINE return "DUMMY_TRACK_COLLECTION"NEWLINENEWLINENEWLINE def _write_file_lists(self):NEWLINE """Write file lists to disk."""NEWLINENEWLINE self._create_dataset_txt(self._formatted_dataset, self._files_alignment)NEWLINE self._create_hippy_txt(self._formatted_dataset, sum(self._hippy_jobs.values(), []))NEWLINE self._create_dataset_cff(NEWLINE "_".join(["Alignment", self._formatted_dataset]),NEWLINE self._files_alignment)NEWLINENEWLINE self._create_dataset_cff(NEWLINE "_".join(["Validation", self._formatted_dataset]),NEWLINE self._files_validation)NEWLINENEWLINENEWLINE if self._args.create_ini:NEWLINE dataset_ini_general = "[general]\n"NEWLINE dataset_ini_general += "datasetdir = {}\n".format(self._output_dir)NEWLINE dataset_ini_general += ("json = {}\n\n".format(self._args.json)NEWLINE if self._args.jsonNEWLINE else "\n")NEWLINENEWLINE ini_path = self._formatted_dataset + ".ini"NEWLINE print_msg("Creating dataset ini file: " + ini_path)NEWLINE ini_path = os.path.join(self._output_dir, ini_path)NEWLINENEWLINE collection = self._get_track_collection(self._files[0])NEWLINENEWLINE with open(ini_path, "w") as f:NEWLINE f.write(dataset_ini_general)NEWLINE f.write(self._create_dataset_ini_section(NEWLINE self._formatted_dataset, collection))NEWLINENEWLINE iov_wise_ini = dataset_ini_generalNEWLINENEWLINE for i,iov in enumerate(sorted(self._iovs)):NEWLINE iov_str = "since{0:d}".format(iov)NEWLINE iov_str = "_".join([self._formatted_dataset, iov_str])NEWLINENEWLINE if self.rereco:NEWLINE if i == len(self._iovs) - 1:NEWLINE last = NoneNEWLINE else:NEWLINE last = sorted(self._iovs)[i+1] - 1NEWLINE local_json = self._create_json_file(iov_str, iov, last)NEWLINE else:NEWLINE local_json = NoneNEWLINENEWLINE if self._args.create_ini:NEWLINE iov_wise_ini += self._create_dataset_ini_section(iov_str,NEWLINE collection,NEWLINE local_json)NEWLINENEWLINE self._create_dataset_txt(iov_str,NEWLINE self._iov_info_alignment[iov]["files"])NEWLINE self._create_hippy_txt(iov_str, sum((self._hippy_jobs[dataset,iov] for dataset in self._datasets), []))NEWLINE self._create_dataset_cff(NEWLINE "_".join(["Alignment", iov_str]),NEWLINE self._iov_info_alignment[iov]["files"],NEWLINE json_file=local_json)NEWLINENEWLINE if (self._iov_info_validation[iov]["events"]NEWLINE < self._args.minimum_events_validation):NEWLINE continueNEWLINE self._create_dataset_cff(NEWLINE "_".join(["Validation", iov_str]),NEWLINE self._iov_info_validation[iov]["files"],NEWLINE json_file=local_json)NEWLINENEWLINE if self._args.create_ini and iov_wise_ini != dataset_ini_general:NEWLINE ini_path = self._formatted_dataset + "_IOVs.ini"NEWLINE print_msg("Creating dataset ini file: " + ini_path)NEWLINE ini_path = os.path.join(self._output_dir, ini_path)NEWLINE with open(ini_path, "w") as f: f.write(iov_wise_ini)NEWLINENEWLINE for run in sorted(self._run_info):NEWLINE if args.rereco: continue #need to implement more jsonsNEWLINE if (self._run_info[run]["events"]NEWLINE < self._args.minimum_events_validation):NEWLINE continueNEWLINE self._create_dataset_cff(NEWLINE "_".join(["Validation", self._formatted_dataset, str(run)]),NEWLINE self._run_info[run]["files"])NEWLINENEWLINENEWLINE def _create_dataset_txt(self, name, file_list):NEWLINE """Write alignment file list to disk.NEWLINENEWLINE Arguments:NEWLINE - `name`: name of the file listNEWLINE - `file_list`: list of files to write to `name`NEWLINE """NEWLINENEWLINE name += ".txt"NEWLINE print_msg("Creating dataset file list: "+name)NEWLINE with open(os.path.join(self._output_dir, name), "w") as f:NEWLINE f.write("\n".join(fileinfo.name for fileinfo in file_list))NEWLINENEWLINENEWLINE def _create_hippy_txt(self, name, job_list):NEWLINE name += "_hippy.txt"NEWLINE print_msg("Creating dataset file list for HipPy: "+name)NEWLINE with open(os.path.join(self._output_dir, name), "w") as f:NEWLINE f.write("\n".join(",".join("'"+fileinfo.name+"'" for fileinfo in job) for job in job_list)+"\n")NEWLINENEWLINENEWLINE def _create_dataset_cff(self, name, file_list, json_file = None):NEWLINE """NEWLINE Create configuration fragment to define a dataset.NEWLINENEWLINE Arguments:NEWLINE - `name`: name of the configuration fragmentNEWLINE - `file_list`: list of files to write to `name`NEWLINE - `json_file`: JSON file to be used for this dataset (optional)NEWLINE """NEWLINENEWLINE if json_file is None: json_file = self._args.json # might still be NoneNEWLINE if json_file is not None:NEWLINE json_file = os.path.join(self._output_dir, json_file)NEWLINENEWLINE name = "_".join(["Dataset",name, "cff.py"])NEWLINE print_msg("Creating dataset configuration fragment: "+name)NEWLINENEWLINE file_list_str = ""NEWLINE for sub_list in get_chunks(file_list, 255):NEWLINE file_list_str += ("readFiles.extend([\n'"+NEWLINE "',\n'".join(fileinfo.name for fileinfo in sub_list)+NEWLINE "'\n])\n")NEWLINENEWLINE fragment = FileListCreator._dataset_template.format(NEWLINE lumi_def = ("import FWCore.PythonUtilities.LumiList as LumiList\n\n"NEWLINE "lumiSecs = cms.untracked.VLuminosityBlockRange()\n"NEWLINE "goodLumiSecs = LumiList.LumiList(filename = "NEWLINE "'{0:s}').getCMSSWString().split(',')"NEWLINE .format(json_file)NEWLINE if json_file else ""),NEWLINE lumi_arg = ("lumisToProcess = lumiSecs,\n "NEWLINE if json_file else ""),NEWLINE lumi_extend = "lumiSecs.extend(goodLumiSecs)" if json_file else "",NEWLINE files = file_list_str)NEWLINENEWLINE with open(os.path.join(self._output_dir, name), "w") as f:NEWLINE f.write(fragment)NEWLINENEWLINENEWLINE _dataset_template = """\NEWLINEimport FWCore.ParameterSet.Config as cmsNEWLINE{lumi_def:s}NEWLINEreadFiles = cms.untracked.vstring()NEWLINEsource = cms.Source("PoolSource",NEWLINE {lumi_arg:s}fileNames = readFiles)NEWLINE{files:s}{lumi_extend:s}NEWLINEmaxEvents = cms.untracked.PSet(input = cms.untracked.int32(-1))NEWLINE"""NEWLINENEWLINENEWLINEclass _DasCache(object):NEWLINE """Helper class to cache information from DAS requests."""NEWLINENEWLINE def __init__(self, file_list_id):NEWLINE """Constructor of the cache.NEWLINENEWLINE Arguments:NEWLINE - `file_list_id`: ID of the cached file listsNEWLINE """NEWLINENEWLINE self._file_list_id = file_list_idNEWLINE self._cache_file_name = os.path.join(file_list_id, ".das_cache.pkl")NEWLINE self.reset()NEWLINENEWLINENEWLINE def reset(self):NEWLINE """Reset the cache contents and the 'empty' flag."""NEWLINENEWLINE self._empty = TrueNEWLINE self._events_in_dataset = 0NEWLINE self._files = []NEWLINE self._file_info = []NEWLINE self._max_run = NoneNEWLINENEWLINENEWLINE def set(self, total_events, file_list, file_info, max_run):NEWLINE """Set the content of the cache.NEWLINENEWLINE Arguments:NEWLINE - `total_events`: total number of events in datasetNEWLINE - `file_list`: list of files in datasetNEWLINE - `file_info`: dictionary with numbers of events per fileNEWLINE - `max_run`: highest run number contained in the datasetNEWLINE """NEWLINENEWLINE self._events_in_dataset = total_eventsNEWLINE self._files = file_listNEWLINE self._file_info = file_infoNEWLINE self._max_run = max_runNEWLINE self._empty = FalseNEWLINENEWLINENEWLINE def get(self):NEWLINE """NEWLINE Get the content of the cache as tuple:NEWLINE result = (total number of events in dataset,NEWLINE list of files in dataset,NEWLINE dictionary with numbers of events and runs per file)NEWLINE """NEWLINENEWLINE return self._events_in_dataset, self._files, self._file_info, self._max_runNEWLINENEWLINENEWLINE def load(self):NEWLINE """Loads the cached contents."""NEWLINENEWLINE if not self.empty:NEWLINE print_msg("Overriding file information with cached information.")NEWLINE try:NEWLINE with open(self._cache_file_name, "rb") as f:NEWLINE tmp_dict = cPickle.load(f)NEWLINE self.__dict__.update(tmp_dict)NEWLINE except IOError as e:NEWLINE if e.args == (2, "No such file or directory"):NEWLINE msg = "Failed to load cache for '{}'.".format(self._file_list_id)NEWLINE if not self.empty:NEWLINE msg += " Keeping the previous file information."NEWLINE print_msg(msg)NEWLINE else:NEWLINE raiseNEWLINENEWLINENEWLINE def dump(self):NEWLINE """Dumps the contents to the cache file."""NEWLINENEWLINE if self.empty:NEWLINE print_msg("Cache is empty. Not writing to file.")NEWLINE returnNEWLINENEWLINE with open(self._cache_file_name, "wb") as f:NEWLINE cPickle.dump(self.__dict__, f, 2)NEWLINENEWLINENEWLINE @propertyNEWLINE def empty(self):NEWLINE """NEWLINE Flag indicating whether the cache is empty or has been filled (possiblyNEWLINE with nothing).NEWLINE """NEWLINENEWLINE return self._emptyNEWLINENEWLINENEWLINENEWLINE################################################################################NEWLINEdef das_client(query, check_key = None):NEWLINE """NEWLINE Submit `query` to DAS client and handle possible errors.NEWLINE Further treatment of the output might be necessary.NEWLINENEWLINE Arguments:NEWLINE - `query`: DAS queryNEWLINE - `check_key`: optional key to be checked for; retriggers query if neededNEWLINE """NEWLINENEWLINE error = TrueNEWLINE for i in range(5): # maximum of 5 triesNEWLINE try:NEWLINE das_data = cmssw_das_client.get_data(query, limit = 0)NEWLINE except IOError as e:NEWLINE if e.errno == 14: #https://stackoverflow.com/q/36397853/5228524NEWLINE continueNEWLINE except ValueError as e:NEWLINE if str(e) == "No JSON object could be decoded":NEWLINE continueNEWLINENEWLINE if das_data["status"] == "ok":NEWLINE if das_data["nresults"] == 0 or check_key is None:NEWLINE error = FalseNEWLINE breakNEWLINENEWLINE result_count = 0NEWLINE for d in find_key(das_data["data"], [check_key]):NEWLINE result_count += len(d)NEWLINE if result_count == 0:NEWLINE das_data["status"] = "error"NEWLINE das_data["reason"] = ("DAS did not return required data.")NEWLINE continueNEWLINE else:NEWLINE error = FalseNEWLINE breakNEWLINENEWLINE if das_data["status"] == "error":NEWLINE print_msg("DAS query '{}' failed 5 times. "NEWLINE "The last time for the the following reason:".format(query))NEWLINE print(das_data["reason"])NEWLINE sys.exit(1)NEWLINE return das_data["data"]NEWLINENEWLINENEWLINEdef find_key(collection, key_chain):NEWLINE """Searches for `key` in `collection` and returns first corresponding value.NEWLINENEWLINE Arguments:NEWLINE - `collection`: list of dictionariesNEWLINE - `key_chain`: chain of keys to be searched forNEWLINE """NEWLINENEWLINE result = NoneNEWLINE for i,key in enumerate(key_chain):NEWLINE for item in collection:NEWLINE if key in item:NEWLINE if i == len(key_chain) - 1:NEWLINE result = item[key]NEWLINE else:NEWLINE try:NEWLINE result = find_key(item[key], key_chain[i+1:])NEWLINE except LookupError:NEWLINE pass # continue with next `item` in `collection`NEWLINE else:NEWLINE pass # continue with next `item` in `collection`NEWLINENEWLINE if result is not None: return resultNEWLINE raise LookupError(key_chain, collection) # putNEWLINENEWLINENEWLINEdef print_msg(text, line_break = True, log_file = None):NEWLINE """Formatted printing of `text`.NEWLINENEWLINE Arguments:NEWLINE - `text`: string to be printedNEWLINE """NEWLINENEWLINE msg = " >>> " + str(text)NEWLINE if line_break:NEWLINE print(msg)NEWLINE else:NEWLINE print(msg, end=' ')NEWLINE sys.stdout.flush()NEWLINE if log_file:NEWLINE with open(log_file, "a") as f: f.write(msg+"\n")NEWLINE return msgNEWLINENEWLINENEWLINEdef get_runs(file_name):NEWLINE """NEWLINE Try to guess the run number from `file_name`. If run could not beNEWLINE determined, gets the run numbers from DAS (slow!)NEWLINENEWLINE Arguments:NEWLINE - `file_name`: name of the considered fileNEWLINE """NEWLINE try:NEWLINE return [int("".join(file_name.split("/")[-4:-2]))]NEWLINE except ValueError:NEWLINE query = "run file="+file_name+" system=dbs3"NEWLINE return [int(_) for _ in find_key(das_client(query), ["run", "run_number"])]NEWLINENEWLINENEWLINEdef get_max_run(dataset_name):NEWLINE """Retrieve the maximum run number in `dataset_name`.NEWLINENEWLINE Arguments:NEWLINE - `dataset_name`: name of the datasetNEWLINE """NEWLINENEWLINE data = das_client("run dataset={0:s} system=dbs3".format(dataset_name))NEWLINE runs = [f["run"][0]["run_number"] for f in data]NEWLINE return max(runs)NEWLINENEWLINENEWLINEdef get_files(dataset_name):NEWLINE """Retrieve list of files in `dataset_name`.NEWLINENEWLINE Arguments:NEWLINE - `dataset_name`: name of the datasetNEWLINE """NEWLINENEWLINE data = das_client(("file dataset={0:s} system=dbs3 detail=True | "+NEWLINE "grep file.name, file.nevents > 0").format(dataset_name),NEWLINE "file")NEWLINE return [find_key(f["file"], ["name"]) for f in data]NEWLINENEWLINENEWLINEdef get_datasets(dataset_pattern):NEWLINE """Retrieve list of dataset matching `dataset_pattern`.NEWLINENEWLINE Arguments:NEWLINE - `dataset_pattern`: pattern of dataset namesNEWLINE """NEWLINENEWLINE data = das_client("dataset dataset={0:s} system=dbs3 detail=True"NEWLINE "| grep dataset.name".format(dataset_pattern), "dataset")NEWLINE return sorted(set([find_key(f["dataset"], ["name"]) for f in data]))NEWLINENEWLINENEWLINEdef get_events_per_dataset(dataset_name):NEWLINE """Retrieve the number of a events in `dataset_name`.NEWLINENEWLINE Arguments:NEWLINE - `dataset_name`: name of a datasetNEWLINE """NEWLINENEWLINE return _get_events("dataset", dataset_name)NEWLINENEWLINENEWLINEdef get_events_per_file(file_name):NEWLINE """Retrieve the number of a events in `file_name`.NEWLINENEWLINE Arguments:NEWLINE - `file_name`: name of a dataset fileNEWLINE """NEWLINENEWLINE return _get_events("file", file_name)NEWLINENEWLINENEWLINEdef _get_events(entity, name):NEWLINE """Retrieve the number of events from `entity` called `name`.NEWLINENEWLINE Arguments:NEWLINE - `entity`: type of entityNEWLINE - `name`: name of entityNEWLINE """NEWLINENEWLINE data = das_client("{0:s}={1:s} system=dbs3 detail=True | grep {0:s}.nevents"NEWLINE .format(entity, name), entity)NEWLINE return int(find_key(data, [entity, "nevents"]))NEWLINENEWLINENEWLINEdef _get_properties(name, entity, properties, filters = None, sub_entity = None,NEWLINE aggregators = None):NEWLINE """Retrieve `properties` from `entity` called `name`.NEWLINENEWLINE Arguments:NEWLINE - `name`: name of entityNEWLINE - `entity`: type of entityNEWLINE - `properties`: list of property namesNEWLINE - `filters`: list of filters on propertiesNEWLINE - `sub_entity`: type of entity from which to extract the properties;NEWLINE defaults to `entity`NEWLINE - `aggregators`: additional aggregators/filters to amend to queryNEWLINE """NEWLINENEWLINE if sub_entity is None: sub_entity = entityNEWLINE if filters is None: filters = []NEWLINE props = ["{0:s}.{1:s}".format(sub_entity,prop.split()[0])NEWLINE for prop in properties]NEWLINE conditions = ["{0:s}.{1:s}".format(sub_entity, filt)NEWLINE for filt in filters]NEWLINE add_ons = "" if aggregators is None else " | "+" | ".join(aggregators)NEWLINENEWLINE data = das_client("{0:s} {1:s}={2:s} system=dbs3 detail=True | grep {3:s}{4:s}"NEWLINE .format(sub_entity, entity, name,NEWLINE ", ".join(props+conditions), add_ons), sub_entity)NEWLINE return [[find_key(f[sub_entity], [prop]) for prop in properties] for f in data]NEWLINENEWLINEdef get_file_info(dataset):NEWLINE result = _get_properties(name=dataset,NEWLINE properties = ["name", "nevents"],NEWLINE filters = ["nevents > 0"],NEWLINE entity = "dataset",NEWLINE sub_entity = "file")NEWLINE return [(dataset, name, nevents) for name, nevents in result]NEWLINENEWLINENEWLINENEWLINEFileInfo = collections.namedtuple("FileInfo", "dataset name nevents runs")NEWLINENEWLINEdef _make_file_info(dataset_name_nevents):NEWLINE return FileInfo(*dataset_name_nevents, runs=get_runs(dataset_name_nevents[1]))NEWLINENEWLINEdef get_chunks(long_list, chunk_size):NEWLINE """NEWLINE Generates list of sub-lists of `long_list` with a maximum size ofNEWLINE `chunk_size`.NEWLINENEWLINE Arguments:NEWLINE - `long_list`: original listNEWLINE - `chunk_size`: maximum size of created sub-listsNEWLINE """NEWLINENEWLINE for i in range(0, len(long_list), chunk_size):NEWLINE yield long_list[i:i+chunk_size]NEWLINENEWLINENEWLINEdef merge_strings(strings):NEWLINE """Merge strings in `strings` into a common string.NEWLINENEWLINE Arguments:NEWLINE - `strings`: list of stringsNEWLINE """NEWLINENEWLINE if type(strings) == str:NEWLINE return stringsNEWLINE elif len(strings) == 0:NEWLINE return ""NEWLINE elif len(strings) == 1:NEWLINE return strings[0]NEWLINE elif len(strings) == 2:NEWLINE first = strings[0]NEWLINE second = strings[1]NEWLINE else:NEWLINE first = merge_strings(strings[:-1])NEWLINE second = strings[-1]NEWLINENEWLINE merged_string = ""NEWLINE blocks = difflib.SequenceMatcher(None, first, second).get_matching_blocks()NEWLINENEWLINE last_i, last_j, last_n = 0, 0, 0NEWLINE for i, j, n in blocks:NEWLINE merged_string += first[last_i+last_n:i]NEWLINE merged_string += second[last_j+last_n:j]NEWLINE merged_string += first[i:i+n]NEWLINE last_i, last_j, last_n = i, j, nNEWLINENEWLINE return str(merged_string)NEWLINENEWLINENEWLINE################################################################################NEWLINEif __name__ == "__main__":NEWLINE try:NEWLINE main()NEWLINE except KeyboardInterrupt:NEWLINE passNEWLINE genero = ''NEWLINEwhile genero != 'F' and genero != 'M':NEWLINE genero = str(input('Gênero [M/F]: ')).upper()NEWLINE if genero == 'F':NEWLINE print('Seu gênero é FEMININO!')NEWLINE if genero == 'M':NEWLINE print('Seu gênero é MASCULINO!')NEWLINEprint('FIM') #!/usr/bin/env pythonNEWLINE# -*- coding: utf-8 -*-NEWLINEimport jsonNEWLINENEWLINEfrom alipay.aop.api.constant.ParamConstants import *NEWLINENEWLINENEWLINEclass FengdieActivityCreatePageData(object):NEWLINENEWLINE def __init__(self):NEWLINE self._name = NoneNEWLINE self._schema_data = NoneNEWLINENEWLINE @propertyNEWLINE def name(self):NEWLINE return self._nameNEWLINENEWLINE @name.setterNEWLINE def name(self, value):NEWLINE self._name = valueNEWLINE @propertyNEWLINE def schema_data(self):NEWLINE return self._schema_dataNEWLINENEWLINE @schema_data.setterNEWLINE def schema_data(self, value):NEWLINE self._schema_data = valueNEWLINENEWLINENEWLINE def to_alipay_dict(self):NEWLINE params = dict()NEWLINE if self.name:NEWLINE if hasattr(self.name, 'to_alipay_dict'):NEWLINE params['name'] = self.name.to_alipay_dict()NEWLINE else:NEWLINE params['name'] = self.nameNEWLINE if self.schema_data:NEWLINE if hasattr(self.schema_data, 'to_alipay_dict'):NEWLINE params['schema_data'] = self.schema_data.to_alipay_dict()NEWLINE else:NEWLINE params['schema_data'] = self.schema_dataNEWLINE return paramsNEWLINENEWLINE @staticmethodNEWLINE def from_alipay_dict(d):NEWLINE if not d:NEWLINE return NoneNEWLINE o = FengdieActivityCreatePageData()NEWLINE if 'name' in d:NEWLINE o.name = d['name']NEWLINE if 'schema_data' in d:NEWLINE o.schema_data = d['schema_data']NEWLINE return oNEWLINENEWLINENEWLINE import datetimeNEWLINEimport mockNEWLINEimport pytestNEWLINEfrom urllib.request import HTTPErrorNEWLINENEWLINEfrom marshmallow.exceptions import ValidationErrorNEWLINEimport responsesNEWLINEfrom werkzeug.security import generate_password_hash, check_password_hashNEWLINENEWLINEfrom database.models import AttestationTypesNEWLINEfrom database.models import AttestationNEWLINEfrom logic.attestation_service import (NEWLINE VerificationService,NEWLINE VerificationServiceResponseNEWLINE)NEWLINEfrom logic.attestation_service import CLAIM_TYPESNEWLINEfrom logic.attestation_service import twitter_access_token_urlNEWLINEfrom logic.attestation_service import twitter_request_token_urlNEWLINEfrom logic.service_utils import (NEWLINE AirbnbVerificationError,NEWLINE EmailVerificationError,NEWLINE FacebookVerificationError,NEWLINE PhoneVerificationError,NEWLINE TwitterVerificationError,NEWLINE)NEWLINEfrom tests.helpers.eth_utils import sample_eth_address, str_ethNEWLINENEWLINENEWLINESIGNATURE_LENGTH = 132NEWLINENEWLINENEWLINE@responses.activateNEWLINEdef test_send_phone_verification_success():NEWLINE responses.add(NEWLINE responses.POST,NEWLINE 'https://api.authy.com/protected/json/phones/verification/start',NEWLINE status=200NEWLINE )NEWLINENEWLINE args = {NEWLINE 'country_calling_code': '1',NEWLINE 'phone': '12341234',NEWLINE 'method': 'sms',NEWLINE 'locale': NoneNEWLINE }NEWLINE response = VerificationService.send_phone_verification(**args)NEWLINE assert isinstance(response, VerificationServiceResponse)NEWLINENEWLINENEWLINE@responses.activateNEWLINEdef test_send_phone_verification_invalid_number():NEWLINE responses.add(NEWLINE responses.POST,NEWLINE 'https://api.authy.com/protected/json/phones/verification/start',NEWLINE json={'error_code': '60033'},NEWLINE status=400NEWLINE )NEWLINENEWLINE args = {NEWLINE 'country_calling_code': '1',NEWLINE 'phone': '1234',NEWLINE 'method': 'sms',NEWLINE 'locale': NoneNEWLINE }NEWLINE with pytest.raises(ValidationError) as validation_err:NEWLINE VerificationService.send_phone_verification(**args)NEWLINENEWLINE assert(validation_err.value.messages[0]) == 'Phone number is invalid.'NEWLINE assert(validation_err.value.field_names[0]) == 'phone'NEWLINENEWLINE # Verify attestation not storedNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 0NEWLINENEWLINENEWLINE@responses.activateNEWLINEdef test_send_phone_verification_cant_sms_landline():NEWLINE responses.add(NEWLINE responses.POST,NEWLINE 'https://api.authy.com/protected/json/phones/verification/start',NEWLINE json={'error_code': '60082'},NEWLINE status=403NEWLINE )NEWLINENEWLINE args = {NEWLINE 'country_calling_code': '1',NEWLINE 'phone': '1234',NEWLINE 'method': 'sms',NEWLINE 'locale': NoneNEWLINE }NEWLINE with pytest.raises(ValidationError) as validation_err:NEWLINE VerificationService.send_phone_verification(**args)NEWLINENEWLINE assert(validation_err.value.messages[0]) == 'Cannot send SMS to landline.'NEWLINE assert(validation_err.value.field_names[0]) == 'phone'NEWLINENEWLINENEWLINE@responses.activateNEWLINEdef test_send_phone_verification_twilio_error():NEWLINE responses.add(NEWLINE responses.POST,NEWLINE 'https://api.authy.com/protected/json/phones/verification/start',NEWLINE json={'error_code': '60060'}, # Account is suspendedNEWLINE status=503NEWLINE )NEWLINENEWLINE args = {NEWLINE 'country_calling_code': '1',NEWLINE 'phone': '1234',NEWLINE 'method': 'sms',NEWLINE 'locale': NoneNEWLINE }NEWLINE with pytest.raises(PhoneVerificationError) as service_err:NEWLINE VerificationService.send_phone_verification(**args)NEWLINENEWLINE assert(str(service_err.value)) == \NEWLINE 'Could not send verification code. Please try again shortly.'NEWLINENEWLINENEWLINE@responses.activateNEWLINEdef test_verify_phone_valid_code(app):NEWLINE responses.add(NEWLINE responses.GET,NEWLINE 'https://api.authy.com/protected/json/phones/verification/check',NEWLINE json={NEWLINE 'message': 'Verification code is correct.',NEWLINE 'success': TrueNEWLINE }NEWLINE )NEWLINENEWLINE args = {NEWLINE 'eth_address': str_eth(sample_eth_address),NEWLINE 'country_calling_code': '1',NEWLINE 'phone': '12341234',NEWLINE 'code': '123456'NEWLINE }NEWLINE with app.test_request_context():NEWLINE response = VerificationService.verify_phone(**args)NEWLINE assert isinstance(response, VerificationServiceResponse)NEWLINENEWLINE assert len(response.data['signature']) == SIGNATURE_LENGTHNEWLINE assert response.data['claim_type'] == CLAIM_TYPES['phone']NEWLINE assert response.data['data'] == 'phone verified'NEWLINENEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 1NEWLINE assert(attestations[0].method) == AttestationTypes.PHONENEWLINE assert(attestations[0].value) == "1 12341234"NEWLINENEWLINENEWLINE@responses.activateNEWLINEdef test_verify_phone_expired_code():NEWLINE responses.add(NEWLINE responses.GET,NEWLINE 'https://api.authy.com/protected/json/phones/verification/check',NEWLINE json={'error_code': '60023'}, # No pending verificationNEWLINE status=404NEWLINE )NEWLINENEWLINE args = {NEWLINE 'eth_address': str_eth(sample_eth_address),NEWLINE 'country_calling_code': '1',NEWLINE 'phone': '12341234',NEWLINE 'code': '123456'NEWLINE }NEWLINE with pytest.raises(ValidationError) as validation_err:NEWLINE VerificationService.verify_phone(**args)NEWLINENEWLINE assert(validation_err.value.messages[0]NEWLINE ) == 'Verification code has expired.'NEWLINE assert(validation_err.value.field_names[0]) == 'code'NEWLINENEWLINENEWLINE@responses.activateNEWLINEdef test_verify_phone_invalid_code():NEWLINE responses.add(NEWLINE responses.GET,NEWLINE 'https://api.authy.com/protected/json/phones/verification/check',NEWLINE json={'error_code': '60022'}, # No pending verificationNEWLINE status=401NEWLINE )NEWLINENEWLINE args = {NEWLINE 'eth_address': str_eth(sample_eth_address),NEWLINE 'country_calling_code': '1',NEWLINE 'phone': '12341234',NEWLINE 'code': 'garbage'NEWLINE }NEWLINE with pytest.raises(ValidationError) as validation_err:NEWLINE VerificationService.verify_phone(**args)NEWLINENEWLINE assert(validation_err.value.messages[0]NEWLINE ) == 'Verification code is incorrect.'NEWLINE assert(validation_err.value.field_names[0]) == 'code'NEWLINENEWLINENEWLINE@mock.patch('logic.attestation_service._send_email_using_sendgrid')NEWLINE@mock.patch('logic.attestation_service.datetime')NEWLINEdef test_send_email_verification(NEWLINE mock_datetime,NEWLINE mock_send_email_using_sendgrid):NEWLINE mock_send_email_using_sendgrid.return_value = TrueNEWLINENEWLINE now = datetime.datetime.utcnow()NEWLINE expire_in = datetime.timedelta(minutes=30)NEWLINE mock_datetime.datetime.utcnow.return_value = nowNEWLINE mock_datetime.timedelta.return_value = expire_inNEWLINENEWLINE email = 'origin@protocol.foo'NEWLINE with mock.patch('logic.attestation_service.session', dict()) as session:NEWLINE response = VerificationService.send_email_verification(email)NEWLINE assert isinstance(response, VerificationServiceResponse)NEWLINE assert 'email_attestation' in sessionNEWLINE assert len(session['email_attestation']['code']) == 6NEWLINE assert session['email_attestation']['expiry'] == now + expire_inNEWLINE assert check_password_hash(NEWLINE session['email_attestation']['email'], emailNEWLINE )NEWLINENEWLINENEWLINE@mock.patch('logic.attestation_service._send_email_using_sendgrid')NEWLINEdef test_send_email_verification_sendgrid_error(NEWLINE mock_send_email_using_sendgrid):NEWLINE mock_send_email_using_sendgrid.side_effect = AttributeErrorNEWLINENEWLINE with mock.patch('logic.attestation_service.session', dict()):NEWLINE with pytest.raises(EmailVerificationError) as service_err:NEWLINE VerificationService.send_email_verification('origin@protocol.foo')NEWLINENEWLINE assert(str(service_err.value)) == \NEWLINE 'Could not send verification code. Please try again shortly.'NEWLINENEWLINENEWLINE@mock.patch('logic.attestation_service.session')NEWLINEdef test_verify_email_valid_code(mock_session, app):NEWLINE session_dict = {NEWLINE 'email_attestation': {NEWLINE 'email': generate_password_hash('origin@protocol.foo'),NEWLINE 'code': '12345',NEWLINE 'expiry': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)NEWLINE }NEWLINE }NEWLINENEWLINE args = {NEWLINE 'eth_address': str_eth(sample_eth_address),NEWLINE 'email': 'origin@protocol.foo',NEWLINE 'code': '12345'NEWLINE }NEWLINENEWLINE with mock.patch('logic.attestation_service.session', session_dict):NEWLINE with app.test_request_context():NEWLINE response = VerificationService.verify_email(**args)NEWLINENEWLINE assert isinstance(response, VerificationServiceResponse)NEWLINENEWLINE assert len(response.data['signature']) == SIGNATURE_LENGTHNEWLINE assert response.data['claim_type'] == CLAIM_TYPES['email']NEWLINE assert response.data['data'] == 'email verified'NEWLINENEWLINE # Verify attestation stored in databaseNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 1NEWLINE assert(attestations[0].method) == AttestationTypes.EMAILNEWLINE assert(attestations[0].value) == "origin@protocol.foo"NEWLINENEWLINENEWLINEdef test_verify_email_expired_code():NEWLINE # Mock a session object with an expiry time in the pastNEWLINE session_dict = {NEWLINE 'email_attestation': {NEWLINE 'email': generate_password_hash('origin@protocol.foo'),NEWLINE 'code': '12345',NEWLINE 'expiry': datetime.datetime.utcnow() - datetime.timedelta(minutes=30)NEWLINE }NEWLINE }NEWLINENEWLINE args = {NEWLINE 'email': 'origin@protocol.foo',NEWLINE 'code': '12345',NEWLINE 'eth_address': str_eth(sample_eth_address)NEWLINE }NEWLINENEWLINE with mock.patch('logic.attestation_service.session', session_dict):NEWLINE with pytest.raises(ValidationError) as validation_err:NEWLINE VerificationService.verify_email(**args)NEWLINENEWLINE assert(validation_err.value.messages[0]NEWLINE ) == 'Verification code has expired.'NEWLINE assert(validation_err.value.field_names[0]) == 'code'NEWLINENEWLINE # Verify attestation not storedNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 0NEWLINENEWLINENEWLINE@mock.patch('logic.attestation_service.session')NEWLINEdef test_verify_email_invalid_code(mock_session):NEWLINE session_dict = {NEWLINE 'email_attestation': {NEWLINE 'email': generate_password_hash('origin@protocol.foo'),NEWLINE 'code': '12345',NEWLINE 'expiry': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)NEWLINE }NEWLINE }NEWLINENEWLINE args = {NEWLINE 'eth_address': str_eth(sample_eth_address),NEWLINE 'email': 'origin@protocol.foo',NEWLINE 'code': '54321'NEWLINE }NEWLINENEWLINE with mock.patch('logic.attestation_service.session', session_dict):NEWLINE with pytest.raises(ValidationError) as validation_err:NEWLINE VerificationService.verify_email(**args)NEWLINENEWLINE assert(validation_err.value.messages[0]NEWLINE ) == 'Verification code is incorrect.'NEWLINE assert(validation_err.value.field_names[0]) == 'code'NEWLINENEWLINE # Verify attestation not storedNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 0NEWLINENEWLINENEWLINEdef test_verify_email_no_verification_sent():NEWLINE args = {NEWLINE 'eth_address': str_eth(sample_eth_address),NEWLINE 'email': 'origin@protocol.foo',NEWLINE 'code': '54321'NEWLINE }NEWLINENEWLINE with mock.patch('logic.attestation_service.session', dict()):NEWLINE with pytest.raises(EmailVerificationError) as verification_err:NEWLINE VerificationService.verify_email(**args)NEWLINENEWLINE assert(verification_err.value.message) == \NEWLINE 'No verification code was found.'NEWLINENEWLINE # Verify attestation not storedNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 0NEWLINENEWLINENEWLINEdef test_verify_email_invalid_email():NEWLINE session_dict = {NEWLINE 'email_attestation': {NEWLINE 'email': generate_password_hash('not_origin@protocol.foo'),NEWLINE 'code': '12345',NEWLINE 'expiry': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)NEWLINE }NEWLINE }NEWLINENEWLINE args = {NEWLINE 'eth_address': str_eth(sample_eth_address),NEWLINE 'email': 'origin@protocol.foo',NEWLINE 'code': '54321'NEWLINE }NEWLINENEWLINE with mock.patch('logic.attestation_service.session', session_dict):NEWLINE with pytest.raises(EmailVerificationError) as verification_err:NEWLINE VerificationService.verify_email(**args)NEWLINENEWLINE assert(verification_err.value.message) == \NEWLINE 'No verification code was found for that email.'NEWLINENEWLINE # Verify attestation not storedNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 0NEWLINENEWLINENEWLINEdef test_facebook_auth_url():NEWLINE resp = VerificationService.facebook_auth_url()NEWLINE resp_data = resp.dataNEWLINE assert resp_data['url'] == (NEWLINE 'https://www.facebook.com/v2.12/dialog/oauth?client_id'NEWLINE '=facebook-client-id&redirect_uri'NEWLINE '=https://testhost.com/redirects/facebook/'NEWLINE )NEWLINENEWLINENEWLINE@responses.activateNEWLINEdef test_verify_facebook_valid_code(app):NEWLINE auth_url = 'https://graph.facebook.com/v2.12/oauth/access_token' + \NEWLINE '?client_id=facebook-client-id' + \NEWLINE '&client_secret=facebook-client-secret' + \NEWLINE '&redirect_uri=https%3A%2F%2Ftesthost.com%2Fredirects%2Ffacebook%2F' + \NEWLINE '&code=abcde12345'NEWLINE verify_url = 'https://graph.facebook.com/me?access_token=12345'NEWLINENEWLINE responses.add(NEWLINE responses.GET,NEWLINE auth_url,NEWLINE json={'access_token': 12345},NEWLINE status=200NEWLINE )NEWLINENEWLINE responses.add(NEWLINE responses.GET,NEWLINE verify_url,NEWLINE json={'name': 'Origin Protocol'},NEWLINE status=200NEWLINE )NEWLINENEWLINE args = {NEWLINE 'eth_address': '0x112234455C3a32FD11230C42E7Bccd4A84e02010',NEWLINE 'code': 'abcde12345'NEWLINE }NEWLINENEWLINE with app.test_request_context():NEWLINE verification_response = VerificationService.verify_facebook(**args)NEWLINE assert isinstance(verification_response, VerificationServiceResponse)NEWLINE assert len(verification_response.data['signature']) == SIGNATURE_LENGTHNEWLINE assert verification_response.data['claim_type'] == CLAIM_TYPES['facebook']NEWLINE assert verification_response.data['data'] == 'facebook verified'NEWLINENEWLINE # Verify attestation stored in databaseNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 1NEWLINE assert(attestations[0].method) == AttestationTypes.FACEBOOKNEWLINE assert(attestations[0].value) == 'Origin Protocol'NEWLINENEWLINENEWLINE@responses.activateNEWLINEdef test_verify_facebook_invalid_code():NEWLINE auth_url = 'https://graph.facebook.com/v2.12/oauth/access_token' + \NEWLINE '?client_id=facebook-client-id' + \NEWLINE '&client_secret=facebook-client-secret' + \NEWLINE '&redirect_uri=https%3A%2F%2Ftesthost.com%2Fredirects%2Ffacebook%2F' + \NEWLINE '&code=bananas'NEWLINENEWLINE responses.add(NEWLINE responses.GET,NEWLINE auth_url,NEWLINE json={'error': 'invalid'},NEWLINE status=403NEWLINE )NEWLINENEWLINE args = {NEWLINE 'eth_address': '0x112234455C3a32FD11230C42E7Bccd4A84e02010',NEWLINE 'code': 'bananas'NEWLINE }NEWLINENEWLINE with pytest.raises(FacebookVerificationError) as service_err:NEWLINE VerificationService.verify_facebook(**args)NEWLINENEWLINE assert str(service_err.value) == 'The code you provided is invalid.'NEWLINENEWLINE # Verify attestation not storedNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 0NEWLINENEWLINENEWLINE@responses.activateNEWLINEdef test_twitter_auth_url(app):NEWLINE response_content = b'oauth_token=peaches&oauth_token_secret=pears'NEWLINENEWLINE responses.add(NEWLINE responses.POST,NEWLINE twitter_request_token_url,NEWLINE body=response_content,NEWLINE status=200NEWLINE )NEWLINENEWLINE with app.test_request_context():NEWLINE verification_response = VerificationService.twitter_auth_url()NEWLINE assert isinstance(verification_response, VerificationServiceResponse)NEWLINE assert verification_response.data['url'] == (NEWLINE 'https://api.twitter.com/oauth/authenticate?oauth_token=peaches'NEWLINE )NEWLINENEWLINENEWLINE@mock.patch('logic.attestation_service.session')NEWLINE@responses.activateNEWLINEdef test_verify_twitter_valid_code(mock_session, app):NEWLINE responses.add(NEWLINE responses.POST,NEWLINE twitter_access_token_url,NEWLINE body=b'screen_name=originprotocol',NEWLINE status=200NEWLINE )NEWLINENEWLINE args = {NEWLINE 'eth_address': '0x112234455C3a32FD11230C42E7Bccd4A84e02010',NEWLINE 'oauth_verifier': 'blueberries'NEWLINE }NEWLINENEWLINE session_dict = {NEWLINE 'request_token': {NEWLINE 'oauth_token': '1234',NEWLINE 'oauth_token_secret': '5678'NEWLINE }NEWLINE }NEWLINENEWLINE with mock.patch('logic.attestation_service.session', session_dict):NEWLINE with app.test_request_context():NEWLINE verification_response = VerificationService.verify_twitter(**args)NEWLINENEWLINE assert isinstance(verification_response, VerificationServiceResponse)NEWLINENEWLINE assert len(verification_response.data['signature']) == SIGNATURE_LENGTHNEWLINE assert verification_response.data['claim_type'] == CLAIM_TYPES['twitter']NEWLINE assert verification_response.data['data'] == 'twitter verified'NEWLINENEWLINE # Verify attestation stored in databaseNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 1NEWLINE assert(attestations[0].method) == AttestationTypes.TWITTERNEWLINE assert(attestations[0].value) == 'originprotocol'NEWLINENEWLINENEWLINE@mock.patch('logic.attestation_service.session')NEWLINE@responses.activateNEWLINEdef test_verify_twitter_invalid_verifier(mock_session, app):NEWLINE responses.add(NEWLINE responses.POST,NEWLINE twitter_access_token_url,NEWLINE status=401NEWLINE )NEWLINENEWLINE args = {NEWLINE 'eth_address': '0x112234455C3a32FD11230C42E7Bccd4A84e02010',NEWLINE 'oauth_verifier': 'pineapples'NEWLINE }NEWLINENEWLINE session_dict = {NEWLINE 'request_token': {NEWLINE 'oauth_token': '1234',NEWLINE 'oauth_token_secret': '5678'NEWLINE }NEWLINE }NEWLINENEWLINE with mock.patch('logic.attestation_service.session', session_dict):NEWLINE with pytest.raises(TwitterVerificationError) as service_err:NEWLINE with app.test_request_context():NEWLINE VerificationService.verify_twitter(**args)NEWLINENEWLINE assert str(service_err.value) == 'The verifier you provided is invalid.'NEWLINENEWLINE # Verify attestation not storedNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 0NEWLINENEWLINENEWLINE@mock.patch('logic.attestation_service.requests')NEWLINE@mock.patch('logic.attestation_service.session')NEWLINEdef test_verify_twitter_invalid_session(mock_session, mock_requests):NEWLINE args = {NEWLINE 'eth_address': '0x112234455C3a32FD11230C42E7Bccd4A84e02010',NEWLINE 'oauth_verifier': 'pineapples'NEWLINE }NEWLINENEWLINE with pytest.raises(TwitterVerificationError) as service_err:NEWLINE VerificationService.verify_twitter(**args)NEWLINENEWLINE assert str(service_err.value) == 'Session not found.'NEWLINENEWLINE # Verify attestation not storedNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 0NEWLINENEWLINENEWLINEdef test_generate_airbnb_verification_code():NEWLINE resp = VerificationService.generate_airbnb_verification_code(NEWLINE '0x112234455C3a32FD11230C42E7Bccd4A84e02010',NEWLINE '123456'NEWLINE )NEWLINE assert isinstance(resp, VerificationServiceResponse)NEWLINENEWLINE assert resp.data['code'] == "art brick aspect accident brass betray antenna"NEWLINENEWLINENEWLINEdef test_generate_airbnb_verification_code_incorrect_user_id_format():NEWLINE with pytest.raises(ValidationError) as validation_error:NEWLINE VerificationService.generate_airbnb_verification_code(NEWLINE '0x112234455C3a32FD11230C42E7Bccd4A84e02010',NEWLINE '12a34'NEWLINE )NEWLINENEWLINE assert str(validation_error.value) == 'AirbnbUserId should be a number.'NEWLINENEWLINENEWLINE@mock.patch('logic.attestation_service.urlopen')NEWLINEdef test_verify_airbnb(mock_urllib_request, app):NEWLINE mock_urllib_request.return_value.read.return_value = """NEWLINE
NEWLINE Airbnb profile descriptionNEWLINE Origin verification code: art brick aspect accident brass betray antennaNEWLINE some more profile descriptionNEWLINE
""".encode('utf-8')NEWLINE airbnbUserId = "123456"NEWLINENEWLINE with app.test_request_context():NEWLINE verification_response = VerificationService.verify_airbnb(NEWLINE '0x112234455C3a32FD11230C42E7Bccd4A84e02010',NEWLINE airbnbUserIdNEWLINE )NEWLINE assert isinstance(verification_response, VerificationServiceResponse)NEWLINENEWLINE assert len(verification_response.data['signature']) == SIGNATURE_LENGTHNEWLINE assert verification_response.data['claim_type'] == CLAIM_TYPES['airbnb']NEWLINE assert verification_response.data['data'] == 'airbnbUserId:' + airbnbUserIdNEWLINENEWLINE # Verify attestation stored in databaseNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 1NEWLINE assert(attestations[0].method) == AttestationTypes.AIRBNBNEWLINE assert(attestations[0].value) == "123456"NEWLINENEWLINENEWLINE@mock.patch('logic.attestation_service.urlopen')NEWLINEdef test_verify_airbnb_verification_code_missing(mock_urllib_request):NEWLINE mock_urllib_request.return_value.read.return_value = """NEWLINE
NEWLINE Airbnb profile description some more profile descriptionNEWLINE
""".encode('utf-8')NEWLINENEWLINE with pytest.raises(AirbnbVerificationError) as service_err:NEWLINE VerificationService.verify_airbnb(NEWLINE '0x112234455C3a32FD11230C42E7Bccd4A84e02010',NEWLINE "123456"NEWLINE )NEWLINENEWLINE assert str(service_err.value) == "Origin verification code: art brick aspect " \NEWLINE + "accident brass betray antenna has not been found in user's Airbnb profile."NEWLINENEWLINE # Verify attestation not storedNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 0NEWLINENEWLINENEWLINE@mock.patch('logic.attestation_service.urlopen')NEWLINEdef test_verify_airbnb_verification_code_incorrect(mock_urllib_request):NEWLINE mock_urllib_request.return_value.read.return_value = """NEWLINE
NEWLINE Airbnb profile descriptionNEWLINE Origin verification code: art brick aspect pimpmobileNEWLINE some more profile descriptionNEWLINE
""".encode('utf-8')NEWLINENEWLINE with pytest.raises(AirbnbVerificationError) as service_err:NEWLINE VerificationService.verify_airbnb(NEWLINE '0x112234455C3a32FD11230C42E7Bccd4A84e02010',NEWLINE "123456"NEWLINE )NEWLINENEWLINE assert str(service_err.value) == "Origin verification code: art brick aspect " \NEWLINE + "accident brass betray antenna has not been found in user's Airbnb profile."NEWLINENEWLINE # Verify attestation not storedNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 0NEWLINENEWLINENEWLINE@mock.patch('logic.attestation_service.urlopen')NEWLINEdef test_verify_airbnb_verification_code_incorrect_user_id_format(NEWLINE mock_urllib_request):NEWLINE mock_urllib_request.return_value.read.return_value = """NEWLINE
NEWLINE Airbnb profile descriptionNEWLINE Origin verification code: art brick aspect accident brass betray antennaNEWLINE some more profile descriptionNEWLINE
""".encode('utf-8')NEWLINENEWLINE with pytest.raises(ValidationError) as validation_error:NEWLINE VerificationService.verify_airbnb(NEWLINE '0x112234455C3a32FD11230C42E7Bccd4A84e02010',NEWLINE "12a34"NEWLINE )NEWLINENEWLINE assert str(validation_error.value) == 'AirbnbUserId should be a number.'NEWLINENEWLINE # Verify attestation not storedNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 0NEWLINENEWLINENEWLINE@mock.patch('logic.attestation_service.urlopen', side_effect=HTTPError(NEWLINE 'https://www.airbnb.com/users/show/99999999999999999',NEWLINE 404,NEWLINE "User not found",NEWLINE {},NEWLINE {}NEWLINE))NEWLINEdef test_verify_airbnb_verification_code_non_existing_user(NEWLINE mock_urllib_request):NEWLINE with pytest.raises(AirbnbVerificationError) as service_err:NEWLINE VerificationService.verify_airbnb(NEWLINE '0x112234455C3a32FD11230C42E7Bccd4A84e02010',NEWLINE "99999999999999999"NEWLINE )NEWLINENEWLINE assert str(NEWLINE service_err.value) == 'Airbnb user id: 99999999999999999 not found.'NEWLINENEWLINE # Verify attestation not storedNEWLINE attestations = Attestation.query.all()NEWLINE assert(len(attestations)) == 0NEWLINENEWLINENEWLINE@mock.patch('logic.attestation_service.urlopen', side_effect=HTTPError(NEWLINE 'https://www.airbnb.com/users/show/123',NEWLINE 500,NEWLINE "Internal server error",NEWLINE {},NEWLINE {}NEWLINE))NEWLINEdef test_verify_airbnb_verification_code_internal_server_error(NEWLINE mock_urllib_request):NEWLINE with pytest.raises(AirbnbVerificationError) as service_err:NEWLINE VerificationService.verify_airbnb(NEWLINE '0x112234455C3a32FD11230C42E7Bccd4A84e02010',NEWLINE "123"NEWLINE )NEWLINENEWLINE assert str(service_err.value) == "Can not fetch user's Airbnb profile."NEWLINE import sysNEWLINEimport importlib.resourcesNEWLINEimport pickleNEWLINEimport argparseNEWLINEimport reNEWLINEfrom contextlib import contextmanagerNEWLINEfrom collections import CounterNEWLINEfrom apycula import chipdbNEWLINENEWLINEclass Bba(object):NEWLINENEWLINE def __init__(self, file):NEWLINE self.file = fileNEWLINE self.block_idx = Counter()NEWLINENEWLINE def __getattr__(self, attr):NEWLINE def write_value(val):NEWLINE self.file.write(f"{attr} {val}\n")NEWLINE return write_valueNEWLINENEWLINE def str(self, val, sep="|"):NEWLINE self.file.write(f"str {sep}{val}{sep}\n")NEWLINENEWLINE @contextmanagerNEWLINE def block(self, prefix="block"):NEWLINE idx = self.block_idx[prefix]NEWLINE self.block_idx.update([prefix])NEWLINE name = f"{prefix}_{idx}"NEWLINE self.push(name)NEWLINE self.label(name)NEWLINE try:NEWLINE yield nameNEWLINE finally:NEWLINE self.pop(name)NEWLINENEWLINEconstids = ['']NEWLINEids = []NEWLINEdef id_string(s):NEWLINE try:NEWLINE return constids.index(s)NEWLINE except ValueError:NEWLINE passNEWLINE try:NEWLINE return len(constids)+ids.index(s)NEWLINE except ValueError:NEWLINE ids.append(s)NEWLINE return len(constids)+len(ids)-1NEWLINENEWLINEdef id_strings(b):NEWLINE with b.block('idstrings') as blk:NEWLINE for s in ids:NEWLINE b.str(s)NEWLINE b.u16(len(constids))NEWLINE b.u16(len(ids))NEWLINE b.ref(blk)NEWLINENEWLINEdef write_pips(b, pips):NEWLINE num = 0NEWLINE with b.block("pips") as blk:NEWLINE for dest, srcs in pips.items():NEWLINE for src in srcs:NEWLINE num += 1NEWLINE b.u16(id_string(dest))NEWLINE b.u16(id_string(src))NEWLINE b.u32(num)NEWLINE b.ref(blk)NEWLINENEWLINEdef write_bels(b, bels):NEWLINE with b.block("bels") as blk:NEWLINE for typ, bel in bels.items():NEWLINE if bel.simplified_iob:NEWLINE b.u16(id_string(f'{typ}S'))NEWLINE else:NEWLINE b.u16(id_string(typ))NEWLINE with b.block("portmap") as port_blk:NEWLINE for dest, src in bel.portmap.items():NEWLINE b.u16(id_string(dest))NEWLINE b.u16(id_string(src))NEWLINE b.u16(len(bel.portmap))NEWLINE b.ref(port_blk)NEWLINENEWLINENEWLINE b.u32(len(bels))NEWLINE b.ref(blk)NEWLINENEWLINEdef write_aliases(b, aliases):NEWLINE with b.block('aliases') as blk:NEWLINE for dest, src in aliases.items():NEWLINE b.u16(id_string(dest))NEWLINE b.u16(id_string(src))NEWLINE b.u32(len(aliases))NEWLINE b.ref(blk)NEWLINENEWLINEdef write_tile(b, tile):NEWLINE with b.block('tile') as blk:NEWLINE write_bels(b, tile.bels)NEWLINE write_pips(b, tile.pips)NEWLINE write_pips(b, tile.clock_pips)NEWLINE write_aliases(b, tile.aliases)NEWLINE return blkNEWLINENEWLINEdef write_grid(b, grid):NEWLINE tiles = {}NEWLINE with b.block('grid') as grid_block:NEWLINE for row in grid:NEWLINE for tile in row:NEWLINE if id(tile) in tiles:NEWLINE b.ref(tiles[id(tile)])NEWLINE else:NEWLINE blk = write_tile(b, tile)NEWLINE tiles[id(tile)] = blkNEWLINE b.ref(blk)NEWLINE b.ref(grid_block)NEWLINENEWLINENEWLINEdef write_global_aliases(b, db):NEWLINE with b.block('aliases') as blk:NEWLINE aliases = sorted(db.aliases.items(),NEWLINE key=lambda i: (i[0][0], i[0][1], id_string(i[0][2])))NEWLINE for (drow, dcol, dest), (srow, scol, src) in aliases:NEWLINE b.u16(drow)NEWLINE b.u16(dcol)NEWLINE b.u16(id_string(dest))NEWLINE b.u16(srow)NEWLINE b.u16(scol)NEWLINE b.u16(id_string(src))NEWLINE b.u32(len(db.aliases))NEWLINE b.ref(blk)NEWLINENEWLINEdef write_timing(b, timing):NEWLINE with b.block('timing') as blk:NEWLINE for speed, groups in timing.items():NEWLINE b.u32(id_string(speed))NEWLINE with b.block('timing_group') as tg:NEWLINE for group, types in groups.items():NEWLINE b.u32(id_string(group))NEWLINE with b.block('timing_types') as tt:NEWLINE for name, items in types.items():NEWLINE try:NEWLINE items[0] # QUACKING THE DUCKNEWLINE b.u32(id_string(name))NEWLINE for item in items:NEWLINE b.u32(int(item*1000))NEWLINE except TypeError:NEWLINE passNEWLINE b.u32(len(types))NEWLINE b.ref(tt)NEWLINE b.u32(len(groups))NEWLINE b.ref(tg)NEWLINE b.u32(len(timing))NEWLINE b.ref(blk)NEWLINENEWLINEdef write_partnumber_packages(b, db):NEWLINE with b.block("partnumber_packages") as blk:NEWLINE for partnumber, pkg_rec in db.packages.items():NEWLINE pkg, device, speed = pkg_recNEWLINE b.u32(id_string(partnumber))NEWLINE b.u32(id_string(pkg))NEWLINE b.u32(id_string(device))NEWLINE b.u32(id_string(speed))NEWLINE b.u32(len(db.packages))NEWLINE b.ref(blk)NEWLINENEWLINEpin_re = re.compile(r"IO([TBRL])(\d+)([A-Z])")NEWLINEdef iob2bel(db, name):NEWLINE banks = {'T': [(1, n) for n in range(1, db.cols)],NEWLINE 'B': [(db.rows, n) for n in range(1, db.cols)],NEWLINE 'L': [(n, 1) for n in range(1, db.rows)],NEWLINE 'R': [(n, db.cols) for n in range(1, db.rows)]}NEWLINE side, num, pin = pin_re.match(name).groups()NEWLINE row, col = banks[side][int(num)-1]NEWLINE return f"R{row}C{col}_IOB{pin}"NEWLINENEWLINEdef write_pinout(b, db):NEWLINE with b.block("variants") as blk:NEWLINE for device, pkgs in db.pinout.items():NEWLINE b.u32(id_string(device))NEWLINE with b.block("packages") as pkgblk:NEWLINE for pkg, pins in pkgs.items():NEWLINE b.u32(id_string(pkg))NEWLINE with b.block("pins") as pinblk:NEWLINE for num, loc in pins.items():NEWLINE b.u16(id_string(num))NEWLINE b.u16(id_string(iob2bel(db, loc)))NEWLINE b.u32(len(pins))NEWLINE b.ref(pinblk)NEWLINE b.u32(len(pkgs))NEWLINE b.ref(pkgblk)NEWLINE b.u32(len(db.pinout))NEWLINE b.ref(blk)NEWLINENEWLINEdef write_chipdb(db, f, device):NEWLINE cdev=device.replace('-', '_')NEWLINE b = Bba(f)NEWLINE b.pre('#include "nextpnr.h"')NEWLINE b.pre('#include "embed.h"')NEWLINE b.pre('NEXTPNR_NAMESPACE_BEGIN')NEWLINE with b.block(f'chipdb_{cdev}') as blk:NEWLINE b.str(device)NEWLINE b.u32(1) # versionNEWLINE b.u16(db.rows)NEWLINE b.u16(db.cols)NEWLINE write_grid(b, db.grid)NEWLINE write_global_aliases(b, db)NEWLINE write_timing(b, db.timing)NEWLINE write_partnumber_packages(b, db)NEWLINE write_pinout(b, db)NEWLINE id_strings(b)NEWLINE b.post(f'EmbeddedFile chipdb_file_{cdev}("gowin/chipdb-{device}.bin", {blk});')NEWLINE b.post('NEXTPNR_NAMESPACE_END')NEWLINENEWLINEdef read_constids(f):NEWLINE xre = re.compile(r"X\((.*)\)")NEWLINE for line in f:NEWLINE m = xre.match(line)NEWLINE if m:NEWLINE constids.append(m.group(1))NEWLINE return idsNEWLINENEWLINENEWLINEdef main():NEWLINE parser = argparse.ArgumentParser(description='Make Gowin BBA')NEWLINE parser.add_argument('-d', '--device', required=True)NEWLINE parser.add_argument('-i', '--constids', type=argparse.FileType('r'), default=sys.stdin)NEWLINE parser.add_argument('-o', '--output', type=argparse.FileType('w'), default=sys.stdout)NEWLINENEWLINE args = parser.parse_args()NEWLINE read_constids(args.constids)NEWLINE with importlib.resources.open_binary("apycula", f"{args.device}.pickle") as f:NEWLINE db = pickle.load(f)NEWLINE write_chipdb(db, args.output, args.device)NEWLINENEWLINEif __name__ == "__main__":NEWLINE main()NEWLINE #!/usr/bin/env python3NEWLINE# coding=utf-8NEWLINENEWLINEimport numpy as npNEWLINEimport pandas as pdNEWLINENEWLINENEWLINEdef show_predict_probability(frame):NEWLINE x1 = frame['x1']NEWLINE x2 = frame['x2']NEWLINE probability = frame['probabilities']NEWLINE class1_x = [x1[i] for i, x in enumerate(probability) if x >= 0.5]NEWLINE class1_y = [x2[i] for i, x in enumerate(probability) if x >= 0.5]NEWLINE class2_x = [x1[i] for i, x in enumerate(probability) if x < 0.5]NEWLINE class2_y = [x2[i] for i, x in enumerate(probability) if x < 0.5]NEWLINE print('class1_x = \n %s' % class1_x)NEWLINE print('class1_y = \n %s' % class1_y)NEWLINE print('class2_x = \n %s' % class2_x)NEWLINE print('class2_y = \n %s' % class2_y)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE frame = pd.DataFrame()NEWLINE n = 5NEWLINE npx1 = np.linspace(0, 9, n)NEWLINE npx2 = np.linspace(100, 109, n)NEWLINE X1, X2 = np.meshgrid(npx1, npx2)NEWLINE frame['x1'] = np.reshape(X1, n * n)NEWLINE frame['x2'] = np.reshape(X2, n * n)NEWLINE frame['probabilities'] = np.random.rand(n * n)NEWLINE print(frame)NEWLINE show_predict_probability(frame)NEWLINE NEWLINEimport sys, jsonNEWLINEimport cv2NEWLINEimport torchNEWLINENEWLINEPATH_EL = "../entity-linking/"NEWLINEsys.path.insert(0, PATH_EL)NEWLINENEWLINEimport clickNEWLINEimport tqdmNEWLINEfrom pycorenlp import StanfordCoreNLPNEWLINENEWLINEfrom entitylinking import core as ELNEWLINEfrom entitylinking.core.sentence import SentenceEncoderNEWLINENEWLINENEWLINEcorenlp = StanfordCoreNLP('http://semanticparsing:9000')NEWLINEcorenlp_properties = {NEWLINE 'annotators': 'tokenize, pos, ner',NEWLINE 'outputFormat': 'json'NEWLINE}NEWLINENEWLINEEL.candidate_retrieval.entity_linking_p['max.match.diff'] = 0NEWLINENEWLINEEL.mention_extraction.np_parser = EL.mention_extraction.NgramNpParser(NEWLINE exclude_pos={".", "ORDINAL", "TIME", "PERCENT", "NUMBER"},NEWLINE exclude_if_first={"WDT", "WP", "WP$", "WRB", "VBZ", "VB", "VBP"},NEWLINE exclude_prefix={"IN", "DT", "CC", "POS"},NEWLINE exclude_suffix={"IN", "DT", "CC", "JJ", "RB", "JJR", "JJS", "RBR", "RBS"},NEWLINE exclude_alone={"IN", "DT", "PDT", "POS", "PRP", "PRP$", "CC", "TO",NEWLINE "VBZ", "VBD", "VBP", "VB", "VBG", "VBN",NEWLINE "JJ", "RB", "JJR", "JJS", "RBR", "RBS",NEWLINE "MD", "WDT", "WP", "WP$", "WRB"NEWLINE })NEWLINENEWLINENEWLINE@click.command()NEWLINE@click.argument('path_to_file')NEWLINE@click.argument('output_file')NEWLINEdef apply(path_to_file, output_file):NEWLINENEWLINE entitylinker = EL.MLLinker(path_to_model="../entity-linking/trainedmodels/VectorModel_137.torchweights",NEWLINE confidence=0.01,NEWLINE num_candidates=3,NEWLINE max_mention_len=2)NEWLINENEWLINE with open(path_to_file) as f:NEWLINE input_data = [l.strip().split(",") for l in f.readlines()][1:]NEWLINENEWLINE output_data = {}NEWLINE for parts in tqdm.tqdm(input_data):NEWLINE output_per_story = []NEWLINE for i in range(1, 7):NEWLINE s = parts[i]NEWLINE sent = entitylinker.link_entities_in_sentence_obj(EL.sentence.Sentence(input_text=s))NEWLINE sent.entities = [{k: e[k] for k in {'type', 'linkings', 'token_ids', 'poss', 'tokens', 'drop_score'}}NEWLINE for e in sent.entities if len(e['linkings']) > 0]NEWLINE for e in sent.entities:NEWLINE e['linkings'] = [(l.get('kbID'), l.get('label')) for l in e['linkings']]NEWLINE output_per_story.append(sent)NEWLINE output_data[parts[0]] = output_per_storyNEWLINE with open(output_file, "w") as out:NEWLINE json.dump(output_data, out, sort_keys=True, indent=4, cls=SentenceEncoder)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE apply()NEWLINE # coding: UTF-8NEWLINENEWLINEfrom __future__ import print_functionNEWLINEfrom configparser import ConfigParserNEWLINEfrom contextlib import contextmanagerNEWLINEimport osNEWLINEimport datetimeNEWLINEfrom os.path import basename, exists, dirname, join, expanduserNEWLINEimport sysNEWLINEimport subprocessNEWLINEimport timeNEWLINEimport loggingNEWLINEimport logging.configNEWLINEimport clickNEWLINEimport termcolorNEWLINEimport colorlogNEWLINEimport MySQLdbNEWLINENEWLINElogger = logging.getLogger('.utils')NEWLINEDEBUG_ENABLED = os.environ.get('SEAFILE_DOCKER_VERBOSE', '').lower() in ('true', '1', 'yes')NEWLINENEWLINENEWLINEdef eprint(*a, **kw):NEWLINE kw['file'] = sys.stderrNEWLINE print(*a, **kw)NEWLINENEWLINEdef identity(msg, *a, **kw):NEWLINE return msgNEWLINENEWLINEcolored = identity if not os.isatty(sys.stdin.fileno()) else termcolor.coloredNEWLINEred = lambda s: colored(s, 'red')NEWLINEgreen = lambda s: colored(s, 'green')NEWLINENEWLINEdef underlined(msg):NEWLINE return '\x1b[4m{}\x1b[0m'.format(msg)NEWLINENEWLINEdef sudo(*a, **kw):NEWLINE call('sudo ' + a[0], *a[1:], **kw)NEWLINENEWLINEdef _find_flag(args, *opts, **kw):NEWLINE is_flag = kw.get('is_flag', False)NEWLINE if is_flag:NEWLINE return any([opt in args for opt in opts])NEWLINE else:NEWLINE for opt in opts:NEWLINE try:NEWLINE return args[args.index(opt) + 1]NEWLINE except ValueError:NEWLINE passNEWLINENEWLINEdef call(*a, **kw):NEWLINE dry_run = kw.pop('dry_run', False)NEWLINE quiet = kw.pop('quiet', DEBUG_ENABLED)NEWLINE cwd = kw.get('cwd', os.getcwd())NEWLINE check_call = kw.pop('check_call', True)NEWLINE reduct_args = kw.pop('reduct_args', [])NEWLINE if not quiet:NEWLINE toprint = a[0]NEWLINE args = [x.strip('"') for x in a[0].split() if '=' not in x]NEWLINE for arg in reduct_args:NEWLINE value = _find_flag(args, arg)NEWLINE toprint = toprint.replace(value, '{}**reducted**'.format(value[:3]))NEWLINE logdbg('calling: ' + green(toprint))NEWLINE logdbg('cwd: ' + green(cwd))NEWLINE kw.setdefault('shell', True)NEWLINE if not dry_run:NEWLINE if check_call:NEWLINE return subprocess.check_call(*a, **kw)NEWLINE else:NEWLINE return subprocess.Popen(*a, **kw).wait()NEWLINENEWLINE@contextmanagerNEWLINEdef cd(path):NEWLINE path = expanduser(path)NEWLINE olddir = os.getcwd()NEWLINE os.chdir(path)NEWLINE try:NEWLINE yieldNEWLINE finally:NEWLINE os.chdir(olddir)NEWLINENEWLINEdef must_makedir(p):NEWLINE p = expanduser(p)NEWLINE if not exists(p):NEWLINE logger.info('created folder %s', p)NEWLINE os.makedirs(p)NEWLINE else:NEWLINE logger.debug('folder %s already exists', p)NEWLINENEWLINEdef setup_colorlog():NEWLINE logging.config.dictConfig({NEWLINE 'version': 1,NEWLINE 'disable_existing_loggers': False,NEWLINE 'formatters': {NEWLINE 'standard': {NEWLINE 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'NEWLINE },NEWLINE 'colored': {NEWLINE '()': 'colorlog.ColoredFormatter',NEWLINE 'format': "%(log_color)s[%(asctime)s]%(reset)s %(blue)s%(message)s",NEWLINE 'datefmt': '%m/%d/%Y %H:%M:%S',NEWLINE },NEWLINE },NEWLINE 'handlers': {NEWLINE 'default': {NEWLINE 'level': 'INFO',NEWLINE 'formatter': 'colored',NEWLINE 'class': 'logging.StreamHandler',NEWLINE },NEWLINE },NEWLINE 'loggers': {NEWLINE '': {NEWLINE 'handlers': ['default'],NEWLINE 'level': 'INFO',NEWLINE 'propagate': TrueNEWLINE },NEWLINE 'django.request': {NEWLINE 'handlers': ['default'],NEWLINE 'level': 'WARN',NEWLINE 'propagate': FalseNEWLINE },NEWLINE }NEWLINE })NEWLINENEWLINE logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(NEWLINE logging.WARNING)NEWLINENEWLINENEWLINEdef setup_logging(level=logging.INFO):NEWLINE kw = {NEWLINE 'format': '[%(asctime)s][%(module)s]: %(message)s',NEWLINE 'datefmt': '%m/%d/%Y %H:%M:%S',NEWLINE 'level': level,NEWLINE 'stream': sys.stdoutNEWLINE }NEWLINENEWLINE logging.basicConfig(**kw)NEWLINE logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(NEWLINE logging.WARNING)NEWLINENEWLINEdef get_process_cmd(pid, env=False):NEWLINE env = 'e' if env else ''NEWLINE try:NEWLINE return subprocess.check_output('ps {} -o command {}'.format(env, pid),NEWLINE shell=True).strip().splitlines()[1]NEWLINE # except Exception, e:NEWLINE # print(e)NEWLINE except:NEWLINE return NoneNEWLINENEWLINEdef get_match_pids(pattern):NEWLINE pgrep_output = subprocess.check_output(NEWLINE 'pgrep -f "{}" || true'.format(pattern),NEWLINE shell=True).strip()NEWLINE return [int(pid) for pid in pgrep_output.splitlines()]NEWLINENEWLINEdef ask_for_confirm(msg):NEWLINE confirm = click.prompt(msg, default='Y')NEWLINE return confirm.lower() in ('y', 'yes')NEWLINENEWLINEdef confirm_command_to_run(cmd):NEWLINE if ask_for_confirm('Run the command: {} ?'.format(green(cmd))):NEWLINE call(cmd)NEWLINE else:NEWLINE sys.exit(1)NEWLINENEWLINEdef git_current_commit():NEWLINE return get_command_output('git rev-parse --short HEAD').strip()NEWLINENEWLINEdef get_command_output(cmd):NEWLINE shell = not isinstance(cmd, list)NEWLINE return subprocess.check_output(cmd, shell=shell)NEWLINENEWLINEdef ask_yes_or_no(msg, prompt='', default=None):NEWLINE print('\n' + msg + '\n')NEWLINE while True:NEWLINE answer = input(prompt + ' [yes/no] ').lower()NEWLINE if not answer:NEWLINE continueNEWLINENEWLINE if answer not in ('yes', 'no', 'y', 'n'):NEWLINE continueNEWLINENEWLINE if answer in ('yes', 'y'):NEWLINE return TrueNEWLINE else:NEWLINE return FalseNEWLINENEWLINEdef git_branch_exists(branch):NEWLINE return call('git rev-parse --short --verify {}'.format(branch)) == 0NEWLINENEWLINEdef to_unicode(s):NEWLINE if isinstance(s, str):NEWLINE return s.decode('utf-8')NEWLINE else:NEWLINE return sNEWLINENEWLINEdef to_utf8(s):NEWLINE if isinstance(s, str):NEWLINE return s.encode('utf-8')NEWLINE else:NEWLINE return sNEWLINENEWLINEdef git_commit_time(refspec):NEWLINE return int(get_command_output('git log -1 --format="%ct" {}'.format(NEWLINE refspec)).strip())NEWLINENEWLINEdef get_seafile_version():NEWLINE return os.environ['SEAFILE_VERSION']NEWLINENEWLINEdef get_install_dir():NEWLINE return join('/opt/seafile/' + get_conf('SEAFILE_SERVER', 'seafile-server') + '-{}'.format(get_seafile_version()))NEWLINENEWLINEdef get_script(script):NEWLINE return join(get_install_dir(), script)NEWLINENEWLINENEWLINE_config = NoneNEWLINENEWLINEdef get_conf(key, default=None):NEWLINE key = key.upper()NEWLINE return os.environ.get(key, default)NEWLINENEWLINEdef _add_default_context(context):NEWLINE default_context = {NEWLINE 'current_timestr': datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S'),NEWLINE }NEWLINE for k in default_context:NEWLINE context.setdefault(k, default_context[k])NEWLINENEWLINEdef render_template(template, target, context):NEWLINE from jinja2 import Environment, FileSystemLoaderNEWLINE env = Environment(loader=FileSystemLoader(dirname(template)))NEWLINE _add_default_context(context)NEWLINE content = env.get_template(basename(template)).render(**context)NEWLINE with open(target, 'w') as fp:NEWLINE fp.write(content)NEWLINENEWLINEdef logdbg(msg):NEWLINE if DEBUG_ENABLED:NEWLINE msg = '[debug] ' + msgNEWLINE loginfo(msg)NEWLINENEWLINEdef loginfo(msg):NEWLINE msg = '[{}] {}'.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), green(msg))NEWLINE eprint(msg)NEWLINENEWLINEdef cert_has_valid_days(cert, days):NEWLINE return TrueNEWLINENEWLINEdef get_version_stamp_file():NEWLINE return '/shared/seafile/seafile-data/current_version'NEWLINENEWLINEdef read_version_stamp(fn=get_version_stamp_file()):NEWLINE assert exists(fn), 'version stamp file {} does not exist!'.format(fn)NEWLINE with open(fn, 'r') as fp:NEWLINE return fp.read().strip()NEWLINENEWLINEdef update_version_stamp(version, fn=get_version_stamp_file()):NEWLINE with open(fn, 'w') as fp:NEWLINE fp.write(version + '\n')NEWLINENEWLINEdef wait_for_mysql():NEWLINE db_host = get_conf('DB_HOST', '127.0.0.1')NEWLINE db_user = 'root'NEWLINE db_passwd = get_conf('DB_ROOT_PASSWD', '')NEWLINENEWLINE while True:NEWLINE try:NEWLINE MySQLdb.connect(host=db_host, port=3306, user=db_user, passwd=db_passwd)NEWLINE except Exception as e:NEWLINE print('waiting for mysql server to be ready: %s', e)NEWLINE time.sleep(2)NEWLINE continueNEWLINE logdbg('mysql server is ready')NEWLINE returnNEWLINENEWLINEdef wait_for_nginx():NEWLINE returnNEWLINENEWLINEdef replace_file_pattern(fn, pattern, replacement):NEWLINE with open(fn, 'r') as fp:NEWLINE content = fp.read()NEWLINE with open(fn, 'w') as fp:NEWLINE fp.write(content.replace(pattern, replacement))NEWLINE # Copyright 1999-2021 Alibaba Group Holding Ltd.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINEimport asyncioNEWLINEfrom typing import Dict, List, Optional, Tuple, UnionNEWLINENEWLINEimport numpy as npNEWLINENEWLINEfrom .... import oscar as moNEWLINEfrom ....core import tileNEWLINEfrom ....utils import build_fetchNEWLINEfrom ...core import NodeRoleNEWLINEfrom ...cluster import ClusterAPINEWLINEfrom ...meta import MetaAPINEWLINEfrom ..core import MutableTensorInfoNEWLINEfrom ..utils import (NEWLINE getitem_to_records,NEWLINE setitem_to_records,NEWLINE normalize_name,NEWLINE normalize_timestamp,NEWLINE)NEWLINEfrom ..worker import MutableTensorChunkActorNEWLINENEWLINENEWLINEclass MutableObjectManagerActor(mo.Actor):NEWLINE def __init__(self, session_id: str):NEWLINE self._session_id = session_idNEWLINE self._cluster_api: Optional[ClusterAPI] = NoneNEWLINENEWLINE self._mutable_objects = dict()NEWLINENEWLINE async def __post_create__(self):NEWLINE self._cluster_api = await ClusterAPI.create(self.address)NEWLINENEWLINE async def __pre_destroy__(self):NEWLINE await asyncio.gather(NEWLINE *[mo.destroy_actor(ref) for ref in self._mutable_objects.values()]NEWLINE )NEWLINENEWLINE @classmethodNEWLINE def gen_uid(cls, session_id: str):NEWLINE return f"mutable-object-manager-{session_id}"NEWLINENEWLINE async def create_mutable_tensor(self, *args, name: Optional[str] = None, **kwargs):NEWLINE name = normalize_name(name)NEWLINE if name in self._mutable_objects:NEWLINE raise ValueError(f"Mutable tensor {name} already exists!")NEWLINENEWLINE workers: List[str] = list(NEWLINE await self._cluster_api.get_nodes_info(role=NodeRole.WORKER)NEWLINE )NEWLINENEWLINE tensor_ref = await mo.create_actor(NEWLINE MutableTensorActor,NEWLINE self._session_id,NEWLINE name,NEWLINE workers,NEWLINE *args,NEWLINE **kwargs,NEWLINE address=self.address,NEWLINE uid=MutableTensorActor.gen_uid(self._session_id, name),NEWLINE )NEWLINE self._mutable_objects[name] = tensor_refNEWLINE return tensor_refNEWLINENEWLINE async def get_mutable_tensor(self, name: str):NEWLINE tensor_ref = self._mutable_objects.get(name, None)NEWLINE if tensor_ref is None:NEWLINE raise ValueError(f"Mutable tensor {name} doesn't exist!")NEWLINE return tensor_refNEWLINENEWLINE async def seal_mutable_tensor(self, name: str, timestamp=None):NEWLINE tensor_ref = self._mutable_objects.get(name, None)NEWLINE if tensor_ref is None:NEWLINE raise ValueError(f"Mutable tensor {name} doesn't exist!")NEWLINE tensor = await tensor_ref.seal(timestamp)NEWLINE await mo.destroy_actor(tensor_ref)NEWLINE self._mutable_objects.pop(name)NEWLINE return tensorNEWLINENEWLINENEWLINEclass MutableTensorActor(mo.Actor):NEWLINE def __init__(NEWLINE self,NEWLINE session_id: str,NEWLINE name: str,NEWLINE workers: List[str],NEWLINE shape: Tuple,NEWLINE dtype: Union[np.dtype, str],NEWLINE default_value: Union[int, float] = 0,NEWLINE chunk_size: Union[int, Tuple] = None,NEWLINE ):NEWLINE self._session_id = session_idNEWLINE self._name = nameNEWLINE self._workers = workersNEWLINE self._shape = shapeNEWLINE self._dtype = dtypeNEWLINE self._default_value = default_valueNEWLINE self._chunk_size = chunk_sizeNEWLINENEWLINE self._sealed = FalseNEWLINENEWLINE self._fetch = NoneNEWLINE self._chunk_actors = []NEWLINE # chunk to actor: {chunk index -> actor uid}NEWLINE self._chunk_to_actor: Dict[NEWLINE Tuple, Union[MutableTensorChunkActor, mo.ActorRef]NEWLINE ] = dict()NEWLINENEWLINE async def __post_create__(self):NEWLINE self._meta_api = await MetaAPI.create(self._session_id, self.address)NEWLINENEWLINE # tiling a random tensor to generate keys, but we doesn't actually executeNEWLINE # the random generatorNEWLINE from ....tensor.random import randNEWLINENEWLINE self._fetch = build_fetch(NEWLINE tile(rand(*self._shape, dtype=self._dtype, chunk_size=self._chunk_size))NEWLINE )NEWLINENEWLINE chunk_groups = np.array_split(self._fetch.chunks, len(self._workers))NEWLINE for idx, (worker, chunks) in enumerate(zip(self._workers, chunk_groups)):NEWLINE if len(chunks) == 0:NEWLINE breakNEWLINE chunk_actor_ref = await mo.create_actor(NEWLINE MutableTensorChunkActor,NEWLINE self._session_id,NEWLINE self.address,NEWLINE list(chunks),NEWLINE dtype=self._dtype,NEWLINE default_value=self._default_value,NEWLINE address=worker,NEWLINE uid=MutableTensorChunkActor.gen_uid(self._session_id, self._name, idx),NEWLINE )NEWLINE self._chunk_actors.append(chunk_actor_ref)NEWLINE for chunk in chunks:NEWLINE self._chunk_to_actor[chunk.index] = chunk_actor_refNEWLINENEWLINE async def __pre_destroy__(self):NEWLINE await asyncio.gather(*[mo.destroy_actor(ref) for ref in self._chunk_actors])NEWLINENEWLINE @classmethodNEWLINE def gen_uid(cls, session_id, name):NEWLINE return f"mutable-tensor-{session_id}-{name}"NEWLINENEWLINE async def info(self) -> "MutableTensorInfo":NEWLINE return MutableTensorInfo(NEWLINE self._shape, self._dtype, self._name, self._default_valueNEWLINE )NEWLINENEWLINE @mo.extensibleNEWLINE async def _read_chunk(NEWLINE self, chunk_actor_ref, chunk_index, records, chunk_value_shape, timestampNEWLINE ):NEWLINE return await chunk_actor_ref.read(NEWLINE chunk_index, records, chunk_value_shape, timestampNEWLINE )NEWLINENEWLINE async def read(self, index, timestamp=None):NEWLINE """NEWLINE Read value from mutable tensor.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE index:NEWLINE Index to read from the tensor.NEWLINENEWLINE timestamp: optionalNEWLINE Timestamp to read value that happened before then.NEWLINE """NEWLINE timestamp = normalize_timestamp(timestamp)NEWLINE records, output_shape = getitem_to_records(self._fetch, index)NEWLINENEWLINE read_tasks, chunk_indices = [], []NEWLINE for chunk_index, (records, chunk_value_shape, indices) in records.items():NEWLINE chunk_actor_ref = self._chunk_to_actor[chunk_index]NEWLINE read_tasks.append(NEWLINE self._read_chunk.delay(NEWLINE chunk_actor_ref, chunk_index, records, chunk_value_shape, timestampNEWLINE )NEWLINE )NEWLINE chunk_indices.append(indices)NEWLINE chunks = await self._read_chunk.batch(*read_tasks)NEWLINE result = np.full(output_shape, fill_value=self._default_value)NEWLINE for chunk, indices in zip(chunks, chunk_indices):NEWLINE result[indices] = chunkNEWLINE return resultNEWLINENEWLINE @mo.extensibleNEWLINE async def _write_chunk(self, chunk_actor_ref, chunk_index, records):NEWLINE await chunk_actor_ref.write(chunk_index, records)NEWLINENEWLINE async def write(self, index, value, timestamp=None):NEWLINE """NEWLINE Write value to mutable tensor.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE index:NEWLINE Index to write to the tensor.NEWLINENEWLINE value:NEWLINE The value that will be filled into the mutable tensor according to `index`.NEWLINENEWLINE timestamp: optionalNEWLINE Timestamp to associated with the newly touched value.NEWLINE """NEWLINE timestamp = normalize_timestamp(timestamp)NEWLINE records = setitem_to_records(self._fetch, index, value, timestamp)NEWLINENEWLINE write_tasks = []NEWLINE for chunk_index, records in records.items():NEWLINE chunk_actor_ref = self._chunk_to_actor[chunk_index]NEWLINE write_tasks.append(NEWLINE self._write_chunk.delay(chunk_actor_ref, chunk_index, records)NEWLINE )NEWLINE await self._write_chunk.batch(*write_tasks)NEWLINENEWLINE @mo.extensibleNEWLINE async def _seal_chunk(self, chunk_actor_ref, timestamp):NEWLINE await chunk_actor_ref.seal(timestamp)NEWLINENEWLINE async def seal(self, timestamp=None):NEWLINE if self._sealed:NEWLINE return self._fetchNEWLINENEWLINE timestamp = normalize_timestamp(timestamp)NEWLINE self._sealed = TrueNEWLINE seal_tasks = []NEWLINE for chunk_actor_ref in self._chunk_actors:NEWLINE seal_tasks.append(self._seal_chunk.delay(chunk_actor_ref, timestamp))NEWLINE await self._seal_chunk.batch(*seal_tasks)NEWLINE self._chunk_actors = []NEWLINE return self._fetchNEWLINE # -*- coding: utf-8 -*-NEWLINE"""NEWLINENEWLINEScript Name: ProFile.pyNEWLINEAuthor: Do Trinh/Jimmy - 3D artist.NEWLINENEWLINEDescription:NEWLINENEWLINE"""NEWLINE# -------------------------------------------------------------------------------------------------------------NEWLINENEWLINEfrom pyPLM.Widgets import GroupGrid, LineEdit, Button, LabelNEWLINENEWLINEclass Profile(GroupGrid):NEWLINENEWLINE key = 'ProFile'NEWLINENEWLINE def __init__(self, parent=None):NEWLINE super(Profile, self).__init__(parent=parent)NEWLINENEWLINE self.parent = parentNEWLINENEWLINE self.layout.addWidget(Label({'txt': 'First Name'}), 0, 0, 1, 2)NEWLINE self.layout.addWidget(Label({'txt': 'Last Name'}), 1, 0, 1, 2)NEWLINE self.layout.addWidget(Label({'txt': 'Your Title'}), 2, 0, 1, 2)NEWLINE self.layout.addWidget(Label({'txt': 'Email'}), 3, 0, 1, 2)NEWLINE self.layout.addWidget(Label({'txt': 'Phone Number'}), 4, 0, 1, 2)NEWLINENEWLINE self.firstnameField = LineEdit()NEWLINE self.lastnameField = LineEdit()NEWLINE self.titleField = LineEdit()NEWLINE self.emailField = LineEdit()NEWLINE self.phoneField = LineEdit()NEWLINENEWLINE self.changeBtn = Button({'txt': "Update Profile", 'cl': self.update_profile})NEWLINENEWLINE self.layout.addWidget(self.firstnameField, 0, 2, 1, 4)NEWLINE self.layout.addWidget(self.lastnameField, 1, 2, 1, 4)NEWLINE self.layout.addWidget(self.titleField, 2, 2, 1, 4)NEWLINE self.layout.addWidget(self.emailField, 3, 2, 1, 4)NEWLINE self.layout.addWidget(self.phoneField, 4, 2, 1, 4)NEWLINE self.layout.addWidget(self.changeBtn, 5, 0, 1, 6)NEWLINENEWLINE def update_profile(self):NEWLINE passNEWLINENEWLINE# -------------------------------------------------------------------------------------------------------------NEWLINE# Created by panda on 28/11/2019 - 7:49 PMNEWLINE# © 2017 - 2018 DAMGteam. All rights reserved from typing import ListNEWLINENEWLINENEWLINEclass InvoiceProfiles:NEWLINE def __init__(self, invoice_profiles: List[str]):NEWLINE self.invoice_profiles = invoice_profilesNEWLINENEWLINE def as_list(self) -> List:NEWLINE return [{"value": invoice_profile} for invoice_profile in self.invoice_profiles]NEWLINE import loggingNEWLINEimport mathNEWLINEimport osNEWLINEimport pickleNEWLINEimport sysNEWLINEimport timeNEWLINENEWLINEimport psutilNEWLINENEWLINEfrom .catboost_utils import construct_custom_catboost_metricNEWLINEfrom .hyperparameters.parameters import get_param_baselineNEWLINEfrom .hyperparameters.searchspaces import get_default_searchspaceNEWLINEfrom ..abstract.abstract_model import AbstractModelNEWLINEfrom ...constants import PROBLEM_TYPES_CLASSIFICATION, MULTICLASSNEWLINEfrom ....utils.exceptions import NotEnoughMemoryError, TimeLimitExceededNEWLINEfrom .....try_import import try_import_catboostNEWLINENEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINENEWLINE# TODO: Catboost crashes on multiclass problems where only two classes have significant member count.NEWLINE# Question: Do we turn these into binary classification and then convert to multiclass output in Learner? This would make the most sense.NEWLINE# TODO: Consider having Catboost variant that converts all categoricals to numerical as done in RFModel, was showing improved results in some problems.NEWLINEclass CatboostModel(AbstractModel):NEWLINE def __init__(self, path: str, name: str, problem_type: str, objective_func, stopping_metric=None, num_classes=None, hyperparameters=None, features=None, debug=0, **kwargs):NEWLINE super().__init__(path=path, name=name, problem_type=problem_type, objective_func=objective_func, stopping_metric=stopping_metric, num_classes=num_classes, hyperparameters=hyperparameters, features=features, debug=debug, **kwargs)NEWLINE try_import_catboost()NEWLINE from catboost import CatBoostClassifier, CatBoostRegressorNEWLINE self.model_type = CatBoostClassifier if problem_type in PROBLEM_TYPES_CLASSIFICATION else CatBoostRegressorNEWLINE if isinstance(self.params['eval_metric'], str):NEWLINE self.metric_name = self.params['eval_metric']NEWLINE else:NEWLINE self.metric_name = type(self.params['eval_metric']).__name__NEWLINENEWLINE def _set_default_params(self):NEWLINE default_params = get_param_baseline(problem_type=self.problem_type)NEWLINE for param, val in default_params.items():NEWLINE self._set_default_param_value(param, val)NEWLINE self._set_default_param_value('random_seed', 0) # Remove randomness for reproducibilityNEWLINE self._set_default_param_value('eval_metric', construct_custom_catboost_metric(self.stopping_metric, True, not self.stopping_metric_needs_y_pred, self.problem_type))NEWLINE # Set 'allow_writing_files' to True in order to keep log files created by catboost during training (these will be saved in the directory where AutoGluon stores this model)NEWLINE self._set_default_param_value('allow_writing_files', False) # Disables creation of catboost logging files during training by defaultNEWLINENEWLINE def _get_default_searchspace(self):NEWLINE return get_default_searchspace(self.problem_type, num_classes=self.num_classes)NEWLINENEWLINE def preprocess(self, X):NEWLINE X = super().preprocess(X)NEWLINE categoricals = list(X.select_dtypes(include='category').columns)NEWLINE if categoricals:NEWLINE X = X.copy()NEWLINE for category in categoricals:NEWLINE current_categories = X[category].cat.categoriesNEWLINE if '__NaN__' in current_categories:NEWLINE X[category] = X[category].fillna('__NaN__')NEWLINE else:NEWLINE X[category] = X[category].cat.add_categories('__NaN__').fillna('__NaN__')NEWLINE return XNEWLINENEWLINE # TODO: Use Pool in preprocess, optimize bagging to do Pool.split() to avoid re-computing pool for each fold! Requires stateful + yNEWLINE # Pool is much more memory efficient, avoids copying data twice in memoryNEWLINE def fit(self, X_train, Y_train, X_test=None, Y_test=None, time_limit=None, **kwargs):NEWLINE from catboost import PoolNEWLINE num_rows_train = len(X_train)NEWLINE num_cols_train = len(X_train.columns)NEWLINE if self.problem_type == MULTICLASS:NEWLINE if self.num_classes is not None:NEWLINE num_classes = self.num_classesNEWLINE else:NEWLINE num_classes = 10 # Guess if not given, can do better by looking at y_trainNEWLINE else:NEWLINE num_classes = 1NEWLINENEWLINE # TODO: Add ignore_memory_limits param to disable NotEnoughMemoryError ExceptionsNEWLINE max_memory_usage_ratio = self.params_aux['max_memory_usage_ratio']NEWLINE approx_mem_size_req = num_rows_train * num_cols_train * num_classes / 2 # TODO: Extremely crude approximation, can be vastly improvedNEWLINE if approx_mem_size_req > 1e9: # > 1 GBNEWLINE available_mem = psutil.virtual_memory().availableNEWLINE ratio = approx_mem_size_req / available_memNEWLINE if ratio > (1 * max_memory_usage_ratio):NEWLINE logger.warning('\tWarning: Not enough memory to safely train CatBoost model, roughly requires: %s GB, but only %s GB is available...' % (round(approx_mem_size_req / 1e9, 3), round(available_mem / 1e9, 3)))NEWLINE raise NotEnoughMemoryErrorNEWLINE elif ratio > (0.2 * max_memory_usage_ratio):NEWLINE logger.warning('\tWarning: Potentially not enough memory to safely train CatBoost model, roughly requires: %s GB, but only %s GB is available...' % (round(approx_mem_size_req / 1e9, 3), round(available_mem / 1e9, 3)))NEWLINENEWLINE start_time = time.time()NEWLINE X_train = self.preprocess(X_train)NEWLINE cat_features = list(X_train.select_dtypes(include='category').columns)NEWLINE X_train = Pool(data=X_train, label=Y_train, cat_features=cat_features)NEWLINENEWLINE if X_test is not None:NEWLINE X_test = self.preprocess(X_test)NEWLINE X_test = Pool(data=X_test, label=Y_test, cat_features=cat_features)NEWLINE eval_set = X_testNEWLINE if num_rows_train <= 10000:NEWLINE modifier = 1NEWLINE else:NEWLINE modifier = 10000/num_rows_trainNEWLINE early_stopping_rounds = max(round(modifier*150), 10)NEWLINE num_sample_iter_max = max(round(modifier*50), 2)NEWLINE else:NEWLINE eval_set = NoneNEWLINE early_stopping_rounds = NoneNEWLINE num_sample_iter_max = 50NEWLINENEWLINE invalid_params = ['num_threads', 'num_gpus']NEWLINE for invalid in invalid_params:NEWLINE if invalid in self.params:NEWLINE self.params.pop(invalid)NEWLINE train_dir = NoneNEWLINE if 'allow_writing_files' in self.params and self.params['allow_writing_files']:NEWLINE if 'train_dir' not in self.params:NEWLINE try:NEWLINE # TODO: What if path is in S3?NEWLINE os.makedirs(os.path.dirname(self.path), exist_ok=True)NEWLINE except:NEWLINE passNEWLINE else:NEWLINE train_dir = self.path + 'catboost_info'NEWLINE logger.log(15, f'\tCatboost model hyperparameters: {self.params}')NEWLINENEWLINE # TODO: Add more control over these params (specifically early_stopping_rounds)NEWLINE verbosity = kwargs.get('verbosity', 2)NEWLINE if verbosity <= 1:NEWLINE verbose = FalseNEWLINE elif verbosity == 2:NEWLINE verbose = FalseNEWLINE elif verbosity == 3:NEWLINE verbose = 20NEWLINE else:NEWLINE verbose = TrueNEWLINENEWLINE init_model = NoneNEWLINE init_model_tree_count = NoneNEWLINE init_model_best_iteration = NoneNEWLINE init_model_best_score = NoneNEWLINENEWLINE params = self.params.copy()NEWLINE num_features = len(self.features)NEWLINE if self.problem_type == MULTICLASS and 'rsm' not in params and 'colsample_bylevel' not in params and num_features > 1000:NEWLINE if time_limit:NEWLINE # Reduce sample iterations to avoid taking unreasonable amounts of timeNEWLINE num_sample_iter_max = max(round(num_sample_iter_max/2), 2)NEWLINE # Subsample columns to speed up trainingNEWLINE params['colsample_bylevel'] = max(min(1.0, 1000 / num_features), 0.05)NEWLINE logger.log(30, f'\tMany features detected ({num_features}), dynamically setting \'colsample_bylevel\' to {params["colsample_bylevel"]} to speed up training (Default = 1).')NEWLINE logger.log(30, f'\tTo disable this functionality, explicitly specify \'colsample_bylevel\' in the model hyperparameters.')NEWLINENEWLINE if time_limit:NEWLINE time_left_start = time_limit - (time.time() - start_time)NEWLINE if time_left_start <= time_limit * 0.4: # if 60% of time was spent preprocessing, likely not enough time to train modelNEWLINE raise TimeLimitExceededNEWLINE params_init = params.copy()NEWLINE num_sample_iter = min(num_sample_iter_max, params_init['iterations'])NEWLINE params_init['iterations'] = num_sample_iterNEWLINE if train_dir is not None:NEWLINE params_init['train_dir'] = train_dirNEWLINE self.model = self.model_type(NEWLINE **params_init,NEWLINE )NEWLINE self.model.fit(NEWLINE X_train,NEWLINE eval_set=eval_set,NEWLINE use_best_model=True,NEWLINE verbose=verbose,NEWLINE # early_stopping_rounds=early_stopping_rounds,NEWLINE )NEWLINENEWLINE init_model_tree_count = self.model.tree_count_NEWLINE init_model_best_iteration = self.model.get_best_iteration()NEWLINE init_model_best_score = self.model.get_best_score()['validation'][self.metric_name]NEWLINENEWLINE time_left_end = time_limit - (time.time() - start_time)NEWLINE time_taken_per_iter = (time_left_start - time_left_end) / num_sample_iterNEWLINE estimated_iters_in_time = round(time_left_end / time_taken_per_iter)NEWLINE init_model = self.modelNEWLINENEWLINE params_final = params.copy()NEWLINENEWLINE # TODO: This only handles memory with time_limits specified, but not with time_limits=None, handle when time_limits=NoneNEWLINE available_mem = psutil.virtual_memory().availableNEWLINE model_size_bytes = sys.getsizeof(pickle.dumps(self.model))NEWLINENEWLINE max_memory_proportion = 0.3 * max_memory_usage_ratioNEWLINE mem_usage_per_iter = model_size_bytes / num_sample_iterNEWLINE max_memory_iters = math.floor(available_mem * max_memory_proportion / mem_usage_per_iter)NEWLINENEWLINE params_final['iterations'] = min(params['iterations'] - num_sample_iter, estimated_iters_in_time)NEWLINE if params_final['iterations'] > max_memory_iters - num_sample_iter:NEWLINE if max_memory_iters - num_sample_iter <= 500:NEWLINE logger.warning('\tWarning: CatBoost will be early stopped due to lack of memory, increase memory to enable full quality models, max training iterations changed to %s from %s' % (max_memory_iters - num_sample_iter, params_final['iterations']))NEWLINE params_final['iterations'] = max_memory_iters - num_sample_iterNEWLINE else:NEWLINE params_final = params.copy()NEWLINENEWLINE if train_dir is not None:NEWLINE params_final['train_dir'] = train_dirNEWLINE if params_final['iterations'] > 0:NEWLINE self.model = self.model_type(NEWLINE **params_final,NEWLINE )NEWLINENEWLINE # TODO: Strangely, this performs different if clone init_model is sent in than if trained for same total number of iterations. May be able to optimize catboost models further with thisNEWLINE self.model.fit(NEWLINE X_train,NEWLINE eval_set=eval_set,NEWLINE verbose=verbose,NEWLINE early_stopping_rounds=early_stopping_rounds,NEWLINE # use_best_model=True,NEWLINE init_model=init_model,NEWLINE )NEWLINENEWLINE if init_model is not None:NEWLINE final_model_best_score = self.model.get_best_score()['validation'][self.metric_name]NEWLINE if self.stopping_metric._optimum > final_model_best_score:NEWLINE if final_model_best_score > init_model_best_score:NEWLINE best_iteration = init_model_tree_count + self.model.get_best_iteration()NEWLINE else:NEWLINE best_iteration = init_model_best_iterationNEWLINE else:NEWLINE if final_model_best_score < init_model_best_score:NEWLINE best_iteration = init_model_tree_count + self.model.get_best_iteration()NEWLINE else:NEWLINE best_iteration = init_model_best_iterationNEWLINENEWLINE self.model.shrink(ntree_start=0, ntree_end=best_iteration+1)NEWLINENEWLINE self.params_trained['iterations'] = self.model.tree_count_NEWLINENEWLINE def get_model_feature_importance(self):NEWLINE importance_df = self.model.get_feature_importance(prettified=True)NEWLINE importance_df['Importances'] = importance_df['Importances'] / 100NEWLINE importance_series = importance_df.set_index('Feature Id')['Importances']NEWLINE importance_dict = importance_series.to_dict()NEWLINE return importance_dictNEWLINE from django.contrib import adminNEWLINEfrom .models import ItemNEWLINENEWLINE# Register your models here.NEWLINEadmin.site.register(Item) """Labware state store tests."""NEWLINEimport pytestNEWLINEfrom collections import OrderedDictNEWLINEfrom contextlib import nullcontext as does_not_raiseNEWLINEfrom typing import List, NamedTuple, Optional, Sequence, Tuple, Type, UnionNEWLINENEWLINEfrom opentrons.protocol_engine import EngineStatus, commands as cmd, errorsNEWLINEfrom opentrons.protocol_engine.state.commands import CommandState, CommandViewNEWLINEfrom opentrons.protocol_engine.actions import PlayAction, PauseActionNEWLINENEWLINEfrom .command_fixtures import (NEWLINE create_pending_command,NEWLINE create_running_command,NEWLINE create_failed_command,NEWLINE create_completed_command,NEWLINE)NEWLINENEWLINENEWLINEdef get_command_view(NEWLINE is_running: bool = False,NEWLINE stop_requested: bool = False,NEWLINE commands_by_id: Sequence[Tuple[str, cmd.Command]] = (),NEWLINE) -> CommandView:NEWLINE """Get a command view test subject."""NEWLINE state = CommandState(NEWLINE is_running=is_running,NEWLINE stop_requested=stop_requested,NEWLINE commands_by_id=OrderedDict(commands_by_id),NEWLINE )NEWLINENEWLINE return CommandView(state=state)NEWLINENEWLINENEWLINEdef test_get_by_id() -> None:NEWLINE """It should get a command by ID from state."""NEWLINE command = create_completed_command(command_id="command-id")NEWLINE subject = get_command_view(commands_by_id=[("command-id", command)])NEWLINENEWLINE assert subject.get("command-id") == commandNEWLINENEWLINENEWLINEdef test_get_command_bad_id() -> None:NEWLINE """It should raise if a requested command ID isn't in state."""NEWLINE command = create_completed_command(command_id="command-id")NEWLINE subject = get_command_view(commands_by_id=[("command-id", command)])NEWLINENEWLINE with pytest.raises(errors.CommandDoesNotExistError):NEWLINE subject.get("asdfghjkl")NEWLINENEWLINENEWLINEdef test_get_all() -> None:NEWLINE """It should get all the commands from the state."""NEWLINE command_1 = create_completed_command(command_id="command-id-1")NEWLINE command_2 = create_running_command(command_id="command-id-2")NEWLINE command_3 = create_pending_command(command_id="command-id-3")NEWLINENEWLINE subject = get_command_view(NEWLINE commands_by_id=[NEWLINE ("command-id-1", command_1),NEWLINE ("command-id-2", command_2),NEWLINE ("command-id-3", command_3),NEWLINE ]NEWLINE )NEWLINENEWLINE assert subject.get_all() == [command_1, command_2, command_3]NEWLINENEWLINENEWLINEdef test_get_next_queued_returns_first_pending() -> None:NEWLINE """It should return the first command that's pending."""NEWLINE pending_command = create_pending_command()NEWLINE running_command = create_running_command()NEWLINE completed_command = create_completed_command()NEWLINENEWLINE subject = get_command_view(NEWLINE is_running=True,NEWLINE commands_by_id=[NEWLINE ("command-id-1", running_command),NEWLINE ("command-id-2", completed_command),NEWLINE ("command-id-3", pending_command),NEWLINE ("command-id-4", pending_command),NEWLINE ],NEWLINE )NEWLINENEWLINE assert subject.get_next_queued() == "command-id-3"NEWLINENEWLINENEWLINEdef test_get_next_queued_returns_none_when_no_pending() -> None:NEWLINE """It should return None if there are no pending commands to return."""NEWLINE running_command = create_running_command(command_id="command-id-1")NEWLINE completed_command = create_completed_command(command_id="command-id-2")NEWLINENEWLINE subject = get_command_view(is_running=True)NEWLINENEWLINE assert subject.get_next_queued() is NoneNEWLINENEWLINE subject = get_command_view(NEWLINE is_running=True,NEWLINE commands_by_id=[NEWLINE ("command-id-1", running_command),NEWLINE ("command-id-2", completed_command),NEWLINE ],NEWLINE )NEWLINENEWLINE assert subject.get_next_queued() is NoneNEWLINENEWLINENEWLINEdef test_get_next_queued_returns_none_if_not_running() -> None:NEWLINE """It should return None if the engine is not running."""NEWLINE pending_command = create_pending_command()NEWLINENEWLINE subject = get_command_view(NEWLINE is_running=False,NEWLINE commands_by_id=[("command-id", pending_command)],NEWLINE )NEWLINE result = subject.get_next_queued()NEWLINENEWLINE assert result is NoneNEWLINENEWLINENEWLINEdef test_get_next_queued_raises_when_earlier_command_failed() -> None:NEWLINE """It should raise if any prior-added command is failed."""NEWLINE running_command = create_running_command(command_id="command-id-1")NEWLINE completed_command = create_completed_command(command_id="command-id-2")NEWLINE failed_command = create_failed_command(command_id="command-id-3")NEWLINE pending_command = create_pending_command(command_id="command-id-4")NEWLINENEWLINE subject = get_command_view(NEWLINE is_running=True,NEWLINE commands_by_id=[NEWLINE ("command-id-1", running_command),NEWLINE ("command-id-2", completed_command),NEWLINE ("command-id-3", failed_command),NEWLINE ("command-id-4", pending_command),NEWLINE ],NEWLINE )NEWLINENEWLINE with pytest.raises(errors.ProtocolEngineStoppedError):NEWLINE subject.get_next_queued()NEWLINENEWLINENEWLINEdef test_get_next_queued_raises_if_stopped() -> None:NEWLINE """It should raise if an engine stop has been requested."""NEWLINE subject = get_command_view(stop_requested=True)NEWLINENEWLINE with pytest.raises(errors.ProtocolEngineStoppedError):NEWLINE subject.get_next_queued()NEWLINENEWLINENEWLINEdef test_get_is_running() -> None:NEWLINE """It should be able to get if the engine is running."""NEWLINE subject = get_command_view(is_running=False)NEWLINE assert subject.get_is_running() is FalseNEWLINENEWLINE subject = get_command_view(is_running=True)NEWLINE assert subject.get_is_running() is TrueNEWLINENEWLINENEWLINEdef test_get_is_complete() -> None:NEWLINE """It should be able to tell if a command is complete."""NEWLINE completed_command = create_completed_command(command_id="command-id-1")NEWLINE running_command = create_running_command(command_id="command-id-2")NEWLINE pending_command = create_pending_command(command_id="command-id-3")NEWLINENEWLINE subject = get_command_view(NEWLINE commands_by_id=[NEWLINE ("command-id-1", completed_command),NEWLINE ("command-id-2", running_command),NEWLINE ("command-id-3", pending_command),NEWLINE ]NEWLINE )NEWLINENEWLINE assert subject.get_is_complete("command-id-1") is TrueNEWLINE assert subject.get_is_complete("command-id-2") is FalseNEWLINE assert subject.get_is_complete("command-id-3") is FalseNEWLINENEWLINENEWLINEdef test_get_is_complete_with_failed_command() -> None:NEWLINE """It should return true if a given command will never be executed."""NEWLINE failed_command = create_failed_command(command_id="command-id-1")NEWLINE pending_command = create_pending_command(command_id="command-id-2")NEWLINENEWLINE subject = get_command_view(NEWLINE commands_by_id=[NEWLINE ("command-id-1", failed_command),NEWLINE ("command-id-2", pending_command),NEWLINE ]NEWLINE )NEWLINENEWLINE assert subject.get_is_complete("command-id-1") is TrueNEWLINE assert subject.get_is_complete("command-id-2") is TrueNEWLINENEWLINENEWLINEdef test_get_all_complete() -> None:NEWLINE """It should return true if all commands completed or any failed."""NEWLINE completed_command = create_completed_command(command_id="command-id-1")NEWLINE running_command = create_running_command(command_id="command-id-2")NEWLINE pending_command = create_pending_command(command_id="command-id-3")NEWLINE failed_command = create_failed_command(command_id="command-id-4")NEWLINENEWLINE subject = get_command_view(NEWLINE commands_by_id=[NEWLINE ("command-id-4", failed_command),NEWLINE ("command-id-3", pending_command),NEWLINE ],NEWLINE )NEWLINENEWLINE assert subject.get_all_complete() is TrueNEWLINENEWLINE subject = get_command_view(NEWLINE commands_by_id=[NEWLINE ("command-id-1", completed_command),NEWLINE ("command-id-2", running_command),NEWLINE ("command-id-3", pending_command),NEWLINE ],NEWLINE )NEWLINENEWLINE assert subject.get_all_complete() is FalseNEWLINENEWLINE subject = get_command_view(NEWLINE commands_by_id=[NEWLINE ("command-id-1", completed_command),NEWLINE ("command-id-2", completed_command),NEWLINE ],NEWLINE )NEWLINENEWLINE assert subject.get_all_complete() is TrueNEWLINENEWLINENEWLINEdef test_get_stop_requested() -> None:NEWLINE """It should return true if the stop_requested flag is set."""NEWLINE subject = get_command_view(stop_requested=True)NEWLINE assert subject.get_stop_requested() is TrueNEWLINENEWLINE subject = get_command_view(stop_requested=False)NEWLINE assert subject.get_stop_requested() is FalseNEWLINENEWLINENEWLINEdef test_get_is_stopped() -> None:NEWLINE """It should return true if stop requested and no command running."""NEWLINE completed_command = create_completed_command(command_id="command-id-1")NEWLINE running_command = create_running_command(command_id="command-id-2")NEWLINE pending_command = create_pending_command(command_id="command-id-3")NEWLINE failed_command = create_failed_command(command_id="command-id-4")NEWLINENEWLINE subject = get_command_view(NEWLINE stop_requested=False,NEWLINE commands_by_id=(),NEWLINE )NEWLINE assert subject.get_is_stopped() is FalseNEWLINENEWLINE subject = get_command_view(NEWLINE stop_requested=True,NEWLINE commands_by_id=[("command-id-2", running_command)],NEWLINE )NEWLINE assert subject.get_is_stopped() is FalseNEWLINENEWLINE subject = get_command_view(NEWLINE stop_requested=True,NEWLINE commands_by_id=[NEWLINE ("command-id-1", completed_command),NEWLINE ("command-id-3", pending_command),NEWLINE ("command-id-4", failed_command),NEWLINE ],NEWLINE )NEWLINE assert subject.get_is_stopped() is TrueNEWLINENEWLINENEWLINEclass ActionAllowedSpec(NamedTuple):NEWLINE """Spec data to test CommandView.validate_action_allowed."""NEWLINENEWLINE subject: CommandViewNEWLINE action: Union[PlayAction, PauseAction]NEWLINE expected_error: Optional[Type[errors.ProtocolEngineError]]NEWLINENEWLINENEWLINEaction_allowed_specs: List[ActionAllowedSpec] = [NEWLINE ActionAllowedSpec(NEWLINE subject=get_command_view(stop_requested=False, is_running=False),NEWLINE action=PlayAction(),NEWLINE expected_error=None,NEWLINE ),NEWLINE ActionAllowedSpec(NEWLINE subject=get_command_view(stop_requested=False, is_running=True),NEWLINE action=PlayAction(),NEWLINE expected_error=None,NEWLINE ),NEWLINE ActionAllowedSpec(NEWLINE subject=get_command_view(stop_requested=True, is_running=False),NEWLINE action=PlayAction(),NEWLINE expected_error=errors.ProtocolEngineStoppedError,NEWLINE ),NEWLINE ActionAllowedSpec(NEWLINE subject=get_command_view(stop_requested=False, is_running=False),NEWLINE action=PauseAction(),NEWLINE expected_error=None,NEWLINE ),NEWLINE ActionAllowedSpec(NEWLINE subject=get_command_view(stop_requested=False, is_running=True),NEWLINE action=PauseAction(),NEWLINE expected_error=None,NEWLINE ),NEWLINE ActionAllowedSpec(NEWLINE subject=get_command_view(stop_requested=True, is_running=False),NEWLINE action=PauseAction(),NEWLINE expected_error=errors.ProtocolEngineStoppedError,NEWLINE ),NEWLINE]NEWLINENEWLINENEWLINE@pytest.mark.parametrize(ActionAllowedSpec._fields, action_allowed_specs)NEWLINEdef test_validate_action_allowed(NEWLINE subject: CommandView,NEWLINE action: Union[PlayAction, PauseAction],NEWLINE expected_error: Optional[Type[errors.ProtocolEngineError]],NEWLINE) -> None:NEWLINE """It should validate allowed play/pause actions."""NEWLINE expectation = pytest.raises(expected_error) if expected_error else does_not_raise()NEWLINENEWLINE with expectation: # type: ignore[attr-defined]NEWLINE subject.validate_action_allowed(action)NEWLINENEWLINENEWLINEclass GetStatusSpec(NamedTuple):NEWLINE """Spec data for get_status tests."""NEWLINENEWLINE subject: CommandViewNEWLINE expected_status: EngineStatusNEWLINENEWLINENEWLINEget_status_specs: List[GetStatusSpec] = [NEWLINE GetStatusSpec(NEWLINE subject=get_command_view(NEWLINE is_running=False,NEWLINE stop_requested=False,NEWLINE commands_by_id=[],NEWLINE ),NEWLINE expected_status=EngineStatus.READY_TO_RUN,NEWLINE ),NEWLINE GetStatusSpec(NEWLINE subject=get_command_view(NEWLINE is_running=False,NEWLINE stop_requested=False,NEWLINE commands_by_id=[("command-id", create_pending_command())],NEWLINE ),NEWLINE expected_status=EngineStatus.READY_TO_RUN,NEWLINE ),NEWLINE GetStatusSpec(NEWLINE subject=get_command_view(NEWLINE is_running=False,NEWLINE stop_requested=False,NEWLINE commands_by_id=[("command-id", create_running_command())],NEWLINE ),NEWLINE expected_status=EngineStatus.PAUSE_REQUESTED,NEWLINE ),NEWLINE GetStatusSpec(NEWLINE subject=get_command_view(NEWLINE is_running=False,NEWLINE stop_requested=False,NEWLINE commands_by_id=[NEWLINE ("command-id-1", create_completed_command()),NEWLINE ("command-id-2", create_pending_command()),NEWLINE ],NEWLINE ),NEWLINE expected_status=EngineStatus.PAUSED,NEWLINE ),NEWLINE GetStatusSpec(NEWLINE subject=get_command_view(NEWLINE is_running=True,NEWLINE stop_requested=False,NEWLINE commands_by_id=[],NEWLINE ),NEWLINE expected_status=EngineStatus.RUNNING,NEWLINE ),NEWLINE GetStatusSpec(NEWLINE subject=get_command_view(NEWLINE is_running=True,NEWLINE stop_requested=False,NEWLINE commands_by_id=[("command-id", create_failed_command())],NEWLINE ),NEWLINE expected_status=EngineStatus.FAILED,NEWLINE ),NEWLINE GetStatusSpec(NEWLINE subject=get_command_view(NEWLINE is_running=False,NEWLINE stop_requested=False,NEWLINE commands_by_id=[("command-id", create_failed_command())],NEWLINE ),NEWLINE expected_status=EngineStatus.FAILED,NEWLINE ),NEWLINE GetStatusSpec(NEWLINE subject=get_command_view(NEWLINE is_running=False,NEWLINE stop_requested=True,NEWLINE commands_by_id=[("command-id", create_failed_command())],NEWLINE ),NEWLINE expected_status=EngineStatus.STOPPED,NEWLINE ),NEWLINE GetStatusSpec(NEWLINE subject=get_command_view(NEWLINE is_running=False,NEWLINE stop_requested=True,NEWLINE commands_by_id=[],NEWLINE ),NEWLINE expected_status=EngineStatus.SUCCEEDED,NEWLINE ),NEWLINE GetStatusSpec(NEWLINE subject=get_command_view(NEWLINE is_running=False,NEWLINE stop_requested=True,NEWLINE commands_by_id=[("command-id", create_completed_command())],NEWLINE ),NEWLINE expected_status=EngineStatus.SUCCEEDED,NEWLINE ),NEWLINE GetStatusSpec(NEWLINE subject=get_command_view(NEWLINE is_running=False,NEWLINE stop_requested=True,NEWLINE commands_by_id=[("command-id", create_running_command())],NEWLINE ),NEWLINE expected_status=EngineStatus.STOP_REQUESTED,NEWLINE ),NEWLINE GetStatusSpec(NEWLINE subject=get_command_view(NEWLINE is_running=False,NEWLINE stop_requested=True,NEWLINE commands_by_id=[NEWLINE ("command-id", create_completed_command()),NEWLINE ("command-id", create_pending_command()),NEWLINE ],NEWLINE ),NEWLINE expected_status=EngineStatus.STOPPED,NEWLINE ),NEWLINE]NEWLINENEWLINENEWLINE@pytest.mark.parametrize(GetStatusSpec._fields, get_status_specs)NEWLINEdef test_get_status(subject: CommandView, expected_status: EngineStatus) -> None:NEWLINE """It should set a status according to the command queue and running flag.NEWLINENEWLINE 1. Not running, no stop requested, only queued commands: READY_TO_RUNNEWLINE 2. Running, no stop requested, no failed commands: RUNNINGNEWLINE 3. Not running, no stop requested, command still running: PAUSE_REQUESTEDNEWLINE 4. Not running, no stop requested, no running commands: PAUSEDNEWLINE 5. Stop requested, command still running: STOP_REQUESTEDNEWLINE 6. Stop requested, no running commands, with queued commands: STOPPEDNEWLINE 7. Stop requested, all commands succeeded: SUCCEEDEDNEWLINE 8. No stop requested, any failed commands: FAILEDNEWLINE """NEWLINE assert subject.get_status() == expected_statusNEWLINE import ipaddressNEWLINEimport structNEWLINEimport pytestNEWLINENEWLINEfrom mitmproxy import dnsNEWLINEfrom mitmproxy import flowfilterNEWLINEfrom mitmproxy.test import tflowNEWLINEfrom mitmproxy.test import tutilsNEWLINENEWLINENEWLINEclass TestResourceRecord:NEWLINENEWLINE def test_str(self):NEWLINE assert str(dns.ResourceRecord.A("test", ipaddress.IPv4Address("1.2.3.4"))) == "1.2.3.4"NEWLINE assert str(dns.ResourceRecord.AAAA("test", ipaddress.IPv6Address("::1"))) == "::1"NEWLINE assert str(dns.ResourceRecord.CNAME("test", "some.other.host")) == "some.other.host"NEWLINE assert str(dns.ResourceRecord.PTR("test", "some.other.host")) == "some.other.host"NEWLINE assert str(dns.ResourceRecord.TXT("test", "unicode text 😀")) == "unicode text 😀"NEWLINE assert str(dns.ResourceRecord("test", dns.types.A, dns.classes.IN, dns.ResourceRecord.DEFAULT_TTL, b'')) == "0x (invalid A data)"NEWLINE assert str(NEWLINE dns.ResourceRecord("test", dns.types.SOA, dns.classes.IN, dns.ResourceRecord.DEFAULT_TTL, b'\x00\x01\x02\x03')NEWLINE ) == "0x00010203"NEWLINENEWLINE def test_setter(self):NEWLINE rr = dns.ResourceRecord("test", dns.types.ANY, dns.classes.IN, dns.ResourceRecord.DEFAULT_TTL, b'')NEWLINE rr.ipv4_address = ipaddress.IPv4Address("8.8.4.4")NEWLINE assert rr.ipv4_address == ipaddress.IPv4Address("8.8.4.4")NEWLINE rr.ipv6_address = ipaddress.IPv6Address("2001:4860:4860::8844")NEWLINE assert rr.ipv6_address == ipaddress.IPv6Address("2001:4860:4860::8844")NEWLINE rr.domain_name = "www.example.org"NEWLINE assert rr.domain_name == "www.example.org"NEWLINE rr.text = "sample text"NEWLINE assert rr.text == "sample text"NEWLINENEWLINENEWLINEclass TestMessage:NEWLINENEWLINE def test_json(self):NEWLINE resp = tutils.tdnsresp()NEWLINE json = resp.to_json()NEWLINE assert json["id"] == resp.idNEWLINE assert len(json["questions"]) == len(resp.questions)NEWLINE assert json["questions"][0]["name"] == resp.questions[0].nameNEWLINE assert len(json["answers"]) == len(resp.answers)NEWLINE assert json["answers"][0]["data"] == str(resp.answers[0])NEWLINENEWLINE def test_responses(self):NEWLINE req = tutils.tdnsreq()NEWLINE resp = tutils.tdnsresp()NEWLINE resp2 = req.succeed([NEWLINE dns.ResourceRecord.A("dns.google", ipaddress.IPv4Address("8.8.8.8"), ttl=32),NEWLINE dns.ResourceRecord.A("dns.google", ipaddress.IPv4Address("8.8.4.4"), ttl=32)NEWLINE ])NEWLINE resp2.timestamp = resp.timestampNEWLINE assert resp == resp2NEWLINE assert resp2.size == 8NEWLINE with pytest.raises(ValueError):NEWLINE req.fail(dns.response_codes.NOERROR)NEWLINE assert req.fail(dns.response_codes.FORMERR).response_code == dns.response_codes.FORMERRNEWLINENEWLINE def test_range(self):NEWLINE def test(what: str, min: int, max: int):NEWLINE req = tutils.tdnsreq()NEWLINE setattr(req, what, min)NEWLINE assert getattr(dns.Message.unpack(req.packed), what) == minNEWLINE setattr(req, what, min - 1)NEWLINE with pytest.raises(ValueError):NEWLINE req.packedNEWLINE setattr(req, what, max)NEWLINE assert getattr(dns.Message.unpack(req.packed), what) == maxNEWLINE setattr(req, what, max + 1)NEWLINE with pytest.raises(ValueError):NEWLINE req.packedNEWLINENEWLINE test("id", 0, 2 ** 16 - 1)NEWLINE test("reserved", 0, 7)NEWLINE test("op_code", 0, 0b1111)NEWLINE test("response_code", 0, 0b1111)NEWLINENEWLINE def test_packing(self):NEWLINE def assert_eq(m: dns.Message, b: bytes) -> None:NEWLINE m_b = dns.Message.unpack(b)NEWLINE m_b.timestamp = m.timestampNEWLINE assert m_b == mNEWLINE assert m_b.packed == m.packedNEWLINENEWLINE assert_eq(tutils.tdnsreq(), b'\x00\x2a\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03dns\x06google\x00\x00\x01\x00\x01')NEWLINE with pytest.raises(struct.error):NEWLINE dns.Message.unpack(b'\x00\x2a\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03dns\x06google\x00\x00\x01\x00\x01\x00')NEWLINE assert_eq(tutils.tdnsresp(), (NEWLINE b'\x00\x2a\x81\x80\x00\x01\x00\x02\x00\x00\x00\x00\x03dns\x06google\x00\x00\x01\x00\x01' +NEWLINE b'\xc0\x0c\x00\x01\x00\x01\x00\x00\x00 \x00\x04\x08\x08\x08\x08\xc0\x0c\x00\x01\x00\x01\x00\x00\x00 \x00\x04\x08\x08\x04\x04'NEWLINE ))NEWLINE with pytest.raises(struct.error): # question errorNEWLINE dns.Message.unpack(b'\x00\x2a\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03dns\x06goo')NEWLINE with pytest.raises(struct.error): # rr length errorNEWLINE dns.Message.unpack(NEWLINE b'\x00\x2a\x81\x80\x00\x01\x00\x02\x00\x00\x00\x00\x03dns\x06google\x00\x00\x01\x00\x01' +NEWLINE b'\xc0\x0c\x00\x01\x00\x01\x00\x00\x00 \x00\x04\x08\x08\x08\x08\xc0\x0c\x00\x01\x00\x01\x00\x00\x00 \x00\x04\x08\x08\x04'NEWLINE )NEWLINE txt = dns.Message.unpack(NEWLINE b'V\x1a\x81\x80\x00\x01\x00\x01\x00\x01\x00\x01\x05alive\x06github\x03com\x00\x00' +NEWLINE b'\x10\x00\x01\xc0\x0c\x00\x05\x00\x01\x00\x00\x0b\xc6\x00\x07\x04live\xc0\x12\xc0\x12\x00\x06\x00\x01' +NEWLINE b'\x00\x00\x03\x84\x00H\x07ns-1707\tawsdns-21\x02co\x02uk\x00\x11awsdns-hostmaster\x06amazon\xc0\x19\x00' +NEWLINE b'\x00\x00\x01\x00\x00\x1c \x00\x00\x03\x84\x00\x12u\x00\x00\x01Q\x80\x00\x00)\x02\x00\x00\x00\x00\x00\x00\x00'NEWLINE )NEWLINE assert txt.answers[0].domain_name == "live.github.com"NEWLINE invalid_rr_domain_name = dns.Message.unpack(NEWLINE b'V\x1a\x81\x80\x00\x01\x00\x01\x00\x01\x00\x01\x05alive\x06github\x03com\x00\x00' +NEWLINE b'\x10\x00\x01\xc0\x0c\x00\x05\x00\x01\x00\x00\x0b\xc6\x00\x07\x99live\xc0\x12\xc0\x12\x00\x06\x00\x01' +NEWLINE b'\x00\x00\x03\x84\x00H\x07ns-1707\tawsdns-21\x02co\x02uk\x00\x11awsdns-hostmaster\x06amazon\xc0\x19\x00' +NEWLINE b'\x00\x00\x01\x00\x00\x1c \x00\x00\x03\x84\x00\x12u\x00\x00\x01Q\x80\x00\x00)\x02\x00\x00\x00\x00\x00\x00\x00'NEWLINE )NEWLINE assert invalid_rr_domain_name.answers[0].data == b'\x99live\xc0\x12'NEWLINENEWLINE req = tutils.tdnsreq()NEWLINE for flag in "authoritative_answer", "truncation", "recursion_desired", "recursion_available":NEWLINE setattr(req, flag, True)NEWLINE assert getattr(dns.Message.unpack(req.packed), flag) is TrueNEWLINE setattr(req, flag, False)NEWLINE assert getattr(dns.Message.unpack(req.packed), flag) is FalseNEWLINENEWLINE def test_copy(self):NEWLINE msg = tutils.tdnsresp()NEWLINE assert dns.Message.from_state(msg.get_state()) == msgNEWLINE copy = msg.copy()NEWLINE assert copy is not msgNEWLINE assert copy != msgNEWLINE copy.id = msg.idNEWLINE assert copy == msgNEWLINE assert copy.questions is not msg.questionsNEWLINE assert copy.questions == msg.questionsNEWLINE assert copy.answers is not msg.answersNEWLINE assert copy.answers == msg.answersNEWLINE assert copy.authorities is not msg.authoritiesNEWLINE assert copy.authorities == msg.authoritiesNEWLINE assert copy.additionals is not msg.additionalsNEWLINE assert copy.additionals == msg.additionalsNEWLINENEWLINENEWLINEclass TestDNSFlow:NEWLINENEWLINE def test_copy(self):NEWLINE f = tflow.tdnsflow(resp=True)NEWLINE assert repr(f)NEWLINE f.get_state()NEWLINE f2 = f.copy()NEWLINE a = f.get_state()NEWLINE b = f2.get_state()NEWLINE del a["id"]NEWLINE del b["id"]NEWLINE assert a == bNEWLINE assert not f == f2NEWLINE assert f is not f2NEWLINENEWLINE assert f.request.get_state() == f2.request.get_state()NEWLINE assert f.request is not f2.requestNEWLINE assert f.request == f2.requestNEWLINE assert f.response is not f2.responseNEWLINE assert f.response.get_state() == f2.response.get_state()NEWLINE assert f.response == f2.responseNEWLINENEWLINE f = tflow.tdnsflow(err=True)NEWLINE f2 = f.copy()NEWLINE assert f is not f2NEWLINE assert f.request is not f2.requestNEWLINE assert f.request == f2.requestNEWLINE assert f.error.get_state() == f2.error.get_state()NEWLINE assert f.error is not f2.errorNEWLINENEWLINE def test_match(self):NEWLINE f = tflow.tdnsflow(resp=True)NEWLINE assert not flowfilter.match("~b nonexistent", f)NEWLINE assert flowfilter.match(None, f)NEWLINE assert flowfilter.match("~b dns.google", f)NEWLINE assert flowfilter.match("~b 8.8.8.8", f)NEWLINENEWLINE assert flowfilter.match("~bq dns.google", f)NEWLINE assert not flowfilter.match("~bq 8.8.8.8", f)NEWLINENEWLINE assert flowfilter.match("~bs dns.google", f)NEWLINE assert flowfilter.match("~bs 8.8.4.4", f)NEWLINENEWLINE assert flowfilter.match("~dns", f)NEWLINE assert not flowfilter.match("~dns", tflow.ttcpflow())NEWLINE assert not flowfilter.match("~dns", tflow.tflow())NEWLINENEWLINE f = tflow.tdnsflow(err=True)NEWLINE assert flowfilter.match("~e", f)NEWLINENEWLINE with pytest.raises(ValueError):NEWLINE flowfilter.match("~", f)NEWLINENEWLINE def test_repr(self):NEWLINE f = tflow.tdnsflow()NEWLINE assert 'DNSFlow' in repr(f)NEWLINE # Licensed under a 3-clause BSD style license - see LICENSE.rstNEWLINENEWLINE"""NEWLINEThis module provides utility functions for the models packageNEWLINE"""NEWLINENEWLINENEWLINEfrom collections import dequeNEWLINEfrom collections.abc import MutableMappingNEWLINEfrom inspect import signatureNEWLINENEWLINEimport numpy as npNEWLINENEWLINENEWLINEfrom ..utils import isiterable, check_broadcastNEWLINEfrom ..utils.compat import NUMPY_LT_1_14NEWLINENEWLINEfrom .. import units as uNEWLINENEWLINE__all__ = ['ExpressionTree', 'AliasDict', 'check_broadcast',NEWLINE 'poly_map_domain', 'comb', 'ellipse_extent']NEWLINENEWLINENEWLINEclass ExpressionTree:NEWLINE __slots__ = ['left', 'right', 'value', 'inputs', 'outputs']NEWLINENEWLINE def __init__(self, value, left=None, right=None, inputs=None, outputs=None):NEWLINE self.value = valueNEWLINE self.inputs = inputsNEWLINE self.outputs = outputsNEWLINE self.left = leftNEWLINENEWLINE # Two subtrees can't be the same *object* or else traverse_postorderNEWLINE # breaks, so we just always copy the right subtree to subvert that.NEWLINE if right is not None and left is right:NEWLINE right = right.copy()NEWLINENEWLINE self.right = rightNEWLINENEWLINE def __getstate__(self):NEWLINE # For some reason the default pickle protocol on Python 2 does not justNEWLINE # do this. On Python 3 it's not a problem.NEWLINE return dict((slot, getattr(self, slot)) for slot in self.__slots__)NEWLINENEWLINE def __setstate__(self, state):NEWLINE for slot, value in state.items():NEWLINE setattr(self, slot, value)NEWLINENEWLINE @staticmethodNEWLINE def _recursive_lookup(branch, adict, key):NEWLINE if isinstance(branch, ExpressionTree):NEWLINE return adict[key]NEWLINE else:NEWLINE return branch, keyNEWLINENEWLINE @propertyNEWLINE def inputs_map(self):NEWLINE """NEWLINE Map the names of the inputs to this ExpressionTree to the inputs to the leaf models.NEWLINE """NEWLINE inputs_map = {}NEWLINE if not isinstance(self.value, str): # If we don't have an operator the mapping is trivialNEWLINE return {inp: (self.value, inp) for inp in self.inputs}NEWLINENEWLINE elif self.value == '|':NEWLINE for inp in self.inputs:NEWLINE m, inp2 = self._recursive_lookup(self.left, self.left.inputs_map, inp)NEWLINE inputs_map[inp] = m, inp2NEWLINENEWLINE elif self.value == '&':NEWLINE for i, inp in enumerate(self.inputs):NEWLINE if i < len(self.left.inputs): # Get from leftNEWLINE m, inp2 = self._recursive_lookup(self.left,NEWLINE self.left.inputs_map,NEWLINE self.left.inputs[i])NEWLINE inputs_map[inp] = m, inp2NEWLINE else: # Get from rightNEWLINE m, inp2 = self._recursive_lookup(self.right,NEWLINE self.right.inputs_map,NEWLINE self.right.inputs[i - len(self.left.inputs)])NEWLINE inputs_map[inp] = m, inp2NEWLINENEWLINE else:NEWLINE for inp in self.left.inputs:NEWLINE m, inp2 = self._recursive_lookup(self.left, self.left.inputs_map, inp)NEWLINE inputs_map[inp] = m, inp2NEWLINENEWLINE return inputs_mapNEWLINENEWLINE @propertyNEWLINE def outputs_map(self):NEWLINE """NEWLINE Map the names of the outputs to this ExpressionTree to the outputs to the leaf models.NEWLINE """NEWLINE outputs_map = {}NEWLINE if not isinstance(self.value, str): # If we don't have an operator the mapping is trivialNEWLINE return {out: (self.value, out) for out in self.outputs}NEWLINENEWLINE elif self.value == '|':NEWLINE for out in self.outputs:NEWLINE m, out2 = self._recursive_lookup(self.right, self.right.outputs_map, out)NEWLINE outputs_map[out] = m, out2NEWLINENEWLINE elif self.value == '&':NEWLINE for i, out in enumerate(self.outputs):NEWLINE if i < len(self.left.outputs): # Get from leftNEWLINE m, out2 = self._recursive_lookup(self.left,NEWLINE self.left.outputs_map,NEWLINE self.left.outputs[i])NEWLINE outputs_map[out] = m, out2NEWLINE else: # Get from rightNEWLINE m, out2 = self._recursive_lookup(self.right,NEWLINE self.right.outputs_map,NEWLINE self.right.outputs[i - len(self.left.outputs)])NEWLINE outputs_map[out] = m, out2NEWLINENEWLINE else:NEWLINE for out in self.left.outputs:NEWLINE m, out2 = self._recursive_lookup(self.left, self.left.outputs_map, out)NEWLINE outputs_map[out] = m, out2NEWLINENEWLINE return outputs_mapNEWLINENEWLINE @propertyNEWLINE def isleaf(self):NEWLINE return self.left is None and self.right is NoneNEWLINENEWLINE def traverse_preorder(self):NEWLINE stack = deque([self])NEWLINE while stack:NEWLINE node = stack.pop()NEWLINE yield nodeNEWLINENEWLINE if node.right is not None:NEWLINE stack.append(node.right)NEWLINE if node.left is not None:NEWLINE stack.append(node.left)NEWLINENEWLINE def traverse_inorder(self):NEWLINE stack = deque()NEWLINE node = selfNEWLINE while stack or node is not None:NEWLINE if node is not None:NEWLINE stack.append(node)NEWLINE node = node.leftNEWLINE else:NEWLINE node = stack.pop()NEWLINE yield nodeNEWLINE node = node.rightNEWLINENEWLINE def traverse_postorder(self):NEWLINE stack = deque([self])NEWLINE last = NoneNEWLINE while stack:NEWLINE node = stack[-1]NEWLINE if last is None or node is last.left or node is last.right:NEWLINE if node.left is not None:NEWLINE stack.append(node.left)NEWLINE elif node.right is not None:NEWLINE stack.append(node.right)NEWLINE elif node.left is last and node.right is not None:NEWLINE stack.append(node.right)NEWLINE else:NEWLINE yield stack.pop()NEWLINE last = nodeNEWLINENEWLINE def evaluate(self, operators, getter=None, start=0, stop=None):NEWLINE """Evaluate the expression represented by this tree.NEWLINENEWLINE ``Operators`` should be a dictionary mapping operator names ('tensor',NEWLINE 'product', etc.) to a function that implements that operator for theNEWLINE correct number of operands.NEWLINENEWLINE If given, ``getter`` is a function evaluated on each *leaf* node'sNEWLINE value before applying the operator between them. This could be used,NEWLINE for example, to operate on an attribute of the node values rather thanNEWLINE directly on the node values. The ``getter`` is passed both the indexNEWLINE of the leaf (a count starting at 0 that is incremented after each leafNEWLINE is found) and the leaf node itself.NEWLINENEWLINE The ``start`` and ``stop`` arguments allow evaluating a sub-expressionNEWLINE within the expression tree.NEWLINENEWLINE TODO: Document this better.NEWLINE """NEWLINENEWLINE stack = deque()NEWLINENEWLINE if getter is None:NEWLINE getter = lambda idx, value: valueNEWLINENEWLINE if start is None:NEWLINE start = 0NEWLINENEWLINE leaf_idx = 0NEWLINE for node in self.traverse_postorder():NEWLINE if node.isleaf:NEWLINE # For a "tree" containing just a single operator at the rootNEWLINE # Also push the index of this leaf onto the stack, which willNEWLINE # prove useful for evaluating subexpressionsNEWLINE stack.append((getter(leaf_idx, node.value), leaf_idx))NEWLINE leaf_idx += 1NEWLINE else:NEWLINE operator = operators[node.value]NEWLINENEWLINE if len(stack) < 2:NEWLINE # Skip this operator if there are not enough operands onNEWLINE # the stack; this can happen if some operands were skippedNEWLINE # when evaluating a sub-expressionNEWLINE continueNEWLINENEWLINE right = stack.pop()NEWLINE left = stack.pop()NEWLINE operands = []NEWLINENEWLINE for operand in (left, right):NEWLINE # idx is the leaf index; -1 if not a leaf nodeNEWLINE if operand[-1] == -1:NEWLINE operands.append(operand)NEWLINE else:NEWLINE operand, idx = operandNEWLINE if start <= idx and (stop is None or idx < stop):NEWLINE operands.append((operand, idx))NEWLINENEWLINE if len(operands) == 2:NEWLINE # evaluate the operator with the given operands and placeNEWLINE # the result on the stack (with -1 for the "leaf index"NEWLINE # since this result is not a leaf nodeNEWLINE left, right = operandsNEWLINE stack.append((operator(left[0], right[0]), -1))NEWLINE elif len(operands) == 0:NEWLINE # Just push the left one back on the stackNEWLINE # TODO: Explain and/or refactor this betterNEWLINE # This is here because even if both operands were "skipped"NEWLINE # due to being outside the (start, stop) range, we've onlyNEWLINE # skipped one operator. But there should be at least 2NEWLINE # operators involving these operands, so we push the oneNEWLINE # from the left back onto the stack so that the nextNEWLINE # operator will be skipped as well. Should probably comeNEWLINE # up with an easier to follow way to write this algorithmNEWLINE stack.append(left)NEWLINE else:NEWLINE # one or more of the operands was not included in theNEWLINE # sub-expression slice, so don't evaluate the operator;NEWLINE # instead place left over operands (if any) back on theNEWLINE # stack for later useNEWLINE stack.extend(operands)NEWLINENEWLINE return stack.pop()[0]NEWLINENEWLINE def copy(self):NEWLINE # Hopefully this won't blow the stack for any practical case; if such aNEWLINE # case arises that this won't work then I suppose we can find anNEWLINE # iterative approach.NEWLINENEWLINE children = []NEWLINE for child in (self.left, self.right):NEWLINE if isinstance(child, ExpressionTree):NEWLINE children.append(child.copy())NEWLINE else:NEWLINE children.append(child)NEWLINENEWLINE return self.__class__(self.value, left=children[0], right=children[1])NEWLINENEWLINE def format_expression(self, operator_precedence, format_leaf=None):NEWLINE leaf_idx = 0NEWLINE operands = deque()NEWLINENEWLINE if format_leaf is None:NEWLINE format_leaf = lambda i, l: '[{0}]'.format(i)NEWLINENEWLINE for node in self.traverse_postorder():NEWLINE if node.isleaf:NEWLINE operands.append(format_leaf(leaf_idx, node))NEWLINE leaf_idx += 1NEWLINE continueNEWLINENEWLINE oper_order = operator_precedence[node.value]NEWLINE right = operands.pop()NEWLINE left = operands.pop()NEWLINENEWLINE if (node.left is not None and not node.left.isleaf andNEWLINE operator_precedence[node.left.value] < oper_order):NEWLINE left = '({0})'.format(left)NEWLINE if (node.right is not None and not node.right.isleaf andNEWLINE operator_precedence[node.right.value] < oper_order):NEWLINE right = '({0})'.format(right)NEWLINENEWLINE operands.append(' '.join((left, node.value, right)))NEWLINENEWLINE return ''.join(operands)NEWLINENEWLINENEWLINEclass AliasDict(MutableMapping):NEWLINE """NEWLINE Creates a `dict` like object that wraps an existing `dict` or otherNEWLINE `MutableMapping`, along with a `dict` of *key aliases* that translateNEWLINE between specific keys in this dict to different keys in the underlyingNEWLINE dict.NEWLINENEWLINE In other words, keys that do not have an associated alias are accessed andNEWLINE stored like a normal `dict`. However, a key that has an alias is accessedNEWLINE and stored to the "parent" dict via the alias.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE parent : dict-likeNEWLINE The parent `dict` that aliased keys and accessed from and stored to.NEWLINENEWLINE aliases : dict-likeNEWLINE Maps keys in this dict to their associated keys in the parent dict.NEWLINENEWLINE ExamplesNEWLINE --------NEWLINENEWLINE >>> parent = {'a': 1, 'b': 2, 'c': 3}NEWLINE >>> aliases = {'foo': 'a', 'bar': 'c'}NEWLINE >>> alias_dict = AliasDict(parent, aliases)NEWLINE >>> alias_dict['foo']NEWLINE 1NEWLINE >>> alias_dict['bar']NEWLINE 3NEWLINENEWLINE Keys in the original parent dict are not visible if they were notNEWLINE aliased::NEWLINENEWLINE >>> alias_dict['b']NEWLINE Traceback (most recent call last):NEWLINE ...NEWLINE KeyError: 'b'NEWLINENEWLINE Likewise, updates to aliased keys are reflected back in the parent dict::NEWLINENEWLINE >>> alias_dict['foo'] = 42NEWLINE >>> alias_dict['foo']NEWLINE 42NEWLINE >>> parent['a']NEWLINE 42NEWLINENEWLINE However, updates/insertions to keys that are *not* aliased are notNEWLINE reflected in the parent dict::NEWLINENEWLINE >>> alias_dict['qux'] = 99NEWLINE >>> alias_dict['qux']NEWLINE 99NEWLINE >>> 'qux' in parentNEWLINE FalseNEWLINENEWLINE In particular, updates on the `AliasDict` to a key that is equal toNEWLINE one of the aliased keys in the parent dict does *not* update the parentNEWLINE dict. For example, ``alias_dict`` aliases ``'foo'`` to ``'a'``. ButNEWLINE assigning to a key ``'a'`` on the `AliasDict` does not impact theNEWLINE parent::NEWLINENEWLINE >>> alias_dict['a'] = 'nope'NEWLINE >>> alias_dict['a']NEWLINE 'nope'NEWLINE >>> parent['a']NEWLINE 42NEWLINE """NEWLINENEWLINE _store_type = dictNEWLINE """NEWLINE Subclasses may override this to use other mapping types as the underlyingNEWLINE storage, for example an `OrderedDict`. However, even in this caseNEWLINE additional work may be needed to get things like the ordering right.NEWLINE """NEWLINENEWLINE def __init__(self, parent, aliases):NEWLINE self._parent = parentNEWLINE self._store = self._store_type()NEWLINE self._aliases = dict(aliases)NEWLINENEWLINE def __getitem__(self, key):NEWLINE if key in self._aliases:NEWLINE try:NEWLINE return self._parent[self._aliases[key]]NEWLINE except KeyError:NEWLINE raise KeyError(key)NEWLINENEWLINE return self._store[key]NEWLINENEWLINE def __setitem__(self, key, value):NEWLINE if key in self._aliases:NEWLINE self._parent[self._aliases[key]] = valueNEWLINE else:NEWLINE self._store[key] = valueNEWLINENEWLINE def __delitem__(self, key):NEWLINE if key in self._aliases:NEWLINE try:NEWLINE del self._parent[self._aliases[key]]NEWLINE except KeyError:NEWLINE raise KeyError(key)NEWLINE else:NEWLINE del self._store[key]NEWLINENEWLINE def __iter__(self):NEWLINE """NEWLINE First iterates over keys from the parent dict (if the aliased keys areNEWLINE present in the parent), followed by any keys in the local store.NEWLINE """NEWLINENEWLINE for key, alias in self._aliases.items():NEWLINE if alias in self._parent:NEWLINE yield keyNEWLINENEWLINE for key in self._store:NEWLINE yield keyNEWLINENEWLINE def __len__(self):NEWLINE # TODO:NEWLINE # This could be done more efficiently, but at present the use case forNEWLINE # it is narrow if non-existent.NEWLINE return len(list(iter(self)))NEWLINENEWLINE def __repr__(self):NEWLINE # repr() just like any other dict--this should look transparentNEWLINE store_copy = self._store_type()NEWLINE for key, alias in self._aliases.items():NEWLINE if alias in self._parent:NEWLINE store_copy[key] = self._parent[alias]NEWLINENEWLINE store_copy.update(self._store)NEWLINENEWLINE return repr(store_copy)NEWLINENEWLINENEWLINEclass _BoundingBox(tuple):NEWLINE """NEWLINE Base class for models with custom bounding box templates (methods thatNEWLINE return an actual bounding box tuple given some adjustable parameters--seeNEWLINE for example `~astropy.modeling.models.Gaussian1D.bounding_box`).NEWLINENEWLINE On these classes the ``bounding_box`` property still returns a `tuple`NEWLINE giving the default bounding box for that instance of the model. But thatNEWLINE tuple may also be a subclass of this class that is callable, and allowsNEWLINE a new tuple to be returned using a user-supplied value for any adjustableNEWLINE parameters to the bounding box.NEWLINE """NEWLINENEWLINE _model = NoneNEWLINENEWLINE def __new__(cls, input_, _model=None):NEWLINE self = super().__new__(cls, input_)NEWLINE if _model is not None:NEWLINE # Bind this _BoundingBox (most likely a subclass) to a ModelNEWLINE # instance so that its __call__ can access the modelNEWLINE self._model = _modelNEWLINENEWLINE return selfNEWLINENEWLINE def __call__(self, *args, **kwargs):NEWLINE raise NotImplementedError(NEWLINE "This bounding box is fixed by the model and does not have "NEWLINE "adjustable parameters.")NEWLINENEWLINE @classmethodNEWLINE def validate(cls, model, bounding_box):NEWLINE """NEWLINE Validate a given bounding box sequence against the given model (whichNEWLINE may be either a subclass of `~astropy.modeling.Model` or an instanceNEWLINE thereof, so long as the ``.inputs`` attribute is defined.NEWLINENEWLINE Currently this just checks that the bounding_box is either a 2-tupleNEWLINE of lower and upper bounds for 1-D models, or an N-tuple of 2-tuplesNEWLINE for N-D models.NEWLINENEWLINE This also returns a normalized version of the bounding_box input toNEWLINE ensure it is always an N-tuple (even for the 1-D case).NEWLINE """NEWLINENEWLINE nd = model.n_inputsNEWLINENEWLINE if nd == 1:NEWLINE if (not isiterable(bounding_box)NEWLINE or np.shape(bounding_box) not in ((2,), (1, 2))):NEWLINE raise ValueError(NEWLINE "Bounding box for {0} model must be a sequence of length "NEWLINE "2 consisting of a lower and upper bound, or a 1-tuple "NEWLINE "containing such a sequence as its sole element.".format(NEWLINE model.name))NEWLINENEWLINE if len(bounding_box) == 1:NEWLINE return cls((tuple(bounding_box[0]),))NEWLINE else:NEWLINE return cls(tuple(bounding_box))NEWLINE else:NEWLINE if (not isiterable(bounding_box)NEWLINE or np.shape(bounding_box) != (nd, 2)):NEWLINE raise ValueError(NEWLINE "Bounding box for {0} model must be a sequence of length "NEWLINE "{1} (the number of model inputs) consisting of pairs of "NEWLINE "lower and upper bounds for those inputs on which to "NEWLINE "evaluate the model.".format(model.name, nd))NEWLINENEWLINE return cls(tuple(bounds) for bounds in bounding_box)NEWLINENEWLINENEWLINEdef make_binary_operator_eval(oper, f, g):NEWLINE """NEWLINE Given a binary operator (as a callable of two arguments) ``oper`` andNEWLINE two callables ``f`` and ``g`` which accept the same arguments,NEWLINE returns a *new* function that takes the same arguments as ``f`` and ``g``,NEWLINE but passes the outputs of ``f`` and ``g`` in the given ``oper``.NEWLINENEWLINE ``f`` and ``g`` are assumed to return tuples (which may be 1-tuples). TheNEWLINE given operator is applied element-wise to tuple outputs).NEWLINENEWLINE ExampleNEWLINE -------NEWLINENEWLINE >>> from operator import addNEWLINE >>> def prod(x, y):NEWLINE ... return (x * y,)NEWLINE ...NEWLINE >>> sum_of_prod = make_binary_operator_eval(add, prod, prod)NEWLINE >>> sum_of_prod(3, 5)NEWLINE (30,)NEWLINE """NEWLINENEWLINE return lambda inputs, params: \NEWLINE tuple(oper(x, y) for x, y in zip(f(inputs, params),NEWLINE g(inputs, params)))NEWLINENEWLINENEWLINEdef poly_map_domain(oldx, domain, window):NEWLINE """NEWLINE Map domain into window by shifting and scaling.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE oldx : arrayNEWLINE original coordinatesNEWLINE domain : list or tuple of length 2NEWLINE function domainNEWLINE window : list or tuple of length 2NEWLINE range into which to map the domainNEWLINE """NEWLINE domain = np.array(domain, dtype=np.float64)NEWLINE window = np.array(window, dtype=np.float64)NEWLINE scl = (window[1] - window[0]) / (domain[1] - domain[0])NEWLINE off = (window[0] * domain[1] - window[1] * domain[0]) / (domain[1] - domain[0])NEWLINE return off + scl * oldxNEWLINENEWLINENEWLINEdef comb(N, k):NEWLINE """NEWLINE The number of combinations of N things taken k at a time.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE N : int, arrayNEWLINE Number of things.NEWLINE k : int, arrayNEWLINE Number of elements taken.NEWLINENEWLINE """NEWLINE if (k > N) or (N < 0) or (k < 0):NEWLINE return 0NEWLINE val = 1NEWLINE for j in range(min(k, N - k)):NEWLINE val = (val * (N - j)) / (j + 1)NEWLINE return valNEWLINENEWLINENEWLINEdef array_repr_oneline(array):NEWLINE """NEWLINE Represents a multi-dimensional Numpy array flattened onto a single line.NEWLINE """NEWLINE sep = ',' if NUMPY_LT_1_14 else ', 'NEWLINE r = np.array2string(array, separator=sep, suppress_small=True)NEWLINE return ' '.join(l.strip() for l in r.splitlines())NEWLINENEWLINENEWLINEdef combine_labels(left, right):NEWLINE """NEWLINE For use with the join operator &: Combine left input/output labels withNEWLINE right input/output labels.NEWLINENEWLINE If none of the labels conflict then this just returns a sum of tuples.NEWLINE However if *any* of the labels conflict, this appends '0' to the left-handNEWLINE labels and '1' to the right-hand labels so there is no ambiguity).NEWLINE """NEWLINENEWLINE if set(left).intersection(right):NEWLINE left = tuple(l + '0' for l in left)NEWLINE right = tuple(r + '1' for r in right)NEWLINENEWLINE return left + rightNEWLINENEWLINENEWLINEdef ellipse_extent(a, b, theta):NEWLINE """NEWLINE Calculates the extent of a box encapsulating a rotated 2D ellipse.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE a : float or `~astropy.units.Quantity`NEWLINE Major axis.NEWLINE b : float or `~astropy.units.Quantity`NEWLINE Minor axis.NEWLINE theta : float or `~astropy.units.Quantity`NEWLINE Rotation angle. If given as a floating-point value, it is assumed to beNEWLINE in radians.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE offsets : tupleNEWLINE The absolute value of the offset distances from the ellipse center thatNEWLINE define its bounding box region, ``(dx, dy)``.NEWLINENEWLINE ExamplesNEWLINE --------NEWLINE .. plot::NEWLINE :include-source:NEWLINENEWLINE import numpy as npNEWLINE import matplotlib.pyplot as pltNEWLINE from astropy.modeling.models import Ellipse2DNEWLINE from astropy.modeling.utils import ellipse_extent, render_modelNEWLINENEWLINE amplitude = 1NEWLINE x0 = 50NEWLINE y0 = 50NEWLINE a = 30NEWLINE b = 10NEWLINE theta = np.pi/4NEWLINENEWLINE model = Ellipse2D(amplitude, x0, y0, a, b, theta)NEWLINENEWLINE dx, dy = ellipse_extent(a, b, theta)NEWLINENEWLINE limits = [x0 - dx, x0 + dx, y0 - dy, y0 + dy]NEWLINENEWLINE model.bounding_box = limitsNEWLINENEWLINE image = render_model(model)NEWLINENEWLINE plt.imshow(image, cmap='binary', interpolation='nearest', alpha=.5,NEWLINE extent = limits)NEWLINE plt.show()NEWLINE """NEWLINENEWLINE t = np.arctan2(-b * np.tan(theta), a)NEWLINE dx = a * np.cos(t) * np.cos(theta) - b * np.sin(t) * np.sin(theta)NEWLINENEWLINE t = np.arctan2(b, a * np.tan(theta))NEWLINE dy = b * np.sin(t) * np.cos(theta) + a * np.cos(t) * np.sin(theta)NEWLINENEWLINE if isinstance(dx, u.Quantity) or isinstance(dy, u.Quantity):NEWLINE return np.abs(u.Quantity([dx, dy]))NEWLINE else:NEWLINE return np.abs([dx, dy])NEWLINENEWLINENEWLINEdef get_inputs_and_params(func):NEWLINE """NEWLINE Given a callable, determine the input variables and theNEWLINE parameters.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE func : callableNEWLINENEWLINE ReturnsNEWLINE -------NEWLINE inputs, params : tupleNEWLINE Each entry is a list of inspect.Parameter objectsNEWLINE """NEWLINE sig = signature(func)NEWLINENEWLINE inputs = []NEWLINE params = []NEWLINE for param in sig.parameters.values():NEWLINE if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):NEWLINE raise ValueError("Signature must not have *args or **kwargs")NEWLINE if param.default == param.empty:NEWLINE inputs.append(param)NEWLINE else:NEWLINE params.append(param)NEWLINENEWLINE return inputs, paramsNEWLINENEWLINENEWLINEdef _parameter_with_unit(parameter, unit):NEWLINE if parameter.unit is None:NEWLINE return parameter.value * unitNEWLINE else:NEWLINE return parameter.quantity.to(unit)NEWLINENEWLINENEWLINEdef _parameter_without_unit(value, old_unit, new_unit):NEWLINE if old_unit is None:NEWLINE return valueNEWLINE else:NEWLINE return value * old_unit.to(new_unit)NEWLINENEWLINENEWLINEdef _combine_equivalency_dict(keys, eq1=None, eq2=None):NEWLINE # Given two dictionaries that give equivalencies for a set of keys, forNEWLINE # example input value names, return a dictionary that includes all theNEWLINE # equivalenciesNEWLINE eq = {}NEWLINE for key in keys:NEWLINE eq[key] = []NEWLINE if eq1 is not None and key in eq1:NEWLINE eq[key].extend(eq1[key])NEWLINE if eq2 is not None and key in eq2:NEWLINE eq[key].extend(eq2[key])NEWLINE return eqNEWLINENEWLINENEWLINEdef _to_radian(value):NEWLINE """ Convert ``value`` to radian. """NEWLINE if isinstance(value, u.Quantity):NEWLINE return value.to(u.rad)NEWLINE else:NEWLINE return np.deg2rad(value)NEWLINENEWLINENEWLINEdef _to_orig_unit(value, raw_unit=None, orig_unit=None):NEWLINE """ Convert value with ``raw_unit`` to ``orig_unit``. """NEWLINE if raw_unit is not None:NEWLINE return (value * raw_unit).to(orig_unit)NEWLINE else:NEWLINE return np.rad2deg(value)NEWLINE """boon-backend URL ConfigurationNEWLINENEWLINEThe `urlpatterns` list routes URLs to views. For more information please see:NEWLINE https://docs.djangoproject.com/en/3.2/topics/http/urls/NEWLINEExamples:NEWLINEFunction viewsNEWLINE 1. Add an import: from my_app import viewsNEWLINE 2. Add a URL to urlpatterns: path('', views.home, name='home')NEWLINEClass-based viewsNEWLINE 1. Add an import: from other_app.views import HomeNEWLINE 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')NEWLINEIncluding another URLconfNEWLINE 1. Import the include() function: from django.urls import include, pathNEWLINE 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))NEWLINE"""NEWLINEfrom django.contrib import adminNEWLINEfrom django.urls import pathNEWLINENEWLINEurlpatterns = [NEWLINE path('admin/', admin.site.urls),NEWLINE]NEWLINE # Try getting setup from setuptools first, then distutils.core.NEWLINE# http://goo.gl/BC32zk (StackOverflow)NEWLINEtry:NEWLINE from setuptools import setupNEWLINEexcept ImportError:NEWLINE from distutils.core import setupNEWLINENEWLINEclassifiers = [NEWLINE 'Development Status :: 3 - Alpha',NEWLINE 'Intended Audience :: Science/Research',NEWLINE 'License :: OSI Approved :: MIT License',NEWLINE 'Operating System :: OS Independent',NEWLINE 'Programming Language :: Python',NEWLINE 'Programming Language :: Python :: 2',NEWLINE 'Programming Language :: Python :: 3',NEWLINE 'Topic :: Scientific/Engineering :: Visualization'NEWLINE ]NEWLINENEWLINEsetup(NEWLINE name = "quickplot",NEWLINE packages = ['quickplot'],NEWLINE version = "0.1.2",NEWLINE description = "The batteries-included plotting wrapper for matplotlib",NEWLINE author = "Ken Sheedlo",NEWLINE author_email = "ovrkenthousand@gmail.com",NEWLINE url = "https://github.com/ksheedlo/quickplot",NEWLINE download_url = "https://github.com/ksheedlo/quickplot/archive/master.zip",NEWLINE classifiers = classifiers,NEWLINE dependency_links = ['https://github.com/matplotlib/matplotlib/tarball/v1.3.x#egg=matplotlib-1.3.0'],NEWLINE install_requires = [NEWLINE "numpy >= 1.5.0",NEWLINE "matplotlib >= 1.3.0"NEWLINE ]NEWLINE )NEWLINE #!/usr/bin/env pythonNEWLINE# -*- coding: utf-8 -*-NEWLINE#NEWLINE# Project: Fast Azimuthal integrationNEWLINE# https://github.com/silx-kit/pyFAINEWLINE#NEWLINE# Copyright (C) 2017-2019 European Synchrotron Radiation Facility, Grenoble, FranceNEWLINE#NEWLINE# Principal author: Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)NEWLINE#NEWLINE# Permission is hereby granted, free of charge, to any person obtaining a copyNEWLINE# of this software and associated documentation files (the "Software"), to dealNEWLINE# in the Software without restriction, including without limitation the rightsNEWLINE# to use, copy, modify, merge, publish, distribute, sublicense, and/or sellNEWLINE# copies of the Software, and to permit persons to whom the Software isNEWLINE# furnished to do so, subject to the following conditions:NEWLINE# .NEWLINE# The above copyright notice and this permission notice shall be included inNEWLINE# all copies or substantial portions of the Software.NEWLINE# .NEWLINE# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORNEWLINE# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,NEWLINE# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THENEWLINE# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERNEWLINE# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,NEWLINE# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INNEWLINE# THE SOFTWARE.NEWLINENEWLINE"""Everything you need to calibrate a detector mounted on a goniometer or anyNEWLINEtranslation tableNEWLINE"""NEWLINENEWLINEfrom __future__ import absolute_import, print_function, with_statement, divisionNEWLINENEWLINE__author__ = "Jérôme Kieffer"NEWLINE__contact__ = "Jerome.Kieffer@ESRF.eu"NEWLINE__license__ = "MIT"NEWLINE__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"NEWLINE__date__ = "22/08/2018"NEWLINE__status__ = "development"NEWLINE__docformat__ = 'restructuredtext'NEWLINENEWLINENEWLINEimport osNEWLINEimport loggingNEWLINEimport jsonNEWLINEimport numpyNEWLINEfrom collections import OrderedDict, namedtupleNEWLINEfrom scipy.optimize import minimizeNEWLINEfrom silx.image import marchingsquaresNEWLINEfrom .massif import MassifNEWLINEfrom .control_points import ControlPointsNEWLINEfrom .detectors import detector_factory, DetectorNEWLINEfrom .geometry import GeometryNEWLINEfrom .geometryRefinement import GeometryRefinementNEWLINEfrom .azimuthalIntegrator import AzimuthalIntegratorNEWLINEfrom .utils import StringTypesNEWLINEfrom .multi_geometry import MultiGeometryNEWLINEfrom .units import CONST_hc, CONST_qNEWLINENEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINEtry:NEWLINE import numexprNEWLINEexcept ImportError:NEWLINE logger.debug("Backtrace", exc_info=True)NEWLINE numexpr = NoneNEWLINENEWLINE# Parameter set used in PyFAI:NEWLINEPoniParam = namedtuple("PoniParam", ["dist", "poni1", "poni2", "rot1", "rot2", "rot3"])NEWLINENEWLINENEWLINEclass BaseTransformation(object):NEWLINE """This class, once instanciated, behaves like a function (via the __call__NEWLINE method). It is responsible for taking any input geometry and translate itNEWLINE into a set of parameters compatible with pyFAI, i.e. a tuple with:NEWLINE (dist, poni1, poni2, rot1, rot2, rot3)NEWLINENEWLINE This class relies on a user provided function which does the work.NEWLINE """NEWLINE def __init__(self, funct, param_names, pos_names=None):NEWLINE """Constructor of the classNEWLINENEWLINE :param funct: function which takes as parameter the param_names and the pos_nameNEWLINE :param param_names: list of names of the parameters used in the modelNEWLINE :param pos_names: list of motor names for gonio with >1 degree of freedomNEWLINE """NEWLINE self.callable = functNEWLINE self.variables = {}NEWLINE self.param_names = tuple(param_names)NEWLINE if pos_names is not None:NEWLINE self.pos_names = tuple(pos_names)NEWLINE else:NEWLINE self.pos_names = ("pos",)NEWLINE for key in self.param_names + self.pos_names:NEWLINE if key in self.variables:NEWLINE raise RuntimeError("The keyword %s is already defined, please chose another variable name")NEWLINE self.variables[key] = numpy.NaNNEWLINE self.codes = []NEWLINENEWLINE def __call__(self, param, pos):NEWLINE """This makes the class instance behave like a function,NEWLINE actually a function that translates the n-parameter of the detectorNEWLINE positioning on the goniometer and the m-parameters.NEWLINE :param param: parameter of the fitNEWLINE :param pos: position of the goniometer (representation from theNEWLINE goniometer)NEWLINE :return: 6-tuple with (dist, poni1, poni2, rot1, rot2, rot3) as neededNEWLINE for pyFAI.NEWLINE """NEWLINE variables = self.variables.copy()NEWLINE for name, value in zip(self.param_names, param):NEWLINE variables[name] = valueNEWLINE if len(self.pos_names) == 1:NEWLINE variables[self.pos_names[0]] = posNEWLINE else:NEWLINE for name, value in zip(self.pos_names, pos):NEWLINE variables[name] = valueNEWLINENEWLINE res = self.callable(**variables)NEWLINE return PoniParam(*res)NEWLINENEWLINE def __repr__(self):NEWLINE return "BaseTransformation with param: %s and pos: %s" % (self.param_names, self.pos_names)NEWLINENEWLINE def to_dict(self):NEWLINE """Export the instance representation for serialization as a dictionaryNEWLINE """NEWLINE raise RuntimeError("BaseTransformation is not serializable")NEWLINENEWLINENEWLINEclass GeometryTransformation(object):NEWLINE """This class, once instanciated, behaves like a function (via the __call__NEWLINE method). It is responsible for taking any input geometry and translate itNEWLINE into a set of parameters compatible with pyFAI, i.e. a tuple with:NEWLINE (dist, poni1, poni2, rot1, rot2, rot3)NEWLINE This function uses numexpr for formula evaluation.NEWLINE """NEWLINE def __init__(self, dist_expr, poni1_expr, poni2_expr,NEWLINE rot1_expr, rot2_expr, rot3_expr,NEWLINE param_names, pos_names=None, constants=None,NEWLINE content=None):NEWLINE """Constructor of the classNEWLINENEWLINE :param dist_expr: formula (as string) providing with the distNEWLINE :param poni1_expr: formula (as string) providing with the poni1NEWLINE :param poni2_expr: formula (as string) providing with the poni2NEWLINE :param rot1_expr: formula (as string) providing with the rot1NEWLINE :param rot2_expr: formula (as string) providing with the rot2NEWLINE :param rot3_expr: formula (as string) providing with the rot3NEWLINE :param param_names: list of names of the parameters used in the modelNEWLINE :param pos_names: list of motor names for gonio with >1 degree of freedomNEWLINE :param constants: a dictionary with some constants the user may want to useNEWLINE :param content: Should be None or the name of the class (may be usedNEWLINE in the future to dispatch to multiple derivative classes)NEWLINE """NEWLINE if content is not None:NEWLINE # Ensures we use the constructor of the right classNEWLINE assert content in (self.__class__.__name__, "GeometryTransformation")NEWLINE if numexpr is None:NEWLINE raise RuntimeError("Geometry translation requires the *numexpr* package")NEWLINE self.dist_expr = dist_exprNEWLINE self.poni1_expr = poni1_exprNEWLINE self.poni2_expr = poni2_exprNEWLINE self.rot1_expr = rot1_exprNEWLINE self.rot2_expr = rot2_exprNEWLINE self.rot3_expr = rot3_exprNEWLINENEWLINE self.variables = {"pi": numpy.pi}NEWLINE if constants is not None:NEWLINE self.variables.update(constants)NEWLINENEWLINE self.param_names = tuple(param_names)NEWLINE if pos_names is not None:NEWLINE self.pos_names = tuple(pos_names)NEWLINE else:NEWLINE self.pos_names = ("pos",)NEWLINE for key in self.param_names + self.pos_names:NEWLINE if key in self.variables:NEWLINE raise RuntimeError("The keyword %s is already defined, please chose another variable name")NEWLINE self.variables[key] = numpy.NaNNEWLINENEWLINE self.codes = [numexpr.NumExpr(expr) for expr in (self.dist_expr, self.poni1_expr, self.poni2_expr,NEWLINE self.rot1_expr, self.rot2_expr, self.rot3_expr)]NEWLINENEWLINE def __call__(self, param, pos):NEWLINE """This makes the class instance behave like a function,NEWLINE actually a function that translates the n-parameter of the detectorNEWLINE positioning on the goniometer and the m-parameters.NEWLINE :param param: parameter of the fitNEWLINE :param pos: position of the goniometer (representation from theNEWLINE goniometer)NEWLINE :return: 6-tuple with (dist, poni1, poni2, rot1, rot2, rot3) as neededNEWLINE for pyFAI.NEWLINE """NEWLINE res = []NEWLINE variables = self.variables.copy()NEWLINE for name, value in zip(self.param_names, param):NEWLINE variables[name] = valueNEWLINE if len(self.pos_names) == 1:NEWLINE variables[self.pos_names[0]] = posNEWLINE else:NEWLINE for name, value in zip(self.pos_names, pos):NEWLINE variables[name] = valueNEWLINE for code in self.codes:NEWLINE signa = [variables.get(name, numpy.NaN) for name in code.input_names]NEWLINE res.append(float(code(*signa)))NEWLINE # could ne done in a single liner but harder to understand !NEWLINE return PoniParam(*res)NEWLINENEWLINE def __repr__(self):NEWLINE res = ["GeometryTransformation with param: %s and pos: %s" % (self.param_names, self.pos_names),NEWLINE " dist= %s" % self.dist_expr,NEWLINE " poni1= %s" % self.poni1_expr,NEWLINE " poni2= %s" % self.poni2_expr,NEWLINE " rot1= %s" % self.rot1_expr,NEWLINE " rot2= %s" % self.rot2_expr,NEWLINE " rot3= %s" % self.rot3_expr]NEWLINE return os.linesep.join(res)NEWLINENEWLINE def to_dict(self):NEWLINE """Export the instance representation for serialization as a dictionaryNEWLINE """NEWLINE res = OrderedDict([("content", self.__class__.__name__),NEWLINE ("param_names", self.param_names),NEWLINE ("pos_names", self.pos_names),NEWLINE ("dist_expr", self.dist_expr),NEWLINE ("poni1_expr", self.poni1_expr),NEWLINE ("poni2_expr", self.poni2_expr),NEWLINE ("rot1_expr", self.rot1_expr),NEWLINE ("rot2_expr", self.rot2_expr),NEWLINE ("rot3_expr", self.rot3_expr),NEWLINE ])NEWLINE constants = OrderedDict()NEWLINE for key, val in self.variables.items():NEWLINE if key in self.param_names:NEWLINE continueNEWLINE if self.pos_names and key in self.pos_names:NEWLINE continueNEWLINE constants[key] = valNEWLINE res["constants"] = constantsNEWLINE return resNEWLINENEWLINENEWLINEclass ExtendedTransformation(object):NEWLINE """This class behaves like GeometryTransformation and extends transformationNEWLINE to the wavelength parameter.NEWLINENEWLINE This function uses numexpr for formula evaluation.NEWLINE """NEWLINE def __init__(self, dist_expr=None, poni1_expr=None, poni2_expr=None,NEWLINE rot1_expr=None, rot2_expr=None, rot3_expr=None, wavelength_expr=None,NEWLINE param_names=None, pos_names=None, constants=None,NEWLINE content=None):NEWLINE """Constructor of the classNEWLINENEWLINE :param dist_expr: formula (as string) providing with the distNEWLINE :param poni1_expr: formula (as string) providing with the poni1NEWLINE :param poni2_expr: formula (as string) providing with the poni2NEWLINE :param rot1_expr: formula (as string) providing with the rot1NEWLINE :param rot2_expr: formula (as string) providing with the rot2NEWLINE :param rot3_expr: formula (as string) providing with the rot3NEWLINE :param wavelength_expr: formula (as a string) to calculate wavelength used in angstromNEWLINE :param param_names: list of names of the parameters used in the modelNEWLINE :param pos_names: list of motor names for gonio with >1 degree of freedomNEWLINE :param constants: a dictionary with some constants the user may want to useNEWLINE :param content: Should be None or the name of the class (may be usedNEWLINE in the future to dispatch to multiple derivative classes)NEWLINE """NEWLINE if content is not None:NEWLINE # Ensures we use the constructor of the right classNEWLINE assert content in (self.__class__.__name__, "ExtendedTransformation")NEWLINE if numexpr is None:NEWLINE raise RuntimeError("This Transformation requires the *numexpr* package")NEWLINE self.expressions = OrderedDict()NEWLINENEWLINE if dist_expr is not None:NEWLINE self.expressions["dist"] = dist_exprNEWLINE if poni1_expr is not None:NEWLINE self.expressions["poni1"] = poni1_exprNEWLINE if poni2_expr is not None:NEWLINE self.expressions["poni2"] = poni2_exprNEWLINE if rot1_expr is not None:NEWLINE self.expressions["rot1"] = rot1_exprNEWLINE if rot2_expr is not None:NEWLINE self.expressions["rot2"] = rot2_exprNEWLINE if rot3_expr is not None:NEWLINE self.expressions["rot3"] = rot3_exprNEWLINE if wavelength_expr is not None:NEWLINE self.expressions["wavelength"] = wavelength_exprNEWLINE self.ParamNT = namedtuple("ParamNT", list(self.expressions.keys()))NEWLINE self.variables = {"pi": numpy.pi,NEWLINE "hc": CONST_hc,NEWLINE "q": CONST_q}NEWLINE if constants is not None:NEWLINE self.variables.update(constants)NEWLINE self.param_names = tuple(param_names) if param_names is not None else tuple()NEWLINE if pos_names is not None:NEWLINE self.pos_names = tuple(pos_names)NEWLINE else:NEWLINE self.pos_names = ("pos",)NEWLINE for key in self.param_names + self.pos_names:NEWLINE if key in self.variables:NEWLINE raise RuntimeError("The keyword %s is already defined, please chose another variable name")NEWLINE self.variables[key] = numpy.NaNNEWLINENEWLINE self.codes = OrderedDict(((name, numexpr.NumExpr(expr)) for name, expr in self.expressions.items()))NEWLINENEWLINE def __call__(self, param, pos):NEWLINE """This makes the class instance behave like a function,NEWLINE actually a function that translates the n-parameter of the detectorNEWLINE positioning on the goniometer and the m-parameters.NEWLINENEWLINE :param param: parameter of the fitNEWLINE :param pos: position of the goniometer (representation from theNEWLINE goniometer)NEWLINE :return: 6-tuple with (dist, poni1, poni2, rot1, rot2, rot3) as neededNEWLINE for pyFAI.NEWLINE """NEWLINE res = {}NEWLINE variables = self.variables.copy()NEWLINE for name, value in zip(self.param_names, param):NEWLINE variables[name] = valueNEWLINE if len(self.pos_names) == 1:NEWLINE variables[self.pos_names[0]] = posNEWLINE else:NEWLINE for name, value in zip(self.pos_names, pos):NEWLINE variables[name] = valueNEWLINE for name, code in self.codes.items():NEWLINE signa = [variables.get(name, numpy.NaN) for name in code.input_names]NEWLINE res[name] = (float(code(*signa)))NEWLINE # could ne done in a single liner but harder to understand !NEWLINE return self.ParamNT(**res)NEWLINENEWLINE def __repr__(self):NEWLINE res = ["%s with param: %s and pos: %s" % (self.__class__.__name__, self.param_names, self.pos_names), ]NEWLINE for name, expr in self.expressions.items():NEWLINE res.append(" %s= %s" % (name, expr))NEWLINE return os.linesep.join(res)NEWLINENEWLINE def to_dict(self):NEWLINE """Export the instance representation for serialization as a dictionaryNEWLINE """NEWLINE res = OrderedDict([("content", self.__class__.__name__),NEWLINE ("param_names", self.param_names),NEWLINE ("pos_names", self.pos_names),NEWLINE ])NEWLINE for name, expr in self.expressions.items():NEWLINE res[name + "_expr"] = exprNEWLINE constants = OrderedDict()NEWLINE for key, val in self.variables.items():NEWLINE if key in self.param_names:NEWLINE continueNEWLINE if self.pos_names and key in self.pos_names:NEWLINE continueNEWLINE constants[key] = valNEWLINE res["constants"] = constantsNEWLINE return resNEWLINENEWLINENEWLINEGeometryTranslation = GeometryTransformationNEWLINENEWLINENEWLINEclass Goniometer(object):NEWLINE """This class represents the goniometer model. Unlike this name suggests,NEWLINE it may include translation in addition to rotationsNEWLINE """NEWLINENEWLINE _file_version_1_1 = "Goniometer calibration v1.1"NEWLINENEWLINE file_version = "Goniometer calibration v2"NEWLINENEWLINE def __init__(self, param, trans_function, detector="Detector",NEWLINE wavelength=None, param_names=None, pos_names=None):NEWLINE """Constructor of the Goniometer class.NEWLINENEWLINE :param param: vector of parameter to refine for defining the detectorNEWLINE position on the goniometerNEWLINE :param trans_function: function taking the parameters of theNEWLINE goniometer and the goniometer position and return theNEWLINE 6 parameters [dist, poni1, poni2, rot1, rot2, rot3]NEWLINE :param detector: detector mounted on the moving armNEWLINE :param wavelength: the wavelength used for the experimentNEWLINE :param param_names: list of names to "label" the param vector.NEWLINE :param pos_names: list of names to "label" the position vector ofNEWLINE the gonio.NEWLINE """NEWLINENEWLINE self.param = paramNEWLINE self.trans_function = trans_functionNEWLINE self.detector = detector_factory(detector)NEWLINE self.wavelength = wavelengthNEWLINE if param_names is None and "param_names" in dir(trans_function):NEWLINE param_names = trans_function.param_namesNEWLINE if param_names is not None:NEWLINE if isinstance(param, dict):NEWLINE self.param = [param.get(i, 0) for i in param_names]NEWLINE self.nt_param = namedtuple("GonioParam", param_names)NEWLINE else:NEWLINE self.nt_param = lambda *x: tuple(x)NEWLINE if pos_names is None and "pos_names" in dir(trans_function):NEWLINE pos_names = trans_function.pos_namesNEWLINE self.nt_pos = namedtuple("GonioPos", pos_names) if pos_names else lambda *x: tuple(x)NEWLINENEWLINE def __repr__(self):NEWLINE return "Goniometer with param %s %s with %s" % (self.nt_param(*self.param), os.linesep, self.detector)NEWLINENEWLINE def get_ai(self, position):NEWLINE """Creates an azimuthal integrator from the motor positionNEWLINENEWLINE :param position: the goniometer position, a float for a 1 axisNEWLINE goniometerNEWLINE :return: A freshly build AzimuthalIntegratorNEWLINE """NEWLINE res = self.trans_function(self.param, position)NEWLINE params = {"detector": self.detector,NEWLINE "wavelength": self.wavelength}NEWLINE for name, value in zip(res._fields, res):NEWLINE params[name] = valueNEWLINE return AzimuthalIntegrator(**params)NEWLINENEWLINE def get_mg(self, positions):NEWLINE """Creates a MultiGeometry integrator from a list of goniometerNEWLINE positions.NEWLINENEWLINE :param positions: A list of goniometer positionsNEWLINE :return: A freshly build multi-geometryNEWLINE """NEWLINE ais = [self.get_ai(pos) for pos in positions]NEWLINE mg = MultiGeometry(ais)NEWLINE return mgNEWLINENEWLINE def to_dict(self):NEWLINE """Export the goniometer configuration to a dictionaryNEWLINENEWLINE :return: Ordered dictionaryNEWLINE """NEWLINE dico = OrderedDict([("content", self.file_version)])NEWLINENEWLINE dico["detector"] = self.detector.nameNEWLINE dico["detector_config"] = self.detector.get_config()NEWLINENEWLINE if self.wavelength:NEWLINE dico["wavelength"] = self.wavelengthNEWLINE dico["param"] = tuple(self.param)NEWLINE if "_fields" in dir(self.nt_param):NEWLINE dico["param_names"] = self.nt_param._fieldsNEWLINE if "_fields" in dir(self.nt_pos):NEWLINE dico["pos_names"] = self.nt_pos._fieldsNEWLINE if "to_dict" in dir(self.trans_function):NEWLINE dico["trans_function"] = self.trans_function.to_dict()NEWLINE else:NEWLINE logger.warning("trans_function is not serializable")NEWLINE return dicoNEWLINENEWLINE def save(self, filename):NEWLINE """Save the goniometer configuration to fileNEWLINENEWLINE :param filename: name of the file to save configuration toNEWLINE """NEWLINE dico = self.to_dict()NEWLINE try:NEWLINE with open(filename, "w") as f:NEWLINE f.write(json.dumps(dico, indent=2))NEWLINE except IOError:NEWLINE logger.error("IOError while writing to file %s", filename)NEWLINE write = saveNEWLINENEWLINE @classmethodNEWLINE def _get_detector_from_dict(cls, dico):NEWLINE file_version = dico["content"]NEWLINE if file_version == cls._file_version_1_1:NEWLINE # v1.1NEWLINE # Try to extract useful keysNEWLINE detector = Detector.factory(dico["detector"])NEWLINE # This is not accurate, some keys could be missingNEWLINE keys = detector.get_config().keys()NEWLINE config = {}NEWLINE for k in keys:NEWLINE if k in dico:NEWLINE config[k] = dico[k]NEWLINE del dico[k]NEWLINE detector = Detector.factory(dico["detector"], config)NEWLINE else:NEWLINE # v2NEWLINE detector = Detector.factory(dico["detector"], dico.get("detector_config", None))NEWLINE return detectorNEWLINENEWLINE @classmethodNEWLINE def sload(cls, filename):NEWLINE """Class method for instanciating a Goniometer object from a JSON fileNEWLINENEWLINE :param filename: name of the JSON fileNEWLINE :return: Goniometer objectNEWLINE """NEWLINENEWLINE with open(filename) as f:NEWLINE dico = json.load(f)NEWLINE assert "trans_function" in dico, "No translation function defined in JSON file"NEWLINE file_version = dico["content"]NEWLINE assert file_version in [cls.file_version, cls._file_version_1_1], "JSON file contains a goniometer calibration"NEWLINE detector = cls._get_detector_from_dict(dico)NEWLINE tansfun = dico.get("trans_function", {})NEWLINE if "content" in tansfun:NEWLINE content = tansfun.pop("content")NEWLINE # May be adapted for other classes of GeometryTransformation functionsNEWLINE if content in ("GeometryTranslation", "GeometryTransformation"):NEWLINE funct = GeometryTransformation(**tansfun)NEWLINE elif content == "ExtendedTranformation":NEWLINE funct = ExtendedTransformation(**tansfun)NEWLINE else:NEWLINE raise RuntimeError("content= %s, not in in (GeometryTranslation, GeometryTransformation, ExtendedTranformation)")NEWLINE else: # assume GeometryTransformationNEWLINE funct = GeometryTransformation(**tansfun)NEWLINENEWLINE gonio = cls(param=dico.get("param", []),NEWLINE trans_function=funct,NEWLINE detector=detector,NEWLINE wavelength=dico.get("wavelength"))NEWLINE return gonioNEWLINENEWLINENEWLINEclass SingleGeometry(object):NEWLINE """This class represents a single geometry of a detector position on aNEWLINE goniometer armNEWLINE """NEWLINE def __init__(self, label, image=None, metadata=None, pos_function=None,NEWLINE control_points=None, calibrant=None, detector=None, geometry=None):NEWLINE """Constructor of the SingleGeometry class, used for calibrating aNEWLINE multi-geometry setup with a moving detector.NEWLINENEWLINE :param label: name of the geometry, a string or anything unmutableNEWLINE :param image: image with Debye-Scherrer rings as 2d numpy arrayNEWLINE :param metadata: anything which contains the goniometer positionNEWLINE :param pos_function: a function which takes the metadata as inputNEWLINE and returns the goniometer arm positionNEWLINE :param control_points: a pyFAI.control_points.ControlPoints instanceNEWLINE (optional parameter)NEWLINE :param calibrant: a pyFAI.calibrant.Calibrant instance.NEWLINE Contains the wavelength to be used (optional parameter)NEWLINE :param detector: a pyFAI.detectors.Detector instance or something likeNEWLINE that Contains the mask to be used (optional parameter)NEWLINE :param geometry: an azimuthal integrator or a ponifileNEWLINE (or a dict with the geometry) (optional parameter)NEWLINE """NEWLINE self.label = labelNEWLINE self.image = imageNEWLINE self.metadata = metadata # may be anythingNEWLINE self.calibrant = calibrantNEWLINE if control_points is None or isinstance(control_points, ControlPoints):NEWLINE self.control_points = control_pointsNEWLINE else:NEWLINE # Probaly a NPT fileNEWLINE self.control_points = ControlPoints(control_points, calibrant=calibrant)NEWLINENEWLINE if detector is not None:NEWLINE self.detector = detector_factory(detector)NEWLINE else:NEWLINE self.detector = NoneNEWLINE if isinstance(geometry, Geometry):NEWLINE dict_geo = geometry.getPyFAI()NEWLINE elif isinstance(geometry, StringTypes) and os.path.exists(geometry):NEWLINE dict_geo = Geometry.sload(geometry).getPyFAI()NEWLINE elif isinstance(geometry, dict):NEWLINE dict_geo = geometryNEWLINE if self.detector is not None:NEWLINE dict_geo["detector"] = self.detectorNEWLINE if self.control_points is not None:NEWLINE dict_geo["data"] = self.control_points.getList()NEWLINE if self.calibrant is not None:NEWLINE dict_geo["calibrant"] = self.calibrantNEWLINE if "max_shape" in dict_geo:NEWLINE # not used in constructorNEWLINE dict_geo.pop("max_shape")NEWLINE self.geometry_refinement = GeometryRefinement(**dict_geo)NEWLINE if self.detector is None:NEWLINE self.detector = self.geometry_refinement.detectorNEWLINE self.pos_function = pos_functionNEWLINE self.massif = NoneNEWLINENEWLINE def get_position(self):NEWLINE """This method is in charge of calculating the motor position from metadata/label/..."""NEWLINE return self.pos_function(self.metadata)NEWLINENEWLINE def extract_cp(self, max_rings=None, pts_per_deg=1.0, Imin=0):NEWLINE """Performs an automatic keypoint extraction and update the geometry refinement partNEWLINENEWLINE :param max_ring: extract at most N rings from the imageNEWLINE :param pts_per_deg: number of control points per azimuthal degree (increase for better precision)NEWLINE """NEWLINE if self.massif is None:NEWLINE self.massif = Massif(self.image)NEWLINENEWLINE tth = numpy.array([i for i in self.calibrant.get_2th() if i is not None])NEWLINE tth = numpy.unique(tth)NEWLINE tth_min = numpy.zeros_like(tth)NEWLINE tth_max = numpy.zeros_like(tth)NEWLINE delta = (tth[1:] - tth[:-1]) / 4.0NEWLINE tth_max[:-1] = deltaNEWLINE tth_max[-1] = delta[-1]NEWLINE tth_min[1:] = -deltaNEWLINE tth_min[0] = -delta[0]NEWLINE tth_max += tthNEWLINE tth_min += tthNEWLINE shape = self.image.shapeNEWLINE ttha = self.geometry_refinement.twoThetaArray(shape)NEWLINE chia = self.geometry_refinement.chiArray(shape)NEWLINE rings = 0NEWLINE cp = ControlPoints(calibrant=self.calibrant)NEWLINE if max_rings is None:NEWLINE max_rings = tth.sizeNEWLINENEWLINE ms = marchingsquares.MarchingSquaresMergeImpl(ttha,NEWLINE mask=self.geometry_refinement.detector.mask,NEWLINE use_minmax_cache=True)NEWLINE for i in range(tth.size):NEWLINE if rings >= max_rings:NEWLINE breakNEWLINE mask = numpy.logical_and(ttha >= tth_min[i], ttha < tth_max[i])NEWLINE if self.detector.mask is not None:NEWLINE mask = numpy.logical_and(mask, numpy.logical_not(self.geometry_refinement.detector.mask))NEWLINE size = mask.sum(dtype=int)NEWLINE if (size > 0):NEWLINE rings += 1NEWLINE sub_data = self.image.ravel()[numpy.where(mask.ravel())]NEWLINE mean = sub_data.mean(dtype=numpy.float64)NEWLINE std = sub_data.std(dtype=numpy.float64)NEWLINE upper_limit = mean + stdNEWLINE mask2 = numpy.logical_and(self.image > upper_limit, mask)NEWLINE size2 = mask2.sum(dtype=int)NEWLINE if size2 < 1000:NEWLINE upper_limit = meanNEWLINE mask2 = numpy.logical_and(self.image > upper_limit, mask)NEWLINE size2 = mask2.sum()NEWLINE # length of the arc:NEWLINE points = ms.find_pixels(tth[i])NEWLINE seeds = set((i[0], i[1]) for i in points if mask2[i[0], i[1]])NEWLINE # max number of points: 360 points for a full circleNEWLINE azimuthal = chia[points[:, 0].clip(0, shape[0]), points[:, 1].clip(0, shape[1])]NEWLINE nb_deg_azim = numpy.unique(numpy.rad2deg(azimuthal).round()).sizeNEWLINE keep = int(nb_deg_azim * pts_per_deg)NEWLINE if keep == 0:NEWLINE continueNEWLINE dist_min = len(seeds) / 2.0 / keepNEWLINE # why 3.0, why not ?NEWLINENEWLINE logger.info("Extracting datapoint for ring %s (2theta = %.2f deg); " +NEWLINE "searching for %i pts out of %i with I>%.1f, dmin=%.1f",NEWLINE i, numpy.degrees(tth[i]), keep, size2, upper_limit, dist_min)NEWLINE res = self.massif.peaks_from_area(mask2, Imin=Imin, keep=keep, dmin=dist_min, seed=seeds, ring=i)NEWLINE cp.append(res, i)NEWLINE self.control_points = cpNEWLINE self.geometry_refinement.data = numpy.asarray(cp.getList(), dtype=numpy.float64)NEWLINE return cpNEWLINENEWLINE def get_ai(self):NEWLINE """Create a new azimuthal integrator to be used.NEWLINENEWLINE :return: Azimuthal Integrator instanceNEWLINE """NEWLINE geo = self.geometry_refinement.getPyFAI()NEWLINE geo["detector"] = self.detectorNEWLINE return AzimuthalIntegrator(**geo)NEWLINENEWLINENEWLINEclass GoniometerRefinement(Goniometer):NEWLINE """This class allow the translation of a goniometer geometry into a pyFAINEWLINE geometry using a set of parameter to refine.NEWLINE """NEWLINE def __init__(self, param, pos_function, trans_function,NEWLINE detector="Detector", wavelength=None, param_names=None, pos_names=None,NEWLINE bounds=None):NEWLINE """Constructor of the GoniometerRefinement classNEWLINENEWLINE :param param: vector of parameter to refine for defining the detectorNEWLINE position on the goniometerNEWLINE :param pos_function: a function taking metadata and extracting theNEWLINE goniometer positionNEWLINE :param trans_function: function taking the parameters of theNEWLINE goniometer and the gonopmeter position and return theNEWLINE 6/7 parameters [dist, poni1, poni2, rot1, rot2, rot3, wavelength]NEWLINE :param detector: detector mounted on the moving armNEWLINE :param wavelength: the wavelength used for the experimentNEWLINE :param param_names: list of names to "label" the param vector.NEWLINE :param pos_names: list of names to "label" the position vector of theNEWLINE gonio.NEWLINE :param bounds: list of 2-tuple with the lower and upper bound of each functionNEWLINE """NEWLINE Goniometer.__init__(self, param, trans_function,NEWLINE detector=detector, wavelength=wavelength,NEWLINE param_names=param_names, pos_names=pos_names)NEWLINE self.single_geometries = OrderedDict() # a dict of labels: SingleGeometryNEWLINE if bounds is None:NEWLINE self.bounds = [(None, None)] * len(self.param)NEWLINE else:NEWLINE if isinstance(bounds, dict) and "_fields" in dir(self.nt_param):NEWLINE self.bounds = [bounds.get(i, (None, None))NEWLINE for i in self.nt_param._fields]NEWLINE else:NEWLINE self.bounds = list(bounds)NEWLINE self.pos_function = pos_functionNEWLINE self.fit_wavelength = "wavelength" in self.trans_function.codesNEWLINENEWLINE def new_geometry(self, label, image=None, metadata=None, control_points=None,NEWLINE calibrant=None, geometry=None):NEWLINE """Add a new geometry for calibrationNEWLINENEWLINE :param label: usually a stringNEWLINE :param image: 2D numpy array with the Debye scherrer ringsNEWLINE :param metadata: some metadataNEWLINE :param control_points: an instance of ControlPointsNEWLINE :param calibrant: the calibrant used for calibratingNEWLINE :param geometry: poni or AzimuthalIntegrator instance.NEWLINE """NEWLINE if geometry is None:NEWLINE geometry = self.get_ai(self.pos_function(metadata))NEWLINE sg = SingleGeometry(label=label,NEWLINE image=image,NEWLINE metadata=metadata,NEWLINE control_points=control_points,NEWLINE calibrant=calibrant,NEWLINE detector=self.detector,NEWLINE pos_function=self.pos_function,NEWLINE geometry=geometry)NEWLINE self.single_geometries[label] = sgNEWLINE return sgNEWLINENEWLINE def __repr__(self):NEWLINE name = self.__class__.__name__NEWLINE count = len(self.single_geometries)NEWLINE geometry_list = ", ".join(self.single_geometries.keys())NEWLINE return "%s with %i geometries labeled: %s." % (name, count, geometry_list)NEWLINENEWLINE def residu2(self, param):NEWLINE "Actually performs the calulation of the average of the error squared"NEWLINE sumsquare = 0.0NEWLINE npt = 0NEWLINE for single in self.single_geometries.values():NEWLINE motor_pos = single.get_position()NEWLINE single_param = self.trans_function(param, motor_pos)._asdict()NEWLINE pyFAI_param = [single_param.get(name, 0.0)NEWLINE for name in ["dist", "poni1", "poni2", "rot1", "rot2", "rot3"]]NEWLINE pyFAI_param.append(single_param.get("wavelength", self.wavelength) * 1e10)NEWLINE if (single.geometry_refinement is not None) and (len(single.geometry_refinement.data) >= 1):NEWLINE sumsquare += single.geometry_refinement.chi2_wavelength(pyFAI_param)NEWLINE npt += single.geometry_refinement.data.shape[0]NEWLINE return sumsquare / max(npt, 1)NEWLINENEWLINE def chi2(self, param=None):NEWLINE """Calculate the average of the square of the error for a given parameter setNEWLINE """NEWLINE if param is not None:NEWLINE return self.residu2(param)NEWLINE else:NEWLINE return self.residu2(self.param)NEWLINENEWLINE def refine2(self, method="slsqp", **options):NEWLINE """Geometry refinement toolNEWLINENEWLINE See https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.optimize.minimize.htmlNEWLINENEWLINE :param method: name of the minimizerNEWLINE :param options: options for the minimizerNEWLINE """NEWLINE if method.lower() in ["simplex", "nelder-mead"]:NEWLINE method = "Nelder-Mead"NEWLINE bounds = NoneNEWLINE else:NEWLINE bounds = self.boundsNEWLINE former_error = self.chi2()NEWLINE print("Cost function before refinement: %s" % former_error)NEWLINE param = numpy.asarray(self.param, dtype=numpy.float64)NEWLINE print(param)NEWLINE res = minimize(self.residu2, param, method=method,NEWLINE bounds=bounds, tol=1e-12,NEWLINE options=options)NEWLINE print(res)NEWLINE newparam = res.xNEWLINE new_error = res.funNEWLINE print("Cost function after refinement: %s" % new_error)NEWLINE print(self.nt_param(*newparam))NEWLINENEWLINE # print("Constrained Least square %s --> %s" % (former_error, new_error))NEWLINE if new_error < former_error:NEWLINE # print(param, newparam)NEWLINENEWLINE i = abs(param - newparam).argmax()NEWLINE if "_fields" in dir(self.nt_param):NEWLINE name = self.nt_param._fields[i]NEWLINE print("maxdelta on: %s (%i) %s --> %s" % (name, i, self.param[i], newparam[i]))NEWLINE else:NEWLINE print("maxdelta on: %i %s --> %s" % (i, self.param[i], newparam[i]))NEWLINE self.param = newparamNEWLINE # update wavelength after successful optimization: not easyNEWLINE # if self.fit_wavelength:NEWLINE # self.wavelength = self.NEWLINE elif self.fit_wavelength:NEWLINE print("Restore wavelength and former parameters")NEWLINE former_wavelength = self.wavelengthNEWLINE for sg in self.single_geometries.values():NEWLINE sg.calibrant.setWavelength_change2th(former_wavelength)NEWLINE print(self.nt_param(*self.param))NEWLINE return self.paramNEWLINENEWLINE def set_bounds(self, name, mini=None, maxi=None):NEWLINE """Redefines the bounds for the refinementNEWLINENEWLINE :param name: name of the parameter or index in the parameter setNEWLINE :param mini: minimum valueNEWLINE :param maxi: maximum valueNEWLINE """NEWLINE if isinstance(name, StringTypes) and "_fields" in dir(self.nt_param):NEWLINE idx = self.nt_param._fields.index(name)NEWLINE else:NEWLINE idx = int(name)NEWLINE self.bounds[idx] = (mini, maxi)NEWLINENEWLINE @classmethodNEWLINE def sload(cls, filename, pos_function=None):NEWLINE """Class method for instanciating a Goniometer object from a JSON fileNEWLINENEWLINE :param filename: name of the JSON fileNEWLINE :param pos_function: a function taking metadata and extracting theNEWLINE goniometer positionNEWLINE :return: Goniometer objectNEWLINE """NEWLINENEWLINE with open(filename) as f:NEWLINE dico = json.load(f)NEWLINE assert dico["content"] == cls.file_version, "JSON file contains a goniometer calibration"NEWLINE assert "trans_function" in dico, "No translation function defined in JSON file"NEWLINE detector = cls._get_detector_from_dict(dico)NEWLINE tansfun = dico.get("trans_function", {})NEWLINE if "content" in tansfun:NEWLINE content = tansfun.pop("content")NEWLINE # May be adapted for other classes of GeometryTransformation functionsNEWLINE if content in ("GeometryTranslation", "GeometryTransformation"):NEWLINE funct = GeometryTransformation(**tansfun)NEWLINE elif content == "ExtendedTranformation":NEWLINE funct = ExtendedTransformation(**tansfun)NEWLINE else:NEWLINE raise RuntimeError("content= %s, not in in (GeometryTranslation, GeometryTransformation, ExtendedTranformation)")NEWLINE else: # assume GeometryTransformationNEWLINE funct = GeometryTransformation(**tansfun)NEWLINENEWLINE gonio = cls(param=dico.get("param", []),NEWLINE trans_function=funct,NEWLINE pos_function=pos_function,NEWLINE detector=detector,NEWLINE wavelength=dico.get("wavelength"))NEWLINE return gonioNEWLINE from __future__ import annotations # type: ignore[attr-defined]NEWLINEfrom dataclasses import dataclass, fieldNEWLINEfrom enum import EnumNEWLINEfrom typing import (NEWLINE Callable,NEWLINE Dict,NEWLINE List,NEWLINE Optional,NEWLINE UnionNEWLINE)NEWLINEimport weakrefNEWLINENEWLINEimport copyNEWLINEimport threadingNEWLINEimport torchNEWLINEimport torch.distributed as distNEWLINEfrom torch.distributed import rpcNEWLINEfrom torch.distributed import distributed_c10dNEWLINEfrom torch.distributed._shard.sharding_spec import (NEWLINE ChunkShardingSpec,NEWLINE EnumerableShardingSpec,NEWLINE ShardMetadata,NEWLINE ShardingSpec,NEWLINE)NEWLINEfrom torch.distributed._shard.sharding_spec._internals import (NEWLINE check_tensor,NEWLINE get_split_size,NEWLINE get_chunked_dim_size,NEWLINE validate_non_overlapping_shards_metadata,NEWLINE)NEWLINEfrom torch.distributed.nn.functional import (NEWLINE reduce_scatter,NEWLINE)NEWLINEfrom torch.types import NumberNEWLINEfrom .metadata import TensorProperties, ShardedTensorMetadataNEWLINEfrom .shard import ShardNEWLINEfrom .reshard import reshuffle_local_shard, reshard_local_shardNEWLINEfrom .utils import (NEWLINE get_current_process_group,NEWLINE _flatten_tensor_size,NEWLINE _parse_and_validate_remote_device,NEWLINE _validate_output_tensor_for_gather,NEWLINE build_metadata_from_local_shards,NEWLINE build_global_metadataNEWLINE)NEWLINENEWLINE# Tracking for sharded tensor objects.NEWLINE_sharded_tensor_lock = threading.Lock()NEWLINE_sharded_tensor_current_id = 0NEWLINE_sharded_tensor_map: Dict[int, 'weakref.ReferenceType[ShardedTensor]'] = {}NEWLINENEWLINE# Custom sharded opsNEWLINE_SHARDED_OPS: Dict[str, Callable] = {}NEWLINEdef _register_sharded_op(op, func):NEWLINE from inspect import signatureNEWLINE if len(signature(func).parameters) != 4:NEWLINE raise TypeError(NEWLINE f'Custom sharded op function expects signature: 'NEWLINE f'(types, args, kwargs, process_group), but received 'NEWLINE f'signature: {signature(func)}')NEWLINENEWLINE global _SHARDED_OPSNEWLINE _SHARDED_OPS[op] = funcNEWLINENEWLINEdef _register_remote_shards(sharded_tensor_id: int, rrefs: List[rpc.RRef[Shard]], rpc_rank: int):NEWLINE with _sharded_tensor_lock:NEWLINE if sharded_tensor_id not in _sharded_tensor_map:NEWLINE raise RuntimeError(NEWLINE f'Could not find sharded_tensor_id: {sharded_tensor_id} in map: {_sharded_tensor_map.keys()}')NEWLINENEWLINE sharded_tensor = _sharded_tensor_map[sharded_tensor_id]()NEWLINE if sharded_tensor is None:NEWLINE raise RuntimeError('ShardedTensor weakref has been deallocated')NEWLINE else:NEWLINE sharded_tensor._register_remote_shards(rrefs, rpc_rank)NEWLINENEWLINENEWLINEclass CreateOp(Enum):NEWLINE EMPTY = 0NEWLINE FULL = 1NEWLINE ONES = 2NEWLINE RAND = 3NEWLINE ZEROS = 4NEWLINENEWLINENEWLINE@dataclassNEWLINEclass TensorInitParams(object):NEWLINE """ Container for list of common params to create new local tensor. """NEWLINENEWLINE create_op: CreateOpNEWLINENEWLINE # needed when create_op is FULLNEWLINE # default set to False (not None) since None is incompatible with Number.NEWLINE fill_value: Number = field(default=False)NEWLINENEWLINE tensor_properties: TensorProperties = field(NEWLINE default=TensorProperties(dtype=torch.get_default_dtype(),NEWLINE layout=torch.strided,NEWLINE requires_grad=False,NEWLINE memory_format=torch.contiguous_format,NEWLINE pin_memory=False))NEWLINENEWLINENEWLINENEWLINEclass ShardedTensor(object):NEWLINE """NEWLINE ShardedTensor is an abstraction to represent Tensors that are shardedNEWLINE across multiple devices and multiple processes.NEWLINENEWLINE ShardedTensor is initialized in an SPMD like fashion where each rankNEWLINE initializes the ShardedTensor. The ShardedTensor object on each rankNEWLINE then only stores the local shard for the Tensor and provides globalNEWLINE metadata for all the shards.NEWLINENEWLINE ShardedTensor doesn't provide any Tensor like operations but is a wrapperNEWLINE providing the Tensor representing the local shard and the global metadata.NEWLINE Using these, users can build their custom distributed._sharded computationsNEWLINE on top of this primitive. The local shards are all initialized using theNEWLINE create_op specified by tensor_init_params.create_op, e.g., torch.ones, orNEWLINE torch.emptyNEWLINENEWLINE Args:NEWLINE sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specificationNEWLINE describing how to shard the Tensor.NEWLINE size (int...): a sequence of integers defining the shape of the outputNEWLINE tensor. Can be a variable number of arguments or a collection like a list or tuple.NEWLINENEWLINE Keyword args:NEWLINE tensor_init_params (:class: `TensorInitParams`): common params to create tensor.NEWLINE init_rrefs (bool, optional): Whether or not to initializeNEWLINE :class:`torch.distributed.rpc.RRef`s pointing to remote shards.NEWLINE Need to initialize the RPC Framework if specified as ``True``.NEWLINE Default: ``False``.NEWLINENEWLINE .. note:: ShardedTensor uses collectives to do various operations, i.e. itNEWLINE uses all_gather to do cross rank validations. For NCCL-based processedNEWLINE groups, internal tensor representations of objects must be moved to theNEWLINE GPU device before communication takes place. In this case, the deviceNEWLINE used is given by ``torch.cuda.current_device()`` and it is the user'sNEWLINE responsiblity to ensure that this is set so that each rank has anNEWLINE individual GPU, via ``torch.cuda.set_device()``NEWLINENEWLINE """NEWLINENEWLINE def __new__(cls, *args, **kwargs):NEWLINE # Use __new__ for logging purposes.NEWLINE torch._C._log_api_usage_once("torch.distributed._shard.sharded_tensor")NEWLINE return super(ShardedTensor, cls).__new__(cls)NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE sharding_spec: ShardingSpec,NEWLINE *size,NEWLINE tensor_init_params: TensorInitParams,NEWLINE process_group=None,NEWLINE init_rrefs=False,NEWLINE ):NEWLINE # prepare initialization, initialize fields likeNEWLINE # _process_group, _local_shards, etc.NEWLINE self._prepare_init(process_group=process_group, init_rrefs=init_rrefs)NEWLINENEWLINE if tensor_init_params.tensor_properties is None:NEWLINE raise ValueError('tensor_properties must not be None.')NEWLINENEWLINE if tensor_init_params.tensor_properties.dtype is None:NEWLINE tensor_init_params.tensor_properties.dtype = torch.get_default_dtype()NEWLINENEWLINE if tensor_init_params.tensor_properties.layout != torch.strided:NEWLINE raise ValueError('Only torch.strided layout is currently supported')NEWLINENEWLINE if tensor_init_params.tensor_properties.memory_format != torch.contiguous_format:NEWLINE raise ValueError('Only torch.contiguous_format memory_format is currently supported')NEWLINENEWLINE dims = _flatten_tensor_size(size)NEWLINENEWLINE self._sharding_spec = sharding_specNEWLINENEWLINE if isinstance(self._sharding_spec, ChunkShardingSpec):NEWLINE self._init_chunked(dims, tensor_init_params)NEWLINE elif isinstance(self._sharding_spec, EnumerableShardingSpec):NEWLINE self._init_enumerable(dims, tensor_init_params)NEWLINE else:NEWLINE raise ValueError(f'Unsupported sharding_spec: {self._sharding_spec}')NEWLINENEWLINE # do post initialization (i.e. register sharded_tensor_id, initialize_rpc)NEWLINE self._post_init()NEWLINENEWLINE def _prepare_init(self, process_group=None, init_rrefs=False):NEWLINE self._init_rrefs = init_rrefsNEWLINE self._sharded_tensor_id = NoneNEWLINENEWLINE self._process_group = (NEWLINE process_groupNEWLINE if process_group is not NoneNEWLINE else distributed_c10d._get_default_group()NEWLINE )NEWLINENEWLINE self._local_shards: List[Shard] = []NEWLINE self._remote_shards: Dict[int, List[rpc.RRef[Shard]]] = {}NEWLINENEWLINE def _post_init(self):NEWLINE # Initialize RPC if available.NEWLINE if self._init_rrefs:NEWLINE with _sharded_tensor_lock:NEWLINE global _sharded_tensor_current_id, _sharded_tensor_mapNEWLINE self._sharded_tensor_id = _sharded_tensor_current_idNEWLINE _sharded_tensor_map[self._sharded_tensor_id] = weakref.ref(self)NEWLINE _sharded_tensor_current_id += 1NEWLINENEWLINE if not rpc._is_current_rpc_agent_set():NEWLINE raise RuntimeError(NEWLINE 'RPC Framework needs to be initialized using'NEWLINE ' torch.distributed.rpc.init_rpc if init_rrefs is set to True')NEWLINE self._init_rpc()NEWLINENEWLINE def __del__(self):NEWLINE # Clean up the global map.NEWLINE with _sharded_tensor_lock:NEWLINE global _sharded_tensor_current_id, _sharded_tensor_mapNEWLINE if self._sharded_tensor_id in _sharded_tensor_map:NEWLINE _sharded_tensor_map.pop(self._sharded_tensor_id) # type: ignore[call-overload]NEWLINENEWLINE def _init_rpc(self):NEWLINE # Validate PG and RPC ranks match.NEWLINE pg_rank = dist.get_rank()NEWLINE rpc_rank = rpc.get_worker_info().idNEWLINE if pg_rank != rpc_rank:NEWLINE raise ValueError(NEWLINE f'Default ProcessGroup and RPC ranks must be 'NEWLINE f'the same for ShardedTensor, found process group rank: 'NEWLINE f'{pg_rank} and RPC rank: {rpc_rank}'NEWLINE )NEWLINENEWLINE self._remote_shards = {}NEWLINENEWLINE # Gather all the sharded tensor ids.NEWLINE worker_infos = rpc._get_current_rpc_agent().get_worker_infos()NEWLINE rank_to_name = {}NEWLINE name_to_rank = {}NEWLINENEWLINE for worker_info in worker_infos:NEWLINE rank_to_name[worker_info.id] = worker_info.nameNEWLINE name_to_rank[worker_info.name] = worker_info.idNEWLINENEWLINE all_tensor_ids = rpc.api._all_gather(self._sharded_tensor_id)NEWLINENEWLINE # Share the local shards to the entire world.NEWLINE futs = []NEWLINE rpc_rank = rpc.get_worker_info().idNEWLINE for rank in range(dist.get_world_size()):NEWLINE # Skip self.NEWLINE if rank == dist.get_rank():NEWLINE continueNEWLINENEWLINE if len(self.local_shards()) != 0:NEWLINE rrefs: List[rpc.RRef[Shard]] = [rpc.RRef(shard) for shard in self.local_shards()]NEWLINE fut = rpc.rpc_async(NEWLINE rank,NEWLINE _register_remote_shards,NEWLINE args=(all_tensor_ids[rank_to_name[rank]], rrefs, rpc_rank))NEWLINE futs.append(fut)NEWLINENEWLINE torch.futures.wait_all(futs)NEWLINENEWLINE # Barrier for all RPCs to finish on all ranks.NEWLINE rpc.api._all_gather(None)NEWLINENEWLINE def gather(NEWLINE self,NEWLINE dst: int = 0,NEWLINE out: Optional[torch.Tensor] = None,NEWLINE ) -> None:NEWLINE """NEWLINE Creates a full :class:`Tensor` on rank ``dst`` by gathering all shards of theNEWLINE sharded tensor.NEWLINENEWLINE The API needs to be called on all ranks in SPMD fashion. All ranks should haveNEWLINE the same ``dst``. ``out`` should be a tensor of the same size as the overallNEWLINE size of the sharded tensor on ``dst`` and ``None`` on all other ranks.NEWLINENEWLINE Args:NEWLINE dst(int): The rank where full tensor is constructed.NEWLINE Default: 0NEWLINE out (:class `torch.Tensor`, optional): The output full tensor.NEWLINE Must to be provided ONLY on ``dst`` rank.NEWLINE Default: ``None``NEWLINE """NEWLINE rank = dist.get_rank(self._process_group)NEWLINE full_size = self.metadata().sizeNEWLINE _validate_output_tensor_for_gather(rank, dst, full_size, out)NEWLINENEWLINE local_shards = self.local_shards()NEWLINENEWLINE world_size = dist.get_world_size(self._process_group)NEWLINENEWLINE gathered_shards = [None] * world_sizeNEWLINE # will revise this part with CPU support and use dist.gather()NEWLINE # once NCCL support for gather() is readyNEWLINE # https://github.com/pytorch/pytorch/issues/66187NEWLINE dist.all_gather_object(NEWLINE obj=local_shards,NEWLINE object_list=gathered_shards,NEWLINE group=self._process_group,NEWLINE )NEWLINENEWLINE if rank == dst:NEWLINE dims = len(full_size)NEWLINE for shards in gathered_shards:NEWLINE if shards is None:NEWLINE raise RuntimeError(NEWLINE 'Gathered shards cannot be None on dst rank {dst}'NEWLINE )NEWLINE for shard in shards:NEWLINE metadata = shard.metadataNEWLINE tensor = shard.tensorNEWLINENEWLINE out_narrow_view = outNEWLINE for dim in range(dims):NEWLINE out_narrow_view = out_narrow_view.narrow(NEWLINE dim,NEWLINE metadata.shard_offsets[dim],NEWLINE metadata.shard_sizes[dim],NEWLINE )NEWLINENEWLINE out_narrow_view.copy_(tensor)NEWLINENEWLINE @classmethodNEWLINE def _init_from_local_shards(NEWLINE cls,NEWLINE local_shards: List[Shard],NEWLINE *global_size,NEWLINE process_group=None,NEWLINE init_rrefs=False,NEWLINE ):NEWLINE # STEP 1: Validate the Shardmetadatas locallyNEWLINE process_group = (NEWLINE process_groupNEWLINE if process_group is not NoneNEWLINE else distributed_c10d._get_default_group()NEWLINE )NEWLINE current_rank = dist.get_rank(process_group)NEWLINE world_size = dist.get_world_size(process_group)NEWLINENEWLINE local_sharded_tensor_metadata: Optional[ShardedTensorMetadata] = NoneNEWLINE global_tensor_size = _flatten_tensor_size(global_size)NEWLINENEWLINE if len(local_shards) > 0:NEWLINE local_sharded_tensor_metadata = \NEWLINE build_metadata_from_local_shards(local_shards, global_tensor_size, current_rank, process_group)NEWLINENEWLINE # STEP 2. Validate metadata across ranks, and build a global sharded tensorNEWLINE # metadata by gathering local ShardedTensorMetadataNEWLINE gathered_metadatas: List[Optional[ShardedTensorMetadata]] = []NEWLINE if world_size > 1:NEWLINE gathered_metadatas = [None for _ in range(world_size)]NEWLINENEWLINE dist.all_gather_object(NEWLINE gathered_metadatas,NEWLINE local_sharded_tensor_metadata,NEWLINE group=process_groupNEWLINE )NEWLINE else:NEWLINE gathered_metadatas = [local_sharded_tensor_metadata]NEWLINENEWLINE global_sharded_tensor_metadata = build_global_metadata(gathered_metadatas)NEWLINENEWLINE # STEP 3: Validation done, create the actual ShardedTensor and populate fieldsNEWLINE # prepare initializationNEWLINE sharded_tensor = cls.__new__(cls)NEWLINE sharded_tensor._prepare_init(process_group=process_group, init_rrefs=init_rrefs)NEWLINENEWLINE # add to metadata and local_shardsNEWLINE sharded_tensor._metadata = global_sharded_tensor_metadataNEWLINE sharded_tensor._local_shards = local_shardsNEWLINE # make a EnumerableShardingSpec for sharded tensors that initialized from this API.NEWLINE # TODO: make sharding spec a ChunkShardingSpec by inferring from the metadata list.NEWLINE # see issue https://github.com/pytorch/pytorch/issues/67244NEWLINE sharded_tensor._sharding_spec = EnumerableShardingSpec(global_sharded_tensor_metadata.shards_metadata)NEWLINENEWLINE # run post initialization, i.e. map registration, rpc initializationNEWLINE sharded_tensor._post_init()NEWLINE return sharded_tensorNEWLINENEWLINE @classmethodNEWLINE def _init_from_local_shards_and_global_metadata(NEWLINE cls,NEWLINE local_shards: List[Shard],NEWLINE sharded_tensor_metadata: ShardedTensorMetadata,NEWLINE process_group=None,NEWLINE init_rrefs=False,NEWLINE ) -> "ShardedTensor":NEWLINE """NEWLINE Initialize a ShardedTensor with local shards and a globalNEWLINE ShardedTensorMetadata built on each rank.NEWLINENEWLINE Warning: This API is experimental and subject to change. It doesNEWLINE not do cross rank validations, and fully rely on the userNEWLINE for the correctness of sharded_tensor_metadata on each rankNEWLINE """NEWLINE process_group = (NEWLINE process_groupNEWLINE if process_group is not NoneNEWLINE else distributed_c10d._get_default_group()NEWLINE )NEWLINE current_rank = dist.get_rank(process_group)NEWLINENEWLINE shards_metadata = sharded_tensor_metadata.shards_metadataNEWLINE tensor_properties = sharded_tensor_metadata.tensor_propertiesNEWLINENEWLINE if len(shards_metadata) == 0:NEWLINE raise ValueError("shards_metadata must not be empty!")NEWLINENEWLINE if tensor_properties.layout != torch.strided:NEWLINE raise ValueError('Only torch.strided layout is currently supported')NEWLINENEWLINE sharded_tensor = cls.__new__(cls)NEWLINE sharded_tensor._prepare_init(process_group=process_group, init_rrefs=init_rrefs)NEWLINENEWLINE sharded_tensor._metadata = sharded_tensor_metadataNEWLINENEWLINE local_shard_metadatas = []NEWLINENEWLINE def _raise_if_mismatch(expected, actual, prop_name, rank, is_property=False):NEWLINE tensor_property_or_metadata = "tensor property" if is_property else "local ShardMetadata"NEWLINE if expected != actual:NEWLINE raise ValueError(f"Local shards' tensor {prop_name} property is incompatible with "NEWLINE f"{tensor_property_or_metadata} on rank {rank}: "NEWLINE f"{tensor_property_or_metadata} {prop_name}={expected}, "NEWLINE f"local shard tensor {prop_name}={actual}.")NEWLINENEWLINE # collect local shard metadatas from the global sharded_tensor_metadataNEWLINE for shard_metadata in shards_metadata: # type: ignore[attr-defined]NEWLINE rank, local_device = _parse_and_validate_remote_device(sharded_tensor._process_group, shard_metadata.placement)NEWLINENEWLINE if current_rank == rank:NEWLINE local_shard_metadatas.append(shard_metadata)NEWLINENEWLINE if len(local_shards) != len(local_shard_metadatas):NEWLINE raise RuntimeError(NEWLINE f'Number of local shards ({len(local_shards)}) does not match number of local 'NEWLINE f'shards metadata in sharded_tensor_metadata ({len(local_shard_metadatas)}) 'NEWLINE f'on rank ({current_rank}) 'NEWLINE )NEWLINENEWLINE for shard in local_shards:NEWLINE shard_meta = shard.metadataNEWLINE local_shard_tensor = shard.tensorNEWLINE rank, local_device = _parse_and_validate_remote_device(sharded_tensor._process_group, shard_meta.placement)NEWLINENEWLINE # validate if shard_meta in the metadatas collected from sharded_tensor_metadataNEWLINE assert shard_meta in local_shard_metadatas, \NEWLINE "local shard metadata not in sharded_tensor_metadata!"NEWLINENEWLINE _raise_if_mismatch(tensor_properties.layout, local_shard_tensor.layout, "layout", current_rank, True)NEWLINE if not local_shard_tensor.is_contiguous():NEWLINE raise ValueError('Only torch.contiguous_format memory_format is currently supported')NEWLINENEWLINE _raise_if_mismatch(shard_meta.shard_sizes, list(local_shard_tensor.size()), "size", current_rank)NEWLINE _raise_if_mismatch(tensor_properties.pin_memory, local_shard_tensor.is_pinned(), "pin_memory", current_rank, True)NEWLINE _raise_if_mismatch(local_device, local_shard_tensor.device, "device", current_rank)NEWLINE _raise_if_mismatch(tensor_properties.dtype, local_shard_tensor.dtype, "dtype", current_rank, True)NEWLINE _raise_if_mismatch(NEWLINE tensor_properties.requires_grad, local_shard_tensor.requires_grad, "requires_grad", current_rank, True)NEWLINENEWLINE # check if shards_metadata have overlap shardsNEWLINE validate_non_overlapping_shards_metadata(shards_metadata)NEWLINENEWLINE # check if the shards_metadata is compatible with overall size of the sharded tensor.NEWLINE check_tensor(shards_metadata, list(sharded_tensor_metadata.size))NEWLINENEWLINE # done validation, add local_shardsNEWLINE sharded_tensor._local_shards = local_shardsNEWLINE # make a EnumerableShardingSpec for sharded tensors that initialized from this API.NEWLINE # TODO: make sharding spec a ChunkShardingSpec by inferring from the metadata list.NEWLINE # see issue https://github.com/pytorch/pytorch/issues/67244NEWLINE sharded_tensor._sharding_spec = EnumerableShardingSpec(shards_metadata)NEWLINENEWLINE # run post initialization, i.e. map registration, rpc initializationNEWLINE sharded_tensor._post_init()NEWLINE return sharded_tensorNEWLINENEWLINENEWLINE def _init_chunked(self, dims, tensor_init_params: TensorInitParams, ):NEWLINE current_rank = dist.get_rank(self._process_group)NEWLINE sharding_dim = self._sharding_spec.dim # type: ignore[attr-defined]NEWLINENEWLINE # Validate the sharding spec.NEWLINE if not isinstance(sharding_dim, int):NEWLINE raise ValueError(NEWLINE f"Sharding dim needs to be an integer, found: {sharding_dim}"NEWLINE )NEWLINE if sharding_dim >= len(dims) or sharding_dim < -len(dims):NEWLINE raise ValueError(f"Invalid sharding dim: {sharding_dim}")NEWLINENEWLINE dim_size = dims[sharding_dim]NEWLINE remote_devices = self._sharding_spec.placements # type: ignore[attr-defined]NEWLINE chunks = len(remote_devices)NEWLINE # split_size computed similar to 'torch.chunk'NEWLINE split_size = get_split_size(dim_size, chunks)NEWLINENEWLINE shards_metadata = []NEWLINE for idx, remote_device in enumerate(remote_devices):NEWLINE rank, local_device = _parse_and_validate_remote_device(self._process_group, remote_device)NEWLINENEWLINE # Adjust the sharding dim for this rank.NEWLINE sharded_dim_size = get_chunked_dim_size(dim_size, split_size, idx)NEWLINENEWLINE if sharded_dim_size > 0:NEWLINE # Build sharding_metadata.NEWLINENEWLINE # deepcopy for modification.NEWLINE rank_dims = dims.copy()NEWLINENEWLINE rank_offsets = [0] * len(dims)NEWLINE rank_offsets[sharding_dim] = split_size * idxNEWLINE rank_dims[sharding_dim] = sharded_dim_sizeNEWLINENEWLINE shard_metadata = ShardMetadata(rank_offsets, rank_dims, remote_device)NEWLINE shards_metadata.append(shard_metadata)NEWLINENEWLINE # Build the local shard for the current rank if it is involved in the sharding spec.NEWLINE if current_rank == rank:NEWLINE # Initialize the local shard.NEWLINE local_shard = _create_tensor_from_params(NEWLINE *rank_dims, local_device=local_device, tensor_init_params=tensor_init_params)NEWLINE self._local_shards.append(Shard(local_shard, shard_metadata))NEWLINENEWLINE # Build overall metadataNEWLINE self._metadata = ShardedTensorMetadata(NEWLINE shards_metadata, dims, tensor_init_params.tensor_properties, )NEWLINENEWLINE def _init_enumerable(self, dims, tensor_init_params: TensorInitParams):NEWLINE # Validate the sharding spec is compatible with the tensor.NEWLINE check_tensor(self._sharding_spec.shards, dims) # type: ignore[attr-defined]NEWLINENEWLINE current_rank = dist.get_rank(self._process_group)NEWLINENEWLINE shards_metadata = []NEWLINE for shard_metadata in self._sharding_spec.shards: # type: ignore[attr-defined]NEWLINE rank, local_device = _parse_and_validate_remote_device(self._process_group, shard_metadata.placement)NEWLINE shards_metadata.append(shard_metadata)NEWLINENEWLINE if current_rank == rank:NEWLINE # Initialize the local shard.NEWLINE local_shard = _create_tensor_from_params(NEWLINE *shard_metadata.shard_sizes, local_device=local_device,NEWLINE tensor_init_params=tensor_init_params)NEWLINE self._local_shards.append(Shard(local_shard, shard_metadata))NEWLINENEWLINE # Build overall metadataNEWLINE self._metadata = ShardedTensorMetadata(NEWLINE shards_metadata, dims, tensor_init_params.tensor_properties, )NEWLINENEWLINE def sharding_spec(self) -> ShardingSpec:NEWLINE """NEWLINE Returns the ShardingSpec for the tensor.NEWLINE """NEWLINE return self._sharding_specNEWLINENEWLINE def reshard(self, resharding_spec: ShardingSpec) -> ShardedTensor:NEWLINE """NEWLINE Reshard a sharded tensor given the ``resharding_spec``. For now, we only supportNEWLINE single local shard.NEWLINENEWLINE If ``resharding_spec`` is same as the original one, this becomes a no-op.NEWLINE If only ``resharding_spec`` shares the same sharding dim with the original one,NEWLINE we swap local shards directly.NEWLINE For more generic cases, we merge different shards across different ranks and splitNEWLINE the local shards based on the ``resharding_spec`` via `all_to_all` collective API.NEWLINENEWLINE Args:NEWLINE resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): TheNEWLINE specification describing how the tensor is sharded.NEWLINENEWLINE Returns:NEWLINE A :class:`ShardedTensor` object whose local shards are resharded.NEWLINENEWLINE Examples:NEWLINE >>> # We have 2 process groups, 2 ranks.NEWLINE >>> tensor = torch.arange(4, dtype=torch.int64) + 1 + 2 * rankNEWLINE >>> tensor = torch.stack([tensor, tensor])NEWLINE >>> tensorNEWLINE tensor([[1, 2, 3, 4], [1, 2, 3, 4]]) # Rank 0NEWLINE tensor([[3, 4, 5, 6], [3, 4, 5, 6]]) # Rank 1NEWLINE tensor([[5, 6, 7, 8], [5, 6, 7, 8]]) # Rank 2NEWLINE tensor([[7, 8, 9, 10], [7, 8, 9, 10]]) # Rank 3NEWLINE >>> sharding_dim = 0NEWLINE >>> spec = ChunkShardingSpec(NEWLINE dim=sharding_dim,NEWLINE placements=[NEWLINE "rank:0/cuda:0",NEWLINE "rank:1/cuda:1",NEWLINE "rank:2/cuda:2",NEWLINE "rank:3/cuda:3",NEWLINE ],NEWLINE )NEWLINE >>> current_offsets = [0] * 2NEWLINE >>> current_offsets[0] = rank * 2NEWLINE >>> shard_metadata = ShardMetadata(NEWLINE shard_offsets=copy.deepcopy(current_offsets),NEWLINE shard_sizes=tensor.size(),NEWLINE placement=spec.placements[rank],NEWLINE )NEWLINE >>> local_shards = [NEWLINE Shard(NEWLINE tensor=tensor,NEWLINE metadata=shard_metadata,NEWLINE )NEWLINE ]NEWLINE >>> st = ShardedTensor._init_from_local_shards(local_shards, tensor.size())NEWLINE >>> sharding_dim = 1NEWLINE >>> resharding_spec = ChunkShardingSpec(NEWLINE dim=sharding_dim,NEWLINE placements=[NEWLINE "rank:0/cuda:0",NEWLINE "rank:1/cuda:1",NEWLINE "rank:2/cuda:2",NEWLINE "rank:3/cuda:3",NEWLINE ],NEWLINE )NEWLINE >>> st.reshard(resharding_spec)NEWLINE >>> tensor = st.local_shards()[0].tensorNEWLINE >>> tensorNEWLINE tensor([[1], [1], [3], [3], [5], [5], [7], [7]]) # Rank 0NEWLINE tensor([[2], [2], [4], [4], [6], [6], [8], [8]]) # Rank 1NEWLINE tensor([[3], [3], [5], [5], [7], [7], [9], [9]]) # Rank 2NEWLINE tensor([[4], [4], [6], [6], [8], [8], [10], [10]]) # Rank 3NEWLINE """NEWLINE if (NEWLINE not isinstance(resharding_spec, ChunkShardingSpec) orNEWLINE not isinstance(self._sharding_spec, ChunkShardingSpec)NEWLINE ):NEWLINE raise NotImplementedError("Only ChunkShardingSpec supported for reshard.")NEWLINE if (len(self.local_shards()) != 1):NEWLINE raise NotImplementedError("Only single local shard supported for reshard.")NEWLINENEWLINE if self._sharding_spec.dim == resharding_spec.dim: # type: ignore[attr-defined]NEWLINE if self._sharding_spec.placements == resharding_spec.placements: # type: ignore[attr-defined]NEWLINE return selfNEWLINE else:NEWLINE local_shards, shards_metadata = reshuffle_local_shard(NEWLINE self.local_tensor(),NEWLINE self.size(), # type: ignore[arg-type]NEWLINE self._sharding_spec,NEWLINE resharding_spec,NEWLINE self._process_group,NEWLINE )NEWLINE else:NEWLINE local_shards, shards_metadata = reshard_local_shard(NEWLINE self.local_tensor(),NEWLINE self.size(), # type: ignore[arg-type]NEWLINE self._sharding_spec,NEWLINE resharding_spec,NEWLINE self._process_group,NEWLINE )NEWLINE self._local_shards = local_shardsNEWLINE self._metadata.shards_metadata = shards_metadataNEWLINE self._sharding_spec = resharding_specNEWLINE return selfNEWLINENEWLINE def local_tensor(self) -> torch.Tensor:NEWLINE """NEWLINE Return local tensor for a sharded_tensor. For now we only support single local shard.NEWLINENEWLINE Returns:NEWLINE A :class:`torch.Tensor` of the local shard.NEWLINE """NEWLINE if len(self.local_shards()) != 1:NEWLINE raise NotImplementedError("Only single local shard is supported.")NEWLINE return self.local_shards()[0].tensorNEWLINENEWLINE def __torch_function__(self, func, types, args=(), kwargs=None):NEWLINE if func in _SHARDED_OPS:NEWLINE return _SHARDED_OPS[func](types, args, kwargs, self._process_group)NEWLINE raise RuntimeError(NEWLINE f"torch function '{func.__name__}', with args: {args} and "NEWLINE f"kwargs: {kwargs} not supported for ShardedTensor!")NEWLINENEWLINE def metadata(self) -> ShardedTensorMetadata:NEWLINE """NEWLINE Returns a :class:`ShardedTensorMetadata` object corresponding to theNEWLINE metadata for the entire tensor.NEWLINE """NEWLINE return self._metadataNEWLINENEWLINE def local_shards(self) -> List[Shard]:NEWLINE """NEWLINE Returns a list of :class:`Shard' corresponding to theNEWLINE local shards for this rank. Returns an empty list if the current rankNEWLINE does not host any shards for this Tensor.NEWLINE """NEWLINE return self._local_shardsNEWLINENEWLINE def size(self, dim: int = None) -> Union[torch.Size, int]:NEWLINE """NEWLINE Returns a :Union:`[torch.Size, int]` which represents the size of the tensor.NEWLINE The dimension can be specified.NEWLINENEWLINE Args:NEWLINE dim (int, optional): the dimension over which the size represents.NEWLINE If specified, it returns the size of the given dimension.NEWLINE If not, it returns a subclass of tuple.NEWLINE Default: ``None``NEWLINENEWLINE Returns:NEWLINE A :Union:`[torch.Size, int]` represents the size of the tensor.NEWLINE """NEWLINE size = self._metadata.sizeNEWLINE if dim is None:NEWLINE return sizeNEWLINE if dim < 0 or dim >= len(size):NEWLINE raise ValueError(NEWLINE f"Argument ``dim`` must be within the range of tensor dimensions [0, {len(size)})"NEWLINE )NEWLINE return size[dim]NEWLINENEWLINENEWLINE def is_pinned(self) -> bool:NEWLINE """NEWLINE Returns True if the sharded tensor (each local shard) resides in pinned memory.NEWLINE """NEWLINE return self._metadata.tensor_properties.pin_memoryNEWLINENEWLINE def is_contiguous(self) -> bool:NEWLINE """NEWLINE Returns True if the sharded tensor (each local shard) is contiguous in memoryNEWLINE in the order specified by memory format.NEWLINE """NEWLINE return self._metadata.tensor_properties.memory_format == torch.contiguous_formatNEWLINENEWLINE @propertyNEWLINE def shape(self):NEWLINE return self._metadata.sizeNEWLINENEWLINE @propertyNEWLINE def requires_grad(self):NEWLINE return self._metadata.tensor_properties.requires_gradNEWLINENEWLINE @propertyNEWLINE def dtype(self):NEWLINE return self._metadata.tensor_properties.dtypeNEWLINENEWLINE @propertyNEWLINE def layout(self):NEWLINE return self._metadata.tensor_properties.layoutNEWLINENEWLINE def _register_remote_shards(self, remote_shards: List[rpc.RRef[Shard]], rpc_rank: int):NEWLINE self._remote_shards[rpc_rank] = remote_shardsNEWLINENEWLINE def remote_shards(self) -> Dict[int, List[rpc.RRef[Shard]]]:NEWLINE """NEWLINE Returns a Dict[int, RRef] with keys being the RPC rank and valuesNEWLINE being RRefs to shards on that rank. Need to initialize theNEWLINE RPC framework for this functionality.NEWLINENEWLINE Raises an exception if ShardedTensor was created with ``init_rrefs=False``NEWLINE """NEWLINE if not self._init_rrefs:NEWLINE raise RuntimeError(NEWLINE 'ShardedTensor created with init_rrefs=False, no RRefs to remote shards available'NEWLINE )NEWLINE return self._remote_shardsNEWLINENEWLINE def __hash__(self):NEWLINE return id(self)NEWLINENEWLINE def __repr__(self):NEWLINE return f'ShardedTensor({self._metadata})'NEWLINENEWLINE @dataclassNEWLINE class ProcessGroupState:NEWLINE """NEWLINE State for ser-de of process groupNEWLINE """NEWLINE local_rank: intNEWLINE global_rank: intNEWLINE local_world_size: intNEWLINE global_world_size: intNEWLINENEWLINE def __getstate__(self):NEWLINE pg_state = ShardedTensor.ProcessGroupState(NEWLINE distributed_c10d.get_rank(self._process_group),NEWLINE distributed_c10d.get_rank(),NEWLINE distributed_c10d.get_world_size(self._process_group),NEWLINE distributed_c10d.get_world_size(),NEWLINE )NEWLINENEWLINE return self._local_shards, self._metadata, pg_state, self._sharding_spec, self._init_rrefsNEWLINENEWLINE def __setstate__(self, state):NEWLINE self._sharded_tensor_id = NoneNEWLINE if not distributed_c10d.is_initialized():NEWLINE raise RuntimeError(NEWLINE 'Need to initialize default process group using 'NEWLINE '"init_process_group" before loading ShardedTensor')NEWLINENEWLINE self._local_shards, self._metadata, pg_state, self._sharding_spec, self._init_rrefs = stateNEWLINENEWLINE # Setup process groupNEWLINE self._process_group = get_current_process_group()NEWLINENEWLINE # Validate process group.NEWLINE local_rank = distributed_c10d.get_rank(self._process_group)NEWLINE if pg_state.local_rank != local_rank:NEWLINE raise RuntimeError(NEWLINE f'Local rank at save time was {pg_state.local_rank}, but at 'NEWLINE f'load time was {local_rank}')NEWLINENEWLINE global_rank = distributed_c10d.get_rank()NEWLINE if pg_state.global_rank != global_rank:NEWLINE raise RuntimeError(NEWLINE f'Global rank at save time was {pg_state.global_rank}, but at 'NEWLINE f'load time was {global_rank}')NEWLINENEWLINE local_world_size = distributed_c10d.get_world_size(self._process_group)NEWLINE if pg_state.local_world_size != local_world_size:NEWLINE raise RuntimeError(NEWLINE f'Local world size at save time was {pg_state.local_world_size}, 'NEWLINE f'but at load time was {local_world_size}')NEWLINENEWLINE global_world_size = distributed_c10d.get_world_size()NEWLINE if pg_state.global_world_size != global_world_size:NEWLINE raise RuntimeError(NEWLINE f'Global world size at save time was {pg_state.global_world_size}, 'NEWLINE f'but at load time was {global_world_size}')NEWLINENEWLINE self._post_init()NEWLINENEWLINENEWLINEdef _create_tensor_from_params(*size, local_device, tensor_init_params: TensorInitParams):NEWLINE """ Helper to construct tensor from size, device and common params. """NEWLINENEWLINE create_op = tensor_init_params.create_opNEWLINE dtype = tensor_init_params.tensor_properties.dtypeNEWLINE layout = tensor_init_params.tensor_properties.layoutNEWLINE requires_grad = tensor_init_params.tensor_properties.requires_gradNEWLINE memory_format = tensor_init_params.tensor_properties.memory_formatNEWLINE pin_memory = tensor_init_params.tensor_properties.pin_memoryNEWLINENEWLINE if create_op == CreateOp.ONES:NEWLINE return torch.ones(*size, dtype=dtype, layout=layout,NEWLINE device=local_device, pin_memory=pin_memory,NEWLINE requires_grad=requires_grad,)NEWLINE elif create_op == CreateOp.EMPTY:NEWLINE return torch.empty(*size, dtype=dtype, layout=layout,NEWLINE device=local_device, requires_grad=requires_grad,NEWLINE # NB: memory_format param is not accepted by torch.onesNEWLINE memory_format=memory_format, pin_memory=pin_memory,)NEWLINE elif tensor_init_params.create_op == CreateOp.ZEROS:NEWLINE return torch.zeros(*size,NEWLINE dtype=dtype,NEWLINE layout=layout,NEWLINE device=local_device,NEWLINE pin_memory=pin_memory,NEWLINE requires_grad=requires_grad,)NEWLINE elif tensor_init_params.create_op == CreateOp.RAND:NEWLINE return torch.rand(*size,NEWLINE dtype=dtype,NEWLINE layout=layout,NEWLINE device=local_device,NEWLINE pin_memory=pin_memory,NEWLINE requires_grad=requires_grad,)NEWLINE elif tensor_init_params.create_op == CreateOp.FULL:NEWLINE return torch.full(size=size,NEWLINE fill_value=tensor_init_params.fill_value,NEWLINE layout=layout,NEWLINE dtype=dtype,NEWLINE requires_grad=requires_grad,NEWLINE device=local_device, )NEWLINE else:NEWLINE raise ValueError(f'Unsupported create_op: {tensor_init_params.create_op}')NEWLINENEWLINENEWLINEclass _PartialTensor(object):NEWLINE """NEWLINE PartialTensor is an abstraction to represent Tensors that needNEWLINE aggregation across multiple devices and multiple processes.NEWLINENEWLINE PartialTensor is initialized in an SPMD like fashion where each rankNEWLINE initializes the PartialTensor. The PartialTensor object on each rankNEWLINE then only stores the local partial shard, process group and theNEWLINE aggregation way to get a full tensor.NEWLINENEWLINE PartialTensor doesn't provide any Tensor like operations but is aNEWLINE wrapper providing the Tensor representing the local partial shard.NEWLINENEWLINE We assume the size of each local tensor to be exactly the same.NEWLINENEWLINE Users can apply custom distributed sharded computations on top ofNEWLINE this primitive.NEWLINENEWLINE Args:NEWLINE local_partial_shard (Tensor): Partial result stored across ranks.NEWLINE process_group (ProcessGroup): The process group to aggregate on.NEWLINE reduce_op (distributed_c10d.ReduceOp): Way to aggregate the partial result.NEWLINE Default: ``distributed_c10d.ReduceOp.SUM``NEWLINENEWLINE Examples:NEWLINE >>> # All tensors below are of torch.int64 type.NEWLINE >>> # We have 2 process groups, 2 ranks.NEWLINE >>> tensor = torch.arange(2, dtype=torch.int64) + 1 + 2 * rankNEWLINE >>> tensor = torch.cat([tensor, tensor + 2])NEWLINE >>> tensorNEWLINE tensor([1, 2, 3, 4]) # Rank 0NEWLINE tensor([3, 4, 5, 6]) # Rank 1NEWLINE >>> partial_tensor = _PartialTensor(tensor, distributed_c10d.ReduceOp.MAX)NEWLINE >>> sharding_dim = 0NEWLINE >>> collect_spec = ChunkShardingSpec(NEWLINE dim=sharding_dim,NEWLINE placements=[NEWLINE "rank:0/cuda:0",NEWLINE "rank:1/cuda:1",NEWLINE ],NEWLINE )NEWLINE >>> complete_tensor = partial_tensor.reshard(collect_spec)NEWLINE >>> complete_tensorNEWLINE ShardedTensor(NEWLINE ShardedTensorMetadata(NEWLINE shards_metadata=[NEWLINE ShardMetadata(shard_offsets=[0], shard_sizes=[2], placement=rank:0/cuda:0),NEWLINE ShardMetadata(shard_offsets=[2], shard_sizes=[2], placement=rank:1/cuda:1)],NEWLINE size=torch.Size([4])NEWLINE )NEWLINE >>> complete_tensor.local_tensor()NEWLINE tensor([3, 4]) # Rank 0NEWLINE tensor([5, 6]) # Rank 1NEWLINENEWLINE >>> # All tensors below are of torch.cfloat type.NEWLINE >>> # We have 2 process groups, 2 ranks.NEWLINE >>> tensor = torch.tensor([1, 2]) + 2 * rankNEWLINE >>> tensor = torch.cat([tensor, tensor + 2])NEWLINE >>> tensorNEWLINE tensor([1, 2, 3, 4]) # Rank 0NEWLINE tensor([3, 4, 5, 6]) # Rank 1NEWLINE >>> partial_tensor = _PartialTensor(tensor)NEWLINE >>> complete_tensor = partial_tensor.reshard(collect_spec)NEWLINE >>> complete_tensorNEWLINE ShardedTensor(NEWLINE ShardedTensorMetadata(NEWLINE shards_metadata=[NEWLINE ShardMetadata(shard_offsets=[0], shard_sizes=[2], placement=rank:0/cuda:0),NEWLINE ShardMetadata(shard_offsets=[2], shard_sizes=[2], placement=rank:1/cuda:1)],NEWLINE size=torch.Size([4])NEWLINE )NEWLINE >>> complete_tensor.local_tensor()NEWLINE tensor([4, 6]) # Rank 0NEWLINE tensor([8, 10]) # Rank 1NEWLINE """NEWLINENEWLINE def __init__(NEWLINE self, local_shard, process_group=None, reduce_op=distributed_c10d.ReduceOp.SUMNEWLINE ):NEWLINE self.local_shard = local_shardNEWLINE self.process_group = (NEWLINE process_groupNEWLINE if process_groupNEWLINE else dist.distributed_c10d._get_default_group()NEWLINE )NEWLINE self.reduce_op = reduce_opNEWLINENEWLINE def __post_init__(self):NEWLINE if not isinstance(self.local_shard, torch.Tensor):NEWLINE raise ValueError("local_shard needs to be a Tensor.")NEWLINE if not isinstance(self.reduce_op, distributed_c10d.ReduceOp):NEWLINE raise ValueError(NEWLINE "reduce_op needs to be a member of distributed_c10d.ReduceOp."NEWLINE )NEWLINENEWLINE def reshard(self, resharding_spec: ShardingSpec) -> ShardedTensor:NEWLINE """NEWLINE The reshard happens in two steps logically:NEWLINENEWLINE 1. Aggregate all the shards of the partial tensor.NEWLINE 2. Shard this tensor according to the provided spec.NEWLINENEWLINE In reality, for the sake of performance, we consolidate all partial tensorsNEWLINE across multiple ranks and covert to a sharded tensor in one step.NEWLINENEWLINE Args:NEWLINE resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`):NEWLINE The specification describing how we reshard the aggregated local result.NEWLINENEWLINE Returns:NEWLINE A :class:`ShardedTensor` filled with local aggregated result.NEWLINE """NEWLINE if not isinstance(resharding_spec, ChunkShardingSpec):NEWLINE raise NotImplementedError("Only ChunkShardingSpec supported for reshard.")NEWLINE sharding_dim = int(resharding_spec.dim) # type: ignore[attr-defined]NEWLINE if self.local_shard.size(sharding_dim) % self.process_group.size() != 0:NEWLINE raise ValueError('World size need to divide the length of the dimension.')NEWLINE if self.local_shard.is_complex():NEWLINE raise NotImplementedError("Only real partial tensor supported for reshard.")NEWLINENEWLINE local_shards = self.local_shard.chunk(self.process_group.size(), dim=sharding_dim)NEWLINE local_result = reduce_scatter(NEWLINE torch.empty_like(local_shards[0]), list(local_shards), op=self.reduce_opNEWLINE )NEWLINENEWLINE sharded_tensor_size = self.local_shard.size()NEWLINE current_offsets = [0] * len(local_result.size())NEWLINE shards = []NEWLINE rank = self.process_group.rank()NEWLINE for idx, placement in enumerate(resharding_spec.placements): # type: ignore[attr-defined]NEWLINE if rank == placement.rank(): # type: ignore[union-attr]NEWLINE local_metadata = ShardMetadata(NEWLINE shard_offsets=current_offsets,NEWLINE shard_sizes=list(local_result.size()),NEWLINE placement=placement,NEWLINE )NEWLINE shards.append(Shard(local_result, local_metadata))NEWLINE breakNEWLINE current_offsets[sharding_dim] += local_result.size(sharding_dim) # type: ignore[index]NEWLINENEWLINE st = ShardedTensor._init_from_local_shards(NEWLINE shards, tuple(sharded_tensor_size), process_group=self.process_groupNEWLINE )NEWLINE st._sharding_spec = copy.deepcopy(resharding_spec)NEWLINENEWLINE return stNEWLINE from __future__ import print_function, division, absolute_importNEWLINENEWLINEimport osNEWLINEimport timeNEWLINEimport subprocessNEWLINEfrom contextlib import contextmanagerNEWLINENEWLINEimport pytestNEWLINENEWLINEimport skeinNEWLINENEWLINENEWLINE@contextmanagerNEWLINEdef set_skein_config(tmpdir):NEWLINE tmpdir = str(tmpdir)NEWLINE old = skein.properties.config_dirNEWLINE try:NEWLINE skein.properties._mapping['config_dir'] = tmpdirNEWLINE yield tmpdirNEWLINE finally:NEWLINE skein.properties._mapping['config_dir'] = oldNEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef skein_config(tmpdir_factory):NEWLINE with set_skein_config(tmpdir_factory.mktemp('config')) as config:NEWLINE yield configNEWLINENEWLINENEWLINE@pytest.fixture(scope="session")NEWLINEdef security(tmpdir_factory):NEWLINE return skein.Security.from_new_directory(str(tmpdir_factory.mktemp('security')))NEWLINENEWLINENEWLINE@pytest.fixture(scope="session")NEWLINEdef has_kerberos_enabled():NEWLINE return HAS_KERBEROSNEWLINENEWLINENEWLINEKEYTAB_PATH = "/home/testuser/testuser.keytab"NEWLINEHAS_KERBEROS = os.path.exists(KEYTAB_PATH)NEWLINENEWLINENEWLINEdef do_kinit():NEWLINE subprocess.check_call(["kinit", "-kt", KEYTAB_PATH, "testuser"])NEWLINENEWLINENEWLINE@pytest.fixture(scope="session")NEWLINEdef kinit():NEWLINE if HAS_KERBEROS:NEWLINE do_kinit()NEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef not_logged_in():NEWLINE if not HAS_KERBEROS:NEWLINE pytest.skip("Without kerberos, users are always logged in")NEWLINE try:NEWLINE subprocess.check_call(["kdestroy"])NEWLINE yieldNEWLINE finally:NEWLINE do_kinit()NEWLINENEWLINENEWLINE@pytest.fixture(scope="session")NEWLINEdef client(security, kinit):NEWLINE with skein.Client(security=security) as client:NEWLINE yield clientNEWLINENEWLINENEWLINEsleeper = skein.Service(resources=skein.Resources(memory=128, vcores=1),NEWLINE commands=['sleep infinity'])NEWLINENEWLINENEWLINEsleep_until_killed = skein.ApplicationSpec(name="sleep_until_killed",NEWLINE queue="default",NEWLINE tags={'sleeps'},NEWLINE services={'sleeper': sleeper})NEWLINENEWLINENEWLINEdef check_is_shutdown(client, app_id, status=None):NEWLINE timeleft = 5NEWLINE while timeleft:NEWLINE if client.application_report(app_id).state != 'RUNNING':NEWLINE breakNEWLINE time.sleep(0.1)NEWLINE timeleft -= 0.1NEWLINE else:NEWLINE assert False, "Application wasn't properly terminated"NEWLINENEWLINE if status is not None:NEWLINE assert client.application_report(app_id).final_status == statusNEWLINENEWLINENEWLINEdef wait_for_completion(client, app_id, timeout=30):NEWLINE while timeout:NEWLINE final_status = client.application_report(app_id).final_statusNEWLINE if final_status != 'UNDEFINED':NEWLINE return final_statusNEWLINE time.sleep(0.1)NEWLINE timeout -= 0.1NEWLINE else:NEWLINE assert False, "Application timed out"NEWLINENEWLINENEWLINE@contextmanagerNEWLINEdef ensure_shutdown(client, app_id, status=None):NEWLINE try:NEWLINE yieldNEWLINE except Exception:NEWLINE client.kill_application(app_id)NEWLINE raiseNEWLINE finally:NEWLINE try:NEWLINE check_is_shutdown(client, app_id, status=status)NEWLINE except AssertionError:NEWLINE client.kill_application(app_id)NEWLINE raiseNEWLINENEWLINENEWLINE@contextmanagerNEWLINEdef run_application(client, spec=sleep_until_killed):NEWLINE app = client.submit_and_connect(spec)NEWLINE with ensure_shutdown(client, app.id):NEWLINE yield appNEWLINENEWLINENEWLINEdef wait_for_containers(app, n, **kwargs):NEWLINE timeleft = 5NEWLINE while timeleft:NEWLINE containers = app.get_containers(**kwargs)NEWLINE if len(containers) == n:NEWLINE breakNEWLINE time.sleep(0.1)NEWLINE timeleft -= 0.1NEWLINE else:NEWLINE assert False, "timeout"NEWLINENEWLINE return containersNEWLINENEWLINENEWLINEdef get_logs(app_id, tries=3):NEWLINE command = ["yarn", "logs", "-applicationId", app_id]NEWLINE for i in range(tries - 1):NEWLINE try:NEWLINE return subprocess.check_output(command).decode()NEWLINE except Exception:NEWLINE passNEWLINE return subprocess.check_output(command).decode()NEWLINE # SETTINGNEWLINEimport osNEWLINENEWLINEencoding_ = 'utf_8_sig'NEWLINEtime_zone = 'Asia/Shanghai'NEWLINEpool_max_workers = 8NEWLINEdefault_options_ = {NEWLINE 'encoding': encoding_,NEWLINE}NEWLINEbase_dir = os.path.dirname(os.path.abspath(__file__)).replace("\\", "/")NEWLINEstatic_dir = os.path.join(base_dir, 'static').replace("\\", "/")NEWLINEdefault_wkhtmltopdf_path = f'{base_dir}/bin/wkhtmltopdf.exe'NEWLINEdefault_wkhtmltoimage_path = f'{base_dir}/bin/wkhtmltoimage.exe'NEWLINENEWLINE# default_wkhtmltopdf_path = r'D:/wkhtmltopdf/bin/wkhtmltopdf.exe'NEWLINE# default_wkhtmltoimage_path = r'D:/wkhtmltopdf/bin/wkhtmltoimage.exe'NEWLINENEWLINEecho_info = '{}{} → {} exported successfully' from __future__ import absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7NEWLINENEWLINE# Importing the Kratos LibraryNEWLINEimport KratosMultiphysicsNEWLINENEWLINE# Import applicationsNEWLINEimport KratosMultiphysics.ConvectionDiffusionApplication as KratosConvDiffNEWLINEimport KratosMultiphysics.MultilevelMonteCarloApplication as KratosMLMCNEWLINENEWLINE# Avoid printing of Kratos informationsNEWLINEKratosMultiphysics.Logger.GetDefaultOutput().SetSeverity(KratosMultiphysics.Logger.Severity.WARNING) # avoid printing of Kratos thingsNEWLINENEWLINE# Importing the base classNEWLINEfrom analysis_stage import AnalysisStageNEWLINENEWLINE# Import packagesNEWLINEimport numpy as npNEWLINENEWLINE# Import Monte Carlo libraryNEWLINEimport mc_utilities as mcNEWLINENEWLINE# Import cpickle to pickle the serializerNEWLINEtry:NEWLINE import cpickle as pickle # Use cPickle on Python 2.7NEWLINEexcept ImportError:NEWLINE import pickleNEWLINENEWLINE# Import exaquteNEWLINEfrom exaqute.ExaquteTaskPyCOMPSs import * # to execute with pycompssNEWLINE# from exaqute.ExaquteTaskHyperLoom import * # to execute with the IT4 schedulerNEWLINE# from exaqute.ExaquteTaskLocal import * # to execute with python3NEWLINE'''NEWLINEget_value_from_remote is the equivalent of compss_wait_on: a synchronization pointNEWLINEin future, when everything is integrated with the it4i team, importing exaqute.ExaquteTaskHyperLoom you can launch your code with their scheduler instead of BSCNEWLINE'''NEWLINENEWLINENEWLINE'''Adapt the following class depending on the problem, deriving the MonteCarloAnalysis class from the problem of interest'''NEWLINENEWLINE'''NEWLINEThis Analysis Stage implementation solves the elliptic PDE in (0,1)^2 with zero Dirichlet boundary conditionsNEWLINE-lapl(u) = xi*f, f= -432*x*(x-1)*y*(y-1)NEWLINE f= -432*(x**2+y**2-x-y)NEWLINEwhere xi is a Beta(2,6) random variable, and computes statistic of the QoINEWLINEQ = int_(0,1)^2 u(x,y)dxdyNEWLINE'''NEWLINEclass MonteCarloAnalysis(AnalysisStage):NEWLINE '''Main analysis stage for Monte Carlo simulations'''NEWLINE def __init__(self,input_model,input_parameters,sample):NEWLINE self.sample = sampleNEWLINE super(MonteCarloAnalysis,self).__init__(input_model,input_parameters)NEWLINE self._GetSolver().main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.NODAL_AREA)NEWLINENEWLINE def _CreateSolver(self):NEWLINE import convection_diffusion_stationary_solverNEWLINE return convection_diffusion_stationary_solver.CreateSolver(self.model,self.project_parameters["solver_settings"])NEWLINENEWLINE def _GetSimulationName(self):NEWLINE return "Monte Carlo Analysis"NEWLINENEWLINE '''Introduce here the stochasticity in the right hand side defining the forcing function and apply the stochastic contribute'''NEWLINE def ModifyInitialProperties(self):NEWLINE for node in self.model.GetModelPart("MLMCLaplacianModelPart").Nodes:NEWLINE coord_x = node.XNEWLINE coord_y = node.YNEWLINE # forcing = -432.0 * coord_x * (coord_x - 1) * coord_y * (coord_y - 1)NEWLINE forcing = -432.0 * (coord_x**2 + coord_y**2 - coord_x - coord_y) # this forcing presents the below commented analytical solutionNEWLINE node.SetSolutionStepValue(KratosMultiphysics.HEAT_FLUX,forcing*self.sample)NEWLINENEWLINENEWLINE##################################################NEWLINE######## END OF CLASS MONTECARLOANALYSIS #########NEWLINE##################################################NEWLINENEWLINENEWLINE'''NEWLINEfunction generating the random sampleNEWLINEhere the sample has a beta distribution with parameters alpha = 2.0 and beta = 6.0NEWLINE'''NEWLINEdef GenerateSample():NEWLINE alpha = 2.0NEWLINE beta = 6.0NEWLINE number_samples = 1NEWLINE sample = np.random.beta(alpha,beta,number_samples)NEWLINE return sampleNEWLINENEWLINENEWLINE'''NEWLINEfunction evaluating the QoI of the problem: int_{domain} TEMPERATURE(x,y) dx dyNEWLINEright now we are using the midpoint rule to evaluate the integral: improve!NEWLINE'''NEWLINEdef EvaluateQuantityOfInterest(simulation):NEWLINE """here we evaluate the QoI of the problem: int_{domain} SOLUTION(x,y) dx dyNEWLINE we use the midpoint rule to evaluate the integral"""NEWLINE KratosMultiphysics.CalculateNodalAreaProcess(simulation._GetSolver().main_model_part,2).Execute()NEWLINE Q = 0.0NEWLINE for node in simulation._GetSolver().main_model_part.Nodes:NEWLINE Q = Q + (node.GetSolutionStepValue(KratosMultiphysics.NODAL_AREA)*node.GetSolutionStepValue(KratosMultiphysics.TEMPERATURE))NEWLINE return QNEWLINENEWLINENEWLINE'''NEWLINEfunction called in the main returning a future object (the result class) and an integer (the finer level)NEWLINEinput:NEWLINE pickled_coarse_model : pickled modelNEWLINE pickled_coarse_parameters : pickled parametersNEWLINEoutput:NEWLINE MonteCarloResults class : class of the simulation resultsNEWLINE current_MC_level : level of the current MLMC simulationNEWLINE'''NEWLINEdef ExecuteMonteCarloAnalysis(pickled_model, pickled_parameters):NEWLINE current_MC_level = 0 # MC has only level 0NEWLINE return (ExecuteMonteCarloAnalysis_Task(pickled_model, pickled_parameters),current_MC_level)NEWLINENEWLINENEWLINE'''NEWLINEfunction executing the problemNEWLINEinput:NEWLINE model : serialization of the modelNEWLINE parameters : serialization of the Project ParametersNEWLINEoutput:NEWLINE QoI : Quantity of InterestNEWLINE'''NEWLINE@ExaquteTask(returns=1)NEWLINEdef ExecuteMonteCarloAnalysis_Task(pickled_model, pickled_parameters):NEWLINE '''overwrite the old model serializer with the unpickled one'''NEWLINE model_serializer = pickle.loads(pickled_model)NEWLINE current_model = KratosMultiphysics.Model()NEWLINE model_serializer.Load("ModelSerialization",current_model)NEWLINE del(model_serializer)NEWLINE '''overwrite the old parameters serializer with the unpickled one'''NEWLINE serialized_parameters = pickle.loads(pickled_parameters)NEWLINE current_parameters = KratosMultiphysics.Parameters()NEWLINE serialized_parameters.Load("ParametersSerialization",current_parameters)NEWLINE del(serialized_parameters)NEWLINE '''initialize the MonteCarloResults class'''NEWLINE current_level = 0 # always 0 for MCNEWLINE mc_results_class = mc.MonteCarloResults(current_level)NEWLINE sample = GenerateSample()NEWLINE simulation = MonteCarloAnalysis(current_model,current_parameters,sample)NEWLINE simulation.Run()NEWLINE QoI = EvaluateQuantityOfInterest(simulation)NEWLINE mc_results_class.QoI[current_level].append(QoI) # saving results in the corresponding list, for MC only list of level 0NEWLINE return mc_results_classNEWLINENEWLINENEWLINE'''NEWLINEfunction serializing and pickling the model and the parameters of the problemNEWLINEthe idea is the following:NEWLINEi) from Model/Parameters Kratos object to StreamSerializer Kratos objectNEWLINEii) from StreamSerializer Kratos object to pickle stringNEWLINEiii) from pickle string to StreamSerializer Kratos objectNEWLINEiv) from StreamSerializer Kratos object to Model/Parameters Kratos objectNEWLINEinput:NEWLINE parameter_file_name : path of the Project Parameters fileNEWLINEoutput:NEWLINE pickled_model : model serializatonNEWLINE pickled_parameters : project parameters serializationNEWLINE'''NEWLINE@ExaquteTask(parameter_file_name=FILE_IN,returns=2)NEWLINEdef SerializeModelParameters_Task(parameter_file_name):NEWLINE with open(parameter_file_name,'r') as parameter_file:NEWLINE parameters = KratosMultiphysics.Parameters(parameter_file.read())NEWLINE local_parameters = parametersNEWLINE model = KratosMultiphysics.Model()NEWLINE # local_parameters["solver_settings"]["model_import_settings"]["input_filename"].SetString(model_part_file_name[:-5])NEWLINE fake_sample = GenerateSample()NEWLINE simulation = MonteCarloAnalysis(model,local_parameters,fake_sample)NEWLINE simulation.Initialize()NEWLINE serialized_model = KratosMultiphysics.StreamSerializer()NEWLINE serialized_model.Save("ModelSerialization",simulation.model)NEWLINE serialized_parameters = KratosMultiphysics.StreamSerializer()NEWLINE serialized_parameters.Save("ParametersSerialization",simulation.project_parameters)NEWLINE # pickle dataserialized_dataNEWLINE pickled_model = pickle.dumps(serialized_model, 2) # second argument is the protocol and is NECESSARY (according to pybind11 docs)NEWLINE pickled_parameters = pickle.dumps(serialized_parameters, 2)NEWLINE print("\n","#"*50," SERIALIZATION COMPLETED ","#"*50,"\n")NEWLINE return pickled_model,pickled_parametersNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINENEWLINE '''set the ProjectParameters.json path'''NEWLINE parameter_file_name = "../tests/PoissonSquareTest/parameters_poisson_finer.json"NEWLINE '''create a serialization of the model and of the project parameters'''NEWLINE pickled_model,pickled_parameters = SerializeModelParameters_Task(parameter_file_name)NEWLINE '''customize setting parameters of the ML simulation'''NEWLINE settings_MC_simulation = KratosMultiphysics.Parameters("""NEWLINE {NEWLINE "tolerance" : 0.1,NEWLINE "cphi" : 5e-1,NEWLINE "batch_size" : 20,NEWLINE "convergence_criteria" : "MC_higher_moments_sequential_stopping_rule"NEWLINE }NEWLINE """)NEWLINE '''contruct MonteCarlo class'''NEWLINE mc_class = mc.MonteCarlo(settings_MC_simulation)NEWLINE '''start MC algorithm'''NEWLINE while mc_class.convergence is not True:NEWLINE mc_class.InitializeMCPhase()NEWLINE mc_class.ScreeningInfoInitializeMCPhase()NEWLINE for instance in range (mc_class.difference_number_samples[0]):NEWLINE mc_class.AddResults(ExecuteMonteCarloAnalysis(pickled_model,pickled_parameters))NEWLINE mc_class.FinalizeMCPhase()NEWLINE mc_class.ScreeningInfoFinalizeMCPhase()NEWLINENEWLINE mc_class.QoI.mean = get_value_from_remote(mc_class.QoI.mean)NEWLINE print("\nMC mean = ",mc_class.QoI.mean)NEWLINENEWLINENEWLINE ''' The below part evaluates the relative L2 error between the numerical solution SOLUTION(x,y,sample) and the analytical solution, also dependent on sample.NEWLINE Analytical solution available in case FORCING = sample * -432.0 * (coord_x**2 + coord_y**2 - coord_x - coord_y)'''NEWLINE # model_serializer = pickle.loads(pickled_model)NEWLINE # current_model = KratosMultiphysics.Model()NEWLINE # model_serializer.Load("ModelSerialization",current_model)NEWLINE # del(model_serializer)NEWLINE # serialized_parameters = pickle.loads(pickled_parameters)NEWLINE # current_parameters = KratosMultiphysics.Parameters()NEWLINE # serialized_parameters.Load("ParametersSerialization",current_parameters)NEWLINE # del(serialized_parameters)NEWLINE # sample = 1.0NEWLINE # simulation = MonteCarloAnalysis(current_model,current_parameters,sample)NEWLINE # simulation.Run()NEWLINE # KratosMultiphysics.CalculateNodalAreaProcess(simulation._GetSolver().main_model_part,2).Execute()NEWLINE # error = 0.0NEWLINE # L2norm_analyticalsolution = 0.0NEWLINE # for node in simulation._GetSolver().main_model_part.Nodes:NEWLINE # local_error = ((node.GetSolutionStepValue(KratosMultiphysics.TEMPERATURE) - (432.0*simulation.sample*node.X*node.Y*(1-node.X)*(1-node.Y)*0.5))**2) * node.GetSolutionStepValue(KratosMultiphysics.NODAL_AREA)NEWLINE # error = error + local_errorNEWLINE # local_analyticalsolution = (432.0*simulation.sample*node.X*node.Y*(1-node.X)*(1-node.Y)*0.5)**2 * node.GetSolutionStepValue(KratosMultiphysics.NODAL_AREA)NEWLINE # L2norm_analyticalsolution = L2norm_analyticalsolution + local_analyticalsolutionNEWLINE # error = np.sqrt(error)NEWLINE # L2norm_analyticalsolution = np.sqrt(L2norm_analyticalsolution)NEWLINE # print("L2 relative error = ", error/L2norm_analyticalsolution) from pylinsql.async_database import ConnectionParametersNEWLINEimport unittestNEWLINENEWLINENEWLINEclass DatabaseTestCase(unittest.IsolatedAsyncioTestCase):NEWLINE params: ConnectionParametersNEWLINENEWLINE def __init__(self, method_name: str):NEWLINE super().__init__(method_name)NEWLINE self.params = ConnectionParameters()NEWLINENEWLINE def assertEmpty(self, obj):NEWLINE self.assertFalse(obj)NEWLINENEWLINE def assertNotEmpty(self, obj):NEWLINE self.assertTrue(obj)NEWLINE from __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import unicode_literalsNEWLINEfrom collections import defaultdictNEWLINEfrom unittest import skipUnless, SkipTestNEWLINEfrom uuid import uuid4, UUIDNEWLINENEWLINEfrom django.conf import settingsNEWLINEfrom django.test import TestCaseNEWLINEfrom django.test.utils import override_settingsNEWLINENEWLINEfrom corehq.form_processor.backends.sql.dbaccessors import ShardAccessorNEWLINEfrom corehq.form_processor.models import XFormInstanceSQL, CommCareCaseSQLNEWLINEfrom corehq.form_processor.tests.utils import create_form_for_test, FormProcessorTestUtils, use_sql_backendNEWLINEfrom corehq.sql_db.config import partition_configNEWLINEimport sixNEWLINEfrom six.moves import rangeNEWLINENEWLINEDOMAIN = 'sharding-test'NEWLINENEWLINENEWLINE@use_sql_backendNEWLINE@skipUnless(settings.USE_PARTITIONED_DATABASE, 'Only applicable if sharding is setup')NEWLINEclass ShardingTests(TestCase):NEWLINENEWLINE @classmethodNEWLINE def setUpClass(cls):NEWLINE if not settings.USE_PARTITIONED_DATABASE:NEWLINE # https://github.com/nose-devs/nose/issues/946NEWLINE raise SkipTest('Only applicable if sharding is setup')NEWLINE super(ShardingTests, cls).setUpClass()NEWLINE assert len(partition_config.get_form_processing_dbs()) > 1NEWLINENEWLINE def tearDown(self):NEWLINE FormProcessorTestUtils.delete_all_sql_forms(DOMAIN)NEWLINE FormProcessorTestUtils.delete_all_sql_cases(DOMAIN)NEWLINE super(ShardingTests, self).tearDown()NEWLINENEWLINE def test_objects_only_in_one_db(self):NEWLINE case_id = uuid4().hexNEWLINE form = create_form_for_test(DOMAIN, case_id=case_id)NEWLINENEWLINE dbs_with_form = []NEWLINE dbs_with_case = []NEWLINE for db in partition_config.get_form_processing_dbs():NEWLINE form_in_db = XFormInstanceSQL.objects.using(db).filter(form_id=form.form_id).exists()NEWLINE if form_in_db:NEWLINE dbs_with_form.append(db)NEWLINENEWLINE case_in_db = CommCareCaseSQL.objects.using(db).filter(case_id=case_id).exists()NEWLINE if case_in_db:NEWLINE dbs_with_case.append(db)NEWLINENEWLINE self.assertEqual(1, len(dbs_with_form))NEWLINE self.assertEqual(1, len(dbs_with_case))NEWLINENEWLINE def test_objects_distributed_to_all_dbs(self):NEWLINE """NEWLINE Rudimentary test to ensure that not all cases / forms get saved to the same DB.NEWLINE """NEWLINE num_forms = 20NEWLINE for i in range(num_forms):NEWLINE create_form_for_test(DOMAIN, case_id=uuid4().hex)NEWLINENEWLINE forms_per_db = {}NEWLINE cases_per_db = {}NEWLINE for db in partition_config.get_form_processing_dbs():NEWLINE forms_per_db[db] = XFormInstanceSQL.objects.using(db).filter(domain=DOMAIN).count()NEWLINE cases_per_db[db] = CommCareCaseSQL.objects.using(db).filter(domain=DOMAIN).count()NEWLINENEWLINE self.assertEqual(num_forms, sum(forms_per_db.values()), forms_per_db)NEWLINE self.assertEqual(num_forms, sum(cases_per_db.values()), cases_per_db)NEWLINE self.assertTrue(NEWLINE all(num_forms_in_db < num_forms for num_forms_in_db in forms_per_db.values()),NEWLINE forms_per_dbNEWLINE )NEWLINE self.assertTrue(NEWLINE all(num_cases_in_db < num_forms for num_cases_in_db in cases_per_db.values()),NEWLINE cases_per_dbNEWLINE )NEWLINENEWLINE def test_python_hashing_gives_correct_db(self):NEWLINE # Rudimentary test to ensure that python sharding matches SQL shardingNEWLINE num_forms = 100NEWLINE form_ids = [create_form_for_test(DOMAIN).form_id for i in range(num_forms)]NEWLINENEWLINE dbs_for_docs = ShardAccessor.get_database_for_docs(form_ids)NEWLINE for form_id, db_alias in dbs_for_docs.items():NEWLINE XFormInstanceSQL.objects.using(db_alias).get(form_id=form_id)NEWLINENEWLINE def test_same_dbalias_util(self):NEWLINE from corehq.sql_db.util import get_db_alias_for_partitioned_doc, new_id_in_same_dbaliasNEWLINE for i in range(10):NEWLINE # test multiple times to test a wider probabilityNEWLINE f1_id = six.text_type(uuid4())NEWLINE old_db_alias = get_db_alias_for_partitioned_doc(f1_id)NEWLINE f2_id = new_id_in_same_dbalias(f1_id)NEWLINE new_db_alias = get_db_alias_for_partitioned_doc(f2_id)NEWLINE self.assertEqual(new_db_alias, old_db_alias)NEWLINENEWLINENEWLINEDATABASES = {NEWLINE key: {NEWLINE 'ENGINE': 'django.db.backends.sqlite3',NEWLINE 'NAME': key,NEWLINE } for key in ['default', 'proxy', 'p1', 'p2', 'p3', 'p4', 'p5']NEWLINE}NEWLINENEWLINENEWLINEPARTITION_DATABASE_CONFIG = {NEWLINE 'shards': {NEWLINE 'p1': [0, 204],NEWLINE 'p2': [205, 409],NEWLINE 'p3': [410, 614],NEWLINE 'p4': [615, 819],NEWLINE 'p5': [820, 1023]NEWLINE },NEWLINE 'groups': {NEWLINE 'main': ['default'],NEWLINE 'proxy': ['proxy'],NEWLINE 'form_processing': ['p1', 'p2', 'p3', 'p4', 'p5'],NEWLINE }NEWLINE}NEWLINENEWLINENEWLINE@use_sql_backendNEWLINE@override_settings(PARTITION_DATABASE_CONFIG=PARTITION_DATABASE_CONFIG, DATABASES=DATABASES)NEWLINE@skipUnless(settings.USE_PARTITIONED_DATABASE, 'Only applicable if sharding is setup')NEWLINEclass ShardAccessorTests(TestCase):NEWLINENEWLINE @classmethodNEWLINE def setUpClass(cls):NEWLINE if not settings.USE_PARTITIONED_DATABASE:NEWLINE # https://github.com/nose-devs/nose/issues/946NEWLINE raise SkipTest('Only applicable if sharding is setup')NEWLINE super(ShardAccessorTests, cls).setUpClass()NEWLINE partition_config.get_django_shard_map.reset_cache(partition_config)NEWLINE partition_config.get_shards.reset_cache(partition_config)NEWLINE partition_config._get_django_shards.reset_cache(partition_config)NEWLINENEWLINE @classmethodNEWLINE def tearDownClass(cls):NEWLINE partition_config.get_django_shard_map.reset_cache(partition_config)NEWLINE partition_config.get_shards.reset_cache(partition_config)NEWLINE partition_config._get_django_shards.reset_cache(partition_config)NEWLINE super(ShardAccessorTests, cls).tearDownClass()NEWLINENEWLINE def test_hash_doc_ids(self):NEWLINE N = 1001NEWLINE doc_ids = [str(i) for i in range(N)]NEWLINE hashes = ShardAccessor.hash_doc_ids_sql_for_testing(doc_ids)NEWLINE self.assertEquals(len(hashes), N)NEWLINE self.assertTrue(all(isinstance(hash_, int) for hash_ in hashes.values()))NEWLINENEWLINE def test_get_database_for_docs(self):NEWLINE # test that sharding 1000 docs gives a distribution withing some toleranceNEWLINE # (bit of a vague test)NEWLINE N = 1000NEWLINE doc_ids = [str(i) for i in range(N)]NEWLINE doc_db_map = ShardAccessor.get_database_for_docs(doc_ids)NEWLINE doc_count_per_db = defaultdict(int)NEWLINE for db_alias in doc_db_map.values():NEWLINE doc_count_per_db[db_alias] += 1NEWLINENEWLINE num_dbs = len(partition_config.get_form_processing_dbs())NEWLINE even_split = int(N // num_dbs)NEWLINE tolerance = N * 0.05 # 5% tolleranceNEWLINE diffs = [abs(even_split - count) for count in doc_count_per_db.values()]NEWLINE outliers = [diff for diff in diffs if diff > tolerance]NEWLINE message = 'partitioning not within tollerance: tolerance={}, diffs={}'.format(tolerance, diffs)NEWLINE self.assertEqual(len(outliers), 0, message)NEWLINENEWLINE def test_hash_in_python(self):NEWLINE # test that python hashing matches with SQL hashingNEWLINE N = 2048NEWLINE doc_ids = [str(i) for i in range(N)]NEWLINENEWLINE sql_hashes = ShardAccessor.hash_doc_ids_sql_for_testing(doc_ids)NEWLINENEWLINE csiphash_hashes = ShardAccessor.hash_doc_ids_python(doc_ids)NEWLINE self.assertEquals(len(csiphash_hashes), N)NEWLINE self.assertTrue(all(isinstance(hash_, six.integer_types) for hash_ in csiphash_hashes.values()))NEWLINENEWLINE N_shards = 1024NEWLINE part_mask = N_shards - 1NEWLINENEWLINE sql_shards = {doc_id: hash_ & part_mask for doc_id, hash_ in sql_hashes.items()}NEWLINE python_shards = {doc_id: hash_ & part_mask for doc_id, hash_ in sql_hashes.items()}NEWLINENEWLINE self.assertEqual(python_shards, sql_shards)NEWLINENEWLINE def test_hash_uuid(self):NEWLINE uuid = UUID('403724ef9fe141f2908363918c62c2ff')NEWLINE self.assertEqual(ShardAccessor.hash_doc_id_python(uuid), 1415444857)NEWLINE self.assertEqual(ShardAccessor.hash_doc_uuid_sql_for_testing(uuid), 1415444857)NEWLINE import osNEWLINEimport pytestNEWLINEimport subprocessNEWLINEimport sysNEWLINEimport timeNEWLINEimport fsspecNEWLINEfrom distutils.version import LooseVersionNEWLINENEWLINEfrom dask.bytes.core import open_filesNEWLINEfrom dask.bytes._compatibility import FSSPEC_042NEWLINEfrom dask.utils import tmpdirNEWLINENEWLINEfiles = ["a", "b"]NEWLINErequests = pytest.importorskip("requests")NEWLINEerrs = (requests.exceptions.RequestException,)NEWLINEif LooseVersion(fsspec.__version__) > "0.7.4":NEWLINE aiohttp = pytest.importorskip("aiohttp")NEWLINE errs = errs + (aiohttp.client_exceptions.ClientResponseError,)NEWLINENEWLINENEWLINE@pytest.fixture(scope="module")NEWLINEdef dir_server():NEWLINE with tmpdir() as d:NEWLINE for fn in files:NEWLINE with open(os.path.join(d, fn), "wb") as f:NEWLINE f.write(b"a" * 10000)NEWLINENEWLINE cmd = [sys.executable, "-m", "http.server", "8999"]NEWLINE p = subprocess.Popen(cmd, cwd=d)NEWLINE timeout = 10NEWLINE while True:NEWLINE try:NEWLINE requests.get("http://localhost:8999")NEWLINE breakNEWLINE except requests.exceptions.ConnectionError as e:NEWLINE time.sleep(0.1)NEWLINE timeout -= 0.1NEWLINE if timeout < 0:NEWLINE raise RuntimeError("Server did not appear") from eNEWLINE yield dNEWLINE p.terminate()NEWLINENEWLINENEWLINEdef test_simple(dir_server):NEWLINE root = "http://localhost:8999/"NEWLINE fn = files[0]NEWLINE f = open_files(root + fn)[0]NEWLINE with f as f:NEWLINE data = f.read()NEWLINE assert data == open(os.path.join(dir_server, fn), "rb").read()NEWLINENEWLINENEWLINEdef test_loc(dir_server):NEWLINE root = "http://localhost:8999/"NEWLINE fn = files[0]NEWLINE f = open_files(root + fn)[0]NEWLINE expected = open(os.path.join(dir_server, fn), "rb").read()NEWLINE with f as f:NEWLINE data = f.read(2)NEWLINE assert data == expected[:2]NEWLINE assert f.loc == 2NEWLINE f.seek(0)NEWLINE data = f.read(3)NEWLINE assert data == expected[:3]NEWLINE f.seek(1, 1)NEWLINE assert f.loc == 4NEWLINENEWLINENEWLINEdef test_fetch_range_with_headers(dir_server):NEWLINE # https://github.com/dask/dask/issues/4479NEWLINE root = "http://localhost:8999/"NEWLINE fn = files[0]NEWLINE headers = {"Date": "Wed, 21 Oct 2015 07:28:00 GMT"}NEWLINE f = open_files(root + fn, headers=headers)[0]NEWLINE with f as f:NEWLINE data = f.read(length=1) + f.read(length=-1)NEWLINE assert data == open(os.path.join(dir_server, fn), "rb").read()NEWLINENEWLINENEWLINE@pytest.mark.parametrize("block_size", [None, 99999])NEWLINEdef test_ops(dir_server, block_size):NEWLINE root = "http://localhost:8999/"NEWLINE fn = files[0]NEWLINE f = open_files(root + fn)[0]NEWLINE data = open(os.path.join(dir_server, fn), "rb").read()NEWLINE with f as f:NEWLINE # these pass because the defaultNEWLINE assert f.read(10) == data[:10]NEWLINE f.seek(0)NEWLINE assert f.read(10) == data[:10]NEWLINE assert f.read(10) == data[10:20]NEWLINE f.seek(-10, 2)NEWLINE assert f.read() == data[-10:]NEWLINENEWLINENEWLINEdef test_ops_blocksize(dir_server):NEWLINE root = "http://localhost:8999/"NEWLINE fn = files[0]NEWLINE f = open_files(root + fn, block_size=2)[0]NEWLINE data = open(os.path.join(dir_server, fn), "rb").read()NEWLINE with f as f:NEWLINE # it's OK to read the whole fileNEWLINE assert f.read() == dataNEWLINE # and now the file magically has a sizeNEWLINE assert f.size == len(data)NEWLINENEWLINE # note that if we reuse f from above, because it is tokenized, we getNEWLINE # the same open file - where is this cached?NEWLINE fn = files[1]NEWLINE f = open_files(root + fn, block_size=2)[0]NEWLINE with f as f:NEWLINE # fails because we want only 12 bytesNEWLINE with pytest.raises(ValueError):NEWLINE assert f.read(10) == data[:10]NEWLINENEWLINENEWLINEdef test_errors(dir_server):NEWLINE f = open_files("http://localhost:8999/doesnotexist")[0]NEWLINE with pytest.raises(errs):NEWLINE with f as f:NEWLINE f.read()NEWLINE f = open_files("http://nohost/")[0]NEWLINENEWLINE if FSSPEC_042:NEWLINE expected = FileNotFoundErrorNEWLINE else:NEWLINE expected = requests.exceptions.RequestExceptionNEWLINENEWLINE with pytest.raises(expected):NEWLINE with f as f:NEWLINE f.read()NEWLINE root = "http://localhost:8999/"NEWLINE fn = files[0]NEWLINE f = open_files(root + fn, mode="wb")[0]NEWLINE with pytest.raises(NotImplementedError):NEWLINE with f:NEWLINE passNEWLINE f = open_files(root + fn)[0]NEWLINE with f as f:NEWLINE with pytest.raises(ValueError):NEWLINE f.seek(-1)NEWLINENEWLINENEWLINEdef test_files(dir_server):NEWLINE root = "http://localhost:8999/"NEWLINE fs = open_files([root + f for f in files])NEWLINE for f, f2 in zip(fs, files):NEWLINE with f as f:NEWLINE assert f.read() == open(os.path.join(dir_server, f2), "rb").read()NEWLINENEWLINENEWLINEdef test_open_glob(dir_server):NEWLINE root = "http://localhost:8999/"NEWLINE fs = open_files(root + "/*")NEWLINE assert fs[0].path == "http://localhost:8999/a"NEWLINE assert fs[1].path == "http://localhost:8999/b"NEWLINENEWLINENEWLINE@pytest.mark.networkNEWLINE@pytest.mark.xfail(reason="https://github.com/dask/dask/issues/5042", strict=False)NEWLINEdef test_parquet():NEWLINE pytest.importorskip("requests", minversion="2.21.0")NEWLINE dd = pytest.importorskip("dask.dataframe")NEWLINE pytest.importorskip("fastparquet") # no pyarrow compatibility FS yetNEWLINE df = dd.read_parquet(NEWLINE [NEWLINE "https://github.com/Parquet/parquet-compatibility/raw/"NEWLINE "master/parquet-testdata/impala/1.1.1-NONE/"NEWLINE "nation.impala.parquet"NEWLINE ]NEWLINE ).compute()NEWLINE assert df.n_nationkey.tolist() == list(range(25))NEWLINE assert df.columns.tolist() == ["n_nationkey", "n_name", "n_regionkey", "n_comment"]NEWLINENEWLINENEWLINE@pytest.mark.xfail(reason="https://github.com/dask/dask/issues/3696", strict=False)NEWLINE@pytest.mark.networkNEWLINEdef test_bag():NEWLINE # This test pulls from different hostsNEWLINE db = pytest.importorskip("dask.bag")NEWLINE urls = [NEWLINE "https://raw.githubusercontent.com/weierophinney/pastebin/"NEWLINE "master/public/js-src/dojox/data/tests/stores/patterns.csv",NEWLINE "https://en.wikipedia.org",NEWLINE ]NEWLINE b = db.read_text(urls)NEWLINE assert b.npartitions == 2NEWLINE b.compute()NEWLINENEWLINENEWLINE@pytest.mark.xfail(NEWLINE LooseVersion(fsspec.__version__) <= "0.4.1",NEWLINE reason="https://github.com/dask/dask/pull/5231",NEWLINE)NEWLINE@pytest.mark.networkNEWLINEdef test_read_csv():NEWLINE dd = pytest.importorskip("dask.dataframe")NEWLINE url = (NEWLINE "https://raw.githubusercontent.com/weierophinney/pastebin/"NEWLINE "master/public/js-src/dojox/data/tests/stores/patterns.csv"NEWLINE )NEWLINE b = dd.read_csv(url)NEWLINE b.compute()NEWLINE #!/usr/bin/pythonNEWLINE#NEWLINE# pybuddyDXNEWLINE# python e-buddy (ibuddy alike sold on DX) daemonNEWLINE# http://code.google.com/p/pybuddyDXNEWLINE#NEWLINE# protocol reverse engineered and implemented byNEWLINE# peter.dhoye@gmail.comNEWLINE#NEWLINE# borrows code from http://code.google.com/p/pybuddyNEWLINE# by Jose.Carlos.Luna@gmail.com and luis.peralta@gmail.comNEWLINE# who got most of the code from http://cuntography.com/blog/?p=17NEWLINE# Which is based on http://scott.weston.id.au/software/pymissile/NEWLINENEWLINEimport usbNEWLINEimport timeNEWLINEimport sysNEWLINEimport socketNEWLINEimport osNEWLINEimport pwdNEWLINEimport loggingNEWLINEfrom ConfigParser import RawConfigParserNEWLINENEWLINE################NEWLINE#CommandsNEWLINE################NEWLINE# GLADNESS = 00NEWLINE# FEAR = 01NEWLINE# FIZZ = 02NEWLINE# PLEASANTSURPRISE =03NEWLINE# GRIEF = 04NEWLINE# FURY = 05NEWLINE# QUELL = 06NEWLINE# REDHEAD = 07NEWLINE# GREENHEAD = 08NEWLINE# BLUEHEAD = 09NEWLINE# YELLOWHEAD = 10NEWLINE# BLAME = 11NEWLINE# BLUEGREENHEAD = 12NEWLINE# WHITEHEAD = 13NEWLINE# HEART = 14NEWLINE# WINGS = 15NEWLINE# BODY = 16NEWLINE# NOEFFECT = 17NEWLINE# ONLINE = 18NEWLINE# BUSY = 19NEWLINE# DAZE = 20NEWLINE# BACKSOON = 21NEWLINE# AWAY = 22NEWLINE# PHONE = 23NEWLINE# LUNCH = 24NEWLINE# OFFLINE = 25NEWLINENEWLINE################NEWLINE#ConfigurationNEWLINE################NEWLINEtsleep = 0.1NEWLINENEWLINENEWLINE################NEWLINE# IBUDDY classNEWLINE################NEWLINENEWLINEclass BuddyDevice:NEWLINE SETUP = (0x21, 0x09, 0x00, 0x02, 0x00, 0x00, 0x04, 0x00)NEWLINE MESS = (0x43, 0x4D)NEWLINE NEWLINE OFF1 = 0x31NEWLINE OFF2 = 0x37NEWLINENEWLINE code1 = OFF1NEWLINE code2 = OFF2NEWLINENEWLINE def __init__(self):NEWLINE try:NEWLINE self.dev=UsbDevice(0x0c45, 0x11)NEWLINE self.dev.open()NEWLINE self.dev.handle.reset()NEWLINE self.resetMessage()NEWLINE except NoBuddyException, e:NEWLINE raise NoBuddyException()NEWLINE NEWLINE def resetMessage(self):NEWLINE self.code1 = self.OFF1NEWLINE self.code1 = self.OFF1NEWLINE self.send()NEWLINENEWLINE def send(self):NEWLINE try:NEWLINE self.dev.handle.controlMsg(0x21, 0x09, self.SETUP, 0x0200, 0x00)NEWLINE self.dev.handle.controlMsg(0x21, 0x09, self.MESS+(self.code1,self.code2), 0x0200, 0x00)NEWLINE except usb.USBError:NEWLINE log.info("Error sending USB command")NEWLINE raise NoBuddyException()NEWLINENEWLINE#####################NEWLINE# USB classNEWLINE######################NEWLINENEWLINEclass UsbDevice:NEWLINE def __init__(self, vendor_id, product_id):NEWLINE busses = usb.busses()NEWLINE self.handle = NoneNEWLINE for bus in busses:NEWLINE devices = bus.devicesNEWLINE for dev in devices:NEWLINE if dev.idVendor==vendor_id and dev.idProduct==product_id:NEWLINE log.info("DX e-buddy found!")NEWLINE# log.info("vend %s prod %s",dev.idVendor, dev.idProduct)NEWLINE self.dev = devNEWLINE self.conf = self.dev.configurations[0]NEWLINE self.intf = self.conf.interfaces[0][0]NEWLINE self.endpoints = []NEWLINE# log.info("interface = %x, class = %s, protocol = %s", self.intf.interfaceNumber, self.intf.interfaceClass, self.intf.interfaceProtocol)NEWLINE for endpoint in self.intf.endpoints:NEWLINE self.endpoints.append(endpoint)NEWLINE# log.info("endpoint number = %x, type = %s", endpoint.address, endpoint.type)NEWLINE returnNEWLINE raise NoBuddyException()NEWLINENEWLINE def open(self):NEWLINE if self.handle:NEWLINE self.handle = NoneNEWLINE self.handle = self.dev.open()NEWLINENEWLINE# if self.handle:NEWLINE# log.info("Handle OK")NEWLINENEWLINE #We need to detach HID interfaceNEWLINE try:NEWLINE self.handle.detachKernelDriver(0)NEWLINE self.handle.detachKernelDriver(1)NEWLINE except:NEWLINE passNEWLINENEWLINE try:NEWLINE self.handle.setConfiguration(self.conf)NEWLINE self.handle.claimInterface(0)NEWLINE self.handle.setAltInterface(0)NEWLINE except:NEWLINE log.info("Configuration failed")NEWLINE raise NoBuddyException()NEWLINENEWLINE# log.info("Device opened OK")NEWLINENEWLINEclass NoBuddyException(Exception): passNEWLINENEWLINENEWLINE#########################################NEWLINE# Decoding macrosNEWLINE##########################################NEWLINENEWLINENEWLINEdef decode_buddy (buddy,msg):NEWLINE# log.info("Received message: %s",msg)NEWLINE buddy.code1 = int(msg)/10 + 0x30NEWLINE buddy.code2 = int(msg) - (int(msg)/10)*10 + 0x30NEWLINE# log.info("Codes: %x %x",buddy.code1,buddy.code2)NEWLINENEWLINE#######################################NEWLINE# MAIN programNEWLINE#######################################NEWLINENEWLINElog = logging.getLogger('pybuddy')NEWLINENEWLINE#Default configNEWLINEconfig = RawConfigParser(NEWLINE { 'port': 8888,NEWLINE 'address': '127.0.0.1',NEWLINE 'user': 'nobody',NEWLINE 'loglevel': 'info',NEWLINE 'logfile': 'console',NEWLINE }NEWLINE)NEWLINENEWLINEconfig._sections = {'network':{}, 'system':{}}NEWLINENEWLINEconfig_files = [ "~/.pybuddy.cfg", NEWLINE "/etc/pybuddy/pybuddy.cfg", NEWLINE "/usr/local/etc/pybuddy.cfg"NEWLINE]NEWLINENEWLINE#Parse configNEWLINEif len(sys.argv) > 1:NEWLINE config_files.append(sys.argv[1])NEWLINE NEWLINEconfig_read = config.read(config_files)NEWLINENEWLINEif config.get("system", "logfile") != "console":NEWLINE logging.basicConfig(NEWLINE filename=config.get("system", "logfile"),NEWLINE format='%(asctime)s %(levelname)-8s %(message)s',NEWLINE )NEWLINEelse:NEWLINE logging.basicConfig(NEWLINE stream=sys.stderr,NEWLINE format='%(asctime)s %(levelname)-8s %(message)s',NEWLINE )NEWLINENEWLINENEWLINEif config.get("system", "loglevel") == "debug":NEWLINE log.setLevel(logging.DEBUG)NEWLINEelif config.get("system", "loglevel") == "info":NEWLINE log.setLevel(logging.INFO)NEWLINENEWLINENEWLINEif config_read:NEWLINE log.info("Read config file: %s", config_read[0])NEWLINE NEWLINE#Initialize deviceNEWLINElog.info("Searching e-buddy...")NEWLINEtry:NEWLINE buddy=BuddyDevice()NEWLINEexcept NoBuddyException, e:NEWLINE log.error("Not found or ERROR!")NEWLINE sys.exit(1)NEWLINENEWLINENEWLINE#DaemonizeNEWLINElog.info("Starting daemon...")NEWLINEif os.fork()==0:NEWLINE os.setsid()NEWLINEelse:NEWLINE sys.exit(0)NEWLINENEWLINE#Create server socketNEWLINEs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)NEWLINEs.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)NEWLINEs.bind((config.get("network", "address"), int(config.get("network", "port"))))NEWLINENEWLINE#Drop privilegesNEWLINEtry:NEWLINE uid = pwd.getpwnam(config.get("system", "user"))[2]NEWLINEexcept KeyError:NEWLINE log.error("Username %s not found, exiting...", config.get("system", "user"))NEWLINE sys.exit(1)NEWLINEos.setuid(uid)NEWLINENEWLINENEWLINE#Main message loopNEWLINEwhile 1:NEWLINE try:NEWLINE message, address = s.recvfrom(8192)NEWLINE# log.debug("Got data from %s", address)NEWLINE decode_buddy(buddy, message)NEWLINE buddy.send()NEWLINE except (KeyboardInterrupt, SystemExit):NEWLINE raiseNEWLINENEWLINE NEWLINE from rest_framework.status import HTTP_404_NOT_FOUNDNEWLINENEWLINENEWLINEERROR_GRID_DOES_NOT_EXIST = (NEWLINE "ERROR_GRID_DOES_NOT_EXIST",NEWLINE HTTP_404_NOT_FOUND,NEWLINE "The requested grid view does not exist.",NEWLINE)NEWLINE # coding=utf-8NEWLINE# --------------------------------------------------------------------------NEWLINE# Copyright (c) Microsoft Corporation. All rights reserved.NEWLINE# Licensed under the MIT License. See License.txt in the project root for license information.NEWLINE# Code generated by Microsoft (R) AutoRest Code Generator.NEWLINE# Changes may cause incorrect behavior and will be lost if the code is regenerated.NEWLINE# --------------------------------------------------------------------------NEWLINENEWLINEfrom typing import TYPE_CHECKINGNEWLINENEWLINEfrom azure.core.configuration import ConfigurationNEWLINEfrom azure.core.pipeline import policiesNEWLINEfrom azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicyNEWLINENEWLINEif TYPE_CHECKING:NEWLINE # pylint: disable=unused-import,ungrouped-importsNEWLINE from typing import AnyNEWLINENEWLINE from azure.core.credentials import AzureKeyCredentialNEWLINENEWLINEVERSION = "unknown"NEWLINENEWLINEclass MultiapiServiceClientConfiguration(Configuration):NEWLINE """Configuration for MultiapiServiceClient.NEWLINENEWLINE Note that all parameters used to create this instance are saved as instanceNEWLINE attributes.NEWLINENEWLINE :param credential: Credential needed for the client to connect to Azure.NEWLINE :type credential: ~azure.core.credentials.AzureKeyCredentialNEWLINE """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE credential, # type: AzureKeyCredentialNEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> NoneNEWLINE if credential is None:NEWLINE raise ValueError("Parameter 'credential' must not be None.")NEWLINE super(MultiapiServiceClientConfiguration, self).__init__(**kwargs)NEWLINENEWLINE self.credential = credentialNEWLINE self.api_version = "3.0.0"NEWLINE kwargs.setdefault('sdk_moniker', 'multiapicredentialdefaultpolicy/{}'.format(VERSION))NEWLINE self._configure(**kwargs)NEWLINENEWLINE def _configure(NEWLINE self,NEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> NoneNEWLINE self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)NEWLINE self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)NEWLINE self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs)NEWLINE self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs)NEWLINE self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs)NEWLINE self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs)NEWLINE self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs)NEWLINE self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs)NEWLINE self.authentication_policy = kwargs.get('authentication_policy')NEWLINE if self.credential and not self.authentication_policy:NEWLINE self.authentication_policy = policies.AzureKeyCredentialPolicy(self.credential, "api-key", **kwargs)NEWLINE # coding=utf-8NEWLINE# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***NEWLINE# *** Do not edit by hand unless you're certain you know what you are doing! ***NEWLINENEWLINEimport jsonNEWLINEimport warningsNEWLINEimport pulumiNEWLINEimport pulumi.runtimeNEWLINEfrom typing import UnionNEWLINEfrom .. import utilities, tablesNEWLINENEWLINEclass Registry(pulumi.CustomResource):NEWLINE admin_enabled: pulumi.Output[bool]NEWLINE """NEWLINE Specifies whether the admin user is enabled. Defaults to `false`.NEWLINE """NEWLINE admin_password: pulumi.Output[str]NEWLINE """NEWLINE The Password associated with the Container Registry Admin account - if the admin account is enabled.NEWLINE """NEWLINE admin_username: pulumi.Output[str]NEWLINE """NEWLINE The Username associated with the Container Registry Admin account - if the admin account is enabled.NEWLINE """NEWLINE georeplication_locations: pulumi.Output[list]NEWLINE """NEWLINE A list of Azure locations where the container registry should be geo-replicated.NEWLINE """NEWLINE location: pulumi.Output[str]NEWLINE """NEWLINE Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.NEWLINE """NEWLINE login_server: pulumi.Output[str]NEWLINE """NEWLINE The URL that can be used to log into the container registry.NEWLINE """NEWLINE name: pulumi.Output[str]NEWLINE """NEWLINE Specifies the name of the Container Registry. Changing this forces a new resource to be created.NEWLINE """NEWLINE network_rule_set: pulumi.Output[dict]NEWLINE """NEWLINE A `network_rule_set` block as documented below.NEWLINENEWLINE * `default_action` (`str`) - The behaviour for requests matching no rules. Either `Allow` or `Deny`. Defaults to `Allow`NEWLINE * `ip_rules` (`list`) - One or more `ip_rule` blocks as defined below.NEWLINE * `action` (`str`) - The behaviour for requests matching this rule. At this time the only supported value is `Allow`NEWLINE * `ipRange` (`str`) - The CIDR block from which requests will match the rule.NEWLINENEWLINE * `virtualNetworks` (`list`) - One or more `virtual_network` blocks as defined below.NEWLINE * `action` (`str`) - The behaviour for requests matching this rule. At this time the only supported value is `Allow`NEWLINE * `subnet_id` (`str`) - The subnet id from which requests will match the rule.NEWLINE """NEWLINE resource_group_name: pulumi.Output[str]NEWLINE """NEWLINE The name of the resource group in which to create the Container Registry. Changing this forces a new resource to be created.NEWLINE """NEWLINE sku: pulumi.Output[str]NEWLINE """NEWLINE The SKU name of the container registry. Possible values are `Basic`, `Standard` and `Premium`. `Classic` (which was previously `Basic`) is supported only for existing resources.NEWLINE """NEWLINE storage_account_id: pulumi.Output[str]NEWLINE """NEWLINE The ID of a Storage Account which must be located in the same Azure Region as the Container Registry.NEWLINE """NEWLINE tags: pulumi.Output[dict]NEWLINE """NEWLINE A mapping of tags to assign to the resource.NEWLINE """NEWLINE def __init__(__self__, resource_name, opts=None, admin_enabled=None, georeplication_locations=None, location=None, name=None, network_rule_set=None, resource_group_name=None, sku=None, storage_account_id=None, tags=None, __props__=None, __name__=None, __opts__=None):NEWLINE """NEWLINE Manages an Azure Container Registry.NEWLINENEWLINE ## Example UsageNEWLINENEWLINENEWLINENEWLINE ```pythonNEWLINE import pulumiNEWLINE import pulumi_azure as azureNEWLINENEWLINE rg = azure.core.ResourceGroup("rg", location="West US")NEWLINE acr = azure.containerservice.Registry("acr",NEWLINE resource_group_name=rg.name,NEWLINE location=rg.location,NEWLINE sku="Premium",NEWLINE admin_enabled=False,NEWLINE georeplication_locations=[NEWLINE "East US",NEWLINE "West Europe",NEWLINE ])NEWLINE ```NEWLINENEWLINENEWLINE :param str resource_name: The name of the resource.NEWLINE :param pulumi.ResourceOptions opts: Options for the resource.NEWLINE :param pulumi.Input[bool] admin_enabled: Specifies whether the admin user is enabled. Defaults to `false`.NEWLINE :param pulumi.Input[list] georeplication_locations: A list of Azure locations where the container registry should be geo-replicated.NEWLINE :param pulumi.Input[str] location: Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.NEWLINE :param pulumi.Input[str] name: Specifies the name of the Container Registry. Changing this forces a new resource to be created.NEWLINE :param pulumi.Input[dict] network_rule_set: A `network_rule_set` block as documented below.NEWLINE :param pulumi.Input[str] resource_group_name: The name of the resource group in which to create the Container Registry. Changing this forces a new resource to be created.NEWLINE :param pulumi.Input[str] sku: The SKU name of the container registry. Possible values are `Basic`, `Standard` and `Premium`. `Classic` (which was previously `Basic`) is supported only for existing resources.NEWLINE :param pulumi.Input[str] storage_account_id: The ID of a Storage Account which must be located in the same Azure Region as the Container Registry.NEWLINE :param pulumi.Input[dict] tags: A mapping of tags to assign to the resource.NEWLINENEWLINE The **network_rule_set** object supports the following:NEWLINENEWLINE * `default_action` (`pulumi.Input[str]`) - The behaviour for requests matching no rules. Either `Allow` or `Deny`. Defaults to `Allow`NEWLINE * `ip_rules` (`pulumi.Input[list]`) - One or more `ip_rule` blocks as defined below.NEWLINE * `action` (`pulumi.Input[str]`) - The behaviour for requests matching this rule. At this time the only supported value is `Allow`NEWLINE * `ipRange` (`pulumi.Input[str]`) - The CIDR block from which requests will match the rule.NEWLINENEWLINE * `virtualNetworks` (`pulumi.Input[list]`) - One or more `virtual_network` blocks as defined below.NEWLINE * `action` (`pulumi.Input[str]`) - The behaviour for requests matching this rule. At this time the only supported value is `Allow`NEWLINE * `subnet_id` (`pulumi.Input[str]`) - The subnet id from which requests will match the rule.NEWLINE """NEWLINE if __name__ is not None:NEWLINE warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)NEWLINE resource_name = __name__NEWLINE if __opts__ is not None:NEWLINE warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)NEWLINE opts = __opts__NEWLINE if opts is None:NEWLINE opts = pulumi.ResourceOptions()NEWLINE if not isinstance(opts, pulumi.ResourceOptions):NEWLINE raise TypeError('Expected resource options to be a ResourceOptions instance')NEWLINE if opts.version is None:NEWLINE opts.version = utilities.get_version()NEWLINE if opts.id is None:NEWLINE if __props__ is not None:NEWLINE raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')NEWLINE __props__ = dict()NEWLINENEWLINE __props__['admin_enabled'] = admin_enabledNEWLINE __props__['georeplication_locations'] = georeplication_locationsNEWLINE __props__['location'] = locationNEWLINE __props__['name'] = nameNEWLINE __props__['network_rule_set'] = network_rule_setNEWLINE if resource_group_name is None:NEWLINE raise TypeError("Missing required property 'resource_group_name'")NEWLINE __props__['resource_group_name'] = resource_group_nameNEWLINE __props__['sku'] = skuNEWLINE __props__['storage_account_id'] = storage_account_idNEWLINE __props__['tags'] = tagsNEWLINE __props__['admin_password'] = NoneNEWLINE __props__['admin_username'] = NoneNEWLINE __props__['login_server'] = NoneNEWLINE super(Registry, __self__).__init__(NEWLINE 'azure:containerservice/registry:Registry',NEWLINE resource_name,NEWLINE __props__,NEWLINE opts)NEWLINENEWLINE @staticmethodNEWLINE def get(resource_name, id, opts=None, admin_enabled=None, admin_password=None, admin_username=None, georeplication_locations=None, location=None, login_server=None, name=None, network_rule_set=None, resource_group_name=None, sku=None, storage_account_id=None, tags=None):NEWLINE """NEWLINE Get an existing Registry resource's state with the given name, id, and optional extraNEWLINE properties used to qualify the lookup.NEWLINENEWLINE :param str resource_name: The unique name of the resulting resource.NEWLINE :param str id: The unique provider ID of the resource to lookup.NEWLINE :param pulumi.ResourceOptions opts: Options for the resource.NEWLINE :param pulumi.Input[bool] admin_enabled: Specifies whether the admin user is enabled. Defaults to `false`.NEWLINE :param pulumi.Input[str] admin_password: The Password associated with the Container Registry Admin account - if the admin account is enabled.NEWLINE :param pulumi.Input[str] admin_username: The Username associated with the Container Registry Admin account - if the admin account is enabled.NEWLINE :param pulumi.Input[list] georeplication_locations: A list of Azure locations where the container registry should be geo-replicated.NEWLINE :param pulumi.Input[str] location: Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.NEWLINE :param pulumi.Input[str] login_server: The URL that can be used to log into the container registry.NEWLINE :param pulumi.Input[str] name: Specifies the name of the Container Registry. Changing this forces a new resource to be created.NEWLINE :param pulumi.Input[dict] network_rule_set: A `network_rule_set` block as documented below.NEWLINE :param pulumi.Input[str] resource_group_name: The name of the resource group in which to create the Container Registry. Changing this forces a new resource to be created.NEWLINE :param pulumi.Input[str] sku: The SKU name of the container registry. Possible values are `Basic`, `Standard` and `Premium`. `Classic` (which was previously `Basic`) is supported only for existing resources.NEWLINE :param pulumi.Input[str] storage_account_id: The ID of a Storage Account which must be located in the same Azure Region as the Container Registry.NEWLINE :param pulumi.Input[dict] tags: A mapping of tags to assign to the resource.NEWLINENEWLINE The **network_rule_set** object supports the following:NEWLINENEWLINE * `default_action` (`pulumi.Input[str]`) - The behaviour for requests matching no rules. Either `Allow` or `Deny`. Defaults to `Allow`NEWLINE * `ip_rules` (`pulumi.Input[list]`) - One or more `ip_rule` blocks as defined below.NEWLINE * `action` (`pulumi.Input[str]`) - The behaviour for requests matching this rule. At this time the only supported value is `Allow`NEWLINE * `ipRange` (`pulumi.Input[str]`) - The CIDR block from which requests will match the rule.NEWLINENEWLINE * `virtualNetworks` (`pulumi.Input[list]`) - One or more `virtual_network` blocks as defined below.NEWLINE * `action` (`pulumi.Input[str]`) - The behaviour for requests matching this rule. At this time the only supported value is `Allow`NEWLINE * `subnet_id` (`pulumi.Input[str]`) - The subnet id from which requests will match the rule.NEWLINE """NEWLINE opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))NEWLINENEWLINE __props__ = dict()NEWLINENEWLINE __props__["admin_enabled"] = admin_enabledNEWLINE __props__["admin_password"] = admin_passwordNEWLINE __props__["admin_username"] = admin_usernameNEWLINE __props__["georeplication_locations"] = georeplication_locationsNEWLINE __props__["location"] = locationNEWLINE __props__["login_server"] = login_serverNEWLINE __props__["name"] = nameNEWLINE __props__["network_rule_set"] = network_rule_setNEWLINE __props__["resource_group_name"] = resource_group_nameNEWLINE __props__["sku"] = skuNEWLINE __props__["storage_account_id"] = storage_account_idNEWLINE __props__["tags"] = tagsNEWLINE return Registry(resource_name, opts=opts, __props__=__props__)NEWLINE def translate_output_property(self, prop):NEWLINE return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or propNEWLINENEWLINE def translate_input_property(self, prop):NEWLINE return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or propNEWLINENEWLINE """!NEWLINE@brief Improved Experiment Argument Parser for SudoRmRfNEWLINENEWLINE@author Efthymios Tzinis {etzinis2@illinois.edu}NEWLINE@copyright University of Illinois at Urbana-ChampaignNEWLINE"""NEWLINENEWLINEimport argparseNEWLINENEWLINENEWLINEdef get_args():NEWLINE """! Command line parser """NEWLINE parser = argparse.ArgumentParser(NEWLINE description='Experiment Argument Parser')NEWLINE # ===============================================NEWLINE # Datasets argumentsNEWLINE parser.add_argument("--train", type=str, nargs='+',NEWLINE help="Training dataset",NEWLINE default=None,NEWLINE choices=['WHAM', 'LIBRI2MIX', 'MUSDB', 'FUSS'])NEWLINE parser.add_argument("--val", type=str, nargs='+',NEWLINE help="Validation dataset",NEWLINE default=None,NEWLINE choices=['WHAM', 'LIBRI2MIX', 'MUSDB', 'FUSS'])NEWLINE parser.add_argument("--test", type=str, nargs='+',NEWLINE help="Test dataset",NEWLINE default=None,NEWLINE choices=['WHAM', 'LIBRI2MIX', 'MUSDB', 'FUSS'])NEWLINE parser.add_argument("--train_val", type=str, nargs='+',NEWLINE help="Validation on the training data",NEWLINE default=None,NEWLINE choices=['WHAM', 'LIBRI2MIX'])NEWLINE parser.add_argument("--n_train", type=int,NEWLINE help="""Reduce the number of training NEWLINE samples to this number.""", default=0)NEWLINE parser.add_argument("--n_val", type=int,NEWLINE help="""Reduce the number of evaluation NEWLINE samples to this number.""", default=0)NEWLINE parser.add_argument("--n_test", type=int,NEWLINE help="""Reduce the number of test NEWLINE samples to this number.""", default=0)NEWLINE parser.add_argument("--n_train_val", type=int,NEWLINE help="""Reduce the number of evaluation NEWLINE samples on the training set.""", default=0)NEWLINE parser.add_argument("--audio_timelength", type=float,NEWLINE help="""The timelength of the audio that you want NEWLINE to load in seconds.""",NEWLINE default=4.)NEWLINE parser.add_argument("--min_or_max", type=str,NEWLINE help="""Min or max if this applies to the dataset NEWLINE that you use. Min means that the mixture is going to NEWLINE be cropped at the minimum of all sources and for max NEWLINE is going to be zero-padded""",NEWLINE default='min',NEWLINE choices=['min', 'max'])NEWLINE parser.add_argument("--zero_pad_audio", action='store_true',NEWLINE help="""If a specific timelength is required all NEWLINE audio sources and mixtures are going to be zero NEWLINE padded in order to have the required length. If not NEWLINE and a specific timelegth is required then the files NEWLINE with less than required legth are not going to be NEWLINE used.""", default=False)NEWLINE parser.add_argument("--normalize_audio", action='store_true',NEWLINE help="""Normalize using mean and standard deviation NEWLINE before processing each audio file.""",NEWLINE default=False)NEWLINE # ===============================================NEWLINE # Separation task argumentsNEWLINE parser.add_argument("--n_channels", type=int,NEWLINE help="""The number of mixture channels.""",NEWLINE default=1, choices=[1, 2])NEWLINE parser.add_argument("--min_num_sources", type=int,NEWLINE help="""The minimum number of sources in a mixture.""",NEWLINE default=1)NEWLINE parser.add_argument("--max_num_sources", type=int,NEWLINE help="""The maximum number of sources in a mixture.""",NEWLINE default=4)NEWLINE parser.add_argument("--separation_task", type=str,NEWLINE help="The separation task you would like to perform, "NEWLINE "some of the tasks might not be available for "NEWLINE "specific datasets.",NEWLINE default=None,NEWLINE choices=['enhance_single_white_noise',NEWLINE 'enhance_single', 'enhance_both',NEWLINE 'sep_clean', 'sep_noisy'])NEWLINE # ===============================================NEWLINE # Training paramsNEWLINE parser.add_argument("-bs", "--batch_size", type=int,NEWLINE help="""The number of samples in each batch. NEWLINE Warning: Cannot be less than the number of NEWLINE the validation samples""", default=4)NEWLINE parser.add_argument("--n_epochs", type=int,NEWLINE help="""The number of epochs that the NEWLINE experiment should run""", default=500)NEWLINE parser.add_argument("-lr", "--learning_rate", type=float,NEWLINE help="""Initial Learning rate""", default=1e-3)NEWLINE parser.add_argument("--divide_lr_by", type=float,NEWLINE help="""The factor that the learning rate NEWLINE would be divided by""", default=3.)NEWLINE parser.add_argument("--patience", type=int,NEWLINE help="""Patience until reducing the learning rate .""",NEWLINE default=5)NEWLINE parser.add_argument("--optimizer", type=str,NEWLINE help="""The optimizer that you want to use""",NEWLINE default="adam",NEWLINE choices=['adam', 'radam'])NEWLINE parser.add_argument("--clip_grad_norm", type=float,NEWLINE help="""The norm value which all gradients NEWLINE are going to be clipped, 0 means that no NEWLINE grads are going to be clipped""",NEWLINE default=5.)NEWLINE parser.add_argument("-fs", type=int,NEWLINE help="""Sampling rate of the audio.""", default=8000)NEWLINE # ===============================================NEWLINE # CometML experiment configuration argumentsNEWLINE parser.add_argument("-tags", "--cometml_tags", type=str,NEWLINE nargs="+", help="""A list of tags for the cometml NEWLINE experiment.""",NEWLINE default=[])NEWLINE parser.add_argument("--experiment_name", type=str,NEWLINE help="""Name of current experiment""",NEWLINE default=None)NEWLINE parser.add_argument("--project_name", type=str,NEWLINE help="""Name of current experiment""",NEWLINE default="yolo_experiment")NEWLINE # ===============================================NEWLINE # Device paramsNEWLINE parser.add_argument("-cad", "--cuda_available_devices", type=str,NEWLINE nargs="+",NEWLINE help="""A list of Cuda IDs that would be NEWLINE available for running this experiment""",NEWLINE default=['0'],NEWLINE choices=['0', '1', '2', '3'])NEWLINE parser.add_argument("--n_jobs", type=int,NEWLINE help="""The number of cpu workers for NEWLINE loading the data, etc.""", default=4)NEWLINE # ===============================================NEWLINE # Local experiment loggingNEWLINE parser.add_argument("-elp", "--experiment_logs_path", type=str,NEWLINE help="""Path for logging experiment's audio.""",NEWLINE default=None)NEWLINE parser.add_argument("-mlp", "--metrics_logs_path", type=str,NEWLINE help="""Path for logging metrics.""",NEWLINE default=None)NEWLINE parser.add_argument("-clp", "--checkpoints_path", type=str,NEWLINE help="""Path for logging checkpoints.""",NEWLINE default=None)NEWLINE parser.add_argument("--save_checkpoint_every", type=int,NEWLINE help="""Number of epochs between each model save.""",NEWLINE default=0)NEWLINE # ===============================================NEWLINE # Separation model (SuDO-RM-RF) paramsNEWLINE parser.add_argument("--out_channels", type=int,NEWLINE help="The number of channels of the internal "NEWLINE "representation outside the U-Blocks.",NEWLINE default=128)NEWLINE parser.add_argument("--in_channels", type=int,NEWLINE help="The number of channels of the internal "NEWLINE "representation inside the U-Blocks.",NEWLINE default=512)NEWLINE parser.add_argument("--num_blocks", type=int,NEWLINE help="Number of the successive U-Blocks.",NEWLINE default=16)NEWLINE parser.add_argument("--upsampling_depth", type=int,NEWLINE help="Number of successive upsamplings and "NEWLINE "effectively downsampling inside each U-Block. "NEWLINE "The aggregation of all scales is performed by "NEWLINE "addition.",NEWLINE default=5)NEWLINE parser.add_argument("--group_size", type=int,NEWLINE help="The number of individual computation groups "NEWLINE "applied if group communication module is used.",NEWLINE default=16)NEWLINE parser.add_argument("--enc_kernel_size", type=int,NEWLINE help="The width of the encoder and decoder kernels.",NEWLINE default=21)NEWLINE parser.add_argument("--enc_num_basis", type=int,NEWLINE help="Number of the encoded basis representations.",NEWLINE default=512)NEWLINENEWLINE # Attentive sudo parametersNEWLINE parser.add_argument("--att_dims", type=int,NEWLINE help="The number of attention depth.",NEWLINE default=256)NEWLINE parser.add_argument("--att_n_heads", type=int,NEWLINE help="The number of attention heads.",NEWLINE default=4)NEWLINE parser.add_argument("--att_dropout", type=float,NEWLINE help="The dropout rate inside the attention layers.",NEWLINE default=0.1)NEWLINENEWLINE parser.add_argument("--model_type", type=str,NEWLINE help="The type of model you would like to use.",NEWLINE default='relu',NEWLINE choices=['relu', 'softmax', 'groupcomm',NEWLINE 'groupcomm_v2', 'causal',NEWLINE 'attention', 'attention_v2',NEWLINE 'attention_v3', 'sepformer'])NEWLINENEWLINE return parser.parse_args() from __future__ import absolute_import, unicode_literalsNEWLINEimport pytestNEWLINEimport loggingNEWLINEimport osNEWLINENEWLINEfrom psd_tools.api import pil_ioNEWLINEfrom psd_tools.api.psd_image import PSDImageNEWLINEfrom psd_tools.constants import ColorModeNEWLINEfrom psd_tools.psd.patterns import PatternNEWLINEfrom ..utils import TEST_ROOT, full_nameNEWLINENEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINENEWLINE@pytest.mark.parametrize(NEWLINE 'mode', [NEWLINE 'L',NEWLINE 'LA',NEWLINE 'RGB',NEWLINE 'RGBA',NEWLINE 'CMYK',NEWLINE 'CMYKA',NEWLINE 'LAB',NEWLINE '1',NEWLINE ]NEWLINE)NEWLINEdef test_get_color_mode(mode):NEWLINE assert isinstance(pil_io.get_color_mode(mode), ColorMode)NEWLINENEWLINENEWLINE@pytest.mark.parametrize(NEWLINE 'mode, alpha, expected',NEWLINE [NEWLINE (ColorMode.BITMAP, False, '1'),NEWLINE (ColorMode.GRAYSCALE, False, 'L'),NEWLINE (ColorMode.GRAYSCALE, True, 'LA'),NEWLINE (ColorMode.RGB, False, 'RGB'),NEWLINE (ColorMode.RGB, True, 'RGBA'),NEWLINE (ColorMode.CMYK, False, 'CMYK'),NEWLINE (ColorMode.CMYK, True, 'CMYK'), # CMYK with alpha is not supported.NEWLINE (ColorMode.LAB, False, 'LAB'),NEWLINE ]NEWLINE)NEWLINEdef test_get_pil_mode(mode, alpha, expected):NEWLINE assert pil_io.get_pil_mode(mode, alpha) == expectedNEWLINENEWLINENEWLINEdef test_convert_pattern_to_pil():NEWLINE filepath = os.path.join(TEST_ROOT, 'tagged_blocks', 'Patt_1.dat')NEWLINE with open(filepath, 'rb') as f:NEWLINE pattern = Pattern.read(f)NEWLINENEWLINE assert pil_io.convert_pattern_to_pil(pattern)NEWLINENEWLINENEWLINEdef test_apply_icc_profile():NEWLINE filepath = full_name('colorprofiles/north_america_newspaper.psd')NEWLINE psd = PSDImage.open(filepath)NEWLINE no_icc = psd.topil(apply_icc=False)NEWLINE with_icc = psd.topil(apply_icc=True)NEWLINE assert no_icc.getextrema() != with_icc.getextrema()NEWLINE from IPython import get_ipythonNEWLINEfrom IPython.core.magic import (magics_class, line_magic)NEWLINEfrom IPython.core.magics.osm import OSMagicsNEWLINEfrom johnstarich.ipython.shell import find_varNEWLINEimport keywordNEWLINEimport shutilNEWLINENEWLINENEWLINE@magics_classNEWLINEclass Bashisms(OSMagics):NEWLINE @propertyNEWLINE def _exit_code(self) -> int:NEWLINE return self.shell.user_ns['_exit_code']NEWLINENEWLINE @_exit_code.setterNEWLINE def _exit_code(self, value: int):NEWLINE self.shell.user_ns['_exit_code'] = valueNEWLINENEWLINE @line_magicNEWLINE def echo(self, line: str):NEWLINE "Simply print out its received arguments."NEWLINE print(line.format(**vars(), **globals()))NEWLINE self._exit_code = 0NEWLINE returnNEWLINENEWLINE @line_magicNEWLINE def cd(self, parameter_s=''):NEWLINE super(Bashisms, self).cd('-q ' + parameter_s)NEWLINENEWLINE @line_magicNEWLINE def which(self, line):NEWLINE var_location = find_var(self.shell, line)NEWLINE if var_location is not None:NEWLINE print(var_location.get(line))NEWLINE self._exit_code = 0NEWLINE returnNEWLINENEWLINE if keyword.iskeyword(line):NEWLINE help(line)NEWLINE self._exit_code = 0NEWLINE returnNEWLINENEWLINE ex = shutil.which(line)NEWLINE if ex is not None:NEWLINE print(ex)NEWLINE self._exit_code = 0NEWLINE returnNEWLINE else:NEWLINE print('"{}" could not be found on $PATH'NEWLINE .format(line))NEWLINE self._exit_code = 1NEWLINE returnNEWLINENEWLINEip = get_ipython()NEWLINEip.register_magics(Bashisms)NEWLINEdel ipNEWLINE def troca(numeros):NEWLINE cont = 0NEWLINE for x in numeros:NEWLINE if numeros[cont] > 0:NEWLINE numeros[cont] = 1NEWLINE else:NEWLINE numeros[cont] = 0NEWLINE cont = cont + 1NEWLINE print(numeros)NEWLINENEWLINENEWLINENEWLINEnumeros = []NEWLINEfor i in range(30):NEWLINE numeros.append(int(input("Digite um numero: ")))NEWLINEprint(numeros)NEWLINEtroca(numeros)NEWLINENEWLINENEWLINE """NEWLINESimple recurrent model - either with LSTM or GRU cells.NEWLINE"""NEWLINEfrom copy import copyNEWLINEfrom typing import Dict, List, Tuple, UnionNEWLINENEWLINEimport numpy as npNEWLINEimport torchNEWLINEimport torch.nn as nnNEWLINENEWLINEfrom pytorch_forecasting.data.encoders import MultiNormalizer, NaNLabelEncoderNEWLINEfrom pytorch_forecasting.data.timeseries import TimeSeriesDataSetNEWLINEfrom pytorch_forecasting.metrics import MAE, MAPE, MASE, RMSE, SMAPE, MultiHorizonMetric, MultiLoss, QuantileLossNEWLINEfrom pytorch_forecasting.models.base_model import AutoRegressiveBaseModelWithCovariatesNEWLINEfrom pytorch_forecasting.models.nn import HiddenState, MultiEmbedding, get_rnnNEWLINEfrom pytorch_forecasting.utils import apply_to_list, to_listNEWLINENEWLINENEWLINEclass RecurrentNetwork(AutoRegressiveBaseModelWithCovariates):NEWLINE def __init__(NEWLINE self,NEWLINE cell_type: str = "LSTM",NEWLINE hidden_size: int = 10,NEWLINE rnn_layers: int = 2,NEWLINE dropout: float = 0.1,NEWLINE static_categoricals: List[str] = [],NEWLINE static_reals: List[str] = [],NEWLINE time_varying_categoricals_encoder: List[str] = [],NEWLINE time_varying_categoricals_decoder: List[str] = [],NEWLINE categorical_groups: Dict[str, List[str]] = {},NEWLINE time_varying_reals_encoder: List[str] = [],NEWLINE time_varying_reals_decoder: List[str] = [],NEWLINE embedding_sizes: Dict[str, Tuple[int, int]] = {},NEWLINE embedding_paddings: List[str] = [],NEWLINE embedding_labels: Dict[str, np.ndarray] = {},NEWLINE x_reals: List[str] = [],NEWLINE x_categoricals: List[str] = [],NEWLINE output_size: Union[int, List[int]] = 1,NEWLINE target: Union[str, List[str]] = None,NEWLINE target_lags: Dict[str, List[int]] = {},NEWLINE loss: MultiHorizonMetric = None,NEWLINE logging_metrics: nn.ModuleList = None,NEWLINE **kwargs,NEWLINE ):NEWLINE """NEWLINE Recurrent Network.NEWLINENEWLINE Simple LSTM or GRU layer followed by output layerNEWLINENEWLINE Args:NEWLINE cell_type (str, optional): Recurrent cell type ["LSTM", "GRU"]. Defaults to "LSTM".NEWLINE hidden_size (int, optional): hidden recurrent size - the most important hyperparameter along withNEWLINE ``rnn_layers``. Defaults to 10.NEWLINE rnn_layers (int, optional): Number of RNN layers - important hyperparameter. Defaults to 2.NEWLINE dropout (float, optional): Dropout in RNN layers. Defaults to 0.1.NEWLINE static_categoricals: integer of positions of static categorical variablesNEWLINE static_reals: integer of positions of static continuous variablesNEWLINE time_varying_categoricals_encoder: integer of positions of categorical variables for encoderNEWLINE time_varying_categoricals_decoder: integer of positions of categorical variables for decoderNEWLINE time_varying_reals_encoder: integer of positions of continuous variables for encoderNEWLINE time_varying_reals_decoder: integer of positions of continuous variables for decoderNEWLINE categorical_groups: dictionary where valuesNEWLINE are list of categorical variables that are forming together a new categoricalNEWLINE variable which is the key in the dictionaryNEWLINE x_reals: order of continuous variables in tensor passed to forward functionNEWLINE x_categoricals: order of categorical variables in tensor passed to forward functionNEWLINE embedding_sizes: dictionary mapping (string) indices to tuple of number of categorical classes andNEWLINE embedding sizeNEWLINE embedding_paddings: list of indices for embeddings which transform the zero's embedding to a zero vectorNEWLINE embedding_labels: dictionary mapping (string) indices to list of categorical labelsNEWLINE output_size (Union[int, List[int]], optional): number of outputs (e.g. number of quantiles forNEWLINE QuantileLoss and one target or list of output sizes).NEWLINE target (str, optional): Target variable or list of target variables. Defaults to None.NEWLINE target_lags (Dict[str, Dict[str, int]]): dictionary of target names mapped to list of time steps byNEWLINE which the variable should be lagged.NEWLINE Lags can be useful to indicate seasonality to the models. If you know the seasonalit(ies) of your data,NEWLINE add at least the target variables with the corresponding lags to improve performance.NEWLINE Defaults to no lags, i.e. an empty dictionary.NEWLINE loss (MultiHorizonMetric, optional): loss: loss function taking prediction and targets.NEWLINE logging_metrics (nn.ModuleList, optional): Metrics to log during training.NEWLINE Defaults to nn.ModuleList([SMAPE(), MAE(), RMSE(), MAPE(), MASE()]).NEWLINE """NEWLINE if loss is None:NEWLINE loss = MAE()NEWLINE if logging_metrics is None:NEWLINE logging_metrics = nn.ModuleList([SMAPE(), MAE(), RMSE(), MAPE(), MASE()])NEWLINE self.save_hyperparameters()NEWLINE # store loss function separately as it is a moduleNEWLINE super().__init__(loss=loss, logging_metrics=logging_metrics, **kwargs)NEWLINENEWLINE self.embeddings = MultiEmbedding(NEWLINE embedding_sizes=embedding_sizes,NEWLINE embedding_paddings=embedding_paddings,NEWLINE categorical_groups=categorical_groups,NEWLINE x_categoricals=x_categoricals,NEWLINE )NEWLINENEWLINE lagged_target_names = [l for lags in target_lags.values() for l in lags]NEWLINE assert set(self.encoder_variables) - set(to_list(target)) - set(lagged_target_names) == set(NEWLINE self.decoder_variablesNEWLINE ), "Encoder and decoder variables have to be the same apart from target variable"NEWLINE for targeti in to_list(target):NEWLINE assert (NEWLINE targeti in time_varying_reals_encoderNEWLINE ), f"target {targeti} has to be real" # todo: remove this restrictionNEWLINE assert (isinstance(target, str) and isinstance(loss, MultiHorizonMetric)) or (NEWLINE isinstance(target, (list, tuple)) and isinstance(loss, MultiLoss) and len(loss) == len(target)NEWLINE ), "number of targets should be equivalent to number of loss metrics"NEWLINENEWLINE rnn_class = get_rnn(cell_type)NEWLINE cont_size = len(self.reals)NEWLINE cat_size = sum([size[1] for size in self.hparams.embedding_sizes.values()])NEWLINE input_size = cont_size + cat_sizeNEWLINE self.rnn = rnn_class(NEWLINE input_size=input_size,NEWLINE hidden_size=self.hparams.hidden_size,NEWLINE num_layers=self.hparams.rnn_layers,NEWLINE dropout=self.hparams.dropout if self.hparams.rnn_layers > 1 else 0,NEWLINE batch_first=True,NEWLINE )NEWLINENEWLINE # add linear layers for argument projectsNEWLINE if isinstance(target, str): # single targetNEWLINE self.output_projector = nn.Linear(self.hparams.hidden_size, self.hparams.output_size)NEWLINE assert not isinstance(self.loss, QuantileLoss), "QuantileLoss does not work with recurrent network"NEWLINE else: # multi targetNEWLINE self.output_projector = nn.ModuleList(NEWLINE [nn.Linear(self.hparams.hidden_size, size) for size in self.hparams.output_size]NEWLINE )NEWLINE for l in self.loss:NEWLINE assert not isinstance(l, QuantileLoss), "QuantileLoss does not work with recurrent network"NEWLINENEWLINE @classmethodNEWLINE def from_dataset(NEWLINE cls,NEWLINE dataset: TimeSeriesDataSet,NEWLINE allowed_encoder_known_variable_names: List[str] = None,NEWLINE **kwargs,NEWLINE ):NEWLINE """NEWLINE Create model from dataset.NEWLINENEWLINE Args:NEWLINE dataset: timeseries datasetNEWLINE allowed_encoder_known_variable_names: List of known variables that are allowed in encoder, defaults to allNEWLINE **kwargs: additional arguments such as hyperparameters for model (see ``__init__()``)NEWLINENEWLINE Returns:NEWLINE Recurrent networkNEWLINE """NEWLINE new_kwargs = copy(kwargs)NEWLINE new_kwargs.update(cls.deduce_default_output_parameters(dataset=dataset, kwargs=kwargs, default_loss=MAE()))NEWLINE assert not isinstance(dataset.target_normalizer, NaNLabelEncoder) and (NEWLINE not isinstance(dataset.target_normalizer, MultiNormalizer)NEWLINE or all([not isinstance(normalizer, NaNLabelEncoder) for normalizer in dataset.target_normalizer])NEWLINE ), "target(s) should be continuous - categorical targets are not supported" # todo: remove this restrictionNEWLINE return super().from_dataset(NEWLINE dataset, allowed_encoder_known_variable_names=allowed_encoder_known_variable_names, **new_kwargsNEWLINE )NEWLINENEWLINE def construct_input_vector(NEWLINE self, x_cat: torch.Tensor, x_cont: torch.Tensor, one_off_target: torch.Tensor = NoneNEWLINE ) -> torch.Tensor:NEWLINE """NEWLINE Create input vector into RNN networkNEWLINENEWLINE Args:NEWLINE one_off_target: tensor to insert into first position of target. If None (default), remove first time step.NEWLINE """NEWLINE # create input vectorNEWLINE if len(self.categoricals) > 0:NEWLINE embeddings = self.embeddings(x_cat)NEWLINE flat_embeddings = torch.cat([emb for emb in embeddings.values()], dim=-1)NEWLINE input_vector = flat_embeddingsNEWLINENEWLINE if len(self.reals) > 0:NEWLINE input_vector = x_contNEWLINENEWLINE if len(self.reals) > 0 and len(self.categoricals) > 0:NEWLINE input_vector = torch.cat([x_cont, flat_embeddings], dim=-1)NEWLINENEWLINE # shift target by oneNEWLINE input_vector[..., self.target_positions] = torch.roll(NEWLINE input_vector[..., self.target_positions], shifts=1, dims=1NEWLINE )NEWLINENEWLINE if one_off_target is not None: # set first target input (which is rolled over)NEWLINE input_vector[:, 0, self.target_positions] = one_off_targetNEWLINE else:NEWLINE input_vector = input_vector[:, 1:]NEWLINENEWLINE # shift targetNEWLINE return input_vectorNEWLINENEWLINE def encode(self, x: Dict[str, torch.Tensor]) -> HiddenState:NEWLINE """NEWLINE Encode sequence into hidden stateNEWLINE """NEWLINE # encode using rnnNEWLINE assert x["encoder_lengths"].min() > 0NEWLINE encoder_lengths = x["encoder_lengths"] - 1NEWLINE input_vector = self.construct_input_vector(x["encoder_cat"], x["encoder_cont"])NEWLINE _, hidden_state = self.rnn(NEWLINE input_vector, lengths=encoder_lengths, enforce_sorted=FalseNEWLINE ) # second ouput is not needed (hidden state)NEWLINE return hidden_stateNEWLINENEWLINE def decode_all(NEWLINE self,NEWLINE x: torch.Tensor,NEWLINE hidden_state: HiddenState,NEWLINE lengths: torch.Tensor = None,NEWLINE ):NEWLINE decoder_output, hidden_state = self.rnn(x, hidden_state, lengths=lengths, enforce_sorted=False)NEWLINE if isinstance(self.hparams.target, str): # single targetNEWLINE output = self.output_projector(decoder_output)NEWLINE else:NEWLINE output = [projector(decoder_output) for projector in self.output_projector]NEWLINE return output, hidden_stateNEWLINENEWLINE def decode(NEWLINE self,NEWLINE input_vector: torch.Tensor,NEWLINE target_scale: torch.Tensor,NEWLINE decoder_lengths: torch.Tensor,NEWLINE hidden_state: HiddenState,NEWLINE n_samples: int = None,NEWLINE ) -> Tuple[torch.Tensor, bool]:NEWLINE """NEWLINE Decode hidden state of RNN into prediction. If n_smaples is given,NEWLINE decode not by using actual values but rather byNEWLINE sampling new targets from past predictions iterativelyNEWLINE """NEWLINE if self.training:NEWLINE output, _ = self.decode_all(input_vector, hidden_state, lengths=decoder_lengths)NEWLINE output = self.transform_output(output, target_scale=target_scale)NEWLINE else:NEWLINE # run in eval, i.e. simulation modeNEWLINE target_pos = self.target_positionsNEWLINE lagged_target_positions = self.lagged_target_positionsNEWLINENEWLINE # define function to run at every decoding stepNEWLINE def decode_one(NEWLINE idx,NEWLINE lagged_targets,NEWLINE hidden_state,NEWLINE ):NEWLINE x = input_vector[:, [idx]]NEWLINE x[:, 0, target_pos] = lagged_targets[-1]NEWLINE for lag, lag_positions in lagged_target_positions.items():NEWLINE if idx > lag:NEWLINE x[:, 0, lag_positions] = lagged_targets[-lag]NEWLINE prediction, hidden_state = self.decode_all(x, hidden_state)NEWLINE prediction = apply_to_list(prediction, lambda x: x[:, 0]) # select first time stepNEWLINE return prediction, hidden_stateNEWLINENEWLINE # make predictions which are fed into next stepNEWLINE output = self.decode_autoregressive(NEWLINE decode_one,NEWLINE first_target=input_vector[:, 0, target_pos],NEWLINE first_hidden_state=hidden_state,NEWLINE target_scale=target_scale,NEWLINE n_decoder_steps=input_vector.size(1),NEWLINE )NEWLINE return outputNEWLINENEWLINE def forward(self, x: Dict[str, torch.Tensor], n_samples: int = None) -> Dict[str, torch.Tensor]:NEWLINE """NEWLINE Forward networkNEWLINE """NEWLINE hidden_state = self.encode(x)NEWLINE # decodeNEWLINE input_vector = self.construct_input_vector(NEWLINE x["decoder_cat"],NEWLINE x["decoder_cont"],NEWLINE one_off_target=x["encoder_cont"][NEWLINE torch.arange(x["encoder_cont"].size(0), device=x["encoder_cont"].device),NEWLINE x["encoder_lengths"] - 1,NEWLINE self.target_positions.unsqueeze(-1),NEWLINE ].T,NEWLINE )NEWLINENEWLINE output = self.decode(NEWLINE input_vector,NEWLINE decoder_lengths=x["decoder_lengths"],NEWLINE target_scale=x["target_scale"],NEWLINE hidden_state=hidden_state,NEWLINE )NEWLINE # return relevant partNEWLINE return self.to_network_output(prediction=output)NEWLINE """Resnet v1 model variants.NEWLINECode branched out from slim/nets/resnet_v1.py, and please refer to it forNEWLINEmore details.NEWLINEThe original version ResNets-v1 were proposed by:NEWLINE[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian SunNEWLINE Deep Residual Learning for Image Recognition. arXiv:1512.03385NEWLINE"""NEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import print_functionNEWLINENEWLINEimport functoolsNEWLINEimport tensorflow as tfNEWLINENEWLINEfrom models import resnet_utilsNEWLINEfrom utils.metrics import *NEWLINEfrom utils.loss import *NEWLINEimport warningsNEWLINEwarnings.filterwarnings('ignore')NEWLINEfrom tensorflow.contrib import layersNEWLINEfrom tensorflow.contrib.framework.python.ops import add_arg_scopeNEWLINEfrom tensorflow.contrib.framework.python.ops import arg_scopeNEWLINEfrom tensorflow.contrib.layers.python.layers import utilsNEWLINEfrom tensorflow.contrib.layers.python.layers import regularizersNEWLINENEWLINE_DEFAULT_MULTI_GRID = [1, 1, 1]NEWLINENEWLINEdef update_argparser(parser):NEWLINE parser.set_defaults(NEWLINE train_steps=40000,NEWLINE learning_rate=((20000,30000), (0.0001, 0.00001,0.000001)),NEWLINE save_checkpoints_steps=200,NEWLINE )NEWLINENEWLINENEWLINE@add_arg_scopeNEWLINEdef bottleneck(inputs,NEWLINE depth,NEWLINE depth_bottleneck,NEWLINE stride,NEWLINE unit_rate=1,NEWLINE rate=1,NEWLINE outputs_collections=None,NEWLINE scope=None):NEWLINE """Bottleneck residual unit variant with BN after convolutions.NEWLINE This is the original residual unit proposed in [1]. See Fig. 1(a) of [2] forNEWLINE its definition. Note that we use here the bottleneck variant which has anNEWLINE extra bottleneck layer.NEWLINE When putting together two consecutive ResNet blocks that use this unit, oneNEWLINE should use stride = 2 in the last unit of the first block.NEWLINE Args:NEWLINE inputs: A tensor of size [batch, height, width, channels].NEWLINE depth: The depth of the ResNet unit output.NEWLINE depth_bottleneck: The depth of the bottleneck layers.NEWLINE stride: The ResNet unit's stride. Determines the amount of downsampling ofNEWLINE the units output compared to its input.NEWLINE unit_rate: An integer, unit rate for atrous convolution.NEWLINE rate: An integer, rate for atrous convolution.NEWLINE outputs_collections: Collection to add the ResNet unit output.NEWLINE scope: Optional variable_scope.NEWLINE Returns:NEWLINE The ResNet unit's output.NEWLINE """NEWLINE with tf.variable_scope(scope, 'bottleneck_v1', [inputs]) as sc:NEWLINE depth_in = utils.last_dimension(inputs.get_shape(), min_rank=4)NEWLINE if depth == depth_in:NEWLINE shortcut = resnet_utils.subsample(inputs, stride, 'shortcut')NEWLINE else:NEWLINE shortcut = layers.conv2d(NEWLINE inputs,NEWLINE depth,NEWLINE [1, 1],NEWLINE stride=stride,NEWLINE activation_fn=None,NEWLINE scope='shortcut')NEWLINENEWLINE residual = layers.conv2d(inputs, depth_bottleneck, [1, 1], stride=1,NEWLINE scope='conv1')NEWLINE residual = resnet_utils.conv2d_same(residual, depth_bottleneck, 3, stride,NEWLINE rate=rate*unit_rate, scope='conv2')NEWLINE residual = layers.conv2d(residual, depth, [1, 1], stride=1,NEWLINE activation_fn=None, scope='conv3')NEWLINE output = tf.nn.relu(shortcut + residual)NEWLINENEWLINE return utils.collect_named_outputs(outputs_collections,NEWLINE sc.name,NEWLINE output)NEWLINENEWLINENEWLINEdef root_block_fn_for_beta_variant(net):NEWLINE """Gets root_block_fn for beta variant.NEWLINE ResNet-v1 beta variant modifies the first original 7x7 convolution to threeNEWLINE 3x3 convolutions.NEWLINE Args:NEWLINE net: A tensor of size [batch, height, width, channels], input to the model.NEWLINE Returns:NEWLINE A tensor after three 3x3 convolutions.NEWLINE """NEWLINE net = resnet_utils.conv2d_same(net, 64, 3, stride=2, scope='conv1_1')NEWLINE net = resnet_utils.conv2d_same(net, 64, 3, stride=1, scope='conv1_2')NEWLINE net = resnet_utils.conv2d_same(net, 128, 3, stride=1, scope='conv1_3')NEWLINENEWLINE return netNEWLINENEWLINENEWLINEdef resnet_v1_beta(inputs,NEWLINE blocks,NEWLINE num_classes=None,NEWLINE is_training=None,NEWLINE global_pool=True,NEWLINE output_stride=None,NEWLINE root_block_fn=None,NEWLINE scope=None):NEWLINE """Generator for v1 ResNet models (beta variant).NEWLINE This function generates a family of modified ResNet v1 models. In particular,NEWLINE the first original 7x7 convolution is replaced with three 3x3 convolutions.NEWLINE See the resnet_v1_*() methods for specific model instantiations, obtained byNEWLINE selecting different block instantiations that produce ResNets of variousNEWLINE depths.NEWLINE The code is modified from slim/nets/resnet_v1.py, and please refer to it forNEWLINE more details.NEWLINE Args:NEWLINE inputs: A tensor of size [batch, height_in, width_in, channels].NEWLINE blocks: A list of length equal to the number of ResNet blocks. Each elementNEWLINE is a resnet_utils.Block object describing the units in the block.NEWLINE num_classes: Number of predicted classes for classification tasks. If NoneNEWLINE we return the features before the logit layer.NEWLINE is_training: Enable/disable is_training for batch normalization.NEWLINE global_pool: If True, we perform global average pooling before computing theNEWLINE logits. Set to True for image classification, False for dense prediction.NEWLINE output_stride: If None, then the output will be computed at the nominalNEWLINE network stride. If output_stride is not None, it specifies the requestedNEWLINE ratio of input to output spatial resolution.NEWLINE root_block_fn: The function consisting of convolution operations applied toNEWLINE the root input. If root_block_fn is None, use the original setting ofNEWLINE RseNet-v1, which is simply one convolution with 7x7 kernel and stride=2.NEWLINE reuse: whether or not the network and its variables should be reused. To beNEWLINE able to reuse 'scope' must be given.NEWLINE scope: Optional variable_scope.NEWLINE Returns:NEWLINE net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].NEWLINE If global_pool is False, then height_out and width_out are reduced by aNEWLINE factor of output_stride compared to the respective height_in and width_in,NEWLINE else both height_out and width_out equal one. If num_classes is None, thenNEWLINE net is the output of the last ResNet block, potentially after globalNEWLINE average pooling. If num_classes is not None, net contains the pre-softmaxNEWLINE activations.NEWLINE end_points: A dictionary from components of the network to the correspondingNEWLINE activation.NEWLINE Raises:NEWLINE ValueError: If the target output_stride is not valid.NEWLINE """NEWLINE if root_block_fn is None:NEWLINE root_block_fn = functools.partial(resnet_utils.conv2d_same,NEWLINE num_outputs=64,NEWLINE kernel_size=7,NEWLINE stride=2,NEWLINE scope='conv1')NEWLINE with tf.variable_scope(scope, 'resnet_v1', [inputs]) as sc:NEWLINE end_points_collection = sc.original_name_scope + '_end_points'NEWLINE with arg_scope([layers.conv2d, bottleneck,NEWLINE resnet_utils.stack_blocks_dense],NEWLINE outputs_collections=end_points_collection):NEWLINE if is_training is not None:NEWLINE arg_sc = arg_scope([layers.batch_norm], is_training=is_training)NEWLINE else:NEWLINE arg_sc = arg_scope([])NEWLINE with arg_sc:NEWLINE net = inputsNEWLINE if output_stride is not None:NEWLINE if output_stride % 4 != 0:NEWLINE raise ValueError('The output_stride needs to be a multiple of 4.')NEWLINE output_stride /= 4NEWLINE print(str(output_stride) + 'Before resnet blocks')NEWLINE net = root_block_fn(net)NEWLINE net = layers.max_pool2d(net, 3, stride=2, padding='SAME', scope='pool1')NEWLINE net = resnet_utils.stack_blocks_dense(net, blocks, output_stride)NEWLINENEWLINE if global_pool:NEWLINE # Global average pooling.NEWLINE net = tf.reduce_mean(net, [1, 2], name='pool5', keepdims=True)NEWLINE if num_classes is not None:NEWLINE net = layers.conv2d(net, num_classes, [1, 1], activation_fn=None,NEWLINE normalizer_fn=None, scope='logit')NEWLINE # Convert end_points_collection into a dictionary of end_points.NEWLINE end_points = utils.convert_collection_to_dict(end_points_collection)NEWLINE if num_classes is not None:NEWLINE end_points['predictions'] = layers.softmax(net, scope='predictions')NEWLINE return net, end_pointsNEWLINENEWLINENEWLINEdef resnet_v1_beta_block(scope, base_depth, num_units, stride):NEWLINE """Helper function for creating a resnet_v1 beta variant bottleneck block.NEWLINE Args:NEWLINE scope: The scope of the block.NEWLINE base_depth: The depth of the bottleneck layer for each unit.NEWLINE num_units: The number of units in the block.NEWLINE stride: The stride of the block, implemented as a stride in the last unit.NEWLINE All other units have stride=1.NEWLINE Returns:NEWLINE A resnet_v1 bottleneck block.NEWLINE """NEWLINE return resnet_utils.Block(scope, bottleneck, [{NEWLINE 'depth': base_depth * 4,NEWLINE 'depth_bottleneck': base_depth,NEWLINE 'stride': 1,NEWLINE 'unit_rate': 1NEWLINE }] * (num_units - 1) + [{NEWLINE 'depth': base_depth * 4,NEWLINE 'depth_bottleneck': base_depth,NEWLINE 'stride': stride,NEWLINE 'unit_rate': 1NEWLINE }])NEWLINENEWLINEdef resnet_v1_101_beta(inputs,NEWLINE num_classes=None,NEWLINE is_training=None,NEWLINE global_pool=False,NEWLINE output_stride=None,NEWLINE multi_grid=None,NEWLINE scope='resnet_v1_101'):NEWLINE """Resnet v1 101 beta variant.NEWLINE This variant modifies the first convolution layer of ResNet-v1-101. InNEWLINE particular, it changes the original one 7x7 convolution to three 3x3NEWLINE convolutions.NEWLINE Args:NEWLINE inputs: A tensor of size [batch, height_in, width_in, channels].NEWLINE num_classes: Number of predicted classes for classification tasks. If NoneNEWLINE we return the features before the logit layer.NEWLINE is_training: Enable/disable is_training for batch normalization.NEWLINE global_pool: If True, we perform global average pooling before computing theNEWLINE logits. Set to True for image classification, False for dense prediction.NEWLINE output_stride: If None, then the output will be computed at the nominalNEWLINE network stride. If output_stride is not None, it specifies the requestedNEWLINE ratio of input to output spatial resolution.NEWLINE multi_grid: Employ a hierarchy of different atrous rates within network.NEWLINE reuse: whether or not the network and its variables should be reused. To beNEWLINE able to reuse 'scope' must be given.NEWLINE scope: Optional variable_scope.NEWLINE Returns:NEWLINE net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].NEWLINE If global_pool is False, then height_out and width_out are reduced by aNEWLINE factor of output_stride compared to the respective height_in and width_in,NEWLINE else both height_out and width_out equal one. If num_classes is None, thenNEWLINE net is the output of the last ResNet block, potentially after globalNEWLINE average pooling. If num_classes is not None, net contains the pre-softmaxNEWLINE activations.NEWLINE end_points: A dictionary from components of the network to the correspondingNEWLINE activation.NEWLINE Raises:NEWLINE ValueError: if multi_grid is not None and does not have length = 3.NEWLINE """NEWLINE if multi_grid is None:NEWLINE multi_grid = _DEFAULT_MULTI_GRIDNEWLINE else:NEWLINE if len(multi_grid) != 3:NEWLINE raise ValueError('Expect multi_grid to have length 3.')NEWLINENEWLINE blocks = [NEWLINE resnet_v1_beta_block(NEWLINE 'block1', base_depth=64, num_units=3, stride=2),NEWLINE resnet_v1_beta_block(NEWLINE 'block2', base_depth=128, num_units=4, stride=2),NEWLINE resnet_v1_beta_block(NEWLINE 'block3', base_depth=256, num_units=23, stride=2),NEWLINE resnet_utils.Block('block4', bottleneck, [NEWLINE {'depth': 2048,NEWLINE 'depth_bottleneck': 512,NEWLINE 'stride': 1,NEWLINE 'unit_rate': rate} for rate in multi_grid]),NEWLINE ]NEWLINE return resnet_v1_beta(NEWLINE inputs,NEWLINE blocks=blocks,NEWLINE num_classes=num_classes,NEWLINE is_training=is_training,NEWLINE global_pool=global_pool,NEWLINE output_stride=output_stride,NEWLINE root_block_fn=functools.partial(root_block_fn_for_beta_variant),NEWLINE scope=scope)NEWLINENEWLINEdef atrous_spatial_pyramid_pooling(net, scope, output_stride, is_training, weight_decay, depth=256):NEWLINE """NEWLINE ASPP consists of (a) one 1×1 convolution and three 3×3 convolutions with rates = (6, 12, 18) when output stride = 16NEWLINE when output stride = 8, rates are doubledNEWLINE (all with 256 filters and batch normalization), and (b) the image-level features as described in https://arxiv.org/abs/1706.05587NEWLINE :param net: tensor of shape [BATCH_SIZE, WIDTH, HEIGHT, DEPTH]NEWLINE :param scope: scope name of the aspp layerNEWLINE :return: network layer with aspp applyed to it.NEWLINE """NEWLINE if output_stride == 16:NEWLINE rates = [6,12,18]NEWLINE elif output_stride == 8:NEWLINE rates = [12,24,36]NEWLINENEWLINE with tf.variable_scope(scope):NEWLINE batch_norm_params = {NEWLINE 'is_training': is_training,NEWLINE 'decay': 0.9997,NEWLINE 'epsilon': 1e-5,NEWLINE 'scale': True,NEWLINE }NEWLINENEWLINE with arg_scope(NEWLINE [layers.conv2d],NEWLINE # comment next line of code if multiple gpus are usedNEWLINE weights_regularizer=regularizers.l2_regularizer(weight_decay),NEWLINE activation_fn=tf.nn.relu,NEWLINE normalizer_fn=layers.batch_norm,NEWLINE normalizer_params=batch_norm_params):NEWLINE NEWLINE with arg_scope([layers.batch_norm], **batch_norm_params):NEWLINENEWLINE feature_map_size = tf.shape(net)NEWLINE # apply global average poolingNEWLINE image_level_features = tf.reduce_mean(net, [1, 2], name='image_level_global_pool', keepdims=True)NEWLINE image_level_features = layers.conv2d(image_level_features, depth, [1, 1], scope="image_level_conv_1x1",NEWLINE activation_fn=None)NEWLINE image_level_features = tf.image.resize_bilinear(image_level_features, (feature_map_size[1], feature_map_size[2]))NEWLINENEWLINE at_pool1x1 = layers.conv2d(net, depth, [1, 1], scope="conv_1x1_0", activation_fn=None)NEWLINENEWLINE at_pool3x3_1 = layers.conv2d(net, depth, [3, 3], scope="conv_3x3_1", rate=rates[0], activation_fn=None)NEWLINENEWLINE at_pool3x3_2 = layers.conv2d(net, depth, [3, 3], scope="conv_3x3_2", rate=rates[1], activation_fn=None)NEWLINENEWLINE at_pool3x3_3 = layers.conv2d(net, depth, [3, 3], scope="conv_3x3_3", rate=rates[2], activation_fn=None)NEWLINENEWLINE net = tf.concat((image_level_features, at_pool1x1, at_pool3x3_1, at_pool3x3_2, at_pool3x3_3), axis=3,NEWLINE name="concat")NEWLINE net = layers.conv2d(net, depth, [1, 1], scope="conv_1x1_output", activation_fn=None)NEWLINE net = layers.dropout(net, keep_prob=0.9, is_training=is_training, scope="dropout")NEWLINE return netNEWLINENEWLINE#用@add_arg_scope修饰目标函数NEWLINE#用with arg_scope(...) 设置默认参数.NEWLINEdef deeplab_v3(inputs, args, is_training, output_stride):NEWLINENEWLINE # inputs has shape - Original: [batch, 513, 513, 3]NEWLINE with arg_scope(resnet_utils.resnet_arg_scope(args.l2_regularizer, is_training)):NEWLINE _, end_points = resnet_v1_101_beta(inputs,NEWLINE args.num_classes,NEWLINE is_training=is_training,NEWLINE global_pool=False,NEWLINE output_stride=output_stride,NEWLINE multi_grid=args.multi_grid)NEWLINENEWLINE with tf.variable_scope("DeepLab_v3"):NEWLINENEWLINE # get block 4 feature outputsNEWLINE net = end_points[args.resnet_model + '/block4']NEWLINENEWLINE net = atrous_spatial_pyramid_pooling(net, "ASPP_layer", output_stride, is_training, args.l2_regularizer, depth=256)NEWLINENEWLINE net = layers.conv2d(net, args.num_classes, [1, 1], activation_fn=None,NEWLINE normalizer_fn=None, scope='logits')NEWLINENEWLINE size = tf.shape(inputs)[1:3]NEWLINE # resize the output logits to match the labels dimensionsNEWLINE net = tf.image.resize_bilinear(net, size)NEWLINE return netNEWLINENEWLINEdef model_fn(features, labels, mode, params):NEWLINE ''' Model function'''NEWLINENEWLINE output_stride = NoneNEWLINENEWLINE if mode == tf.estimator.ModeKeys.TRAIN:NEWLINE train = TrueNEWLINE output_stride = params.train_output_strideNEWLINE else:NEWLINE train = FalseNEWLINE output_stride = params.eval_output_strideNEWLINE NEWLINE img_input = tf.reshape(features, [-1, params.crop_size, params.crop_size, 3])NEWLINENEWLINE # Create networkNEWLINE raw_output = deeplab_v3(img_input, params, train, output_stride)NEWLINENEWLINE predictions = tf.argmax(raw_output, axis=-1)NEWLINENEWLINE # Setup the estimator according to the phase (Train, eval)NEWLINE reduced_loss = NoneNEWLINE train_op = NoneNEWLINE eval_metric_ops = {}NEWLINENEWLINE # compute loss(train and eval)NEWLINE loss = softmax_sparse_crossentropy_ignoring_last_label(labels,raw_output)NEWLINENEWLINE # L2 regularizationNEWLINE l2_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)NEWLINENEWLINE # Trainable VariablesNEWLINE #all_trainable = tf.trainable_variables()NEWLINE # L2 regularizationNEWLINE #l2_losses = [params.l2_regularizer * tf.nn.l2_loss(v) for v in all_trainable if 'weights' in v.name]NEWLINENEWLINE # Loss functionNEWLINE reduced_loss = tf.reduce_mean(loss) + tf.add_n(l2_losses)NEWLINENEWLINENEWLINE # evaluation metricNEWLINE miou, update_op = mIOU(raw_output,labels,params.num_classes,img_input)NEWLINENEWLINENEWLINE # configure trainingNEWLINE if mode == tf.estimator.ModeKeys.TRAIN:NEWLINE # piecewise learning rate schedulerNEWLINE global_step = tf.train.get_or_create_global_step()NEWLINE learning_rate = tf.train.piecewise_constant(global_step, params.learning_rate[0], params.learning_rate[1])NEWLINENEWLINE '''NEWLINE # learning rate schedulerNEWLINE global_step = tf.train.get_or_create_global_step()NEWLINE starter_learning_rate = 0.0001NEWLINE end_learning_rate = 0NEWLINE decay_steps = params.train_stepsNEWLINE learning_rate = tf.train.polynomial_decay(starter_learning_rate, global_step,NEWLINE decay_steps, end_learning_rate,NEWLINE power=0.9)NEWLINE '''NEWLINE NEWLINE # SGD + momentum optimizerNEWLINE optimizer = tf.train.MomentumOptimizer(learning_rate,momentum = 0.9)NEWLINE # comment out next two lines if batch norm is frozenNEWLINE # NOTE still need this because aspp needs batch normNEWLINE update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)NEWLINE with tf.control_dependencies(update_ops):NEWLINE train_op = optimizer.minimize(reduced_loss, global_step=tf.train.get_or_create_global_step())NEWLINENEWLINE if mode == tf.estimator.ModeKeys.EVAL:NEWLINE eval_metric_ops = {NEWLINE 'miou': (miou, update_op)NEWLINE }NEWLINENEWLINE return tf.estimator.EstimatorSpec(NEWLINE mode=mode,NEWLINE predictions=predictions,NEWLINE loss=reduced_loss,NEWLINE train_op=train_op,NEWLINE eval_metric_ops=eval_metric_ops,NEWLINE export_outputs=None,NEWLINE )NEWLINE # TRANSMITTER HAS A DIRECTIONAL ANTENNA - POINTED IN 12 DIFFERENT POSESNEWLINE# RECEIVER HAS AN OMNI DIRECTIONAL ANTENNANEWLINE# DISTANCE BETWEEN RECEIVER AND TRANSMITTER - (5, 10, 15) FEETNEWLINE# IMPEMENTING HIERARCHICAL MACHINE LEARNINGNEWLINE# IMPLEMENTING TRANSFER LEARNINGNEWLINE# DATA COLLECTED IN INDOOR ENVIRONMENTNEWLINENEWLINE#############################################################NEWLINE# Pose Estimation and Ranging the RF Transmitter #NEWLINE# Neural Network for Direction Finding Data 2020 #NEWLINE# Author: Debashri Roy #NEWLINE#############################################################NEWLINENEWLINE############ IMPORTING NECESSARY PACKAGES ################NEWLINEimport numpy as np # Package for numerical computationNEWLINEnp.set_printoptions(threshold=np.inf) # To print each elementsNEWLINEimport time # Package is for computing execution timeNEWLINEimport sys # Package to get command line argumentsNEWLINEimport tensorflow as tfNEWLINEfrom sklearn.model_selection import train_test_splitNEWLINEfrom array import arrayNEWLINENEWLINE# by setting env variables before Keras import you can set up which backendNEWLINEimport os,randomNEWLINE#os.environ["KERAS_BACKEND"] = "theano"NEWLINEos.environ["KERAS_BACKEND"] = "tensorflow"NEWLINEos.environ["THEANO_FLAGS"] = "device=cuda0, dnn.enabled=False"NEWLINEimport theanoNEWLINE#theano.config.mode = ""NEWLINENEWLINENEWLINENEWLINENEWLINEimport theano as thNEWLINEimport theano.tensor as TNEWLINEfrom keras.utils import np_utilsNEWLINEimport keras.models as modelsNEWLINEfrom keras.models import SequentialNEWLINEfrom keras.layers.core import Reshape,Dense,Dropout,Activation,FlattenNEWLINEfrom keras.layers import EmbeddingNEWLINEfrom keras.layers.noise import GaussianNoiseNEWLINEfrom keras.layers.convolutional import Conv2D, Conv1D, Convolution2D, MaxPooling2D, ZeroPadding2D, Convolution1DNEWLINEfrom keras.regularizers import *NEWLINEfrom keras.optimizers import adam, Nadam, AdadeltaNEWLINEfrom keras.optimizers import Adam, RMSprop, AdagradNEWLINEfrom keras.layers.convolutional_recurrent import ConvLSTM2DNEWLINEfrom keras.optimizers import rmspropNEWLINEfrom keras.callbacks import ReduceLROnPlateau, ModelCheckpointNEWLINE#from keras.regularizers import l2, activity_l2NEWLINEfrom sklearn import preprocessingNEWLINEfrom sklearn.preprocessing import StandardScalerNEWLINEfrom keras.layers.advanced_activations import LeakyReLU, PReLUNEWLINE# import BatchNormalizationNEWLINEfrom keras.layers.normalization import BatchNormalizationNEWLINEfrom keras.layers import GRU, RNN, SimpleRNN, LSTM, GRUCell, SimpleRNNCell, LSTMCellNEWLINENEWLINEfrom sklearn.metrics import classification_reportNEWLINEfrom sklearn.metrics import confusion_matrixNEWLINENEWLINEfrom keras.utils.np_utils import to_categoricalNEWLINEfrom keras.optimizers import SGDNEWLINENEWLINEimport matplotlibNEWLINE#matplotlib.use('TkAgg')NEWLINEmatplotlib.use('Agg')NEWLINEimport matplotlib.pyplot as pltNEWLINE#import seaborn as snsNEWLINEimport kerasNEWLINEimport itertoolsNEWLINEimport scipyNEWLINENEWLINEfrom keras.models import load_modelNEWLINENEWLINE########## FUNCTIONS TO CALCULATE F SCORE OF THE MODEL ###############NEWLINEfrom keras import backend as KNEWLINEdef recall_m(y_true, y_pred):NEWLINE true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))NEWLINE possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))NEWLINE recall = true_positives / (possible_positives + K.epsilon())NEWLINE return recallNEWLINENEWLINENEWLINEdef precision_m(y_true, y_pred):NEWLINE true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))NEWLINE predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))NEWLINE precision = true_positives / (predicted_positives + K.epsilon())NEWLINE return precisionNEWLINENEWLINENEWLINEdef f1_m(y_true, y_pred):NEWLINE precision = precision_m(y_true, y_pred)NEWLINE recall = recall_m(y_true, y_pred)NEWLINE return 2 * ((precision * recall) / (precision + recall + K.epsilon()))NEWLINE######################################################################NEWLINENEWLINENEWLINE################# THE WEIGHT MATRIX #################3NEWLINEW = np.matrix([[np.cos(1*(np.pi/8)), np.sin(1*(np.pi/8))],NEWLINE[np.cos(2*(np.pi/8)), np.sin(2*(np.pi/8))],NEWLINE[np.cos(3*(np.pi/8)), np.sin(3*(np.pi/8))],NEWLINE[np.cos(4*(np.pi/8)), np.sin(4*(np.pi/8))],NEWLINE[np.cos(5*(np.pi/8)), np.sin(5*(np.pi/8))],NEWLINE[np.cos(6*(np.pi/8)), np.sin(6*(np.pi/8))],NEWLINE[np.cos(7*(np.pi/8)), np.sin(7*(np.pi/8))],NEWLINE[np.cos(8*(np.pi/8)), np.sin(8*(np.pi/8))]]NEWLINE)NEWLINENEWLINE# W = np.matrix([[np.cos(4*(np.pi/8)), np.sin(4*(np.pi/8))],NEWLINE# [np.cos(4*(np.pi/8)), np.sin(4*(np.pi/8))],NEWLINE# [np.cos(4*(np.pi/8)), np.sin(4*(np.pi/8))],NEWLINE# [np.cos(4*(np.pi/8)), np.sin(4*(np.pi/8))],NEWLINE# [np.cos(0*(np.pi/8)), np.sin(0*(np.pi/8))],NEWLINE# [np.cos(0*(np.pi/8)), np.sin(0*(np.pi/8))],NEWLINE# [np.cos(0*(np.pi/8)), np.sin(0*(np.pi/8))],NEWLINE# [np.cos(0*(np.pi/8)), np.sin(0*(np.pi/8))]]NEWLINE# )NEWLINENEWLINEprint(W)NEWLINENEWLINE# variablesNEWLINEdtype_all= scipy.dtype([('raw-iq', scipy.complex64)])NEWLINENEWLINENEWLINEsample_size = 1024 # CHANGE AND EXPERIMENT -512NEWLINEno_of_samples = 4000 # CHANGE AND EXPERIMENT - 4000NEWLINEno_of_features= 8 # CHANGE AND EXPERIMENTNEWLINEnumber_of_data_to_read = sample_size * no_of_samplesNEWLINENEWLINE#######################################################################################NEWLINENEWLINE#############################################################################################################################NEWLINE######## #######NEWLINE######## READING THE 5FT DATA #######NEWLINE######## #######NEWLINE#############################################################################################################################NEWLINENEWLINEdata_file_loc1 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/0_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER DIRECTLY POINTING TO THE RECEIVERNEWLINEdata_file_loc2 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/+30_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 30 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc3 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/+60_5ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS 60 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc4 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/+90_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 90 DEGREE LEFT TO THE RECEIVERNEWLINENEWLINEdata_file_loc5 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/+120_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 120 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc6 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/+150_5ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS 150 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc7 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/180_5ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS DIRECTLY POINTED AWAY FROM THE RECEIVERNEWLINEdata_file_loc8 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/-150_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 30 DEGREE RIGHT TO THE RECEIVERNEWLINENEWLINEdata_file_loc9 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/-120_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 60 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc10 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/-90_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 90 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc11 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/-60_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 120 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc12 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/-30_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 150 DEGREE RIGHT TO THE RECEIVERNEWLINENEWLINENEWLINENEWLINEiqdata_loc1 = scipy.fromfile(open(data_file_loc1), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc2 = scipy.fromfile(open(data_file_loc2), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc3 = scipy.fromfile(open(data_file_loc3), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc4 = scipy.fromfile(open(data_file_loc4), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINEiqdata_loc5 = scipy.fromfile(open(data_file_loc5), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc6 = scipy.fromfile(open(data_file_loc6), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc7 = scipy.fromfile(open(data_file_loc7), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc8 = scipy.fromfile(open(data_file_loc8), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINENEWLINEiqdata_loc9 = scipy.fromfile(open(data_file_loc9), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc10 = scipy.fromfile(open(data_file_loc10), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc11 = scipy.fromfile(open(data_file_loc11), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc12 = scipy.fromfile(open(data_file_loc12), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINENEWLINENEWLINE# PREPARING THE DATA WITHOUT TIME INFORMATIONNEWLINEno_of_data_loc1 = iqdata_loc1.shape[0]NEWLINEno_of_data_loc2 = iqdata_loc2.shape[0]NEWLINEno_of_data_loc3 = iqdata_loc3.shape[0]NEWLINEno_of_data_loc4 = iqdata_loc4.shape[0]NEWLINENEWLINEno_of_data_loc5 = iqdata_loc5.shape[0]NEWLINEno_of_data_loc6 = iqdata_loc6.shape[0]NEWLINEno_of_data_loc7 = iqdata_loc7.shape[0]NEWLINEno_of_data_loc8 = iqdata_loc8.shape[0]NEWLINENEWLINEno_of_data_loc9 = iqdata_loc9.shape[0]NEWLINEno_of_data_loc10 = iqdata_loc10.shape[0]NEWLINEno_of_data_loc11 = iqdata_loc11.shape[0]NEWLINEno_of_data_loc12 = iqdata_loc12.shape[0]NEWLINENEWLINENEWLINENEWLINE################################################################################################################NEWLINE# CONCATINATING THE I AND Q VALUES VERTICALLY OF (I, Q) SAMPLE. -- note the axis argument is set to 1 (means vertical stacking)NEWLINE# SIMULATNEOUSLY MULTIPLYING WITH THE WEIGHT MATRIX - TO REFLECT THE MULTI-ANGULAR PROJECTIONNEWLINENEWLINExdata_loc1= np.concatenate([iqdata_loc1['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc1['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc1 = np.matmul(xdata_loc1, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc2= np.concatenate([iqdata_loc2['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc2['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc2 = np.matmul(xdata_loc2, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc3= np.concatenate([iqdata_loc3['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc3['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc3 = np.matmul(xdata_loc3, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc4= np.concatenate([iqdata_loc4['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc4['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc4 = np.matmul(xdata_loc4, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINExdata_loc5= np.concatenate([iqdata_loc5['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc5['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc5 = np.matmul(xdata_loc5, np.transpose(W))NEWLINENEWLINExdata_loc6= np.concatenate([iqdata_loc6['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc6['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc6 = np.matmul(xdata_loc6, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc7= np.concatenate([iqdata_loc7['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc7['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc7 = np.matmul(xdata_loc7, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc8= np.concatenate([iqdata_loc8['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc8['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc8 = np.matmul(xdata_loc8, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINExdata_loc9= np.concatenate([iqdata_loc9['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc9['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc9 = np.matmul(xdata_loc9, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc10= np.concatenate([iqdata_loc10['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc10['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc10 = np.matmul(xdata_loc10, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc11= np.concatenate([iqdata_loc11['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc11['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc11 = np.matmul(xdata_loc11, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc12= np.concatenate([iqdata_loc12['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc12['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc12 = np.matmul(xdata_loc12, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINE# RESHAPING THE XDATANEWLINExdata_loc1= xdata_loc1.T.reshape(no_of_data_loc1//(sample_size), sample_size*no_of_features)NEWLINExdata_loc2 = xdata_loc2.T.reshape(no_of_data_loc2//(sample_size), sample_size*no_of_features)NEWLINExdata_loc3 = xdata_loc3.T.reshape(no_of_data_loc3//(sample_size), sample_size*no_of_features)NEWLINExdata_loc4 = xdata_loc4.T.reshape(no_of_data_loc4//(sample_size), sample_size*no_of_features)NEWLINENEWLINExdata_loc5= xdata_loc5.T.reshape(no_of_data_loc5//(sample_size), sample_size*no_of_features)NEWLINExdata_loc6 = xdata_loc6.T.reshape(no_of_data_loc6//(sample_size), sample_size*no_of_features)NEWLINExdata_loc7 = xdata_loc7.T.reshape(no_of_data_loc7//(sample_size), sample_size*no_of_features)NEWLINExdata_loc8 = xdata_loc8.T.reshape(no_of_data_loc8//(sample_size), sample_size*no_of_features)NEWLINENEWLINExdata_loc9= xdata_loc9.T.reshape(no_of_data_loc9//(sample_size), sample_size*no_of_features)NEWLINExdata_loc10 = xdata_loc10.T.reshape(no_of_data_loc10//(sample_size), sample_size*no_of_features)NEWLINExdata_loc11 = xdata_loc11.T.reshape(no_of_data_loc11//(sample_size), sample_size*no_of_features)NEWLINExdata_loc12 = xdata_loc12.T.reshape(no_of_data_loc12//(sample_size), sample_size*no_of_features)NEWLINENEWLINENEWLINENEWLINE#CONCATINATING THE DIFFERENT POSE DATA HORIZONTALLY (ROWWISE)NEWLINExdata = np.concatenate([xdata_loc1, xdata_loc2, xdata_loc3, xdata_loc4, xdata_loc5, xdata_loc6, xdata_loc7, xdata_loc8, xdata_loc9, xdata_loc10, xdata_loc11, xdata_loc12], axis=0)NEWLINENEWLINENEWLINENEWLINE# CREATING LABEL FOR THE DATASETSNEWLINEydata_loc1 = np.full(xdata_loc1.shape[0], 0, dtype=int)NEWLINEydata_loc2 = np.full(xdata_loc2.shape[0], 1, dtype=int)NEWLINEydata_loc3 = np.full(xdata_loc3.shape[0], 2, dtype=int)NEWLINEydata_loc4 = np.full(xdata_loc4.shape[0], 3, dtype=int)NEWLINENEWLINEydata_loc5 = np.full(xdata_loc5.shape[0], 4, dtype=int)NEWLINEydata_loc6 = np.full(xdata_loc6.shape[0], 5, dtype=int)NEWLINEydata_loc7 = np.full(xdata_loc7.shape[0], 6, dtype=int)NEWLINEydata_loc8 = np.full(xdata_loc8.shape[0], 7, dtype=int)NEWLINENEWLINEydata_loc9 = np.full(xdata_loc9.shape[0], 8, dtype=int)NEWLINEydata_loc10 = np.full(xdata_loc10.shape[0], 9, dtype=int)NEWLINEydata_loc11 = np.full(xdata_loc11.shape[0], 10, dtype=int)NEWLINEydata_loc12 = np.full(xdata_loc12.shape[0], 11, dtype=int)NEWLINENEWLINE#CONCATINATING THE DIFFERENT POSE LABELS HORIZONTALLY (ROWWISE)NEWLINEydata = np.concatenate([ydata_loc1, ydata_loc2, ydata_loc3, ydata_loc4, ydata_loc5, ydata_loc6, ydata_loc7, ydata_loc8, ydata_loc9, ydata_loc10, ydata_loc11, ydata_loc12], axis=0)NEWLINENEWLINENEWLINE# PREPROCESSING X AND Y DATANEWLINExdata =xdata.astype(np.float)NEWLINENEWLINEydata = ydata.astype(np.int).flatten()NEWLINENEWLINE# REMOVING THE NANSNEWLINExdata = np.nan_to_num(xdata)NEWLINENEWLINENEWLINE# ############## RANDOMLY SHUFFLING THE DATA ###################NEWLINE#NEWLINE# first concatinate - TO MAINTIAN THE XDATA AND YDATA MAPPINGNEWLINExydata = np.concatenate([xdata.reshape(xdata.shape[0], xdata.shape[1]), ydata.reshape(ydata.shape[0], 1)], axis=1)NEWLINENEWLINEnp.random.shuffle(xydata)NEWLINENEWLINEprint("Shape of XYDATA", xydata.shape)NEWLINENEWLINExdata_5ft, ydata_5ft = xydata[:,0:sample_size*no_of_features], xydata[:,((sample_size*no_of_features))] # THE LAST COLUMN IS THE YDATA # USE 2 INSTEAD OF 8 OF YOU DO NOT USE MULTI-ANGULAR PROJECTIONNEWLINENEWLINENEWLINE################################################################################################################################NEWLINENEWLINE#############################################################################################################################NEWLINE######## #######NEWLINE######## READING THE 10FT DATA #######NEWLINE######## #######NEWLINE#############################################################################################################################NEWLINENEWLINEdata_file_loc1 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/0_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER DIRECTLY POINTING TO THE RECEIVERNEWLINEdata_file_loc2 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/+30_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 30 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc3 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/+60_10ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS 60 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc4 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/+90_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 90 DEGREE LEFT TO THE RECEIVERNEWLINENEWLINEdata_file_loc5 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/+120_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 120 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc6 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/+150_10ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS 150 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc7 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/180_10ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS DIRECTLY POINTED AWAY FROM THE RECEIVERNEWLINEdata_file_loc8 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/-150_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 30 DEGREE RIGHT TO THE RECEIVERNEWLINENEWLINEdata_file_loc9 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/-120_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 60 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc10 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/-90_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 90 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc11 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/-60_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 120 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc12 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/-30_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 150 DEGREE RIGHT TO THE RECEIVERNEWLINENEWLINENEWLINENEWLINEiqdata_loc1 = scipy.fromfile(open(data_file_loc1), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc2 = scipy.fromfile(open(data_file_loc2), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc3 = scipy.fromfile(open(data_file_loc3), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc4 = scipy.fromfile(open(data_file_loc4), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINEiqdata_loc5 = scipy.fromfile(open(data_file_loc5), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc6 = scipy.fromfile(open(data_file_loc6), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc7 = scipy.fromfile(open(data_file_loc7), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc8 = scipy.fromfile(open(data_file_loc8), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINENEWLINEiqdata_loc9 = scipy.fromfile(open(data_file_loc9), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc10 = scipy.fromfile(open(data_file_loc10), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc11 = scipy.fromfile(open(data_file_loc11), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc12 = scipy.fromfile(open(data_file_loc12), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINENEWLINENEWLINE# PREPARING THE DATA WITHOUT TIME INFORMATIONNEWLINEno_of_data_loc1 = iqdata_loc1.shape[0]NEWLINEno_of_data_loc2 = iqdata_loc2.shape[0]NEWLINEno_of_data_loc3 = iqdata_loc3.shape[0]NEWLINEno_of_data_loc4 = iqdata_loc4.shape[0]NEWLINENEWLINEno_of_data_loc5 = iqdata_loc5.shape[0]NEWLINEno_of_data_loc6 = iqdata_loc6.shape[0]NEWLINEno_of_data_loc7 = iqdata_loc7.shape[0]NEWLINEno_of_data_loc8 = iqdata_loc8.shape[0]NEWLINENEWLINEno_of_data_loc9 = iqdata_loc9.shape[0]NEWLINEno_of_data_loc10 = iqdata_loc10.shape[0]NEWLINEno_of_data_loc11 = iqdata_loc11.shape[0]NEWLINEno_of_data_loc12 = iqdata_loc12.shape[0]NEWLINENEWLINENEWLINENEWLINE################################################################################################################NEWLINE# CONCATINATING THE I AND Q VALUES VERTICALLY OF (I, Q) SAMPLE. -- note the axis argument is set to 1 (means vertical stacking)NEWLINE# SIMULATNEOUSLY MULTIPLYING WITH THE WEIGHT MATRIX - TO REFLECT THE MULTI-ANGULAR PROJECTIONNEWLINENEWLINExdata_loc1= np.concatenate([iqdata_loc1['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc1['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc1 = np.matmul(xdata_loc1, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc2= np.concatenate([iqdata_loc2['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc2['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc2 = np.matmul(xdata_loc2, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc3= np.concatenate([iqdata_loc3['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc3['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc3 = np.matmul(xdata_loc3, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc4= np.concatenate([iqdata_loc4['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc4['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc4 = np.matmul(xdata_loc4, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINExdata_loc5= np.concatenate([iqdata_loc5['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc5['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc5 = np.matmul(xdata_loc5, np.transpose(W))NEWLINENEWLINExdata_loc6= np.concatenate([iqdata_loc6['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc6['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc6 = np.matmul(xdata_loc6, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc7= np.concatenate([iqdata_loc7['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc7['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc7 = np.matmul(xdata_loc7, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc8= np.concatenate([iqdata_loc8['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc8['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc8 = np.matmul(xdata_loc8, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINExdata_loc9= np.concatenate([iqdata_loc9['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc9['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc9 = np.matmul(xdata_loc9, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc10= np.concatenate([iqdata_loc10['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc10['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc10 = np.matmul(xdata_loc10, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc11= np.concatenate([iqdata_loc11['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc11['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc11 = np.matmul(xdata_loc11, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc12= np.concatenate([iqdata_loc12['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc12['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc12 = np.matmul(xdata_loc12, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINE# RESHAPING THE XDATANEWLINExdata_loc1= xdata_loc1.T.reshape(no_of_data_loc1//(sample_size), sample_size*no_of_features)NEWLINExdata_loc2 = xdata_loc2.T.reshape(no_of_data_loc2//(sample_size), sample_size*no_of_features)NEWLINExdata_loc3 = xdata_loc3.T.reshape(no_of_data_loc3//(sample_size), sample_size*no_of_features)NEWLINExdata_loc4 = xdata_loc4.T.reshape(no_of_data_loc4//(sample_size), sample_size*no_of_features)NEWLINENEWLINExdata_loc5= xdata_loc5.T.reshape(no_of_data_loc5//(sample_size), sample_size*no_of_features)NEWLINExdata_loc6 = xdata_loc6.T.reshape(no_of_data_loc6//(sample_size), sample_size*no_of_features)NEWLINExdata_loc7 = xdata_loc7.T.reshape(no_of_data_loc7//(sample_size), sample_size*no_of_features)NEWLINExdata_loc8 = xdata_loc8.T.reshape(no_of_data_loc8//(sample_size), sample_size*no_of_features)NEWLINENEWLINExdata_loc9= xdata_loc9.T.reshape(no_of_data_loc9//(sample_size), sample_size*no_of_features)NEWLINExdata_loc10 = xdata_loc10.T.reshape(no_of_data_loc10//(sample_size), sample_size*no_of_features)NEWLINExdata_loc11 = xdata_loc11.T.reshape(no_of_data_loc11//(sample_size), sample_size*no_of_features)NEWLINExdata_loc12 = xdata_loc12.T.reshape(no_of_data_loc12//(sample_size), sample_size*no_of_features)NEWLINENEWLINENEWLINENEWLINE#CONCATINATING THE DIFFERENT POSE DATA HORIZONTALLY (ROWWISE)NEWLINExdata = np.concatenate([xdata_loc1, xdata_loc2, xdata_loc3, xdata_loc4, xdata_loc5, xdata_loc6, xdata_loc7, xdata_loc8, xdata_loc9, xdata_loc10, xdata_loc11, xdata_loc12], axis=0)NEWLINENEWLINENEWLINENEWLINE# CREATING LABEL FOR THE DATASETSNEWLINEydata_loc1 = np.full(xdata_loc1.shape[0], 0, dtype=int)NEWLINEydata_loc2 = np.full(xdata_loc2.shape[0], 1, dtype=int)NEWLINEydata_loc3 = np.full(xdata_loc3.shape[0], 2, dtype=int)NEWLINEydata_loc4 = np.full(xdata_loc4.shape[0], 3, dtype=int)NEWLINENEWLINEydata_loc5 = np.full(xdata_loc5.shape[0], 4, dtype=int)NEWLINEydata_loc6 = np.full(xdata_loc6.shape[0], 5, dtype=int)NEWLINEydata_loc7 = np.full(xdata_loc7.shape[0], 6, dtype=int)NEWLINEydata_loc8 = np.full(xdata_loc8.shape[0], 7, dtype=int)NEWLINENEWLINEydata_loc9 = np.full(xdata_loc9.shape[0], 8, dtype=int)NEWLINEydata_loc10 = np.full(xdata_loc10.shape[0], 9, dtype=int)NEWLINEydata_loc11 = np.full(xdata_loc11.shape[0], 10, dtype=int)NEWLINEydata_loc12 = np.full(xdata_loc12.shape[0], 11, dtype=int)NEWLINENEWLINE#CONCATINATING THE DIFFERENT POSE LABELS HORIZONTALLY (ROWWISE)NEWLINEydata = np.concatenate([ydata_loc1, ydata_loc2, ydata_loc3, ydata_loc4, ydata_loc5, ydata_loc6, ydata_loc7, ydata_loc8, ydata_loc9, ydata_loc10, ydata_loc11, ydata_loc12], axis=0)NEWLINENEWLINENEWLINE# PREPROCESSING X AND Y DATANEWLINExdata =xdata.astype(np.float)NEWLINENEWLINEydata = ydata.astype(np.int).flatten()NEWLINENEWLINE# REMOVING THE NANSNEWLINExdata = np.nan_to_num(xdata)NEWLINENEWLINENEWLINE# ############## RANDOMLY SHUFFLING THE DATA ###################NEWLINE#NEWLINE# first concatinate - TO MAINTIAN THE XDATA AND YDATA MAPPINGNEWLINExydata = np.concatenate([xdata.reshape(xdata.shape[0], xdata.shape[1]), ydata.reshape(ydata.shape[0], 1)], axis=1)NEWLINENEWLINEnp.random.shuffle(xydata)NEWLINENEWLINEprint("Shape of XYDATA", xydata.shape)NEWLINENEWLINExdata_10ft, ydata_10ft = xydata[:,0:sample_size*no_of_features], xydata[:,((sample_size*no_of_features))] # THE LAST COLUMN IS THE YDATA # USE 2 INSTEAD OF 8 OF YOU DO NOT USE MULTI-ANGULAR PROJECTIONNEWLINENEWLINENEWLINE################################################################################################################################NEWLINENEWLINE#############################################################################################################################NEWLINE######## #######NEWLINE######## READING THE 15FT DATA #######NEWLINE######## #######NEWLINE#############################################################################################################################NEWLINENEWLINEdata_file_loc1 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/0_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER DIRECTLY POINTING TO THE RECEIVERNEWLINEdata_file_loc2 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/+30_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 30 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc3 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/+60_15ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS 60 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc4 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/+90_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 90 DEGREE LEFT TO THE RECEIVERNEWLINENEWLINEdata_file_loc5 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/+120_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 120 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc6 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/+150_15ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS 150 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc7 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/180_15ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS DIRECTLY POINTED AWAY FROM THE RECEIVERNEWLINEdata_file_loc8 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/-150_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 30 DEGREE RIGHT TO THE RECEIVERNEWLINENEWLINEdata_file_loc9 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/-120_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 60 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc10 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/-90_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 90 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc11 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/-60_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 120 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc12 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/-30_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 150 DEGREE RIGHT TO THE RECEIVERNEWLINENEWLINENEWLINENEWLINEiqdata_loc1 = scipy.fromfile(open(data_file_loc1), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc2 = scipy.fromfile(open(data_file_loc2), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc3 = scipy.fromfile(open(data_file_loc3), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc4 = scipy.fromfile(open(data_file_loc4), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINEiqdata_loc5 = scipy.fromfile(open(data_file_loc5), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc6 = scipy.fromfile(open(data_file_loc6), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc7 = scipy.fromfile(open(data_file_loc7), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc8 = scipy.fromfile(open(data_file_loc8), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINENEWLINEiqdata_loc9 = scipy.fromfile(open(data_file_loc9), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc10 = scipy.fromfile(open(data_file_loc10), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc11 = scipy.fromfile(open(data_file_loc11), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc12 = scipy.fromfile(open(data_file_loc12), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINENEWLINENEWLINE# PREPARING THE DATA WITHOUT TIME INFORMATIONNEWLINEno_of_data_loc1 = iqdata_loc1.shape[0]NEWLINEno_of_data_loc2 = iqdata_loc2.shape[0]NEWLINEno_of_data_loc3 = iqdata_loc3.shape[0]NEWLINEno_of_data_loc4 = iqdata_loc4.shape[0]NEWLINENEWLINEno_of_data_loc5 = iqdata_loc5.shape[0]NEWLINEno_of_data_loc6 = iqdata_loc6.shape[0]NEWLINEno_of_data_loc7 = iqdata_loc7.shape[0]NEWLINEno_of_data_loc8 = iqdata_loc8.shape[0]NEWLINENEWLINEno_of_data_loc9 = iqdata_loc9.shape[0]NEWLINEno_of_data_loc10 = iqdata_loc10.shape[0]NEWLINEno_of_data_loc11 = iqdata_loc11.shape[0]NEWLINEno_of_data_loc12 = iqdata_loc12.shape[0]NEWLINENEWLINENEWLINENEWLINE################################################################################################################NEWLINE# CONCATINATING THE I AND Q VALUES VERTICALLY OF (I, Q) SAMPLE. -- note the axis argument is set to 1 (means vertical stacking)NEWLINE# SIMULATNEOUSLY MULTIPLYING WITH THE WEIGHT MATRIX - TO REFLECT THE MULTI-ANGULAR PROJECTIONNEWLINENEWLINExdata_loc1= np.concatenate([iqdata_loc1['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc1['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc1 = np.matmul(xdata_loc1, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc2= np.concatenate([iqdata_loc2['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc2['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc2 = np.matmul(xdata_loc2, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc3= np.concatenate([iqdata_loc3['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc3['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc3 = np.matmul(xdata_loc3, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc4= np.concatenate([iqdata_loc4['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc4['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc4 = np.matmul(xdata_loc4, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINExdata_loc5= np.concatenate([iqdata_loc5['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc5['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc5 = np.matmul(xdata_loc5, np.transpose(W))NEWLINENEWLINExdata_loc6= np.concatenate([iqdata_loc6['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc6['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc6 = np.matmul(xdata_loc6, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc7= np.concatenate([iqdata_loc7['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc7['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc7 = np.matmul(xdata_loc7, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc8= np.concatenate([iqdata_loc8['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc8['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc8 = np.matmul(xdata_loc8, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINExdata_loc9= np.concatenate([iqdata_loc9['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc9['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc9 = np.matmul(xdata_loc9, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc10= np.concatenate([iqdata_loc10['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc10['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc10 = np.matmul(xdata_loc10, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc11= np.concatenate([iqdata_loc11['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc11['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc11 = np.matmul(xdata_loc11, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc12= np.concatenate([iqdata_loc12['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc12['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc12 = np.matmul(xdata_loc12, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINE# RESHAPING THE XDATANEWLINExdata_loc1= xdata_loc1.T.reshape(no_of_data_loc1//(sample_size), sample_size*no_of_features)NEWLINExdata_loc2 = xdata_loc2.T.reshape(no_of_data_loc2//(sample_size), sample_size*no_of_features)NEWLINExdata_loc3 = xdata_loc3.T.reshape(no_of_data_loc3//(sample_size), sample_size*no_of_features)NEWLINExdata_loc4 = xdata_loc4.T.reshape(no_of_data_loc4//(sample_size), sample_size*no_of_features)NEWLINENEWLINExdata_loc5= xdata_loc5.T.reshape(no_of_data_loc5//(sample_size), sample_size*no_of_features)NEWLINExdata_loc6 = xdata_loc6.T.reshape(no_of_data_loc6//(sample_size), sample_size*no_of_features)NEWLINExdata_loc7 = xdata_loc7.T.reshape(no_of_data_loc7//(sample_size), sample_size*no_of_features)NEWLINExdata_loc8 = xdata_loc8.T.reshape(no_of_data_loc8//(sample_size), sample_size*no_of_features)NEWLINENEWLINExdata_loc9= xdata_loc9.T.reshape(no_of_data_loc9//(sample_size), sample_size*no_of_features)NEWLINExdata_loc10 = xdata_loc10.T.reshape(no_of_data_loc10//(sample_size), sample_size*no_of_features)NEWLINExdata_loc11 = xdata_loc11.T.reshape(no_of_data_loc11//(sample_size), sample_size*no_of_features)NEWLINExdata_loc12 = xdata_loc12.T.reshape(no_of_data_loc12//(sample_size), sample_size*no_of_features)NEWLINENEWLINENEWLINENEWLINE#CONCATINATING THE DIFFERENT POSE DATA HORIZONTALLY (ROWWISE)NEWLINExdata = np.concatenate([xdata_loc1, xdata_loc2, xdata_loc3, xdata_loc4, xdata_loc5, xdata_loc6, xdata_loc7, xdata_loc8, xdata_loc9, xdata_loc10, xdata_loc11, xdata_loc12], axis=0)NEWLINENEWLINENEWLINENEWLINE# CREATING LABEL FOR THE DATASETSNEWLINEydata_loc1 = np.full(xdata_loc1.shape[0], 0, dtype=int)NEWLINEydata_loc2 = np.full(xdata_loc2.shape[0], 1, dtype=int)NEWLINEydata_loc3 = np.full(xdata_loc3.shape[0], 2, dtype=int)NEWLINEydata_loc4 = np.full(xdata_loc4.shape[0], 3, dtype=int)NEWLINENEWLINEydata_loc5 = np.full(xdata_loc5.shape[0], 4, dtype=int)NEWLINEydata_loc6 = np.full(xdata_loc6.shape[0], 5, dtype=int)NEWLINEydata_loc7 = np.full(xdata_loc7.shape[0], 6, dtype=int)NEWLINEydata_loc8 = np.full(xdata_loc8.shape[0], 7, dtype=int)NEWLINENEWLINEydata_loc9 = np.full(xdata_loc9.shape[0], 8, dtype=int)NEWLINEydata_loc10 = np.full(xdata_loc10.shape[0], 9, dtype=int)NEWLINEydata_loc11 = np.full(xdata_loc11.shape[0], 10, dtype=int)NEWLINEydata_loc12 = np.full(xdata_loc12.shape[0], 11, dtype=int)NEWLINENEWLINE#CONCATINATING THE DIFFERENT POSE LABELS HORIZONTALLY (ROWWISE)NEWLINEydata = np.concatenate([ydata_loc1, ydata_loc2, ydata_loc3, ydata_loc4, ydata_loc5, ydata_loc6, ydata_loc7, ydata_loc8, ydata_loc9, ydata_loc10, ydata_loc11, ydata_loc12], axis=0)NEWLINENEWLINENEWLINE# PREPROCESSING X AND Y DATANEWLINExdata =xdata.astype(np.float)NEWLINENEWLINEydata = ydata.astype(np.int).flatten()NEWLINENEWLINE# REMOVING THE NANSNEWLINExdata = np.nan_to_num(xdata)NEWLINENEWLINENEWLINE# ############## RANDOMLY SHUFFLING THE DATA ###################NEWLINE#NEWLINE# first concatinate - TO MAINTIAN THE XDATA AND YDATA MAPPINGNEWLINExydata = np.concatenate([xdata.reshape(xdata.shape[0], xdata.shape[1]), ydata.reshape(ydata.shape[0], 1)], axis=1)NEWLINENEWLINEnp.random.shuffle(xydata)NEWLINENEWLINEprint("Shape of XYDATA", xydata.shape)NEWLINENEWLINExdata_15ft, ydata_15ft = xydata[:,0:sample_size*no_of_features], xydata[:,((sample_size*no_of_features))] # THE LAST COLUMN IS THE YDATA # USE 2 INSTEAD OF 8 OF YOU DO NOT USE MULTI-ANGULAR PROJECTIONNEWLINENEWLINENEWLINE################################################################################################################################NEWLINENEWLINE#############################################################################################################################NEWLINE######## #######NEWLINE######## HIERARCHICAL TRAINING- FIRST STEP #######NEWLINE######## FIRST CLASSIFYING THE DATA BASED ON DISTANCES #######NEWLINE######## PREDICTING DISTANCE BETWEEN THE RECEIVER AND TRANSMITTER #######NEWLINE######## #######NEWLINE#############################################################################################################################NEWLINENEWLINENEWLINExdata_ranging = np.concatenate([xdata_5ft, xdata_10ft, xdata_15ft], axis= 0 )NEWLINENEWLINE# CREATING LABEL FOR THE DATASETSNEWLINEydata_range1 = np.full(xdata_5ft.shape[0], 0, dtype=int)NEWLINEydata_range2 = np.full(xdata_10ft.shape[0], 1, dtype=int)NEWLINEydata_range3 = np.full(xdata_15ft.shape[0], 2, dtype=int)NEWLINENEWLINE#CONCATINATING THE DIFFERENT POSE LABELS HORIZONTALLY (ROWWISE)NEWLINEydata_ranging = np.concatenate([ydata_range1, ydata_range2, ydata_range3], axis=0)NEWLINENEWLINE#################### NORMALIZE THE X DATA #######################NEWLINENEWLINENEWLINEstandard = preprocessing.StandardScaler().fit(xdata_ranging) # Normalize the data with zero mean and unit variance for each columnNEWLINExdata_ranging = standard.transform(xdata_ranging)NEWLINENEWLINENEWLINENEWLINE############### SEPARATING TRAIN AND TEST DATA #######################NEWLINEprint("############## STARTING THE TRAINING TO PREDICT THE RANGE BETWEEN RECEIVER AND TRANSMITTER ##########################")NEWLINENEWLINExtrain_ranging, xtest_ranging, ytrain_ranging, ytest_ranging = train_test_split(xdata_ranging, ydata_ranging, test_size=0.2, shuffle = True, random_state=42) # Randomly shuffling and 80/20 is train/test sizeNEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_ranging.shape, xtest_ranging.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_ranging.shape, ytest_ranging.shape)NEWLINENEWLINE# RESHAPING THE DATA FROM 2 DIMENSIONAL TO 4 DIMENSIONAL SHAPE - NEEDED TO APPLY TO USE 2D-CONVOLUTIONNEWLINE# reshape to be [samples][width][height][channels]NEWLINExtrain_ranging = xtrain_ranging.reshape((xtrain_ranging.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINExtest_ranging = xtest_ranging.reshape((xtest_ranging.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINENEWLINENEWLINEnum_classes = 3 # TOTAL NUMBER OF RANGESNEWLINENEWLINENEWLINENEWLINE# Convert labels to categorical one-hot encodingNEWLINEytrain_ranging_one_hot = to_categorical(ytrain_ranging, num_classes=num_classes) # DEFINE THE NUMBER OF TOTAL CLASSES IN LABELNEWLINEytest_ranging_one_hot = to_categorical(ytest_ranging, num_classes=num_classes)NEWLINENEWLINENEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_ranging.shape, xtest_ranging.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_ranging_one_hot.shape, ytest_ranging_one_hot.shape)NEWLINENEWLINE############################################################NEWLINE# #NEWLINE######## Building a 2D Convolutional Neural Network #####NEWLINE# #NEWLINE############################################################NEWLINENEWLINEdr = 0.6 # dropout rate (%)NEWLINEbatch_size = 128 # Mini batch sizeNEWLINEnb_epoch = 100 # Number of Epoch (Give a higher number to get better accuracy)NEWLINENEWLINEclasses = ["5ft", "10ft", "15ft"] # CHANGE LABELNEWLINEin_shp = list(xtrain_ranging.shape[1:]) # Input DimensionNEWLINEprint(in_shp)NEWLINE# model = models.Sequential()NEWLINEtimesteps=1NEWLINEdata_dim=xtrain_ranging.shape[1]NEWLINENEWLINENEWLINENEWLINE# print ("AFTER RESHAPE")NEWLINEytrain_ranging_one_hot = np.reshape(ytrain_ranging_one_hot, (ytrain_ranging_one_hot.shape[0], num_classes)) # Used in trainingNEWLINEytest_ranging_one_hot = np.reshape(ytest_ranging_one_hot, (ytest_ranging_one_hot.shape[0], num_classes)) # Used in trainingNEWLINENEWLINEstart_time = time.time() # Taking start time to calculate overall execution timeNEWLINENEWLINE# Modeling the CNNNEWLINEmodel_ranging = Sequential()NEWLINENEWLINE# FIRST CONVOLUTIONAL LAYERNEWLINEmodel_ranging.add(Conv2D(128, (2, 2), input_shape=(no_of_features, sample_size, 1), activation='relu')) # CHANGE # Stride (1, 1)NEWLINEmodel_ranging.add(MaxPooling2D()) # Pool size: (2, 2) and stride (2, 2)NEWLINEmodel_ranging.add(Dropout(0.2))NEWLINENEWLINE# SECOND CONVOLUTIONAL LAYERNEWLINEmodel_ranging.add(Conv2D(64, (2, 2), activation='relu'))NEWLINEmodel_ranging.add(MaxPooling2D())NEWLINEmodel_ranging.add(Dropout(dr))NEWLINENEWLINEmodel_ranging.add(Flatten())NEWLINENEWLINE# FIRST DENSE LAYERNEWLINEmodel_ranging.add(Dense(256, activation='relu'))NEWLINENEWLINE# SECOND DENSE LAYERNEWLINEmodel_ranging.add(Dense(128, activation='relu'))NEWLINENEWLINE# OUTPUT LAYERNEWLINEmodel_ranging.add(Dense(num_classes, activation='softmax'))NEWLINENEWLINE# Compile modelNEWLINE# For a multi-class classification problemNEWLINEsgd = SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True)NEWLINEadam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)NEWLINENEWLINE# model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # Multiclass classification with rmspropNEWLINENEWLINE#model.compile(optimizer='sgd', loss='categorical_crossentropy',metrics=['acc', f1_m, precision_m, recall_m]) # Multiclass classification with rms adam optimizer # CHANGENEWLINENEWLINEmodel_ranging.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc', f1_m, precision_m, recall_m])NEWLINENEWLINEmodel_ranging.summary()NEWLINEfilepath = '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/direction_data_ranging_2D_CNN_Mapping.wts.h5'NEWLINEprint("The dropout rate was: ")NEWLINEprint(dr)NEWLINENEWLINENEWLINE# Fit the modelNEWLINE# history= model.fit(xtrain, ytrain_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_data = (xtest, ytest_one_hot), callbacks = [keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'), keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINEhistory = model_ranging.fit(xtrain_ranging, ytrain_ranging_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_split=0.1, callbacks=[NEWLINE keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'),NEWLINE keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINENEWLINENEWLINENEWLINE# SAVING THE MODEL FOR TRANSFER LEARNINGNEWLINEsaved_file = '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/2D_CNN_ranging_classifier.h5'NEWLINEmodel_ranging.save(saved_file) # SAVING THE MODEL FOR TRANSFER LEARNINGNEWLINENEWLINENEWLINENEWLINE# Evaluate the modelNEWLINEloss, accuracy, f1_score, precision, recall = model_ranging.evaluate(xtest_ranging, ytest_ranging_one_hot, batch_size=batch_size) # CHANGENEWLINEprint("\nTest Loss: %s: %.2f%%" % (model_ranging.metrics_names[0], loss * 100)) # CHANGENEWLINEprint("\nTest Accuracy: %s: %.2f%%" % (model_ranging.metrics_names[1], accuracy * 100)) # CHANGENEWLINEprint("\nTest F1 Score: %s: %.2f" % (model_ranging.metrics_names[2], f1_score)) # CHANGENEWLINEprint("\nTest Precision: %s: %.2f%%" % (model_ranging.metrics_names[3], precision * 100)) # CHANGENEWLINEprint("\nTest Recall: %s: %.2f%%" % (model_ranging.metrics_names[4], recall * 100)) # CHANGENEWLINENEWLINE# Calculating total execution timeNEWLINEend_time = time.time() # Taking end time to calculate overall execution timeNEWLINEprint("\n Total Execution Time (Minutes): ")NEWLINEprint(((end_time - start_time) / 60))NEWLINENEWLINE#### SET PLOTTING PARAMETERS #########NEWLINEparams = {'legend.fontsize': 'xx-large',NEWLINE 'axes.labelsize': 'xx-large',NEWLINE 'axes.titlesize': 'xx-large',NEWLINE 'xtick.labelsize': 'xx-large',NEWLINE 'ytick.labelsize': 'xx-large'}NEWLINEplt.rcParams.update(params)NEWLINENEWLINENEWLINE# Show Accuracy CurvesNEWLINEfig = plt.figure()NEWLINE# plt.title('Training Performance')NEWLINEplt.plot(history.epoch, history.history['acc'], label='Training Accuracy', linewidth=2.0, c='b')NEWLINEplt.plot(history.epoch, history.history['val_acc'], label='Validation Accuracy', linewidth=2.0, c='r')NEWLINEplt.ylabel('Accuracy(%)')NEWLINEplt.xlabel('Epoch')NEWLINEplt.legend()NEWLINEplt.tight_layout()NEWLINEfig.savefig('/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/direction_ranging_acc_2D_CNN_Mapping.png') # save the figure to fileNEWLINEplt.close(fig)NEWLINENEWLINENEWLINE# plt.show()NEWLINENEWLINENEWLINEdef plot_confusion_matrix(cm, title='Confusion Matrix', cmap=plt.cm.YlGnBu, labels=[], normalize=False, filedest = ''):NEWLINE if normalize:NEWLINE cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]NEWLINE # print("Normalized confusion matrix")NEWLINE else:NEWLINE cm = cm.astype('int')NEWLINE # print('Confusion matrix, without normalization')NEWLINE plt.rcParams.update(params) # ADDEDNEWLINE fig = plt.figure(figsize=(12,12))NEWLINE plt.imshow(cm, interpolation='nearest', cmap=cmap)NEWLINE # plt.title(title)NEWLINE plt.colorbar()NEWLINE tick_marks = np.arange(len(labels))NEWLINE plt.xticks(tick_marks, labels, rotation=45)NEWLINE plt.yticks(tick_marks, labels)NEWLINE thresh = cm.max() / 2NEWLINE fmt = '.2f' if normalize else 'd'NEWLINE for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):NEWLINE # plt.text(j, i,"{:,}".format(cm[i, j]),NEWLINE plt.text(j, i, format(cm[i, j], fmt),NEWLINE horizontalalignment="center", fontsize="xx-large",NEWLINE color="white" if cm[i, j] > thresh else "black")NEWLINENEWLINE plt.ylabel('True label')NEWLINE plt.xlabel('Predicted label')NEWLINE # fig, ax = plt.subplots(nrows=1, ncols=1) # create figure & 1 axisNEWLINE # ax.plot([0, 1, 2], [10, 20, 3])NEWLINE plt.tight_layout()NEWLINE fig.savefig(filedest) # save the figure to fileNEWLINE plt.close(fig)NEWLINENEWLINENEWLINE# plt.show()NEWLINENEWLINENEWLINENEWLINE# Plot confusion matrixNEWLINEtest_Y_hat = model_ranging.predict(xtest_ranging, batch_size=batch_size)NEWLINEconf = np.zeros([len(classes), len(classes)])NEWLINEconfnorm = np.zeros([len(classes), len(classes)])NEWLINEfor i in range(0, xtest_ranging.shape[0]):NEWLINE j = list(ytest_ranging_one_hot[i, :]).index(1)NEWLINE k = int(np.argmax(test_Y_hat[i, :]))NEWLINE conf[j, k] = conf[j, k] + 1NEWLINEplot_confusion_matrix(conf, labels=classes, normalize=False, filedest='/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/direction_ranging_conf_mat_2D_CNN_Mapping.png')NEWLINENEWLINENEWLINE#############################################################################################################################NEWLINE######## #######NEWLINE######## HIERARCHICAL TRAINING- SECOND STEP #######NEWLINE######## CLASSIFYING THE DATA BASED ON POSES OF TRANSMITER ANTENNA #######NEWLINE######## PREDICTING REALTIVE POSES OF TRANSMITER ANTENNA #######NEWLINE######## DISTANCE: 5FT #######NEWLINE#############################################################################################################################NEWLINENEWLINENEWLINE#################### NORMALIZE THE X DATA #######################NEWLINENEWLINENEWLINEstandard = preprocessing.StandardScaler().fit(xdata_5ft) # Normalize the data with zero mean and unit variance for each columnNEWLINExdata_5ft = standard.transform(xdata_5ft)NEWLINENEWLINEprint("############## STARTING THE TRAINING TO PREDICT THE POSES OF TRANSMITTER ANTENNA WITH 5 FT DISTANCE FROM RECEIVER ##########################")NEWLINENEWLINENEWLINENEWLINE############### SEPARATING TRAIN AND TEST DATA #######################NEWLINENEWLINExtrain_5ft, xtest_5ft, ytrain_5ft, ytest_5ft = train_test_split(xdata_5ft, ydata_5ft, test_size=0.2, shuffle = True, random_state=42) # Randomly shuffling and 80/20 is train/test sizeNEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_5ft.shape, xtest_5ft.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_5ft.shape, ytest_5ft.shape)NEWLINENEWLINE# RESHAPING THE DATA FROM 2 DIMENSIONAL TO 4 DIMENSIONAL SHAPE - NEEDED TO APPLY TO USE 2D-CONVOLUTIONNEWLINE# reshape to be [samples][width][height][channels]NEWLINExtrain_5ft = xtrain_5ft.reshape((xtrain_5ft.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINExtest_5ft = xtest_5ft.reshape((xtest_5ft.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINENEWLINENEWLINEnum_classes = 12 # TOTAL NUMBER OF RANGESNEWLINENEWLINENEWLINENEWLINE# Convert labels to categorical one-hot encodingNEWLINEytrain_5ft_one_hot = to_categorical(ytrain_5ft, num_classes=num_classes) # DEFINE THE NUMBER OF TOTAL CLASSES IN LABELNEWLINEytest_5ft_one_hot = to_categorical(ytest_5ft, num_classes=num_classes)NEWLINENEWLINENEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_5ft.shape, xtest_5ft.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_5ft_one_hot.shape, ytest_5ft_one_hot.shape)NEWLINENEWLINE############################################################NEWLINE# #NEWLINE######## Building a 2D Convolutional Neural Network #####NEWLINE# #NEWLINE############################################################NEWLINENEWLINEdr = 0.6 # dropout rate (%)NEWLINEbatch_size = 128 # Mini batch sizeNEWLINEnb_epoch = 100 # Number of Epoch (Give a higher number to get better accuracy)NEWLINENEWLINEclasses = ["0", "+30", "+60", "+90", "+120", "+150", "180", "-150", "-120", "-90", "-60", "-30"] # CHANGE LABELNEWLINEin_shp = list(xtrain_5ft.shape[1:]) # Input DimensionNEWLINEprint(in_shp)NEWLINE# model = models.Sequential()NEWLINEtimesteps=1NEWLINEdata_dim=xtrain_5ft.shape[1]NEWLINENEWLINENEWLINENEWLINE# print ("AFTER RESHAPE")NEWLINEytrain_5ft_one_hot = np.reshape(ytrain_5ft_one_hot, (ytrain_5ft_one_hot.shape[0], num_classes)) # Used in trainingNEWLINEytest_5ft_one_hot = np.reshape(ytest_5ft_one_hot, (ytest_5ft_one_hot.shape[0], num_classes)) # Used in trainingNEWLINENEWLINEstart_time = time.time() # Taking start time to calculate overall execution timeNEWLINENEWLINE# IMPLEMENTING THE TRANSFER LEARNINGNEWLINE#source_model = load_model(saved_file)NEWLINE# loading the previously saved modelNEWLINEsource_model = load_model(saved_file, custom_objects={NEWLINE "f1_m": f1_m,NEWLINE "precision_m": precision_m,NEWLINE "recall_m": recall_mNEWLINE })NEWLINENEWLINEmodel_pose = Sequential()NEWLINEfor layer in source_model.layers[:-1]: # go through until last layerNEWLINE model_pose.add(layer)NEWLINENEWLINENEWLINE# ADDING OUTPUT LAYERNEWLINEmodel_pose.add(Dense(num_classes, activation='softmax'))NEWLINENEWLINE# Compile modelNEWLINE# For a multi-class classification problemNEWLINEsgd = SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True)NEWLINEadam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)NEWLINENEWLINE# model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # Multiclass classification with rmspropNEWLINENEWLINE#model.compile(optimizer='sgd', loss='categorical_crossentropy',metrics=['acc', f1_m, precision_m, recall_m]) # Multiclass classification with rms adam optimizer # CHANGENEWLINENEWLINEmodel_pose.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc', f1_m, precision_m, recall_m])NEWLINENEWLINEmodel_pose.summary()NEWLINEfilepath = '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/5ft/direction_data_12_poses_2D_CNN_Mapping.wts.h5'NEWLINEprint("The dropout rate was: ")NEWLINEprint(dr)NEWLINENEWLINENEWLINE# Fit the modelNEWLINE# history= model.fit(xtrain, ytrain_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_data = (xtest, ytest_one_hot), callbacks = [keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'), keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINEhistory = model_pose.fit(xtrain_5ft, ytrain_5ft_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_split=0.1, callbacks=[NEWLINE keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'),NEWLINE keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINENEWLINENEWLINE# Evaluate the modelNEWLINEloss, accuracy, f1_score, precision, recall = model_pose.evaluate(xtest_5ft, ytest_5ft_one_hot, batch_size=batch_size) # CHANGENEWLINEprint("\nTest Loss: %s: %.2f%%" % (model_pose.metrics_names[0], loss * 100)) # CHANGENEWLINEprint("\nTest Accuracy: %s: %.2f%%" % (model_pose.metrics_names[1], accuracy * 100)) # CHANGENEWLINEprint("\nTest F1 Score: %s: %.2f" % (model_pose.metrics_names[2], f1_score)) # CHANGENEWLINEprint("\nTest Precision: %s: %.2f%%" % (model_pose.metrics_names[3], precision * 100)) # CHANGENEWLINEprint("\nTest Recall: %s: %.2f%%" % (model_pose.metrics_names[4], recall * 100)) # CHANGENEWLINENEWLINE# Calculating total execution timeNEWLINEend_time = time.time() # Taking end time to calculate overall execution timeNEWLINEprint("\n Total Execution Time (Minutes): ")NEWLINEprint(((end_time - start_time) / 60))NEWLINENEWLINE#### SET PLOTTING PARAMETERS #########NEWLINEparams = {'legend.fontsize': 'xx-large',NEWLINE 'axes.labelsize': 'xx-large',NEWLINE 'axes.titlesize': 'xx-large',NEWLINE 'xtick.labelsize': 'xx-large',NEWLINE 'ytick.labelsize': 'xx-large'}NEWLINEplt.rcParams.update(params)NEWLINENEWLINENEWLINE# Show Accuracy CurvesNEWLINEfig = plt.figure()NEWLINE# plt.title('Training Performance')NEWLINEplt.plot(history.epoch, history.history['acc'], label='Training Accuracy', linewidth=2.0, c='b')NEWLINEplt.plot(history.epoch, history.history['val_acc'], label='Validation Accuracy', linewidth=2.0, c='r')NEWLINEplt.ylabel('Accuracy(%)')NEWLINEplt.xlabel('Epoch')NEWLINEplt.legend()NEWLINEplt.tight_layout()NEWLINEfig.savefig('/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/5ft/direction_12_poses_acc_2D_CNN_Mapping.png') # save the figure to fileNEWLINEplt.close(fig)NEWLINENEWLINENEWLINE# plt.show()NEWLINENEWLINENEWLINE# Plot confusion matrixNEWLINEtest_Y_hat = model_pose.predict(xtest_5ft, batch_size=batch_size)NEWLINEconf = np.zeros([len(classes), len(classes)])NEWLINEconfnorm = np.zeros([len(classes), len(classes)])NEWLINEfor i in range(0, xtest_5ft.shape[0]):NEWLINE j = list(ytest_5ft_one_hot[i, :]).index(1)NEWLINE k = int(np.argmax(test_Y_hat[i, :]))NEWLINE conf[j, k] = conf[j, k] + 1NEWLINEplot_confusion_matrix(conf, labels=classes, normalize=False, filedest= '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/5ft/direction_12_poses_conf_mat_2D_CNN_Mapping.png')NEWLINENEWLINENEWLINE#############################################################################################################################NEWLINE######## #######NEWLINE######## HIERARCHICAL TRAINING- SECOND STEP #######NEWLINE######## CLASSIFYING THE DATA BASED ON POSES OF TRANSMITER ANTENNA #######NEWLINE######## PREDICTING REALTIVE POSES OF TRANSMITER ANTENNA #######NEWLINE######## DISTANCE: 10FT #######NEWLINE#############################################################################################################################NEWLINENEWLINENEWLINE#################### NORMALIZE THE X DATA #######################NEWLINENEWLINENEWLINEstandard = preprocessing.StandardScaler().fit(xdata_10ft) # Normalize the data with zero mean and unit variance for each columnNEWLINExdata_10ft = standard.transform(xdata_10ft)NEWLINENEWLINEprint("############## STARTING THE TRAINING TO PREDICT THE POSES OF TRANSMITTER ANTENNA WITH 10 FT DISTANCE FROM RECEIVER ##########################")NEWLINENEWLINENEWLINE############### SEPARATING TRAIN AND TEST DATA #######################NEWLINENEWLINExtrain_10ft, xtest_10ft, ytrain_10ft, ytest_10ft = train_test_split(xdata_10ft, ydata_10ft, test_size=0.2, shuffle = True, random_state=42) # Randomly shuffling and 80/20 is train/test sizeNEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_10ft.shape, xtest_10ft.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_10ft.shape, ytest_10ft.shape)NEWLINENEWLINE# RESHAPING THE DATA FROM 2 DIMENSIONAL TO 4 DIMENSIONAL SHAPE - NEEDED TO APPLY TO USE 2D-CONVOLUTIONNEWLINE# reshape to be [samples][width][height][channels]NEWLINExtrain_10ft = xtrain_10ft.reshape((xtrain_10ft.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINExtest_10ft = xtest_10ft.reshape((xtest_10ft.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINENEWLINENEWLINEnum_classes = 12 # TOTAL NUMBER OF RANGESNEWLINENEWLINENEWLINENEWLINE# Convert labels to categorical one-hot encodingNEWLINEytrain_10ft_one_hot = to_categorical(ytrain_10ft, num_classes=num_classes) # DEFINE THE NUMBER OF TOTAL CLASSES IN LABELNEWLINEytest_10ft_one_hot = to_categorical(ytest_10ft, num_classes=num_classes)NEWLINENEWLINENEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_10ft.shape, xtest_10ft.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_10ft_one_hot.shape, ytest_10ft_one_hot.shape)NEWLINENEWLINE############################################################NEWLINE# #NEWLINE######## Building a 2D Convolutional Neural Network #####NEWLINE# #NEWLINE############################################################NEWLINENEWLINEdr = 0.6 # dropout rate (%)NEWLINEbatch_size = 128 # Mini batch sizeNEWLINEnb_epoch = 100 # Number of Epoch (Give a higher number to get better accuracy)NEWLINENEWLINEclasses = ["0", "+30", "+60", "+90", "+120", "+150", "180", "-150", "-120", "-90", "-60", "-30"] # CHANGE LABELNEWLINEin_shp = list(xtrain_10ft.shape[1:]) # Input DimensionNEWLINEprint(in_shp)NEWLINE# model = models.Sequential()NEWLINEtimesteps=1NEWLINEdata_dim=xtrain_10ft.shape[1]NEWLINENEWLINENEWLINENEWLINE# print ("AFTER RESHAPE")NEWLINEytrain_10ft_one_hot = np.reshape(ytrain_10ft_one_hot, (ytrain_10ft_one_hot.shape[0], num_classes)) # Used in trainingNEWLINEytest_10ft_one_hot = np.reshape(ytest_10ft_one_hot, (ytest_10ft_one_hot.shape[0], num_classes)) # Used in trainingNEWLINENEWLINEstart_time = time.time() # Taking start time to calculate overall execution timeNEWLINENEWLINE# IMPLEMENTING THE TRANSFER LEARNINGNEWLINE#source_model = load_model(saved_file)NEWLINE# loading the previously saved modelNEWLINEsource_model = load_model(saved_file, custom_objects={NEWLINE "f1_m": f1_m,NEWLINE "precision_m": precision_m,NEWLINE "recall_m": recall_mNEWLINE })NEWLINENEWLINEmodel_pose = Sequential()NEWLINEfor layer in source_model.layers[:-1]: # go through until last layerNEWLINE model_pose.add(layer)NEWLINENEWLINENEWLINE# ADDING OUTPUT LAYERNEWLINEmodel_pose.add(Dense(num_classes, activation='softmax'))NEWLINENEWLINE# Compile modelNEWLINE# For a multi-class classification problemNEWLINEsgd = SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True)NEWLINEadam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)NEWLINENEWLINE# model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # Multiclass classification with rmspropNEWLINENEWLINE#model.compile(optimizer='sgd', loss='categorical_crossentropy',metrics=['acc', f1_m, precision_m, recall_m]) # Multiclass classification with rms adam optimizer # CHANGENEWLINENEWLINEmodel_pose.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc', f1_m, precision_m, recall_m])NEWLINENEWLINEmodel_pose.summary()NEWLINEfilepath = '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/10ft/direction_data_12_poses_2D_CNN_Mapping.wts.h5'NEWLINEprint("The dropout rate was: ")NEWLINEprint(dr)NEWLINENEWLINENEWLINE# Fit the modelNEWLINE# history= model.fit(xtrain, ytrain_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_data = (xtest, ytest_one_hot), callbacks = [keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'), keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINEhistory = model_pose.fit(xtrain_10ft, ytrain_10ft_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_split=0.1, callbacks=[NEWLINE keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'),NEWLINE keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINENEWLINENEWLINE# Evaluate the modelNEWLINEloss, accuracy, f1_score, precision, recall = model_pose.evaluate(xtest_10ft, ytest_10ft_one_hot, batch_size=batch_size) # CHANGENEWLINEprint("\nTest Loss: %s: %.2f%%" % (model_pose.metrics_names[0], loss * 100)) # CHANGENEWLINEprint("\nTest Accuracy: %s: %.2f%%" % (model_pose.metrics_names[1], accuracy * 100)) # CHANGENEWLINEprint("\nTest F1 Score: %s: %.2f" % (model_pose.metrics_names[2], f1_score)) # CHANGENEWLINEprint("\nTest Precision: %s: %.2f%%" % (model_pose.metrics_names[3], precision * 100)) # CHANGENEWLINEprint("\nTest Recall: %s: %.2f%%" % (model_pose.metrics_names[4], recall * 100)) # CHANGENEWLINENEWLINE# Calculating total execution timeNEWLINEend_time = time.time() # Taking end time to calculate overall execution timeNEWLINEprint("\n Total Execution Time (Minutes): ")NEWLINEprint(((end_time - start_time) / 60))NEWLINENEWLINE#### SET PLOTTING PARAMETERS #########NEWLINEparams = {'legend.fontsize': 'xx-large',NEWLINE 'axes.labelsize': 'xx-large',NEWLINE 'axes.titlesize': 'xx-large',NEWLINE 'xtick.labelsize': 'xx-large',NEWLINE 'ytick.labelsize': 'xx-large'}NEWLINEplt.rcParams.update(params)NEWLINENEWLINENEWLINE# Show Accuracy CurvesNEWLINEfig = plt.figure()NEWLINE# plt.title('Training Performance')NEWLINEplt.plot(history.epoch, history.history['acc'], label='Training Accuracy', linewidth=2.0, c='b')NEWLINEplt.plot(history.epoch, history.history['val_acc'], label='Validation Accuracy', linewidth=2.0, c='r')NEWLINEplt.ylabel('Accuracy(%)')NEWLINEplt.xlabel('Epoch')NEWLINEplt.legend()NEWLINEplt.tight_layout()NEWLINEfig.savefig('/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/10ft/direction_12_poses_acc_2D_CNN_Mapping.png') # save the figure to fileNEWLINEplt.close(fig)NEWLINENEWLINENEWLINE# plt.show()NEWLINENEWLINENEWLINE# Plot confusion matrixNEWLINEtest_Y_hat = model_pose.predict(xtest_10ft, batch_size=batch_size)NEWLINEconf = np.zeros([len(classes), len(classes)])NEWLINEconfnorm = np.zeros([len(classes), len(classes)])NEWLINEfor i in range(0, xtest_10ft.shape[0]):NEWLINE j = list(ytest_10ft_one_hot[i, :]).index(1)NEWLINE k = int(np.argmax(test_Y_hat[i, :]))NEWLINE conf[j, k] = conf[j, k] + 1NEWLINEplot_confusion_matrix(conf, labels=classes, normalize=False, filedest= '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/10ft/direction_12_poses_conf_mat_2D_CNN_Mapping.png')NEWLINENEWLINENEWLINE#############################################################################################################################NEWLINE######## #######NEWLINE######## HIERARCHICAL TRAINING- SECOND STEP #######NEWLINE######## CLASSIFYING THE DATA BASED ON POSES OF TRANSMITER ANTENNA #######NEWLINE######## PREDICTING REALTIVE POSES OF TRANSMITER ANTENNA #######NEWLINE######## DISTANCE: 15FT #######NEWLINE#############################################################################################################################NEWLINENEWLINENEWLINE#################### NORMALIZE THE X DATA #######################NEWLINENEWLINENEWLINEstandard = preprocessing.StandardScaler().fit(xdata_15ft) # Normalize the data with zero mean and unit variance for each columnNEWLINExdata_15ft = standard.transform(xdata_15ft)NEWLINENEWLINEprint("############## STARTING THE TRAINING TO PREDICT THE POSES OF TRANSMITTER ANTENNA WITH 15 FT DISTANCE FROM RECEIVER ##########################")NEWLINENEWLINENEWLINE############### SEPARATING TRAIN AND TEST DATA #######################NEWLINENEWLINExtrain_15ft, xtest_15ft, ytrain_15ft, ytest_15ft = train_test_split(xdata_15ft, ydata_15ft, test_size=0.2, shuffle = True, random_state=42) # Randomly shuffling and 80/20 is train/test sizeNEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_5ft.shape, xtest_5ft.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_5ft.shape, ytest_5ft.shape)NEWLINENEWLINE# RESHAPING THE DATA FROM 2 DIMENSIONAL TO 4 DIMENSIONAL SHAPE - NEEDED TO APPLY TO USE 2D-CONVOLUTIONNEWLINE# reshape to be [samples][width][height][channels]NEWLINExtrain_15ft = xtrain_15ft.reshape((xtrain_15ft.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINExtest_15ft = xtest_15ft.reshape((xtest_15ft.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINENEWLINENEWLINEnum_classes = 12 # TOTAL NUMBER OF RANGESNEWLINENEWLINENEWLINENEWLINE# Convert labels to categorical one-hot encodingNEWLINEytrain_15ft_one_hot = to_categorical(ytrain_15ft, num_classes=num_classes) # DEFINE THE NUMBER OF TOTAL CLASSES IN LABELNEWLINEytest_15ft_one_hot = to_categorical(ytest_15ft, num_classes=num_classes)NEWLINENEWLINENEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_15ft.shape, xtest_15ft.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_15ft_one_hot.shape, ytest_15ft_one_hot.shape)NEWLINENEWLINE############################################################NEWLINE# #NEWLINE######## Building a 2D Convolutional Neural Network #####NEWLINE# #NEWLINE############################################################NEWLINENEWLINEdr = 0.6 # dropout rate (%)NEWLINEbatch_size = 128 # Mini batch sizeNEWLINEnb_epoch = 100 # Number of Epoch (Give a higher number to get better accuracy)NEWLINENEWLINEclasses = ["0", "+30", "+60", "+90", "+120", "+150", "180", "-150", "-120", "-90", "-60", "-30"] # CHANGE LABELNEWLINEin_shp = list(xtrain_15ft.shape[1:]) # Input DimensionNEWLINEprint(in_shp)NEWLINE# model = models.Sequential()NEWLINEtimesteps=1NEWLINEdata_dim=xtrain_15ft.shape[1]NEWLINENEWLINENEWLINENEWLINE# print ("AFTER RESHAPE")NEWLINEytrain_15ft_one_hot = np.reshape(ytrain_15ft_one_hot, (ytrain_15ft_one_hot.shape[0], num_classes)) # Used in trainingNEWLINEytest_15ft_one_hot = np.reshape(ytest_15ft_one_hot, (ytest_15ft_one_hot.shape[0], num_classes)) # Used in trainingNEWLINENEWLINEstart_time = time.time() # Taking start time to calculate overall execution timeNEWLINENEWLINE# IMPLEMENTING THE TRANSFER LEARNINGNEWLINE#source_model = load_model(saved_file)NEWLINE# loading the previously saved modelNEWLINEsource_model = load_model(saved_file, custom_objects={NEWLINE "f1_m": f1_m,NEWLINE "precision_m": precision_m,NEWLINE "recall_m": recall_mNEWLINE })NEWLINENEWLINEmodel_pose = Sequential()NEWLINEfor layer in source_model.layers[:-1]: # go through until last layerNEWLINE model_pose.add(layer)NEWLINENEWLINENEWLINE# ADDING OUTPUT LAYERNEWLINEmodel_pose.add(Dense(num_classes, activation='softmax'))NEWLINENEWLINE# Compile modelNEWLINE# For a multi-class classification problemNEWLINEsgd = SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True)NEWLINEadam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)NEWLINENEWLINE# model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # Multiclass classification with rmspropNEWLINENEWLINE#model.compile(optimizer='sgd', loss='categorical_crossentropy',metrics=['acc', f1_m, precision_m, recall_m]) # Multiclass classification with rms adam optimizer # CHANGENEWLINENEWLINEmodel_pose.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc', f1_m, precision_m, recall_m])NEWLINENEWLINEmodel_pose.summary()NEWLINEfilepath = '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/15ft/direction_data_12_poses_2D_CNN_Mapping.wts.h5'NEWLINEprint("The dropout rate was: ")NEWLINEprint(dr)NEWLINENEWLINENEWLINE# Fit the modelNEWLINE# history= model.fit(xtrain, ytrain_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_data = (xtest, ytest_one_hot), callbacks = [keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'), keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINEhistory = model_pose.fit(xtrain_15ft, ytrain_15ft_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_split=0.1, callbacks=[NEWLINE keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'),NEWLINE keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINENEWLINENEWLINE# Evaluate the modelNEWLINEloss, accuracy, f1_score, precision, recall = model_pose.evaluate(xtest_15ft, ytest_15ft_one_hot, batch_size=batch_size) # CHANGENEWLINEprint("\nTest Loss: %s: %.2f%%" % (model_pose.metrics_names[0], loss * 100)) # CHANGENEWLINEprint("\nTest Accuracy: %s: %.2f%%" % (model_pose.metrics_names[1], accuracy * 100)) # CHANGENEWLINEprint("\nTest F1 Score: %s: %.2f" % (model_pose.metrics_names[2], f1_score)) # CHANGENEWLINEprint("\nTest Precision: %s: %.2f%%" % (model_pose.metrics_names[3], precision * 100)) # CHANGENEWLINEprint("\nTest Recall: %s: %.2f%%" % (model_pose.metrics_names[4], recall * 100)) # CHANGENEWLINENEWLINE# Calculating total execution timeNEWLINEend_time = time.time() # Taking end time to calculate overall execution timeNEWLINEprint("\n Total Execution Time (Minutes): ")NEWLINEprint(((end_time - start_time) / 60))NEWLINENEWLINE#### SET PLOTTING PARAMETERS #########NEWLINEparams = {'legend.fontsize': 'xx-large',NEWLINE 'axes.labelsize': 'xx-large',NEWLINE 'axes.titlesize': 'xx-large',NEWLINE 'xtick.labelsize': 'xx-large',NEWLINE 'ytick.labelsize': 'xx-large'}NEWLINEplt.rcParams.update(params)NEWLINENEWLINENEWLINE# Show Accuracy CurvesNEWLINEfig = plt.figure()NEWLINE# plt.title('Training Performance')NEWLINEplt.plot(history.epoch, history.history['acc'], label='Training Accuracy', linewidth=2.0, c='b')NEWLINEplt.plot(history.epoch, history.history['val_acc'], label='Validation Accuracy', linewidth=2.0, c='r')NEWLINEplt.ylabel('Accuracy(%)')NEWLINEplt.xlabel('Epoch')NEWLINEplt.legend()NEWLINEplt.tight_layout()NEWLINEfig.savefig('/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/15ft/direction_12_poses_acc_2D_CNN_Mapping.png') # save the figure to fileNEWLINEplt.close(fig)NEWLINENEWLINENEWLINE# plt.show()NEWLINENEWLINENEWLINE# Plot confusion matrixNEWLINEtest_Y_hat = model_pose.predict(xtest_15ft, batch_size=batch_size)NEWLINEconf = np.zeros([len(classes), len(classes)])NEWLINEconfnorm = np.zeros([len(classes), len(classes)])NEWLINEfor i in range(0, xtest_15ft.shape[0]):NEWLINE j = list(ytest_15ft_one_hot[i, :]).index(1)NEWLINE k = int(np.argmax(test_Y_hat[i, :]))NEWLINE conf[j, k] = conf[j, k] + 1NEWLINEplot_confusion_matrix(conf, labels=classes, normalize=False, filedest= '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/15ft/direction_12_poses_conf_mat_2D_CNN_Mapping.png')NEWLINE # TRANSMITTER HAS A DIRECTIONAL ANTENNA - POINTED IN 12 DIFFERENT POSESNEWLINE# RECEIVER HAS AN OMNI DIRECTIONAL ANTENNANEWLINE# DISTANCE BETWEEN RECEIVER AND TRANSMITTER - (5, 10, 15) FEETNEWLINE# IMPEMENTING HIERARCHICAL MACHINE LEARNINGNEWLINE# IMPLEMENTING TRANSFER LEARNINGNEWLINE# DATA COLLECTED IN INDOOR ENVIRONMENTNEWLINENEWLINE#############################################################NEWLINE# Pose Estimation and Ranging the RF Transmitter #NEWLINE# Neural Network for Direction Finding Data 2020 #NEWLINE# Author: Debashri Roy #NEWLINE#############################################################NEWLINENEWLINE############ IMPORTING NECESSARY PACKAGES ################NEWLINEimport numpy as np # Package for numerical computationNEWLINEnp.set_printoptions(threshold=np.inf) # To print each elementsNEWLINEimport time # Package is for computing execution timeNEWLINEimport sys # Package to get command line argumentsNEWLINEimport tensorflow as tfNEWLINEfrom sklearn.model_selection import train_test_splitNEWLINEfrom array import arrayNEWLINENEWLINE# by setting env variables before Keras import you can set up which backendNEWLINEimport os,randomNEWLINE#os.environ["KERAS_BACKEND"] = "theano"NEWLINEos.environ["KERAS_BACKEND"] = "tensorflow"NEWLINEos.environ["THEANO_FLAGS"] = "device=cuda0, dnn.enabled=False"NEWLINEimport theanoNEWLINE#theano.config.mode = ""NEWLINENEWLINENEWLINENEWLINENEWLINEimport theano as thNEWLINEimport theano.tensor as TNEWLINEfrom keras.utils import np_utilsNEWLINEimport keras.models as modelsNEWLINEfrom keras.models import SequentialNEWLINEfrom keras.layers.core import Reshape,Dense,Dropout,Activation,FlattenNEWLINEfrom keras.layers import EmbeddingNEWLINEfrom keras.layers.noise import GaussianNoiseNEWLINEfrom keras.layers.convolutional import Conv2D, Conv1D, Convolution2D, MaxPooling2D, ZeroPadding2D, Convolution1DNEWLINEfrom keras.regularizers import *NEWLINEfrom keras.optimizers import adam, Nadam, AdadeltaNEWLINEfrom keras.optimizers import Adam, RMSprop, AdagradNEWLINEfrom keras.layers.convolutional_recurrent import ConvLSTM2DNEWLINEfrom keras.optimizers import rmspropNEWLINEfrom keras.callbacks import ReduceLROnPlateau, ModelCheckpointNEWLINE#from keras.regularizers import l2, activity_l2NEWLINEfrom sklearn import preprocessingNEWLINEfrom sklearn.preprocessing import StandardScalerNEWLINEfrom keras.layers.advanced_activations import LeakyReLU, PReLUNEWLINE# import BatchNormalizationNEWLINEfrom keras.layers.normalization import BatchNormalizationNEWLINEfrom keras.layers import GRU, RNN, SimpleRNN, LSTM, GRUCell, SimpleRNNCell, LSTMCellNEWLINENEWLINEfrom sklearn.metrics import classification_reportNEWLINEfrom sklearn.metrics import confusion_matrixNEWLINENEWLINEfrom keras.utils.np_utils import to_categoricalNEWLINEfrom keras.optimizers import SGDNEWLINENEWLINEimport matplotlibNEWLINE#matplotlib.use('TkAgg')NEWLINEmatplotlib.use('Agg')NEWLINEimport matplotlib.pyplot as pltNEWLINE#import seaborn as snsNEWLINEimport kerasNEWLINEimport itertoolsNEWLINEimport scipyNEWLINENEWLINEfrom keras.models import load_modelNEWLINENEWLINE########## FUNCTIONS TO CALCULATE F SCORE OF THE MODEL ###############NEWLINEfrom keras import backend as KNEWLINEdef recall_m(y_true, y_pred):NEWLINE true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))NEWLINE possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))NEWLINE recall = true_positives / (possible_positives + K.epsilon())NEWLINE return recallNEWLINENEWLINENEWLINEdef precision_m(y_true, y_pred):NEWLINE true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))NEWLINE predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))NEWLINE precision = true_positives / (predicted_positives + K.epsilon())NEWLINE return precisionNEWLINENEWLINENEWLINEdef f1_m(y_true, y_pred):NEWLINE precision = precision_m(y_true, y_pred)NEWLINE recall = recall_m(y_true, y_pred)NEWLINE return 2 * ((precision * recall) / (precision + recall + K.epsilon()))NEWLINE######################################################################NEWLINENEWLINENEWLINE################# THE WEIGHT MATRIX #################3NEWLINEW = np.matrix([[np.cos(1*(np.pi/8)), np.sin(1*(np.pi/8))],NEWLINE[np.cos(2*(np.pi/8)), np.sin(2*(np.pi/8))],NEWLINE[np.cos(3*(np.pi/8)), np.sin(3*(np.pi/8))],NEWLINE[np.cos(4*(np.pi/8)), np.sin(4*(np.pi/8))],NEWLINE[np.cos(5*(np.pi/8)), np.sin(5*(np.pi/8))],NEWLINE[np.cos(6*(np.pi/8)), np.sin(6*(np.pi/8))],NEWLINE[np.cos(7*(np.pi/8)), np.sin(7*(np.pi/8))],NEWLINE[np.cos(8*(np.pi/8)), np.sin(8*(np.pi/8))]]NEWLINE)NEWLINENEWLINE# W = np.matrix([[np.cos(4*(np.pi/8)), np.sin(4*(np.pi/8))],NEWLINE# [np.cos(4*(np.pi/8)), np.sin(4*(np.pi/8))],NEWLINE# [np.cos(4*(np.pi/8)), np.sin(4*(np.pi/8))],NEWLINE# [np.cos(4*(np.pi/8)), np.sin(4*(np.pi/8))],NEWLINE# [np.cos(0*(np.pi/8)), np.sin(0*(np.pi/8))],NEWLINE# [np.cos(0*(np.pi/8)), np.sin(0*(np.pi/8))],NEWLINE# [np.cos(0*(np.pi/8)), np.sin(0*(np.pi/8))],NEWLINE# [np.cos(0*(np.pi/8)), np.sin(0*(np.pi/8))]]NEWLINE# )NEWLINENEWLINEprint(W)NEWLINENEWLINE# variablesNEWLINEdtype_all= scipy.dtype([('raw-iq', scipy.complex64)])NEWLINENEWLINENEWLINEsample_size = 1024 # CHANGE AND EXPERIMENT -512NEWLINEno_of_samples = 4000 # CHANGE AND EXPERIMENT - 4000NEWLINEno_of_features= 8 # CHANGE AND EXPERIMENTNEWLINEnumber_of_data_to_read = sample_size * no_of_samplesNEWLINENEWLINE#######################################################################################NEWLINENEWLINE#############################################################################################################################NEWLINE######## #######NEWLINE######## READING THE 5FT DATA #######NEWLINE######## #######NEWLINE#############################################################################################################################NEWLINENEWLINEdata_file_loc1 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/0_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER DIRECTLY POINTING TO THE RECEIVERNEWLINEdata_file_loc2 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/+30_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 30 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc3 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/+60_5ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS 60 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc4 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/+90_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 90 DEGREE LEFT TO THE RECEIVERNEWLINENEWLINEdata_file_loc5 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/+120_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 120 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc6 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/+150_5ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS 150 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc7 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/180_5ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS DIRECTLY POINTED AWAY FROM THE RECEIVERNEWLINEdata_file_loc8 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/-150_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 30 DEGREE RIGHT TO THE RECEIVERNEWLINENEWLINEdata_file_loc9 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/-120_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 60 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc10 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/-90_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 90 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc11 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/-60_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 120 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc12 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/5ft/-30_5ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 150 DEGREE RIGHT TO THE RECEIVERNEWLINENEWLINENEWLINENEWLINEiqdata_loc1 = scipy.fromfile(open(data_file_loc1), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc2 = scipy.fromfile(open(data_file_loc2), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc3 = scipy.fromfile(open(data_file_loc3), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc4 = scipy.fromfile(open(data_file_loc4), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINEiqdata_loc5 = scipy.fromfile(open(data_file_loc5), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc6 = scipy.fromfile(open(data_file_loc6), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc7 = scipy.fromfile(open(data_file_loc7), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc8 = scipy.fromfile(open(data_file_loc8), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINENEWLINEiqdata_loc9 = scipy.fromfile(open(data_file_loc9), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc10 = scipy.fromfile(open(data_file_loc10), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc11 = scipy.fromfile(open(data_file_loc11), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc12 = scipy.fromfile(open(data_file_loc12), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINENEWLINENEWLINE# PREPARING THE DATA WITHOUT TIME INFORMATIONNEWLINEno_of_data_loc1 = iqdata_loc1.shape[0]NEWLINEno_of_data_loc2 = iqdata_loc2.shape[0]NEWLINEno_of_data_loc3 = iqdata_loc3.shape[0]NEWLINEno_of_data_loc4 = iqdata_loc4.shape[0]NEWLINENEWLINEno_of_data_loc5 = iqdata_loc5.shape[0]NEWLINEno_of_data_loc6 = iqdata_loc6.shape[0]NEWLINEno_of_data_loc7 = iqdata_loc7.shape[0]NEWLINEno_of_data_loc8 = iqdata_loc8.shape[0]NEWLINENEWLINEno_of_data_loc9 = iqdata_loc9.shape[0]NEWLINEno_of_data_loc10 = iqdata_loc10.shape[0]NEWLINEno_of_data_loc11 = iqdata_loc11.shape[0]NEWLINEno_of_data_loc12 = iqdata_loc12.shape[0]NEWLINENEWLINENEWLINENEWLINE################################################################################################################NEWLINE# CONCATINATING THE I AND Q VALUES VERTICALLY OF (I, Q) SAMPLE. -- note the axis argument is set to 1 (means vertical stacking)NEWLINE# SIMULATNEOUSLY MULTIPLYING WITH THE WEIGHT MATRIX - TO REFLECT THE MULTI-ANGULAR PROJECTIONNEWLINENEWLINExdata_loc1= np.concatenate([iqdata_loc1['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc1['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc1 = np.matmul(xdata_loc1, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc2= np.concatenate([iqdata_loc2['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc2['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc2 = np.matmul(xdata_loc2, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc3= np.concatenate([iqdata_loc3['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc3['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc3 = np.matmul(xdata_loc3, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc4= np.concatenate([iqdata_loc4['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc4['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc4 = np.matmul(xdata_loc4, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINExdata_loc5= np.concatenate([iqdata_loc5['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc5['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc5 = np.matmul(xdata_loc5, np.transpose(W))NEWLINENEWLINExdata_loc6= np.concatenate([iqdata_loc6['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc6['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc6 = np.matmul(xdata_loc6, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc7= np.concatenate([iqdata_loc7['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc7['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc7 = np.matmul(xdata_loc7, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc8= np.concatenate([iqdata_loc8['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc8['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc8 = np.matmul(xdata_loc8, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINExdata_loc9= np.concatenate([iqdata_loc9['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc9['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc9 = np.matmul(xdata_loc9, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc10= np.concatenate([iqdata_loc10['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc10['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc10 = np.matmul(xdata_loc10, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc11= np.concatenate([iqdata_loc11['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc11['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc11 = np.matmul(xdata_loc11, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc12= np.concatenate([iqdata_loc12['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc12['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc12 = np.matmul(xdata_loc12, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINE# RESHAPING THE XDATANEWLINExdata_loc1= xdata_loc1.T.reshape(no_of_data_loc1//(sample_size), sample_size*no_of_features)NEWLINExdata_loc2 = xdata_loc2.T.reshape(no_of_data_loc2//(sample_size), sample_size*no_of_features)NEWLINExdata_loc3 = xdata_loc3.T.reshape(no_of_data_loc3//(sample_size), sample_size*no_of_features)NEWLINExdata_loc4 = xdata_loc4.T.reshape(no_of_data_loc4//(sample_size), sample_size*no_of_features)NEWLINENEWLINExdata_loc5= xdata_loc5.T.reshape(no_of_data_loc5//(sample_size), sample_size*no_of_features)NEWLINExdata_loc6 = xdata_loc6.T.reshape(no_of_data_loc6//(sample_size), sample_size*no_of_features)NEWLINExdata_loc7 = xdata_loc7.T.reshape(no_of_data_loc7//(sample_size), sample_size*no_of_features)NEWLINExdata_loc8 = xdata_loc8.T.reshape(no_of_data_loc8//(sample_size), sample_size*no_of_features)NEWLINENEWLINExdata_loc9= xdata_loc9.T.reshape(no_of_data_loc9//(sample_size), sample_size*no_of_features)NEWLINExdata_loc10 = xdata_loc10.T.reshape(no_of_data_loc10//(sample_size), sample_size*no_of_features)NEWLINExdata_loc11 = xdata_loc11.T.reshape(no_of_data_loc11//(sample_size), sample_size*no_of_features)NEWLINExdata_loc12 = xdata_loc12.T.reshape(no_of_data_loc12//(sample_size), sample_size*no_of_features)NEWLINENEWLINENEWLINENEWLINE#CONCATINATING THE DIFFERENT POSE DATA HORIZONTALLY (ROWWISE)NEWLINExdata = np.concatenate([xdata_loc1, xdata_loc2, xdata_loc3, xdata_loc4, xdata_loc5, xdata_loc6, xdata_loc7, xdata_loc8, xdata_loc9, xdata_loc10, xdata_loc11, xdata_loc12], axis=0)NEWLINENEWLINENEWLINENEWLINE# CREATING LABEL FOR THE DATASETSNEWLINEydata_loc1 = np.full(xdata_loc1.shape[0], 0, dtype=int)NEWLINEydata_loc2 = np.full(xdata_loc2.shape[0], 1, dtype=int)NEWLINEydata_loc3 = np.full(xdata_loc3.shape[0], 2, dtype=int)NEWLINEydata_loc4 = np.full(xdata_loc4.shape[0], 3, dtype=int)NEWLINENEWLINEydata_loc5 = np.full(xdata_loc5.shape[0], 4, dtype=int)NEWLINEydata_loc6 = np.full(xdata_loc6.shape[0], 5, dtype=int)NEWLINEydata_loc7 = np.full(xdata_loc7.shape[0], 6, dtype=int)NEWLINEydata_loc8 = np.full(xdata_loc8.shape[0], 7, dtype=int)NEWLINENEWLINEydata_loc9 = np.full(xdata_loc9.shape[0], 8, dtype=int)NEWLINEydata_loc10 = np.full(xdata_loc10.shape[0], 9, dtype=int)NEWLINEydata_loc11 = np.full(xdata_loc11.shape[0], 10, dtype=int)NEWLINEydata_loc12 = np.full(xdata_loc12.shape[0], 11, dtype=int)NEWLINENEWLINE#CONCATINATING THE DIFFERENT POSE LABELS HORIZONTALLY (ROWWISE)NEWLINEydata = np.concatenate([ydata_loc1, ydata_loc2, ydata_loc3, ydata_loc4, ydata_loc5, ydata_loc6, ydata_loc7, ydata_loc8, ydata_loc9, ydata_loc10, ydata_loc11, ydata_loc12], axis=0)NEWLINENEWLINENEWLINE# PREPROCESSING X AND Y DATANEWLINExdata =xdata.astype(np.float)NEWLINENEWLINEydata = ydata.astype(np.int).flatten()NEWLINENEWLINE# REMOVING THE NANSNEWLINExdata = np.nan_to_num(xdata)NEWLINENEWLINENEWLINE# ############## RANDOMLY SHUFFLING THE DATA ###################NEWLINE#NEWLINE# first concatinate - TO MAINTIAN THE XDATA AND YDATA MAPPINGNEWLINExydata = np.concatenate([xdata.reshape(xdata.shape[0], xdata.shape[1]), ydata.reshape(ydata.shape[0], 1)], axis=1)NEWLINENEWLINEnp.random.shuffle(xydata)NEWLINENEWLINEprint("Shape of XYDATA", xydata.shape)NEWLINENEWLINExdata_5ft, ydata_5ft = xydata[:,0:sample_size*no_of_features], xydata[:,((sample_size*no_of_features))] # THE LAST COLUMN IS THE YDATA # USE 2 INSTEAD OF 8 OF YOU DO NOT USE MULTI-ANGULAR PROJECTIONNEWLINENEWLINENEWLINE################################################################################################################################NEWLINENEWLINE#############################################################################################################################NEWLINE######## #######NEWLINE######## READING THE 10FT DATA #######NEWLINE######## #######NEWLINE#############################################################################################################################NEWLINENEWLINEdata_file_loc1 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/0_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER DIRECTLY POINTING TO THE RECEIVERNEWLINEdata_file_loc2 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/+30_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 30 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc3 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/+60_10ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS 60 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc4 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/+90_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 90 DEGREE LEFT TO THE RECEIVERNEWLINENEWLINEdata_file_loc5 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/+120_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 120 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc6 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/+150_10ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS 150 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc7 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/180_10ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS DIRECTLY POINTED AWAY FROM THE RECEIVERNEWLINEdata_file_loc8 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/-150_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 30 DEGREE RIGHT TO THE RECEIVERNEWLINENEWLINEdata_file_loc9 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/-120_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 60 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc10 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/-90_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 90 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc11 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/-60_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 120 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc12 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/10ft/-30_10ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 150 DEGREE RIGHT TO THE RECEIVERNEWLINENEWLINENEWLINENEWLINEiqdata_loc1 = scipy.fromfile(open(data_file_loc1), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc2 = scipy.fromfile(open(data_file_loc2), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc3 = scipy.fromfile(open(data_file_loc3), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc4 = scipy.fromfile(open(data_file_loc4), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINEiqdata_loc5 = scipy.fromfile(open(data_file_loc5), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc6 = scipy.fromfile(open(data_file_loc6), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc7 = scipy.fromfile(open(data_file_loc7), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc8 = scipy.fromfile(open(data_file_loc8), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINENEWLINEiqdata_loc9 = scipy.fromfile(open(data_file_loc9), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc10 = scipy.fromfile(open(data_file_loc10), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc11 = scipy.fromfile(open(data_file_loc11), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc12 = scipy.fromfile(open(data_file_loc12), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINENEWLINENEWLINE# PREPARING THE DATA WITHOUT TIME INFORMATIONNEWLINEno_of_data_loc1 = iqdata_loc1.shape[0]NEWLINEno_of_data_loc2 = iqdata_loc2.shape[0]NEWLINEno_of_data_loc3 = iqdata_loc3.shape[0]NEWLINEno_of_data_loc4 = iqdata_loc4.shape[0]NEWLINENEWLINEno_of_data_loc5 = iqdata_loc5.shape[0]NEWLINEno_of_data_loc6 = iqdata_loc6.shape[0]NEWLINEno_of_data_loc7 = iqdata_loc7.shape[0]NEWLINEno_of_data_loc8 = iqdata_loc8.shape[0]NEWLINENEWLINEno_of_data_loc9 = iqdata_loc9.shape[0]NEWLINEno_of_data_loc10 = iqdata_loc10.shape[0]NEWLINEno_of_data_loc11 = iqdata_loc11.shape[0]NEWLINEno_of_data_loc12 = iqdata_loc12.shape[0]NEWLINENEWLINENEWLINENEWLINE################################################################################################################NEWLINE# CONCATINATING THE I AND Q VALUES VERTICALLY OF (I, Q) SAMPLE. -- note the axis argument is set to 1 (means vertical stacking)NEWLINE# SIMULATNEOUSLY MULTIPLYING WITH THE WEIGHT MATRIX - TO REFLECT THE MULTI-ANGULAR PROJECTIONNEWLINENEWLINExdata_loc1= np.concatenate([iqdata_loc1['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc1['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc1 = np.matmul(xdata_loc1, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc2= np.concatenate([iqdata_loc2['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc2['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc2 = np.matmul(xdata_loc2, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc3= np.concatenate([iqdata_loc3['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc3['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc3 = np.matmul(xdata_loc3, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc4= np.concatenate([iqdata_loc4['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc4['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc4 = np.matmul(xdata_loc4, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINExdata_loc5= np.concatenate([iqdata_loc5['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc5['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc5 = np.matmul(xdata_loc5, np.transpose(W))NEWLINENEWLINExdata_loc6= np.concatenate([iqdata_loc6['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc6['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc6 = np.matmul(xdata_loc6, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc7= np.concatenate([iqdata_loc7['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc7['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc7 = np.matmul(xdata_loc7, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc8= np.concatenate([iqdata_loc8['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc8['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc8 = np.matmul(xdata_loc8, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINExdata_loc9= np.concatenate([iqdata_loc9['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc9['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc9 = np.matmul(xdata_loc9, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc10= np.concatenate([iqdata_loc10['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc10['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc10 = np.matmul(xdata_loc10, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc11= np.concatenate([iqdata_loc11['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc11['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc11 = np.matmul(xdata_loc11, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc12= np.concatenate([iqdata_loc12['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc12['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc12 = np.matmul(xdata_loc12, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINE# RESHAPING THE XDATANEWLINExdata_loc1= xdata_loc1.T.reshape(no_of_data_loc1//(sample_size), sample_size*no_of_features)NEWLINExdata_loc2 = xdata_loc2.T.reshape(no_of_data_loc2//(sample_size), sample_size*no_of_features)NEWLINExdata_loc3 = xdata_loc3.T.reshape(no_of_data_loc3//(sample_size), sample_size*no_of_features)NEWLINExdata_loc4 = xdata_loc4.T.reshape(no_of_data_loc4//(sample_size), sample_size*no_of_features)NEWLINENEWLINExdata_loc5= xdata_loc5.T.reshape(no_of_data_loc5//(sample_size), sample_size*no_of_features)NEWLINExdata_loc6 = xdata_loc6.T.reshape(no_of_data_loc6//(sample_size), sample_size*no_of_features)NEWLINExdata_loc7 = xdata_loc7.T.reshape(no_of_data_loc7//(sample_size), sample_size*no_of_features)NEWLINExdata_loc8 = xdata_loc8.T.reshape(no_of_data_loc8//(sample_size), sample_size*no_of_features)NEWLINENEWLINExdata_loc9= xdata_loc9.T.reshape(no_of_data_loc9//(sample_size), sample_size*no_of_features)NEWLINExdata_loc10 = xdata_loc10.T.reshape(no_of_data_loc10//(sample_size), sample_size*no_of_features)NEWLINExdata_loc11 = xdata_loc11.T.reshape(no_of_data_loc11//(sample_size), sample_size*no_of_features)NEWLINExdata_loc12 = xdata_loc12.T.reshape(no_of_data_loc12//(sample_size), sample_size*no_of_features)NEWLINENEWLINENEWLINENEWLINE#CONCATINATING THE DIFFERENT POSE DATA HORIZONTALLY (ROWWISE)NEWLINExdata = np.concatenate([xdata_loc1, xdata_loc2, xdata_loc3, xdata_loc4, xdata_loc5, xdata_loc6, xdata_loc7, xdata_loc8, xdata_loc9, xdata_loc10, xdata_loc11, xdata_loc12], axis=0)NEWLINENEWLINENEWLINENEWLINE# CREATING LABEL FOR THE DATASETSNEWLINEydata_loc1 = np.full(xdata_loc1.shape[0], 0, dtype=int)NEWLINEydata_loc2 = np.full(xdata_loc2.shape[0], 1, dtype=int)NEWLINEydata_loc3 = np.full(xdata_loc3.shape[0], 2, dtype=int)NEWLINEydata_loc4 = np.full(xdata_loc4.shape[0], 3, dtype=int)NEWLINENEWLINEydata_loc5 = np.full(xdata_loc5.shape[0], 4, dtype=int)NEWLINEydata_loc6 = np.full(xdata_loc6.shape[0], 5, dtype=int)NEWLINEydata_loc7 = np.full(xdata_loc7.shape[0], 6, dtype=int)NEWLINEydata_loc8 = np.full(xdata_loc8.shape[0], 7, dtype=int)NEWLINENEWLINEydata_loc9 = np.full(xdata_loc9.shape[0], 8, dtype=int)NEWLINEydata_loc10 = np.full(xdata_loc10.shape[0], 9, dtype=int)NEWLINEydata_loc11 = np.full(xdata_loc11.shape[0], 10, dtype=int)NEWLINEydata_loc12 = np.full(xdata_loc12.shape[0], 11, dtype=int)NEWLINENEWLINE#CONCATINATING THE DIFFERENT POSE LABELS HORIZONTALLY (ROWWISE)NEWLINEydata = np.concatenate([ydata_loc1, ydata_loc2, ydata_loc3, ydata_loc4, ydata_loc5, ydata_loc6, ydata_loc7, ydata_loc8, ydata_loc9, ydata_loc10, ydata_loc11, ydata_loc12], axis=0)NEWLINENEWLINENEWLINE# PREPROCESSING X AND Y DATANEWLINExdata =xdata.astype(np.float)NEWLINENEWLINEydata = ydata.astype(np.int).flatten()NEWLINENEWLINE# REMOVING THE NANSNEWLINExdata = np.nan_to_num(xdata)NEWLINENEWLINENEWLINE# ############## RANDOMLY SHUFFLING THE DATA ###################NEWLINE#NEWLINE# first concatinate - TO MAINTIAN THE XDATA AND YDATA MAPPINGNEWLINExydata = np.concatenate([xdata.reshape(xdata.shape[0], xdata.shape[1]), ydata.reshape(ydata.shape[0], 1)], axis=1)NEWLINENEWLINEnp.random.shuffle(xydata)NEWLINENEWLINEprint("Shape of XYDATA", xydata.shape)NEWLINENEWLINExdata_10ft, ydata_10ft = xydata[:,0:sample_size*no_of_features], xydata[:,((sample_size*no_of_features))] # THE LAST COLUMN IS THE YDATA # USE 2 INSTEAD OF 8 OF YOU DO NOT USE MULTI-ANGULAR PROJECTIONNEWLINENEWLINENEWLINE################################################################################################################################NEWLINENEWLINE#############################################################################################################################NEWLINE######## #######NEWLINE######## READING THE 15FT DATA #######NEWLINE######## #######NEWLINE#############################################################################################################################NEWLINENEWLINEdata_file_loc1 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/0_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER DIRECTLY POINTING TO THE RECEIVERNEWLINEdata_file_loc2 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/+30_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 30 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc3 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/+60_15ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS 60 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc4 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/+90_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 90 DEGREE LEFT TO THE RECEIVERNEWLINENEWLINEdata_file_loc5 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/+120_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 120 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc6 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/+150_15ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS 150 DEGREE LEFT TO THE RECEIVERNEWLINEdata_file_loc7 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/180_15ft_06_16_2020_914MHz_indoor.dat'# TRANSMITTER ANTENNA IS DIRECTLY POINTED AWAY FROM THE RECEIVERNEWLINEdata_file_loc8 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/-150_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 30 DEGREE RIGHT TO THE RECEIVERNEWLINENEWLINEdata_file_loc9 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/-120_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 60 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc10 ='/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/-90_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 90 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc11 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/-60_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 120 DEGREE RIGHT TO THE RECEIVERNEWLINEdata_file_loc12 = '/Users/debashri/Desktop/DirectionFinding_Data/Indoor/DataJune16Indoor/15ft/-30_15ft_06_16_2020_914MHz_indoor.dat' # TRANSMITTER ANTENNA IS 150 DEGREE RIGHT TO THE RECEIVERNEWLINENEWLINENEWLINENEWLINEiqdata_loc1 = scipy.fromfile(open(data_file_loc1), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc2 = scipy.fromfile(open(data_file_loc2), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc3 = scipy.fromfile(open(data_file_loc3), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc4 = scipy.fromfile(open(data_file_loc4), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINEiqdata_loc5 = scipy.fromfile(open(data_file_loc5), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc6 = scipy.fromfile(open(data_file_loc6), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc7 = scipy.fromfile(open(data_file_loc7), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc8 = scipy.fromfile(open(data_file_loc8), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINENEWLINEiqdata_loc9 = scipy.fromfile(open(data_file_loc9), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc10 = scipy.fromfile(open(data_file_loc10), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc11 = scipy.fromfile(open(data_file_loc11), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINEiqdata_loc12 = scipy.fromfile(open(data_file_loc12), dtype=dtype_all, count = sample_size * no_of_samples)NEWLINENEWLINENEWLINENEWLINE# PREPARING THE DATA WITHOUT TIME INFORMATIONNEWLINEno_of_data_loc1 = iqdata_loc1.shape[0]NEWLINEno_of_data_loc2 = iqdata_loc2.shape[0]NEWLINEno_of_data_loc3 = iqdata_loc3.shape[0]NEWLINEno_of_data_loc4 = iqdata_loc4.shape[0]NEWLINENEWLINEno_of_data_loc5 = iqdata_loc5.shape[0]NEWLINEno_of_data_loc6 = iqdata_loc6.shape[0]NEWLINEno_of_data_loc7 = iqdata_loc7.shape[0]NEWLINEno_of_data_loc8 = iqdata_loc8.shape[0]NEWLINENEWLINEno_of_data_loc9 = iqdata_loc9.shape[0]NEWLINEno_of_data_loc10 = iqdata_loc10.shape[0]NEWLINEno_of_data_loc11 = iqdata_loc11.shape[0]NEWLINEno_of_data_loc12 = iqdata_loc12.shape[0]NEWLINENEWLINENEWLINENEWLINE################################################################################################################NEWLINE# CONCATINATING THE I AND Q VALUES VERTICALLY OF (I, Q) SAMPLE. -- note the axis argument is set to 1 (means vertical stacking)NEWLINE# SIMULATNEOUSLY MULTIPLYING WITH THE WEIGHT MATRIX - TO REFLECT THE MULTI-ANGULAR PROJECTIONNEWLINENEWLINExdata_loc1= np.concatenate([iqdata_loc1['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc1['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc1 = np.matmul(xdata_loc1, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc2= np.concatenate([iqdata_loc2['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc2['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc2 = np.matmul(xdata_loc2, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc3= np.concatenate([iqdata_loc3['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc3['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc3 = np.matmul(xdata_loc3, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc4= np.concatenate([iqdata_loc4['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc4['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc4 = np.matmul(xdata_loc4, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINExdata_loc5= np.concatenate([iqdata_loc5['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc5['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc5 = np.matmul(xdata_loc5, np.transpose(W))NEWLINENEWLINExdata_loc6= np.concatenate([iqdata_loc6['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc6['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc6 = np.matmul(xdata_loc6, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc7= np.concatenate([iqdata_loc7['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc7['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc7 = np.matmul(xdata_loc7, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc8= np.concatenate([iqdata_loc8['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc8['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc8 = np.matmul(xdata_loc8, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINExdata_loc9= np.concatenate([iqdata_loc9['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc9['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc9 = np.matmul(xdata_loc9, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc10= np.concatenate([iqdata_loc10['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc10['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc10 = np.matmul(xdata_loc10, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc11= np.concatenate([iqdata_loc11['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc11['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc11 = np.matmul(xdata_loc11, np.transpose(W))NEWLINENEWLINENEWLINExdata_loc12= np.concatenate([iqdata_loc12['raw-iq'].real.reshape(number_of_data_to_read,1), iqdata_loc12['raw-iq'].imag.reshape(number_of_data_to_read,1)], axis=1)NEWLINExdata_loc12 = np.matmul(xdata_loc12, np.transpose(W))NEWLINENEWLINENEWLINENEWLINENEWLINE# RESHAPING THE XDATANEWLINExdata_loc1= xdata_loc1.T.reshape(no_of_data_loc1//(sample_size), sample_size*no_of_features)NEWLINExdata_loc2 = xdata_loc2.T.reshape(no_of_data_loc2//(sample_size), sample_size*no_of_features)NEWLINExdata_loc3 = xdata_loc3.T.reshape(no_of_data_loc3//(sample_size), sample_size*no_of_features)NEWLINExdata_loc4 = xdata_loc4.T.reshape(no_of_data_loc4//(sample_size), sample_size*no_of_features)NEWLINENEWLINExdata_loc5= xdata_loc5.T.reshape(no_of_data_loc5//(sample_size), sample_size*no_of_features)NEWLINExdata_loc6 = xdata_loc6.T.reshape(no_of_data_loc6//(sample_size), sample_size*no_of_features)NEWLINExdata_loc7 = xdata_loc7.T.reshape(no_of_data_loc7//(sample_size), sample_size*no_of_features)NEWLINExdata_loc8 = xdata_loc8.T.reshape(no_of_data_loc8//(sample_size), sample_size*no_of_features)NEWLINENEWLINExdata_loc9= xdata_loc9.T.reshape(no_of_data_loc9//(sample_size), sample_size*no_of_features)NEWLINExdata_loc10 = xdata_loc10.T.reshape(no_of_data_loc10//(sample_size), sample_size*no_of_features)NEWLINExdata_loc11 = xdata_loc11.T.reshape(no_of_data_loc11//(sample_size), sample_size*no_of_features)NEWLINExdata_loc12 = xdata_loc12.T.reshape(no_of_data_loc12//(sample_size), sample_size*no_of_features)NEWLINENEWLINENEWLINENEWLINE#CONCATINATING THE DIFFERENT POSE DATA HORIZONTALLY (ROWWISE)NEWLINExdata = np.concatenate([xdata_loc1, xdata_loc2, xdata_loc3, xdata_loc4, xdata_loc5, xdata_loc6, xdata_loc7, xdata_loc8, xdata_loc9, xdata_loc10, xdata_loc11, xdata_loc12], axis=0)NEWLINENEWLINENEWLINENEWLINE# CREATING LABEL FOR THE DATASETSNEWLINEydata_loc1 = np.full(xdata_loc1.shape[0], 0, dtype=int)NEWLINEydata_loc2 = np.full(xdata_loc2.shape[0], 1, dtype=int)NEWLINEydata_loc3 = np.full(xdata_loc3.shape[0], 2, dtype=int)NEWLINEydata_loc4 = np.full(xdata_loc4.shape[0], 3, dtype=int)NEWLINENEWLINEydata_loc5 = np.full(xdata_loc5.shape[0], 4, dtype=int)NEWLINEydata_loc6 = np.full(xdata_loc6.shape[0], 5, dtype=int)NEWLINEydata_loc7 = np.full(xdata_loc7.shape[0], 6, dtype=int)NEWLINEydata_loc8 = np.full(xdata_loc8.shape[0], 7, dtype=int)NEWLINENEWLINEydata_loc9 = np.full(xdata_loc9.shape[0], 8, dtype=int)NEWLINEydata_loc10 = np.full(xdata_loc10.shape[0], 9, dtype=int)NEWLINEydata_loc11 = np.full(xdata_loc11.shape[0], 10, dtype=int)NEWLINEydata_loc12 = np.full(xdata_loc12.shape[0], 11, dtype=int)NEWLINENEWLINE#CONCATINATING THE DIFFERENT POSE LABELS HORIZONTALLY (ROWWISE)NEWLINEydata = np.concatenate([ydata_loc1, ydata_loc2, ydata_loc3, ydata_loc4, ydata_loc5, ydata_loc6, ydata_loc7, ydata_loc8, ydata_loc9, ydata_loc10, ydata_loc11, ydata_loc12], axis=0)NEWLINENEWLINENEWLINE# PREPROCESSING X AND Y DATANEWLINExdata =xdata.astype(np.float)NEWLINENEWLINEydata = ydata.astype(np.int).flatten()NEWLINENEWLINE# REMOVING THE NANSNEWLINExdata = np.nan_to_num(xdata)NEWLINENEWLINENEWLINE# ############## RANDOMLY SHUFFLING THE DATA ###################NEWLINE#NEWLINE# first concatinate - TO MAINTIAN THE XDATA AND YDATA MAPPINGNEWLINExydata = np.concatenate([xdata.reshape(xdata.shape[0], xdata.shape[1]), ydata.reshape(ydata.shape[0], 1)], axis=1)NEWLINENEWLINEnp.random.shuffle(xydata)NEWLINENEWLINEprint("Shape of XYDATA", xydata.shape)NEWLINENEWLINExdata_15ft, ydata_15ft = xydata[:,0:sample_size*no_of_features], xydata[:,((sample_size*no_of_features))] # THE LAST COLUMN IS THE YDATA # USE 2 INSTEAD OF 8 OF YOU DO NOT USE MULTI-ANGULAR PROJECTIONNEWLINENEWLINENEWLINE################################################################################################################################NEWLINENEWLINE#############################################################################################################################NEWLINE######## #######NEWLINE######## HIERARCHICAL TRAINING- FIRST STEP #######NEWLINE######## FIRST CLASSIFYING THE DATA BASED ON DISTANCES #######NEWLINE######## PREDICTING DISTANCE BETWEEN THE RECEIVER AND TRANSMITTER #######NEWLINE######## #######NEWLINE#############################################################################################################################NEWLINENEWLINENEWLINExdata_ranging = np.concatenate([xdata_5ft, xdata_10ft, xdata_15ft], axis= 0 )NEWLINENEWLINE# CREATING LABEL FOR THE DATASETSNEWLINEydata_range1 = np.full(xdata_5ft.shape[0], 0, dtype=int)NEWLINEydata_range2 = np.full(xdata_10ft.shape[0], 1, dtype=int)NEWLINEydata_range3 = np.full(xdata_15ft.shape[0], 2, dtype=int)NEWLINENEWLINE#CONCATINATING THE DIFFERENT POSE LABELS HORIZONTALLY (ROWWISE)NEWLINEydata_ranging = np.concatenate([ydata_range1, ydata_range2, ydata_range3], axis=0)NEWLINENEWLINE#################### NORMALIZE THE X DATA #######################NEWLINENEWLINENEWLINEstandard = preprocessing.StandardScaler().fit(xdata_ranging) # Normalize the data with zero mean and unit variance for each columnNEWLINExdata_ranging = standard.transform(xdata_ranging)NEWLINENEWLINENEWLINENEWLINE############### SEPARATING TRAIN AND TEST DATA #######################NEWLINEprint("############## STARTING THE TRAINING TO PREDICT THE RANGE BETWEEN RECEIVER AND TRANSMITTER ##########################")NEWLINENEWLINExtrain_ranging, xtest_ranging, ytrain_ranging, ytest_ranging = train_test_split(xdata_ranging, ydata_ranging, test_size=0.2, shuffle = True, random_state=42) # Randomly shuffling and 80/20 is train/test sizeNEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_ranging.shape, xtest_ranging.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_ranging.shape, ytest_ranging.shape)NEWLINENEWLINE# RESHAPING THE DATA FROM 2 DIMENSIONAL TO 4 DIMENSIONAL SHAPE - NEEDED TO APPLY TO USE 2D-CONVOLUTIONNEWLINE# reshape to be [samples][width][height][channels]NEWLINExtrain_ranging = xtrain_ranging.reshape((xtrain_ranging.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINExtest_ranging = xtest_ranging.reshape((xtest_ranging.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINENEWLINENEWLINEnum_classes = 3 # TOTAL NUMBER OF RANGESNEWLINENEWLINENEWLINENEWLINE# Convert labels to categorical one-hot encodingNEWLINEytrain_ranging_one_hot = to_categorical(ytrain_ranging, num_classes=num_classes) # DEFINE THE NUMBER OF TOTAL CLASSES IN LABELNEWLINEytest_ranging_one_hot = to_categorical(ytest_ranging, num_classes=num_classes)NEWLINENEWLINENEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_ranging.shape, xtest_ranging.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_ranging_one_hot.shape, ytest_ranging_one_hot.shape)NEWLINENEWLINE############################################################NEWLINE# #NEWLINE######## Building a 2D Convolutional Neural Network #####NEWLINE# #NEWLINE############################################################NEWLINENEWLINEdr = 0.6 # dropout rate (%)NEWLINEbatch_size = 128 # Mini batch sizeNEWLINEnb_epoch = 100 # Number of Epoch (Give a higher number to get better accuracy)NEWLINENEWLINEclasses = ["5ft", "10ft", "15ft"] # CHANGE LABELNEWLINEin_shp = list(xtrain_ranging.shape[1:]) # Input DimensionNEWLINEprint(in_shp)NEWLINE# model = models.Sequential()NEWLINEtimesteps=1NEWLINEdata_dim=xtrain_ranging.shape[1]NEWLINENEWLINENEWLINENEWLINE# print ("AFTER RESHAPE")NEWLINEytrain_ranging_one_hot = np.reshape(ytrain_ranging_one_hot, (ytrain_ranging_one_hot.shape[0], num_classes)) # Used in trainingNEWLINEytest_ranging_one_hot = np.reshape(ytest_ranging_one_hot, (ytest_ranging_one_hot.shape[0], num_classes)) # Used in trainingNEWLINENEWLINEstart_time = time.time() # Taking start time to calculate overall execution timeNEWLINENEWLINE# Modeling the CNNNEWLINEmodel_ranging = Sequential()NEWLINENEWLINE# FIRST CONVOLUTIONAL LAYERNEWLINEmodel_ranging.add(Conv2D(128, (2, 2), input_shape=(no_of_features, sample_size, 1), activation='relu')) # CHANGE # Stride (1, 1)NEWLINEmodel_ranging.add(MaxPooling2D()) # Pool size: (2, 2) and stride (2, 2)NEWLINEmodel_ranging.add(Dropout(0.2))NEWLINENEWLINE# SECOND CONVOLUTIONAL LAYERNEWLINEmodel_ranging.add(Conv2D(64, (2, 2), activation='relu'))NEWLINEmodel_ranging.add(MaxPooling2D())NEWLINEmodel_ranging.add(Dropout(dr))NEWLINENEWLINEmodel_ranging.add(Flatten())NEWLINENEWLINE# FIRST DENSE LAYERNEWLINEmodel_ranging.add(Dense(256, activation='relu'))NEWLINENEWLINE# SECOND DENSE LAYERNEWLINEmodel_ranging.add(Dense(128, activation='relu'))NEWLINENEWLINE# OUTPUT LAYERNEWLINEmodel_ranging.add(Dense(num_classes, activation='softmax'))NEWLINENEWLINE# Compile modelNEWLINE# For a multi-class classification problemNEWLINEsgd = SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True)NEWLINEadam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)NEWLINENEWLINE# model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # Multiclass classification with rmspropNEWLINENEWLINE#model.compile(optimizer='sgd', loss='categorical_crossentropy',metrics=['acc', f1_m, precision_m, recall_m]) # Multiclass classification with rms adam optimizer # CHANGENEWLINENEWLINEmodel_ranging.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc', f1_m, precision_m, recall_m])NEWLINENEWLINEmodel_ranging.summary()NEWLINEfilepath = '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/direction_data_ranging_2D_CNN_Mapping.wts.h5'NEWLINEprint("The dropout rate was: ")NEWLINEprint(dr)NEWLINENEWLINENEWLINE# Fit the modelNEWLINE# history= model.fit(xtrain, ytrain_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_data = (xtest, ytest_one_hot), callbacks = [keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'), keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINEhistory = model_ranging.fit(xtrain_ranging, ytrain_ranging_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_split=0.1, callbacks=[NEWLINE keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'),NEWLINE keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINENEWLINENEWLINENEWLINE# SAVING THE MODEL FOR TRANSFER LEARNINGNEWLINEsaved_file = '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/2D_CNN_ranging_classifier.h5'NEWLINEmodel_ranging.save(saved_file) # SAVING THE MODEL FOR TRANSFER LEARNINGNEWLINENEWLINENEWLINENEWLINE# Evaluate the modelNEWLINEloss, accuracy, f1_score, precision, recall = model_ranging.evaluate(xtest_ranging, ytest_ranging_one_hot, batch_size=batch_size) # CHANGENEWLINEprint("\nTest Loss: %s: %.2f%%" % (model_ranging.metrics_names[0], loss * 100)) # CHANGENEWLINEprint("\nTest Accuracy: %s: %.2f%%" % (model_ranging.metrics_names[1], accuracy * 100)) # CHANGENEWLINEprint("\nTest F1 Score: %s: %.2f" % (model_ranging.metrics_names[2], f1_score)) # CHANGENEWLINEprint("\nTest Precision: %s: %.2f%%" % (model_ranging.metrics_names[3], precision * 100)) # CHANGENEWLINEprint("\nTest Recall: %s: %.2f%%" % (model_ranging.metrics_names[4], recall * 100)) # CHANGENEWLINENEWLINE# Calculating total execution timeNEWLINEend_time = time.time() # Taking end time to calculate overall execution timeNEWLINEprint("\n Total Execution Time (Minutes): ")NEWLINEprint(((end_time - start_time) / 60))NEWLINENEWLINE#### SET PLOTTING PARAMETERS #########NEWLINEparams = {'legend.fontsize': 'xx-large',NEWLINE 'axes.labelsize': 'xx-large',NEWLINE 'axes.titlesize': 'xx-large',NEWLINE 'xtick.labelsize': 'xx-large',NEWLINE 'ytick.labelsize': 'xx-large'}NEWLINEplt.rcParams.update(params)NEWLINENEWLINENEWLINE# Show Accuracy CurvesNEWLINEfig = plt.figure()NEWLINE# plt.title('Training Performance')NEWLINEplt.plot(history.epoch, history.history['acc'], label='Training Accuracy', linewidth=2.0, c='b')NEWLINEplt.plot(history.epoch, history.history['val_acc'], label='Validation Accuracy', linewidth=2.0, c='r')NEWLINEplt.ylabel('Accuracy(%)')NEWLINEplt.xlabel('Epoch')NEWLINEplt.legend()NEWLINEplt.tight_layout()NEWLINEfig.savefig('/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/direction_ranging_acc_2D_CNN_Mapping.png') # save the figure to fileNEWLINEplt.close(fig)NEWLINENEWLINENEWLINE# plt.show()NEWLINENEWLINENEWLINEdef plot_confusion_matrix(cm, title='Confusion Matrix', cmap=plt.cm.YlGnBu, labels=[], normalize=False, filedest = ''):NEWLINE if normalize:NEWLINE cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]NEWLINE # print("Normalized confusion matrix")NEWLINE else:NEWLINE cm = cm.astype('int')NEWLINE # print('Confusion matrix, without normalization')NEWLINE plt.rcParams.update(params) # ADDEDNEWLINE fig = plt.figure(figsize=(12,12))NEWLINE plt.imshow(cm, interpolation='nearest', cmap=cmap)NEWLINE # plt.title(title)NEWLINE plt.colorbar()NEWLINE tick_marks = np.arange(len(labels))NEWLINE plt.xticks(tick_marks, labels, rotation=45)NEWLINE plt.yticks(tick_marks, labels)NEWLINE thresh = cm.max() / 2NEWLINE fmt = '.2f' if normalize else 'd'NEWLINE for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):NEWLINE # plt.text(j, i,"{:,}".format(cm[i, j]),NEWLINE plt.text(j, i, format(cm[i, j], fmt),NEWLINE horizontalalignment="center", fontsize="xx-large",NEWLINE color="white" if cm[i, j] > thresh else "black")NEWLINENEWLINE plt.ylabel('True label')NEWLINE plt.xlabel('Predicted label')NEWLINE # fig, ax = plt.subplots(nrows=1, ncols=1) # create figure & 1 axisNEWLINE # ax.plot([0, 1, 2], [10, 20, 3])NEWLINE plt.tight_layout()NEWLINE fig.savefig(filedest) # save the figure to fileNEWLINE plt.close(fig)NEWLINENEWLINENEWLINE# plt.show()NEWLINENEWLINENEWLINENEWLINE# Plot confusion matrixNEWLINEtest_Y_hat = model_ranging.predict(xtest_ranging, batch_size=batch_size)NEWLINEconf = np.zeros([len(classes), len(classes)])NEWLINEconfnorm = np.zeros([len(classes), len(classes)])NEWLINEfor i in range(0, xtest_ranging.shape[0]):NEWLINE j = list(ytest_ranging_one_hot[i, :]).index(1)NEWLINE k = int(np.argmax(test_Y_hat[i, :]))NEWLINE conf[j, k] = conf[j, k] + 1NEWLINEplot_confusion_matrix(conf, labels=classes, normalize=False, filedest='/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/direction_ranging_conf_mat_2D_CNN_Mapping.png')NEWLINENEWLINENEWLINE#############################################################################################################################NEWLINE######## #######NEWLINE######## HIERARCHICAL TRAINING- SECOND STEP #######NEWLINE######## CLASSIFYING THE DATA BASED ON POSES OF TRANSMITER ANTENNA #######NEWLINE######## PREDICTING REALTIVE POSES OF TRANSMITER ANTENNA #######NEWLINE######## DISTANCE: 5FT #######NEWLINE#############################################################################################################################NEWLINENEWLINENEWLINE#################### NORMALIZE THE X DATA #######################NEWLINENEWLINENEWLINEstandard = preprocessing.StandardScaler().fit(xdata_5ft) # Normalize the data with zero mean and unit variance for each columnNEWLINExdata_5ft = standard.transform(xdata_5ft)NEWLINENEWLINEprint("############## STARTING THE TRAINING TO PREDICT THE POSES OF TRANSMITTER ANTENNA WITH 5 FT DISTANCE FROM RECEIVER ##########################")NEWLINENEWLINENEWLINENEWLINE############### SEPARATING TRAIN AND TEST DATA #######################NEWLINENEWLINExtrain_5ft, xtest_5ft, ytrain_5ft, ytest_5ft = train_test_split(xdata_5ft, ydata_5ft, test_size=0.2, shuffle = True, random_state=42) # Randomly shuffling and 80/20 is train/test sizeNEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_5ft.shape, xtest_5ft.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_5ft.shape, ytest_5ft.shape)NEWLINENEWLINE# RESHAPING THE DATA FROM 2 DIMENSIONAL TO 4 DIMENSIONAL SHAPE - NEEDED TO APPLY TO USE 2D-CONVOLUTIONNEWLINE# reshape to be [samples][width][height][channels]NEWLINExtrain_5ft = xtrain_5ft.reshape((xtrain_5ft.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINExtest_5ft = xtest_5ft.reshape((xtest_5ft.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINENEWLINENEWLINEnum_classes = 12 # TOTAL NUMBER OF RANGESNEWLINENEWLINENEWLINENEWLINE# Convert labels to categorical one-hot encodingNEWLINEytrain_5ft_one_hot = to_categorical(ytrain_5ft, num_classes=num_classes) # DEFINE THE NUMBER OF TOTAL CLASSES IN LABELNEWLINEytest_5ft_one_hot = to_categorical(ytest_5ft, num_classes=num_classes)NEWLINENEWLINENEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_5ft.shape, xtest_5ft.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_5ft_one_hot.shape, ytest_5ft_one_hot.shape)NEWLINENEWLINE############################################################NEWLINE# #NEWLINE######## Building a 2D Convolutional Neural Network #####NEWLINE# #NEWLINE############################################################NEWLINENEWLINEdr = 0.6 # dropout rate (%)NEWLINEbatch_size = 128 # Mini batch sizeNEWLINEnb_epoch = 100 # Number of Epoch (Give a higher number to get better accuracy)NEWLINENEWLINEclasses = ["0", "+30", "+60", "+90", "+120", "+150", "180", "-150", "-120", "-90", "-60", "-30"] # CHANGE LABELNEWLINEin_shp = list(xtrain_5ft.shape[1:]) # Input DimensionNEWLINEprint(in_shp)NEWLINE# model = models.Sequential()NEWLINEtimesteps=1NEWLINEdata_dim=xtrain_5ft.shape[1]NEWLINENEWLINENEWLINENEWLINE# print ("AFTER RESHAPE")NEWLINEytrain_5ft_one_hot = np.reshape(ytrain_5ft_one_hot, (ytrain_5ft_one_hot.shape[0], num_classes)) # Used in trainingNEWLINEytest_5ft_one_hot = np.reshape(ytest_5ft_one_hot, (ytest_5ft_one_hot.shape[0], num_classes)) # Used in trainingNEWLINENEWLINEstart_time = time.time() # Taking start time to calculate overall execution timeNEWLINENEWLINE# IMPLEMENTING THE TRANSFER LEARNINGNEWLINE#source_model = load_model(saved_file)NEWLINE# loading the previously saved modelNEWLINEsource_model = load_model(saved_file, custom_objects={NEWLINE "f1_m": f1_m,NEWLINE "precision_m": precision_m,NEWLINE "recall_m": recall_mNEWLINE })NEWLINENEWLINEmodel_pose = Sequential()NEWLINEfor layer in source_model.layers[:-1]: # go through until last layerNEWLINE model_pose.add(layer)NEWLINENEWLINENEWLINE# ADDING OUTPUT LAYERNEWLINEmodel_pose.add(Dense(num_classes, activation='softmax'))NEWLINENEWLINE# Compile modelNEWLINE# For a multi-class classification problemNEWLINEsgd = SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True)NEWLINEadam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)NEWLINENEWLINE# model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # Multiclass classification with rmspropNEWLINENEWLINE#model.compile(optimizer='sgd', loss='categorical_crossentropy',metrics=['acc', f1_m, precision_m, recall_m]) # Multiclass classification with rms adam optimizer # CHANGENEWLINENEWLINEmodel_pose.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc', f1_m, precision_m, recall_m])NEWLINENEWLINEmodel_pose.summary()NEWLINEfilepath = '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/5ft/direction_data_12_poses_2D_CNN_Mapping.wts.h5'NEWLINEprint("The dropout rate was: ")NEWLINEprint(dr)NEWLINENEWLINENEWLINE# Fit the modelNEWLINE# history= model.fit(xtrain, ytrain_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_data = (xtest, ytest_one_hot), callbacks = [keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'), keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINEhistory = model_pose.fit(xtrain_5ft, ytrain_5ft_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_split=0.1, callbacks=[NEWLINE keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'),NEWLINE keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINENEWLINENEWLINE# Evaluate the modelNEWLINEloss, accuracy, f1_score, precision, recall = model_pose.evaluate(xtest_5ft, ytest_5ft_one_hot, batch_size=batch_size) # CHANGENEWLINEprint("\nTest Loss: %s: %.2f%%" % (model_pose.metrics_names[0], loss * 100)) # CHANGENEWLINEprint("\nTest Accuracy: %s: %.2f%%" % (model_pose.metrics_names[1], accuracy * 100)) # CHANGENEWLINEprint("\nTest F1 Score: %s: %.2f" % (model_pose.metrics_names[2], f1_score)) # CHANGENEWLINEprint("\nTest Precision: %s: %.2f%%" % (model_pose.metrics_names[3], precision * 100)) # CHANGENEWLINEprint("\nTest Recall: %s: %.2f%%" % (model_pose.metrics_names[4], recall * 100)) # CHANGENEWLINENEWLINE# Calculating total execution timeNEWLINEend_time = time.time() # Taking end time to calculate overall execution timeNEWLINEprint("\n Total Execution Time (Minutes): ")NEWLINEprint(((end_time - start_time) / 60))NEWLINENEWLINE#### SET PLOTTING PARAMETERS #########NEWLINEparams = {'legend.fontsize': 'xx-large',NEWLINE 'axes.labelsize': 'xx-large',NEWLINE 'axes.titlesize': 'xx-large',NEWLINE 'xtick.labelsize': 'xx-large',NEWLINE 'ytick.labelsize': 'xx-large'}NEWLINEplt.rcParams.update(params)NEWLINENEWLINENEWLINE# Show Accuracy CurvesNEWLINEfig = plt.figure()NEWLINE# plt.title('Training Performance')NEWLINEplt.plot(history.epoch, history.history['acc'], label='Training Accuracy', linewidth=2.0, c='b')NEWLINEplt.plot(history.epoch, history.history['val_acc'], label='Validation Accuracy', linewidth=2.0, c='r')NEWLINEplt.ylabel('Accuracy(%)')NEWLINEplt.xlabel('Epoch')NEWLINEplt.legend()NEWLINEplt.tight_layout()NEWLINEfig.savefig('/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/5ft/direction_12_poses_acc_2D_CNN_Mapping.png') # save the figure to fileNEWLINEplt.close(fig)NEWLINENEWLINENEWLINE# plt.show()NEWLINENEWLINENEWLINE# Plot confusion matrixNEWLINEtest_Y_hat = model_pose.predict(xtest_5ft, batch_size=batch_size)NEWLINEconf = np.zeros([len(classes), len(classes)])NEWLINEconfnorm = np.zeros([len(classes), len(classes)])NEWLINEfor i in range(0, xtest_5ft.shape[0]):NEWLINE j = list(ytest_5ft_one_hot[i, :]).index(1)NEWLINE k = int(np.argmax(test_Y_hat[i, :]))NEWLINE conf[j, k] = conf[j, k] + 1NEWLINEplot_confusion_matrix(conf, labels=classes, normalize=False, filedest= '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/5ft/direction_12_poses_conf_mat_2D_CNN_Mapping.png')NEWLINENEWLINENEWLINE#############################################################################################################################NEWLINE######## #######NEWLINE######## HIERARCHICAL TRAINING- SECOND STEP #######NEWLINE######## CLASSIFYING THE DATA BASED ON POSES OF TRANSMITER ANTENNA #######NEWLINE######## PREDICTING REALTIVE POSES OF TRANSMITER ANTENNA #######NEWLINE######## DISTANCE: 10FT #######NEWLINE#############################################################################################################################NEWLINENEWLINENEWLINE#################### NORMALIZE THE X DATA #######################NEWLINENEWLINENEWLINEstandard = preprocessing.StandardScaler().fit(xdata_10ft) # Normalize the data with zero mean and unit variance for each columnNEWLINExdata_10ft = standard.transform(xdata_10ft)NEWLINENEWLINEprint("############## STARTING THE TRAINING TO PREDICT THE POSES OF TRANSMITTER ANTENNA WITH 10 FT DISTANCE FROM RECEIVER ##########################")NEWLINENEWLINENEWLINE############### SEPARATING TRAIN AND TEST DATA #######################NEWLINENEWLINExtrain_10ft, xtest_10ft, ytrain_10ft, ytest_10ft = train_test_split(xdata_10ft, ydata_10ft, test_size=0.2, shuffle = True, random_state=42) # Randomly shuffling and 80/20 is train/test sizeNEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_10ft.shape, xtest_10ft.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_10ft.shape, ytest_10ft.shape)NEWLINENEWLINE# RESHAPING THE DATA FROM 2 DIMENSIONAL TO 4 DIMENSIONAL SHAPE - NEEDED TO APPLY TO USE 2D-CONVOLUTIONNEWLINE# reshape to be [samples][width][height][channels]NEWLINExtrain_10ft = xtrain_10ft.reshape((xtrain_10ft.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINExtest_10ft = xtest_10ft.reshape((xtest_10ft.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINENEWLINENEWLINEnum_classes = 12 # TOTAL NUMBER OF RANGESNEWLINENEWLINENEWLINENEWLINE# Convert labels to categorical one-hot encodingNEWLINEytrain_10ft_one_hot = to_categorical(ytrain_10ft, num_classes=num_classes) # DEFINE THE NUMBER OF TOTAL CLASSES IN LABELNEWLINEytest_10ft_one_hot = to_categorical(ytest_10ft, num_classes=num_classes)NEWLINENEWLINENEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_10ft.shape, xtest_10ft.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_10ft_one_hot.shape, ytest_10ft_one_hot.shape)NEWLINENEWLINE############################################################NEWLINE# #NEWLINE######## Building a 2D Convolutional Neural Network #####NEWLINE# #NEWLINE############################################################NEWLINENEWLINEdr = 0.6 # dropout rate (%)NEWLINEbatch_size = 128 # Mini batch sizeNEWLINEnb_epoch = 100 # Number of Epoch (Give a higher number to get better accuracy)NEWLINENEWLINEclasses = ["0", "+30", "+60", "+90", "+120", "+150", "180", "-150", "-120", "-90", "-60", "-30"] # CHANGE LABELNEWLINEin_shp = list(xtrain_10ft.shape[1:]) # Input DimensionNEWLINEprint(in_shp)NEWLINE# model = models.Sequential()NEWLINEtimesteps=1NEWLINEdata_dim=xtrain_10ft.shape[1]NEWLINENEWLINENEWLINENEWLINE# print ("AFTER RESHAPE")NEWLINEytrain_10ft_one_hot = np.reshape(ytrain_10ft_one_hot, (ytrain_10ft_one_hot.shape[0], num_classes)) # Used in trainingNEWLINEytest_10ft_one_hot = np.reshape(ytest_10ft_one_hot, (ytest_10ft_one_hot.shape[0], num_classes)) # Used in trainingNEWLINENEWLINEstart_time = time.time() # Taking start time to calculate overall execution timeNEWLINENEWLINE# IMPLEMENTING THE TRANSFER LEARNINGNEWLINE#source_model = load_model(saved_file)NEWLINE# loading the previously saved modelNEWLINEsource_model = load_model(saved_file, custom_objects={NEWLINE "f1_m": f1_m,NEWLINE "precision_m": precision_m,NEWLINE "recall_m": recall_mNEWLINE })NEWLINENEWLINEmodel_pose = Sequential()NEWLINEfor layer in source_model.layers[:-1]: # go through until last layerNEWLINE model_pose.add(layer)NEWLINENEWLINENEWLINE# ADDING OUTPUT LAYERNEWLINEmodel_pose.add(Dense(num_classes, activation='softmax'))NEWLINENEWLINE# Compile modelNEWLINE# For a multi-class classification problemNEWLINEsgd = SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True)NEWLINEadam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)NEWLINENEWLINE# model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # Multiclass classification with rmspropNEWLINENEWLINE#model.compile(optimizer='sgd', loss='categorical_crossentropy',metrics=['acc', f1_m, precision_m, recall_m]) # Multiclass classification with rms adam optimizer # CHANGENEWLINENEWLINEmodel_pose.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc', f1_m, precision_m, recall_m])NEWLINENEWLINEmodel_pose.summary()NEWLINEfilepath = '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/10ft/direction_data_12_poses_2D_CNN_Mapping.wts.h5'NEWLINEprint("The dropout rate was: ")NEWLINEprint(dr)NEWLINENEWLINENEWLINE# Fit the modelNEWLINE# history= model.fit(xtrain, ytrain_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_data = (xtest, ytest_one_hot), callbacks = [keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'), keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINEhistory = model_pose.fit(xtrain_10ft, ytrain_10ft_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_split=0.1, callbacks=[NEWLINE keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'),NEWLINE keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINENEWLINENEWLINE# Evaluate the modelNEWLINEloss, accuracy, f1_score, precision, recall = model_pose.evaluate(xtest_10ft, ytest_10ft_one_hot, batch_size=batch_size) # CHANGENEWLINEprint("\nTest Loss: %s: %.2f%%" % (model_pose.metrics_names[0], loss * 100)) # CHANGENEWLINEprint("\nTest Accuracy: %s: %.2f%%" % (model_pose.metrics_names[1], accuracy * 100)) # CHANGENEWLINEprint("\nTest F1 Score: %s: %.2f" % (model_pose.metrics_names[2], f1_score)) # CHANGENEWLINEprint("\nTest Precision: %s: %.2f%%" % (model_pose.metrics_names[3], precision * 100)) # CHANGENEWLINEprint("\nTest Recall: %s: %.2f%%" % (model_pose.metrics_names[4], recall * 100)) # CHANGENEWLINENEWLINE# Calculating total execution timeNEWLINEend_time = time.time() # Taking end time to calculate overall execution timeNEWLINEprint("\n Total Execution Time (Minutes): ")NEWLINEprint(((end_time - start_time) / 60))NEWLINENEWLINE#### SET PLOTTING PARAMETERS #########NEWLINEparams = {'legend.fontsize': 'xx-large',NEWLINE 'axes.labelsize': 'xx-large',NEWLINE 'axes.titlesize': 'xx-large',NEWLINE 'xtick.labelsize': 'xx-large',NEWLINE 'ytick.labelsize': 'xx-large'}NEWLINEplt.rcParams.update(params)NEWLINENEWLINENEWLINE# Show Accuracy CurvesNEWLINEfig = plt.figure()NEWLINE# plt.title('Training Performance')NEWLINEplt.plot(history.epoch, history.history['acc'], label='Training Accuracy', linewidth=2.0, c='b')NEWLINEplt.plot(history.epoch, history.history['val_acc'], label='Validation Accuracy', linewidth=2.0, c='r')NEWLINEplt.ylabel('Accuracy(%)')NEWLINEplt.xlabel('Epoch')NEWLINEplt.legend()NEWLINEplt.tight_layout()NEWLINEfig.savefig('/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/10ft/direction_12_poses_acc_2D_CNN_Mapping.png') # save the figure to fileNEWLINEplt.close(fig)NEWLINENEWLINENEWLINE# plt.show()NEWLINENEWLINENEWLINE# Plot confusion matrixNEWLINEtest_Y_hat = model_pose.predict(xtest_10ft, batch_size=batch_size)NEWLINEconf = np.zeros([len(classes), len(classes)])NEWLINEconfnorm = np.zeros([len(classes), len(classes)])NEWLINEfor i in range(0, xtest_10ft.shape[0]):NEWLINE j = list(ytest_10ft_one_hot[i, :]).index(1)NEWLINE k = int(np.argmax(test_Y_hat[i, :]))NEWLINE conf[j, k] = conf[j, k] + 1NEWLINEplot_confusion_matrix(conf, labels=classes, normalize=False, filedest= '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/10ft/direction_12_poses_conf_mat_2D_CNN_Mapping.png')NEWLINENEWLINENEWLINE#############################################################################################################################NEWLINE######## #######NEWLINE######## HIERARCHICAL TRAINING- SECOND STEP #######NEWLINE######## CLASSIFYING THE DATA BASED ON POSES OF TRANSMITER ANTENNA #######NEWLINE######## PREDICTING REALTIVE POSES OF TRANSMITER ANTENNA #######NEWLINE######## DISTANCE: 15FT #######NEWLINE#############################################################################################################################NEWLINENEWLINENEWLINE#################### NORMALIZE THE X DATA #######################NEWLINENEWLINENEWLINEstandard = preprocessing.StandardScaler().fit(xdata_15ft) # Normalize the data with zero mean and unit variance for each columnNEWLINExdata_15ft = standard.transform(xdata_15ft)NEWLINENEWLINEprint("############## STARTING THE TRAINING TO PREDICT THE POSES OF TRANSMITTER ANTENNA WITH 15 FT DISTANCE FROM RECEIVER ##########################")NEWLINENEWLINENEWLINE############### SEPARATING TRAIN AND TEST DATA #######################NEWLINENEWLINExtrain_15ft, xtest_15ft, ytrain_15ft, ytest_15ft = train_test_split(xdata_15ft, ydata_15ft, test_size=0.2, shuffle = True, random_state=42) # Randomly shuffling and 80/20 is train/test sizeNEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_5ft.shape, xtest_5ft.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_5ft.shape, ytest_5ft.shape)NEWLINENEWLINE# RESHAPING THE DATA FROM 2 DIMENSIONAL TO 4 DIMENSIONAL SHAPE - NEEDED TO APPLY TO USE 2D-CONVOLUTIONNEWLINE# reshape to be [samples][width][height][channels]NEWLINExtrain_15ft = xtrain_15ft.reshape((xtrain_15ft.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINExtest_15ft = xtest_15ft.reshape((xtest_15ft.shape[0], no_of_features, sample_size, 1)).astype('float32')NEWLINENEWLINENEWLINEnum_classes = 12 # TOTAL NUMBER OF RANGESNEWLINENEWLINENEWLINENEWLINE# Convert labels to categorical one-hot encodingNEWLINEytrain_15ft_one_hot = to_categorical(ytrain_15ft, num_classes=num_classes) # DEFINE THE NUMBER OF TOTAL CLASSES IN LABELNEWLINEytest_15ft_one_hot = to_categorical(ytest_15ft, num_classes=num_classes)NEWLINENEWLINENEWLINEprint("XTRAIN AND XTEST SHAPE:", xtrain_15ft.shape, xtest_15ft.shape)NEWLINEprint("YTRAIN AND YTEST SHAPE:", ytrain_15ft_one_hot.shape, ytest_15ft_one_hot.shape)NEWLINENEWLINE############################################################NEWLINE# #NEWLINE######## Building a 2D Convolutional Neural Network #####NEWLINE# #NEWLINE############################################################NEWLINENEWLINEdr = 0.6 # dropout rate (%)NEWLINEbatch_size = 128 # Mini batch sizeNEWLINEnb_epoch = 100 # Number of Epoch (Give a higher number to get better accuracy)NEWLINENEWLINEclasses = ["0", "+30", "+60", "+90", "+120", "+150", "180", "-150", "-120", "-90", "-60", "-30"] # CHANGE LABELNEWLINEin_shp = list(xtrain_15ft.shape[1:]) # Input DimensionNEWLINEprint(in_shp)NEWLINE# model = models.Sequential()NEWLINEtimesteps=1NEWLINEdata_dim=xtrain_15ft.shape[1]NEWLINENEWLINENEWLINENEWLINE# print ("AFTER RESHAPE")NEWLINEytrain_15ft_one_hot = np.reshape(ytrain_15ft_one_hot, (ytrain_15ft_one_hot.shape[0], num_classes)) # Used in trainingNEWLINEytest_15ft_one_hot = np.reshape(ytest_15ft_one_hot, (ytest_15ft_one_hot.shape[0], num_classes)) # Used in trainingNEWLINENEWLINEstart_time = time.time() # Taking start time to calculate overall execution timeNEWLINENEWLINE# IMPLEMENTING THE TRANSFER LEARNINGNEWLINE#source_model = load_model(saved_file)NEWLINE# loading the previously saved modelNEWLINEsource_model = load_model(saved_file, custom_objects={NEWLINE "f1_m": f1_m,NEWLINE "precision_m": precision_m,NEWLINE "recall_m": recall_mNEWLINE })NEWLINENEWLINEmodel_pose = Sequential()NEWLINEfor layer in source_model.layers[:-1]: # go through until last layerNEWLINE model_pose.add(layer)NEWLINENEWLINENEWLINE# ADDING OUTPUT LAYERNEWLINEmodel_pose.add(Dense(num_classes, activation='softmax'))NEWLINENEWLINE# Compile modelNEWLINE# For a multi-class classification problemNEWLINEsgd = SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True)NEWLINEadam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)NEWLINENEWLINE# model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # Multiclass classification with rmspropNEWLINENEWLINE#model.compile(optimizer='sgd', loss='categorical_crossentropy',metrics=['acc', f1_m, precision_m, recall_m]) # Multiclass classification with rms adam optimizer # CHANGENEWLINENEWLINEmodel_pose.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc', f1_m, precision_m, recall_m])NEWLINENEWLINEmodel_pose.summary()NEWLINEfilepath = '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/15ft/direction_data_12_poses_2D_CNN_Mapping.wts.h5'NEWLINEprint("The dropout rate was: ")NEWLINEprint(dr)NEWLINENEWLINENEWLINE# Fit the modelNEWLINE# history= model.fit(xtrain, ytrain_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_data = (xtest, ytest_one_hot), callbacks = [keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'), keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINEhistory = model_pose.fit(xtrain_15ft, ytrain_15ft_one_hot, epochs=nb_epoch, batch_size=batch_size, validation_split=0.1, callbacks=[NEWLINE keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=2, save_best_only=True, mode='auto'),NEWLINE keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=2, mode='auto')])NEWLINENEWLINENEWLINE# Evaluate the modelNEWLINEloss, accuracy, f1_score, precision, recall = model_pose.evaluate(xtest_15ft, ytest_15ft_one_hot, batch_size=batch_size) # CHANGENEWLINEprint("\nTest Loss: %s: %.2f%%" % (model_pose.metrics_names[0], loss * 100)) # CHANGENEWLINEprint("\nTest Accuracy: %s: %.2f%%" % (model_pose.metrics_names[1], accuracy * 100)) # CHANGENEWLINEprint("\nTest F1 Score: %s: %.2f" % (model_pose.metrics_names[2], f1_score)) # CHANGENEWLINEprint("\nTest Precision: %s: %.2f%%" % (model_pose.metrics_names[3], precision * 100)) # CHANGENEWLINEprint("\nTest Recall: %s: %.2f%%" % (model_pose.metrics_names[4], recall * 100)) # CHANGENEWLINENEWLINE# Calculating total execution timeNEWLINEend_time = time.time() # Taking end time to calculate overall execution timeNEWLINEprint("\n Total Execution Time (Minutes): ")NEWLINEprint(((end_time - start_time) / 60))NEWLINENEWLINE#### SET PLOTTING PARAMETERS #########NEWLINEparams = {'legend.fontsize': 'xx-large',NEWLINE 'axes.labelsize': 'xx-large',NEWLINE 'axes.titlesize': 'xx-large',NEWLINE 'xtick.labelsize': 'xx-large',NEWLINE 'ytick.labelsize': 'xx-large'}NEWLINEplt.rcParams.update(params)NEWLINENEWLINENEWLINE# Show Accuracy CurvesNEWLINEfig = plt.figure()NEWLINE# plt.title('Training Performance')NEWLINEplt.plot(history.epoch, history.history['acc'], label='Training Accuracy', linewidth=2.0, c='b')NEWLINEplt.plot(history.epoch, history.history['val_acc'], label='Validation Accuracy', linewidth=2.0, c='r')NEWLINEplt.ylabel('Accuracy(%)')NEWLINEplt.xlabel('Epoch')NEWLINEplt.legend()NEWLINEplt.tight_layout()NEWLINEfig.savefig('/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/15ft/direction_12_poses_acc_2D_CNN_Mapping.png') # save the figure to fileNEWLINEplt.close(fig)NEWLINENEWLINENEWLINE# plt.show()NEWLINENEWLINENEWLINE# Plot confusion matrixNEWLINEtest_Y_hat = model_pose.predict(xtest_15ft, batch_size=batch_size)NEWLINEconf = np.zeros([len(classes), len(classes)])NEWLINEconfnorm = np.zeros([len(classes), len(classes)])NEWLINEfor i in range(0, xtest_15ft.shape[0]):NEWLINE j = list(ytest_15ft_one_hot[i, :]).index(1)NEWLINE k = int(np.argmax(test_Y_hat[i, :]))NEWLINE conf[j, k] = conf[j, k] + 1NEWLINEplot_confusion_matrix(conf, labels=classes, normalize=False, filedest= '/Users/debashri/Desktop/DirectionFinding_Plots/Indoor/15ft/direction_12_poses_conf_mat_2D_CNN_Mapping.png')NEWLINE from tkinter import *NEWLINEfrom new_main import semaphore_algoNEWLINENEWLINEwindow = Tk()NEWLINEwindow.title("Timetable Generation OS Project")NEWLINENEWLINENEWLINEclass ProvideException(object):NEWLINE def __init__(self, func):NEWLINE self._func = funcNEWLINENEWLINE def __call__(self, *args):NEWLINE try:NEWLINE return self._func(*args)NEWLINE except ValueError:NEWLINE print("Please enter Numerical values only")NEWLINE except KeyboardInterrupt:NEWLINE print("You hit a interrupt key like ' ctrl+c' or 'ctrl+v'. Please rerun the code. ")NEWLINENEWLINE@ProvideExceptionNEWLINEdef set_values():NEWLINE list_1 = [label3_1.get(), label3_2.get(), label3_3.get(), label3_4.get()] #Batch 1NEWLINE list_2 = [label4_1.get(), label4_2.get(), label4_3.get(), label4_4.get()] #Batch 2NEWLINE list_3 = [label5_1.get(), label5_2.get(), label5_3.get(), label5_4.get()] #Batch 3NEWLINE list_4 = [label6_1.get(), label6_2.get(), label6_3.get(), label6_4.get()] #Batch 4NEWLINE final_list = [list_1, list_2, list_3, list_4]NEWLINE print(list_1)NEWLINE print(list_2)NEWLINE print(list_3)NEWLINE print(list_4)NEWLINE print(final_list)NEWLINENEWLINE fac_list_1 = [] # Number of lectures by each batchNEWLINE fac_list_2 = []NEWLINE fac_list_3 = []NEWLINE fac_list_4 = []NEWLINENEWLINE for faculty_no in range(0, 4):NEWLINE x = int(final_list[faculty_no][0])NEWLINE for hour_cnt in range(0, x):NEWLINE fac_list_1.append(faculty_no)NEWLINENEWLINE x1 = int(final_list[faculty_no][1])NEWLINE for hour_cnt in range(0, x1):NEWLINE fac_list_2.append(faculty_no)NEWLINENEWLINE x2 = int(final_list[faculty_no][2])NEWLINE for hour_cnt in range(0, x2):NEWLINE fac_list_3.append(faculty_no)NEWLINENEWLINE x3 = int(final_list[faculty_no][3])NEWLINE for hour_cnt in range(0, x3):NEWLINE fac_list_4.append(faculty_no)NEWLINENEWLINE print(fac_list_1)NEWLINE print(fac_list_2)NEWLINE print(fac_list_3)NEWLINE print(fac_list_4)NEWLINENEWLINE semaphore_algo(fac_list_1, fac_list_2, fac_list_3, fac_list_4)NEWLINENEWLINENEWLINEtext1 = Label(window, text="Enter the faculty hours required for each branch")NEWLINEtext1.grid(row=0)NEWLINENEWLINEtext2 = Label(window, text="Branch Name")NEWLINEtext2_1 = Label(window, text="Faculty 1")NEWLINEtext2_2 = Label(window, text="Faculty 2")NEWLINEtext2_3 = Label(window, text="Faculty 3")NEWLINEtext2_4 = Label(window, text="Faculty 4")NEWLINEtext2.grid(row=1, column=0)NEWLINEtext2_1.grid(row=1, column=1)NEWLINEtext2_2.grid(row=1, column=2)NEWLINEtext2_3.grid(row=1, column=3)NEWLINEtext2_4.grid(row=1, column=4)NEWLINENEWLINEtext3 = Label(window, text="B.Tech CS")NEWLINElabel3_1 = Entry(window)NEWLINElabel3_2 = Entry(window)NEWLINElabel3_3 = Entry(window)NEWLINElabel3_4 = Entry(window)NEWLINEtext3.grid(row=2, column=0)NEWLINElabel3_1.grid(row=2, column=1)NEWLINElabel3_2.grid(row=2, column=2)NEWLINElabel3_3.grid(row=2, column=3)NEWLINElabel3_4.grid(row=2, column=4)NEWLINENEWLINEtext4 = Label(window, text="B.Tech IT")NEWLINElabel4_1 = Entry(window)NEWLINElabel4_2 = Entry(window)NEWLINElabel4_3 = Entry(window)NEWLINElabel4_4 = Entry(window)NEWLINEtext4.grid(row=3, column=0)NEWLINElabel4_1.grid(row=3, column=1)NEWLINElabel4_2.grid(row=3, column=2)NEWLINElabel4_3.grid(row=3, column=3)NEWLINElabel4_4.grid(row=3, column=4)NEWLINENEWLINEtext5 = Label(window, text="MBA.Tech CS")NEWLINElabel5_1 = Entry(window)NEWLINElabel5_2 = Entry(window)NEWLINElabel5_3 = Entry(window)NEWLINElabel5_4 = Entry(window)NEWLINEtext5.grid(row=4, column=0)NEWLINElabel5_1.grid(row=4, column=1)NEWLINElabel5_2.grid(row=4, column=2)NEWLINElabel5_3.grid(row=4, column=3)NEWLINElabel5_4.grid(row=4, column=4)NEWLINENEWLINEtext6 = Label(window, text="MBA.Tech IT")NEWLINElabel6_1 = Entry(window)NEWLINElabel6_2 = Entry(window)NEWLINElabel6_3 = Entry(window)NEWLINElabel6_4 = Entry(window)NEWLINEtext6.grid(row=5, column=0)NEWLINElabel6_1.grid(row=5, column=1)NEWLINElabel6_2.grid(row=5, column=2)NEWLINElabel6_3.grid(row=5, column=3)NEWLINElabel6_4.grid(row=5, column=4)NEWLINENEWLINEbutton1 = Button(window, text="Submit Request", command=set_values)NEWLINEbutton1.grid(row=6, column=2)NEWLINENEWLINEwindow.mainloop()NEWLINE from unittest import mockNEWLINENEWLINEimport pytestNEWLINENEWLINEfrom bgmi.lib.models import Bangumi, Filter, FollowedNEWLINEfrom bgmi.main import mainNEWLINEfrom bgmi.website.bangumi_moe import BangumiMoeNEWLINENEWLINENEWLINEdef test_gen_nginx_conf():NEWLINE main("gen nginx.conf --server-name _".split())NEWLINENEWLINENEWLINE@pytest.mark.usefixtures("_clean_bgmi")NEWLINEdef test_cal_force_update():NEWLINE class MockWebsite(BangumiMoe):NEWLINE def fetch_bangumi_calendar(self):NEWLINE bangumi = BangumiMoe().fetch_bangumi_calendar()NEWLINE bangumi[0].update_time = "Unknown"NEWLINE return bangumiNEWLINENEWLINE with mock.patch("bgmi.lib.controllers.website", MockWebsite()):NEWLINE main("cal -f".split())NEWLINE assert [NEWLINE x.name for x in Bangumi.select().where(Bangumi.update_time == "Unknown")NEWLINE ], "at least 1 bangumi's update_time is 'Unknown'"NEWLINENEWLINENEWLINEdef test_cal_config():NEWLINE main("config".split())NEWLINE main("config ADMIN_TOKEN 233".split())NEWLINE main("config DOWNLOAD_DELEGATE xunlei".split())NEWLINE main("config BANGUMI_MOE_URL https://bangumi.moe".split())NEWLINENEWLINENEWLINEdef test_add(bangumi_names):NEWLINE main(["add", *bangumi_names])NEWLINENEWLINENEWLINE@pytest.mark.usefixtures("_clean_bgmi")NEWLINEdef test_update(bangumi_names):NEWLINE main(["add", *bangumi_names])NEWLINE main(["update"])NEWLINENEWLINENEWLINE@pytest.mark.usefixtures("_clean_bgmi")NEWLINEdef test_update_single(bangumi_names):NEWLINE name = bangumi_names[0]NEWLINE main(f"add {name}".split())NEWLINE main(["update", name])NEWLINENEWLINENEWLINE@pytest.mark.usefixtures("_clean_bgmi")NEWLINEdef test_search(bangumi_names):NEWLINE main(["search", "海贼王", "--regex-filter", ".*MP4.*720P.*"])NEWLINENEWLINENEWLINE@pytest.mark.usefixtures("_clean_bgmi")NEWLINEdef test_delete(bangumi_names):NEWLINE name = bangumi_names[0]NEWLINE main(f"add {name} --episode 0".split())NEWLINE main(f"delete --name {name}".split())NEWLINENEWLINENEWLINE@pytest.mark.usefixtures("_clean_bgmi")NEWLINEdef test_delete_batch(bangumi_names):NEWLINE main(["add", *bangumi_names, "--episode", "0"])NEWLINE main("delete --clear-all --batch".split())NEWLINENEWLINENEWLINE@pytest.mark.usefixtures("_clean_bgmi")NEWLINEdef test_filter(bangumi_names):NEWLINE name = bangumi_names[0]NEWLINE main(f"add {name} --episode 0".split())NEWLINE main(["filter", name, "--subtitle", "", "--exclude", "MKV", "--regex", "720p|720P"])NEWLINE f = Filter.get(bangumi_name=name, exclude="MKV", regex="720p|720P")NEWLINE assert not f.includeNEWLINE assert not f.subtitleNEWLINENEWLINENEWLINE@pytest.mark.usefixtures("_clean_bgmi")NEWLINEdef test_fetch(bangumi_names):NEWLINE name = bangumi_names[0]NEWLINE main(f"add {name} --episode 0".split())NEWLINE main(f"fetch {name}".split())NEWLINENEWLINENEWLINE@pytest.mark.usefixtures("_clean_bgmi")NEWLINEdef test_mark(bangumi_names):NEWLINE name = bangumi_names[0]NEWLINE main(f"add {name} --episode 0".split())NEWLINE main(f"mark {name} 1".split())NEWLINE assert Followed.get(bangumi_name=name).episode == 1NEWLINE """DSM 7 SYNO.Core.* datas."""NEWLINE """NEWLINEMIT LicenseNEWLINENEWLINECopyright (c) 2020-present phenom4n4nNEWLINENEWLINEPermission is hereby granted, free of charge, to any person obtaining a copyNEWLINEof this software and associated documentation files (the "Software"), to dealNEWLINEin the Software without restriction, including without limitation the rightsNEWLINEto use, copy, modify, merge, publish, distribute, sublicense, and/or sellNEWLINEcopies of the Software, and to permit persons to whom the Software isNEWLINEfurnished to do so, subject to the following conditions:NEWLINENEWLINEThe above copyright notice and this permission notice shall be included in allNEWLINEcopies or substantial portions of the Software.NEWLINENEWLINETHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORNEWLINEIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,NEWLINEFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THENEWLINEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERNEWLINELIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,NEWLINEOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THENEWLINESOFTWARE.NEWLINE"""NEWLINENEWLINEimport loggingNEWLINEfrom collections import defaultdictNEWLINEfrom colorsys import rgb_to_hsvNEWLINEfrom typing import List, OptionalNEWLINENEWLINEimport discordNEWLINEfrom redbot.core import commandsNEWLINEfrom redbot.core.utils.chat_formatting import humanize_number as hnNEWLINEfrom redbot.core.utils.chat_formatting import pagify, text_to_fileNEWLINEfrom redbot.core.utils.mod import get_audit_reasonNEWLINEfrom TagScriptEngine import Interpreter, LooseVariableGetterBlock, MemberAdapterNEWLINENEWLINEfrom .abc import MixinMetaNEWLINEfrom .converters import FuzzyRole, StrictRole, TargeterArgs, TouchableMemberNEWLINEfrom .utils import (NEWLINE can_run_command,NEWLINE guild_roughly_chunked,NEWLINE humanize_roles,NEWLINE is_allowed_by_role_hierarchy,NEWLINE)NEWLINENEWLINElog = logging.getLogger("red.phenom4n4n.roleutils")NEWLINENEWLINENEWLINEdef targeter_cog(ctx: commands.Context):NEWLINE cog = ctx.bot.get_cog("Targeter")NEWLINE return cog is not None and hasattr(cog, "args_to_list")NEWLINENEWLINENEWLINEdef chunks(l, n):NEWLINE """NEWLINE Yield successive n-sized chunks from l.NEWLINE https://github.com/flaree/flare-cogs/blob/08b78e33ab814aa4da5422d81a5037ae3df51d4e/commandstats/commandstats.py#L16NEWLINE """NEWLINE for i in range(0, len(l), n):NEWLINE yield l[i : i + n]NEWLINENEWLINENEWLINEclass Roles(MixinMeta):NEWLINE """NEWLINE Useful role commands.NEWLINE """NEWLINENEWLINE def __init__(self):NEWLINE self.interpreter = Interpreter([LooseVariableGetterBlock()])NEWLINE super().__init__()NEWLINENEWLINE async def initialize(self):NEWLINE log.debug("Roles Initialize")NEWLINE await super().initialize()NEWLINENEWLINE @commands.guild_only()NEWLINE @commands.group(invoke_without_command=True)NEWLINE async def role(NEWLINE self, ctx: commands.Context, member: TouchableMember(False), *, role: StrictRole(False)NEWLINE ):NEWLINE """Base command for modifying roles.NEWLINENEWLINE Invoking this command will add or remove the given role from the member, depending on whether they already had it."""NEWLINE if role in member.roles and await can_run_command(ctx, "role remove"):NEWLINE com = self.bot.get_command("role remove")NEWLINE await ctx.invoke(NEWLINE com,NEWLINE member=member,NEWLINE role=role,NEWLINE )NEWLINE elif role not in member.roles and await can_run_command(ctx, "role add"):NEWLINE com = self.bot.get_command("role add")NEWLINE await ctx.invoke(NEWLINE com,NEWLINE member=member,NEWLINE role=role,NEWLINE )NEWLINE else:NEWLINE await ctx.send_help()NEWLINENEWLINE @commands.bot_has_permissions(embed_links=True)NEWLINE @role.command("info")NEWLINE async def role_info(self, ctx: commands.Context, *, role: FuzzyRole):NEWLINE """Get information about a role."""NEWLINE await ctx.send(embed=await self.get_info(role))NEWLINENEWLINE async def get_info(self, role: discord.Role) -> discord.Embed:NEWLINE if guild_roughly_chunked(role.guild) is False and self.bot.intents.members:NEWLINE await role.guild.chunk()NEWLINE description = [NEWLINE f"{role.mention}",NEWLINE f"Members: {len(role.members)} | Position: {role.position}",NEWLINE f"Color: {role.color}",NEWLINE f"Hoisted: {role.hoist}",NEWLINE f"Mentionable: {role.mentionable}",NEWLINE ]NEWLINE if role.managed:NEWLINE description.append(f"Managed: {role.managed}")NEWLINE if role in await self.bot.get_mod_roles(role.guild):NEWLINE description.append(f"Mod Role: True")NEWLINE if role in await self.bot.get_admin_roles(role.guild):NEWLINE description.append(f"Admin Role: True")NEWLINE e = discord.Embed(NEWLINE color=role.color,NEWLINE title=role.name,NEWLINE description="\n".join(description),NEWLINE timestamp=role.created_at,NEWLINE )NEWLINE e.set_footer(text=role.id)NEWLINE return eNEWLINENEWLINE def format_member(self, member: discord.Member, formatting: str) -> str:NEWLINE output = self.interpreter.process(formatting, {"member": MemberAdapter(member)})NEWLINE return output.bodyNEWLINENEWLINE @commands.bot_has_permissions(attach_files=True)NEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @role.command("members", aliases=["dump"])NEWLINE async def role_members(NEWLINE self,NEWLINE ctx: commands.Context,NEWLINE role: FuzzyRole,NEWLINE *,NEWLINE formatting: str = "{member} - {member(id)}",NEWLINE ):NEWLINE """NEWLINE Sends a list of members in a role.NEWLINENEWLINE You can supply a custom formatting tagscript for each member.NEWLINE The [member](https://phen-cogs.readthedocs.io/en/latest/tags/default_variables.html#author-block) block is available to use, found on the [TagScript documentation](https://phen-cogs.readthedocs.io/en/latest/index.html).NEWLINENEWLINE **Example:**NEWLINE `[p]role dump @admin - {member(mention)}`NEWLINE """NEWLINE if guild_roughly_chunked(ctx.guild) is False and self.bot.intents.members:NEWLINE await ctx.guild.chunk()NEWLINE if not role.members:NEWLINE return await ctx.send(f"**{role}** has no members.")NEWLINE members = "\n".join(self.format_member(member, formatting) for member in role.members)NEWLINE if len(members) > 2000:NEWLINE await ctx.send(file=text_to_file(members, f"members.txt"))NEWLINE else:NEWLINE await ctx.send(members, allowed_mentions=discord.AllowedMentions.none())NEWLINENEWLINE @staticmethodNEWLINE def get_hsv(role: discord.Role):NEWLINE return rgb_to_hsv(*role.color.to_rgb())NEWLINENEWLINE @commands.bot_has_permissions(embed_links=True)NEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @role.command("colors")NEWLINE async def role_colors(self, ctx: commands.Context):NEWLINE """Sends the server's roles, ordered by color."""NEWLINE roles = defaultdict(list)NEWLINE for r in ctx.guild.roles:NEWLINE roles[str(r.color)].append(r)NEWLINE roles = dict(sorted(roles.items(), key=lambda v: self.get_hsv(v[1][0])))NEWLINENEWLINE lines = [f"**{color}**\n{' '.join(r.mention for r in rs)}" for color, rs in roles.items()]NEWLINE for page in pagify("\n".join(lines)):NEWLINE e = discord.Embed(description=page)NEWLINE await ctx.send(embed=e)NEWLINENEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @role.command("create")NEWLINE async def role_create(NEWLINE self,NEWLINE ctx: commands.Context,NEWLINE color: Optional[discord.Color] = discord.Color.default(),NEWLINE hoist: Optional[bool] = False,NEWLINE *,NEWLINE name: str = None,NEWLINE ):NEWLINE """NEWLINE Creates a role.NEWLINENEWLINE Color and whether it is hoisted can be specified.NEWLINE """NEWLINE if len(ctx.guild.roles) >= 250:NEWLINE return await ctx.send("This server has reached the maximum role limit (250).")NEWLINENEWLINE role = await ctx.guild.create_role(name=name, colour=color, hoist=hoist)NEWLINE await ctx.send(f"**{role}** created!", embed=await self.get_info(role))NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command("color", aliases=["colour"])NEWLINE async def role_color(NEWLINE self, ctx: commands.Context, role: StrictRole(check_integrated=False), color: discord.ColorNEWLINE ):NEWLINE """Change a role's color."""NEWLINE await role.edit(color=color)NEWLINE await ctx.send(NEWLINE f"**{role}** color changed to **{color}**.", embed=await self.get_info(role)NEWLINE )NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command("hoist")NEWLINE async def role_hoist(NEWLINE self,NEWLINE ctx: commands.Context,NEWLINE role: StrictRole(check_integrated=False),NEWLINE hoisted: bool = None,NEWLINE ):NEWLINE """Toggle whether a role should appear seperate from other roles."""NEWLINE hoisted = hoisted if hoisted is not None else not role.hoistNEWLINE await role.edit(hoist=hoisted)NEWLINE now = "now" if hoisted else "no longer"NEWLINE await ctx.send(f"**{role}** is {now} hoisted.", embed=await self.get_info(role))NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command("name")NEWLINE async def role_name(NEWLINE self, ctx: commands.Context, role: StrictRole(check_integrated=False), *, name: strNEWLINE ):NEWLINE """Change a role's name."""NEWLINE old_name = role.nameNEWLINE await role.edit(name=name)NEWLINE await ctx.send(f"Changed **{old_name}** to **{name}**.", embed=await self.get_info(role))NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command("add")NEWLINE async def role_add(self, ctx: commands.Context, member: TouchableMember, *, role: StrictRole):NEWLINE """Add a role to a member."""NEWLINE if role in member.roles:NEWLINE await ctx.send(NEWLINE f"**{member}** already has the role **{role}**. Maybe try removing it instead."NEWLINE )NEWLINE returnNEWLINE reason = get_audit_reason(ctx.author)NEWLINE await member.add_roles(role, reason=reason)NEWLINE await ctx.send(f"Added **{role.name}** to **{member}**.")NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command("remove")NEWLINE async def role_remove(NEWLINE self, ctx: commands.Context, member: TouchableMember, *, role: StrictRoleNEWLINE ):NEWLINE """Remove a role from a member."""NEWLINE if role not in member.roles:NEWLINE await ctx.send(NEWLINE f"**{member}** doesn't have the role **{role}**. Maybe try adding it instead."NEWLINE )NEWLINE returnNEWLINE reason = get_audit_reason(ctx.author)NEWLINE await member.remove_roles(role, reason=reason)NEWLINE await ctx.send(f"Removed **{role.name}** from **{member}**.")NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command(require_var_positional=True)NEWLINE async def addmulti(self, ctx: commands.Context, role: StrictRole, *members: TouchableMember):NEWLINE """Add a role to multiple members."""NEWLINE reason = get_audit_reason(ctx.author)NEWLINE already_members = []NEWLINE success_members = []NEWLINE for member in members:NEWLINE if role not in member.roles:NEWLINE await member.add_roles(role, reason=reason)NEWLINE success_members.append(member)NEWLINE else:NEWLINE already_members.append(member)NEWLINE msg = []NEWLINE if success_members:NEWLINE msg.append(f"Added **{role}** to {humanize_roles(success_members)}.")NEWLINE if already_members:NEWLINE msg.append(f"{humanize_roles(already_members)} already had **{role}**.")NEWLINE await ctx.send("\n".join(msg))NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command(require_var_positional=True)NEWLINE async def removemulti(NEWLINE self, ctx: commands.Context, role: StrictRole, *members: TouchableMemberNEWLINE ):NEWLINE """Remove a role from multiple members."""NEWLINE reason = get_audit_reason(ctx.author)NEWLINE already_members = []NEWLINE success_members = []NEWLINE for member in members:NEWLINE if role in member.roles:NEWLINE await member.remove_roles(role, reason=reason)NEWLINE success_members.append(member)NEWLINE else:NEWLINE already_members.append(member)NEWLINE msg = []NEWLINE if success_members:NEWLINE msg.append(f"Removed **{role}** from {humanize_roles(success_members)}.")NEWLINE if already_members:NEWLINE msg.append(f"{humanize_roles(already_members)} didn't have **{role}**.")NEWLINE await ctx.send("\n".join(msg))NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @commands.group(invoke_without_command=True, require_var_positional=True)NEWLINE async def multirole(self, ctx: commands.Context, member: TouchableMember, *roles: StrictRole):NEWLINE """Add multiple roles to a member."""NEWLINE not_allowed = []NEWLINE already_added = []NEWLINE to_add = []NEWLINE for role in roles:NEWLINE allowed = await is_allowed_by_role_hierarchy(self.bot, ctx.me, ctx.author, role)NEWLINE if not allowed[0]:NEWLINE not_allowed.append(role)NEWLINE elif role in member.roles:NEWLINE already_added.append(role)NEWLINE else:NEWLINE to_add.append(role)NEWLINE reason = get_audit_reason(ctx.author)NEWLINE msg = []NEWLINE if to_add:NEWLINE await member.add_roles(*to_add, reason=reason)NEWLINE msg.append(f"Added {humanize_roles(to_add)} to **{member}**.")NEWLINE if already_added:NEWLINE msg.append(f"**{member}** already had {humanize_roles(already_added)}.")NEWLINE if not_allowed:NEWLINE msg.append(NEWLINE f"You do not have permission to assign the roles {humanize_roles(not_allowed)}."NEWLINE )NEWLINE await ctx.send("\n".join(msg))NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @multirole.command("remove", require_var_positional=True)NEWLINE async def multirole_remove(NEWLINE self, ctx: commands.Context, member: TouchableMember, *roles: StrictRoleNEWLINE ):NEWLINE """Remove multiple roles from a member."""NEWLINE not_allowed = []NEWLINE not_added = []NEWLINE to_rm = []NEWLINE for role in roles:NEWLINE allowed = await is_allowed_by_role_hierarchy(self.bot, ctx.me, ctx.author, role)NEWLINE if not allowed[0]:NEWLINE not_allowed.append(role)NEWLINE elif role not in member.roles:NEWLINE not_added.append(role)NEWLINE else:NEWLINE to_rm.append(role)NEWLINE reason = get_audit_reason(ctx.author)NEWLINE msg = []NEWLINE if to_rm:NEWLINE await member.remove_roles(*to_rm, reason=reason)NEWLINE msg.append(f"Removed {humanize_roles(to_rm)} from **{member}**.")NEWLINE if not_added:NEWLINE msg.append(f"**{member}** didn't have {humanize_roles(not_added)}.")NEWLINE if not_allowed:NEWLINE msg.append(NEWLINE f"You do not have permission to assign the roles {humanize_roles(not_allowed)}."NEWLINE )NEWLINE await ctx.send("\n".join(msg))NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command()NEWLINE async def all(self, ctx: commands.Context, *, role: StrictRole):NEWLINE """Add a role to all members of the server."""NEWLINE await self.super_massrole(ctx, ctx.guild.members, role)NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command(aliases=["removeall"])NEWLINE async def rall(self, ctx: commands.Context, *, role: StrictRole):NEWLINE """Remove a role from all members of the server."""NEWLINE member_list = self.get_member_list(ctx.guild.members, role, False)NEWLINE await self.super_massrole(NEWLINE ctx, member_list, role, "No one on the server has this role.", FalseNEWLINE )NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command()NEWLINE async def humans(self, ctx: commands.Context, *, role: StrictRole):NEWLINE """Add a role to all humans (non-bots) in the server."""NEWLINE await self.super_massrole(NEWLINE ctx,NEWLINE [member for member in ctx.guild.members if not member.bot],NEWLINE role,NEWLINE "Every human in the server has this role.",NEWLINE )NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command()NEWLINE async def rhumans(self, ctx: commands.Context, *, role: StrictRole):NEWLINE """Remove a role from all humans (non-bots) in the server."""NEWLINE await self.super_massrole(NEWLINE ctx,NEWLINE [member for member in ctx.guild.members if not member.bot],NEWLINE role,NEWLINE "None of the humans in the server have this role.",NEWLINE False,NEWLINE )NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command()NEWLINE async def bots(self, ctx: commands.Context, *, role: StrictRole):NEWLINE """Add a role to all bots in the server."""NEWLINE await self.super_massrole(NEWLINE ctx,NEWLINE [member for member in ctx.guild.members if member.bot],NEWLINE role,NEWLINE "Every bot in the server has this role.",NEWLINE )NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command()NEWLINE async def rbots(self, ctx: commands.Context, *, role: StrictRole):NEWLINE """Remove a role from all bots in the server."""NEWLINE await self.super_massrole(NEWLINE ctx,NEWLINE [member for member in ctx.guild.members if member.bot],NEWLINE role,NEWLINE "None of the bots in the server have this role.",NEWLINE False,NEWLINE )NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command("in")NEWLINE async def role_in(NEWLINE self, ctx: commands.Context, target_role: FuzzyRole, *, add_role: StrictRoleNEWLINE ):NEWLINE """Add a role to all members of a another role."""NEWLINE await self.super_massrole(NEWLINE ctx,NEWLINE [member for member in target_role.members],NEWLINE add_role,NEWLINE f"Every member of **{target_role}** has this role.",NEWLINE )NEWLINENEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.command("rin")NEWLINE async def role_rin(NEWLINE self, ctx: commands.Context, target_role: FuzzyRole, *, remove_role: StrictRoleNEWLINE ):NEWLINE """Remove a role from all members of a another role."""NEWLINE await self.super_massrole(NEWLINE ctx,NEWLINE [member for member in target_role.members],NEWLINE remove_role,NEWLINE f"No one in **{target_role}** has this role.",NEWLINE False,NEWLINE )NEWLINENEWLINE @commands.check(targeter_cog)NEWLINE @commands.has_guild_permissions(manage_roles=True)NEWLINE @commands.bot_has_permissions(manage_roles=True)NEWLINE @role.group()NEWLINE async def target(self, ctx: commands.Context):NEWLINE """NEWLINE Modify roles using 'targeting' args.NEWLINENEWLINE An explanation of Targeter and test commands to preview the members affected can be found with `[p]target`.NEWLINE """NEWLINENEWLINE @target.command("add")NEWLINE async def target_add(self, ctx: commands.Context, role: StrictRole, *, args: TargeterArgs):NEWLINE """NEWLINE Add a role to members using targeting args.NEWLINENEWLINE An explanation of Targeter and test commands to preview the members affected can be found with `[p]target`.NEWLINE """NEWLINE await self.super_massrole(NEWLINE ctx,NEWLINE args,NEWLINE role,NEWLINE f"No one was found with the given args that was eligible to recieve **{role}**.",NEWLINE )NEWLINENEWLINE @target.command("remove")NEWLINE async def target_remove(self, ctx: commands.Context, role: StrictRole, *, args: TargeterArgs):NEWLINE """NEWLINE Remove a role from members using targeting args.NEWLINENEWLINE An explanation of Targeter and test commands to preview the members affected can be found with `[p]target`.NEWLINE """NEWLINE await self.super_massrole(NEWLINE ctx,NEWLINE args,NEWLINE role,NEWLINE f"No one was found with the given args that was eligible have **{role}** removed from them.",NEWLINE False,NEWLINE )NEWLINENEWLINE async def super_massrole(NEWLINE self,NEWLINE ctx: commands.Context,NEWLINE members: list,NEWLINE role: discord.Role,NEWLINE fail_message: str = "Everyone in the server has this role.",NEWLINE adding: bool = True,NEWLINE ):NEWLINE if guild_roughly_chunked(ctx.guild) is False and self.bot.intents.members:NEWLINE await ctx.guild.chunk()NEWLINE member_list = self.get_member_list(members, role, adding)NEWLINE if not member_list:NEWLINE await ctx.send(fail_message)NEWLINE returnNEWLINE verb = "add" if adding else "remove"NEWLINE word = "to" if adding else "from"NEWLINE await ctx.send(NEWLINE f"Beginning to {verb} **{role.name}** {word} **{len(member_list)}** members."NEWLINE )NEWLINE async with ctx.typing():NEWLINE result = await self.massrole(member_list, [role], get_audit_reason(ctx.author), adding)NEWLINE result_text = f"{verb.title()[:5]}ed **{role.name}** {word} **{len(result['completed'])}** members."NEWLINE if result["skipped"]:NEWLINE result_text += (NEWLINE f"\nSkipped {verb[:5]}ing roles for **{len(result['skipped'])}** members."NEWLINE )NEWLINE if result["failed"]:NEWLINE result_text += (NEWLINE f"\nFailed {verb[:5]}ing roles for **{len(result['failed'])}** members."NEWLINE )NEWLINE await ctx.send(result_text)NEWLINENEWLINE def get_member_list(self, members: list, role: discord.Role, adding: bool = True):NEWLINE if adding:NEWLINE members = [member for member in members if role not in member.roles]NEWLINE else:NEWLINE members = [member for member in members if role in member.roles]NEWLINE return membersNEWLINENEWLINE async def massrole(self, members: list, roles: list, reason: str, adding: bool = True):NEWLINE completed = []NEWLINE skipped = []NEWLINE failed = []NEWLINE for member in members:NEWLINE if adding:NEWLINE to_add = [role for role in roles if role not in member.roles]NEWLINE if to_add:NEWLINE try:NEWLINE await member.add_roles(*to_add, reason=reason)NEWLINE except Exception as e:NEWLINE failed.append(member)NEWLINE log.exception(f"Failed to add roles to {member}", exc_info=e)NEWLINE else:NEWLINE completed.append(member)NEWLINE else:NEWLINE skipped.append(member)NEWLINE else:NEWLINE to_remove = [role for role in roles if role in member.roles]NEWLINE if to_remove:NEWLINE try:NEWLINE await member.remove_roles(*to_remove, reason=reason)NEWLINE except Exception as e:NEWLINE failed.append(member)NEWLINE log.exception(f"Failed to remove roles from {member}", exc_info=e)NEWLINE else:NEWLINE completed.append(member)NEWLINE else:NEWLINE skipped.append(member)NEWLINE return {"completed": completed, "skipped": skipped, "failed": failed}NEWLINENEWLINE @staticmethodNEWLINE def format_members(members: List[discord.Member]):NEWLINE length = len(members)NEWLINE s = "" if length == 1 else "s"NEWLINE return f"**{hn(length)}** member{s}"NEWLINENEWLINE @role.command("uniquemembers", aliases=["um"], require_var_positional=True)NEWLINE async def role_uniquemembers(self, ctx: commands.Context, *roles: FuzzyRole):NEWLINE """NEWLINE View the total unique members between multiple roles.NEWLINE """NEWLINE roles_length = len(roles)NEWLINE if roles_length == 1:NEWLINE raise commands.UserFeedbackCheckFailure("You must provide at least 2 roles.")NEWLINE if not ctx.guild.chunked:NEWLINE await ctx.guild.chunk()NEWLINE color = roles[0].colorNEWLINE unique_members = set()NEWLINE description = []NEWLINE for role in roles:NEWLINE unique_members.update(role.members)NEWLINE description.append(f"{role.mention}: {self.format_members(role.members)}")NEWLINE description.insert(0, f"**Unique members**: {self.format_members(unique_members)}")NEWLINE e = discord.Embed(NEWLINE color=color,NEWLINE title=f"Unique members between {roles_length} roles",NEWLINE description="\n".join(description),NEWLINE )NEWLINE ref = ctx.message.to_reference(fail_if_not_exists=False)NEWLINE await ctx.send(embed=e, reference=ref)NEWLINE # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINEimport argparseNEWLINEimport osNEWLINEimport randomNEWLINEimport timeNEWLINEimport mathNEWLINEimport sysNEWLINEfrom functools import partialNEWLINENEWLINEimport numpy as npNEWLINEimport paddleNEWLINENEWLINEimport paddlenlp as ppnlpNEWLINEfrom paddlenlp.transformers import LinearDecayWithWarmupNEWLINEfrom paddlenlp.metrics import ChunkEvaluatorNEWLINEfrom paddlenlp.datasets import load_datasetNEWLINEfrom paddlenlp.data import Stack, Tuple, PadNEWLINEfrom paddlenlp.utils.log import loggerNEWLINENEWLINE# from paddlenlp.trainer.trainer_base import TrainerBaseNEWLINEsys.path.insert(0, os.path.abspath("."))NEWLINEfrom utils import DictNEWLINENEWLINENEWLINEdef tokenize_and_align_labels(example, tokenizer, no_entity_id,NEWLINE max_seq_len=512):NEWLINE labels = example['labels']NEWLINE example = example['tokens']NEWLINE tokenized_input = tokenizer(NEWLINE example,NEWLINE is_split_into_words=True,NEWLINE max_seq_len=max_seq_len, )NEWLINENEWLINE # -2 for [CLS] and [SEP]NEWLINE if len(tokenized_input['input_ids']) - 2 < len(labels):NEWLINE labels = labels[:len(tokenized_input['input_ids']) - 2]NEWLINE tokenized_input['labels'] = [no_entity_id] + labels + [no_entity_id]NEWLINE tokenized_input['labels'] += [no_entity_id] * (NEWLINE len(tokenized_input['input_ids']) - len(tokenized_input['labels']))NEWLINENEWLINE return tokenized_inputNEWLINENEWLINENEWLINEdef ner_collator(tokenizer, args):NEWLINE batchify_fn = lambda samples, fn=Dict({NEWLINE 'input_ids': Pad(axis=0, pad_val=tokenizer.pad_token_id, dtype='int32'), # inputNEWLINE 'token_type_ids': Pad(axis=0, pad_val=tokenizer.pad_token_type_id, dtype='int32'), # segmentNEWLINE 'labels': Pad(axis=0, pad_val=args.ignore_label, dtype='int64') # labelNEWLINE }): fn(samples)NEWLINENEWLINE return batchify_fnNEWLINENEWLINENEWLINEdef ner_trans_fn(example, tokenizer, args):NEWLINE return tokenize_and_align_labels(NEWLINE example,NEWLINE tokenizer=tokenizer,NEWLINE no_entity_id=args.no_entity_id,NEWLINE max_seq_len=args.max_seq_length)NEWLINE #!/usr/bin/env python2.7NEWLINENEWLINEimport argparseNEWLINEimport randomNEWLINEimport reNEWLINEimport stringNEWLINENEWLINEparser = argparse.ArgumentParser(description='Email Campaign Formatter')NEWLINEparser.add_argument('-s', action="store", dest='subject', default="CHANGE SUBJECT", help="email subject surrounded by double-quotes")NEWLINEparser.add_argument('-d', action="store", dest='domain', default='127.0.0.1', help='FQDN emails come from')NEWLINEparser.add_argument('-u', action="store", dest='username', default='jdoe', help='sender short email name')NEWLINEparser.add_argument('-f', action="store", dest='firstname', default='John', help='first name of sender')NEWLINEparser.add_argument('-l', action="store", dest='lastname', default='Doe', help='last name of sender')NEWLINEparser.add_argument('-e', action="store", dest='email', default=[], help='plain text email body file')NEWLINEparser.add_argument('-S', action="store", dest='signature', default=[], help='plain text signature file')NEWLINEparser.add_argument('-L', action="store", dest='link', default='', help='HTA link')NEWLINEparser.add_argument('-P', action="store", dest='pixel', default='', help='pixel link')NEWLINENEWLINEresults = parser.parse_args()NEWLINENEWLINEboundaryID = ''.join(random.SystemRandom().choice(string.digits + string.ascii_lowercase + string.digits) for _ in range(28))NEWLINENEWLINEheader = '\nMIME-Version: 1.0\n'NEWLINEheader += 'Subject: ' + results.subject + '\n'NEWLINEheader += 'From: ' + results.firstname + ' ' + results.lastname + ' <' + results.username + "@" + results.domain + '>' + '\n'NEWLINEheader += 'Content-Type: multipart/alternative; boundary=' + boundaryID + '\n'NEWLINENEWLINEaltTextContent = '\n--' + boundaryID + '\n'NEWLINEaltTextContent += 'Content-Type: text/plain; charset="UTF-8"\n\n'NEWLINENEWLINEhttpContent = '\n--' + boundaryID + '\n'NEWLINEhttpContent += 'Content-Type: text/html; charset="UTF-8"\n'NEWLINEhttpContent += 'Content-Transfer-Encoding: quoted-printable\n\n'NEWLINENEWLINEfooter = '\n\n--' + boundaryID + '--\n'NEWLINENEWLINEbody = ''NEWLINEbodyDiv = '
'NEWLINEwith open(results.email) as f:NEWLINE for line in f:NEWLINE body += lineNEWLINE bodyDiv += '
' + "
".join(line.split("\n")) + '
'NEWLINENEWLINEif results.link == '':NEWLINE with open(results.signature) as f:NEWLINE for line in f:NEWLINE body += lineNEWLINE bodyDiv += '
' + "
".join(line.split("\n")) + '
'NEWLINEelse:NEWLINE body += results.link + '\n'NEWLINE bodyDiv += '' + results.link + ""NEWLINE with open(results.signature) as f:NEWLINE for line in f:NEWLINE body += lineNEWLINE bodyDiv += '
' + "
".join(line.split("\n")) + '
'NEWLINENEWLINEif results.pixel == '':NEWLINE bodyDiv += '
' + "
".join(line.split("\n")) + '
'NEWLINEelse:NEWLINE context = ''NEWLINE bodyDiv += '
' + "
".join(line.split("\n")) + context + '
'NEWLINENEWLINEbodyDiv += "
"NEWLINEbodyHTTP = "=\n".join(re.findall("(?s).{,68}", bodyDiv))[:-1]NEWLINEemail = header + altTextContent +body + httpContent + bodyHTTP + footerNEWLINENEWLINEprint(email)NEWLINE from ..base.event import BaseEventNEWLINENEWLINENEWLINEclass ItemPurchase(BaseEvent):NEWLINE amount: floatNEWLINE username: strNEWLINE item_id: strNEWLINE r"""NEWLINEModule for some integrators.NEWLINENEWLINE - IRK3: Implicit third order Runge-KuttaNEWLINE - RK4: Runge-Kutta fourth orderNEWLINE - ETD: Exponential time differencing Euler methodNEWLINE - ETDRK4: Exponential time differencing Runge-Kutta fourth orderNEWLINENEWLINESee, e.g.,NEWLINEH. Montanelli and N. Bootland "Solving periodic semilinear PDEs in 1D, 2D andNEWLINE3D with exponential integrators", https://arxiv.org/pdf/1604.08900.pdfNEWLINENEWLINEIntegrators are set up to solve equations likeNEWLINENEWLINE.. math::NEWLINENEWLINE \frac{\partial u}{\partial t} = L u + N(u)NEWLINENEWLINEwhere :math:`u` is the solution, :math:`L` is a linear operator andNEWLINE:math:`N(u)` is the nonlinear part of the right hand side.NEWLINENEWLINENoteNEWLINE----NEWLINE`RK4`, `ETD` and `ETDRK4` can only be used with Fourier function spaces,NEWLINEas they assume all matrices are diagonal.NEWLINENEWLINE"""NEWLINEimport typesNEWLINEimport numpy as npNEWLINEfrom shenfun import Function, TPMatrix, TrialFunction, TestFunction,\NEWLINE inner, la, Expr, CompositeSpace, BlockMatrix, extract_bc_matrices,\NEWLINE SparseMatrix, get_simplified_tpmatrices, ScipyMatrixNEWLINENEWLINE__all__ = ('IRK3', 'BackwardEuler', 'RK4', 'ETDRK4', 'ETD')NEWLINENEWLINE#pylint: disable=unused-variableNEWLINENEWLINEclass IntegratorBase:NEWLINE """Abstract base class for integratorsNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : functionNEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINENEWLINE """NEWLINENEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE _p = {'dt': 0}NEWLINE _p.update(params)NEWLINE self.params = _pNEWLINE self.T = TNEWLINE if L is not None:NEWLINE self.LinearRHS = types.MethodType(L, self)NEWLINE if N is not None:NEWLINE self.NonlinearRHS = types.MethodType(N, self)NEWLINE if update is not None:NEWLINE self.update = types.MethodType(update, self)NEWLINENEWLINE def update(self, u, u_hat, t, tstep, **par):NEWLINE passNEWLINENEWLINE def LinearRHS(self, *args, **kwargs):NEWLINE return 0NEWLINENEWLINE def NonlinearRHS(self, *args, **kwargs):NEWLINE return 0NEWLINENEWLINE def setup(self, dt):NEWLINE """Set up solver"""NEWLINE passNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE """Integrate forward in timeNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE u : arrayNEWLINE The solution array in physical spaceNEWLINE u_hat : arrayNEWLINE The solution array in spectral spaceNEWLINE dt : floatNEWLINE TimestepNEWLINE trange : two-tupleNEWLINE Time and end timeNEWLINE """NEWLINE passNEWLINENEWLINENEWLINEclass IRK3(IntegratorBase):NEWLINE """Third order implicit Runge KuttaNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : function of TrialFunction(T)NEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINENEWLINE """NEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.dU = Function(T)NEWLINE self.dU1 = Function(T)NEWLINE self.a = (8./15., 5./12., 3./4.)NEWLINE self.b = (0.0, -17./60., -5./12.)NEWLINE self.c = (0.0, 8./15., 2./3., 1)NEWLINE self.solver = NoneNEWLINE self.bm = NoneNEWLINE self.rhs_mats = NoneNEWLINE self.w0 = Function(self.T)NEWLINE self.mask = NoneNEWLINE if hasattr(T, 'get_mask_nyquist'):NEWLINE self.mask = T.get_mask_nyquist()NEWLINENEWLINE def setup(self, dt):NEWLINE if isinstance(self.T, CompositeSpace):NEWLINE assert self.T.tensor_rank > 0, 'IRK3 only works for tensors, not generic CompositeSpaces'NEWLINENEWLINE self.params['dt'] = dtNEWLINE u = TrialFunction(self.T)NEWLINE v = TestFunction(self.T)NEWLINENEWLINE # Note that we are here assembling implicit left hand side matrices,NEWLINE # as well as matrices that can be used to assemble the right hand sideNEWLINE # much faster through matrix-vector productsNEWLINENEWLINE a, b = self.a, self.bNEWLINE self.solver = []NEWLINE self.rhs_mats = []NEWLINE u0 = self.LinearRHS(u)NEWLINE for rk in range(3):NEWLINE if u0:NEWLINE mats = inner(v, u-((a[rk]+b[rk])*dt/2)*u0)NEWLINE else:NEWLINE mats = inner(v, u)NEWLINE if self.T.dimensions == 1:NEWLINE self.solver.append(la.Solver(mats))NEWLINENEWLINE elif self.T.tensor_rank == 0:NEWLINE if len(mats[0].naxes) == 1:NEWLINE self.solver.append(la.SolverGeneric1ND(mats))NEWLINE elif len(mats[0].naxes) == 2:NEWLINE self.solver.append(la.SolverGeneric2ND(mats))NEWLINE else:NEWLINE raise NotImplementedErrorNEWLINE else:NEWLINE self.solver.append(BlockMatrixSolver(mats))NEWLINENEWLINE if u0:NEWLINE rhs_mats = inner(v, u+((a[rk]+b[rk])*dt/2)*u0)NEWLINE else:NEWLINE rhs_mats = inner(v, u)NEWLINE mat = ScipyMatrix if self.T.dimensions == 1 else BlockMatrixNEWLINE self.rhs_mats.append(mat(rhs_mats))NEWLINENEWLINE def compute_rhs(self, u, u_hat, dU, dU1, rk):NEWLINE a = self.a[rk]NEWLINE b = self.b[rk]NEWLINE dt = self.params['dt']NEWLINE dU = self.NonlinearRHS(u, u_hat, dU, **self.params)NEWLINE if self.mask:NEWLINE dU.mask_nyquist(self.mask)NEWLINE w1 = dU*a*dt + dU1*b*dtNEWLINE dU1[:] = dUNEWLINE if isinstance(dU, np.ndarray):NEWLINE dU[:] = w1NEWLINE return dUNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE if self.solver is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = self.tstep = 0NEWLINE while t < end_time-1e-8:NEWLINE self.tstep = tstepNEWLINE for rk in range(3):NEWLINE self.params['ti'] = t+self.c[rk]*dtNEWLINE dU = self.compute_rhs(u, u_hat, self.dU, self.dU1, rk)NEWLINE dU += self.rhs_mats[rk].matvec(u_hat, self.w0)NEWLINE u_hat = self.solver[rk](dU, u=u_hat)NEWLINE if self.mask:NEWLINE u_hat.mask_nyquist(self.mask)NEWLINENEWLINE t += dtNEWLINE tstep += 1NEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINENEWLINEclass BackwardEuler(IntegratorBase):NEWLINE """First order backward EulerNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : function of TrialFunction(T)NEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINENEWLINE """NEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.dU = Function(T)NEWLINE self.dU1 = Function(T)NEWLINE self.solver = NoneNEWLINE self.rhs_mats = NoneNEWLINE self.w0 = Function(self.T)NEWLINE self.mask = NoneNEWLINE if hasattr(T, 'get_mask_nyquist'):NEWLINE self.mask = T.get_mask_nyquist()NEWLINENEWLINE def setup(self, dt):NEWLINE if isinstance(self.T, CompositeSpace):NEWLINE assert self.T.tensor_rank > 0, 'BackwardEuler only works for tensors, not generic CompositeSpaces'NEWLINENEWLINE self.params['dt'] = dtNEWLINE u = TrialFunction(self.T)NEWLINE v = TestFunction(self.T)NEWLINE mats = inner(u-dt*self.LinearRHS(u), v)NEWLINE M = inner(u, v)NEWLINENEWLINE if self.T.dimensions == 1:NEWLINE self.solver = la.Solve(mats)NEWLINE self.rhs_mats = MNEWLINE returnNEWLINENEWLINE if self.T.tensor_rank == 0:NEWLINE if len(mats[0].naxes) == 1:NEWLINE self.solver = la.SolverGeneric1ND(mats)NEWLINE elif len(mats[0].naxes) == 2:NEWLINE self.solver = la.SolverGeneric2ND(mats)NEWLINE else:NEWLINE raise NotImplementedErrorNEWLINE else:NEWLINE self.solver = BlockMatrixSolver(mats)NEWLINE self.rhs_mats = BlockMatrix(M if isinstance(M, list) else [M])NEWLINENEWLINE def compute_rhs(self, u, u_hat, dU, dU1):NEWLINE dt = self.params['dt']NEWLINE dU = self.NonlinearRHS(u, u_hat, dU, **self.params)NEWLINE if self.mask:NEWLINE dU.mask_nyquist(self.mask)NEWLINE w1 = dU*2*dt - dU1*dtNEWLINE dU1[:] = dUNEWLINE return w1NEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE if self.solver is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = self.tstep = 0NEWLINE while t < end_time-1e-8:NEWLINE self.params['ti'] = tNEWLINE self.tstep = tstepNEWLINE dU = self.compute_rhs(u, u_hat, self.dU, self.dU1)NEWLINE dU += self.rhs_mats.matvec(u_hat, self.w0)NEWLINE u_hat = self.solver(dU, u=u_hat)NEWLINE if self.mask:NEWLINE u_hat.mask_nyquist(self.mask)NEWLINE t += dtNEWLINE tstep += 1NEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINENEWLINENEWLINEclass ETD(IntegratorBase):NEWLINE """Exponential time differencing Euler methodNEWLINENEWLINE H. Montanelli and N. Bootland "Solving periodic semilinear PDEs in 1D, 2D andNEWLINE 3D with exponential integrators", https://arxiv.org/pdf/1604.08900.pdfNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : functionNEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINE """NEWLINENEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.dU = Function(T)NEWLINE self.psi = NoneNEWLINE self.ehL = NoneNEWLINENEWLINE def setup(self, dt):NEWLINE """Set up ETD ODE solver"""NEWLINE self.params['dt'] = dtNEWLINE u = TrialFunction(self.T)NEWLINE v = TestFunction(self.T)NEWLINE L = self.LinearRHS(u, **self.params)NEWLINE if isinstance(L, Expr):NEWLINE L = inner(v, L)NEWLINE L = get_simplified_tpmatrices(L)[0]NEWLINE if isinstance(L, list):NEWLINE assert self.T.tensor_rank == 1NEWLINE assert L[0].isidentity()NEWLINE L = L[0].scaleNEWLINE # Use only L[0] and let numpy broadcasting take care of the restNEWLINE elif isinstance(L, TPMatrix):NEWLINE assert L.isidentity()NEWLINE L = L.scaleNEWLINE elif isinstance(L, SparseMatrix):NEWLINE L.simplify_diagonal_matrices()NEWLINE L = L.scaleNEWLINENEWLINE L = np.atleast_1d(L)NEWLINE hL = L*dtNEWLINE self.ehL = np.exp(hL)NEWLINE M = 50NEWLINE psi = self.psi = np.zeros(hL.shape, dtype=float)NEWLINE for k in range(1, M+1):NEWLINE ll = hL+np.exp(np.pi*1j*(k-0.5)/M)NEWLINE psi += ((np.exp(ll)-1.)/ll).realNEWLINE psi /= MNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE """Integrate forward in timeNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE u : arrayNEWLINE The solution array in physical spaceNEWLINE u_hat : arrayNEWLINE The solution array in spectral spaceNEWLINE dt : floatNEWLINE TimestepNEWLINE trange : two-tupleNEWLINE Time and end timeNEWLINE """NEWLINE if self.psi is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = 0NEWLINE while t < end_time-1e-8:NEWLINE t += dtNEWLINE tstep += 1NEWLINE self.dU = self.NonlinearRHS(u, u_hat, self.dU, **self.params)NEWLINE u_hat[:] = self.ehL*u_hat + dt*self.psi*self.dUNEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINE return u_hatNEWLINENEWLINENEWLINEclass ETDRK4(IntegratorBase):NEWLINE """Exponential time differencing Runge-Kutta 4'th order methodNEWLINENEWLINE H. Montanelli and N. Bootland "Solving periodic semilinear PDEs in 1D, 2D andNEWLINE 3D with exponential integrators", https://arxiv.org/pdf/1604.08900.pdfNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : functionNEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINE """NEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.U_hat0 = Function(T)NEWLINE self.U_hat1 = Function(T)NEWLINE self.dU = Function(T)NEWLINE self.dU0 = Function(T)NEWLINE self.V2 = Function(T)NEWLINE self.psi = np.zeros((4,)+self.U_hat0.shape, dtype=float)NEWLINE self.a = NoneNEWLINE self.b = [0.5, 0.5, 0.5]NEWLINE self.ehL = NoneNEWLINE self.ehL_h = NoneNEWLINENEWLINE def setup(self, dt):NEWLINE """Set up ETDRK4 ODE solver"""NEWLINE self.params['dt'] = dtNEWLINE u = TrialFunction(self.T)NEWLINE v = TestFunction(self.T)NEWLINE L = self.LinearRHS(u, **self.params)NEWLINE if isinstance(L, Expr):NEWLINE L = inner(v, L)NEWLINE L = get_simplified_tpmatrices(L)[0]NEWLINE if isinstance(L, list):NEWLINE assert self.T.tensor_rank == 1NEWLINE assert L[0].isidentity()NEWLINE L = L[0].scaleNEWLINE # Use only L[0] and let numpy broadcasting take care of the restNEWLINE elif isinstance(L, TPMatrix):NEWLINE assert L.isidentity()NEWLINE L = L.scaleNEWLINE elif isinstance(L, SparseMatrix):NEWLINE L.simplify_diagonal_matrices()NEWLINE L = L.scaleNEWLINENEWLINE L = np.atleast_1d(L)NEWLINE hL = L*dtNEWLINE self.ehL = np.exp(hL)NEWLINE self.ehL_h = np.exp(hL/2.)NEWLINE M = 50NEWLINE psi = self.psi = np.zeros((4,) + hL.shape, dtype=float)NEWLINE for k in range(1, M+1):NEWLINE ll = hL+np.exp(np.pi*1j*(k-0.5)/M)NEWLINE psi[0] += ((np.exp(ll)-1.)/ll).realNEWLINE psi[1] += ((np.exp(ll)-ll-1.)/ll**2).realNEWLINE psi[2] += ((np.exp(ll)-0.5*ll**2-ll-1.)/ll**3).realNEWLINE ll2 = hL/2.+np.exp(np.pi*1j*(k-0.5)/M)NEWLINE psi[3] += ((np.exp(ll2)-1.)/(ll2)).realNEWLINENEWLINE psi /= MNEWLINE a = [psi[0]-3*psi[1]+4*psi[2]]NEWLINE a.append(2*psi[1]-4*psi[2])NEWLINE a.append(2*psi[1]-4*psi[2])NEWLINE a.append(-psi[1]+4*psi[2])NEWLINE self.a = aNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE """Integrate forward in timeNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE u : arrayNEWLINE The solution array in physical spaceNEWLINE u_hat : arrayNEWLINE The solution array in spectral spaceNEWLINE dt : floatNEWLINE TimestepNEWLINE trange : two-tupleNEWLINE Time and end timeNEWLINE """NEWLINE if self.a is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = 0NEWLINE while t < end_time-1e-8:NEWLINE t += dtNEWLINE tstep += 1NEWLINENEWLINE self.U_hat0[:] = u_hat*self.ehL_hNEWLINE self.U_hat1[:] = u_hat*self.ehLNEWLINE for rk in range(4):NEWLINE self.dU = self.NonlinearRHS(u, u_hat, self.dU, **self.params)NEWLINE if rk < 2:NEWLINE u_hat[:] = self.U_hat0 + self.b[rk]*dt*self.psi[3]*self.dUNEWLINE elif rk == 2:NEWLINE u_hat[:] = self.ehL_h*self.V2 + self.b[rk]*dt*self.psi[3]*(2*self.dU-self.dU0)NEWLINENEWLINE if rk == 0:NEWLINE self.dU0[:] = self.dUNEWLINE self.V2[:] = u_hatNEWLINENEWLINE self.U_hat1 += self.a[rk]*dt*self.dUNEWLINE u_hat[:] = self.U_hat1NEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINE return u_hatNEWLINENEWLINENEWLINEclass RK4(IntegratorBase):NEWLINE """Regular 4'th order Runge-Kutta integratorNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : functionNEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINE """NEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.U_hat0 = Function(T)NEWLINE self.U_hat1 = Function(T)NEWLINE self.dU = Function(T)NEWLINE self.a = np.array([1./6., 1./3., 1./3., 1./6.])NEWLINE self.b = np.array([0.5, 0.5, 1.])NEWLINENEWLINE def setup(self, dt):NEWLINE """Set up RK4 ODE solver"""NEWLINE self.params['dt'] = dtNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE """Integrate forward in end_timeNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE u : arrayNEWLINE The solution array in physical spaceNEWLINE u_hat : arrayNEWLINE The solution array in spectral spaceNEWLINE dt : floatNEWLINE TimestepNEWLINE trange : two-tupleNEWLINE Time and end timeNEWLINE """NEWLINE if self.a is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = 0NEWLINE ut = TrialFunction(self.T)NEWLINE vt = TestFunction(self.T)NEWLINE L = self.LinearRHS(ut, **self.params)NEWLINE if isinstance(L, Expr):NEWLINE L = inner(vt, L)NEWLINE L = get_simplified_tpmatrices(L)[0]NEWLINE if isinstance(L, list):NEWLINE assert self.T.tensor_rank == 1NEWLINE assert L[0].isidentity()NEWLINE L = L[0].scaleNEWLINE # Use only L[0] and let numpy broadcasting take care of the restNEWLINE elif isinstance(L, TPMatrix):NEWLINE assert L.isidentity()NEWLINE L = L.scaleNEWLINE elif isinstance(L, SparseMatrix):NEWLINE L.simplify_diagonal_matrices()NEWLINE L = L.scaleNEWLINENEWLINE while t < end_time-1e-8:NEWLINE t += dtNEWLINE tstep += 1NEWLINE self.U_hat0[:] = self.U_hat1[:] = u_hatNEWLINE for rk in range(4):NEWLINE dU = self.NonlinearRHS(u, u_hat, self.dU, **self.params)NEWLINE if isinstance(L, np.ndarray):NEWLINE dU += L*u_hatNEWLINE if rk < 3:NEWLINE u_hat[:] = self.U_hat0 + self.b[rk]*dt*dUNEWLINE self.U_hat1 += self.a[rk]*dt*dUNEWLINE u_hat[:] = self. U_hat1NEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINE return u_hatNEWLINE import osNEWLINENEWLINEfrom aiogram import Bot, DispatcherNEWLINEfrom aiogram.contrib.fsm_storage.memory import MemoryStorageNEWLINENEWLINEAPI_TOKEN = os.getenv('API_TOKEN')NEWLINETIMEOUT = int(os.getenv('TIMEOUT'))NEWLINEDATABASE_URI = os.getenv('DATABASE_URI')NEWLINENEWLINEbot = Bot(token=API_TOKEN)NEWLINEstorage = MemoryStorage()NEWLINEdp = Dispatcher(bot, storage=storage)NEWLINE #NEWLINE# PySNMP MIB module DES-1210-28MEbx (http://snmplabs.com/pysmi)NEWLINE# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DES-1210-28MEbxNEWLINE# Produced by pysmi-0.3.4 at Wed May 1 12:38:52 2019NEWLINE# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4NEWLINE# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) NEWLINE#NEWLINEInteger, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")NEWLINENamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")NEWLINEConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint")NEWLINEdot1dBasePort, dot1dBasePortEntry, dot1dBridge = mibBuilder.importSymbols("BRIDGE-MIB", "dot1dBasePort", "dot1dBasePortEntry", "dot1dBridge")NEWLINEAddressFamilyNumbers, = mibBuilder.importSymbols("IANA-ADDRESS-FAMILY-NUMBERS-MIB", "AddressFamilyNumbers")NEWLINEInterfaceIndex, InterfaceIndexOrZero = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex", "InterfaceIndexOrZero")NEWLINEInetAddress, = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress")NEWLINEVlanId, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "VlanId")NEWLINESnmpSecurityLevel, SnmpEngineID, SnmpAdminString = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpSecurityLevel", "SnmpEngineID", "SnmpAdminString")NEWLINEModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")NEWLINEBits, ObjectIdentity, ModuleIdentity, Unsigned32, NotificationType, MibIdentifier, iso, Gauge32, Integer32, enterprises, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Counter32, IpAddress, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "ObjectIdentity", "ModuleIdentity", "Unsigned32", "NotificationType", "MibIdentifier", "iso", "Gauge32", "Integer32", "enterprises", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "Counter32", "IpAddress", "Counter64")NEWLINETruthValue, MacAddress, RowStatus, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "MacAddress", "RowStatus", "DisplayString", "TextualConvention")NEWLINEdes_1210_28mebx = ModuleIdentity((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2)).setLabel("des-1210-28mebx")NEWLINEdes_1210_28mebx.setRevisions(('2015-06-03 00:00', '2015-04-16 00:00', '2014-03-06 00:00',))NEWLINENEWLINEif getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):NEWLINE if mibBuilder.loadTexts: des_1210_28mebx.setRevisionsDescriptions((' In order to pass the web www.simpleweb.org to verify severity level 3, which must be change the SYNTAX of mib file.', 'Add trafficCtrlAutoRecoverTime object.', 'Initial version, published as D-Link des-1210 28ME mib.',))NEWLINEif mibBuilder.loadTexts: des_1210_28mebx.setLastUpdated('201506030000Z')NEWLINEif mibBuilder.loadTexts: des_1210_28mebx.setOrganization('DES-1210-28-BX-6-07-017.mib')NEWLINEif mibBuilder.loadTexts: des_1210_28mebx.setContactInfo('')NEWLINEif mibBuilder.loadTexts: des_1210_28mebx.setDescription(' In order to pass the web www.simpleweb.org to verify severity level 3, which must be change the SYNTAX of mib file.')NEWLINEd_link = MibIdentifier((1, 3, 6, 1, 4, 1, 171)).setLabel("d-link")NEWLINEdlink_products = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10)).setLabel("dlink-products")NEWLINEdlink_DES1210SeriesProd = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75)).setLabel("dlink-DES1210SeriesProd")NEWLINEdes_1210_28me = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15)).setLabel("des-1210-28me")NEWLINEclass VlanIndex(TextualConvention, Unsigned32):NEWLINE description = 'A value used to index per-VLAN tables: values of 0 and 4095 are not permitted; if the value is between 1 and 4094 inclusive, it represents an IEEE 802.1Q VLAN-ID with global scope within a given bridged domain (see VlanId textual convention). If the value is greater than 4095 then it represents a VLAN with scope local to the particular agent, i.e. one without a global VLAN-ID assigned to it. Such VLANs are outside the scope of IEEE 802.1Q but it is convenient to be able to manage them in the same way using this MIB.'NEWLINE status = 'current'NEWLINENEWLINEclass PortList(TextualConvention, OctetString):NEWLINE description = "Each octet within this value specifies a set of eight ports, with the first octet specifying ports 1 through 8, the second octet specifying ports 9 through 16, etc. Within each octet, the most significant bit represents the lowest numbered port, and the least significant bit represents the highest numbered port. Thus, each port of the bridge is represented by a single bit within the value of this object. If that bit has a value of '1' then that port is included in the set of ports; the port is not included if its bit has a value of '0'."NEWLINE status = 'current'NEWLINENEWLINEclass BridgeId(TextualConvention, OctetString):NEWLINE description = "The Bridge-Identifier as used in the Spanning Tree Protocol to uniquely identify a bridge. Its first two octets (in network byte order) contain a priority value and its last 6 octets contain the MAC address used to refer to a bridge in a unique fashion (typically, the numerically smallest MAC address of all ports on the bridge). Several objects in this MIB module represent values of timers used by the Spanning Tree Protocol. In this MIB, these timers have values in units of hundreths of a second (i.e. 1/100 secs). These timers, when stored in a Spanning Tree Protocol's BPDU, are in units of 1/256 seconds. Note, however, that 802.1D-1990 specifies a settable granularity of no more than 1 second for these timers. To avoid ambiguity, a data type is defined here as a textual convention and all representation of these timers in this MIB module are defined using this data type. An algorithm is also defined for converting between the different units, to ensure a timer's value is not distorted by multiple conversions."NEWLINE status = 'current'NEWLINE subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(8, 8)NEWLINE fixedLength = 8NEWLINENEWLINEclass Timeout(TextualConvention, Integer32):NEWLINE description = 'A STP timer in units of 1/100 seconds To convert a Timeout value into a value in units of 1/256 seconds, the following algorithm should be used: b = floor( (n * 256) / 100) where: floor = quotient [ignore remainder] n is the value in 1/100 second units b is the value in 1/256 second units To convert the value from 1/256 second units back to 1/100 seconds, the following algorithm should be used: n = ceiling( (b * 100) / 256) where: ceiling = quotient [if remainder is 0], or quotient + 1 [if remainder is non-zero] n is the value in 1/100 second units b is the value in 1/256 second units Note: it is important that the arithmetic operations are done in the order specified (i.e., multiply first, divide second).'NEWLINE status = 'current'NEWLINE displayHint = 'd4'NEWLINENEWLINEclass LldpManAddress(TextualConvention, OctetString):NEWLINE description = 'The value of a management address associated with the LLDP agent that may be used to reach higher layer entities to assist discovery by network management. It should be noted that appropriate security credentials, such as SNMP engineId, may be required to access the LLDP agent using a management address. These necessary credentials should be known by the network management and the objects associated with the credentials are not included in the LLDP agent.'NEWLINE status = 'current'NEWLINE subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 31)NEWLINENEWLINEclass OwnerString(TextualConvention, OctetString):NEWLINE description = "This data type is used to model an administratively assigned name of the owner of a resource. Implementations must accept values composed of well-formed NVT ASCII sequences. In addition, implementations should accept values composed of well-formed UTF-8 sequences. It is suggested that this name contain one or more of the following: IP address, management station name, network manager's name, location, or phone number. In some cases the agent itself will be the owner of an entry. In these cases, this string shall be set to a string starting with 'monitor'. SNMP access control is articulated entirely in terms of the contents of MIB views; access to a particular SNMP object instance depends only upon its presence or absence in a particular MIB view and never upon its value or the value of related object instances. Thus, objects of this type afford resolution of resource contention only among cooperating managers; they realize no access control function with respect to uncooperative parties."NEWLINE status = 'current'NEWLINE subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 127)NEWLINENEWLINEclass RmonStatus(TextualConvention, Integer32):NEWLINE description = 'The status of a table entry. Setting this object to the value invalid(4) has the effect of invalidating the corresponding entry. That is, it effectively disassociates the mapping identified with said entry. It is an implementation-specific matter as to whether the agent removes an invalidated entry from the table. Accordingly, management stations must be prepared to receive tabular information from agents that corresponds to entries currently not in use. Proper interpretation of such entries requires examination of the relevant RmonStatus object. An existing instance of this object cannot be set to createRequest(2). This object may only be set to createRequest(2) when this instance is created. When this object is created, the agent may wish to create supplemental object instances with default values to complete a conceptual row in this table. Because the creation of these default objects is entirely at the option of the agent, the manager must not assume that any will be created, but may make use of any that are created. Immediately after completing the create operation, the agent must set this object to underCreation(3). When in the underCreation(3) state, an entry is allowed to exist in a possibly incomplete, possibly inconsistent state, usually to allow it to be modified in multiple PDUs. When in this state, an entry is not fully active. Entries shall exist in the underCreation(3) state until the management station is finished configuring the entry and sets this object to valid(1) or aborts, setting this object to invalid(4). If the agent determines that an entry has been in the underCreation(3) state for an abnormally long time, it may decide that the management station has crashed. If the agent makes this decision, it may set this object to invalid(4) to reclaim the entry. A prudent agent will understand that the management station may need to wait for human input and will allow for that possibility in its determination of this abnormally long period. An entry in the valid(1) state is fully configured and consistent and fully represents the configuration or operation such a row is intended to represent. For example, it could be a statistical function that is configured and active, or a filter that is available in the list of filters processed by the packet capture process. A manager is restricted to changing the state of an entry in the following ways: To: valid createRequest underCreation invalid From: valid OK NO OK OK createRequest N/A N/A N/A N/A underCreation OK NO OK OK invalid NO NO NO OK nonExistent NO OK NO OK In the table above, it is not applicable to move the state from the createRequest state to any other state because the manager will never find the variable in that state. The nonExistent state is not a value of the enumeration, rather it means that the entryStatus variable does not exist at all. An agent may allow an entryStatus variable to change state in additional ways, so long as the semantics of the states are followed. This allowance is made to ease the implementation of the agent and is made despite the fact that managers should never exercise these additional state transitions.'NEWLINE status = 'current'NEWLINE subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))NEWLINE namedValues = NamedValues(("valid", 1), ("createRequest", 2), ("underCreation", 3), ("invalid", 4))NEWLINENEWLINEclass Ipv6Address(TextualConvention, OctetString):NEWLINE description = 'This data type is used to model IPv6 addresses. This is a binary string of 16 octets in network byte-order.'NEWLINE status = 'current'NEWLINE displayHint = '2x:'NEWLINE subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(16, 16)NEWLINE fixedLength = 16NEWLINENEWLINEcompanySystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1))NEWLINEcompanyIpifGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2))NEWLINEcompanyTftpGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3))NEWLINEcompanyMiscGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 4))NEWLINEcompanySNMPV3 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5))NEWLINEcompanySTP = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6))NEWLINEcompanyDot1qVlanGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7))NEWLINEcompanyLA = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8))NEWLINEcompanyStaticMAC = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9))NEWLINEcompanyIgsGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10))NEWLINEcompanyGVRPGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11))NEWLINEcompanyQoSGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12))NEWLINEcompanyTrafficMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13))NEWLINEcompanySecurity = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14))NEWLINEcompanyACLGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15))NEWLINEcompanySyslog = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16))NEWLINEcompanyLBD = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17))NEWLINEcompanyMirror = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18))NEWLINEcompanyStaticMcast = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19))NEWLINEcompanySNTPSetting = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20))NEWLINEcompanyRMON = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22))NEWLINEcompanyAuthGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23))NEWLINEcompanyGuestVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 24))NEWLINEcompanyMacNotify = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25))NEWLINEcompanyISMVLAN = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27))NEWLINEcompanyDHCPRelay = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28))NEWLINEcompanyDHCPLocalRelay = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29))NEWLINEcompanyTrapSetting = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30))NEWLINEsysFirmwareInfomation = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31))NEWLINEcompanyLLDPSetting = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32))NEWLINEcompanyCPUInterfaceFilterGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33))NEWLINEcompanyStaticARP = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34))NEWLINEcompanyCableDiagnostic = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35))NEWLINEcompanyVLANTrunk = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36))NEWLINEcompanyQinQ = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37))NEWLINEcompanyTimeRangeMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38))NEWLINEcompanySMTP = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40))NEWLINEcompanyLimitIp = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45))NEWLINEcompanyGratuitousARP = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48))NEWLINEcompanyMulticastFilter = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49))NEWLINEcompanyNeighbor = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50))NEWLINEcompanyEoam = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51))NEWLINEcompanyDuld = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52))NEWLINEcompanyMacBasedVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70))NEWLINEcompanyBPDUAttack = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77))NEWLINEcompanyDHCPv6Relay = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86))NEWLINEcompanyMldsGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88))NEWLINEcompanyPPPoE = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98))NEWLINEcompanyDoSCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99))NEWLINEcompanyAgentBasicInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100))NEWLINEcompanyProtocolVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101))NEWLINEcompanyL2PT = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102))NEWLINEcompanySfpVendorInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104))NEWLINEcompanyDDM = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105))NEWLINEcompanyFTPGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107))NEWLINEcompanyTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120))NEWLINEsysSwitchName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSwitchName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSwitchName.setDescription('System name used for identification of the device. The following characters are allowed to input. 0 ~ 9 / a ~ z / A ~ Z Special character: ( ) V + _ = .')NEWLINEsysHardwareVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysHardwareVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysHardwareVersion.setDescription('Version number of the Hardware.')NEWLINEsysFirmwareVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysFirmwareVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysFirmwareVersion.setDescription('Version number of the Firmware.')NEWLINEsysLoginTimeoutInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(3, 30)).clone(5)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLoginTimeoutInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLoginTimeoutInterval.setDescription('This time interval is used to count the time and logout web interface automatically.')NEWLINEsysLocationName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLocationName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLocationName.setDescription("The location name of this node (e.g., `telephone closet, 3rd floor'). If the location is unknown, the value is the zero-length string.")NEWLINEsysGroupInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(120, 1225), ))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGroupInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGroupInterval.setDescription('Group Interval is used to send D-link Discover packet to D-link SmartConsole Utility frequency. The timer in units of seconds. Set value 0 to disable group Interval.')NEWLINEsysSafeGuardEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('enable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSafeGuardEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSafeGuardEnable.setDescription('This object is used to set Safeguard Enable\\Disable.')NEWLINEsysRestart = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 9), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysRestart.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysRestart.setDescription("This object allows the user to restart the Switch (i.e)the entire switch will operationally go down and start again. Setting a value of 'true' causes the switch to be restarted. When the switch operationally goes down, configuration save operation is initiated based on the configuration save option chosen. When the switch operationally come up, the saved configurations are restored based on the restore option chosen. Once the switch is restarted, the value of this object reverts to 'false'.")NEWLINEsysSave = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("true", 1), ("false", 2), ("config-1", 3), ("config-2", 4))).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSave.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSave.setDescription('This object is used to save Configuration , value 1 save config_1 , value 2 is not in process , value 3 is save config_1 and value 4 is save config_2.')NEWLINEsysJumboFrameEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysJumboFrameEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysJumboFrameEnable.setDescription('Gigabit Web Smart Switches support jumbo frames (frames larger than the Ethernet frame size of 1522 bytes) of up to 10,000 bytes (tagged). Default jumbo frame is disabled.')NEWLINEsysPortCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13), )NEWLINEif mibBuilder.loadTexts: sysPortCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlTable.setDescription('A table to control the port specific parameters of the device like speed, duplex mode, etc.')NEWLINEsysPortCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysPortCtrlIndex"), (0, "DES-1210-28MEbx", "sysPortCtrlMediumType"))NEWLINEif mibBuilder.loadTexts: sysPortCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlEntry.setDescription('An entry appears in this table for each interface in the system. Index to the table is the interface index of the port.')NEWLINEsysPortCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlIndex.setDescription('Interface index of the port for the configuration in this entry applies.')NEWLINEsysPortCtrlMediumType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(100, 101))).clone(namedValues=NamedValues(("copper", 100), ("fiber", 101)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlMediumType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlMediumType.setDescription('This object indicates the port type: fiber 1G/100M or copper.')NEWLINEsysPortCtrlSpeed = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("rate1000M-Full", 1), ("rate100M-Full", 2), ("rate100M-Half", 3), ("rate10M-Full", 4), ("rate10M-Half", 5), ("auto", 6), ("disable", 7)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortCtrlSpeed.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlSpeed.setDescription('Configures interface speed.')NEWLINEsysPortCtrlOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("down", 1), ("rate1000M-Full", 2), ("rate100M-Full", 3), ("rate100M-Half", 4), ("rate10M-Full", 5), ("rate10M-Half", 6), ("rate10G-Full", 7)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlOperStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlOperStatus.setDescription("The port's operating speed state.")NEWLINEsysPortCtrlMDI = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("auto", 1), ("mdi", 2), ("mdix", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortCtrlMDI.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlMDI.setDescription('Configures interface auto/mdi/mdix mode. The default setting is Auto.')NEWLINEsysPortCtrlFlowControl = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortCtrlFlowControl.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlFlowControl.setDescription('Enables / disables flow control for the interface.')NEWLINEsysPortCtrlFlowControlOper = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlFlowControlOper.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlFlowControlOper.setDescription("The link parner negotiate port's operating flow control state.")NEWLINEsysPortCtrlType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("fastethernet", 1), ("gigabitethernet", 2), ("fiberwith100Base-and-1000BaseSFPModule", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlType.setDescription("The port's media type.")NEWLINEsysPortCtrlCapability = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 9), Bits().clone(namedValues=NamedValues(("rate10-half", 0), ("rate10-full", 1), ("rate100-half", 2), ("rate100-full", 3), ("reserve", 4), ("rate1000-full", 5)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortCtrlCapability.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlCapability.setDescription("The port's capability advertised.")NEWLINEsysPortDescriptionTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14), )NEWLINEif mibBuilder.loadTexts: sysPortDescriptionTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescriptionTable.setDescription('The port description table.')NEWLINEsysPortDescriptionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysPortDescIndex"), (0, "DES-1210-28MEbx", "sysPortDescMediumType"))NEWLINEif mibBuilder.loadTexts: sysPortDescriptionEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescriptionEntry.setDescription('The port description entry.')NEWLINEsysPortDescIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortDescIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescIndex.setDescription('This object indicates the port index.')NEWLINEsysPortDescMediumType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(100, 101))).clone(namedValues=NamedValues(("copper", 100), ("fiber", 101)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortDescMediumType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescMediumType.setDescription('This object indicates the port type: fiber 1G/100M or copper.')NEWLINEsysPortDescString = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortDescString.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescString.setDescription('This object indicates the port description.')NEWLINEsysPortUpLinkTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortUpLinkTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortUpLinkTime.setDescription('This object indicates the port link up time.')NEWLINEsysPortErrTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15), )NEWLINEif mibBuilder.loadTexts: sysPortErrTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrTable.setDescription('The port error table.')NEWLINEsysPortErrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysPortErrPortIndex"))NEWLINEif mibBuilder.loadTexts: sysPortErrEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrEntry.setDescription('A list of information for the err port of the device.')NEWLINEsysPortErrPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortErrPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrPortIndex.setDescription("This object indicates the module's port number.(1..Max port number in the module)")NEWLINEsysPortErrPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortErrPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrPortState.setDescription('This object decides whether the port state is enabled or disabled.')NEWLINEsysPortErrPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("err-disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortErrPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrPortStatus.setDescription('This object decides whether the PortStatus is err-disabled.')NEWLINEsysPortErrPortReason = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("lbd", 1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortErrPortReason.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrPortReason.setDescription('This object decides whether the PortStatus is LBD.')NEWLINEsysDhcpAutoConfiguration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysDhcpAutoConfiguration.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysDhcpAutoConfiguration.setDescription('This object indicates auto config is enabled or disabled.')NEWLINEsysWebState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysWebState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysWebState.setDescription('This object is for Enabled(1) or Disabled(2) Web state in the system.')NEWLINEsysWebPortNumber = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 18), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(80)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysWebPortNumber.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysWebPortNumber.setDescription('Web Server Port Number.')NEWLINEsysARPAgingTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 19), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysARPAgingTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysARPAgingTime.setDescription('This object is for ARP aging time.')NEWLINEsysMACAgingTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 20), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 1000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMACAgingTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMACAgingTime.setDescription('This object is for MAC aging time.')NEWLINEbaudRateConfiguration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(9600, 19200, 38400, 115200))).clone(namedValues=NamedValues(("baudrate9600", 9600), ("baudrate19200", 19200), ("baudrate38400", 38400), ("baudrate115200", 115200)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: baudRateConfiguration.setStatus('current')NEWLINEif mibBuilder.loadTexts: baudRateConfiguration.setDescription('To set SerialPort baud-rate configuration.')NEWLINEautologoutConfiguration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(120, 300, 600, 900, 0))).clone(namedValues=NamedValues(("logouttime2mins", 120), ("logouttime5mins", 300), ("logouttime10mins", 600), ("logouttime15mins", 900), ("logouttimenever", 0)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: autologoutConfiguration.setStatus('current')NEWLINEif mibBuilder.loadTexts: autologoutConfiguration.setDescription('To set SerialPort auto-logout-time configuration.')NEWLINEtelnetsettingManagementOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 23), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: telnetsettingManagementOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: telnetsettingManagementOnOff.setDescription('Enable/Disable management Telnetsetting mechanism.')NEWLINEtelnetUDPPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 24), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(23)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: telnetUDPPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: telnetUDPPort.setDescription("The value is for setting telnet's UDP Port.")NEWLINEautoRefreshConfiguration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("refreshimenever", 0), ("refreshtime10secs", 1), ("refreshtime30secs", 2), ("refreshtime1min", 3), ("refreshtime5mins", 4)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: autoRefreshConfiguration.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoRefreshConfiguration.setDescription('To set the WEB panel auto refresh timer.')NEWLINEfloodfdbOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 26), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: floodfdbOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: floodfdbOnOff.setDescription('To set enable status for flood fdb.')NEWLINEsysContactName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 27), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysContactName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysContactName.setDescription('To set system contact name.')NEWLINEsysDhcpAutoConfigTimeout = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 28), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysDhcpAutoConfigTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysDhcpAutoConfigTimeout.setDescription('To set dhcp auto config timeout.')NEWLINEsysCommandLogging = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 29), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysCommandLogging.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysCommandLogging.setDescription('To set enable status for CommandLogging.')NEWLINEsysSerialNumber = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 30), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 13))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysSerialNumber.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSerialNumber.setDescription('To get the serial number.')NEWLINEsysVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysVersion.setDescription('The version of firmware information.')NEWLINEsysSize = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysSize.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSize.setDescription('The size of firmware information.')NEWLINEsysUpdateTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysUpdateTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysUpdateTime.setDescription('The Update Time of firmware information.')NEWLINEsysFromIP = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 4), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysFromIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysFromIP.setDescription('The IP address of firmware information.')NEWLINEsysUser = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 9))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysUser.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysUser.setDescription('The user of firmware infomation.')NEWLINEsysType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, -1))).clone(namedValues=NamedValues(("console", 1), ("telnet", 2), ("ssh", 3), ("web", 4), ("unknown", -1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysType.setDescription('The type of firmware infomation.')NEWLINEsysBootupConfigID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 33), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBootupConfigID.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBootupConfigID.setDescription('To get/set bootup config ID.')NEWLINEsysDhcpAutoImage = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 34), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysDhcpAutoImage.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysDhcpAutoImage.setDescription('This object indicates auto image is enabled or disabled.')NEWLINEsysPortMediaTypeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36), )NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeTable.setDescription('A table to control the port specific parameters of the device like speed, Vendor name, etc.')NEWLINEsysPortMediaTypeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysPortMediaTypeIndex"), (0, "DES-1210-28MEbx", "sysPortMediaType"))NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeEntry.setDescription('An entry appears in this table for each interface in the system. Index to the table is the interface index of the port.')NEWLINEsysPortMediaTypeIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeIndex.setDescription('Interface index of the port for the configuration in this entry applies.')NEWLINEsysPortMediaType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(100, 101))).clone(namedValues=NamedValues(("copper", 100), ("fiber", 101)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaType.setDescription('This object indicates the port type: fiber 1G/100M or copper.')NEWLINEsysPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("rate100M", 1), ("rate1000M", 2), ("rate10G", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortType.setDescription('Configures interface speed.')NEWLINEsysPortMediaTypeVendorName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeVendorName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeVendorName.setDescription("The port's VendorName.")NEWLINEsysPortMediaTypeOui = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeOui.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeOui.setDescription("The port's Oui.")NEWLINEsysPortMediaTypePn = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypePn.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypePn.setDescription("The port's Pn.")NEWLINEsysPortMediaTypeRev = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeRev.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeRev.setDescription("The port's Rev.")NEWLINEsysPortMediaTypeSn = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeSn.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeSn.setDescription("The port's Sn.")NEWLINEsysPortMediaTypeDateCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeDateCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeDateCode.setDescription("The port's DateCode.")NEWLINEipv4sysIpAddrCfgMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("manual", 1), ("dynamic", 2))).clone('manual')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIpAddrCfgMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIpAddrCfgMode.setDescription("Specifies the means by which the default interface in the device gets the IP address. If 'manual' mode is selected, the default interface takes the 'sysDefaultIpAddr' configured in the system. If 'dynamic' mode is selected, the default interface gets the IP address through dynamic IP address configuration protocols such as RARP client, BootP client, DHCP Client, etc. If the system fails to get the IP address dynamically through all the above protocols, the default interface uses the 'sysDefaultIpAddr' configured in the system.")NEWLINEipv4sysIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIpAddr.setDescription('Default IP Address of the system. This IP address, if modified, will take effect only when the configuration is stored & restored.')NEWLINEipv4sysIpSubnetMask = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 3), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIpSubnetMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIpSubnetMask.setDescription('IP subnet mask for the default IP address. This subnet mask, if modified, will take effect only when the configuration is stored & restored.')NEWLINEipv4sysGateway = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 4), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysGateway.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysGateway.setDescription('Gateway')NEWLINEipv4dhcpOption12Status = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4dhcpOption12Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4dhcpOption12Status.setDescription('Status of DHCP Option12')NEWLINEipv4dhcpOption12HostName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 6), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4dhcpOption12HostName.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4dhcpOption12HostName.setDescription('Host name in DHCP option 12')NEWLINEipifSupportV4V6Info = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7))NEWLINEsysIpAddrCfgMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("manual", 1), ("dynamic", 2))).clone('manual')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysIpAddrCfgMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysIpAddrCfgMode.setDescription("Specifies the means by which the default interface in the device gets the IP address. If 'manual' mode is selected, the default interface takes the 'sysDefaultIpAddr' configured in the system. If 'dynamic' mode is selected, the default interface gets the IP address through dynamic IP address configuration protocols such as RARP client, BootP client, DHCP Client, etc. If the system fails to get the IP address dynamically through all the above protocols, the default interface uses the 'sysDefaultIpAddr' configured in the system.")NEWLINEsysIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysIpAddr.setDescription('Default IP Address of the system. This IP address, if modified, will take effect only when the configuration is stored & restored.')NEWLINEsysIpSubnetMask = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 3), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysIpSubnetMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysIpSubnetMask.setDescription('IP subnet mask for the default IP address. This subnet mask, if modified, will take effect only when the configuration is stored & restored.')NEWLINEsysGateway = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 4), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGateway.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGateway.setDescription('Gateway')NEWLINEdhcpOption12Status = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpOption12Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpOption12Status.setDescription('Status of DHCP Option12')NEWLINEdhcpOption12HostName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 6), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpOption12HostName.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpOption12HostName.setDescription('Host name in DHCP option 12')NEWLINEipifName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 7), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifName.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifName.setDescription('The Description for the interface.')NEWLINEipifVLANname = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 8), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifVLANname.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifVLANname.setDescription('The vlan name for the interface.')NEWLINEipifv6GlobalStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6GlobalStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6GlobalStatus.setDescription('The ID of VLAN that you want this interface to be in. It must be a exist vlan id.')NEWLINEipifv6DHCPStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6DHCPStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6DHCPStatus.setDescription('The state of DHCPv6 that you want this interface to be in. It must be a exist vlan id.')NEWLINEipifv6AutolinkloStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6AutolinkloStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6AutolinkloStatus.setDescription('The global state of link local that you want this interface to be in. It must be a exist vlan id.')NEWLINEipifv6NSRetransmitTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 12), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6NSRetransmitTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6NSRetransmitTime.setDescription("The NS's retransmit time that you want this interface to be in. It must be a exist vlan id (1~3600).")NEWLINEipifv6DefaultGateway = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 13), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6DefaultGateway.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6DefaultGateway.setDescription('The ipv6 default gateway that you want this interface to be in. It must be a exist vlan id.')NEWLINEipifV6AddressTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14), )NEWLINEif mibBuilder.loadTexts: ipifV6AddressTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressTable.setDescription('A list of interface entries.')NEWLINEipifV6AddressEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipifV6AddressMainIndex"), (0, "DES-1210-28MEbx", "ipifV6AddressIpAddr"), (0, "DES-1210-28MEbx", "ipifV6AddressIpPrefix"))NEWLINEif mibBuilder.loadTexts: ipifV6AddressEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressEntry.setDescription('An entry containing management information applicable to a particular interface.')NEWLINEipifV6AddressMainIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifV6AddressMainIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressMainIndex.setDescription('The index of this IPv6 entry.')NEWLINEipifV6AddressIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 2), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpAddr.setDescription('The ip address of this IPv6 entry.')NEWLINEipifV6AddressIpPrefix = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpPrefix.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpPrefix.setDescription('The ip prefix of this IPv6 entry.')NEWLINEipifV6AddressIpType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("unicast", 1), ("anycast", 2), ("linklocal", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpType.setDescription('The ip type of this IPv6 entry.')NEWLINEipifV6AddressRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 5), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipifV6AddressRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressRowStatus.setDescription('The status of an entry in the Multi Interface Table. Only a subset of the rowstatus variables (active, createAndWait, destroy) are available.')NEWLINEipv4sysIprouteGateway = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 8), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIprouteGateway.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIprouteGateway.setDescription('IProute Gateway of the system.')NEWLINEipv4sysIprouteHops = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 9), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIprouteHops.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIprouteHops.setDescription('IProute Hops of the system.')NEWLINEtftpFwServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 1), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwServerIpAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpFwServerIpAddress.setDescription("The TFTP server's IP address is used to upload or download firmware.")NEWLINEtftpFwImageFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwImageFileName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpFwImageFileName.setDescription('Configure firmware filename to download.')NEWLINEtftpFwTftpOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("download", 1), ("upload", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTftpOperation.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpFwTftpOperation.setDescription('The tftp operates to perform downloading the firmware image to the unit. This object is used in conjunction with configBootTftpServerIp and configBootImageFileName.')NEWLINEtftpFwTftpOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3), ("transmit", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: tftpFwTftpOperationStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpFwTftpOperationStatus.setDescription('The tftp operation status represent firmware backup or upgrade status.')NEWLINEtftpCfgServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 5), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgServerIpAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpCfgServerIpAddress.setDescription("The TFTP server's IP address is used to upload or download configuration file.")NEWLINEtftpConfigFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpConfigFileName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpConfigFileName.setDescription('The configuration filename is used to store or retrieve config from the tftp server.')NEWLINEtftpConfigTftpOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("download", 1), ("upload", 2), ("progressing", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpConfigTftpOperation.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpConfigTftpOperation.setDescription('The tftp operates to perform either downloading the configuration file to the unit or uploading the current configuration file to the tftp server. This object is used in conjunction with configTftpServerIpAddress and configTftpServerFileName.')NEWLINEtftpConfigTftpOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: tftpConfigTftpOperationStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpConfigTftpOperationStatus.setDescription('The tftp operation status represent configuration file backup or restore status.')NEWLINEtftpFwTargetGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9))NEWLINEtftpFwTargetServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 1), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetServerIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetServerIpAddress.setDescription("The TFTP server's IP address is used to upload or download firmware.")NEWLINEtftpFwTargetServerIpType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetServerIpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetServerIpType.setDescription('Type of IP interface.')NEWLINEtftpFwTargetInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 3), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetInterfaceName.setDescription('Specifies the interface name when the tftpFwTargetServerIpAddress is linklocal address.')NEWLINEtftpFwTargetImageFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetImageFileName.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetImageFileName.setDescription('Configure firmware filename to download.')NEWLINEtftpFwTargetTftpOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("download", 1), ("upload", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetTftpOperation.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetTftpOperation.setDescription('The tftp operates to perform downloading the firmware image to the unit. This object is used in conjunction with configBootTftpServerIp and configBootImageFileName.')NEWLINEtftpFwTargetTftpOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3), ("transmit", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: tftpFwTargetTftpOperationStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetTftpOperationStatus.setDescription('The tftp operation status represent firmware backup or upgrade status.')NEWLINEtftpCfgTargetGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10))NEWLINEtftpCfgTargetServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 1), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetServerIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetServerIpAddress.setDescription("The TFTP server's IP address is used to upload or download configuration file.")NEWLINEtftpCfgTargetServerIpType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetServerIpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetServerIpType.setDescription('Type of IP interface.')NEWLINEtftpCfgTargetInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 3), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetInterfaceName.setDescription('Specifies the interface name when the tftpCfgTargetServerIpAddress is linklocal address.')NEWLINEtftpCfgTargetImageFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetImageFileName.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetImageFileName.setDescription('The configuration filename is used to store or retrieve config from the tftp server.')NEWLINEtftpCfgTargetTftpOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("download", 1), ("upload", 2), ("progressing", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpOperation.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpOperation.setDescription('The tftp operates to perform either downloading the configuration file to the unit or uploading the current configuration file to the tftp server. This object is used in conjunction with configTftpServerIpAddress and configTftpServerFileName.')NEWLINEtftpCfgTargetTftpOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpOperationStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpOperationStatus.setDescription('The tftp operation status represent configuration file backup or restore status.')NEWLINEtftpCfgTargetTftpConfigID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("configId-1", 1), ("configId-2", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpConfigID.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpConfigID.setDescription('The tftp config ID determine which config what you need.')NEWLINEtftpCfgTargetTftpIncrement = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("false", 0), ("true", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpIncrement.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpIncrement.setDescription('The tftp increment determine download config behavior.')NEWLINEmiscReset = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 4, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("reset", 1), ("noop", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: miscReset.setStatus('current')NEWLINEif mibBuilder.loadTexts: miscReset.setDescription('Physically resets the unit - use with care. A (1) resets the unit, a (2) does nothing.')NEWLINEmiscStatisticsReset = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 4, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("reset", 1), ("noop", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: miscStatisticsReset.setStatus('current')NEWLINEif mibBuilder.loadTexts: miscStatisticsReset.setDescription('Resets the units statistics. A (1) resets the statistics count, a (2) does nothing.')NEWLINEsecurityIpMacPortBinding = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10))NEWLINEimpbSettingTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1), )NEWLINEif mibBuilder.loadTexts: impbSettingTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbSettingTable.setDescription('A table to control IP-MAC-Port Binding Setting features of the device.')NEWLINEimpbSettingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbPortIndex"))NEWLINEif mibBuilder.loadTexts: impbSettingEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbSettingEntry.setDescription('An entry appears in IP-MAC-Port Binding Setting table for each interface in the system.')NEWLINEimpbPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortIndex.setDescription("Specifies the port numbers through which the authorized manager can access the switch. By default the authorized manager is allowed to access the switch through all the ports. If a set of ports are configured in the 'PortList', the manager can access the switch only through the configured ports.")NEWLINEimpbPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortState.setDescription('Disable / enable IP-MAC-Port Binding admin state for the interface.')NEWLINEimpbPortDHCPSnoopingState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPSnoopingState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPSnoopingState.setDescription('Disable / enable IP-MAC-Port Binding DHCP snooping state for the interface.')NEWLINEimpbPortArpInspectionState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("disabled", 0), ("strict", 1), ("loose", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortArpInspectionState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortArpInspectionState.setDescription('Set IP-MAC-Port Binding ARP Inspection state for the interface.')NEWLINEimpbPortIpInspectionState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortIpInspectionState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortIpInspectionState.setDescription('Set IP-MAC-Port Binding IP Inspection state for the interface.')NEWLINEimpbPortAllowZeroIPState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortAllowZeroIPState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortAllowZeroIPState.setDescription('Disable / enable IP-MAC-Port Binding Allow-Zero-IP state for the interface.')NEWLINEimpbPortForwardDHCPPktState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortForwardDHCPPktState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortForwardDHCPPktState.setDescription('Disable / enable IP-MAC-Port Binding Forward-DHCP-Packet state for the interface.')NEWLINEimpbPortDHCPMaxEntryIPv4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 10))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPMaxEntryIPv4.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPMaxEntryIPv4.setDescription('Set the maximum number of IPv4 entries that can be learned for the interface.')NEWLINEimpbPortDHCPMaxEntryIPv6 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 10))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPMaxEntryIPv6.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPMaxEntryIPv6.setDescription('Set the maximum number of IPv6 entries that can be learned for the interface.')NEWLINEimpbPortNDInspectionState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortNDInspectionState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortNDInspectionState.setDescription('Set IP-MAC-Port Binding ND Inspection state for the interface.')NEWLINEimpbPortProtocolState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("ipv4", 0), ("ipv6", 1), ("all", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortProtocolState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortProtocolState.setDescription('Set IP-MAC-Port Binding protocol state for the interface.')NEWLINEimpbPortDHCPv4SetVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 13), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4SetVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4SetVlanList.setDescription('A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. The set of vlans configured by management to map for this Instance. If the VlanId to Instance Mapping has to be known then any one of the VlanMapped object should be used.If a vlan is already mapped to this Instance, it may not be mapped again. This object is used only for SET operation. GET Operation returns null values.')NEWLINEimpbPortDHCPv4VlanList1k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 14), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList1k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList1k.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCP snooping, the bit corresponding to that VLAN is set to '1'. ")NEWLINEimpbPortDHCPv4VlanList2k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 15), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList2k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1025 through 2048. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv4 snooping, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv4VlanList3k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 16), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2049 through 3072. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv4 snooping the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv4VlanList4k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 17), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3073 through 4094. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv4 snooping, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv6SetVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 18), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6SetVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6SetVlanList.setDescription('A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. The set of vlans configured by management to map for this Instance. If the VlanId to Instance Mapping has to be known then any one of the VlanMapped object should be used.If a vlan is already mapped to this Instance, it may not be mapped again. This object is used only for SET operation. GET Operation returns null values.')NEWLINEimpbPortDHCPv6VlanList1k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 19), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList1k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList1k.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCP snooping, the bit corresponding to that VLAN is set to '1'. ")NEWLINEimpbPortDHCPv6VlanList2k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 20), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList2k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1025 through 2048. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv6 snooping, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv6VlanList3k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 21), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2049 through 3072. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv6 snooping the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv6VlanList4k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 22), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3073 through 4094. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv6 snooping, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbAutoScanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2), )NEWLINEif mibBuilder.loadTexts: impbAutoScanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanTable.setDescription('A table to control auto scan features of the device.')NEWLINEimpbAutoScanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbAutoScanMacAddress"), (0, "DES-1210-28MEbx", "impbAutoScanPort"), (0, "DES-1210-28MEbx", "impbAutoScanIpAddress"))NEWLINEif mibBuilder.loadTexts: impbAutoScanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanEntry.setDescription('An entry appears in auto scan table for each interface in the system.')NEWLINEimpbAutoScanMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 1), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanMacAddress.setDescription('The MAC address associated of the auto scan entry.')NEWLINEimpbAutoScanPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanPort.setDescription('The port number of the auto scan entry. For all machines give maximum port number.')NEWLINEimpbAutoScanIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 3), DisplayString().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddress.setDescription('The IP address associated of the auto scan entry.')NEWLINEimpbAutoScanVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanVlanId.setDescription('The VLAN ID of the auto scan entry.')NEWLINEimpbAutoScanBinding = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbAutoScanBinding.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanBinding.setDescription('Disable / enable IP-MAC-Port Binding for the entry.')NEWLINEimpbBindingListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3), )NEWLINEif mibBuilder.loadTexts: impbBindingListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListTable.setDescription('A table to control Manual IP-MAC-Port Binding white list features of the device.')NEWLINEimpbBindingListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbBindingListIpAddress"), (0, "DES-1210-28MEbx", "impbBindingListMacAddress"))NEWLINEif mibBuilder.loadTexts: impbBindingListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListEntry.setDescription('An entry appears in Manual IP-MAC-Port Binding white list table for each interface in the system.')NEWLINEimpbBindingListIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1, 1), DisplayString().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBindingListIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListIpAddress.setDescription('The IP address associated of the Manual IP-MAC-PORT Binding white list entry.')NEWLINEimpbBindingListMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1, 2), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBindingListMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListMacAddress.setDescription('The MAC address associated of the Manual IP-MAC-PORT Binding white list entry.')NEWLINEimpbBindingListPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1, 3), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbBindingListPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListPort.setDescription('The port number of the Manual IP-MAC-PORT Binding white list entry.')NEWLINEimpbBindingListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: impbBindingListRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListRowStatus.setDescription('The status of a row in impbBindingListTable. By setting this object, new entries can be created in impbBindingListTable and existing entries can be removed from impbBindingListTable. It can be used as specified in the SNMP v2 standard.')NEWLINEimpbBlockListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4), )NEWLINEif mibBuilder.loadTexts: impbBlockListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListTable.setDescription('A table to control IP-MAC-Port Binding black list of the device.')NEWLINEimpbBlockListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbBlockListMacAddress"), (0, "DES-1210-28MEbx", "impbBlockListVlanId"), (0, "DES-1210-28MEbx", "impbBlockListPort"))NEWLINEif mibBuilder.loadTexts: impbBlockListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListEntry.setDescription('An entry appears in Manual IP-MAC-Port Binding black list table for each interface in the system.')NEWLINEimpbBlockListMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 1), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBlockListMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListMacAddress.setDescription('The MAC address associated of the IP-MAC-PORT Binding black list entry.')NEWLINEimpbBlockListVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBlockListVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListVlanId.setDescription('The VLAN ID of the IP-MAC-PORT Binding black list entry.')NEWLINEimpbBlockListPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBlockListPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListPort.setDescription('The port number of the IP-MAC-PORT Binding black list entry.')NEWLINEimpbBlockListIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 4), DisplayString().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBlockListIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListIpAddress.setDescription('The IP address associated of the IP-MAC-PORT Binding black list entry.')NEWLINEimpbBlockListStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("nothing", 0), ("deleted", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbBlockListStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListStatus.setDescription('nothing/delete IP-MAC-Port Binding for the interface.')NEWLINEimpbAutoScanIpAddressFrom = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 5), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddressFrom.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddressFrom.setDescription('The begin for IP address associated of the IP-MAC-PORT Binding auto scan entry.')NEWLINEimpbAutoScanIpAddressTo = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 6), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddressTo.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddressTo.setDescription('The end for IP address associated of the IP-MAC-PORT Binding auto scan entry.')NEWLINEimpbAutoScanStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("nothing", 0), ("scan", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbAutoScanStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanStatus.setDescription('Nothing / scan IP-MAC-Port Binding auto scan for the interface.')NEWLINEimpbDhcpSnoopingTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8), )NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingTable.setDescription('A table to display DHCP snooping entries of the device.')NEWLINEimpbDhcpSnoopingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbDhcpSnoopingMacAddress"), (0, "DES-1210-28MEbx", "impbDhcpSnoopingIpAddress"))NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingEntry.setDescription('An entry appears in DHCP snooping table for each interface in the system.')NEWLINEimpbDhcpSnoopingMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1, 1), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingMacAddress.setDescription('The MAC address associated of the DHCP snooping entry.')NEWLINEimpbDhcpSnoopingIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1, 2), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingIpAddress.setDescription('The IP address associated of the DHCP snooping entry.')NEWLINEimpbDhcpSnoopingLeaseTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1, 3), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingLeaseTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingLeaseTime.setDescription('The lease time associated of the DHCP snooping entry.')NEWLINEimpbDhcpSnoopingPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingPort.setDescription('The port number associated of the DHCP snooping entry.')NEWLINEimpbRoamingState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbRoamingState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbRoamingState.setDescription('Disable / enable IP-MAC-Port Binding roaming state.')NEWLINEimpbVlanModeState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbVlanModeState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbVlanModeState.setDescription('Disable / enable IP-MAC-Port Binding vlan mode state.')NEWLINEimpbVlanModeVlanList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 11), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbVlanModeVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbVlanModeVlanList.setDescription('IP-MAC-Port Binding vlan mode VID list.')NEWLINEimpbLogState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("disabled", 0), ("ipv4", 1), ("ipv6", 2), ("all", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbLogState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbLogState.setDescription('Configure IP-MAC-Port Binding log state.')NEWLINEimpbDHCPv6PrefixDelegationSnoopState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbDHCPv6PrefixDelegationSnoopState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDHCPv6PrefixDelegationSnoopState.setDescription('Configure DHCPv6 PD snooping state.')NEWLINEimpbBindingtraplog = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2, 1))).clone(namedValues=NamedValues(("disabled", 2), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbBindingtraplog.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingtraplog.setDescription('This object is for enabling or disabling topology change event trap in the system.')NEWLINEimpbBindingtrap = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 15))NEWLINEimpbBindingtrapsign = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 15, 1))NEWLINEif mibBuilder.loadTexts: impbBindingtrapsign.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingtrapsign.setDescription('The object is for IMPB trap sign in the system.')NEWLINEimpbAutoScanCurrentStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("stop", 0), ("scanning", 1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanCurrentStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanCurrentStatus.setDescription('Show Auto scan status')NEWLINEstpBridgeGlobal = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1))NEWLINEstpModuleStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpModuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpModuleStatus.setDescription('The administrative status requested by management for the MST feature. The value enabled(1) indicates that Mst should be enabled in the device on all ports. The value disabled(2) indicates that Mst should be disabled in the device on all ports. The object can be set to enabled(1) if and only if, fsMIMstSystemControl set to start.')NEWLINEstpProtocolVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("stp", 1), ("rstp", 2), ("mstp", 3))).clone('mstp')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpProtocolVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpProtocolVersion.setDescription("The version of Spanning Tree Protocol the bridge is currently running. The value 'stpCompatible(0)' indicates the Spanning Tree Protocol specified in IEEE 802.1D and 'rstp(2)' indicates the Rapid Spanning Tree Protocol specified in IEEE 802.1w and 'mstp(3)' indicates the Multiple Spanning Tree Protocol Specified in IEEE 802.1s.")NEWLINEstpBridgePriority = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 61440)).clone(32768)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpBridgePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpBridgePriority.setDescription('The Value of the writable portion of the Bridge Identifier comprising of the first two octets. The values that are set for Bridge Priority must be in steps of 4096.')NEWLINEstpTxHoldCount = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10)).clone(3)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpTxHoldCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpTxHoldCount.setDescription('The value used by the Port Transmit state machine to limit the maximum transmission rate.')NEWLINEstpBridgeMaxAge = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 5), Timeout().subtype(subtypeSpec=ValueRangeConstraint(600, 4000)).clone(2000)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpBridgeMaxAge.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpBridgeMaxAge.setDescription('The value that all bridges use for MaxAge when this bridge is acting as the root. The granularity of this timer is specified to be 1 second. An agent may return a badValue error if a set is attempted to a value which is not a whole number of seconds.')NEWLINEstpBridgeHelloTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 6), Timeout().subtype(subtypeSpec=ValueRangeConstraint(100, 1000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpBridgeHelloTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpBridgeHelloTime.setDescription('The amount of time between the transmission of Configuration bridge PDUs by this node in units of hundredths of a second.')NEWLINEstpBridgeForwardDelay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 7), Timeout().subtype(subtypeSpec=ValueRangeConstraint(400, 3000)).clone(1500)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpBridgeForwardDelay.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpBridgeForwardDelay.setDescription('The value that all bridges use for ForwardDelay when this bridge is acting as the root. Note that 802.1D specifies that the range for this parameter is related to the value of BridgeMaxAge. The granularity of this timer is specified to be 1 second. An agent may return a badValue error if a set is attempted to a value which is not a whole number of seconds.')NEWLINEstpFowardBPDU = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpFowardBPDU.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpFowardBPDU.setDescription('This object is for enabling or disabling forward BPDU.')NEWLINEstpRootBridge = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 9), BridgeId()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpRootBridge.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpRootBridge.setDescription('The bridge identifier of the Root of the common spanning tree as determined by the Spanning Tree Protocol as executed by this node. This value is used as the CIST Root Identifier parameter in all Configuration Bridge PDUs originated by this node.')NEWLINEstpRootCost = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 10), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpRootCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpRootCost.setDescription('The Cost of the path to the CIST Root as seen from this bridge.')NEWLINEstpMaxAge = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 11), Timeout()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpMaxAge.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpMaxAge.setDescription('The maximum age of Spanning Tree Protocol information learned from the network on any port before it is discarded, in units of hundredths of a second. This is the actual value that this bridge is currently using.')NEWLINEstpForwardDelay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 12), Timeout()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpForwardDelay.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpForwardDelay.setDescription('This time value, measured in units of hundredths of a second, controls how fast a port changes its spanning state when moving towards the Forwarding state. The value determines how long the port stays in a particular state before moving to the next state.')NEWLINEstpRootPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 13), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpRootPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpRootPort.setDescription('The Port Number of the Port which offers the lowest path cost from this bridge to the CIST Root Bridge.')NEWLINEstpTopologyChangeTrapStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpTopologyChangeTrapStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpTopologyChangeTrapStatus.setDescription('This object is for enabling or disabling topology change event trap in the system.')NEWLINEstpNewRootTrapStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpNewRootTrapStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpNewRootTrapStatus.setDescription('This object is for enabling or disabling new root event trap in the system.')NEWLINEstpNewRootTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 16))NEWLINEbrgAddress = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 16, 1))NEWLINEif mibBuilder.loadTexts: brgAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: brgAddress.setDescription('The MAC address used by this bridge when it must be referred to in a unique fashion.')NEWLINEoldDesignatedRoot = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 16, 2))NEWLINEif mibBuilder.loadTexts: oldDesignatedRoot.setStatus('current')NEWLINEif mibBuilder.loadTexts: oldDesignatedRoot.setDescription('The bridge identifier of the old root of the spanning tree instance as determined by the Spanning Tree Protocol as executed by this node.')NEWLINEmstiBridgeRegionalRoot = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 16, 3))NEWLINEif mibBuilder.loadTexts: mstiBridgeRegionalRoot.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstiBridgeRegionalRoot.setDescription('MSTI Regional Root Identifier value for the Instance.')NEWLINEstpPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2), )NEWLINEif mibBuilder.loadTexts: stpPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortTable.setDescription('A table that contains port-specific information for the Spanning Tree Protocol.')NEWLINEstpPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "stpPort"))NEWLINEif mibBuilder.loadTexts: stpPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortEntry.setDescription('A list of information maintained by every port about the Spanning Tree Protocol state for that port.')NEWLINEstpPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPort.setDescription('The Port number of the port for which this entry contains spanning tree information.')NEWLINEstpPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 0))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 0)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortStatus.setDescription("Current state of the Port which can be changed to either Disabled or Enabled for ALL spanning tree instances. Setting this object will override the port's status in any of the MSTI contexts")NEWLINEstpPortPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 240)).clone(128)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortPriority.setDescription('The four most significant bits of the Port Identifier of the Spanning Tree instance can be modified by setting the CistPortPriority value. The values that are set for Port Priority must be in steps of 16.')NEWLINEstpAdminPortPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpAdminPortPathCost.setReference('IEEE 802.1D-2004')NEWLINEif mibBuilder.loadTexts: stpAdminPortPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpAdminPortPathCost.setDescription("The contribution of this port to the path cost of paths towards the spanning tree root which include this port. Writing a value of '0' assigns the automatically calculated default Path Cost value to the ohter object stpPortPathCost. If the default Path Cost is being used,this object returns '0' when read.")NEWLINEstpPortPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 200000000))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpPortPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortPathCost.setDescription('The contribution of this port to the path cost of paths towards the CIST Root which include this port.')NEWLINEstpPortProtocolMigration = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("false", 0), ("true", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortProtocolMigration.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortProtocolMigration.setDescription('Indicates the Protocol migration state of this Port. When operating in RSTP/MSTP (version >= 2) mode, writing TRUE(1) to this object forces this port to transmit MSTP BPDUs without instance information. Any other operation on this object has no effect and it always returns FALSE(2) when read.')NEWLINEstpPortEdge = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 0, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 0), ("auto", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortEdge.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortEdge.setDescription(' This parameter when TRUE(1) indicates that detection of a port as Edge Port happens automatically and FALSE(2) indicates that this feature is disabled.')NEWLINEstpPortAdminP2P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("forceTrue", 0), ("forceFalse", 1), ("auto", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortAdminP2P.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortAdminP2P.setDescription('The administrative point-to-point status of the LAN segment attached to this port. A value of forceTrue(0) indicates that this port should always be treated as if it is connected to a point-to-point link. A value of forceFalse(1) indicates that this port should be treated as having a shared media connection. A value of auto(2) indicates that this port is considered to have a point-to-point link if it is an Aggregator and all of its members are aggregatable, or if the MAC entity is configured for full duplex operation, either through auto-negotiation or by management means.')NEWLINEstpPortRestrictedRole = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 9), TruthValue()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortRestrictedRole.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortRestrictedRole.setDescription("A Boolean value set by management. If TRUE causes the Port not to be selected as Root Port for the CIST or any MSTI, even it has the best spanning tree priority vector. Such a Port will be selected as an Alternate Port after the Root Port has been selected. This parameter should be FALSE by default. If set it can cause lack of spanning tree connectivity. It is set by a network administrator to prevent bridges external to a core region of the network influencing the spanning tree active topology, possibly because those bridges are not under the full control of the administrator. This administrator configuration is also known as 'Root Guard'.")NEWLINEstpPortRestrictedTCN = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 10), TruthValue()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortRestrictedTCN.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortRestrictedTCN.setDescription('A Boolean value set by management. If TRUE causes the Port not to propagate received topology change notifications and topology changes to other Ports. This parameter should be FALSE by default. If set it can cause temporary loss of connectivity after changes in a spanning trees active topology as a result of persistent incorrectly learnt station location information. It is set by a network administrator to prevent bridges external to a core region of the network causing address flushing in that region, possibly because those bridges are not under the full control of the administrator or MAC_Operational for the attached LANs transitions frequently.')NEWLINEstpPortHelloTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 11), Timeout().subtype(subtypeSpec=ValueRangeConstraint(100, 1000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortHelloTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortHelloTime.setDescription('The amount of time between the transmission of Configuration bridge PDUs by this node in units of hundredths of a second.')NEWLINEstpPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 4, 5))).clone(namedValues=NamedValues(("disabled", 1), ("discarding", 2), ("learning", 4), ("forwarding", 5)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortState.setDescription('Current state of the Port as defined by the Common spanning tree protocol.')NEWLINEstpPortFowardBPDU = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortFowardBPDU.setReference('IEEE 802.1D-2004')NEWLINEif mibBuilder.loadTexts: stpPortFowardBPDU.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortFowardBPDU.setDescription('This object is for enabling or disabling forward BPDU.')NEWLINEmstConfigurationIdentification = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3))NEWLINEmstiConfigurationName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstiConfigurationName.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstiConfigurationName.setDescription("The Name for the Region's configuration. By Default Region Name will be equal to the Bridge Mac Address.")NEWLINEmstiRevisionLevel = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstiRevisionLevel.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstiRevisionLevel.setDescription('Version of the MST Region.')NEWLINEmstCistVlanMapped = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'.")NEWLINEmstCistVlanMapped2k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped2k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1024 through 2047. The first octet corresponds to VLANs with VlanIndex values 1024 through 1031; the second octet to VLANs 1032 through 1039 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstCistVlanMapped3k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2048 through 3071. The first octet corresponds to VLANs with VlanIndex values of 2048 through 2055; the second octet to VLANs 2056 through 2063 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstCistVlanMapped4k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3072 through 4095. The first octet corresponds to VLANs with VlanIndex values 3072 through 3079; the second octet to VLANs 3080 through 3087 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstVlanMstiMappingTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7), )NEWLINEif mibBuilder.loadTexts: mstVlanMstiMappingTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstVlanMstiMappingTable.setDescription('This table contains one entry for each instance of MSTP. This table maintains context ID as one more index to support Multiple Instances.')NEWLINEmstVlanMstiMappingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mstInstanceIndex"))NEWLINEif mibBuilder.loadTexts: mstVlanMstiMappingEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstVlanMstiMappingEntry.setDescription('A conceptual row containing the status of the MSTP instance.')NEWLINEmstInstanceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceIndex.setDescription('An arbitrary integer within the range from 1 to the value of Max Instance Number that uniquely identifies an instance.')NEWLINEmstSetVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstSetVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstSetVlanList.setDescription('A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. The set of vlans configured by management to map for this Instance. If the VlanId to Instance Mapping has to be known then any one of the VlanMapped object should be used.If a vlan is already mapped to this Instance, it may not be mapped again. This object is used only for SET operation. GET Operation returns null values.')NEWLINEmstResetVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstResetVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstResetVlanList.setDescription('A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. The set of vlans configured by management to unmap from this Instance. A vlan may not be unmapped from this instance if it is not already mapped to this Instance. This object is used only for SET operation.GET Operation returns null values.')NEWLINEmstInstanceVlanMapped = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'.")NEWLINEmstInstanceVlanMapped2k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped2k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1024 through 2047. The first octet corresponds to VLANs with VlanIndex values 1024 through 1031; the second octet to VLANs 1032 through 1039 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstInstanceVlanMapped3k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2048 through 3071. The first octet corresponds to VLANs with VlanIndex values of 2048 through 2055; the second octet to VLANs 2056 through 2063 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstInstanceVlanMapped4k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3072 through 4095. The first octet corresponds to VLANs with VlanIndex values 3072 through 3079; the second octet to VLANs 3080 through 3087 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEstpInstance = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4))NEWLINEmstCistBridgePriority = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 61440)).clone(32768)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstCistBridgePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistBridgePriority.setDescription('The writable portion of the MSTI Bridge Identifier. comprising of the first two octets. The values that are set for Bridge Priority must be in steps of 4096.')NEWLINEmstCistStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistStatus.setDescription('The administrative status requested by management for the MST feature. The value enabled(1) indicates that Mst should be enabled in the device on all ports. The value disabled(2) indicates that Mst should be disabled in the device on all ports. The object can be set to enabled(1) if and only if, fsMIMstSystemControl set to start.')NEWLINEmstMstiBridgeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3), )NEWLINEif mibBuilder.loadTexts: mstMstiBridgeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiBridgeTable.setDescription('Table containing Bridge Information specific to Spanning Tree Instance. This table maintains context ID as one more index to support Multiple Instances.')NEWLINEmstMstiBridgeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mstMstiInstanceIndex"))NEWLINEif mibBuilder.loadTexts: mstMstiBridgeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiBridgeEntry.setDescription('Entry indicating the Bridge Information.')NEWLINEmstMstiInstanceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiInstanceIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiInstanceIndex.setDescription('Spanning Tree Instance to which the information belongs.')NEWLINEmstMstiBridgePriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 61440)).clone(32768)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstMstiBridgePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiBridgePriority.setDescription('The writable portion of the MSTI Bridge Identifier. comprising of the first two octets. The values that are set for Bridge Priority must be in steps of 4096.')NEWLINEmstMstiStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiStatus.setDescription('The administrative status requested by management for the MST feature. The value enabled(1) indicates that Mst should be enabled in the device on all ports. The value disabled(2) indicates that Mst should be disabled in the device on all ports. The object can be set to enabled(1) if and only if, fsMIMstSystemControl set to start.')NEWLINEstpInstancePortTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5))NEWLINEmstCistPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1), )NEWLINEif mibBuilder.loadTexts: mstCistPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortTable.setDescription('This table contains Common Spanning Tree Port Information.')NEWLINEmstCistPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mstCistPort"))NEWLINEif mibBuilder.loadTexts: mstCistPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortEntry.setDescription('A list of information maintained by every port for Common Spanning tree.')NEWLINEmstCistPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))NEWLINEif mibBuilder.loadTexts: mstCistPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPort.setDescription('The Port number of the port for which this entry contains spanning tree information.')NEWLINEmstCistPortDesignatedBridge = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 2), BridgeId()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistPortDesignatedBridge.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortDesignatedBridge.setDescription("The unique Bridge Identifier of the bridge which this port considers to be the Designated Bridge for the port's segment.")NEWLINEmstCistPortAdminPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstCistPortAdminPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortAdminPathCost.setDescription('The contribution of this port to the path cost of paths towards the MSTI Root which include this port.')NEWLINEmstCistPortPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstCistPortPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortPathCost.setDescription('The contribution of this port to the path cost of paths towards the MSTI Root which include this port.')NEWLINEmstCistPortPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 240)).clone(128)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstCistPortPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortPriority.setDescription('The four most significant bits of the Port Identifier for a given Spanning Tree instance can be modified independently for each Spanning Tree instance supported by the Bridge. The values that are set for Port Priority must be in steps of 16.')NEWLINEmstCistForcePortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistForcePortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistForcePortState.setDescription("Current state of the Port which can be changed to either Disabled or Enabled for the specific spanning tree instance. This object can be set to enabled only if the 'fsMIMstCistForcePortState' is set to 'enabled' for this port")NEWLINEmstCistCurrentPortRole = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("disabled", 0), ("alternate", 1), ("backup", 2), ("root", 3), ("designated", 4), ("master", 5)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistCurrentPortRole.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistCurrentPortRole.setDescription('Current Port Role of the port for this spanning tree instance.')NEWLINEmstMstiPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2), )NEWLINEif mibBuilder.loadTexts: mstMstiPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortTable.setDescription('This table contains Spanning Tree Instance Specific Port Information.')NEWLINEmstMstiPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mstMstiPort"), (0, "DES-1210-28MEbx", "mstInstanceIndex"))NEWLINEif mibBuilder.loadTexts: mstMstiPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortEntry.setDescription('A list of information maintained by every port for each and every spanning tree instance.')NEWLINEmstMstiPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))NEWLINEif mibBuilder.loadTexts: mstMstiPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPort.setDescription('The Port number of the port for which this entry contains spanning tree information.')NEWLINEmstMstiPortDesignatedBridge = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 2), BridgeId()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiPortDesignatedBridge.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortDesignatedBridge.setDescription("The unique Bridge Identifier of the bridge which this port considers to be the Designated Bridge for the port's segment.")NEWLINEmstMstiPortAdminPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstMstiPortAdminPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortAdminPathCost.setDescription('The contribution of this port to the path cost of paths towards the MSTI Root which include this port.')NEWLINEmstMstiPortPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstMstiPortPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortPathCost.setDescription('The contribution of this port to the path cost of paths towards the MSTI Root which include this port.')NEWLINEmstMstiPortPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 240)).clone(128)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstMstiPortPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortPriority.setDescription('The four most significant bits of the Port Identifier for a given Spanning Tree instance can be modified independently for each Spanning Tree instance supported by the Bridge. The values that are set for Port Priority must be in steps of 16.')NEWLINEmstMstiForcePortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiForcePortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiForcePortState.setDescription("Current state of the Port which can be changed to either Disabled or Enabled for the specific spanning tree instance. This object can be set to enabled only if the 'fsMIMstCistForcePortState' is set to 'enabled' for this port")NEWLINEmstMstiCurrentPortRole = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("disabled", 0), ("alternate", 1), ("backup", 2), ("root", 3), ("designated", 4), ("master", 5)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiCurrentPortRole.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiCurrentPortRole.setDescription('Current Port Role of the port for this spanning tree instance.')NEWLINEstaticMcastTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1), )NEWLINEif mibBuilder.loadTexts: staticMcastTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastTable.setDescription('A list of the Static MACs')NEWLINEstaticMcastEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "staticMcastVlanID"), (0, "DES-1210-28MEbx", "staticMcastMac"), (0, "DES-1210-28MEbx", "staticMcastEgressPorts"), (0, "DES-1210-28MEbx", "staticMcastIpAddr"))NEWLINEif mibBuilder.loadTexts: staticMcastEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastEntry.setDescription('A Static MAC entry containing the mac and forwarding port.')NEWLINEstaticMcastVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMcastVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastVlanID.setDescription('The VLAN ID of the static MAC entry.')NEWLINEstaticMcastMac = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 2), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMcastMac.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastMac.setDescription('The MAC address associated of the static MAC entry.')NEWLINEstaticMcastEgressPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 3), PortList().subtype(subtypeSpec=ValueSizeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMcastEgressPorts.setReference('IEEE 802.1Q/D11 Section 12.7.7.3, 11.2.3.2.3')NEWLINEif mibBuilder.loadTexts: staticMcastEgressPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastEgressPorts.setDescription('The set of ports to which frames received from a specific port and destined for a specific Multicast or Broadcast MAC address must be forwarded, regardless of any dynamic information e.g. from GMRP. A port may not be added in this set if it is already a member of the set of ports in dot1qStaticMulticastForbiddenEgressPorts. The default value of this object is a string of ones of appropriate length.')NEWLINEstaticMcastIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 4), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMcastIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastIpAddr.setDescription('Static Multicast IP Address.')NEWLINEstaticMcastStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 5), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticMcastStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastStatus.setDescription('The status of an entry in the Static Mcast Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINEdot1qVlanManagementOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanManagementOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanManagementOnOff.setDescription('Enable/Disable management VLAN mechanism.')NEWLINEdot1qVlanManagementid = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 3), Integer32().clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanManagementid.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanManagementid.setDescription('The management VLAN ID, which will allow to forward packets of that VLAN to CPU.')NEWLINEdot1qVlanAsyOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanAsyOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanAsyOnOff.setDescription('Enable/Disable IEEE 802.1Q Asymmetric VLAN')NEWLINEdot1qVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6), )NEWLINEif mibBuilder.loadTexts: dot1qVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanTable.setDescription('A table containing static configuration information for each VLAN configured into the device by (local or network) management. All entries are permanent and will be restored after the device is reset.')NEWLINEdot1qVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dot1qVlanName"))NEWLINEif mibBuilder.loadTexts: dot1qVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanEntry.setDescription('Information for a VLAN configured into the device by (local or network) management.')NEWLINEdot1qVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanName.setReference('IEEE 802.1Q/D11 Section 12.10.2.1')NEWLINEif mibBuilder.loadTexts: dot1qVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanName.setDescription('An administratively assigned string, which may be used to identify the VLAN.')NEWLINEdot1qVlanEgressPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 2), PortList()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanEgressPorts.setReference('IEEE 802.1Q/D11 Section 12.7.7.3, 11.2.3.2.3')NEWLINEif mibBuilder.loadTexts: dot1qVlanEgressPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanEgressPorts.setDescription('The set of ports which are permanently assigned to the egress list for this VLAN by management. Changes to a bit in this object affect the per-port per-VLAN Registrar control for Registration Fixed for the relevant GVRP state machine on each port. A port may not be added in this set if it is already a member of the set of ports in dot1qVlanForbiddenEgressPorts. The default value of this object is a string of zeros of appropriate length, indicating not fixed.')NEWLINEdot1qVlanForbiddenPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanForbiddenPorts.setReference('IEEE 802.1Q/D11 Section 12.7.7.3, 11.2.3.2.3')NEWLINEif mibBuilder.loadTexts: dot1qVlanForbiddenPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanForbiddenPorts.setDescription('The set of ports which are prohibited by management from being included in the egress list for this VLAN. Changes to this object that cause a port to be included or excluded affect the per-port per-VLAN Registrar control for Registration Forbidden for the relevant GVRP state machine on each port. A port may not be added in this set if it is already a member of the set of ports in dot1qVlanEgressPorts. The default value of this object is a string of zeros of appropriate length, excluding all ports from the forbidden set.')NEWLINEdot1qVlanUntaggedPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 4), PortList()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanUntaggedPorts.setReference('IEEE 802.1Q/D11 Section 12.10.2.1')NEWLINEif mibBuilder.loadTexts: dot1qVlanUntaggedPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanUntaggedPorts.setDescription('The set of ports which should transmit egress packets for this VLAN as untagged. The default value of this object for the default VLAN (dot1qVlanIndex = 1) is a string of appropriate length including all ports. There is no specified default for other VLANs. If a device agent cannot support the set of ports being set then it will reject the set operation with an error. An example might be if a manager attempts to set more than one VLAN to be untagged on egress where the device does not support this IEEE 802.1Q option.')NEWLINEdot1qVlanAdvertisementStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanAdvertisementStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanAdvertisementStatus.setDescription('Enable/Disable Advertisement Status of the IEEE 802.1Q VLAN.')NEWLINEdot1qVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 6), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanRowStatus.setDescription('The status of a row in dot1qVlanTable. By setting this object, new entries can be created in dot1qVlanTable and existing entries can be removed from dot1qVlanTable. It can be used as specified in the SNMP v2 standard.')NEWLINEdot1qVlanPVIDAutoAssignOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanPVIDAutoAssignOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanPVIDAutoAssignOnOff.setDescription('Enable/Disable VLAN PVID auto assignment')NEWLINEgvrpGVRPGlobalSettingsOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpGVRPGlobalSettingsOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpGVRPGlobalSettingsOnOff.setDescription('Enable/Disable GVRP mechanism.')NEWLINEgvrpSettingsJoinTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100, 100000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsJoinTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsJoinTime.setDescription('The Join Time value assigned to this Join Time field. This 16-bit value is read-write.')NEWLINEgvrpSettingsLeaveTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100, 100000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsLeaveTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsLeaveTime.setDescription('The Leave Time value assigned to this Leave Time field. This 16-bit value is read-write.')NEWLINEgvrpSettingsLeaveAllTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100, 100000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsLeaveAllTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsLeaveAllTime.setDescription('The Leave_All Time value assigned to this Leave_All Time field. This 16-bit value is read-write.')NEWLINEgvrpSettingsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5), )NEWLINEif mibBuilder.loadTexts: gvrpSettingsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsTable.setDescription('A table containing static configuration information for each GVRP configured into the device by (local or network) management. All entries are permanent and will be restored after the device is reset.')NEWLINEgvrpSettingsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "gvrpSettingsPortControlIndex"))NEWLINEif mibBuilder.loadTexts: gvrpSettingsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsEntry.setDescription('Information for a GVRP configured into the device by (local or network) management.')NEWLINEgvrpSettingsPortControlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: gvrpSettingsPortControlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsPortControlIndex.setDescription('The index of the port.')NEWLINEgvrpSettingsPVID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsPVID.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsPVID.setDescription('The PVID value assigned to this Aggregation Port. This 16-bit value is read-write.')NEWLINEgvrpSettingsGVRPState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsGVRPState.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsGVRPState.setDescription('Enable/Disable GVRP State to this Aggregation Port.')NEWLINEgvrpSettingsIngressChecking = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsIngressChecking.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsIngressChecking.setDescription('Enable/Disable Ingress Checking mechanism of GVRP to this Aggregation Port.')NEWLINEgvrpSettingsAcceptableFrameType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allFrames", 1), ("taggedOnly", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsAcceptableFrameType.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsAcceptableFrameType.setDescription('Chose types All Frames/Tagged to this Aggregation Port.')NEWLINEdhcpBOOTPRelayControl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1))NEWLINEdhcpBOOTPRelayManagement = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2))NEWLINEdhcpBOOTPRelayManagementOption82 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2))NEWLINEdhcpBOOTPRelayState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayState.setDescription('This object indicates DHCP relay function is enabled or disabled.')NEWLINEdhcpBOOTPRelayHopCount = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayHopCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayHopCount.setDescription('This object indicates the maximum number of router hops that the BOOTP packets can cross.')NEWLINEdhcpBOOTPRelayTimeThreshold = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayTimeThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayTimeThreshold.setDescription('This object indicates the minimum time in seconds within which the switch must relay the DHCP request. If this time is exceeded, the switch will drop the DHCP packet.')NEWLINEdhcpBOOTPRelayEnablePortlist = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayEnablePortlist.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayEnablePortlist.setDescription('This object indicates DHCP relay function is enabled or disabled by portlist.')NEWLINEdhcpRelayVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 5), )NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanTable.setDescription('This table indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpRelayVlanTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpRelayVlanSettingsVLANID"))NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanTableEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanTableEntry.setDescription('A list of information indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpRelayVlanSettingsVLANID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanSettingsVLANID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanSettingsVLANID.setDescription('This object displays the current VLAN ID of the device.')NEWLINEdhcpRelayVlanSettingsState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanSettingsState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanSettingsState.setDescription('This object indicates DHCP relay function of VLAN is enabled or disabled.')NEWLINEdhcpBOOTPRelayInterfaceSettingsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1), )NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsTable.setDescription('This table indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpBOOTPRelayInterfaceSettingsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpBOOTPRelayInterface"), (0, "DES-1210-28MEbx", "dhcpBOOTPRelayServerIP"))NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsEntry.setDescription('A list of information indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpBOOTPRelayInterface = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 12))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterface.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterface.setDescription('This object indicates the name of the IP interface.')NEWLINEdhcpBOOTPRelayServerIP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1, 1, 2), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayServerIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayServerIP.setDescription('This object indicates the DHCP server IP address.')NEWLINEdhcpBOOTPRelayInterfaceSettingsRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1, 1, 3), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEdhcpBOOTPRelayOption82State = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82State.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82State.setDescription('This object indicates DHCP relay option 82 function is enabled or disabled.')NEWLINEdhcpBOOTPRelayOption82CheckState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CheckState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CheckState.setDescription('This object indicates DHCP relay option 82 Check function is enabled or disabled.')NEWLINEdhcpBOOTPRelayOption82Policy = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("replace", 1), ("drop", 2), ("keep", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82Policy.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82Policy.setDescription('This object indicates DHCP relay option 82 policy.')NEWLINEdhcpBOOTPRelayOption82RemoteIDType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("default", 1), ("userdefined", 2), ("userdefinedhex", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82RemoteIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82RemoteIDType.setDescription('This object indicates the type of remote ID. If the type is default, the remote ID will be the MAC address of the device, otherwise, the remote ID can be defined by writing to the swDHCPRelayOption82RemoteID object.')NEWLINEdhcpBOOTPRelayOption82RemoteID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 5), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82RemoteID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82RemoteID.setDescription('This object displays the current remote ID of the device. If swDHCPRelayOption82RemoteIDType is set to default, the value will be the MAC address of the device, and this object cannot be modified. If swDHCPRelayOption82RemoteIDType is set to user-defined or user-defined-hex, a new value can be written to this object.')NEWLINEdhcpBOOTPRelayOption82CircuitIDType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("default", 1), ("userdefined", 2), ("userdefinedhex", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CircuitIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CircuitIDType.setDescription('This object indicates the type of remote ID. If the type is default, the circuit ID will be blank, otherwise, the circuit ID can be defined by writing to the dhcpBOOTPRelayOption82CircuitID object.')NEWLINEdhcpBOOTPRelayOption82CircuitID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 8), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CircuitID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CircuitID.setDescription('This object displays the current remote ID of the device. If dhcpBOOTPRelayOption82CircuitIDType is set to default, the value will be the MAC address of the device, and this object cannot be modified. If dhcpBOOTPRelayOption82CircuitIDType is set to user-defined or user-defined-hex, a new value can be written to this object.')NEWLINEdhcpLocalRelayGlobalState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayGlobalState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayGlobalState.setDescription('This object indicates DHCP local relay function of VLAN is enabled or disabled.')NEWLINEdhcpLocalRelayTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 2), )NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayTable.setDescription('This table indicates the IP address as a destination to forward (local relay) DHCP packets to.')NEWLINEdhcpLocalRelayTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpLocalRelaySettingsVLANID"))NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayTableEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayTableEntry.setDescription('A list of information indicates the IP address as a destination to forward (local relay) DHCP packets to.')NEWLINEdhcpLocalRelaySettingsVLANID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpLocalRelaySettingsVLANID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelaySettingsVLANID.setDescription('This object displays the current VLAN ID of the device.')NEWLINEdhcpLocalRelaySettingsState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpLocalRelaySettingsState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelaySettingsState.setDescription('This object indicates DHCP local relay function of VLAN is enabled or disabled.')NEWLINEdhcpLocalRelayEnablePortlist = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayEnablePortlist.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayEnablePortlist.setDescription('This object indicates DHCP local relay function is enabled or disabled by portlist.')NEWLINElaSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1))NEWLINElaPortControl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2))NEWLINEclass PortLaMode(TextualConvention, Integer32):NEWLINE description = 'Defines how a Port Channel does channeling. lacp(1) - place the port into passive negotiation state, in which the port waits for its peer to initiate negotiation. static(2) - force the port to enable channeling. disable(3) - channeling is disabled.'NEWLINE status = 'current'NEWLINE subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))NEWLINE namedValues = NamedValues(("lacp", 1), ("static", 2), ("disable", 3))NEWLINENEWLINEclass LacpKey(TextualConvention, Integer32):NEWLINE description = 'The Actor or Partner Key value (0..65535).'NEWLINE status = 'current'NEWLINE subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 65535)NEWLINENEWLINElaStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: laStatus.setDescription('Sets the Link Aggregation Module administrative status as enabled or disabled.')NEWLINElaPortChannelTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3), )NEWLINEif mibBuilder.loadTexts: laPortChannelTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelTable.setDescription('A Port-channel is created through ifMain table. After the creation of the port-channel, corresponding logical interface will be created in the ifMain table. This Port-channel table is indexed through Key values and allows to configure link selection policy and the Mac address for the port-channel. All other objects in this table displays the details of the port-channel.')NEWLINElaPortChannelEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "laPortChannelIfIndex"))NEWLINEif mibBuilder.loadTexts: laPortChannelEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelEntry.setDescription('There is one entry in this table for each created port-channel port.')NEWLINElaPortChannelIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: laPortChannelIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelIfIndex.setDescription("The index of the port-channel(Aggregator's interface index). ")NEWLINElaPortChannelMemberList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1, 2), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortChannelMemberList.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelMemberList.setDescription('Member Port list of the port channel. Add the ports as a aggregation member associated of a port-channel.')NEWLINElaPortChannelMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1, 3), PortLaMode()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortChannelMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelMode.setDescription('Current Operating Channel Mode of the port channel Lacp(1) - forcing the port to negotiate with the partner. manual(2) - force the port to enable channeling (Manual). disable(3) - channeling is disabled.')NEWLINElaPortChannelMasterPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1, 4), InterfaceIndex()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortChannelMasterPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelMasterPort.setDescription('The master port of the port-channel. ')NEWLINElaAlgorithm = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("sourceMAC", 1), ("destMAC", 2), ("sourceAndDestMAC", 3), ("sourceIP", 4), ("destIP", 5), ("sourceAndDestIP", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laAlgorithm.setStatus('current')NEWLINEif mibBuilder.loadTexts: laAlgorithm.setDescription('Sets the Link Aggregation load balance algorithm.')NEWLINElaPortControlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1), )NEWLINEif mibBuilder.loadTexts: laPortControlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortControlTable.setDescription('A table that contains Link Aggregation Control configuration information about every Aggregation Port associated with this device. A row appears in this table for each physical port.')NEWLINElaPortControlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "laPortControlIndex"))NEWLINEif mibBuilder.loadTexts: laPortControlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortControlEntry.setDescription('A list of Link Aggregation Control configuration parameters for each Aggregation Port on this device.')NEWLINElaPortControlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: laPortControlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortControlIndex.setDescription('The index of the port.')NEWLINElaPortActorPortPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortActorPortPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortActorPortPriority.setDescription('The priority value assigned to this Aggregation Port. This 16-bit value is read-write.')NEWLINElaPortActorActivity = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("active", 1), ("passive", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortActorActivity.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortActorActivity.setDescription('This object indicates LACP_Activity to this Aggregation Port. LACP can be configured in one of two modes: active or passive. In active mode it will always send frames along the configured links. If the actor and partner are both in passive mode, they do not exchange LACP packets.')NEWLINElaPortActorTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("short", 1), ("long", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortActorTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortActorTimeout.setDescription('This object indicates LACP_Timeout to this Aggregation Port. short(1) - LACP Timeout 3 seconds. long (2) - LACP Timeout 90 seconds.')NEWLINEstaticVlanBaseTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5))NEWLINEstaticDisableAutoLearn = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("on", 1), ("off", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticDisableAutoLearn.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticDisableAutoLearn.setDescription('Set on to disable Auto Learning Excluding Uplink Port and set off to enable Auto Learning.')NEWLINEstaticAutoLearningList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 2), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticAutoLearningList.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticAutoLearningList.setDescription("The set of the device's member ports that belong to the Static MAC auto learning enable/disable. For example, when Disable Auto Learning is enable, the octet value set up as '# 0x0F 0xFF 0xFF 0xFF' means from port 1 to port 4 are not in auto learning state, the other ports are in auto learning state. It can be set up when Disable Auto Learning is enable.")NEWLINEstaticTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3), )NEWLINEif mibBuilder.loadTexts: staticTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticTable.setDescription('A list of the Static MACs')NEWLINEstaticEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "staticVlanID"), (0, "DES-1210-28MEbx", "staticMac"), (0, "DES-1210-28MEbx", "staticPort"))NEWLINEif mibBuilder.loadTexts: staticEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticEntry.setDescription('A Static MAC entry containing the mac and forwarding port.')NEWLINEstaticVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanID.setDescription('The VLAN ID of the static MAC entry.')NEWLINEstaticMac = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1, 2), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMac.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMac.setDescription('The MAC address associated of the static MAC entry.')NEWLINEstaticPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticPort.setDescription('The forwarding port of the static MAC entry. For all machines give maximum port number.')NEWLINEstaticStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1, 4), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticStatus.setDescription('The status of an entry in the Static MAC Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available. The trunk member port can not set up static MAC.')NEWLINEautoFdbTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4), )NEWLINEif mibBuilder.loadTexts: autoFdbTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbTable.setDescription('A list of the Auto Fdb')NEWLINEautoFdbEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "autoFdbIPAddress"))NEWLINEif mibBuilder.loadTexts: autoFdbEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbEntry.setDescription('A auto fdb entry containing the ipaddress')NEWLINEautoFdbIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 1), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbIPAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbIPAddress.setDescription('The IpAddress of the autoFdbEntry.')NEWLINEautoFdbVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbVlanID.setDescription('The VlanID of the autoFdbEntry.')NEWLINEautoFdbMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbMacAddress.setDescription('The Mac Address of the autoFdbEntry.')NEWLINEautoFdbPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbPort.setDescription('The Port of the autoFdbEntry.')NEWLINEautoFdbTimeStamp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 5), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbTimeStamp.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbTimeStamp.setDescription('The Time Stamp of the autoFdbEntry.')NEWLINEautoFdbStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 6), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: autoFdbStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbStatus.setDescription('The status of an entry in the Auto Fdb Table. Only a subset of the rowstatus variables (createAndGo, createAndWait,destroy) are available.')NEWLINEstaticVlanBaseAutoLearnList1k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList1k.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList1k.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this Auto Learn, the bit corresponding to that VLAN is set to '1'. Write AutoLearnList1k use 256 character, and conform to the foregoing rules.")NEWLINEstaticVlanBaseAutoLearnList2k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList2k.setDescription('A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1025 through 2048. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this Auto Learn. Write AutoLearnList2k use 256 character, and conform to the foregoing rules.')NEWLINEstaticVlanBaseAutoLearnList3k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2049 through 3072. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this Auto Learn the bit corresponding to that VLAN is set to '1'. Write AutoLearnList3k use 256 character, and conform to the foregoing rules.")NEWLINEstaticVlanBaseAutoLearnList4k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3073 through 4094. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this Auto Learn the bit corresponding to that VLAN is set to '1'. Write AutoLearnList4k use 256 character, and conform to the foregoing rules.")NEWLINEstaticVlanBaseEnableAutoLearn = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseEnableAutoLearn.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseEnableAutoLearn.setDescription('Set enable vlan list to auto learn, and range 1-4094.')NEWLINEstaticVlanBaseDisableAutoLearn = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseDisableAutoLearn.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseDisableAutoLearn.setDescription('Set disable vlan list to auto learn, and range 1-4094.')NEWLINEigsSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1))NEWLINEigsVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3))NEWLINEigsHost = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6))NEWLINEigsStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsStatus.setDescription("Enables or disables IGMP snooping in the system. When set to 'enabled', the IGS module starts protocol operations. When set to 'disabled', the IGS module stops performing protocol operations.")NEWLINEigsRouterPortPurgeInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60, 600)).clone(260)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsRouterPortPurgeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsRouterPortPurgeInterval.setDescription("This is the interval (in seconds) after which a learnt router port entry will be purged. For each router port learnt, this timer runs for 'RouterPortPurgeInterval' seconds.When the timer expires, the learnt router port entry is purged. However if control messages are received from the router before the timer expiry, then the timer is restarted.")NEWLINEigsHostPortPurgeInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(130, 153025)).clone(260)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsHostPortPurgeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostPortPurgeInterval.setDescription("This is the interval (in seconds) after which a learnt port entry will be purged. For each port on which report has been received this timer runs for 'PortPurgeInterval' seconds. This timer will be restarted whenever a report message is received from a host on the specific port. If the timer expires, then , the learnt port entry will be purged from the multicast group.")NEWLINEigsDataDrivenLearningMaxLearnedEntryVlaue = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024)).clone(64)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsDataDrivenLearningMaxLearnedEntryVlaue.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsDataDrivenLearningMaxLearnedEntryVlaue.setDescription('The maximum data driven learning entry value.')NEWLINEigsReportToAllPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsReportToAllPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsReportToAllPort.setDescription("Enables or disables IGMP snooping in the system. When set to 'enabled', the IGS module forwards packets to report to all port. When set to 'disabled', the IGS module forwards packets to router port only.")NEWLINEigsVlanRouterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 3), )NEWLINEif mibBuilder.loadTexts: igsVlanRouterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRouterTable.setDescription('This table contains the list of ports through which a router, in a particular VLAN is reachable.')NEWLINEigsVlanRouterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igsVlanRouterVlanId"))NEWLINEif mibBuilder.loadTexts: igsVlanRouterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRouterEntry.setDescription('Contains the VLAN ID and list of ports on which routers are present in the VLAN.')NEWLINEigsVlanRouterVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanRouterVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRouterVlanId.setDescription('VLAN ID of the ports through which router is reachable.')NEWLINEigsVlanRouterPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 3, 1, 2), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanRouterPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRouterPortList.setDescription('List of ports on which routers are present. These router ports are learnt through control messages received from routers, and can also be configured statically.')NEWLINEigsVlanFilterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4), )NEWLINEif mibBuilder.loadTexts: igsVlanFilterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFilterTable.setDescription('This table contains configuration of snooping on specific Vlans. This Table is valid only when VLAN is enabled in the system.')NEWLINEigsVlanFilterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igsVlanFilterVlanId"))NEWLINEif mibBuilder.loadTexts: igsVlanFilterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFilterEntry.setDescription('Contains snooping status , version and fast leave configuration for a specific VLAN.')NEWLINEigsVlanFilterVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanFilterVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFilterVlanId.setDescription('Index of IgsVlanFilterEntry. This object indicates the VLAN ID for which the snooping configurations in IgsVlanFilterEntry is to be done.')NEWLINEigsVlanSnoopStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanSnoopStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanSnoopStatus.setDescription('This object allows you to enable/disable IGS function on a specific VLAN.')NEWLINEigsVlanQuerier = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanQuerier.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanQuerier.setDescription('Indicates whether the switch is configured as a querier in the VLAN')NEWLINEigsVlanCfgQuerier = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanCfgQuerier.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanCfgQuerier.setDescription("The snooping switch can be configured as a querier via this object to send out IGMP general queries when IGMP routers are not present in the VLAN. When set to 'enabled', the switch will generate general queries.")NEWLINEigsVlanQueryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60, 600)).clone(125)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanQueryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanQueryInterval.setDescription('This is the interval (in seconds) for which the switch sends general queries when it is configured as a querier for the VLAN. A switch should be configured as a querier for a VLAN only when there is no queriers in the network.')NEWLINEigsVlanRtrPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanRtrPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRtrPortList.setDescription('List of ports which are configured statically as router ports')NEWLINEigsVlanFbdRtrPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 7), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanFbdRtrPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFbdRtrPortList.setDescription('List of ports which can be configured statically as forbidden router ports.')NEWLINEigsVlanFastLeave = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanFastLeave.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFastLeave.setDescription("Enables or disables fast leave for the VLAN. When it is 'disabled',on reception of a leave message, the switch checks if they are any interested receivers for the group by sending a group specific query before removing the port from the forwarding table. If set to 'enabled', the switch does not send a group specific query and immediately removes the port from the forwarding table.")NEWLINEigsVlanDataDrivenLearningStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanDataDrivenLearningStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanDataDrivenLearningStatus.setDescription('This object allows you to enable/disable Data Driven Learning function on a specific VLAN.')NEWLINEigsVlanQuerierVersionStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(3, 2))).clone(namedValues=NamedValues(("igmp-v3", 3), ("igmp-v2", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanQuerierVersionStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanQuerierVersionStatus.setDescription('This object allows you to enable/disable Querier Version function on a specific VLAN.')NEWLINEigsVlanDataDrivenLearningAgeOutStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanDataDrivenLearningAgeOutStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanDataDrivenLearningAgeOutStatus.setDescription('This object allows you to enable/disable Data Driven Learning Age Out State on a specific VLAN.')NEWLINEigsVlanReportSuppression = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanReportSuppression.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanReportSuppression.setDescription('Enables or disables Report suppression in the system.')NEWLINEigsVlanRobustnessValue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 255)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanRobustnessValue.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRobustnessValue.setDescription("When the switch receives leave message on a port, it sends group specific query to check if there are any other interested receivers for the group. This attribute defines the maximum number of queries sent by the switch before deleting the port from the group membership information in the forwarding database. If the maximum retry count exceeds 'igsRobustnessValue', then the port will be deleted from the multicast group membership information in the forwarding database and received leave message will be forwarded onto the router ports if there are no interested receivers for the group.")NEWLINEigsVlanGrpQueryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 14), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 25)).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanGrpQueryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanGrpQueryInterval.setDescription("The value of this attribute defines the time period with which the switch will send group specific queries on a port to check if there is any intersted receivers. The switch will send 'igsRobustnessValue' queries before removing the port from the group membership information in the forwarding database.")NEWLINEigsVlanQueryMaxResponseTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 15), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 25)).clone(10)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanQueryMaxResponseTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanQueryMaxResponseTime.setDescription('The maximum query response time advertised in IGMPv2 general queries on this interface.')NEWLINEigsVlanMulticastGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5), )NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupTable.setDescription('This table contains MAC based multicast forwarding information.')NEWLINEigsVlanMulticastGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igsVlanMulticastGroupVlanId"), (0, "DES-1210-28MEbx", "igsVlanMulticastGroupIpAddress"))NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupEntry.setDescription('This table contains VLAN ID, multicast group MAC address and the list of ports onto which the multicast data packets for group should be forwarded.')NEWLINEigsVlanMulticastGroupVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupVlanId.setDescription('VLAN ID pertaining to the Multicast forwarding entry')NEWLINEigsVlanMulticastGroupIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1, 2), InetAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupIpAddress.setDescription('Multicast group IP address. This object indicates that a multicast group address was learned in the switch and be represented as IP address format.')NEWLINEigsVlanMulticastGroupMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupMacAddress.setDescription('Multicast group MAC address. This object indicates that a multicast group address was learned in the switch and be represented as MAC address format.')NEWLINEigsVlanMulticastGroupPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1, 4), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupPortList.setDescription('List of ports onto which the multicast data packets destined for this group will be forwarded.')NEWLINEigsHostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1), )NEWLINEif mibBuilder.loadTexts: igsHostTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTable.setDescription('This table is used to manage the IGMP Host based Fast Leave function of the switch.')NEWLINEigsHostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igsHostTableVLANID"), (0, "DES-1210-28MEbx", "igsHostTableGroupAddress"), (0, "DES-1210-28MEbx", "igsHostTablePort"), (0, "DES-1210-28MEbx", "igsHostTableHostIPAddress"))NEWLINEif mibBuilder.loadTexts: igsHostEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostEntry.setDescription('Contains management entities for IGMP Host based fast leave function.')NEWLINEigsHostTableVLANID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsHostTableVLANID.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTableVLANID.setDescription('VLAN ID of Host table entry.')NEWLINEigsHostTableGroupAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1, 2), InetAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsHostTableGroupAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTableGroupAddress.setDescription('Group address of Host table entry.')NEWLINEigsHostTablePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsHostTablePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTablePort.setDescription('Port number of Host table entry. For all machines give maximum port number.')NEWLINEigsHostTableHostIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1, 4), InetAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsHostTableHostIPAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTableHostIPAddress.setDescription('Host IP address of Group in Host table entry.')NEWLINEmldsSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1))NEWLINEmldsVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3))NEWLINEmldsHost = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4))NEWLINEmldsStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsStatus.setDescription("Enables or disables MLD snooping in the system. When set to 'enabled', the MLDS module starts protocol operations. When set to 'disabled', the MLDS module stops performing protocol operations.")NEWLINEmldsRouterPortPurgeInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60, 600)).clone(260)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsRouterPortPurgeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsRouterPortPurgeInterval.setDescription("This is the interval (in seconds) after which a learnt router port entry will be purged. For each router port learnt, this timer runs for 'RouterPortPurgeInterval' seconds.When the timer expires, the learnt router port entry is purged. However if control messages are received from the router before the timer expiry, then the timer is restarted.")NEWLINEmldsHostPortPurgeInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(130, 153025)).clone(260)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsHostPortPurgeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostPortPurgeInterval.setDescription("This is the interval (in seconds) after which a learnt port entry will be purged. For each port on which report has been received this timer runs for 'PortPurgeInterval' seconds. This timer will be restarted whenever a report message is received from a host on the specific port. If the timer expires, then , the learnt port entry will be purged from the multicast group.")NEWLINEmldsDataDrivenLearningMaxLearnedEntryVlaue = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024)).clone(64)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsDataDrivenLearningMaxLearnedEntryVlaue.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsDataDrivenLearningMaxLearnedEntryVlaue.setDescription('The maximum data driven learning entry value.')NEWLINEmldsVlanRouterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 3), )NEWLINEif mibBuilder.loadTexts: mldsVlanRouterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRouterTable.setDescription('This table contains the list of ports through which a router, in a particular VLAN is reachable.')NEWLINEmldsVlanRouterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mldsVlanRouterVlanId"))NEWLINEif mibBuilder.loadTexts: mldsVlanRouterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRouterEntry.setDescription('Contains the VLAN ID and list of ports on which routers are present in the VLAN.')NEWLINEmldsVlanRouterVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanRouterVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRouterVlanId.setDescription('VLAN ID of the ports through which router is reachable.')NEWLINEmldsVlanRouterPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 3, 1, 2), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanRouterPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRouterPortList.setDescription('List of ports on which routers are present. These router ports are learnt through control messages received from routers, and can also be configured statically.')NEWLINEmldsVlanFilterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4), )NEWLINEif mibBuilder.loadTexts: mldsVlanFilterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFilterTable.setDescription('This table contains configuration of snooping on specific Vlans. This Table is valid only when VLAN is enabled in the system.')NEWLINEmldsVlanFilterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mldsVlanFilterVlanId"))NEWLINEif mibBuilder.loadTexts: mldsVlanFilterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFilterEntry.setDescription('Contains snooping status , version and fast leave configuration for a specific VLAN.')NEWLINEmldsVlanFilterVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanFilterVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFilterVlanId.setDescription('Index of MldsVlanFilterEntry. This object indicates the VLAN ID for which the snooping configurations in MldsVlanFilterEntry is to be done.')NEWLINEmldsVlanSnoopStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanSnoopStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanSnoopStatus.setDescription('This object allows you to enable/disable MLDS function on a specific VLAN.')NEWLINEmldsVlanQuerier = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanQuerier.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanQuerier.setDescription('Indicates whether the switch is configured as a querier in the VLAN')NEWLINEmldsVlanCfgQuerier = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanCfgQuerier.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanCfgQuerier.setDescription("The snooping switch can be configured as a querier via this object to send out MLD general queries when IGMP routers are not present in the VLAN. When set to 'enabled', the switch will generate general queries.")NEWLINEmldsVlanQueryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60, 600)).clone(125)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanQueryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanQueryInterval.setDescription('This is the interval (in seconds) for which the switch sends general queries when it is configured as a querier for the VLAN. A switch should be configured as a querier for a VLAN only when there is no queriers in the network.')NEWLINEmldsVlanRtrPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanRtrPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRtrPortList.setDescription('List of ports which are configured statically as router ports')NEWLINEmldsVlanFbdRtrPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 7), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanFbdRtrPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFbdRtrPortList.setDescription('List of ports which can be configured statically as forbidden router ports.')NEWLINEmldsVlanFastLeave = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanFastLeave.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFastLeave.setDescription("Enables or disables fast leave for the VLAN. When it is 'disabled',on reception of a leave message, the switch checks if they are any interested receivers for the group by sending a group specific query before removing the port from the forwarding table. If set to 'enabled', the switch does not send a group specific query and immediately removes the port from the forwarding table.")NEWLINEmldsVlanDataDrivenLearningStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanDataDrivenLearningStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanDataDrivenLearningStatus.setDescription('This object allows you to enable/disable Data Driven Learning function on a specific VLAN.')NEWLINEmldsVlanReportSuppression = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanReportSuppression.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanReportSuppression.setDescription('Enables or disables Report suppression in the system.')NEWLINEmldsVlanRobustnessValue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 255)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanRobustnessValue.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRobustnessValue.setDescription("When the switch receives leave message on a port, it sends group specific query to check if there are any other interested receivers for the group. This attribute defines the maximum number of queries sent by the switch before deleting the port from the group membership information in the forwarding database. If the maximum retry count exceeds 'mldsRobustnessValue', then the port will be deleted from the multicast group membership information in the forwarding database and received leave message will be forwarded onto the router ports if there are no interested receivers for the group.")NEWLINEmldsVlanGrpQueryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 25)).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanGrpQueryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanGrpQueryInterval.setDescription("The value of this attribute defines the time period with which the switch will send group specific queries on a port to check if there is any intersted receivers. The switch will send 'mldsRobustnessValue' queries before removing the port from the group membership information in the forwarding database.")NEWLINEmldsVlanQueryMaxResponseTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 25)).clone(10)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanQueryMaxResponseTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanQueryMaxResponseTime.setDescription('The maximum query response time advertised in MLDv1 general queries on this interface.')NEWLINEmldsVlanMulticastGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5), )NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupTable.setDescription('This table contains MAC based multicast forwarding information.')NEWLINEmldsVlanMulticastGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mldsVlanMulticastGroupVlanId"), (0, "DES-1210-28MEbx", "mldsVlanMulticastGroupIpAddress"))NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupEntry.setDescription('This table contains VLAN ID, multicast group MAC address and the list of ports onto which the multicast data packets for group should be forwarded.')NEWLINEmldsVlanMulticastGroupVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupVlanId.setDescription('VLAN ID pertaining to the Multicast forwarding entry')NEWLINEmldsVlanMulticastGroupIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1, 2), InetAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupIpAddress.setDescription('Multicast group IP address. This object indicates that a multicast group address was learned in the switch and be represented as IP address format.')NEWLINEmldsVlanMulticastGroupMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupMacAddress.setDescription('Multicast group MAC address. This object indicates that a multicast group address was learned in the switch and be represented as MAC address format.')NEWLINEmldsVlanMulticastGroupPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1, 4), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupPortList.setDescription('List of ports onto which the multicast data packets destined for this group will be forwarded.')NEWLINEmldsHostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1), )NEWLINEif mibBuilder.loadTexts: mldsHostTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTable.setDescription('This table is used to manage the IGMP Host based Fast Leave function of the switch.')NEWLINEmldsHostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mldsHostTableVLANID"), (0, "DES-1210-28MEbx", "mldsHostTableGroupAddress"), (0, "DES-1210-28MEbx", "mldsHostTablePort"), (0, "DES-1210-28MEbx", "mldsHostTableHostIPAddress"))NEWLINEif mibBuilder.loadTexts: mldsHostEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostEntry.setDescription('Contains management entities for IGMP Host based fast leave function.')NEWLINEmldsHostTableVLANID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsHostTableVLANID.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTableVLANID.setDescription('VLAN ID of IPv6 Host table entry.')NEWLINEmldsHostTableGroupAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1, 2), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsHostTableGroupAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTableGroupAddress.setDescription('Group address of IPv6 Host table entry.')NEWLINEmldsHostTablePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsHostTablePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTablePort.setDescription('Port number of IPv6 Host table entry. For all machines give maximum port number.')NEWLINEmldsHostTableHostIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1, 4), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsHostTableHostIPAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTableHostIPAddress.setDescription('Host IP address of Group in IPv6 Host table entry.')NEWLINEswAuthenCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1))NEWLINEswAuthStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthStatus.setDescription('Enable/Disable Static 802.1x.')NEWLINEswAuthMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("portBase", 1), ("macBase", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthMode.setDescription('This object indicates the authentication mode of the device.')NEWLINEauthProtocol = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("authProtocolRadiusEap", 1), ("authProtocolLocal", 2))).clone('authProtocolRadiusEap')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: authProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: authProtocol.setDescription('The authentication method used to authenticate users.')NEWLINEswAuthCtrlPktFwdMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("authForwardEap", 1), ("authDropEap", 2))).clone('authForwardEap')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthCtrlPktFwdMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthCtrlPktFwdMode.setDescription('When 802.1x disable, this item can decided eap packet be forward or drop.')NEWLINEswAuthPortAccessCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2))NEWLINEswAuthPortAccessControlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1), )NEWLINEif mibBuilder.loadTexts: swAuthPortAccessControlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthPortAccessControlTable.setDescription('A table that contains the configuration objects for the Authenticator PAE associated with each port. An entry appears in this table for each port that may authenticate access to itself.')NEWLINEswAuthPortAccessControlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "swAuthAuthConfigPortNumber"))NEWLINEif mibBuilder.loadTexts: swAuthPortAccessControlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthPortAccessControlEntry.setDescription('The configuration information for an Authenticator Port.')NEWLINEswAuthAuthConfigPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortNumber.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortNumber.setDescription('A unique value for each port that correlates to port index. Its value ranges between 1 and the value of port number. For all machines give maximum port number.')NEWLINEswAuthAuthQuietPeriod = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)).clone(60)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthQuietPeriod.setReference('9.4.1, quietPeriod.')NEWLINEif mibBuilder.loadTexts: swAuthAuthQuietPeriod.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthQuietPeriod.setDescription('The value, in seconds, of the quietPeriod constant currently in use by the Authenticator PAE state machine.')NEWLINEswAuthAuthSuppTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(12)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthSuppTimeout.setReference('9.4.1, suppTimeout.')NEWLINEif mibBuilder.loadTexts: swAuthAuthSuppTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthSuppTimeout.setDescription('The value, in seconds, of the suppTimeout constant currently in use by the Backend Authentication state machine.')NEWLINEswAuthAuthServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(16)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthServerTimeout.setReference('9.4.1, serverTimeout.')NEWLINEif mibBuilder.loadTexts: swAuthAuthServerTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthServerTimeout.setDescription('The value, in seconds, of the serverTimeout constant currently in use by the Backend Authentication state machine.')NEWLINEswAuthAuthMaxReq = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthMaxReq.setReference('9.4.1, maxReq.')NEWLINEif mibBuilder.loadTexts: swAuthAuthMaxReq.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthMaxReq.setDescription('The value of the maxReq constant currently in use by the Backend Authentication state machine.')NEWLINEswAuthAuthTxPeriod = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(24)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthTxPeriod.setReference('9.4.1, txPeriod.')NEWLINEif mibBuilder.loadTexts: swAuthAuthTxPeriod.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthTxPeriod.setDescription('The value, in seconds, of the txPeriod constant currently in use by the Authenticator PAE state machine.')NEWLINEswAuthAuthReAuthPeriod = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(3600)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthPeriod.setReference('9.4.1, reAuthPerio.')NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthPeriod.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthPeriod.setDescription('The value, in seconds, of the reAuthPeriod constant currently in use by the Reauthentication Timer state machine.')NEWLINEswAuthAuthReAuthentication = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthentication.setReference('9.4.1, reAuthEnable.')NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthentication.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthentication.setDescription('The enable/disable control used by the Reauthentication Timer state machine (8.5.5.1).')NEWLINEswAuthAuthConfigPortControl = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("forceUnauthorized", 1), ("auto", 2), ("forceAuthorized", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortControl.setReference('9.4.1, AuthControlledPortControl.')NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortControl.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortControl.setDescription('The current value of the controlled Port control parameter for the Port.')NEWLINEswAuthAuthCapability = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("authenticator", 1), ("none", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthCapability.setReference('AuthCapability.')NEWLINEif mibBuilder.loadTexts: swAuthAuthCapability.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthCapability.setDescription('The current value of the controlled Port control parameter for the Port.')NEWLINEswAuthAuthDirection = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("both", 0), ("in", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthDirection.setReference('AuthDirection.')NEWLINEif mibBuilder.loadTexts: swAuthAuthDirection.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthDirection.setDescription('The current value of the controlled Port control parameter for the Port.')NEWLINEswAuthUser = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3))NEWLINEswAuthUserTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1), )NEWLINEif mibBuilder.loadTexts: swAuthUserTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserTable.setDescription('A table that contains the configuration objects for the Authenticator PAE associated with each port. An entry appears in this table for each port that may authenticate access to itself.')NEWLINEswAuthUserEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "swAuthUserName"))NEWLINEif mibBuilder.loadTexts: swAuthUserEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserEntry.setDescription('The configuration information for an Authenticator Port.')NEWLINEswAuthUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: swAuthUserName.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserName.setDescription('The unique index value of a row in this table. This object is used to set 802.1X Local user name, The following characters are allowed to input: semicolon, question mark, space, and double quotation mark.')NEWLINEswAuthUserPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthUserPassword.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserPassword.setDescription('This object is used to set 802.1X Local user Password, The following characters are allowed to input: semicolon, question mark, space, and double quotation mark.')NEWLINEswAuthUserStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1, 1, 3), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: swAuthUserStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserStatus.setDescription('The status of this conceptual row in the swAuthUserTable. An entry in this table is not qualified for activation until instances of all corresponding columns have been initialized, either through default values, or through Set operations. The swAuthUserName objects must be explicitly set.')NEWLINEswAuthRadiusServer = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4))NEWLINEiPv4swAuthRadiusServerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1), )NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerTable.setDescription('A table that contains the configuration objects for the Authenticator PAE associated with each port. An entry appears in this table for each port that may authenticate access to itself.')NEWLINEiPv4swAuthRadiusServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "iPv4swAuthRadiusServerIndex"))NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerEntry.setDescription('The configuration information for an Authenticator Port.')NEWLINEiPv4swAuthRadiusServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerIndex.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerIndex.setDescription('A unique value for Authentication RADIUS Server index. Its value ranges between 1 and 3.')NEWLINEiPv4swAuthRadiusServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAddress.setDescription('The IP address of the RADIUS server referred to in this table entry.')NEWLINEiPv4swAuthRadiusServerAuthenticationPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1812)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAuthenticationPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAuthenticationPort.setDescription('The value is for setting UDP Port.')NEWLINEiPv4swAuthRadiusServerAccountingPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1813)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAccountingPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAccountingPort.setDescription('The value is for setting UDP Port.')NEWLINEiPv4swAuthRadiusServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)).clone(5)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerTimeout.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerTimeout.setDescription('The value is for setting UDP Port.')NEWLINEiPv4swAuthRadiusServerRetransmit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerRetransmit.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerRetransmit.setDescription('The value is for setting UDP Port.')NEWLINEiPv4swAuthRadiusServerKey = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerKey.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerKey.setDescription('This object is used to set 802.1X Radius Server Key, The following characters are allowed to input: semicolon, question mark, space, and double quotation mark.')NEWLINEiPv4swAuthRadiusServerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 8), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerStatus.setDescription('The status of this conceptual row in the swAuthRadiusServerTable. An entry in this table is not qualified for activation until instances of all corresponding columns have been initialized, either through default values, or through Set operations. The swAuthRadiusServerIndex objects must be explicitly set.')NEWLINEswAuthRadiusServerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2), )NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerTable.setDescription('A table that contains the configuration objects for the Authenticator PAE associated with each port. An entry appears in this table for each port that may authenticate access to itself.')NEWLINEswAuthRadiusServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "swAuthRadiusServerIndex"))NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerEntry.setDescription('The configuration information for an Authenticator Port.')NEWLINEswAuthRadiusServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerIndex.setDescription('A unique value for Authentication RADIUS Server index. Its value ranges between 1 and 3.')NEWLINEswAuthRadiusIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2)).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusIPType.setDescription('The IP address of the RADIUS server IP type referred to in this table entry.')NEWLINEswAuthRadiusServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 3), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAddress.setDescription('The IP address of the RADIUS server referred to in this table entry.')NEWLINEswAuthRadiusServerInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 4), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerInterfaceName.setDescription('Specifies the interface name when the swAuthRadiusServerAddress is linklocal address.')NEWLINEswAuthRadiusServerAuthenticationPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1812)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAuthenticationPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAuthenticationPort.setDescription('The value is for setting UDP Port.')NEWLINEswAuthRadiusServerAccountingPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1813)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAccountingPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAccountingPort.setDescription('The value is for setting UDP Port.')NEWLINEswAuthRadiusServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)).clone(5)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerTimeout.setDescription('The value is for setting UDP Port.')NEWLINEswAuthRadiusServerRetransmit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerRetransmit.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerRetransmit.setDescription('The value is for setting UDP Port.')NEWLINEswAuthRadiusServerKey = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerKey.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerKey.setDescription('This object is used to set 802.1X Radius Server Key, The following characters are allowed to input: semicolon, question mark, space, and double quotation mark.')NEWLINEswAuthRadiusServerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 10), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerStatus.setDescription('The status of this conceptual row in the swAuthRadiusServerTable. An entry in this table is not qualified for activation until instances of all corresponding columns have been initialized, either through default values, or through Set operations. The swAuthRadiusServerIndex objects must be explicitly set.')NEWLINEcosScheduleMechanism = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("strictPriority", 1), ("wrr", 2), ("strict3wrr", 3), ("strict2wrr", 4)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cosScheduleMechanism.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosScheduleMechanism.setDescription('Queuing mechanism. strictPriority(1) : Strict Priority wrr(2) : Weighted Round Robin Strict-priority scheduling is implemented with a special strict-priority scheduler node that is stacked directly above the port. Queues stacked on top of the strict-priority scheduler node always get bandwidth before other queues. Weighted round-robin scheduling is designed to better handle queues with different processing capacities. Each queue has a weight : Low is 1, Medium is 2, High is 4 and Highest is 8 for WS3 spec. Queues with higher weights get bandwidth before than other queues with less weights. ')NEWLINEcosOutputSchedule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2))NEWLINEcosClassTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2, 1), )NEWLINEif mibBuilder.loadTexts: cosClassTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosClassTable.setDescription('A list of cosOutputSchedule.')NEWLINEcosClassEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cosClassIndex"))NEWLINEif mibBuilder.loadTexts: cosClassEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosClassEntry.setDescription('A list of cosOutputClass Weight.')NEWLINEcosClassIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosClassIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosClassIndex.setDescription('A index of class 0 ~ 3.')NEWLINEcosWeight = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 55))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cosWeight.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosWeight.setDescription('cos weight ')NEWLINEcosBandwidthCtrlSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9))NEWLINEcosBandwidthCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1), )NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlTable.setDescription('A list of cosBandwidthCtrlEntry default priority Entries.')NEWLINEcosBandwidthCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cosBandwidthCtrlPortIndex"), (0, "DES-1210-28MEbx", "cosBandwidthCtrlClassIndex"))NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlEntry.setDescription('A list of cosBandwidthCtrlEntry default priority priorities.')NEWLINEcosBandwidthCtrlPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlPortIndex.setDescription('A port identifier that is in the range of 1 to ifNumber.')NEWLINEcosBandwidthCtrlClassIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlClassIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlClassIndex.setDescription('A BandwidthCtrlClassIndex identifier that is in the range of 1 to ifNumber.')NEWLINEcosBandwidthValue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 3), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cosBandwidthValue.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthValue.setDescription('The BandwidthValue return value.')NEWLINEcosBandwidthEffectiveRX = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosBandwidthEffectiveRX.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthEffectiveRX.setDescription('A speed rate of Effective RX.')NEWLINEcosBandwidthEffectiveTX = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 5), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosBandwidthEffectiveTX.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthEffectiveTX.setDescription('A speed value of Effective TX.')NEWLINEqosDefaultUserPri = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4))NEWLINEqosDefaultUserPriTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1), )NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriTable.setDescription('A list of 802.1p port default priority Entries.')NEWLINEqosDefaultUserPriEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qosDefaultUserPriPortIndex"))NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriEntry.setDescription('A list of 802.1p port default priority priorities.')NEWLINEqosDefaultUserPriPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriPortIndex.setDescription('A port identifier that is in the range of 1 to ifNumber.')NEWLINEqosDefaultPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("priority0", 0), ("priority1", 1), ("priority2", 2), ("priority3", 3), ("priority4", 4), ("priority5", 5), ("priority6", 6), ("priority7", 7)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDefaultPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDefaultPriority.setDescription("For ingress untagged packets, the per port 'Default Priority' setting will be applied to packets of each port to provide port-based traffic prioritization when 802.1p is enabled.")NEWLINEqosEffectiveDefaultPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("priority0", 0), ("priority1", 1), ("priority2", 2), ("priority3", 3), ("priority4", 4), ("priority5", 5), ("priority6", 6), ("priority7", 7)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qosEffectiveDefaultPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosEffectiveDefaultPriority.setDescription("For ingress untagged packets, the per port 'Effective Default Priority' setting will be applied to packets of each port to provide port-based traffic prioritization when 802.1p is enabled.")NEWLINEqosUserPriority = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5))NEWLINEqosUserPriorityTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5, 1), )NEWLINEif mibBuilder.loadTexts: qosUserPriorityTable.setReference('ISO/IEC 15802-3 Table 7-2')NEWLINEif mibBuilder.loadTexts: qosUserPriorityTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosUserPriorityTable.setDescription('A table mapping evaluated User Priority to Traffic Class, for forwarding by the bridge. Traffic class is a number in the range (0..3).')NEWLINEqosUserPriEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qosUserPriIndex"))NEWLINEif mibBuilder.loadTexts: qosUserPriEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosUserPriEntry.setDescription('User Priority to Traffic Class mapping.')NEWLINEqosUserPriIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qosUserPriIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosUserPriIndex.setDescription('For ingress tagged packets, D-Link Smart Switches will refer to these information and prioritize them with 4 different priority queues. If 802.1p is enabled.')NEWLINEqosUserPriClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosUserPriClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosUserPriClass.setDescription('The User Class the received frame is mapped to.')NEWLINEqosPriSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7))NEWLINEqosPriSettingsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7, 1), )NEWLINEif mibBuilder.loadTexts: qosPriSettingsTable.setReference('ISO/IEC 15802-3 Table 7-2')NEWLINEif mibBuilder.loadTexts: qosPriSettingsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosPriSettingsTable.setDescription('A list of port priority settings.')NEWLINEqosPriSettingsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qosPriSetPortIndex"))NEWLINEif mibBuilder.loadTexts: qosPriSettingsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosPriSettingsEntry.setDescription('A list of port priority settings Entries.')NEWLINEqosPriSetPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qosPriSetPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosPriSetPortIndex.setDescription('A port identifier that is in the range of 1 to ifNumber.')NEWLINEqosPriSetPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 4, 6))).clone(namedValues=NamedValues(("none", 0), ("ieee8021P", 2), ("dscp-tos", 4), ("ieee8021P-dscp-tos", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosPriSetPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosPriSetPortType.setDescription('The port priority setting type. (ex. none = 0, 802.1p = 2, DSCP = 4. If you want enable 802.1p & DSCP, the value is 2 + 4 = 6. ')NEWLINEqosDiffServTOS = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6))NEWLINEqosDSCPTOSMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("tos", 1), ("dscp", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDSCPTOSMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDSCPTOSMode.setDescription('Settings of Qos mode: DSCP QoS or TOS Qos. IEEE 802.1p : It specifies a priority(0~7) value to four queues in WS3 : Low(1,2), Medium(0,3), High(4,5) and Highest(6,7), inclusive that can be used by Quality of Service (QoS) disciplines to differentiate traffic. DSCP : Differentiated services enhancements to the Internet protocol are intended to enable scalable service discrimination in the Internet without the need for per-flow state and signaling at every hop. ')NEWLINEqosDiffServTypeGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2))NEWLINEqosDiffServType00 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType00.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType00.setDescription('DiffServ Type 0 : IP ToS value = 0')NEWLINEqosDiffServType01 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType01.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType01.setDescription('DiffServ Type 01 : IP ToS value = 4')NEWLINEqosDiffServType02 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType02.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType02.setDescription('DiffServ Type 02 : IP ToS value = 8')NEWLINEqosDiffServType03 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType03.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType03.setDescription('DiffServ Type 03 : IP ToS value = 12')NEWLINEqosDiffServType04 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType04.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType04.setDescription('DiffServ Type 04 : IP ToS value = 16')NEWLINEqosDiffServType05 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType05.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType05.setDescription('DiffServ Type 05 : IP ToS value = 20')NEWLINEqosDiffServType06 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType06.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType06.setDescription('DiffServ Type 06 : IP ToS value = 24')NEWLINEqosDiffServType07 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType07.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType07.setDescription('DiffServ Type 07 : IP ToS value = 28')NEWLINEqosDiffServType08 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType08.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType08.setDescription('DiffServ Type 08 : IP ToS value = 32')NEWLINEqosDiffServType09 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType09.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType09.setDescription('DiffServ Type 09 : IP ToS value = 36')NEWLINEqosDiffServType10 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType10.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType10.setDescription('DiffServ Type 10 : IP ToS value = 40')NEWLINEqosDiffServType11 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType11.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType11.setDescription('DiffServ Type 11 : IP ToS value = 44')NEWLINEqosDiffServType12 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType12.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType12.setDescription('DiffServ Type 12 : IP ToS value = 48')NEWLINEqosDiffServType13 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType13.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType13.setDescription('DiffServ Type 13 : IP ToS value = 52')NEWLINEqosDiffServType14 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType14.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType14.setDescription('DiffServ Type 14 : IP ToS value = 56')NEWLINEqosDiffServType15 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType15.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType15.setDescription('DiffServ Type 15 : IP ToS value = 60')NEWLINEqosDiffServType16 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType16.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType16.setDescription('DiffServ Type 16 : IP ToS value = 64')NEWLINEqosDiffServType17 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType17.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType17.setDescription('DiffServ Type 17 : IP ToS value = 68')NEWLINEqosDiffServType18 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType18.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType18.setDescription('DiffServ Type 18 : IP ToS value = 72')NEWLINEqosDiffServType19 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType19.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType19.setDescription('DiffServ Type 19 : IP ToS value = 76')NEWLINEqosDiffServType20 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType20.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType20.setDescription('DiffServ Type 20 : IP ToS value = 80')NEWLINEqosDiffServType21 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType21.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType21.setDescription('DiffServ Type 21 : IP ToS value = 84')NEWLINEqosDiffServType22 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 23), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType22.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType22.setDescription('DiffServ Type 22 : IP ToS value = 88')NEWLINEqosDiffServType23 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType23.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType23.setDescription('DiffServ Type 23 : IP ToS value = 92')NEWLINEqosDiffServType24 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType24.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType24.setDescription('DiffServ Type 24 : IP ToS value = 96')NEWLINEqosDiffServType25 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 26), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType25.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType25.setDescription('DiffServ Type 25 : IP ToS value = 100')NEWLINEqosDiffServType26 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 27), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType26.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType26.setDescription('DiffServ Type 26 : IP ToS value = 104')NEWLINEqosDiffServType27 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 28), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType27.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType27.setDescription('DiffServ Type 27 : IP ToS value = 108')NEWLINEqosDiffServType28 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 29), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType28.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType28.setDescription('DiffServ Type 28 : IP ToS value = 112')NEWLINEqosDiffServType29 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType29.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType29.setDescription('DiffServ Type 29 : IP ToS value = 116')NEWLINEqosDiffServType30 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 31), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType30.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType30.setDescription('DiffServ Type 30 : IP ToS value = 120')NEWLINEqosDiffServType31 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType31.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType31.setDescription('DiffServ Type 31 : IP ToS value = 124')NEWLINEqosDiffServType32 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 33), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType32.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType32.setDescription('DiffServ Type 32 : IP ToS value = 128')NEWLINEqosDiffServType33 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 34), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType33.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType33.setDescription('DiffServ Type 33 : IP ToS value = 132')NEWLINEqosDiffServType34 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 35), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType34.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType34.setDescription('DiffServ Type 34 : IP ToS value = 136')NEWLINEqosDiffServType35 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 36), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType35.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType35.setDescription('DiffServ Type 35 : IP ToS value = 140')NEWLINEqosDiffServType36 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 37), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType36.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType36.setDescription('DiffServ Type 36 : IP ToS value = 144')NEWLINEqosDiffServType37 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 38), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType37.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType37.setDescription('DiffServ Type 37 : IP ToS value = 148')NEWLINEqosDiffServType38 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 39), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType38.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType38.setDescription('DiffServ Type 38 : IP ToS value = 152')NEWLINEqosDiffServType39 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 40), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType39.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType39.setDescription('DiffServ Type 39 : IP ToS value = 156')NEWLINEqosDiffServType40 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 41), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType40.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType40.setDescription('DiffServ Type 40 : IP ToS value = 160')NEWLINEqosDiffServType41 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 42), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType41.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType41.setDescription('DiffServ Type 41 : IP ToS value = 164')NEWLINEqosDiffServType42 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 43), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType42.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType42.setDescription('DiffServ Type 42 : IP ToS value = 168')NEWLINEqosDiffServType43 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 44), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType43.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType43.setDescription('DiffServ Type 43 : IP ToS value = 172')NEWLINEqosDiffServType44 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 45), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType44.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType44.setDescription('DiffServ Type 44 : IP ToS value = 176')NEWLINEqosDiffServType45 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 46), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType45.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType45.setDescription('DiffServ Type 45 : IP ToS value = 180')NEWLINEqosDiffServType46 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 47), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType46.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType46.setDescription('DiffServ Type 46 : IP ToS value = 184')NEWLINEqosDiffServType47 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 48), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType47.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType47.setDescription('DiffServ Type 47 : IP ToS value = 188')NEWLINEqosDiffServType48 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 49), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType48.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType48.setDescription('DiffServ Type 48 : IP ToS value = 192')NEWLINEqosDiffServType49 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 50), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType49.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType49.setDescription('DiffServ Type 49 : IP ToS value = 196')NEWLINEqosDiffServType50 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 51), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType50.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType50.setDescription('DiffServ Type 50 : IP ToS value = 200')NEWLINEqosDiffServType51 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 52), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType51.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType51.setDescription('DiffServ Type 51 : IP ToS value = 204')NEWLINEqosDiffServType52 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 53), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType52.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType52.setDescription('DiffServ Type 52 : IP ToS value = 208')NEWLINEqosDiffServType53 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 54), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType53.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType53.setDescription('DiffServ Type 53 : IP ToS value = 212')NEWLINEqosDiffServType54 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 55), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType54.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType54.setDescription('DiffServ Type 54 : IP ToS value = 216')NEWLINEqosDiffServType55 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 56), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType55.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType55.setDescription('DiffServ Type 55 : IP ToS value = 220')NEWLINEqosDiffServType56 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 57), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType56.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType56.setDescription('DiffServ Type 56 : IP ToS value = 224')NEWLINEqosDiffServType57 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 58), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType57.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType57.setDescription('DiffServ Type 57 : IP ToS value = 228')NEWLINEqosDiffServType58 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 59), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType58.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType58.setDescription('DiffServ Type 58 : IP ToS value = 232')NEWLINEqosDiffServType59 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 60), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType59.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType59.setDescription('DiffServ Type 59 : IP ToS value = 236')NEWLINEqosDiffServType60 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 61), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType60.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType60.setDescription('DiffServ Type 60 : IP ToS value = 240')NEWLINEqosDiffServType61 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 62), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType61.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType61.setDescription('DiffServ Type 61 : IP ToS value = 244')NEWLINEqosDiffServType62 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 63), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType62.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType62.setDescription('DiffServ Type 62 : IP ToS value = 248')NEWLINEqosDiffServType63 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 64), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType63.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType63.setDescription('DiffServ Type 63 : IP ToS value = 252')NEWLINEqosTOSGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3))NEWLINEqosTOSType00 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType00.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType00.setDescription('TOS 0')NEWLINEqosTOSType01 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType01.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType01.setDescription('TOS 01')NEWLINEqosTOSType02 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType02.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType02.setDescription('TOS 02')NEWLINEqosTOSType03 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType03.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType03.setDescription('TOS 03')NEWLINEqosTOSType04 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType04.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType04.setDescription('TOS 04')NEWLINEqosTOSType05 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType05.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType05.setDescription('TOS 05')NEWLINEqosTOSType06 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType06.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType06.setDescription('TOS 06')NEWLINEqosTOSType07 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType07.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType07.setDescription('TOS 07')NEWLINEqosAclPrioritySettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8))NEWLINEipv4aclQosTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1), )NEWLINEif mibBuilder.loadTexts: ipv4aclQosTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosTable.setDescription('A list of priority by acl setting.')NEWLINEipv4aclQosEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4aclQosIndex"))NEWLINEif mibBuilder.loadTexts: ipv4aclQosEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosEntry.setDescription('A list of priority by acl setting entry.')NEWLINEipv4aclQosIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclQosIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosIndex.setDescription('Index of priority by acl setting.')NEWLINEipv4aclQosType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("mac", 0), ("ip", 1), ("tcp", 2), ("udp", 3), ("vlanid", 4), ("protocol", 5)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosType.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosType.setDescription('Type of priority by acl setting.')NEWLINEipv4aclQosMACAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 3), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosMACAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosMACAddr.setDescription('Dst MAC of priority by acl setting.')NEWLINEipv4aclQosIPAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 4), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosIPAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosIPAddr.setDescription('Dst IP of priority by acl setting')NEWLINEipv4aclQosTCPUDPPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosTCPUDPPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosTCPUDPPort.setDescription('Dst TCP/UDP port of priority by acl setting')NEWLINEipv4aclQosVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosVlanID.setDescription('VLAN ID of priority by acl setting')NEWLINEipv4aclQosProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosProtocol.setDescription('Ip protocol number of priority by acl setting')NEWLINEipv4aclQosAssignClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("class0", 0), ("class1", 1), ("class2", 2), ("class3", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosAssignClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosAssignClass.setDescription('Be mapped class of priority by acl setting.')NEWLINEipv4aclQosStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 9), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosStatus.setDescription('Status of priority by acl setting.')NEWLINEaclQosTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2), )NEWLINEif mibBuilder.loadTexts: aclQosTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosTable.setDescription('A list of priority by acl setting.')NEWLINEaclQosEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclQosIndex"))NEWLINEif mibBuilder.loadTexts: aclQosEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosEntry.setDescription('A list of priority by acl setting entry.')NEWLINEaclQosIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclQosIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosIndex.setDescription('Index of priority by acl setting.')NEWLINEaclQosType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("mac", 0), ("ip", 1), ("tcp", 2), ("udp", 3), ("vlanid", 4), ("protocol", 5), ("ipv6", 6), ("ipv6traffic-class", 7)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosType.setDescription('Type of priority by acl setting.')NEWLINEaclQosMACAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 3), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosMACAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosMACAddr.setDescription('Dst MAC of priority by acl setting.')NEWLINEaclQosIPAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 4), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosIPAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosIPAddr.setDescription('Dst IP of priority by acl setting')NEWLINEaclQosIPv6Addr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 5), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosIPv6Addr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosIPv6Addr.setDescription('Dst IP of priority by acl setting. ')NEWLINEaclQosTCPUDPPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosTCPUDPPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosTCPUDPPort.setDescription('Dst TCP/UDP port of priority by acl setting')NEWLINEaclQosVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosVlanID.setDescription('VLAN ID of priority by acl setting')NEWLINEaclQosProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosProtocol.setDescription('Ip protocol number of priority by acl setting')NEWLINEaclQosIP6TC = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosIP6TC.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosIP6TC.setDescription('Ipv6 Traffic Class number of priority by acl setting')NEWLINEaclQosAssignClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 98), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("class0", 0), ("class1", 1), ("class2", 2), ("class3", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosAssignClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosAssignClass.setDescription('Be mapped class of priority by acl setting.')NEWLINEaclQosStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 99), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosStatus.setDescription('Status of priority by acl setting.')NEWLINEbandwidthCtrlSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1))NEWLINEbandwidthCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2), )NEWLINEif mibBuilder.loadTexts: bandwidthCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlTable.setDescription('A table to control the rate limiting parameters either for the entire switch or for each interface in the switch.')NEWLINEbandwidthCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "bandwidthCtrlIndex"))NEWLINEif mibBuilder.loadTexts: bandwidthCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlEntry.setDescription('An entry appears in this table for each physical interface in the switch.')NEWLINEbandwidthCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: bandwidthCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlIndex.setDescription('The interface index for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEbandwidthCtrlTxThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(64, 1024000), ))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: bandwidthCtrlTxThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlTxThreshold.setDescription("Configures interface Rate Limit (Packet that can be transferred on a port at a particular second). This object's value will take effect on the interface speed. Based on the operating speed of the port, the rate limit will be applied. This value can also be affected by the metering. A value of zero(0) disable rate limiting i.e. sets the port to full speed. The value can be set between 64~102400(Kbits per second) in FE port, 64~1024000 (Kbits per second) in GE port.")NEWLINEbandwidthCtrlRxThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(64, 1024000), ))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: bandwidthCtrlRxThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlRxThreshold.setDescription('Allows to configure the limiting value for the maximum number of receive packets that can be transmitted per second over this interface. Setting this object to the value zero disables rate limiting for receive packets on this interface. The value that can be set for this object is limited by the underlying hardware. The value can be set between 64~102400(Kbits per second) in FE port, 64~1024000(Kbits per second) in GE port.')NEWLINEbandwidthEffecTxThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: bandwidthEffecTxThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthEffecTxThreshold.setDescription("This object's value will take effect on the interface speed. Based on the operating speed of the port, the rate limit will be applied. This value can also be affected by the metering. A value of zero(0) disable rate limiting i.e. sets the port to full speed. ")NEWLINEbandwidthEffecRxThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 5), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: bandwidthEffecRxThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthEffecRxThreshold.setDescription('Allows to configure the limiting value for the maximum number of receive packets that can be transmitted per second over this interface. Setting this object to the value zero disables rate limiting for receive packets on this interface. The value that can be set for this object is limited by the underlying hardware. ')NEWLINEtrafficCtrlSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4))NEWLINEtrafficCtrlTrap = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("stormOccurred", 1), ("stormCleared", 2), ("both", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlTrap.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlTrap.setDescription('The trap setting of traffic control.')NEWLINEtrafficCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2), )NEWLINEif mibBuilder.loadTexts: trafficCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlTable.setDescription('The traffic control table.')NEWLINEtrafficCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "trafficCtrlIndex"))NEWLINEif mibBuilder.loadTexts: trafficCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlEntry.setDescription('The traffic control entry.')NEWLINEtrafficCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trafficCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlIndex.setDescription('The traffic control index.')NEWLINEtrafficCtrlActionMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("drop", 0), ("shutdown", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlActionMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlActionMode.setDescription('The action mode of traffic control.')NEWLINEtrafficCtrlType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("none", 0), ("b", 1), ("m", 2), ("mb", 3), ("u", 4), ("ub", 5), ("um", 6), ("umb", 7)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlType.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlType.setDescription('The control type of traffic control. (b: Broadcast, m: Multicast, u: Unknown Unicast)')NEWLINEtrafficCtrlThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 102400))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlThreshold.setDescription('The threshold of traffic control.')NEWLINEtrafficCtrlCountDown = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 30))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlCountDown.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlCountDown.setDescription('The count down value of traffic control.')NEWLINEtrafficCtrlTimeInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(5, 30))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlTimeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlTimeInterval.setDescription('The time interval of traffic control.')NEWLINEtrafficCtrlAutoRecoverTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlAutoRecoverTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlAutoRecoverTime.setDescription('The recover time of traffic control.')NEWLINEsecurityTrustedHost = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1))NEWLINEtrustedHostStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trustedHostStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostStatus.setDescription('This object indicates trusted host function is enabled or disabled. When trusted host function is enabled, D-Link Smart Switches will only allow hosts which you trust to access and control the switch. Your local host IP Addresses must be one of the IP Addresses to avoid disconnection.')NEWLINEipv4trustedHostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2), )NEWLINEif mibBuilder.loadTexts: ipv4trustedHostTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostTable.setDescription('A table to configure trusted host in the system.')NEWLINEipv4trustedHostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4trustedHostIpAddr"), (0, "DES-1210-28MEbx", "ipv4trustedHostIpMask"))NEWLINEif mibBuilder.loadTexts: ipv4trustedHostEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostEntry.setDescription('Each entry in this table represents rules for particular trusted host.')NEWLINEipv4trustedHostIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2, 1, 1), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4trustedHostIpAddr.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostIpAddr.setDescription('The IP address of host you allow to access to D-Link Smart Switch. Your local host IP Addresses must be one of the IP Addresses to avoid disconnection.')NEWLINEipv4trustedHostIpMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2, 1, 2), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4trustedHostIpMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostIpMask.setDescription('Used to mask with IP address, it allow you set a subnet as a trusted host entry.')NEWLINEipv4trustedHostRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2, 1, 3), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4trustedHostRowStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostRowStatus.setDescription('The status of an entry in the Trusted Host Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINEtrustedHostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3), )NEWLINEif mibBuilder.loadTexts: trustedHostTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostTable.setDescription('A table to configure trusted host for in the system.')NEWLINEtrustedHostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "trustedHostIPType"), (0, "DES-1210-28MEbx", "trustedHostIpAddr"), (0, "DES-1210-28MEbx", "trustedHostIpMask"))NEWLINEif mibBuilder.loadTexts: trustedHostEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostEntry.setDescription('Each entry in this table represents rules for particular trusted host.')NEWLINEtrustedHostIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trustedHostIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostIPType.setDescription('Type of IP interface.')NEWLINEtrustedHostIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1, 2), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trustedHostIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostIpAddr.setDescription('The IP address of host you allow to access to D-Link Smart Switch. Your local host IPv4/6 Addresses must be one of the IP Addresses to avoid disconnection.')NEWLINEtrustedHostIpMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1, 3), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trustedHostIpMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostIpMask.setDescription('Used to mask with IPv4/6 address, it allow you set a subnet as a trusted host entry.')NEWLINEtrustedHostRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: trustedHostRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostRowStatus.setDescription('The status of an entry in the Trusted Host Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINEsecurityARPSpoofPrevent = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3))NEWLINEaRPSpoofPreventTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1), )NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventTable.setDescription('A table to control ARP Spoofing prevention for the entire switch or for each interface in the switch.')NEWLINEaRPSpoofPreventEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aRPSpoofPreventIpAddr"))NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEaRPSpoofPreventIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1, 1), IpAddress())NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventIpAddr.setDescription("Specifies either the Network or Host address from which the switch can be managed. An address 0.0.0.0 indicates 'Any Manager'.")NEWLINEaRPSpoofPreventMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1, 2), MacAddress().clone(hexValue="000102030405")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventMacAddress.setDescription('Ethernet Mac Address.')NEWLINEaRPSpoofPreventPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventPortList.setDescription("Specifies the port numbers through which the authorized manager can access the switch. By default the authorized manager is allowed to access the switch through all the ports. If a set of ports are configured in the 'PortList', the manager can access the switch only through the configured ports.")NEWLINEaRPSpoofPreventRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEsecuritySSL = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 5))NEWLINEsslSecurityHttpStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 5, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sslSecurityHttpStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sslSecurityHttpStatus.setDescription('This object is for enabling or disabling secure HTTP in the system.')NEWLINEsslCiphers = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 5, 2))NEWLINEsslCipherSuiteList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 5, 2, 1), Bits().clone(namedValues=NamedValues(("rsa-null-md5", 0), ("rsa-null-sha", 1), ("rsa-des-sha", 2), ("rsa-3des-sha", 3), ("dh-rsa-des-sha", 4), ("dh-rsa-3des-sha", 5), ("rsa-exp1024-des-sha", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sslCipherSuiteList.setStatus('current')NEWLINEif mibBuilder.loadTexts: sslCipherSuiteList.setDescription('This object is to configure the cipher-suites list.')NEWLINEsecuritySSH = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8))NEWLINEsshSecurityStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshSecurityStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshSecurityStatus.setDescription('This object is for enabling or disabling ssh in the system.')NEWLINEsshMaxAuthFailAttempts = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshMaxAuthFailAttempts.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshMaxAuthFailAttempts.setDescription('This object indicates the max auth fail retry attempt times.')NEWLINEsshSessionKeyRekeying = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("never", 0), ("ten-min", 1), ("thirty-min", 2), ("sixty-min", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshSessionKeyRekeying.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshSessionKeyRekeying.setDescription('This object indicates one SSH session rekey time interval.')NEWLINEsshMaxSession = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshMaxSession.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshMaxSession.setDescription('This object indicates max SSH session number supported in system.')NEWLINEsshConnectionTimeout = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(120, 600))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshConnectionTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshConnectionTimeout.setDescription('This object indicates SSH connection timeout value.')NEWLINEsshAuthenMethodPassWordAdmin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshAuthenMethodPassWordAdmin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshAuthenMethodPassWordAdmin.setDescription('The object indicates authen method password is enabled or disabled.')NEWLINEsshAuthenMethodPubKeyAdmin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshAuthenMethodPubKeyAdmin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshAuthenMethodPubKeyAdmin.setDescription('The object indicates authen method public-key is enabled or disabled.')NEWLINEsshAuthenMethodHostKeyAdmin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshAuthenMethodHostKeyAdmin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshAuthenMethodHostKeyAdmin.setDescription('The object indicates authen method host-key is enabled or disabled.')NEWLINEsshCipherSuiteList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 9), Bits().clone(namedValues=NamedValues(("tripleDESCBC", 0)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sshCipherSuiteList.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshCipherSuiteList.setDescription('This object is to configure the cipher-suites list.')NEWLINEsshMacSuiteList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 10), Bits().clone(namedValues=NamedValues(("hMAC-SHA1", 0), ("hMAC-MD5", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshMacSuiteList.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshMacSuiteList.setDescription('This object is to configure the MAC-list.')NEWLINEsshPublKeyRSAAdmin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshPublKeyRSAAdmin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshPublKeyRSAAdmin.setDescription('The object indicates Public key generating algorithm RSA is enabled or disabled.')NEWLINEsshUserInfoTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12), )NEWLINEif mibBuilder.loadTexts: sshUserInfoTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoTable.setDescription('A table to configure SSH user auth in the system.')NEWLINEsshUserInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sshUserInfoID"))NEWLINEif mibBuilder.loadTexts: sshUserInfoEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoEntry.setDescription('An entry to configure user auth in the system.')NEWLINEsshUserInfoID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sshUserInfoID.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoID.setDescription('The Schedule identifier. The maximum number of Schedule entry is the number of ports supported PoE function. The value must be between 1 and 8.')NEWLINEsshUserInfoUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sshUserInfoUserName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoUserName.setDescription("The ssh user name associated with the SSH suer Info. entry (e.g., `admin, user').")NEWLINEsshUserInfoAuth = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4, 2, 1))).clone(namedValues=NamedValues(("publickey", 4), ("password", 2), ("hostbased", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshUserInfoAuth.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoAuth.setDescription('The object indicates which auth used by the user.')NEWLINEsshUserInfoHostName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshUserInfoHostName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoHostName.setDescription("The ssh host name associated with the SSH suer Info. entry (e.g., `DUT1, DUT2').")NEWLINEsshUserInfoHostIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 5), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshUserInfoHostIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoHostIp.setDescription('SSH HostBased IP Address of the system.')NEWLINEsecurityPortSecurity = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2))NEWLINEportSecTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1), )NEWLINEif mibBuilder.loadTexts: portSecTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecTable.setDescription('A table to control port security features of the device.')NEWLINEportSecEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "portSecIndex"))NEWLINEif mibBuilder.loadTexts: portSecEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecEntry.setDescription('An entry appears in port security table for each interface in the system.')NEWLINEportSecIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecIndex.setDescription('The interface index for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEportSecState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: portSecState.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecState.setDescription("Enable / disable port security admin state for the interface. A given ports' dynamic MAC address learning will be stopped such that the current source MAC addresses entered into the MAC address forwarding table can not be changed once the port security admin state is enabled.")NEWLINEportSecMLA = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: portSecMLA.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecMLA.setDescription("Configures interface port security maximum learning address numbers. When given ports' admin state is enabled, allows forwarding table learning address number. The number can be set 0 to 64. Note: Set value 0 means cannot learn MAC address.")NEWLINEportSecLockAddrMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("deleteOnReset", 1), ("deleteOnTimeout", 2), ("permanent", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: portSecLockAddrMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecLockAddrMode.setDescription('Configures port security lock address mode for the interface. deleteOnReset : The locked addresses will not age out until the Switch has been reset. deleteOnTimeout : The locked addresses will age out after the aging timer expires. Permanent : The locked addresses will not age out after the aging timer expires.')NEWLINEportSecFDBPermanentTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2), )NEWLINEif mibBuilder.loadTexts: portSecFDBPermanentTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermanentTable.setDescription('A table to control port security FDB Permanent of the device.')NEWLINEportSecFDBPermanentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "portSecFDBPermPort"), (0, "DES-1210-28MEbx", "portSecFDBPermIndex"))NEWLINEif mibBuilder.loadTexts: portSecFDBPermanentEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermanentEntry.setDescription('An entry appears in port security table for each interface in the system.')NEWLINEportSecFDBPermIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecFDBPermIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermIndex.setDescription('The index of the port security MAC entry. For all machines give maximum port number.')NEWLINEportSecFDBPermVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecFDBPermVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermVlanID.setDescription('The VLAN ID of the port security MAC entry.')NEWLINEportSecFDBPermMac = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecFDBPermMac.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermMac.setDescription('The MAC address associated of the port security MAC entry.')NEWLINEportSecFDBPermPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecFDBPermPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermPort.setDescription('The forwarding port of the port security MAC entry. For all machines give maximum port number.')NEWLINEcableDiagTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1), )NEWLINEif mibBuilder.loadTexts: cableDiagTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagTable.setDescription('A table that contains the cable situation for each port.')NEWLINEcableDiagEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cableDiagPortIndex"))NEWLINEif mibBuilder.loadTexts: cableDiagEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagEntry.setDescription('A list of cable situations for each port on the device.')NEWLINEcableDiagPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPortIndex.setDescription('The interface index for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEcableDiagPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("fastEthernet", 0), ("gigaEthernet", 1), ("other", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPortType.setDescription('Indicates the supported port data rate classification.')NEWLINEcableDiagLinkStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("linkdown", 0), ("linkup", 1), ("other", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagLinkStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagLinkStatus.setDescription('This object indicates the link status.')NEWLINEcableDiagPair1Status = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("ok", 0), ("open", 1), ("short", 2), ("open-short", 3), ("crosstalk", 4), ("unknown", 5), ("count", 6), ("no-cable", 7), ("other", 8)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair1Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair1Status.setDescription('Cable diagnostics pair 1 test result.')NEWLINEcableDiagPair2Status = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("ok", 0), ("open", 1), ("short", 2), ("open-short", 3), ("crosstalk", 4), ("unknown", 5), ("count", 6), ("no-cable", 7), ("other", 8)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair2Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair2Status.setDescription('Cable diagnostics pair 2 test result.')NEWLINEcableDiagPair3Status = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("ok", 0), ("open", 1), ("short", 2), ("open-short", 3), ("crosstalk", 4), ("unknown", 5), ("count", 6), ("no-cable", 7), ("other", 8)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair3Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair3Status.setDescription('Cable diagnostics pair 3 test result.')NEWLINEcableDiagPair4Status = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("ok", 0), ("open", 1), ("short", 2), ("open-short", 3), ("crosstalk", 4), ("unknown", 5), ("count", 6), ("no-cable", 7), ("other", 8)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair4Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair4Status.setDescription('Cable diagnostics pair 4 test result.')NEWLINEcableDiagPair1Length = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 8), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair1Length.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair1Length.setDescription('Cable Diagnostics pair 1 fault distance.')NEWLINEcableDiagPair2Length = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 9), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair2Length.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair2Length.setDescription('Cable diagnostics pair 2 fault distance.')NEWLINEcableDiagPair3Length = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 10), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair3Length.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair3Length.setDescription('Cable diagnostics pair 3 fault distance.')NEWLINEcableDiagPair4Length = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 11), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair4Length.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair4Length.setDescription('Cable diagnostics pair 4 fault distance.')NEWLINEcableDiagAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("action", 1), ("processing", 2), ("other", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cableDiagAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagAction.setDescription('Function to run the cable diagnostic on selected port. Can not detect fiber ports')NEWLINEcableDiagStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("notrun", 1), ("processing", 2), ("lasttestok", 3), ("lasttestfailed", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagStatus.setDescription('Indicates the status of cable diagnostics on the port. not-run - cable diagnostics has never been run for this port processing - cable diagnostics is currently running on the port last-test-ok - the last cable diagnostics done on the port was successful last-test-failed - the last cable diagnostics done on the port failed')NEWLINEaclProfile = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1))NEWLINEipv4aclProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1), )NEWLINEif mibBuilder.loadTexts: ipv4aclProfileTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileTable.setDescription(' A table to ACL profile . ')NEWLINEipv4aclProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4aclProfileNo"))NEWLINEif mibBuilder.loadTexts: ipv4aclProfileEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileEntry.setDescription(' Each entry in this table is a ACL profile. Index to the table is ACL profile ID. ')NEWLINEipv4aclProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileNo.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileNo.setDescription('The ACL Profile ID. The ID 1 to 50 is user-defined ACL, and the ID more than 50 is reserved for system-defined ACL. The user only allow to create user-defined ACL ID. And system-defined ACL is read only.')NEWLINEipv4aclProfileType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 8, 9))).clone(namedValues=NamedValues(("l2", 1), ("l3", 2), ("impb", 3), ("arpSP-permit", 4), ("arpSP-deny", 5), ("aclQos", 8), ("userDefined", 9)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileType.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileType.setDescription('The ACL Profile type, possible value are l2 (1) - for MAC-based rule, l3 (2) - for IPv4-based rule, arpSP_permit(4) - for ARP Spoofing prevention entry, arpSP_deny(5) - for ARP Spoofing prevention entry, voiceVlan(6) - for Voice VLAN OUI entry. userDefined(9) - for User Defined entry. Note that only l2, l3 and userDefined could be set by user, other is reserved for system to show information. ')NEWLINEipv4aclProfileRuleCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileRuleCount.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileRuleCount.setDescription('The number of rules in this profile.')NEWLINEipv4aclProfileMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileMask.setDescription('Indicate which field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ L2 DST_MAC 0 (LSB) L2 SRC_MAC 1 L2 VID 2 L2 8021P_PRIORITY 3 L2 ETHER_TYPE 4 L3 DSCP 5 L3 ICMP_TYPE 6 L3 ICMP_CODE 7 L3 IGMP_TYPE 8 L3 DST_IP 9 L3 SRC_IP 10 L3 DST_PORT 11 L3 SRC_PORT 12 L3 TCPFLAG 13 ARP-SP ARP_SENDER_MAC 14 ARP-SP ARP_SENDER_IP 15 L3 TOS 16 UDF UDF1 17 UDF UDF2 18 UDF UDF3 19 UDF UDF4 20 L3v6 TRAFFIC_CLASS 21 L3v6 DST_IPV6 22 L3v6 SRC_IPV6 23 (MSB) ------------------------------------------- The value is in Hex format. ')NEWLINEipv4aclProfileDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstMacAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstMacAddrMask.setDescription('The ACL Profile destination MAC address mask. If DST_MAC is turn on in aclProfileMask, it will work with its member rule field,aclL2RuleDstMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEipv4aclProfileSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 6), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcMacAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcMacAddrMask.setDescription('The ACL Profile source MAC address mask. If SRC_MAC is turn on in aclProfileMask, it will work with its member rule field,aclL2RuleSrcMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEipv4aclProfileIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 6, 17, 58, 256))).clone(namedValues=NamedValues(("none", 0), ("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17), ("icmpv6", 58), ("ipProtocolMask", 256)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileIPProtocol.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileIPProtocol.setDescription('Indicate which IP Protocol will be care in this profile. Only profile type is l3 can set the IP protocol. For others, this field will be none. ')NEWLINEipv4aclProfileIPProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 8), OctetString().clone(hexValue="FF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileIPProtocolMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileIPProtocolMask.setDescription('The ACL Profile IP protocol mask. If aclProfileIPProtocol set to ipMask, this field will be refered. It will work with its member rule field,aclL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ')NEWLINEipv4aclProfileDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 9), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstIpAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstIpAddrMask.setDescription("The ACL Profile destination IP address mask. If DST_IP is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleDstIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEipv4aclProfileSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 10), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcIpAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcIpAddrMask.setDescription("The ACL Profile source IP address mask. If SRC_IP is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleSrcIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEipv4aclProfileDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 11), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstPortMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstPortMask.setDescription('The ACL Profile UDP/TCP destination port mask. If DST_PORT is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleTcpUdpDstPort, to caculate a range of destination port which is really care. The value is in HEX format. ')NEWLINEipv4aclProfileSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 12), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcPortMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcPortMask.setDescription('The ACL Profile UDP/TCP source port mask. If SRC_PORT is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleTcpUdpSrcPort, to caculate a range of source port which is really care. The value is in HEX format. ')NEWLINEipv4aclProfileArpSenderMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 13), MacAddress().clone(hexValue="FFFFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileArpSenderMacAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileArpSenderMacAddrMask.setDescription("The ACL Profile Sender MAC mask. This is only for ARP Spoofing Prevention which is System-defined ACL, and it's not allow to modify. The value is in HEX format. ")NEWLINEipv4aclProfileArpSenderIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 14), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileArpSenderIpAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileArpSenderIpAddrMask.setDescription("The ACL Profile Sender IP mask. This is only for ARP Spoofing Prevention which is System-defined ACL, and it's not allow to modify. The value is in HEX format. ")NEWLINEipv4aclProfileUdfOffsetMap = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 15), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileUdfOffsetMap.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileUdfOffsetMap.setDescription('Indicate which Udf field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ UDF Offset1 0 (LSB) UDF Offset2 1 UDF Offset3 2 UDF Offset4 3 ------------------------------------------- The value is in Hex format. ')NEWLINEipv4aclUdfOffsetBase1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase1.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase1.setDescription('The value of offset Base.')NEWLINEipv4aclUdfOffsetByte1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 17), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte1.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte1.setDescription('The value of offset Byte from base.')NEWLINEipv4aclUdfOffsetMask1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 18), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask1.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask1.setDescription('The value of offset MAsk.')NEWLINEipv4aclUdfOffsetBase2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase2.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase2.setDescription('The value of offset Base.')NEWLINEipv4aclUdfOffsetByte2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 20), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte2.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte2.setDescription('The value of offset Byte from base.')NEWLINEipv4aclUdfOffsetMask2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 21), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask2.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask2.setDescription('The value of offset MAsk.')NEWLINEipv4aclUdfOffsetBase3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase3.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase3.setDescription('The value of offset Base.')NEWLINEipv4aclUdfOffsetByte3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 23), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte3.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte3.setDescription('The value of offset Byte from base.')NEWLINEipv4aclUdfOffsetMask3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 24), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask3.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask3.setDescription('The value of offset MAsk.')NEWLINEipv4aclUdfOffsetBase4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase4.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase4.setDescription('The value of offset Base.')NEWLINEipv4aclUdfOffsetByte4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 26), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte4.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte4.setDescription('The value of offset Byte from base.')NEWLINEipv4aclUdfOffsetMask4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 27), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask4.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask4.setDescription('The value of offset MAsk.')NEWLINEipv4aclProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 28), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileStatus.setDescription(" This object indicates the status of this entry, can only be set to 'createAndWait','active' and 'destroy'. When the value of the entry status is 'createAndWait', it could be set to 'active' only if the three values of aclProfileType, aclProfileMask and ProtocolType are not conflicted. ")NEWLINEaclProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2), )NEWLINEif mibBuilder.loadTexts: aclProfileTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileTable.setDescription(' A table to ACL profile . ')NEWLINEaclProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclProfileNo"))NEWLINEif mibBuilder.loadTexts: aclProfileEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileEntry.setDescription(' Each entry in this table is a ACL profile. Index to the table is ACL profile ID. ')NEWLINEaclProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileNo.setDescription('The ACL Profile ID. The ID 1 to 50 is user-defined ACL, and the ID more than 50 is reserved for system-defined ACL. The user only allow to create user-defined ACL ID. And system-defined ACL is read only.')NEWLINEaclProfileType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 11, 3, 4, 5, 8, 9))).clone(namedValues=NamedValues(("l2", 1), ("l3v4", 2), ("l3v6", 11), ("impb", 3), ("arpSP-permit", 4), ("arpSP-deny", 5), ("aclQos", 8), ("userDefined", 9)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileType.setDescription('The ACL Profile type, possible value are l2 (1) - for MAC-based rule, l3v4 (2) - for IPv4-based rule, l3v6 (11) - for IPv6-based rule, arpSP_permit(4) - for ARP Spoofing prevention entry, arpSP_deny(5) - for ARP Spoofing prevention entry, voiceVlan(6) - for Voice VLAN OUI entry. userDefined(9) - for User Defined entry. Note that only l2, l3 and userDefined could be set by user, other is reserved for system to show information. ')NEWLINEaclProfileRuleCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclProfileRuleCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileRuleCount.setDescription('The number of rules in this profile.')NEWLINEaclProfileMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileMask.setDescription('Indicate which field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ L2 DST_MAC 0 (LSB) L2 SRC_MAC 1 L2 VID 2 L2 8021P_PRIORITY 3 L2 ETHER_TYPE 4 L3 DSCP 5 L3 ICMP_TYPE 6 L3 ICMP_CODE 7 L3 IGMP_TYPE 8 L3 DST_IP 9 L3 SRC_IP 10 L3 DST_PORT 11 L3 SRC_PORT 12 L3 TCPFLAG 13 ARP-SP ARP_SENDER_MAC 14 ARP-SP ARP_SENDER_IP 15 L3 TRAFFIC_CLASS 21 L3 TOS 16 UDF UDF1 17 UDF UDF2 18 UDF UDF3 19 UDF UDF4 20 L3v6 TRAFFIC_CLASS 21 L3v6 DST_IPV6 22 L3v6 SRC_IPV6 23 (MSB) ------------------------------------------- The value is in Hex format. ')NEWLINEaclProfileDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileDstMacAddrMask.setDescription('The ACL Profile destination MAC address mask. If DST_MAC is turn on in aclProfileMask, it will work with its member rule field,aclL2RuleDstMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEaclProfileSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 6), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileSrcMacAddrMask.setDescription('The ACL Profile source MAC address mask. If SRC_MAC is turn on in aclProfileMask, it will work with its member rule field,aclL2RuleSrcMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEaclProfileIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 6, 17, 58, 256))).clone(namedValues=NamedValues(("none", 0), ("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17), ("icmpv6", 58), ("ipProtocolMask", 256)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileIPProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileIPProtocol.setDescription('Indicate which IP Protocol will be care in this profile. Only profile type is l3 can set the IP protocol. For others, this field will be none. ')NEWLINEaclProfileIPProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 8), OctetString().clone(hexValue="FF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileIPProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileIPProtocolMask.setDescription('The ACL Profile IP protocol mask. If aclProfileIPProtocol set to ipMask, this field will be refered. It will work with its member rule field,aclL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ')NEWLINEaclProfileDstIpAddrMaskType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileDstIpAddrMaskType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileDstIpAddrMaskType.setDescription('IPv6 Address type.')NEWLINEaclProfileDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 10), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileDstIpAddrMask.setDescription("The ACL Profile destination IP address mask. If DST_IP is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleDstIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEaclProfileSrcIpAddrMaskType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileSrcIpAddrMaskType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileSrcIpAddrMaskType.setDescription('IPv6 Address type.')NEWLINEaclProfileSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 12), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileSrcIpAddrMask.setDescription("The ACL Profile source IP address mask. If SRC_IP is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleSrcIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEaclProfileDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 13), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileDstPortMask.setDescription('The ACL Profile UDP/TCP destination port mask. If DST_PORT is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleTcpUdpDstPort, to caculate a range of destination port which is really care. The value is in HEX format. ')NEWLINEaclProfileSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 14), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileSrcPortMask.setDescription('The ACL Profile UDP/TCP source port mask. If SRC_PORT is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleTcpUdpSrcPort, to caculate a range of source port which is really care. The value is in HEX format. ')NEWLINEaclProfileArpSenderMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 15), MacAddress().clone(hexValue="FFFFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclProfileArpSenderMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileArpSenderMacAddrMask.setDescription("The ACL Profile Sender MAC mask. This is only for ARP Spoofing Prevention which is System-defined ACL, and it's not allow to modify. The value is in HEX format. ")NEWLINEaclProfileArpSenderIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 16), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclProfileArpSenderIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileArpSenderIpAddrMask.setDescription("The ACL Profile Sender IP mask. This is only for ARP Spoofing Prevention which is System-defined ACL, and it's not allow to modify. The value is in HEX format. ")NEWLINEaclProfileUdfOffsetMap = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 17), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileUdfOffsetMap.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileUdfOffsetMap.setDescription('Indicate which Udf field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ UDF Offset1 0 (LSB) UDF Offset2 1 UDF Offset3 2 UDF Offset4 3 ------------------------------------------- The value is in Hex format. ')NEWLINEaclUdfOffsetBase1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase1.setDescription('The value of offset Base.')NEWLINEaclUdfOffsetByte1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 19), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte1.setDescription('The value of offset Byte from base.')NEWLINEaclUdfOffsetMask1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 20), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask1.setDescription('The value of offset MAsk.')NEWLINEaclUdfOffsetBase2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase2.setDescription('The value of offset Base.')NEWLINEaclUdfOffsetByte2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 22), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte2.setDescription('The value of offset Byte from base.')NEWLINEaclUdfOffsetMask2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 23), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask2.setDescription('The value of offset MAsk.')NEWLINEaclUdfOffsetBase3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase3.setDescription('The value of offset Base.')NEWLINEaclUdfOffsetByte3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 25), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte3.setDescription('The value of offset Byte from base.')NEWLINEaclUdfOffsetMask3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 26), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask3.setDescription('The value of offset MAsk.')NEWLINEaclUdfOffsetBase4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 27), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase4.setDescription('The value of offset Base.')NEWLINEaclUdfOffsetByte4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 28), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte4.setDescription('The value of offset Byte from base.')NEWLINEaclUdfOffsetMask4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 29), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask4.setDescription('The value of offset MAsk.')NEWLINEaclProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 30), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclProfileStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileStatus.setDescription(" This object indicates the status of this entry, can only be set to 'createAndWait','active' and 'destroy'. When the value of the entry status is 'createAndWait', it could be set to 'active' only if the three values of aclProfileType, aclProfileMask and ProtocolType are not conflicted. ")NEWLINEaclL2Rule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2))NEWLINEaclL2RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1), )NEWLINEif mibBuilder.loadTexts: aclL2RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleTable.setDescription('A table to configure L2 filter rules in the system.')NEWLINEaclL2RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclL2ProfileID"), (0, "DES-1210-28MEbx", "aclL2AccessID"))NEWLINEif mibBuilder.loadTexts: aclL2RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleEntry.setDescription('Each entry in this table is a L2 filter rule. Index to the table is the L2 filter number and Profile ID.')NEWLINEaclL2AccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL2AccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2AccessID.setDescription('L2 Filter rule ID. 0 means auto assign.')NEWLINEaclL2ProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50)).clone(1)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL2ProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2ProfileID.setDescription('ACL Profile ID which this rule join.')NEWLINEaclL2RuleEtherType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(1501, 65535), )).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleEtherType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleEtherType.setDescription("The value in the Type/Len field of a frame that will be matched to trigger this filter. The default value of this object is '-1', which means the rule don't care this condition.")NEWLINEaclL2RuleDstMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 4), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleDstMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleDstMacAddr.setDescription("Destination MAC address to be matched with the packet. By Default, the Destination Mac Address will be zero,which means the rule don't care this condition.")NEWLINEaclL2RuleSrcMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleSrcMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleSrcMacAddr.setDescription("Source MAC address to be matched with the packet. By Default, the Source Mac Address will be zero, which means the rule don't care this condition.. address")NEWLINEaclL2RuleVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 4094)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleVlanId.setDescription("Vlan Id to be filtered. In case of Provider bridges, This Vlan Id will be treated as customer Vlan Id. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEaclL2Rule1pPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2Rule1pPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2Rule1pPriority.setDescription("802.1p priority to be matched with the packet. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEaclL2RuleDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 8), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL2RuleDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleDstMacAddrMask.setDescription("The MAC address Mask work for Destination MAC address. This field is read-only and copy from it's Profile setting.")NEWLINEaclL2RuleSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 9), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL2RuleSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleSrcMacAddrMask.setDescription("The MAC address Mask work for Source MAC address. This field is read-only and copy from it's Profile setting.")NEWLINEaclL2RuleInPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 10), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleInPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleInPortList.setDescription('Specifies the complete set of ports over which this filter is applied for packets ingress at ports in this list.')NEWLINEaclL2RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 5, 6, 7))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2), ("mirror", 3), ("replaceDSCP", 5), ("replace1P", 6), ("replaceQueue", 7))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleAction.setDescription("Specifies the action to be taken on the packet if the filter rule matches. If the action is 'allow', the packet will be forwarded according to the forwarding rules. If the action is 'drop', the packet will be discarded.")NEWLINEaclL2RuleRateLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 12), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleRateLimit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleRateLimit.setDescription('Rate limit for matched packet.')NEWLINEaclL2RuleReplaceDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleReplaceDSCP.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleReplaceDSCP.setDescription('Replace DSCP for matched packet.')NEWLINEaclL2RuleReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 14), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleReplace1P.setDescription('Replace DSCP for matched packet.')NEWLINEaclL2RuleReplaceQueue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 15), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleReplaceQueue.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleReplaceQueue.setDescription('ACL L2 Rule Replace Queue.')NEWLINEaclL2RuleFilterTimeRange = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 16), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL2RuleFilterTimeRange.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleFilterTimeRange.setDescription('ACL L2 Filter Time Range')NEWLINEaclL2RuleVlanIdMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 17), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleVlanIdMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleVlanIdMask.setDescription("Vlan Id to be filtered. In case of Provider bridges, This Vlan Id will be treated as customer Vlan Id. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEaclL2RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL2RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaclL3Rule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3))NEWLINEaclL3RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1), )NEWLINEif mibBuilder.loadTexts: aclL3RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTable.setDescription(' A table to configure L3 filter rules in the system. ')NEWLINEaclL3RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclL3RuleProfileNo"), (0, "DES-1210-28MEbx", "aclL3RuleAccessID"))NEWLINEif mibBuilder.loadTexts: aclL3RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleEntry.setDescription(' Each entry in this table is a L3 filter rule. Index to the table is L3 filter number and Profile ID.')NEWLINEaclL3RuleAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleAccessID.setDescription('L3 Filter rule ID. 0 means auto assign.')NEWLINEaclL3RuleProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleProfileNo.setDescription('The Profile ID which this rule join.')NEWLINEaclL3RuleProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 6, 17))).clone(namedValues=NamedValues(("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleProtocol.setDescription(' The type of protocol to be checked against the packet.')NEWLINEaclL3RuleProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 4), OctetString().clone(hexValue="FF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleProtocolMask.setDescription("The IP protocol mask. This field is read-only and copy from it's Profile setting. It will work with the other field,aclL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ")NEWLINEaclL3RuleICMPMessageType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleICMPMessageType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleICMPMessageType.setDescription(" The message type to be checked against the packet. If the message type matches with the packet, then the packet will be dropped / allowed based on the action set in aclL3RuleAction. The default value is '-1',which means the rule don't care this condition. Some ICMP message types are: echoReply(0), destinationUnreachable(3), sourceQuench(4), redirect(5), echoRequest(8), timeExceeded(11), parameterProblem(12), timestampRequest(13), timestampReply(14), informationRequest(15), informationReply(16), addressMaskRequest(17), addressMaskReply (18), ")NEWLINEaclL3RuleICMPMessageCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleICMPMessageCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleICMPMessageCode.setDescription(" The message code to be checked against the packet. If the packet matches with the message code, then the packet will be dropped / allowed based on the action set in aclL3RuleAction. The default value is '-1', which means the rule don't care this condition. Some ICMP message codes are : networkUnreachable(0), hostUnreachable(1), protocolUnreachable(2), portUnreachable(3), fragmentNeed(4), sourceRouteFail(5), destNetworkUnknown(6), destHostUnknown(7), srcHostIsolated(8), destNetworkAdminProhibited(9), destHostAdminProhibited(10), networkUnreachableTOS(11), hostUnreachableTOS(12), ")NEWLINEaclL3RuleDstIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 7), IpAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleDstIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleDstIpAddr.setDescription("Destination IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEaclL3RuleSrcIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 8), IpAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleSrcIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleSrcIpAddr.setDescription("Source IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEaclL3RuleDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 9), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleDstIpAddrMask.setDescription("The IP subnet mask for Destination IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEaclL3RuleSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 10), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleSrcIpAddrMask.setDescription("The IP subnet mask for Source IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEaclL3RuleTcpUdpDstPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpDstPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpDstPort.setDescription("The TCP / UDP destination port. The default value is -1, which means the rule don't care this condition.")NEWLINEaclL3RuleTcpUdpSrcPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpSrcPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpSrcPort.setDescription("The TCP / UDP source port. The default value is -1, which means the rule don't care this condition.")NEWLINEaclL3RuleTcpUdpDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 13), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpDstPortMask.setDescription("The TCP / UDP Destination port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEaclL3RuleTcpUdpSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 14), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpSrcPortMask.setDescription("The TCP / UDP Source port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEaclL3RuleTcpAckBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpAckBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpAckBit.setDescription(" The TCP ACK bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleTcpRstBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpRstBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpRstBit.setDescription(" The TCP RST bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleTcpUrgBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUrgBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUrgBit.setDescription(" The TCP Urg bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleTcpPshBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpPshBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpPshBit.setDescription(" The TCP Psh bit to be checked against the packet. The default value is 'dont_care'(-1). which means the rule don't care this condition.")NEWLINEaclL3RuleTcpSynBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpSynBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpSynBit.setDescription(" The TCP Syn bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleTcpFinBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpFinBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpFinBit.setDescription(" The TCP Fin bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleDscp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleDscp.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleDscp.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEaclL3RuleTos = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 22), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTos.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTos.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEaclL3RuleIgmpType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 23), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleIgmpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleIgmpType.setDescription(" The IGMP Type to be checked against the packet.A default value is '-1', which means the rule don't care this condition.")NEWLINEaclL3RulePortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 24), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RulePortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RulePortList.setDescription('Specifies the complete set of ports over which if the packet arrives this filter rule will be applicable.')NEWLINEaclL3RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 5, 6, 7))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2), ("mirror", 3), ("replaceDSCP", 5), ("replace1P", 6), ("replaceQueue", 7))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleAction.setDescription('Specifies the action to be taken on the packet if the filter rule matches.')NEWLINEaclL3RuleRateLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 26), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleRateLimit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleRateLimit.setDescription('Rate limit for matched packet.')NEWLINEaclL3RuleReplaceDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 27), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleReplaceDSCP.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleReplaceDSCP.setDescription('ReplaceDSCP for matched packet.')NEWLINEaclL3RuleReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 28), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleReplace1P.setDescription('ReplaceDSCP for matched packet.')NEWLINEaclL3RuleReplaceQueue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 29), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleReplaceQueue.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleReplaceQueue.setDescription('Acl L3 Rule Replace Queue.')NEWLINEaclL3RuleFilterTimeRange = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 30), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleFilterTimeRange.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleFilterTimeRange.setDescription('ACL L3 Filter Time Range')NEWLINEaclL3RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaclv6L3RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2), )NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTable.setDescription(' A table to configure L3 filter rules in the system. ')NEWLINEaclv6L3RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclv6L3RuleProfileNo"), (0, "DES-1210-28MEbx", "aclv6L3RuleAccessID"))NEWLINEif mibBuilder.loadTexts: aclv6L3RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleEntry.setDescription(' Each entry in this table is a L3 filter rule. Index to the table is L3 filter number and Profile ID.')NEWLINEaclv6L3RuleAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleAccessID.setDescription('L3 Filter rule ID. 0 means auto assign.')NEWLINEaclv6L3RuleProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProfileNo.setDescription('The Profile ID which this rule join.')NEWLINEaclv6L3RuleProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(6, 17, 58))).clone(namedValues=NamedValues(("tcp", 6), ("udp", 17), ("icmpv6", 58)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProtocol.setDescription(' The type of protocol to be checked against the packet.')NEWLINEaclv6L3RuleProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 4), OctetString().clone(hexValue="FF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProtocolMask.setDescription("The IP protocol mask. This field is read-only and copy from it's Profile setting. It will work with the other field,aclL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ")NEWLINEaclv6L3RuleICMPMessageType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleICMPMessageType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleICMPMessageType.setDescription(" The message type to be checked against the packet. If the message type matches with the packet, then the packet will be dropped / allowed based on the action set in aclL3RuleAction. The default value is '-1',which means the rule don't care this condition. Some ICMP message types are: echoReply(0), destinationUnreachable(3), sourceQuench(4), redirect(5), echoRequest(8), timeExceeded(11), parameterProblem(12), timestampRequest(13), timestampReply(14), informationRequest(15), informationReply(16), addressMaskRequest(17), addressMaskReply (18), ")NEWLINEaclv6L3RuleICMPMessageCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleICMPMessageCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleICMPMessageCode.setDescription(" The message code to be checked against the packet. If the packet matches with the message code, then the packet will be dropped / allowed based on the action set in aclL3RuleAction. The default value is '-1', which means the rule don't care this condition. Some ICMP message codes are : networkUnreachable(0), hostUnreachable(1), protocolUnreachable(2), portUnreachable(3), fragmentNeed(4), sourceRouteFail(5), destNetworkUnknown(6), destHostUnknown(7), srcHostIsolated(8), destNetworkAdminProhibited(9), destHostAdminProhibited(10), networkUnreachableTOS(11), hostUnreachableTOS(12), ")NEWLINEaclv6L3RuleDstIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 7), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleDstIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleDstIpAddr.setDescription("Destination IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEaclv6L3RuleSrcIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 8), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleSrcIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleSrcIpAddr.setDescription("Source IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEaclv6L3RuleDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 9), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleDstIpAddrMask.setDescription("The IP subnet mask for Destination IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEaclv6L3RuleSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 10), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleSrcIpAddrMask.setDescription("The IP subnet mask for Source IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEaclv6L3RuleTcpUdpDstPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpDstPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpDstPort.setDescription("The TCP / UDP destination port. The default value is -1, which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpUdpSrcPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpSrcPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpSrcPort.setDescription("The TCP / UDP source port. The default value is -1, which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpUdpDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 13), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpDstPortMask.setDescription("The TCP / UDP Destination port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEaclv6L3RuleTcpUdpSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 14), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpSrcPortMask.setDescription("The TCP / UDP Source port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEaclv6L3RuleTcpAckBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpAckBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpAckBit.setDescription(" The TCP ACK bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpRstBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpRstBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpRstBit.setDescription(" The TCP RST bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpUrgBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUrgBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUrgBit.setDescription(" The TCP Urg bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpPshBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpPshBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpPshBit.setDescription(" The TCP Psh bit to be checked against the packet. The default value is 'dont_care'(-1). which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpSynBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpSynBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpSynBit.setDescription(" The TCP Syn bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpFinBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpFinBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpFinBit.setDescription(" The TCP Fin bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTrafficClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTrafficClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTrafficClass.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEaclv6L3RulePortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 23), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RulePortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RulePortList.setDescription('Specifies the complete set of ports over which if the packet arrives this filter rule will be applicable.')NEWLINEaclv6L3RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 5, 6, 7))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2), ("mirror", 3), ("replaceDSCP", 5), ("replace1P", 6), ("replaceQueue", 7))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleAction.setDescription('Specifies the action to be taken on the packet if the filter rule matches.')NEWLINEaclv6L3RuleRateLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 25), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleRateLimit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleRateLimit.setDescription('Rate limit for matched packet.')NEWLINEaclv6L3RuleReplaceDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 26), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplaceDSCP.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplaceDSCP.setDescription('Replace DSCP for matched packet.')NEWLINEaclv6L3RuleReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 27), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplace1P.setDescription('Replace DSCP for matched packet.')NEWLINEaclv6L3RuleReplaceQueue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 28), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplaceQueue.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplaceQueue.setDescription('Acl IPV6 L3 Rule Replace Queue.')NEWLINEaclv6L3RuleFilterTimeRange = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 29), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleFilterTimeRange.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleFilterTimeRange.setDescription('ACL IPV6 L3 Filter Time Range')NEWLINEaclv6L3RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaclPacketRule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4))NEWLINEaclPacketRuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1), )NEWLINEif mibBuilder.loadTexts: aclPacketRuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleTable.setDescription('A table to configure Packet Content filter rules in the system.')NEWLINEaclPacketRuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclPacketProfileID"), (0, "DES-1210-28MEbx", "aclPacketAccessID"))NEWLINEif mibBuilder.loadTexts: aclPacketRuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleEntry.setDescription('Each entry in this table is a Packet filter rule. Index to the table is the Packet filter number and Profile ID.')NEWLINEaclPacketAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclPacketAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketAccessID.setDescription('Packet Filter rule ID. 0 means auto assign.')NEWLINEaclPacketProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclPacketProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketProfileID.setDescription('ACL Profile ID which this rule join.')NEWLINEaclPacketRuleOffsetValue1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 3), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue1.setDescription('The filter value of Offset 1.')NEWLINEaclPacketRuleOffsetValue2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue2.setDescription('The filter value of Offset 2.')NEWLINEaclPacketRuleOffsetValue3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 5), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue3.setDescription('The filter value of Offset 3.')NEWLINEaclPacketRuleOffsetValue4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 6), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue4.setDescription('The filter value of Offset 4.')NEWLINEaclPacketRuleInPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 7), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleInPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleInPortList.setDescription('Specifies the complete set of ports over which this filter is applied for packets ingress at ports in this list.')NEWLINEaclPacketRuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 5, 6, 7))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2), ("mirror", 3), ("replaceDSCP", 5), ("replace1P", 6), ("replaceQueue", 7))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleAction.setDescription("Specifies the action to be taken on the packet if the filter rule matches. If the action is 'allow', the packet will be forwarded according to the forwarding rules. If the action is 'drop', the packet will be discarded.")NEWLINEaclPacketRuleRateLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 9), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleRateLimit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleRateLimit.setDescription('Rate limit for matched packet.')NEWLINEaclPacketRuleReplaceDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplaceDSCP.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplaceDSCP.setDescription('Replace DSCP for matched packet.')NEWLINEaclPacketRuleReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplace1P.setDescription('Replace 1p for matched packet.')NEWLINEaclPacketRuleReplaceQueue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 12), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplaceQueue.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplaceQueue.setDescription('Acl Rule Replace Queue.')NEWLINEaclPacketRuleFilterTimeRange = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 13), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclPacketRuleFilterTimeRange.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleFilterTimeRange.setDescription('Acl Filter Time Range')NEWLINEaclPacketRuleOffsetValue1Mask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 14), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue1Mask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue1Mask.setDescription('The filter Mask of Offset 1.')NEWLINEaclPacketRuleOffsetValue2Mask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 15), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue2Mask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue2Mask.setDescription('The filter Mask of Offset 2.')NEWLINEaclPacketRuleOffsetValue3Mask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 16), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue3Mask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue3Mask.setDescription('The filter Mask of Offset 3.')NEWLINEaclPacketRuleOffsetValue4Mask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 17), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue4Mask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue4Mask.setDescription('The filter Mask of Offset 4.')NEWLINEaclPacketRuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclPacketRuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaclFlowMeterRule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10))NEWLINEaclFlowMeterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1), )NEWLINEif mibBuilder.loadTexts: aclFlowMeterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterTable.setDescription('A table to configure L2 filter rules in the system.')NEWLINEaclFlowMeterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclFlowMeterProfileID"), (0, "DES-1210-28MEbx", "aclFlowMeterAccessID"))NEWLINEif mibBuilder.loadTexts: aclFlowMeterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterEntry.setDescription('Each entry in this table is a L2 filter rule. Index to the table is the L2 filter number and Profile ID.')NEWLINEaclFlowMeterProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclFlowMeterProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterProfileID.setDescription('ACL Profile ID which this flow meter join.')NEWLINEaclFlowMeterAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclFlowMeterAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterAccessID.setDescription('ACL Access ID which this flow meter join.')NEWLINEaclFlowMeterRate = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(64, 1024000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclFlowMeterRate.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterRate.setDescription('The rate limiter of meter.')NEWLINEaclFlowMeterBurstSize = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1016))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclFlowMeterBurstSize.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterBurstSize.setDescription('The burst size of meter.')NEWLINEaclFlowMeterReplaceDscp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclFlowMeterReplaceDscp.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterReplaceDscp.setDescription('Replace DSCP for matched out-band packets when aclFlowMeterAction is replace DSCP.')NEWLINEaclFlowMeterAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2, 5))).clone(namedValues=NamedValues(("drop", 2), ("replaceDSCP", 5))).clone('drop')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclFlowMeterAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterAction.setDescription("Specifies the action to be taken on the out-band packet if the filter rule matches. If the action is 'drop', the packet will be discarded.")NEWLINEaclFlowMeterStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclFlowMeterStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEcpuFilterProfile = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1))NEWLINEipv4cpuFilterProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1), )NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileTable.setDescription(' A table to CPUInterfaceFilter profile . ')NEWLINEipv4cpuFilterProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4cpuFilterProfileNo"))NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileEntry.setDescription(' Each entry in this table is a CPUInterfaceFilter profile. Index to the table is CPUInterfaceFilter profile ID. ')NEWLINEipv4cpuFilterProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileNo.setDescription('The CPUInterfaceFilter Profile ID. The ID 1 to 50 is user-defined CPUInterfaceFilter, and the ID more than 50 is reserved for system-defined CPUInterfaceFilter. The user only allow to create user-defined CPUInterfaceFilter ID. And system-defined CPUInterfaceFilter is read only.')NEWLINEipv4cpuFilterProfileType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 11))).clone(namedValues=NamedValues(("l2", 1), ("l3", 2), ("l3v6", 11)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileType.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileType.setDescription('The CPUInterfaceFilter Profile type, possible value are l2 (1) - for MAC-based rule, l3 (2) - for IPv4-based rule, l3v6 (11) - for IPv6-based rule ')NEWLINEipv4cpuFilterProfileRuleCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileRuleCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileRuleCount.setDescription('The number of rules in this profile.')NEWLINEipv4cpuFilterProfileMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileMask.setDescription('Indicate which field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ L2 DST_MAC 0 (LSB) L2 SRC_MAC 1 L2 VID 2 L2 8021P_PRIORITY 3 L2 ETHER_TYPE 4 L3 DSCP 5 L3 ICMP_TYPE 6 L3 ICMP_CODE 7 L3 IGMP_TYPE 8 L3 DST_IP 9 L3 SRC_IP 10 L3 DST_PORT 11 L3 SRC_PORT 12 L3 TCPFLAG 13 (MSB) ------------------------------------------- The value is in Hex format. ')NEWLINEipv4cpuFilterProfileDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstMacAddrMask.setDescription('The CPUInterfaceFilter Profile destination MAC address mask. If DST_MAC is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL2RuleDstMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEipv4cpuFilterProfileSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 6), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcMacAddrMask.setDescription('The CPUInterfaceFilter Profile source MAC address mask. If SRC_MAC is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL2RuleSrcMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEipv4cpuFilterProfileIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 6, 17, 255))).clone(namedValues=NamedValues(("none", 0), ("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17), ("ipMask", 255)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileIPProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileIPProtocol.setDescription('Indicate which IP Protocol will be care in this profile. Only profile type is l3 can set the IP protocol. For others, this field will be none. ')NEWLINEipv4cpuFilterProfileIPProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 8), OctetString().clone(hexValue="FF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileIPProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileIPProtocolMask.setDescription('The CPUInterfaceFilter Profile IP protocol mask. If cpuFilterProfileIPProtocol set to ipMask, this field will be refered. It will work with its member rule field,cpuFilterL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ')NEWLINEipv4cpuFilterProfileDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 9), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstIpAddrMask.setDescription("The CPUInterfaceFilter Profile destination IP address mask. If DST_IP is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleDstIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEipv4cpuFilterProfileSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 10), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcIpAddrMask.setDescription("The CPUInterfaceFilter Profile source IP address mask. If SRC_IP is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleSrcIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEipv4cpuFilterProfileDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 11), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstPortMask.setDescription('The CPUInterfaceFilter Profile UDP/TCP destination port mask. If DST_PORT is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleTcpUdpDstPort, to caculate a range of destination port which is really care. The value is in HEX format. ')NEWLINEipv4cpuFilterProfileSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 12), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcPortMask.setDescription('The CPUInterfaceFilter Profile UDP/TCP source port mask. If SRC_PORT is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleTcpUdpSrcPort, to caculate a range of source port which is really care. The value is in HEX format. ')NEWLINEipv4cpuFilterProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 15), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileStatus.setDescription(" This object indicates the status of this entry, can only be set to 'createAndWait','active' and 'destroy'. When the value of the entry status is 'createAndWait', it could be set to 'active' only if the three values of cpuFilterProfileType, cpuFilterProfileMask and ProtocolType are not conflicted. ")NEWLINEcpuFilterProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2), )NEWLINEif mibBuilder.loadTexts: cpuFilterProfileTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileTable.setDescription(' A table to CPUInterfaceFilter profile . ')NEWLINEcpuFilterProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cpuFilterProfileNo"))NEWLINEif mibBuilder.loadTexts: cpuFilterProfileEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileEntry.setDescription(' Each entry in this table is a CPUInterfaceFilter profile. Index to the table is CPUInterfaceFilter profile ID. ')NEWLINEcpuFilterProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileNo.setDescription('The CPUInterfaceFilter Profile ID. The ID 1 to 50 is user-defined CPUInterfaceFilter, and the ID more than 50 is reserved for system-defined CPUInterfaceFilter. The user only allow to create user-defined CPUInterfaceFilter ID. And system-defined CPUInterfaceFilter is read only.')NEWLINEcpuFilterProfileType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 11))).clone(namedValues=NamedValues(("l2", 1), ("l3", 2), ("l3v6", 11)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileType.setDescription('The CPUInterfaceFilter Profile type, possible value are l2 (1) - for MAC-based rule, l3 (2) - for IPv4-based rule, l3v6 (11) - for IPv6-based rule ')NEWLINEcpuFilterProfileRuleCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileRuleCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileRuleCount.setDescription('The number of rules in this profile.')NEWLINEcpuFilterProfileMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileMask.setDescription('Indicate which field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ L2 DST_MAC 0 (LSB) L2 SRC_MAC 1 L2 VID 2 L2 8021P_PRIORITY 3 L2 ETHER_TYPE 4 L3 DSCP 5 L3 ICMP_TYPE 6 L3 ICMP_CODE 7 L3 IGMP_TYPE 8 L3 DST_IP 9 L3 SRC_IP 10 L3 DST_PORT 11 L3 SRC_PORT 12 L3 TCPFLAG 13 (MSB) L3 TRAFFIC_CLASS 21 ------------------------------------------- The value is in Hex format. ')NEWLINEcpuFilterProfileDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstMacAddrMask.setDescription('The CPUInterfaceFilter Profile destination MAC address mask. If DST_MAC is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL2RuleDstMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEcpuFilterProfileSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 6), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcMacAddrMask.setDescription('The CPUInterfaceFilter Profile source MAC address mask. If SRC_MAC is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL2RuleSrcMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEcpuFilterProfileIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 6, 17, 255))).clone(namedValues=NamedValues(("none", 0), ("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17), ("ipMask", 255)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileIPProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileIPProtocol.setDescription('Indicate which IP Protocol will be care in this profile. Only profile type is l3 can set the IP protocol. For others, this field will be none. ')NEWLINEcpuFilterProfileIPProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 8), OctetString().clone(hexValue="FF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileIPProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileIPProtocolMask.setDescription('The CPUInterfaceFilter Profile IP protocol mask. If cpuFilterProfileIPProtocol set to ipMask, this field will be refered. It will work with its member rule field,cpuFilterL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ')NEWLINEcpuFilterProfileDstIpAddrMaskType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstIpAddrMaskType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstIpAddrMaskType.setDescription('IPv6 Address type.')NEWLINEcpuFilterProfileDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 10), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstIpAddrMask.setDescription("The CPUInterfaceFilter Profile destination IP address mask. If DST_IP is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleDstIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEcpuFilterProfileSrcIpAddrMaskType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcIpAddrMaskType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcIpAddrMaskType.setDescription('IPv6 Address type.')NEWLINEcpuFilterProfileSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 12), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcIpAddrMask.setDescription("The CPUInterfaceFilter Profile source IP address mask. If SRC_IP is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleSrcIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEcpuFilterProfileDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 13), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstPortMask.setDescription('The CPUInterfaceFilter Profile UDP/TCP destination port mask. If DST_PORT is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleTcpUdpDstPort, to caculate a range of destination port which is really care. The value is in HEX format. ')NEWLINEcpuFilterProfileSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 14), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcPortMask.setDescription('The CPUInterfaceFilter Profile UDP/TCP source port mask. If SRC_PORT is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleTcpUdpSrcPort, to caculate a range of source port which is really care. The value is in HEX format. ')NEWLINEcpuFilterProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 15), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileStatus.setDescription(" This object indicates the status of this entry, can only be set to 'createAndWait','active' and 'destroy'. When the value of the entry status is 'createAndWait', it could be set to 'active' only if the three values of cpuFilterProfileType, cpuFilterProfileMask and ProtocolType are not conflicted. ")NEWLINEcpuFilterL2Rule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2))NEWLINEcpuFilterL2RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1), )NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleTable.setDescription('A table to configure L2 filter rules in the system.')NEWLINEcpuFilterL2RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cpuFilterL2ProfileID"), (0, "DES-1210-28MEbx", "cpuFilterL2AccessID"))NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleEntry.setDescription('Each entry in this table is a L2 filter rule. Index to the table is the L2 filter number and Profile ID.')NEWLINEcpuFilterL2ProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL2ProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2ProfileID.setDescription('L2 Filter rule ID.')NEWLINEcpuFilterL2AccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 5)).clone(1)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL2AccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2AccessID.setDescription('CPUInterfaceFilter Profile ID which this rule join.')NEWLINEcpuFilterL2RuleEtherType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(1501, 65535), )).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleEtherType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleEtherType.setDescription("The value in the Type/Len field of a frame that will be matched to trigger this filter. The default value of this object is '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL2RuleDstMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 4), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleDstMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleDstMacAddr.setDescription("Destination MAC address to be matched with the packet. By Default, the Destination Mac Address will be zero,which means the rule don't care this condition.")NEWLINEcpuFilterL2RuleSrcMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleSrcMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleSrcMacAddr.setDescription("Source MAC address to be matched with the packet. By Default, the Source Mac Address will be zero, which means the rule don't care this condition.. address")NEWLINEcpuFilterL2RuleVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 4094)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleVlanId.setDescription("Vlan Id to be filtered. In case of Provider bridges, This Vlan Id will be treated as customer Vlan Id. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL2Rule1pPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2Rule1pPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2Rule1pPriority.setDescription("802.1p priority to be matched with the packet. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL2RuleDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 8), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleDstMacAddrMask.setDescription("The MAC address Mask work for Destination MAC address. This field is read-only and copy from it's Profile setting.")NEWLINEcpuFilterL2RuleSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 9), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleSrcMacAddrMask.setDescription("The MAC address Mask work for Source MAC address. This field is read-only and copy from it's Profile setting.")NEWLINEcpuFilterL2RuleInPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 10), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleInPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleInPortList.setDescription('Specifies the complete set of ports over which this filter is applied for packets ingress at ports in this list.')NEWLINEcpuFilterL2RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleAction.setDescription("Specifies the action to be taken on the packet if the filter rule matches. If the action is 'allow', the packet will be forwarded according to the forwarding rules. If the action is 'drop', the packet will be discarded.")NEWLINEcpuFilterL2RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 14), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEcpuFilterL3Rule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3))NEWLINEcpuFilterL3RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1), )NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTable.setDescription(' A table to configure L3 filter rules in the system. ')NEWLINEcpuFilterL3RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cpuFilterL3RuleProfileNo"), (0, "DES-1210-28MEbx", "cpuFilterL3RuleAccessID"))NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleEntry.setDescription(' Each entry in this table is a L3 filter rule. Index to the table is L3 filter number and Profile ID.')NEWLINEcpuFilterL3RuleProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 5))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProfileNo.setDescription('L3 Filter rule ID.')NEWLINEcpuFilterL3RuleAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleAccessID.setDescription('The Profile ID which this rule join.')NEWLINEcpuFilterL3RuleProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 6, 17))).clone(namedValues=NamedValues(("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProtocol.setDescription(' The type of protocol to be checked against the packet.')NEWLINEcpuFilterL3RuleProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 4), OctetString().clone(hexValue="FF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProtocolMask.setDescription("The IP protocol mask. This field is read-only and copy from it's Profile setting. It will work with the other field,cpuFilterL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ")NEWLINEcpuFilterL3RuleICMPMessageType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleICMPMessageType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleICMPMessageType.setDescription(" The message type to be checked against the packet. If the message type matches with the packet, then the packet will be dropped / allowed based on the action set in cpuFilterL3RuleAction. The default value is '-1',which means the rule don't care this condition. Some ICMP message types are: echoReply(0), destinationUnreachable(3), sourceQuench(4), redirect(5), echoRequest(8), timeExceeded(11), parameterProblem(12), timestampRequest(13), timestampReply(14), informationRequest(15), informationReply(16), addressMaskRequest(17), addressMaskReply (18), ")NEWLINEcpuFilterL3RuleICMPMessageCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleICMPMessageCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleICMPMessageCode.setDescription(" The message code to be checked against the packet. If the packet matches with the message code, then the packet will be dropped / allowed based on the action set in cpuFilterL3RuleAction. The default value is '-1', which means the rule don't care this condition. Some ICMP message codes are : networkUnreachable(0), hostUnreachable(1), protocolUnreachable(2), portUnreachable(3), fragmentNeed(4), sourceRouteFail(5), destNetworkUnknown(6), destHostUnknown(7), srcHostIsolated(8), destNetworkAdminProhibited(9), destHostAdminProhibited(10), networkUnreachableTOS(11), hostUnreachableTOS(12), ")NEWLINEcpuFilterL3RuleDstIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 7), IpAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDstIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDstIpAddr.setDescription("Destination IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleSrcIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 8), IpAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleSrcIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleSrcIpAddr.setDescription("Source IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 9), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDstIpAddrMask.setDescription("The IP subnet mask for Destination IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterL3RuleSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 10), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleSrcIpAddrMask.setDescription("The IP subnet mask for Source IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterL3RuleTcpUdpDstPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpDstPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpDstPort.setDescription("The TCP / UDP destination port. The default value is -1, which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpUdpSrcPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpSrcPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpSrcPort.setDescription("The TCP / UDP source port. The default value is -1, which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpUdpDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 13), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpDstPortMask.setDescription("The TCP / UDP Destination port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterL3RuleTcpUdpSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 14), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpSrcPortMask.setDescription("The TCP / UDP Source port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterL3RuleTcpAckBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpAckBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpAckBit.setDescription(" The TCP ACK bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpRstBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpRstBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpRstBit.setDescription(" The TCP RST bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpUrgBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUrgBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUrgBit.setDescription(" The TCP Urg bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpPshBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpPshBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpPshBit.setDescription(" The TCP Psh bit to be checked against the packet. The default value is 'dontcare'(-1). which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpSynBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpSynBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpSynBit.setDescription(" The TCP Syn bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpFinBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpFinBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpFinBit.setDescription(" The TCP Fin bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleDscp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDscp.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDscp.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleIgmpType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 22), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleIgmpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleIgmpType.setDescription(" The IGMP Type to be checked against the packet.A default value is '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL3RulePortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 23), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RulePortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RulePortList.setDescription('Specifies the complete set of ports over which if the packet arrives this filter rule will be applicable.')NEWLINEcpuFilterL3RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleAction.setDescription('Specifies the action to be taken on the packet if the filter rule matches.')NEWLINEcpuFilterL3RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 27), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEcpuFilterv6L3RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2), )NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTable.setDescription(' A table to configure L3 filter rules in the system. ')NEWLINEcpuFilterv6L3RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cpuFilterv6L3RuleProfileNo"), (0, "DES-1210-28MEbx", "cpuFilterv6L3RuleAccessID"))NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleEntry.setDescription(' Each entry in this table is a L3 filter rule. Index to the table is L3 filter number and Profile ID.')NEWLINEcpuFilterv6L3RuleProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 5))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProfileNo.setDescription('L3 Filter rule ID.')NEWLINEcpuFilterv6L3RuleAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleAccessID.setDescription('The Profile ID which this rule join.')NEWLINEcpuFilterv6L3RuleProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 6, 17))).clone(namedValues=NamedValues(("icmp", 1), ("tcp", 6), ("udp", 17)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProtocol.setDescription(' The type of protocol to be checked against the packet.')NEWLINEcpuFilterv6L3RuleProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 4), OctetString().clone(hexValue="FF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProtocolMask.setDescription("The IP protocol mask. This field is read-only and copy from it's Profile setting. It will work with the other field,cpuFilterL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ")NEWLINEcpuFilterv6L3RuleICMPMessageType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleICMPMessageType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleICMPMessageType.setDescription(" The message type to be checked against the packet. If the message type matches with the packet, then the packet will be dropped / allowed based on the action set in cpuFilterL3RuleAction. The default value is '-1',which means the rule don't care this condition. Some ICMP message types are: echoReply(0), destinationUnreachable(3), sourceQuench(4), redirect(5), echoRequest(8), timeExceeded(11), parameterProblem(12), timestampRequest(13), timestampReply(14), informationRequest(15), informationReply(16), addressMaskRequest(17), addressMaskReply (18), ")NEWLINEcpuFilterv6L3RuleICMPMessageCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleICMPMessageCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleICMPMessageCode.setDescription(" The message code to be checked against the packet. If the packet matches with the message code, then the packet will be dropped / allowed based on the action set in cpuFilterL3RuleAction. The default value is '-1', which means the rule don't care this condition. Some ICMP message codes are : networkUnreachable(0), hostUnreachable(1), protocolUnreachable(2), portUnreachable(3), fragmentNeed(4), sourceRouteFail(5), destNetworkUnknown(6), destHostUnknown(7), srcHostIsolated(8), destNetworkAdminProhibited(9), destHostAdminProhibited(10), networkUnreachableTOS(11), hostUnreachableTOS(12), ")NEWLINEcpuFilterv6L3RuleDstIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 7), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleDstIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleDstIpAddr.setDescription("Destination IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleSrcIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 8), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleSrcIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleSrcIpAddr.setDescription("Source IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 9), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleDstIpAddrMask.setDescription("The IP subnet mask for Destination IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterv6L3RuleSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 10), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleSrcIpAddrMask.setDescription("The IP subnet mask for Source IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterv6L3RuleTcpUdpDstPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpDstPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpDstPort.setDescription("The TCP / UDP destination port. The default value is -1, which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpUdpSrcPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpSrcPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpSrcPort.setDescription("The TCP / UDP source port. The default value is -1, which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpUdpDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 13), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpDstPortMask.setDescription("The TCP / UDP Destination port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterv6L3RuleTcpUdpSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 14), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpSrcPortMask.setDescription("The TCP / UDP Source port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterv6L3RuleTcpAckBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpAckBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpAckBit.setDescription(" The TCP ACK bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpRstBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpRstBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpRstBit.setDescription(" The TCP RST bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpUrgBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUrgBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUrgBit.setDescription(" The TCP Urg bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpPshBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpPshBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpPshBit.setDescription(" The TCP Psh bit to be checked against the packet. The default value is 'dontcare'(-1). which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpSynBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpSynBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpSynBit.setDescription(" The TCP Syn bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpFinBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpFinBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpFinBit.setDescription(" The TCP Fin bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTrafficClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTrafficClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTrafficClass.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RulePortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 22), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RulePortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RulePortList.setDescription('Specifies the complete set of ports over which if the packet arrives this filter rule will be applicable.')NEWLINEcpuFilterv6L3RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 23), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleAction.setDescription('Specifies the action to be taken on the packet if the filter rule matches.')NEWLINEcpuFilterv6L3RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 24), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEsnmpGlobalState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpGlobalState.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpGlobalState.setDescription('This object is for enabling or disabling SNMP Community function.')NEWLINEsnmpV3User = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2))NEWLINEsnmpV3Group = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3))NEWLINEsnmpV3ViewTree = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4))NEWLINEsnmpV3Community = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5))NEWLINEsnmpV3Host = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6))NEWLINEsnmpV3EngineID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 7), SnmpEngineID()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3EngineID.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3EngineID.setDescription("An SNMP engine's administratively-unique identifier. In a simple agent, this value is always that agent's own snmpEngineID value. The value can also take the value of the snmpEngineID of a remote SNMP engine with which this user can communicate.")NEWLINEsnmpV3Trap = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8))NEWLINEsnmpV3UserTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1), )NEWLINEif mibBuilder.loadTexts: snmpV3UserTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserTable.setDescription('')NEWLINEsnmpV3UserEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3UserName"), (0, "DES-1210-28MEbx", "snmpV3UserVersion"))NEWLINEif mibBuilder.loadTexts: snmpV3UserEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserEntry.setDescription('')NEWLINEsnmpV3UserName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3UserName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserName.setDescription('A human readable string representing the name of the user. This is the (User-based Security) Model dependent security ID. ')NEWLINEsnmpV3UserVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("v1", 1), ("v2c", 2), ("v3", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3UserVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserVersion.setDescription('A human readable string representing the name of the user. This is the (User-based Security) Model dependent security ID. ')NEWLINEsnmpV3UserGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserGroupName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserGroupName.setDescription('The name of the group to which this entry (e.g., the combination of securityModel and securityName) belongs. This groupName is used as index into the vacmAccessTable to select an access control policy. However, a value in this table does not imply that an instance with the value exists in table vacmAccesTable. ')NEWLINEsnmpV3UserAuthProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("md5", 2), ("sha", 3)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserAuthProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserAuthProtocol.setDescription("An indication of whether messages sent on behalf of this user to/from the SNMP engine identified by usmUserEngineID, can be authenticated, and if so, the type of authentication protocol which is used. An instance of this object is created concurrently with the creation of any other object instance for the same user (i.e., as part of the processing of the set operation which creates the first object instance in the same conceptual row). If an initial set operation (i.e. at row creation time) tries to set a value for an unknown or unsupported protocol, then a 'wrongValue' error must be returned. The value will be overwritten/set when a set operation is performed on the corresponding instance of UserCloneFrom. Once instantiated, the value of such an instance of this object can only be changed via a set operation to the value of the NoAuthProtocol. If a set operation tries to change the value of an existing instance of this object to any value other than NoAuthProtocol, then an 'inconsistentValue' error must be returned. If a set operation tries to set the value to the NoAuthProtocol while the UserPrivProtocol value in the same row is not equal to NoPrivProtocol, then an 'inconsistentValue' error must be returned. That means that an SNMP command generator application must first ensure that the UserPrivProtocol is set to the NoPrivProtocol value before it can set the UserAuthProtocol value to NoAuthProtocol. ")NEWLINEsnmpV3UserAuthProtocolPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 5), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserAuthProtocolPassword.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserAuthProtocolPassword.setDescription('')NEWLINEsnmpV3UserPrivProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("none", 1), ("des", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserPrivProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserPrivProtocol.setDescription("An indication of whether messages sent on behalf of this user to/from the SNMP engine identified by usmUserEngineID, can be protected from disclosure, and if so, the type of privacy protocol which is used. An instance of this object is created concurrently with the creation of any other object instance for the same user (i.e., as part of the processing of the set operation which creates the first object instance in the same conceptual row). If an initial set operation (i.e. at row creation time) tries to set a value for an unknown or unsupported protocol, then a 'wrongValue' error must be returned. The value will be overwritten/set when a set operation is performed on the corresponding instance of usmUserCloneFrom. Once instantiated, the value of such an instance of this object can only be changed via a set operation to the value of the NoPrivProtocol. If a set operation tries to change the value of an existing instance of this object to any value other than NoPrivProtocol, then an 'inconsistentValue' error must be returned. Note that if any privacy protocol is used, then you must also use an authentication protocol. In other words, if usmUserPrivProtocol is set to anything else than NoPrivProtocol, then the corresponding instance of usmUserAuthProtocol cannot have a value of usmNoAuthProtocol. If it does, then an 'inconsistentValue' error must be returned. ")NEWLINEsnmpV3UserPrivProtocolPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 7), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserPrivProtocolPassword.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserPrivProtocolPassword.setDescription('')NEWLINEsnmpV3UserStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 8), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserStatus.setDescription("The status of this conceptual row. Until instances of all corresponding columns are appropriately configured, the value of the corresponding instance of the usmUserStatus column is 'notReady'. In particular, a newly created row for a user who employs authentication, cannot be made active until the corresponding usmUserCloneFrom and usmUserAuthKeyChange have been set. Further, a newly created row for a user who also employs privacy, cannot be made active until the usmUserPrivKeyChange has been set. The RowStatus TC [RFC2579] requires that this DESCRIPTION clause states under which circumstances other objects in this row can be modified: The value of this object has no effect on whether other objects in this conceptual row can be modified, except for usmUserOwnAuthKeyChange and usmUserOwnPrivKeyChange. For these 2 objects, the value of usmUserStatus MUST be active. ")NEWLINEsnmpV3GroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1), )NEWLINEif mibBuilder.loadTexts: snmpV3GroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupTable.setDescription('')NEWLINEsnmpV3GroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3GroupName"), (0, "DES-1210-28MEbx", "snmpV3GroupSecurityModel"), (0, "DES-1210-28MEbx", "snmpV3GroupSecurityLevel"))NEWLINEif mibBuilder.loadTexts: snmpV3GroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupEntry.setDescription('')NEWLINEsnmpV3GroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3GroupName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupName.setDescription('The name of the group to which this entry (e.g., the combination of securityModel and securityName) belongs. This groupName is used as index into the vacmAccessTable to select an access control policy. However, a value in this table does not imply that an instance with the value exists in table vacmAccesTable. ')NEWLINEsnmpV3GroupSecurityModel = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("v1", 1), ("v2c", 2), ("v3", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3GroupSecurityModel.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupSecurityModel.setDescription('In order to gain the access rights allowed by this conceptual row, this securityModel must be in use. ')NEWLINEsnmpV3GroupSecurityLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 3), SnmpSecurityLevel()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3GroupSecurityLevel.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupSecurityLevel.setDescription('The minimum level of security required in order to gain the access rights allowed by this conceptual row. A securityLevel of noAuthNoPriv is less than authNoPriv which in turn is less than authPriv. If multiple entries are equally indexed except for this vacmAccessSecurityLevel index, then the entry which has the highest value for vacmAccessSecurityLevel is selected. ')NEWLINEsnmpV3GroupReadViewName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 4), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3GroupReadViewName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupReadViewName.setDescription('The value of an instance of this object identifies the MIB view of the SNMP context to which this conceptual row authorizes read access. The identified MIB view is that one for which the vacmViewTreeFamilyViewName has the same value as the instance of this object; if the value is the empty string or if there is no active MIB view having this value of vacmViewTreeFamilyViewName, then no access is granted. ')NEWLINEsnmpV3GroupWriteViewName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 5), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3GroupWriteViewName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupWriteViewName.setDescription('The value of an instance of this object identifies the MIB view of the SNMP context to which this conceptual row authorizes write access. The identified MIB view is that one for which the vacmViewTreeFamilyViewName has the same value as the instance of this object; if the value is the empty string or if there is no active MIB view having this value of vacmViewTreeFamilyViewName, then no access is granted. ')NEWLINEsnmpV3GroupNotifyViewName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 6), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3GroupNotifyViewName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupNotifyViewName.setDescription('The value of an instance of this object identifies the MIB view of the SNMP context to which this conceptual row authorizes access for notifications. The identified MIB view is that one for which the vacmViewTreeFamilyViewName has the same value as the instance of this object; if the value is the empty string or if there is no active MIB view having this value of vacmViewTreeFamilyViewName, then no access is granted. ')NEWLINEsnmpV3GroupStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 7), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3GroupStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupStatus.setDescription('The status of this conceptual row. The RowStatus TC [RFC2579] requires that this DESCRIPTION clause states under which circumstances other objects in this row can be modified: The value of this object has no effect on whether other objects in this conceptual row can be modified. ')NEWLINEsnmpV3ViewTreeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1), )NEWLINEif mibBuilder.loadTexts: snmpV3ViewTreeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3ViewTreeTable.setDescription('')NEWLINEsnmpV3ViewTreeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3viewTreeName"), (0, "DES-1210-28MEbx", "snmpV3viewTreeSubtree"))NEWLINEif mibBuilder.loadTexts: snmpV3ViewTreeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3ViewTreeEntry.setDescription('')NEWLINEsnmpV3viewTreeName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeName.setDescription('The human readable name for a family of view subtrees. ')NEWLINEsnmpV3viewTreeSubtree = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeSubtree.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeSubtree.setDescription('The MIB subtree which when combined with the corresponding instance of vacmViewTreeFamilyMask defines a family of view subtrees. ')NEWLINEsnmpV3viewTreeMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeMask.setDescription("The bit mask which, in combination with the corresponding instance of vacmViewTreeFamilySubtree, defines a family of view subtrees. Each bit of this bit mask corresponds to a sub-identifier of vacmViewTreeFamilySubtree, with the most significant bit of the i-th octet of this octet string value (extended if necessary, see below) corresponding to the (8*i - 7)-th sub-identifier, and the least significant bit of the i-th octet of this octet string corresponding to the (8*i)-th sub-identifier, where i is in the range 1 through 16. Each bit of this bit mask specifies whether or not the corresponding sub-identifiers must match when determining if an OBJECT IDENTIFIER is in this family of view subtrees; a '1' indicates that an exact match must occur; a '0' indicates 'wild card', i.e., any sub-identifier value matches. Thus, the OBJECT IDENTIFIER X of an object instance is contained in a family of view subtrees if, for each sub-identifier of the value of vacmViewTreeFamilySubtree, either: the i-th bit of vacmViewTreeFamilyMask is 0, or the i-th sub-identifier of X is equal to the i-th sub-identifier of the value of vacmViewTreeFamilySubtree. If the value of this bit mask is M bits long and there are more than M sub-identifiers in the corresponding instance of vacmViewTreeFamilySubtree, then the bit mask is extended with 1's to be the required length. Note that when the value of this object is the zero-length string, this extension rule results in a mask of all-1's being used (i.e., no 'wild card'), and the family of view subtrees is the one view subtree uniquely identified by the corresponding instance of vacmViewTreeFamilySubtree. Note that masks of length greater than zero length do not need to be supported. In this case this object is made read-only. ")NEWLINEsnmpV3viewTreeType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("included", 1), ("excluded", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeType.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeType.setDescription('Indicates whether the corresponding instances of vacmViewTreeFamilySubtree and vacmViewTreeFamilyMask define a family of view subtrees which is included in or excluded from the MIB view. ')NEWLINEsnmpV3viewTreeStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 5), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeStatus.setDescription('The status of this conceptual row. The RowStatus TC [RFC2579] requires that this DESCRIPTION clause states under which circumstances other objects in this row can be modified: The value of this object has no effect on whether other objects in this conceptual row can be modified. ')NEWLINEsnmpV3CommunityTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1), )NEWLINEif mibBuilder.loadTexts: snmpV3CommunityTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityTable.setDescription('')NEWLINEsnmpV3CommunityEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3CommunityName"))NEWLINEif mibBuilder.loadTexts: snmpV3CommunityEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityEntry.setDescription('')NEWLINEsnmpV3CommunityName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3CommunityName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityName.setDescription('The unique index value of a row in this table.')NEWLINEsnmpV3CommunityPolicy = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3CommunityPolicy.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityPolicy.setDescription('A human readable string representing the corresponding value of snmpCommunityName in a Security Model independent format.')NEWLINEsnmpV3CommunityStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1, 1, 3), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3CommunityStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityStatus.setDescription('The status of this conceptual row in the snmpCommunityTable. An entry in this table is not qualified for activation until instances of all corresponding columns have been initialized, either through default values, or through Set operations. The snmpCommunityName and snmpCommunitySecurityName objects must be explicitly set. There is no restriction on setting columns in this table when the value of snmpCommunityStatus is active(1).')NEWLINEipv4snmpV3HostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1), )NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostTable.setDescription('')NEWLINEipv4snmpV3HostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4snmpV3HostAddress"))NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostEntry.setDescription('')NEWLINEipv4snmpV3HostAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1, 1), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostAddress.setDescription('This object contains a transport address. The format of this address depends on the value of the snmpTargetAddrTDomain object. And this object is unique identifier associated with this snmpNotifyEntry.')NEWLINEipv4snmpV3HostCommunityName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostCommunityName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostCommunityName.setDescription('The locally arbitrary.')NEWLINEipv4snmpV3HostVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("v1", 1), ("v2c", 2), ("v3NoAuthNoPriv", 3), ("v3AuthNoPriv", 4), ("v3AuthPriv", 5)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostVersion.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostVersion.setDescription('The Level of Security to be used when generating SNMP messages using this entry.')NEWLINEipv4snmpV3HostStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostStatus.setDescription('')NEWLINEsnmpV3HostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2), )NEWLINEif mibBuilder.loadTexts: snmpV3HostTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostTable.setDescription('')NEWLINEsnmpV3HostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3HostAddress"), (0, "DES-1210-28MEbx", "snmpV3IPType"))NEWLINEif mibBuilder.loadTexts: snmpV3HostEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostEntry.setDescription('')NEWLINEsnmpV3HostAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 1), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3HostAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostAddress.setDescription('This object contains a transport address. The format of this address depends on the value of the snmpTargetAddrTDomain object. And this object is unique identifier associated with this snmpNotifyEntry.')NEWLINEsnmpV3IPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3IPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3IPType.setDescription('Type of IP interface.')NEWLINEsnmpV3HostCommunityName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3HostCommunityName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostCommunityName.setDescription('The locally arbitrary.')NEWLINEsnmpV3HostVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("v1", 1), ("v2c", 2), ("v3NoAuthNoPriv", 3), ("v3AuthNoPriv", 4), ("v3AuthPriv", 5)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3HostVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostVersion.setDescription('The Level of Security to be used when generating SNMP messages using this entry.')NEWLINEsnmpV3HostInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 5), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3HostInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostInterfaceName.setDescription('Specifies the interface name when the syslogSrvIP is linklocal address.')NEWLINEsnmpV3HostStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 6), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3HostStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostStatus.setDescription('')NEWLINEsnmpV3TrapSNMPAuthentication = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapSNMPAuthentication.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapSNMPAuthentication.setDescription('This object is for enabling or disabling SNMP login fail event trap in the system.')NEWLINEsnmpV3TrapColdStart = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapColdStart.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapColdStart.setDescription('This object is for enabling or disabling devie Bootup event trap in the system.')NEWLINEsnmpV3TrapWarmStart = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapWarmStart.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapWarmStart.setDescription('This object is for enabling or disabling devie Bootup event trap in the system.')NEWLINEsnmpV3TrapLinkUpDown = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapLinkUpDown.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapLinkUpDown.setDescription('This object is for enabling or disabling Copper link up / link down event trap in the system.')NEWLINEsnmpV3TrapRSTPStateChange = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapRSTPStateChange.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapRSTPStateChange.setDescription('This object is for enabling or disabling RSTP topology change event trap in the system.')NEWLINEsnmpV3TrapFirmUpgrade = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapFirmUpgrade.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapFirmUpgrade.setDescription('This object is for enabling or disabling Firmware upgrade suess or fail event trap in the system.')NEWLINEsnmpV3TrapBPDUAttack = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("attackDetected", 2), ("attackCleared", 3), ("both", 4))).clone('none')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapBPDUAttack.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapBPDUAttack.setDescription('Used to configure trap settings for BPDU attack protection events.')NEWLINEsnmpV3TrapPortSecurity = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapPortSecurity.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapPortSecurity.setDescription('')NEWLINEsnmpV3TrapIMPBViolation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapIMPBViolation.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapIMPBViolation.setDescription('')NEWLINEsnmpV3TrapLBD = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapLBD.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapLBD.setDescription('')NEWLINEsnmpV3TrapDHCPServerScreening = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapDHCPServerScreening.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapDHCPServerScreening.setDescription('')NEWLINEsnmpV3TrapDuplicateIPDetected = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapDuplicateIPDetected.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapDuplicateIPDetected.setDescription('This object is for enabling or disabling send gratuitous trap when IP address conflicted in the network.')NEWLINEsnmpV3CommunityEncryption = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3CommunityEncryption.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityEncryption.setDescription('This object is for enabling or disabling community encryption.')NEWLINEtraps = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0))NEWLINEsnmpTrapSNMPAuthentication = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 1))NEWLINEif mibBuilder.loadTexts: snmpTrapSNMPAuthentication.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapSNMPAuthentication.setDescription('SnmpV3TrapSNMPAuthentication.')NEWLINEsnmpTrapColdStart = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 2))NEWLINEif mibBuilder.loadTexts: snmpTrapColdStart.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapColdStart.setDescription('SnmpV3TrapColdStart.')NEWLINEsnmpTrapWarmStart = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 3))NEWLINEif mibBuilder.loadTexts: snmpTrapWarmStart.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapWarmStart.setDescription('SnmpV3TrapWarmStart.')NEWLINEsnmpTrapCopperLinkUpDown = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 4))NEWLINEif mibBuilder.loadTexts: snmpTrapCopperLinkUpDown.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapCopperLinkUpDown.setDescription('SnmpV3TrapCopperLinkUpDown.')NEWLINEsnmpTrapRSTPStateChange = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 5))NEWLINEif mibBuilder.loadTexts: snmpTrapRSTPStateChange.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapRSTPStateChange.setDescription('SnmpV3TrapRSTPStateChange.')NEWLINEsnmpTrapFirmUpgrade = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 6))NEWLINEif mibBuilder.loadTexts: snmpTrapFirmUpgrade.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapFirmUpgrade.setDescription('SnmpV3TrapFirmUpgrade.')NEWLINEsnmpTrapBPDUAttack = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 11))NEWLINEif mibBuilder.loadTexts: snmpTrapBPDUAttack.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapBPDUAttack.setDescription('SnmpV3TrapBPDUAttack.')NEWLINEsnmpTrapPortSecurity = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 12))NEWLINEif mibBuilder.loadTexts: snmpTrapPortSecurity.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapPortSecurity.setDescription('SnmpV3TrapPortSecurity.')NEWLINEsnmpTrapIMPBv2 = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 13))NEWLINEif mibBuilder.loadTexts: snmpTrapIMPBv2.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapIMPBv2.setDescription('SnmpV3TrapIMPBv2.')NEWLINEsnmpTrapLBD = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 14))NEWLINEif mibBuilder.loadTexts: snmpTrapLBD.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapLBD.setDescription('SnmpV3TrapLBD.')NEWLINEsnmpTrapDHCPScreen = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 15))NEWLINEif mibBuilder.loadTexts: snmpTrapDHCPScreen.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapDHCPScreen.setDescription('SnmpV3TrapDHCPScreen.')NEWLINEsnmpTrapGratuitousArp = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 16))NEWLINEif mibBuilder.loadTexts: snmpTrapGratuitousArp.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapGratuitousArp.setDescription('SnmpV3TrapGratuitousArp.')NEWLINEmacNotificatiotn = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 17))NEWLINEif mibBuilder.loadTexts: macNotificatiotn.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotificatiotn.setDescription(' This trap indicates the MAC address variations in the address table . ')NEWLINEduplicateIP = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 21))NEWLINEif mibBuilder.loadTexts: duplicateIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: duplicateIP.setDescription(' duplicateIP . ')NEWLINEtrafficControl = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 22))NEWLINEif mibBuilder.loadTexts: trafficControl.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficControl.setDescription(' trafficControl. ')NEWLINEtopologyChange = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 23))NEWLINEif mibBuilder.loadTexts: topologyChange.setStatus('current')NEWLINEif mibBuilder.loadTexts: topologyChange.setDescription(' topologyChange. ')NEWLINEnewRootBrgaddress = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 24))NEWLINEif mibBuilder.loadTexts: newRootBrgaddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: newRootBrgaddress.setDescription(' newRootBrgaddress. ')NEWLINEnewRootOlddesignatedroot = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 25))NEWLINEif mibBuilder.loadTexts: newRootOlddesignatedroot.setStatus('current')NEWLINEif mibBuilder.loadTexts: newRootOlddesignatedroot.setDescription(' newRootOlddesignatedroot. ')NEWLINEnewRootMSTibridgeregionalroot = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 26))NEWLINEif mibBuilder.loadTexts: newRootMSTibridgeregionalroot.setStatus('current')NEWLINEif mibBuilder.loadTexts: newRootMSTibridgeregionalroot.setDescription(' topologyChange. ')NEWLINEsyslogSettingGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 1))NEWLINEsyslogEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogEnable.setDescription('This object is for enabling or disabling syslog alert features in the system and the syslog will save to flash or send to remote syslog server. System Logs record and manage events, as well as report errors and informational messages.')NEWLINEsyslogSaveMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("onDemand", 0), ("timeInterval", 1), ("logTrigger", 2))).clone('logTrigger')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogSaveMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogSaveMode.setDescription('This object is for choosing the method to save syslog into flash.')NEWLINEsyslogSaveMinutes = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(30)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogSaveMinutes.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogSaveMinutes.setDescription("When savemode is time interval, it's used to set the interval minutes of system save syslog to flash.")NEWLINEipv4syslogServerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2))NEWLINEipv4syslogServTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1), )NEWLINEif mibBuilder.loadTexts: ipv4syslogServTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServTable.setDescription('The table of syslog remote server.')NEWLINEipv4syslogServEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4syslogServIndex"))NEWLINEif mibBuilder.loadTexts: ipv4syslogServEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServEntry.setDescription('The list of syslog remote server entry.')NEWLINEipv4syslogServIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4syslogServIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServIndex.setDescription('The index of syslog remote server.')NEWLINEipv4syslogServAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 2), IpAddress()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServAddr.setDescription('The IP Address of syslog remote server.')NEWLINEipv4syslogServSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4, 6, 7))).clone(namedValues=NamedValues(("warning", 4), ("information", 6), ("all", 7)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServSeverity.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServSeverity.setDescription('Specifies the log level option to be set for a specific server.')NEWLINEipv4syslogServFacility = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(128, 136, 144, 152, 160, 168, 176, 184))).clone(namedValues=NamedValues(("local0", 128), ("local1", 136), ("local2", 144), ("local3", 152), ("local4", 160), ("local5", 168), ("local6", 176), ("local7", 184))).clone('local0')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServFacility.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServFacility.setDescription('The Syslog standard facilities. The facility to be used when sending Syslog messages to this server.')NEWLINEipv4syslogServUDPport = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(514, 514), ValueRangeConstraint(6000, 65535), ))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServUDPport.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServUDPport.setDescription('The value is for setting UDP Port.')NEWLINEipv4syslogServSrvStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServSrvStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServSrvStatus.setDescription('The status for this server. If enable, system will send message to this server.')NEWLINEipv4syslogServSrvRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 7), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4syslogServSrvRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServSrvRowStatus.setDescription('Row status of this server entry.')NEWLINEsyslogServerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3))NEWLINEsyslogServTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1), )NEWLINEif mibBuilder.loadTexts: syslogServTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServTable.setDescription('The table of syslog remote server.')NEWLINEsyslogServEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "syslogServIndex"))NEWLINEif mibBuilder.loadTexts: syslogServEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServEntry.setDescription('The list of syslog remote server entry.')NEWLINEsyslogServIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: syslogServIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServIndex.setDescription('The index of syslog remote server.')NEWLINEsyslogServAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipv4", 1), ("ipv6", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServAddrType.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServAddrType.setDescription('Specifies the Address type of server.Address type shall be ipv4 or ipv6.')NEWLINEsyslogServAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 3), Ipv6Address()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServAddr.setDescription('Specifies the ServerIP to which the syslog shall be forwarded.')NEWLINEsyslogServInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 4), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServInterfaceName.setDescription('Specifies the interface name when the syslogServInterfaceName is linklocal address.')NEWLINEsyslogServSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4, 6, 7))).clone(namedValues=NamedValues(("warning", 4), ("information", 6), ("all", 7)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServSeverity.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServSeverity.setDescription('Specifies the log level option to be set for a specific server.')NEWLINEsyslogServFacility = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(128, 136, 144, 152, 160, 168, 176, 184))).clone(namedValues=NamedValues(("local0", 128), ("local1", 136), ("local2", 144), ("local3", 152), ("local4", 160), ("local5", 168), ("local6", 176), ("local7", 184))).clone('local0')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServFacility.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServFacility.setDescription('The Syslog standard facilities. The facility to be used when sending Syslog messages to this server.')NEWLINEsyslogServUDPport = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(514, 514), ValueRangeConstraint(6000, 65535), ))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServUDPport.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServUDPport.setDescription('The value is for setting UDP Port.')NEWLINEsyslogServSrvStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogServSrvStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServSrvStatus.setDescription('The status for this server. If enable, system will send message to this server.')NEWLINEsyslogServSrvRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 9), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogServSrvRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServSrvRowStatus.setDescription('Row status of this server entry.')NEWLINEsysLBDStateEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDStateEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDStateEnable.setDescription('Enable/Disable Loopback detection function. The Loopback Detection function is used to detect the loop created by a specific port while Spanning Tree Protocol (STP) is not enabled in the network, especially when the down links are hubs or unmanaged switchs.The Switch will automatically shutdown the port and sends a log to the administrator.')NEWLINEsysLBDMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("port", 1), ("vlan", 2))).clone('port')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDMode.setDescription('Loopback detection function mode.')NEWLINEsysLBDInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32767)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDInterval.setDescription('Set a Loop detection Interval between 1 and 32767 seconds. The default is 2 seconds. This time interval to be used at counting time seconds to resend the CTP packet automatically.')NEWLINEsysLBDRecoverTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(60, 1000000), )).clone(60)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDRecoverTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDRecoverTime.setDescription('This time interval to be used at counting time seconds to recover the disabled port automatically. The Loop Detection Recover Time can be set at 0 seconds, or 60 to 1000000 seconds. Entering 0 will disable the Loop Detection Recover Time. The default is 60 seconds.')NEWLINEsysLBDCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5), )NEWLINEif mibBuilder.loadTexts: sysLBDCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDCtrlTable.setDescription('A table to control Loopback detection features either for the entire switch or for each interface in the switch.')NEWLINEsysLBDCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysLBDCtrlIndex"))NEWLINEif mibBuilder.loadTexts: sysLBDCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDCtrlEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEsysLBDCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysLBDCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDCtrlIndex.setDescription('The interface index of the port for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEsysLBDPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDPortStatus.setDescription('Provides control to per port enable or disable the loopback detection function. Default is disabled.')NEWLINEsysLBDPortLoopStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("normal", 1), ("loop", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysLBDPortLoopStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDPortLoopStatus.setDescription('The loop status for this port.')NEWLINEsysLBDVlanLoopTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 6), )NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopTable.setDescription('A table to display Loopback detection features by vlan mode .')NEWLINEsysLBDVlanLoopEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 6, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysLBDVlanLoopIndex"))NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEsysLBDVlanLoopIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopIndex.setDescription('Display port lists loop status by vlan.')NEWLINEsysLBDVlanLoopPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 6, 1, 2), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopPorts.setDescription('Display port lists loop status by vlan.')NEWLINEsysMirrorStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMirrorStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMirrorStatus.setDescription('Enable/Disable Port Mirroring function. Default is disabled. Port Mirroring is a method of monitoring network traffic that forwards a copy of each incoming and/or outgoing packet from one port of the Switch to another port where the packet can be studied.')NEWLINEsysMirrorTargetPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18, 2), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMirrorTargetPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMirrorTargetPort.setDescription('Specifies the port to which the mirrored traffic in the system is to be copied.')NEWLINEsysMirrorCtrlIngressMirroring = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMirrorCtrlIngressMirroring.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMirrorCtrlIngressMirroring.setDescription('Provides control to enable or disable mirroring of ingress traffic over this interface to the mirrored-to port.')NEWLINEsysMirrorCtrlEgressMirroring = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMirrorCtrlEgressMirroring.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMirrorCtrlEgressMirroring.setDescription('Provides control to enable or disable mirroring of egress traffic over this interface to the mirrored-to port.')NEWLINEsysTrapIP = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 1), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapIP.setDescription("The smart console utility's IP address is used to recive trap events.")NEWLINEsysTrapSystemEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("deviceBootUp", 1), ("illegalLogin", 2), ("both", 3))).clone('none')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapSystemEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapSystemEvent.setDescription('Enable/Disable system trap events in the switch system.')NEWLINEsysTrapFiberPortEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapFiberPortEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapFiberPortEvent.setDescription('Enable/Disable fiber port trap event in the system.')NEWLINEsysTrapTwistedPortEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapTwistedPortEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapTwistedPortEvent.setDescription('Enable/Disable twisted port trap event in the system.')NEWLINEsysTrapStateChangeEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapStateChangeEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapStateChangeEvent.setDescription('Enable/Disable RSTP state change trap event in the system.')NEWLINEsysTrapFirmUpgradeEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapFirmUpgradeEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapFirmUpgradeEvent.setDescription('Enable/Disable firmware upgrading trap event in the system.')NEWLINEsysTrapStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapStatus.setDescription('Enable/Disable trap event in the system.')NEWLINEsysTrapPortSecurity = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapPortSecurity.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapPortSecurity.setDescription('')NEWLINEsysTrapIMPBViolation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapIMPBViolation.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapIMPBViolation.setDescription('')NEWLINEsysTrapLBD = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapLBD.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapLBD.setDescription('')NEWLINEsysTrapDHCPServerScreening = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapDHCPServerScreening.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapDHCPServerScreening.setDescription('')NEWLINEsysTrapDuplicateIPDetected = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapDuplicateIPDetected.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapDuplicateIPDetected.setDescription('This object is for enabling or disabling send gratuitous trap when IP address conflicted in the network.')NEWLINEipv4sysSNTPTimeSeconds = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 1), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPTimeSeconds.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPTimeSeconds.setDescription('This object is for setting the system time in seconds from Epoch (00:00:00 UTC, January 1, 2009). Notice : input value must larger than 1230768000 (00:00:00 UTC, January 1, 2009) and smaller than 2145916799 (23:59:59 UTC, December 31, 2037).')NEWLINEipv4sysSNTPFirstServer = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPFirstServer.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPFirstServer.setDescription("SNTP First Server's IP Address")NEWLINEipv4sysSNTPSecondServer = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 3), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPSecondServer.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPSecondServer.setDescription("SNTP Second Server's IP Address")NEWLINEipv4sysSNTPPollInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 4), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPPollInterval.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPPollInterval.setDescription('SNTP Poll Interval In Seconds (30-99999) ')NEWLINEipv4sysSNTPState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("sntp", 1), ("local", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPState.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPState.setDescription('Enable/Disable SNTP function in the system.')NEWLINEipv4sysSNTPDSTOffset = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(30, 60, 90, 120))).clone(namedValues=NamedValues(("offset30min", 30), ("offset60min", 60), ("offset90min", 90), ("offset120min", 120)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTOffset.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTOffset.setDescription('This object is for Daylight Saving Time Offset In (30/60/90/120) Minutes.')NEWLINEipv4sysSNTPGMTMinutes = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 7), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPGMTMinutes.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPGMTMinutes.setDescription('Specifies the Time Zone Offset from GMT in +/- Minutes. (+780 ~ -720)')NEWLINEipv4sysSNTPDSTStartMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 8), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartMon.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartMon.setDescription('The start month of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTStartDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 9), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartDay.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartDay.setDescription('The start day of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTStartHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 10), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartHour.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartHour.setDescription('The start hour of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTStartMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 11), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartMin.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartMin.setDescription('The start minute of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTEndMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 12), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndMon.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndMon.setDescription('The end month of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTEndDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 13), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndDay.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndDay.setDescription('The end day of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTEndHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 14), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndHour.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndHour.setDescription('The end hour of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTEndMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 15), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndMin.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndMin.setDescription('The end minute of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("annual", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTState.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTState.setDescription('This object is for Annual(1) or Disabled(2) DST state in the system.')NEWLINEsysSNTPServerTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17))NEWLINEsysSNTPTimeSeconds = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 1), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPTimeSeconds.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPTimeSeconds.setDescription('This object is for setting the system time in seconds from Epoch (00:00:00 UTC, January 1, 2009). Notice : input value must larger than 1230768000 (00:00:00 UTC, January 1, 2009) and smaller than 2145916799 (23:59:59 UTC, December 31, 2037).')NEWLINEsysSNTPFirstServer = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 2), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPFirstServer.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPFirstServer.setDescription("SNTP First Server's IPv6 Address")NEWLINEsysSNTPFirstType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPFirstType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPFirstType.setDescription("SNTP First Server's IPv6 Address type.")NEWLINEsysSNTPFirstInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPFirstInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPFirstInterfaceName.setDescription('Specifies the interface name when the sysSNTPFirstServer is linklocal address.')NEWLINEsysSNTPSecondServer = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 5), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPSecondServer.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPSecondServer.setDescription("SNTP Second Server's IPv6 Address")NEWLINEsysSNTPSecondType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPSecondType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPSecondType.setDescription("SNTP First Server's IPv6 Address type.")NEWLINEsysSNTPSecondInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 7), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPSecondInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPSecondInterfaceName.setDescription('Specifies the interface name when the sysSNTPSecondServer is linklocal address.')NEWLINEsysSNTPPollInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 8), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPPollInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPPollInterval.setDescription('SNTP Poll Interval In Seconds (30-99999) ')NEWLINEsysSNTPState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("sntp", 1), ("local", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPState.setDescription('Enable/Disable SNTP function in the system.')NEWLINEsysSNTPDSTOffset = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(30, 60, 90, 120))).clone(namedValues=NamedValues(("offset30min", 30), ("offset60min", 60), ("offset90min", 90), ("offset120min", 120)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTOffset.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTOffset.setDescription('This object is for Daylight Saving Time Offset In (30/60/90/120) Minutes.')NEWLINEsysSNTPGMTMinutes = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 11), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPGMTMinutes.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPGMTMinutes.setDescription('Specifies the Time Zone Offset from GMT in +/- Minutes. (+780 ~ -720)')NEWLINEsysSNTPDSTStartMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 12), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartMon.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartMon.setDescription('The start month of Daylight Saving Time.')NEWLINEsysSNTPDSTStartDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 13), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartDay.setDescription('The start day of Daylight Saving Time.')NEWLINEsysSNTPDSTStartHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 14), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartHour.setDescription('The start hour of Daylight Saving Time.')NEWLINEsysSNTPDSTStartMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 15), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartMin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartMin.setDescription('The start minute of Daylight Saving Time.')NEWLINEsysSNTPDSTEndMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 16), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndMon.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndMon.setDescription('The end month of Daylight Saving Time.')NEWLINEsysSNTPDSTEndDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 17), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndDay.setDescription('The end day of Daylight Saving Time.')NEWLINEsysSNTPDSTEndHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 18), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndHour.setDescription('The end hour of Daylight Saving Time.')NEWLINEsysSNTPDSTEndMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 19), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndMin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndMin.setDescription('The end minute of Daylight Saving Time.')NEWLINEsysSNTPDSTState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTState.setDescription('This object is for Enabled(1) or Disabled(2) DST state in the system.')NEWLINEsysSNTPDSTMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("annual", 1), ("repeating", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTMethod.setDescription('This object is for Annual(1) or Repeating(2) DST method in the system.')NEWLINEsysSNTPDSTRepeatStartMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 31), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartMon.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartMon.setDescription('The start month of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatStartWeek = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("last", 0), ("first", 1), ("second", 2), ("third", 3), ("fourth", 4), ("fifth", 5)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartWeek.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartWeek.setDescription('The start week of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatStartWeekDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 33), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("sun", 0), ("mon", 1), ("tue", 2), ("wed", 3), ("thu", 4), ("fri", 5), ("sat", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartWeekDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartWeekDay.setDescription('The start weekday of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatStartHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 34), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartHour.setDescription('The start hour of Daylight Saving Time in Repeating mode..')NEWLINEsysSNTPDSTRepeatStartMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 35), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartMin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartMin.setDescription('The start minute of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatEndMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 36), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndMon.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndMon.setDescription('The end month of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatEndWeek = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 37), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("last", 0), ("first", 1), ("second", 2), ("third", 3), ("fourth", 4), ("fifth", 5)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndWeek.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndWeek.setDescription('The end week of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatEndWeekDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 38), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("sun", 0), ("mon", 1), ("tue", 2), ("wed", 3), ("thu", 4), ("fri", 5), ("sat", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndWeekDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndWeekDay.setDescription('The end weekday of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatEndHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 39), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndHour.setDescription('The end hour of Daylight Saving Time in Repeating mode..')NEWLINEsysSNTPDSTRepeatEndMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 40), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndMin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndMin.setDescription('The end minute of Daylight Saving Time in Repeating mode.')NEWLINElimitIpMulticastProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1), )NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileTable.setDescription('A list of the limit ip multicast Profile Table.')NEWLINElimitIpMulticastProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "limitIpMulticastIPType"), (0, "DES-1210-28MEbx", "limitIpMulticastProfileID"))NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileEntry.setDescription('A limit ip multicast entry maintain by the start IP Address, end ip address, profile id.')NEWLINElimitIpMulticastIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipv4", 1), ("ipv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastIPType.setDescription('Indicate the IP type of profile.')NEWLINElimitIpMulticastProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 24))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileID.setDescription('The ProfileID of the limit ip multicast profile entry.')NEWLINElimitIpMulticastProfileName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileName.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileName.setDescription('The ProfileName of the limit ip multicast profile entry.')NEWLINElimitIpMulticastProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1, 4), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileStatus.setDescription('The status of an entry in the limit ip multicast profile Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINElimitIpMulticastEntryTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2), )NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryTable.setDescription('A list of the limit ip multicast entry Table.')NEWLINElimitIpMulticastEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "limitIpMulticastEntryIPType"), (0, "DES-1210-28MEbx", "limitIpMulticastEntryProfileID"), (0, "DES-1210-28MEbx", "limitIpMulticaststartIpAddr"), (0, "DES-1210-28MEbx", "limitIpMulticastendIpAddr"))NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntry.setDescription('A limit ip multicast entry maintain by the start IP Address, end ip address, profile id.')NEWLINElimitIpMulticastEntryIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipv4", 1), ("ipv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryIPType.setDescription('Indicate the IP type of entry.')NEWLINElimitIpMulticastEntryProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 24))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryProfileID.setDescription('The ProfileID of the limit ip multicast entry.')NEWLINElimitIpMulticaststartIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticaststartIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticaststartIpAddr.setDescription('The limit ip multicast IP address is used to set start ip')NEWLINElimitIpMulticastendIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastendIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastendIpAddr.setDescription('The limit ip multicast IP address is used to set end ip')NEWLINElimitIpMulticastStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 5), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastStatus.setDescription('The status of an entry in the limit ip multicast entry Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINElimitIpMulticastPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3), )NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortTable.setDescription('A list of the limit ip multicast Port entry Table.')NEWLINElimitIpMulticastPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "limitIpMulticastPortIPType"), (0, "DES-1210-28MEbx", "limitIpMulticastPortID"))NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortEntry.setDescription('A limit ip multicast entry maintain by the Port Index.')NEWLINElimitIpMulticastPortIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipv4", 1), ("ipv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortIPType.setDescription('Indicate the IP type of entry.')NEWLINElimitIpMulticastPortID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortID.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortID.setDescription('The Port Index of the limit ip multicast port entry. For all machines give maximum port number.')NEWLINElimitIpMulticastPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("permit", 1), ("deny", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortState.setDescription('The limit ip multicast port state')NEWLINElimitIpMulticastPortProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortProfileID.setDescription('The limit ip multicast port mapping profileID list.')NEWLINElimitIpMulticastPortMaxGrp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 256))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortMaxGrp.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortMaxGrp.setDescription('The limit ip multicast per-port max group.')NEWLINEguestVlanName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 24, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: guestVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: guestVlanName.setDescription('The VLAN name of guest VLAN.')NEWLINEguestVlanPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 24, 2), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: guestVlanPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: guestVlanPort.setDescription('This object indicates the guest VLAN port members of this device.')NEWLINEguestVlanDelState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 24, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("none", 1), ("start", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: guestVlanDelState.setStatus('current')NEWLINEif mibBuilder.loadTexts: guestVlanDelState.setDescription('Used to delete the guest VLAN.')NEWLINEprotocolGroupNameTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 1), )NEWLINEif mibBuilder.loadTexts: protocolGroupNameTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupNameTable.setDescription('A table to control protocol group name features of the device.')NEWLINEprotocolGroupNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "protocolGroupGID"))NEWLINEif mibBuilder.loadTexts: protocolGroupNameEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupNameEntry.setDescription('An entry appears in protocol group name table for each interface in the system.')NEWLINEprotocolGroupGID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolGroupGID.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupGID.setDescription('The group ID of protocol group name table.')NEWLINEprotocolGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: protocolGroupName.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupName.setDescription('The group name of protocol group name table.')NEWLINEprotocolGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2), )NEWLINEif mibBuilder.loadTexts: protocolGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupTable.setDescription('A table to control protocol group features of the device.')NEWLINEprotocolGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "protocolGroupId"), (0, "DES-1210-28MEbx", "protocolGroupFrameType"), (0, "DES-1210-28MEbx", "protocolGroupProtocolValue"))NEWLINEif mibBuilder.loadTexts: protocolGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupEntry.setDescription('An entry appears in protocol group table for each interface in the system.')NEWLINEprotocolGroupId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolGroupId.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupId.setDescription('The group ID of protocol group table.')NEWLINEprotocolGroupFrameType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ethernet", 1), ("ieee8023-snap", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolGroupFrameType.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupFrameType.setDescription('The frame type of protocol group table.')NEWLINEprotocolGroupProtocolValue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolGroupProtocolValue.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupProtocolValue.setDescription('The protocol value of protocol group table.')NEWLINEprotocolGroupRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: protocolGroupRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupRowStatus.setDescription('The row status of protocol group table.')NEWLINEprotocolVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3), )NEWLINEif mibBuilder.loadTexts: protocolVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanTable.setDescription('A table to control protocol vlan features of the device.')NEWLINEprotocolVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "protocolVlanPort"), (0, "DES-1210-28MEbx", "protocolVlanVID"), (0, "DES-1210-28MEbx", "protocolVlanGroupID"))NEWLINEif mibBuilder.loadTexts: protocolVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanEntry.setDescription('An entry appears in protocol vlan table for each interface in the system.')NEWLINEprotocolVlanPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolVlanPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanPort.setDescription('The interface number of protocol vlan table.')NEWLINEprotocolVlanVID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolVlanVID.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanVID.setDescription('The vlan ID of protocol vlan table.')NEWLINEprotocolVlanGroupID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolVlanGroupID.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanGroupID.setDescription('The group ID of protocol vlan table.')NEWLINEprotocolVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: protocolVlanRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanRowStatus.setDescription('The row status of protocol vlan table.')NEWLINEmacNotifyState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyState.setDescription('This object can enabled or disabled MAC Notification.')NEWLINEmacNotifyInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macNotifyInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyInterval.setDescription('This object indicates the time interval in second for trigger the MAC notify message. ')NEWLINEmacNotifyHistorySize = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 500))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macNotifyHistorySize.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyHistorySize.setDescription('This object indicates the history size of variation MAC in address table. The default value is 1 .')NEWLINEmacNotifyCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 4), )NEWLINEif mibBuilder.loadTexts: macNotifyCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyCtrlTable.setDescription('A table to control Loopback detection features either for the entire switch or for each interface in the switch.')NEWLINEmacNotifyCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "macNotifyCtrlIndex"))NEWLINEif mibBuilder.loadTexts: macNotifyCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyCtrlEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEmacNotifyCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: macNotifyCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyCtrlIndex.setDescription('The interface index of the port for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEmacNotifyPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macNotifyPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyPortStatus.setDescription('Provides control to per port enable or disable the loopback detection function. Default is disabled.')NEWLINEmacNotifyInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 5))NEWLINEmacNotifyInfoDiscription = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 5, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1024))).setMaxAccess("accessiblefornotify")NEWLINEif mibBuilder.loadTexts: macNotifyInfoDiscription.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyInfoDiscription.setDescription('This object indicates the information for the device MAC address changes. And the detailed information include: Operation Code + MAC address + Box ID + Port Number + Zero... Operation Code: 1, 2 and 3 1 means learned a new MAC address 2 means deleted an old MAC address. 3 means station movement. Box ID: The switch box ID, for standalone device, it always 1. Port Number: The port number learned or deleted for the box. Zero: Used to separate each message (Operate Code + MAC address + Box ID + Port Number).')NEWLINEsysBPDUAttackStateEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackStateEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackStateEnable.setDescription('Use this to enable BPDU attack protection. The BPDU Attack Protection function and Spanning Tree Protocol for ports are mutually exclusive. When the STP function is enabled on a particular port, BPDU Attack Protection cannot be enabled.')NEWLINEsysBPDUAttackRecoverTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(60, 1000000), )).clone(60)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackRecoverTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackRecoverTime.setDescription('When a port enters under attack state, it can be disabled or blocked based on the configuration. The state can be recovered manually or by the auto recovery mechanism. This command is used to configure the auto-recovery timer. To manually recover the port, the user needs to disable and re-enable the port.')NEWLINEsysBPDUAttackCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3), )NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlTable.setDescription('A table to control BPDU Attack features either for the entire switch or for each interface in the switch.')NEWLINEsysBPDUAttackCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysBPDUAttackCtrlIndex"))NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEsysBPDUAttackCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlIndex.setDescription('The interface index of the port for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEsysBPDUAttackPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortState.setDescription('Used to configure the BPDU Attack Protection state of a port. The default state is disable.')NEWLINEsysBPDUAttackPortMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("drop", 1), ("block", 2), ("shutdown", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortMode.setDescription('Used to configure the BPDU Attack Protection mode of a port.')NEWLINEsysBPDUAttackPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("normal", 1), ("underAttack", 2))).clone('normal')).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortStatus.setDescription('Use this to view per port BPDU attack protection status.')NEWLINEsysBPDUAttackLog = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("attackDetected", 2), ("attackCleared", 3), ("both", 4))).clone('none')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackLog.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackLog.setDescription('Used to configure log settings for BPDU attack protection events.')NEWLINEvlanTrunkSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1))NEWLINEvlanTrunkGlobalStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanTrunkGlobalStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkGlobalStatus.setDescription('This indicates the global state of the VLAN trunking feature of the device.')NEWLINEvlanTrunkTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 2), )NEWLINEif mibBuilder.loadTexts: vlanTrunkTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkTable.setDescription('This table is used to manage the VLAN trunking feature of the device.')NEWLINEvlanTrunkEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "vlanTrunkIfIndex"))NEWLINEif mibBuilder.loadTexts: vlanTrunkEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkEntry.setDescription('There is one entry in this table for each created port-channel port.')NEWLINEvlanTrunkIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 2, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: vlanTrunkIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkIfIndex.setDescription('The index of the port. ')NEWLINEvlanTrunkState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanTrunkState.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkState.setDescription('Sets the VLAN trunk status as enabled or disabled.')NEWLINEqinqSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1))NEWLINEqinqVLANTranslation = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2))NEWLINEqinqGlobalStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqGlobalStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqGlobalStatus.setDescription('This object is used to enable/disable the Q-in-Q status.')NEWLINEqinqTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2), )NEWLINEif mibBuilder.loadTexts: qinqTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqTable.setDescription('A table that contains Q-in-Q VLAN mode information about each port.')NEWLINEqinqEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qinqIfIndex"))NEWLINEif mibBuilder.loadTexts: qinqEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqEntry.setDescription('A list of Q-in-Q VLAN mode information for each port.')NEWLINEqinqIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qinqIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqIfIndex.setDescription('The index of the port. ')NEWLINEqinqRoleState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("nni", 1), ("uni", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqRoleState.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqRoleState.setDescription('Sets the QinQ Role as NNI or UNI.')NEWLINEqinqOuterTPID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 3), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqOuterTPID.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqOuterTPID.setDescription('Sets the QinQ Outer TPID value.')NEWLINEqinqTrustCVIDState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqTrustCVIDState.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqTrustCVIDState.setDescription('Sets the QinQ Trust CVID state as enabled or disabled.')NEWLINEqinqVLANTranslationState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqVLANTranslationState.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVLANTranslationState.setDescription('Sets the QinQ VLANTranslation state as enabled or disabled.')NEWLINEqinqVlanTranslationCVIDTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1), )NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDTable.setDescription("A table that contains VLAN translation information applied in enabling port's swQinQPortVlanTranslation, swQinQPortTrustCVID and QinQ.")NEWLINEqinqVlanTranslationCVIDEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qinqVlanTranslationCVID"))NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDEntry.setDescription("A list of VLAN translation information applied in enabling a port's swQinQPortVlanTranslation, swQinQPortTrustCVID and QinQ.")NEWLINEqinqVlanTranslationCVID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1, 1), Unsigned32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVID.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVID.setDescription('The customer VLAN identifier in a C-TAG.')NEWLINEqinqVlanTranslationSVID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1, 2), Unsigned32()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationSVID.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationSVID.setDescription('A VLAN identifier conveyed in an S-TAG.')NEWLINEqinqVlanTranslationSVIDOperation = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("add", 1), ("replace", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationSVIDOperation.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationSVIDOperation.setDescription("The 'add' action indicates to add a tag for the assigned SP-VLAN before the C-VLAN tag. If there is S-TAG in the packet, this rule will not take effect. The 'replace' action indicates to replace the C-VLAN in the tag by the SP-VLAN. If there is no C-TAG in the packet, this rule will not take effect.")NEWLINEqinqVlanTranslationCVIDRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEeoamSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1))NEWLINEeoamLinkMonitor = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2))NEWLINEeoamTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2), )NEWLINEif mibBuilder.loadTexts: eoamTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamTable.setDescription('A table that contains EOAM mode information about each port.')NEWLINEeoamEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "eoamIfIndex"))NEWLINEif mibBuilder.loadTexts: eoamEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamEntry.setDescription('A list of EOAM mode information for each port.')NEWLINEeoamIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: eoamIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamIfIndex.setDescription('The index of the port. ')NEWLINEeoamState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamState.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamState.setDescription('Sets the EOAM state enabled or disabled.')NEWLINEeoamMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("passive", 1), ("active", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamMode.setDescription('Sets the EOAM mode as active or passive.')NEWLINEeoamReceivedRemoteLoopback = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ignore", 1), ("process", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamReceivedRemoteLoopback.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamReceivedRemoteLoopback.setDescription('Sets the EOAM received or ignore remote loopback packets.')NEWLINEeoamRemoteLoopback = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("noLoopBack", 1), ("startLoopBack", 2), ("remoteLoopBack", 3), ("stopLoopBack", 4), ("localLoopBack", 5), ("unknownLoopBack", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamRemoteLoopback.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamRemoteLoopback.setDescription('Sets the EOAM remote loopback start or stop.')NEWLINEeoamDyingGaspEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamDyingGaspEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamDyingGaspEnable.setDescription('Sets the EOAM dying gasp state enabled or disabled.')NEWLINEeoamCriticalEventEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamCriticalEventEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamCriticalEventEnable.setDescription('Sets the EOAM critical event state enabled or disabled.')NEWLINEeoamLinkMonitorTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1), )NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorTable.setDescription('A table that contains EOAM link monitor information about each port.')NEWLINEeoamLinkMonitorEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "eoamLinkMonitorIfIndex"))NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorEntry.setDescription('A list of EOAM link monitor information for each port.')NEWLINEeoamLinkMonitorIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorIfIndex.setDescription('The index of the port. ')NEWLINEerrorSymbolNotifyState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorSymbolNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorSymbolNotifyState.setDescription('Sets the EOAM error symbol notify state enabled or disabled.')NEWLINEerrorSymbolThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 3), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorSymbolThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorSymbolThreshold.setDescription('Sets the EOAM error symbol threshold.')NEWLINEerrorSymbolWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 4), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorSymbolWindow.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorSymbolWindow.setDescription('Sets the EOAM error symbol window.')NEWLINEerrorFrameNotifyState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameNotifyState.setDescription('Sets the EOAM error frame notify state enabled or disabled.')NEWLINEerrorFrameThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 6), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameThreshold.setDescription('Sets the EOAM error frame threshold.')NEWLINEerrorFrameWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 7), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameWindow.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameWindow.setDescription('Sets the EOAM error symbol window.')NEWLINEerrorFrameSecondsNotifyState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameSecondsNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameSecondsNotifyState.setDescription('Sets the EOAM error symbol notify state enabled or disabled.')NEWLINEerrorFrameSecondsThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 9), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameSecondsThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameSecondsThreshold.setDescription('Sets the EOAM error symbol threshold.')NEWLINEerrorFrameSecondsWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 10), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameSecondsWindow.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameSecondsWindow.setDescription('Sets the EOAM error symbol window.')NEWLINEerrorFramePeriodNotifyState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFramePeriodNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFramePeriodNotifyState.setDescription('Sets the EOAM error symbol notify state enabled or disabled.')NEWLINEerrorFramePeriodThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 12), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFramePeriodThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFramePeriodThreshold.setDescription('Sets the EOAM error symbol threshold.')NEWLINEerrorFramePeriodWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 13), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFramePeriodWindow.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFramePeriodWindow.setDescription('Sets the EOAM error symbol window.')NEWLINEduldSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1))NEWLINEduldTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1), )NEWLINEif mibBuilder.loadTexts: duldTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldTable.setDescription('A table that contains DULD mode information about each port.')NEWLINEduldEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "duldIfIndex"))NEWLINEif mibBuilder.loadTexts: duldEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldEntry.setDescription('A list of DULD mode information for each port.')NEWLINEduldIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: duldIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldIfIndex.setDescription('The index of the port. ')NEWLINEduldState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: duldState.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldState.setDescription('Sets the DULD admin state enabled or disabled.')NEWLINEduldOperState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: duldOperState.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldOperState.setDescription('Gets the DULD Oper state enabled or disabled.')NEWLINEduldMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("shutdown", 1), ("normal", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: duldMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldMode.setDescription('Sets the DULD mode as shutdown or normal.')NEWLINEduldLinkStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("unknow", 1), ("bidirectional", 2), ("txFault", 3), ("rxFault", 4), ("linkDown", 5)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: duldLinkStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldLinkStatus.setDescription('Gets the DULD link status.')NEWLINEduldDiscoveryTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 6), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(5, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: duldDiscoveryTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldDiscoveryTime.setDescription('Sets the DULD discovery time.')NEWLINEduldRecoverTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 2), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(60, 1000000), )).clone(60)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: duldRecoverTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldRecoverTime.setDescription('Duld auto recover time.')NEWLINEdoSCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1), )NEWLINEif mibBuilder.loadTexts: doSCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlTable.setDescription('A table that holds the DoS prevention settings of the device.')NEWLINEdoSCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "doSCtrlType"))NEWLINEif mibBuilder.loadTexts: doSCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlEntry.setDescription('A list of DoS prevention settings of the device.')NEWLINEdoSCtrlType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("land-attack", 1), ("blat-attack", 2), ("smurf-attack", 3), ("tcp-null-scan", 4), ("tcp-xmascan", 5), ("tcp-synfin", 6), ("tcp-syn-srcport-less-1024", 7)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: doSCtrlType.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlType.setDescription('This object indicates the DoS prevention type.')NEWLINEdoSCtrlState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlState.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlState.setDescription('This object indicates the status of the DoS prevention type.')NEWLINEdoSCtrlActionType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("drop", 0), ("mirror", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlActionType.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlActionType.setDescription("This object indicates the action for the DoS prevention type. If this object is set to 'mirror' and DoSCtrlState is set to 'enable', the configuration will not take effect until a valid mirror port is specified. If mirror port is not valid the behavior will be the same as 'drop'")NEWLINEdoSCtrlMirrorPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorPort.setDescription("This object indicates the port to which the attack packet will be forwarded. A value of 0 means that the DoS prevention action type is either not set to 'mirror'. or the 'mirror' DoS action is not active. When DoSCtrlActionType is set to 'mirror' with DoSCtrlState set to 'enable', setting this value to a valid port number will activate the 'mirror' DoS action.")NEWLINEdoSCtrlMirrorReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorReplace1P.setDescription('This object indicates the packet to which the attack packet will be replaced 1p to mirror port. The Range of 1p is 0 ~ 7. If value set to -1, it means no chenged.')NEWLINEdoSCtrlMirrorRxRate = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1024000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorRxRate.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorRxRate.setDescription('This object indicates the packet to which the attack packet will be rate limited to mirror port. The Range of rx limit is 0 or 64~1024000. If rate set to 0, it means no limit.')NEWLINEdoSCtrlFrameCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 7), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: doSCtrlFrameCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlFrameCount.setDescription('This object indicates the frame counts of the DoS prevention type.')NEWLINEdoSCtrlClearFrameCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("normal", 0), ("clear", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlClearFrameCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlClearFrameCount.setDescription('This object will clear frame count when set to clear.')NEWLINEdosCtrlTrapLogState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dosCtrlTrapLogState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dosCtrlTrapLogState.setDescription('Enable/Disable Dos Trap Log function. Default is disabled.')NEWLINEswTimeRangeSettingTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1), )NEWLINEif mibBuilder.loadTexts: swTimeRangeSettingTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeSettingTable.setDescription('A table to configure time Range in the system.')NEWLINEswTimeRangeSettingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "swTimeRangeIndex"))NEWLINEif mibBuilder.loadTexts: swTimeRangeSettingEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeSettingEntry.setDescription('A schedule entry to configure time Range in the system.')NEWLINEswTimeRangeIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 52))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: swTimeRangeIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeIndex.setDescription('The Time Range identifier. The maximum number of Schedule entry is the number of ports supported PoE function. The value must be between 1 and 52.')NEWLINEswTimeRangeName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeName.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeName.setDescription("The Schedule name associated with the Schedule entry (e.g., `abc, bbb').")NEWLINEswTimeRangeDate = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeDate.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeDate.setDescription('Enable/Disable date range checking while executing time base PoE.')NEWLINEswTimeRangeStartYear = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037))).clone(namedValues=NamedValues(("y2009", 2009), ("y2010", 2010), ("y2011", 2011), ("y2012", 2012), ("y2013", 2013), ("y2014", 2014), ("y2015", 2015), ("y2016", 2016), ("y2017", 2017), ("y2018", 2018), ("y2019", 2019), ("y2020", 2020), ("y2021", 2021), ("y2022", 2022), ("y2023", 2023), ("y2024", 2024), ("y2025", 2025), ("y2026", 2026), ("y2027", 2027), ("y2028", 2028), ("y2029", 2029), ("y2030", 2030), ("y2031", 2031), ("y2032", 2032), ("y2033", 2033), ("y2034", 2034), ("y2035", 2035), ("y2036", 2036), ("y2037", 2037)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartYear.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartYear.setDescription('Start year of the Schedule entry.')NEWLINEswTimeRangeStartMonth = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=NamedValues(("january", 1), ("february", 2), ("march", 3), ("april", 4), ("may", 5), ("june", 6), ("july", 7), ("august", 8), ("september", 9), ("october", 10), ("november", 11), ("december", 12)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartMonth.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartMonth.setDescription('Start month of the Schedule entry.')NEWLINEswTimeRangeStartDay = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartDay.setDescription('Start day of the Schedule entry. The value must be from 1 to 31.')NEWLINEswTimeRangeStartHour = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 23))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartHour.setDescription('Start hour of the Schedule entry. The value must be from 0 to 23.')NEWLINEswTimeRangeStartMinute = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 59))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartMinute.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartMinute.setDescription('Start minute of the Schedule entry. The value must be from 0 to 59.')NEWLINEswTimeRangeEndYear = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037))).clone(namedValues=NamedValues(("y2009", 2009), ("y2010", 2010), ("y2011", 2011), ("y2012", 2012), ("y2013", 2013), ("y2014", 2014), ("y2015", 2015), ("y2016", 2016), ("y2017", 2017), ("y2018", 2018), ("y2019", 2019), ("y2020", 2020), ("y2021", 2021), ("y2022", 2022), ("y2023", 2023), ("y2024", 2024), ("y2025", 2025), ("y2026", 2026), ("y2027", 2027), ("y2028", 2028), ("y2029", 2029), ("y2030", 2030), ("y2031", 2031), ("y2032", 2032), ("y2033", 2033), ("y2034", 2034), ("y2035", 2035), ("y2036", 2036), ("y2037", 2037)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndYear.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndYear.setDescription('End year of the Schedule entry.')NEWLINEswTimeRangeEndMonth = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=NamedValues(("january", 1), ("february", 2), ("march", 3), ("april", 4), ("may", 5), ("june", 6), ("july", 7), ("august", 8), ("september", 9), ("october", 10), ("november", 11), ("december", 12)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndMonth.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndMonth.setDescription('End month of the Schedule entry.')NEWLINEswTimeRangeEndDay = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndDay.setDescription('End day of the Schedule entry. The value must be from 1 to 31.')NEWLINEswTimeRangeEndHour = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 23))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndHour.setDescription('End hour of the Schedule entry. The value must be from 0 to 23.')NEWLINEswTimeRangeEndMinute = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 59))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndMinute.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndMinute.setDescription('End minute of the Schedule entry. The value must be from 0 to 59.')NEWLINEswTimeRangeMonday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeMonday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeMonday.setDescription('Enable/Disble scheduling Monday.')NEWLINEswTimeRangeTuesday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeTuesday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeTuesday.setDescription('Enable/Disble scheduling Tuesday.')NEWLINEswTimeRangeWednesday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeWednesday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeWednesday.setDescription('Enable/Disble scheduling Wednesday.')NEWLINEswTimeRangeThursday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeThursday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeThursday.setDescription('Enable/Disble scheduling Thursday.')NEWLINEswTimeRangeFriday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeFriday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeFriday.setDescription('Enable/Disble scheduling Friday.')NEWLINEswTimeRangeSaturday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeSaturday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeSaturday.setDescription('Enable/Disble scheduling Saturday.')NEWLINEswTimeRangeSunday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeSunday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeSunday.setDescription('Enable/Disble scheduling Sunday.')NEWLINEswTimeRangeRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 21), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: swTimeRangeRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeRowStatus.setDescription('The status of an entry in the Time Range Information Table. Only a subset of the rowstatus variables (active, notinservice, createAndWait, destroy) are available.')NEWLINEdlinklldpState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpState.setDescription('This object is used for enabling or disabling LLDP in the system.')NEWLINEdlinklldpMsgHoldMultiplier = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 10))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpMsgHoldMultiplier.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpMsgHoldMultiplier.setDescription('The time-to-live value expressed as a multiple of the lldpMessageTxInterval object.The actual time-to-live value used in LLDP frames, transmitted on behalf of this LLDP agent, can be expressed by the following formula: TTL = min(65535, (lldpMessageTxInterval * lldpMessageTxHoldMultiplier))')NEWLINEdlinklldpMsgTxInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(5, 32768))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpMsgTxInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpMsgTxInterval.setDescription('This object is used for LLDP packet update frequency. The timer in units of seconds.')NEWLINEdlinklldpReinitDelay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpReinitDelay.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpReinitDelay.setDescription('This object is used for LLDP Reinitialization Delay. The timer in units of seconds.')NEWLINEdlinklldpTxDelay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8192))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpTxDelay.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpTxDelay.setDescription('The lldpTxDelay indicates the delay (in units of seconds) between successive LLDP frame transmissions initiated by value/status changes in the LLDP local systems MIB. The recommended value for the lldpTxDelay is set by the following formula: 1 <= lldpTxDelay <= (0.25 * lldpMessageTxInterval).')NEWLINEdlinklldpConfigManAddrPortsTxEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpConfigManAddrPortsTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: dlinklldpConfigManAddrPortsTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpConfigManAddrPortsTxEnable.setDescription('A set of ports that are identified by a PortList, in which each port is represented as a bit. The corresponding local system management address instance will be transmitted on the member ports of the lldpManAddrPortsTxEnable. The default value for lldpConfigManAddrPortsTxEnable object is empty binary string, which means no ports are specified for advertising indicated management address instance.')NEWLINEclass LldpPortNumber(TextualConvention, Integer32):NEWLINE description = "Each port contained in the chassis (that is known to the LLDP agent) is uniquely identified by a port number. A port number has no mandatory relationship to an InterfaceIndex object (of the interfaces MIB, IETF RFC 2863). If the LLDP agent is a IEEE 802.1D, IEEE 802.1Q bridge, the LldpPortNumber will have the same value as the dot1dBasePort object (defined in IETF RFC 1493) associated corresponding bridge port. If the system hosting LLDP agent is not an IEEE 802.1D or an IEEE 802.1Q bridge, the LldpPortNumber will have the same value as the corresponding interface's InterfaceIndex object. Port numbers should be in the range of 1 and 4096 since a particular port is also represented by the corresponding port number bit in LldpPortList."NEWLINE status = 'current'NEWLINE displayHint = 'd'NEWLINE subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 4096)NEWLINENEWLINElldpPortConfigTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11), )NEWLINEif mibBuilder.loadTexts: lldpPortConfigTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigTable.setDescription('The table that controls LLDP frame transmission on individual ports.')NEWLINElldpPortConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpPortConfigPortNum"))NEWLINEif mibBuilder.loadTexts: lldpPortConfigEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigEntry.setDescription('LLDP configuration information for a particular port. This configuration parameter controls the transmission and the reception of LLDP frames on those ports whose rows are created in this table.')NEWLINElldpPortConfigPortNum = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1, 1), LldpPortNumber())NEWLINEif mibBuilder.loadTexts: lldpPortConfigPortNum.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigPortNum.setDescription('The index value used to identify the port component (contained in the local chassis with the LLDP agent) associated with this entry. The value of this object is used as a port index to the lldpPortConfigTable.')NEWLINElldpPortConfigAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("txOnly", 1), ("rxOnly", 2), ("txAndRx", 3), ("disabled", 4))).clone('txAndRx')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpPortConfigAdminStatus.setReference('IEEE 802.1AB-2005 10.5.1')NEWLINEif mibBuilder.loadTexts: lldpPortConfigAdminStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigAdminStatus.setDescription("The administratively desired status of the local LLDP agent. If the associated lldpPortConfigAdminStatus object has a value of 'txOnly(1)', then LLDP agent will transmit LLDP frames on this port and it will not store any information about the remote systems connected. If the associated lldpPortConfigAdminStatus object has a value of 'rxOnly(2)', then the LLDP agent will receive, but it will not transmit LLDP frames on this port. If the associated lldpPortConfigAdminStatus object has a value of 'txAndRx(3)', then the LLDP agent will transmit and receive LLDP frames on this port. If the associated lldpPortConfigAdminStatus object has a value of 'disabled(4)', then LLDP agent will not transmit or receive LLDP frames on this port. If there is remote systems information which is received on this port and stored in other tables, before the port's lldpPortConfigAdminStatus becomes disabled, then the information will naturally age out.")NEWLINElldpPortConfigNotificationEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1, 3), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpPortConfigNotificationEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigNotificationEnable.setDescription('The lldpPortConfigNotificationEnable controls, on a per port basis, whether or not notifications from the agent are enabled. The value true(1) means that notifications are enabled; the value false(2) means that they are not.')NEWLINElldpPortConfigTLVsTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1, 4), Bits().clone(namedValues=NamedValues(("portDesc", 0), ("sysName", 1), ("sysDesc", 2), ("sysCap", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpPortConfigTLVsTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpPortConfigTLVsTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigTLVsTxEnable.setDescription("The lldpPortConfigTLVsTxEnable, defined as a bitmap, includes the basic set of LLDP TLVs whose transmission is allowed on the local LLDP agent by the network management. Each bit in the bitmap corresponds to a TLV type associated with a specific optional TLV. It should be noted that the organizationally-specific TLVs are excluded from the lldpTLVsTxEnable bitmap. LLDP Organization Specific Information Extension MIBs should have similar configuration object to control transmission of their organizationally defined TLVs. The bit 'portDesc(0)' indicates that LLDP agent should transmit 'Port Description TLV'. The bit 'sysName(1)' indicates that LLDP agent should transmit 'System Name TLV'. The bit 'sysDesc(2)' indicates that LLDP agent should transmit 'System Description TLV'. The bit 'sysCap(3)' indicates that LLDP agent should transmit 'System Capabilities TLV'. There is no bit reserved for the management address TLV type since transmission of management address TLVs are controlled by another object, lldpConfigManAddrTable. The default value for lldpPortConfigTLVsTxEnable object is empty set, which means no enumerated values are set. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.")NEWLINElldpXdot3Objects = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12))NEWLINElldpXdot3Config = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 1))NEWLINElldpXdot3LocalData = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2))NEWLINElldpXdot3RemoteData = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3))NEWLINEclass LldpPowerPortClass(TextualConvention, Integer32):NEWLINE description = 'This TC describes the Power over Ethernet (PoE) port class.'NEWLINE status = 'current'NEWLINE subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))NEWLINE namedValues = NamedValues(("pClassPSE", 1), ("pClassPD", 2))NEWLINENEWLINEclass LldpLinkAggStatusMap(TextualConvention, Bits):NEWLINE description = "This TC describes the link aggregation status. The bit 'aggCapable(0)' indicates the link is capable of being aggregated. The bit 'aggEnabled(1)' indicates the link is currently in aggregation."NEWLINE status = 'current'NEWLINE namedValues = NamedValues(("aggCapable", 0), ("aggEnabled", 1))NEWLINENEWLINElldpXdot3PortConfigTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 1, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTable.setDescription('A table that controls selection of LLDP TLVs to be transmitted on individual ports.')NEWLINElldpXdot3PortConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 1, 1, 1), )NEWLINElldpPortConfigEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot3PortConfigEntry"))NEWLINElldpXdot3PortConfigEntry.setIndexNames(*lldpPortConfigEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigEntry.setDescription('LLDP configuration information that controls the transmission of IEEE 802.3 organizationally defined TLVs on LLDP transmission capable ports. This configuration object augments the lldpPortConfigEntry of the LLDP-MIB, therefore it is only present along with the port configuration defined by the associated lldpPortConfigEntry entry. Each active lldpXdot3PortConfigEntry must be from non-volatile storage (along with the corresponding lldpPortConfigEntry) after a re-initialization of the management system.')NEWLINElldpXdot3PortConfigTLVsTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 1, 1, 1, 1), Bits().clone(namedValues=NamedValues(("macPhyConfigStatus", 0), ("powerViaMDI", 1), ("linkAggregation", 2), ("maxFrameSize", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTLVsTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTLVsTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTLVsTxEnable.setDescription("The lldpXdot3PortConfigTLVsTxEnable, defined as a bitmap, includes the IEEE 802.3 organizationally defined set of LLDP TLVs whose transmission is allowed on the local LLDP agent by the network management. Each bit in the bitmap corresponds to an IEEE 802.3 subtype associated with a specific IEEE 802.3 optional TLV. The bit 0 is not used since there is no corresponding subtype. The bit 'macPhyConfigStatus(0)' indicates that LLDP agent should transmit 'MAC/PHY configuration/status TLV'. The bit 'powerViaMDI(1)' indicates that LLDP agent should transmit 'Power via MDI TLV'. The bit 'linkAggregation(2)' indicates that LLDP agent should transmit 'Link Aggregation TLV'. The bit 'maxFrameSize(3)' indicates that LLDP agent should transmit 'Maximum-frame-size TLV'. The default value for lldpXdot3PortConfigTLVsTxEnable object is an empty set, which means no enumerated values are set. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.")NEWLINElldpXdot3LocPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortTable.setDescription('This table contains one row per port of Ethernet port information (as a part of the LLDP 802.3 organizational extension) on the local system known to this agent.')NEWLINElldpXdot3LocPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3LocPortAutoNegSupported"))NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortEntry.setDescription('Information about a particular port component.')NEWLINElldpXdot3LocPortAutoNegSupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1, 1), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegSupported.setReference('IEEE 802.1AB-2005 G.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegSupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegSupported.setDescription('The truth value used to indicate whether the given port (associated with the local system) supports Auto-negotiation.')NEWLINElldpXdot3LocPortAutoNegEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegEnabled.setReference('IEEE 802.1AB-2005 G.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegEnabled.setDescription('The truth value used to indicate whether port Auto-negotiation is enabled on the given port associated with the local system.')NEWLINElldpXdot3LocPortAutoNegAdvertisedCap = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(2, 2)).setFixedLength(2)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegAdvertisedCap.setReference('IEEE 802.1AB-2005 G.2.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegAdvertisedCap.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegAdvertisedCap.setDescription('This object contains the value (bitmap) of the ifMauAutoNegCapAdvertisedBits object (defined in IETF RFC 3636) which is associated with the given port on the local system.')NEWLINElldpXdot3LocPortOperMauType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortOperMauType.setReference('IEEE 802.1AB-2005 G.2.3')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortOperMauType.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortOperMauType.setDescription('An integer value that indicates the operational MAU type of the given port on the local system. This object contains the integer value derived from the list position of the corresponding dot3MauType as listed in IETF RFC 3636 (or subsequent revisions) and is equal to the last number in the respective dot3MauType OID. For example, if the ifMauType object is dot3MauType1000BaseTHD which corresponds to {dot3MauType 29}, the numerical value of this field will be 29. For MAU types not listed in RFC 3636 (or subsequent revisions), the value of this field shall be set to zero.')NEWLINElldpXdot3LocPowerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerTable.setDescription('This table contains one row per port of power ethernet information (as a part of the LLDP 802.3 organizational extension) on the local system known to this agent.')NEWLINElldpXdot3LocPowerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3LocPowerPortClass"))NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerEntry.setDescription('Information about a particular port component.')NEWLINElldpXdot3LocPowerPortClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 1), LldpPowerPortClass()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPortClass.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPortClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPortClass.setDescription('The value that identifies the port Class of the given port associated with the local system.')NEWLINElldpXdot3LocPowerMDISupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDISupported.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDISupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDISupported.setDescription('The truth value used to indicate whether the MDI power is supported on the given port associated with the local system.')NEWLINElldpXdot3LocPowerMDIEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 3), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDIEnabled.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDIEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDIEnabled.setDescription('The truth value used to identify whether MDI power is enabled on the given port associated with the local system.')NEWLINElldpXdot3LocPowerPairControlable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 4), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairControlable.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairControlable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairControlable.setDescription('The truth value is derived from the value of pethPsePortPowerPairsControlAbility object (defined in IETF RFC 3621) and is used to indicate whether the pair selection can be controlled on the given port associated with the local system.')NEWLINElldpXdot3LocPowerPairs = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(1, 1), ValueRangeConstraint(2, 2), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairs.setReference('IEEE 802.1AB-2005 G.3.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairs.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairs.setDescription('This object contains the value of the pethPsePortPowerPairs object (defined in IETF RFC 3621) which is associated with the given port on the local system.')NEWLINElldpXdot3LocPowerClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(1, 1), ValueRangeConstraint(2, 2), ValueRangeConstraint(3, 3), ValueRangeConstraint(4, 4), ValueRangeConstraint(5, 5), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerClass.setReference('IEEE 802.1AB-2005 G.3.3')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerClass.setDescription('This object contains the value of the pethPsePortPowerClassifications object (defined in IETF RFC 3621) which is associated with the given port on the local system.')NEWLINElldpXdot3LocLinkAggTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggTable.setDescription('This table contains one row per port of link aggregation information (as a part of the LLDP 802.3 organizational extension) on the local system known to this agent.')NEWLINElldpXdot3LocLinkAggEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3LocLinkAggStatus"))NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggEntry.setDescription('Link Aggregation information about a particular port component.')NEWLINElldpXdot3LocLinkAggStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 3, 1, 1), LldpLinkAggStatusMap()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggStatus.setReference('IEEE 802.1AB-2005 G.4.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggStatus.setDescription('The bitmap value contains the link aggregation capabilities and the current aggregation status of the link.')NEWLINElldpXdot3LocLinkAggPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 2147483647), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggPortId.setReference('IEEE 802.1AB-2005 G.4.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggPortId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggPortId.setDescription('This object contains the IEEE 802.3 aggregated port identifier, aAggPortID (IEEE 802.3-2002, 30.7.2.1.1), derived from the ifNumber of the ifIndex for the port component in link aggregation. If the port is not in link aggregation state and/or it does not support link aggregation, this value should be set to zero.')NEWLINElldpXdot3LocMaxFrameSizeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSizeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSizeTable.setDescription('This table contains one row per port of maximum frame size information (as a part of the LLDP 802.3 organizational extension) on the local system known to this agent.')NEWLINElldpXdot3LocMaxFrameSizeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3LocMaxFrameSize"))NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSizeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSizeEntry.setDescription('Maximum Frame Size information about a particular port component.')NEWLINElldpXdot3LocMaxFrameSize = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSize.setReference('IEEE 802.1AB-2005 G.5.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSize.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSize.setDescription('An integer value indicating the maximum supported frame size in octets on the given port of the local system.')NEWLINElldpXdot3RemPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortTable.setDescription('This table contains Ethernet port information (as a part of the LLDP 802.3 organizational extension) of the remote system.')NEWLINElldpXdot3RemPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3RemPortAutoNegSupported"))NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortEntry.setDescription('Information about a particular physical network connection.')NEWLINElldpXdot3RemPortAutoNegSupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1, 1), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegSupported.setReference('IEEE 802.1AB-2005 G.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegSupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegSupported.setDescription('The truth value used to indicate whether the given port (associated with remote system) supports Auto-negotiation.')NEWLINElldpXdot3RemPortAutoNegEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegEnabled.setReference('IEEE 802.1AB-2005 G.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegEnabled.setDescription('The truth value used to indicate whether port Auto-negotiation is enabled on the given port associated with the remote system.')NEWLINElldpXdot3RemPortAutoNegAdvertisedCap = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(2, 2)).setFixedLength(2)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegAdvertisedCap.setReference('IEEE 802.1AB-2005 G.2.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegAdvertisedCap.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegAdvertisedCap.setDescription('This object contains the value (bitmap) of the ifMauAutoNegCapAdvertisedBits object (defined in IETF RFC 3636) which is associated with the given port on the remote system.')NEWLINElldpXdot3RemPortOperMauType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortOperMauType.setReference('IEEE 802.1AB-2005 G.2.3')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortOperMauType.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortOperMauType.setDescription('An integer value that indicates the operational MAU type of the sending device. This object contains the integer value derived from the list position of the corresponding dot3MauType as listed in in IETF RFC 3636 (or subsequent revisions) and is equal to the last number in the respective dot3MauType OID. For example, if the ifMauType object is dot3MauType1000BaseTHD which corresponds to {dot3MauType 29}, the numerical value of this field will be 29. For MAU types not listed in RFC 3636 (or subsequent revisions), the value of this field shall be set to zero.')NEWLINElldpXdot3RemPowerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerTable.setDescription('This table contains Ethernet power information (as a part of the LLDP 802.3 organizational extension) of the remote system.')NEWLINElldpXdot3RemPowerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3RemPowerPortClass"))NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerEntry.setDescription('Information about a particular physical network connection.')NEWLINElldpXdot3RemPowerPortClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 1), LldpPowerPortClass()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPortClass.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPortClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPortClass.setDescription('The value that identifies the port Class of the given port associated with the remote system.')NEWLINElldpXdot3RemPowerMDISupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDISupported.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDISupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDISupported.setDescription('The truth value used to indicate whether the MDI power is supported on the given port associated with the remote system.')NEWLINElldpXdot3RemPowerMDIEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 3), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDIEnabled.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDIEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDIEnabled.setDescription('The truth value used to identify whether MDI power is enabled on the given port associated with the remote system.')NEWLINElldpXdot3RemPowerPairControlable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 4), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairControlable.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairControlable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairControlable.setDescription('The truth value is derived from the value of pethPsePortPowerPairsControlAbility object (defined in IETF RFC 3621) and is used to indicate whether the pair selection can be controlled on the given port associated with the remote system.')NEWLINElldpXdot3RemPowerPairs = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(1, 1), ValueRangeConstraint(2, 2), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairs.setReference('IEEE 802.1AB-2005 G.3.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairs.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairs.setDescription('This object contains the value of the pethPsePortPowerPairs object (defined in IETF RFC 3621) which is associated with the given port on the remote system.')NEWLINElldpXdot3RemPowerClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(1, 1), ValueRangeConstraint(2, 2), ValueRangeConstraint(3, 3), ValueRangeConstraint(4, 4), ValueRangeConstraint(5, 5), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerClass.setReference('IEEE 802.1AB-2005 G.3.3')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerClass.setDescription('This object contains the value of the pethPsePortPowerClassifications object (defined in IETF RFC 3621) which is associated with the given port on the remote system.')NEWLINElldpXdot3RemLinkAggTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggTable.setDescription('This table contains port link aggregation information (as a part of the LLDP 802.3 organizational extension) of the remote system.')NEWLINElldpXdot3RemLinkAggEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3RemLinkAggStatus"))NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggEntry.setDescription("Link Aggregation information about remote system's port component.")NEWLINElldpXdot3RemLinkAggStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 3, 1, 1), LldpLinkAggStatusMap()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggStatus.setReference('IEEE 802.1AB-2005 G.4.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggStatus.setDescription('The bitmap value contains the link aggregation capabilities and the current aggregation status of the link.')NEWLINElldpXdot3RemLinkAggPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 2147483647), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggPortId.setReference('IEEE 802.1AB-2005 G.4.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggPortId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggPortId.setDescription('This object contains the IEEE 802.3 aggregated port identifier, aAggPortID (IEEE 802.3-2002, 30.7.2.1.1), derived from the ifNumber of the ifIndex for the port component associated with the remote system. If the remote port is not in link aggregation state and/or it does not support link aggregation, this value should be zero.')NEWLINElldpXdot3RemMaxFrameSizeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSizeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSizeTable.setDescription('This table contains one row per port of maximum frame size information (as a part of the LLDP 802.3 organizational extension) of the remote system.')NEWLINElldpXdot3RemMaxFrameSizeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3RemMaxFrameSize"))NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSizeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSizeEntry.setDescription('Maximum Frame Size information about a particular port component.')NEWLINElldpXdot3RemMaxFrameSize = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSize.setReference('IEEE 802.1AB-2005 G.5.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSize.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSize.setDescription('An integer value indicating the maximum supported frame size in octets on the port component associated with the remote system.')NEWLINElldpXdot1Objects = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13))NEWLINElldpXdot1Config = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1))NEWLINElldpXdot1LocalData = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2))NEWLINElldpXdot1RemoteData = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3))NEWLINElldpXdot1ConfigPortVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTable.setDescription('A table that controls selection of LLDP Port VLAN-ID TLVs to be transmitted on individual ports.')NEWLINElldpXdot1ConfigPortVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 1, 1), )NEWLINElldpPortConfigEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot1ConfigPortVlanEntry"))NEWLINElldpXdot1ConfigPortVlanEntry.setIndexNames(*lldpPortConfigEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanEntry.setDescription('LLDP configuration information that controls the transmission of IEEE 802.1 organizationally defined Port VLAN-ID TLV on LLDP transmission capable ports. This configuration object augments the lldpPortConfigEntry of the LLDP-MIB, therefore it is only present along with the port configuration defined by the associated lldpPortConfigEntry entry. Each active lldpConfigEntry must be restored from non-volatile storage (along with the corresponding lldpPortConfigEntry) after a re-initialization of the management system.')NEWLINElldpXdot1ConfigPortVlanTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 1, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTxEnable.setDescription('The lldpXdot1ConfigPortVlanTxEnable, which is defined as a truth value and configured by the network management, determines whether the IEEE 802.1 organizationally defined port VLAN TLV transmission is allowed on a given LLDP transmission capable port. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.')NEWLINElldpXdot1LocVlanNameTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanNameTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanNameTable.setDescription('This table contains one or more rows per IEEE 802.1Q VLAN name information on the local system known to this agent.')NEWLINElldpXdot1LocVlanNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1LocVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanNameEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanNameEntry.setDescription('VLAN name Information about a particular port component. There may be multiple VLANs, identified by a particular lldpXdot1LocVlanId, configured on the given port.')NEWLINElldpXdot1LocVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 3, 1, 1), VlanId())NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanId.setReference('IEEE 802.1AB-2005 F.4.2')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanId.setDescription('The integer value used to identify the IEEE 802.1Q VLAN IDs with which the given port is compatible.')NEWLINElldpXdot1LocVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 3, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanName.setReference('IEEE 802.1AB-2005 F.4.4')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanName.setDescription('The string value used to identify VLAN name identified by the Vlan Id associated with the given port on the local system. This object should contain the value of the dot1QVLANStaticName object (defined in IETF RFC 2674) identified with the given lldpXdot1LocVlanId.')NEWLINElldpXdot1ConfigVlanNameTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTable.setDescription('The table that controls selection of LLDP VLAN name TLV instances to be transmitted on individual ports.')NEWLINElldpXdot1ConfigVlanNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 2, 1), )NEWLINElldpXdot1LocVlanNameEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot1ConfigVlanNameEntry"))NEWLINElldpXdot1ConfigVlanNameEntry.setIndexNames(*lldpXdot1LocVlanNameEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameEntry.setDescription('LLDP configuration information that specifies the set of ports (represented as a PortList) on which the Local System VLAN name instance will be transmitted. This configuration object augments the lldpLocVlanEntry, therefore it is only present along with the VLAN Name instance contained in the associated lldpLocVlanNameEntry entry. Each active lldpXdot1ConfigVlanNameEntry must be restored from non-volatile storage (along with the corresponding lldpXdot1LocVlanNameEntry) after a re-initialization of the management system.')NEWLINElldpXdot1ConfigVlanNameTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 2, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTxEnable.setDescription('The boolean value that indicates whether the corresponding Local System VLAN name instance will be transmitted on the port defined by the given lldpXdot1LocVlanNameEntry. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.')NEWLINElldpXdot1LocProtoVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanTable.setDescription('This table contains one or more rows per Port and Protocol VLAN information about the local system.')NEWLINElldpXdot1LocProtoVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1LocProtoVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEntry.setDescription('Port and protocol VLAN ID Information about a particular port component. There may be multiple port and protocol VLANs, identified by a particular lldpXdot1LocProtoVlanId, configured on the given port.')NEWLINElldpXdot1LocProtoVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), )))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanId.setReference('IEEE 802.1AB-2005 F.3.2')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanId.setDescription('The integer value used to identify the port and protocol VLANs associated with the given port associated with the local system. A value of zero shall be used if the system either does not know the protocol VLAN ID (PPVID) or does not support port and protocol VLAN operation.')NEWLINElldpXdot1LocProtoVlanSupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanSupported.setReference('IEEE 802.1AB-2005 F.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanSupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanSupported.setDescription('The truth value used to indicate whether the given port (associated with the local system) supports port and protocol VLANs.')NEWLINElldpXdot1LocProtoVlanEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2, 1, 3), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEnabled.setReference('IEEE 802.1AB-2005 F.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEnabled.setDescription('The truth value used to indicate whether the port and protocol VLANs are enabled on the given port associated with the local system.')NEWLINElldpXdot1ConfigProtoVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTable.setDescription('The table that controls selection of LLDP Port and Protocol VLAN ID TLV instances to be transmitted on individual ports.')NEWLINElldpXdot1ConfigProtoVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 3, 1), )NEWLINElldpXdot1LocProtoVlanEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot1ConfigProtoVlanEntry"))NEWLINElldpXdot1ConfigProtoVlanEntry.setIndexNames(*lldpXdot1LocProtoVlanEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanEntry.setDescription('LLDP configuration information that specifies the set of ports (represented as a PortList) on which the Local System Protocol VLAN instance will be transmitted. This configuration object augments the lldpXdot1LocVlanEntry, therefore it is only present along with the Port and Protocol VLAN ID instance contained in the associated lldpXdot1LocVlanEntry entry. Each active lldpXdot1ConfigProtoVlanEntry must be restored from non-volatile storage (along with the corresponding lldpXdot1LocProtoVlanEntry) after a re-initialization of the management system.')NEWLINElldpXdot1ConfigProtoVlanTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 3, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTxEnable.setDescription('The boolean value that indicates whether the corresponding Local System Port and Protocol VLAN instance will be transmitted on the port defined by the given lldpXdot1LocProtoVlanEntry. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.')NEWLINElldpXdot1LocProtocolTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolTable.setReference('IEEE 802.1AB-2005 F.5')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolTable.setDescription('This table contains one or more rows per protocol identity information on the local system known to this agent.')NEWLINElldpXdot1LocProtocolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1LocProtocolIndex"))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolEntry.setReference('IEEE 802.1AB-2005 F.5')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolEntry.setDescription('Information about particular protocols that are accessible through the given port component. There may be multiple protocols, identified by particular lldpXdot1ProtocolIndex, and lldpLocPortNum.')NEWLINElldpXdot1LocProtocolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolIndex.setDescription('This object represents an arbitrary local integer value used by this agent to identify a particular protocol identity.')NEWLINElldpXdot1LocProtocolId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 4, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolId.setReference('IEEE 802.1AB-2005 F.5.3')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolId.setDescription('The octet string value used to identify the protocols associated with the given port of the local system.')NEWLINElldpXdot1ConfigProtocolTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTable.setDescription('The table that controls selection of LLDP Protocol TLV instances to be transmitted on individual ports.')NEWLINElldpXdot1ConfigProtocolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 4, 1), )NEWLINElldpXdot1LocProtocolEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot1ConfigProtocolEntry"))NEWLINElldpXdot1ConfigProtocolEntry.setIndexNames(*lldpXdot1LocProtocolEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolEntry.setDescription('LLDP configuration information that specifies the set of ports (represented as a PortList) on which the Local System Protocol instance will be transmitted. This configuration object augments the lldpXdot1LocProtoEntry, therefore it is only present along with the Protocol instance contained in the associated lldpXdot1LocProtoEntry entry. Each active lldpXdot1ConfigProtocolEntry must be restored from non-volatile storage (along with the corresponding lldpXdot1LocProtocolEntry) after a re-initialization of the management system.')NEWLINElldpXdot1ConfigProtocolTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 4, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTxEnable.setDescription('The boolean value that indicates whether the corresponding Local System Protocol Identity instance will be transmitted on the port defined by the given lldpXdot1LocProtocolEntry. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.')NEWLINElldpXdot1LocTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot1LocTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocTable.setDescription('This table contains one row per port for IEEE 802.1 organizationally defined LLDP extension on the local system known to this agent.')NEWLINElldpXdot1LocEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1LocPortVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocEntry.setDescription('Information about IEEE 802.1 organizationally defined LLDP extension.')NEWLINElldpXdot1LocPortVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocPortVlanId.setReference('IEEE 802.1AB-2005 F.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocPortVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocPortVlanId.setDescription("The integer value used to identify the port's VLAN identifier associated with the local system. A value of zero shall be used if the system either does not know the PVID or does not support port-based VLAN operation.")NEWLINElldpXdot1RemTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot1RemTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemTable.setDescription('This table contains one or more rows per physical network connection known to this agent. The agent may wish to ensure that only one lldpXdot1RemEntry is present for each local port, or it may choose to maintain multiple lldpXdot1RemEntries for the same local port.')NEWLINElldpXdot1RemEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1RemPortVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemEntry.setDescription('Information about a particular port component.')NEWLINElldpXdot1RemPortVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemPortVlanId.setReference('IEEE 802.1AB-2005 F.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemPortVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemPortVlanId.setDescription("The integer value used to identify the port's VLAN identifier associated with the remote system. if the remote system either does not know the PVID or does not support port-based VLAN operation, the value of lldpXdot1RemPortVlanId should be zero.")NEWLINElldpXdot1RemProtoVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanTable.setDescription('This table contains one or more rows per Port and Protocol VLAN information about the remote system, received on the given port.')NEWLINElldpXdot1RemProtoVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1RemProtoVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEntry.setDescription('Port and protocol VLAN name Information about a particular port component. There may be multiple protocol VLANs, identified by a particular lldpXdot1RemProtoVlanId, configured on the remote system.')NEWLINElldpXdot1RemProtoVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), )))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanId.setReference('IEEE 802.1AB-2005 F.3.2')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanId.setDescription('The integer value used to identify the port and protocol VLANs associated with the given port associated with the remote system. If port and protocol VLANs are not supported on the given port associated with the remote system, or if the port is not enabled with any port and protocol VLAN, the value of lldpXdot1RemProtoVlanId should be zero.')NEWLINElldpXdot1RemProtoVlanSupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanSupported.setReference('IEEE 802.1AB-2005 F.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanSupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanSupported.setDescription('The truth value used to indicate whether the given port (associated with the remote system) is capable of supporting port and protocol VLANs.')NEWLINElldpXdot1RemProtoVlanEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2, 1, 3), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEnabled.setReference('IEEE 802.1AB-2005 F.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEnabled.setDescription('The truth value used to indicate whether the port and protocol VLANs are enabled on the given port associated with the remote system.')NEWLINElldpXdot1RemVlanNameTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameTable.setReference('IEEE 802.1AB-2005 F.4')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameTable.setDescription('This table contains one or more rows per IEEE 802.1Q VLAN name information about the remote system, received on the given port.')NEWLINElldpXdot1RemVlanNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1RemVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameEntry.setDescription('VLAN name Information about a particular port component. There may be multiple VLANs, identified by a particular lldpXdot1RemVlanId, received on the given port.')NEWLINElldpXdot1RemVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 3, 1, 1), VlanId())NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanId.setReference('IEEE 802.1AB-2005 F.4.2')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanId.setDescription('The integer value used to identify the IEEE 802.1Q VLAN IDs with which the given port of the remote system is compatible.')NEWLINElldpXdot1RemVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 3, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanName.setReference('IEEE 802.1AB-2005 F.4.4')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanName.setDescription('The string value used to identify VLAN name identified by the VLAN Id associated with the remote system.')NEWLINElldpXdot1RemProtocolTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolTable.setDescription('This table contains one or more rows per protocol information about the remote system, received on the given port.')NEWLINElldpXdot1RemProtocolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1RemProtocolIndex"))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolEntry.setDescription('Protocol information about a particular port component. There may be multiple protocols, identified by a particular lldpXdot1ProtocolIndex, received on the given port.')NEWLINElldpXdot1RemProtocolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolIndex.setDescription('This object represents an arbitrary local integer value used by this agent to identify a particular protocol identity.')NEWLINElldpXdot1RemProtocolId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 4, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolId.setReference('IEEE 802.1AB-2005 F.5.3')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolId.setDescription('The octet string value used to identify the protocols associated with the given port of remote system.')NEWLINEsecurityDhcpServerScreen = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7))NEWLINEdhcpServerScreenEnablePortlist = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 1), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpServerScreenEnablePortlist.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpServerScreenEnablePortlist.setDescription('To enable or disable DHCP Server Screening port list.')NEWLINEdhcpServerScreenEnableVlanlist = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 2), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpServerScreenEnableVlanlist.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpServerScreenEnableVlanlist.setDescription('To enable or disable DHCP Server Screening vlan list.')NEWLINEdhcpServerScreenLogSuppressDuration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 5, 30))).clone(namedValues=NamedValues(("one-min", 1), ("five-min", 5), ("thirty-min", 30)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpServerScreenLogSuppressDuration.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpServerScreenLogSuppressDuration.setDescription('DSS Trap Log Suppress Duration.')NEWLINEfilterDHCPServerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4), )NEWLINEif mibBuilder.loadTexts: filterDHCPServerTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerTable.setDescription('A table to control filter DHCP Server for the entire switch or for each interface in the switch.')NEWLINEfilterDHCPServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "filterDHCPServerIpAddr"), (0, "DES-1210-28MEbx", "filterDHCPServerClientMacAddr"))NEWLINEif mibBuilder.loadTexts: filterDHCPServerEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEfilterDHCPServerIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 1), IpAddress())NEWLINEif mibBuilder.loadTexts: filterDHCPServerIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerIpAddr.setDescription("Specifies either the Network or Host address from which the switch can be managed. An address 0.0.0.0 indicates 'Any Manager'.")NEWLINEfilterDHCPServerClientMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 2), MacAddress().clone(hexValue="000102030405"))NEWLINEif mibBuilder.loadTexts: filterDHCPServerClientMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerClientMacAddr.setDescription('Ethernet Mac Address.')NEWLINEfilterDHCPServerPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: filterDHCPServerPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerPortList.setDescription("Specifies the port numbers through which the authorized manager can access the switch. By default the authorized manager is allowed to access the switch through all the ports. If a set of ports are configured in the 'PortList', the manager can access the switch only through the configured ports.")NEWLINEfilterDHCPServerVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: filterDHCPServerVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerVlanList.setDescription("Specifies the port numbers through which the authorized manager can access the switch. By default the authorized manager is allowed to access the switch through all the ports. If a set of ports are configured in the 'PortList', the manager can access the switch only through the configured ports.")NEWLINEfilterDHCPServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: filterDHCPServerRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEsecurityTrafficSeg = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9))NEWLINEtrafficSegTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9, 1), )NEWLINEif mibBuilder.loadTexts: trafficSegTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficSegTable.setDescription('A Port-channel is created through ifMain table. After the creation of the port-channel, corresponding logical interface will be created in the ifMain table. This Port-channel table is indexed through Key values and allows to configure link selection policy and the Mac address for the port-channel. All other objects in this table displays the details of the port-channel')NEWLINEtrafficSegEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "trafficSegIfIndex"))NEWLINEif mibBuilder.loadTexts: trafficSegEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficSegEntry.setDescription('There is one entry in this table for each created port-channel port')NEWLINEtrafficSegIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trafficSegIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficSegIfIndex.setDescription("The ifIndex of the port-channel(Aggregator's interface index). ")NEWLINEtrafficSegMemberList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9, 1, 1, 2), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficSegMemberList.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficSegMemberList.setDescription('Port list of port channel.')NEWLINEsecurityAAC = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11))NEWLINEaacAuthenAdminState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAuthenAdminState.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAuthenAdminState.setDescription('This object indicates the Access Authentication is enable or disable.')NEWLINEaacAuthParamResponseTimeout = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAuthParamResponseTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAuthParamResponseTimeout.setDescription('Timeout in second for login authentication response.')NEWLINEaacAuthParamAttempt = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAuthParamAttempt.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAuthParamAttempt.setDescription('The amount for login authentication, if login failure exceed, connection or access would be locked.')NEWLINEaacAPAuthMethodGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4))NEWLINEaacAPLoginMethod = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1))NEWLINEaacAPEnableMethod = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2))NEWLINEaacAPConsoleLoginMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPConsoleLoginMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPConsoleLoginMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via local console')NEWLINEaacAPTelnetLoginMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPTelnetLoginMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPTelnetLoginMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via telnet.')NEWLINEaacAPSSHLoginMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPSSHLoginMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPSSHLoginMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via SSH.')NEWLINEaacAPHttpLoginMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPHttpLoginMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPHttpLoginMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via HTTP.')NEWLINEaacAPConsoleEnableMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPConsoleEnableMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPConsoleEnableMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via local console.')NEWLINEaacAPTelnetEnableMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPTelnetEnableMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPTelnetEnableMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via telnet.')NEWLINEaacAPSSHEnableMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPSSHEnableMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPSSHEnableMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via SSH.')NEWLINEaacAPHttpEnableMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPHttpEnableMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPHttpEnableMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via HTTP.')NEWLINEaacServerGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5), )NEWLINEif mibBuilder.loadTexts: aacServerGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupTable.setDescription('A table that contains informations about server group.')NEWLINEaacServerGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacServerGroupIndex"))NEWLINEif mibBuilder.loadTexts: aacServerGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupEntry.setDescription('A list of the group including servers.')NEWLINEaacServerGroupIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 9))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacServerGroupIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupIndex.setDescription('A value that uniquely identifies this SwAACServerGroupEntry .')NEWLINEaacServerGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerGroupName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupName.setDescription("A human-readable text string of the method group. The name is writable only if Group is new created, which the value of aacServerGroupRowStatus is 'notReady'.")NEWLINEaacServersInGroup = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1, 3), Bits().clone(namedValues=NamedValues(("id1", 0), ("id2", 1), ("id3", 2), ("id4", 3), ("id5", 4), ("id6", 5), ("id7", 6), ("id8", 7), ("id9", 8), ("id10", 9), ("id11", 10), ("id12", 11), ("id13", 12), ("id14", 13), ("id15", 14), ("id16", 15)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServersInGroup.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServersInGroup.setDescription('The list of servers in the group, each bit indicates a specified server ID. The server must be created before including it.')NEWLINEaacServerGroupRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacServerGroupRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEiPv4aacServerInfoTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6), )NEWLINEif mibBuilder.loadTexts: iPv4aacServerInfoTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerInfoTable.setDescription('A table that contains information about severs.')NEWLINEiPv4aacServerInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1), ).setIndexNames((0, "DES-1210-28MEbx", "iPv4aacServerIndex"))NEWLINEif mibBuilder.loadTexts: iPv4aacServerInfoEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerInfoEntry.setDescription('A list of the information of server .')NEWLINEiPv4aacServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: iPv4aacServerIndex.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerIndex.setDescription('A value that uniquely identifies this SwAACServerGroupEntry.')NEWLINEiPv4aacServerIPAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerIPAddr.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerIPAddr.setDescription('The IP address of Server')NEWLINEiPv4aacServerAuthProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthProtocol.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthProtocol.setDescription('The authentication protocol provided by the Server.')NEWLINEiPv4aacServerAuthPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthPort.setDescription('The TCP/IP port .')NEWLINEiPv4aacServerAuthKey = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 254))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthKey.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthKey.setDescription('The key used while authentication process.')NEWLINEiPv4aacServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerTimeout.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerTimeout.setDescription('Server response timeout .')NEWLINEiPv4aacServerRetryCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerRetryCount.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerRetryCount.setDescription('Client retry count . (-1: No retry mechanism)')NEWLINEiPv4aacServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 8), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: iPv4aacServerRowStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacServerInfoTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7), )NEWLINEif mibBuilder.loadTexts: aacServerInfoTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerInfoTable.setDescription('A table that contains information about severs.')NEWLINEaacServerInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacServerIndex"))NEWLINEif mibBuilder.loadTexts: aacServerInfoEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerInfoEntry.setDescription('A list of the information of server .')NEWLINEaacServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacServerIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerIndex.setDescription('A value that uniquely identifies this SwAACServerGroupEntry.')NEWLINEaacServerIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2)).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerIPType.setDescription('The IP address of the AAC server IP type referred to in this table entry. (IPv4=1, IPv6=2)')NEWLINEaacServerIPAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 3), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerIPAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerIPAddr.setDescription('The IP address of Server')NEWLINEaacServerInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 4), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacServerInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerInterfaceName.setDescription('Specifies the interface name when the aacServerIPAddr is linklocal address.')NEWLINEaacServerAuthProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerAuthProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerAuthProtocol.setDescription('The authentication protocol provided by the Server.')NEWLINEaacServerAuthPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerAuthPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerAuthPort.setDescription('The TCP/IP port .')NEWLINEaacServerAuthKey = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 254))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerAuthKey.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerAuthKey.setDescription('The key used while authentication process.')NEWLINEaacServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerTimeout.setDescription('Server response timeout .')NEWLINEaacServerRetryCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerRetryCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerRetryCount.setDescription('Client retry count . (-1: No retry mechanism)')NEWLINEaacServerAccountingPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerAccountingPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerAccountingPort.setDescription('The accounting port .')NEWLINEaacServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacServerRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacLoginMethodListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8), )NEWLINEif mibBuilder.loadTexts: aacLoginMethodListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListTable.setDescription('A table that contains information about Login authentication method lists.')NEWLINEaacLoginMethodListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacLoginMethodListIndex"))NEWLINEif mibBuilder.loadTexts: aacLoginMethodListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListEntry.setDescription('A list of the Authentication methods.')NEWLINEaacLoginMethodListIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacLoginMethodListIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListIndex.setDescription('A value that identifies this method list.')NEWLINEaacLoginMethodListName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethodListName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListName.setDescription('A human-readable text string of the method list.')NEWLINEaacLoginMethod1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethod1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethod1.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacLoginMethod2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethod2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethod2.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacLoginMethod3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethod3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethod3.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacLoginMethod4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethod4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethod4.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacLoginMethodListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 7), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacLoginMethodListRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacEnableMethodListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9), )NEWLINEif mibBuilder.loadTexts: aacEnableMethodListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListTable.setDescription('A table that contains information about Enable authentication method lists.')NEWLINEaacEnableMethodListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacEnableMethodListIndex"))NEWLINEif mibBuilder.loadTexts: aacEnableMethodListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListEntry.setDescription('A list of the Authentication methods.')NEWLINEaacEnableMethodListIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacEnableMethodListIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListIndex.setDescription('A value that identifies this method list.')NEWLINEaacEnableMethodListName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethodListName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListName.setDescription('A human-readable text string of the method list.')NEWLINEaacEnableMethod1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethod1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethod1.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacEnableMethod2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethod2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethod2.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacEnableMethod3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethod3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethod3.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacEnableMethod4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethod4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethod4.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacEnableMethodListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 7), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacEnableMethodListRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacLocalEnablePassword = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 10), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLocalEnablePassword.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLocalEnablePassword.setDescription('This object is used to set Local Enable Password.')NEWLINEaacAccountingMethodListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11), )NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListTable.setDescription('A table that contains information about Accounting authentication method lists.')NEWLINEaacAccountingMethodListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacAccountingMethodListIndex"))NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListEntry.setDescription('A list of the Authentication methods.')NEWLINEaacAccountingMethodListIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListIndex.setDescription('A value that identifies this method list.')NEWLINEaacAccountingMethodListName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListName.setDescription('A human-readable text string of the method list.')NEWLINEaacAccountingMethod1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethod1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethod1.setDescription('The type of Accounting method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacAccountingMethod2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethod2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethod2.setDescription('The type of Accounting method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacAccountingMethod3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethod3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethod3.setDescription('The type of Accounting method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacAccountingMethod4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethod4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethod4.setDescription('The type of Accounting method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacAccountingMethodListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 7), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacAccountingServiceIndex = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 12))NEWLINEaacAccountingServiceNetwork = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 12, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, -1))).clone(namedValues=NamedValues(("radius-only", 0), ("default-method-list", 1), ("method-list-name", 2), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceNetwork.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceNetwork.setDescription('This object indicates aac Accounting Service Network is radius_only, default_method_list, method_list_name and disable about Accounting Service Network.')NEWLINEaacAccountingServiceShell = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 12, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, -1))).clone(namedValues=NamedValues(("radius-only", 0), ("default-method-list", 1), ("method-list-name", 2), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceShell.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceShell.setDescription('This object indicates aac Accounting Service Shell is radius_only, default_method_list, method_list_name and disable about Accounting Service Network.')NEWLINEaacAccountingServiceSystem = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 12, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, -1))).clone(namedValues=NamedValues(("radius-only", 0), ("default-method-list", 1), ("method-list-name", 2), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceSystem.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceSystem.setDescription('This object indicates aac Accounting System Shell is radius_only, default_method_list, method_list_name and disable about Accounting Service Network.')NEWLINEaacAccountingServiceCommand = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13))NEWLINEaacAccountingServiceCommandAdministrator = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, -1))).clone(namedValues=NamedValues(("method1", 0), ("method2", 1), ("method3", 2), ("method4", 3), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandAdministrator.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandAdministrator.setDescription('This object indicates aac Accounting Command Admin is method1, method2, method3 , method4 and disable about Accounting Service Command')NEWLINEaacAccountingServiceCommandOperator = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, -1))).clone(namedValues=NamedValues(("method1", 0), ("method2", 1), ("method3", 2), ("method4", 3), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandOperator.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandOperator.setDescription('This object indicates aac Accounting Command Operato is method1, method2, method3 , method4 and disable about Accounting Service Command')NEWLINEaacAccountingServiceCommandPoweruser = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, -1))).clone(namedValues=NamedValues(("method1", 0), ("method2", 1), ("method3", 2), ("method4", 3), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandPoweruser.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandPoweruser.setDescription('This object indicates aac Accounting Command Power user is method1, method2, method3 , method4 and disable about Accounting Service Command')NEWLINEaacAccountingServiceCommandUser = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, -1))).clone(namedValues=NamedValues(("method1", 0), ("method2", 1), ("method3", 2), ("method4", 3), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandUser.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandUser.setDescription('This object indicates aac Accounting Command User is method1, method2, method3 , method4 and disable about Accounting Service Command')NEWLINEaacServerPasswordEncryption = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerPasswordEncryption.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerPasswordEncryption.setDescription('This object is used to configure server password encryption status.')NEWLINEmcastFilterPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49, 1), )NEWLINEif mibBuilder.loadTexts: mcastFilterPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mcastFilterPortTable.setDescription('A table to control multicast filtering modes.')NEWLINEmcastFilterPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mcastFilterPortIndex"))NEWLINEif mibBuilder.loadTexts: mcastFilterPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mcastFilterPortEntry.setDescription('An entry appears in this table for each interface in the mcastFiltertem. Index to the table is the interface index of the port.')NEWLINEmcastFilterPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28)))NEWLINEif mibBuilder.loadTexts: mcastFilterPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: mcastFilterPortIndex.setDescription('Interface index of the port for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEmcastFilterPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("forward", 1), ("filter", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mcastFilterPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: mcastFilterPortType.setDescription('Configures the multicast filtering modes as below : forward -Forwards all unregistered groups. filter -Filters all unregistered groups.')NEWLINEstaticARPTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2), )NEWLINEif mibBuilder.loadTexts: staticARPTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPTable.setDescription('A list of the Static MACs')NEWLINEstaticARPEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "staticARPIP"), (0, "DES-1210-28MEbx", "staticARPMac"))NEWLINEif mibBuilder.loadTexts: staticARPEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPEntry.setDescription('A Static MAC entry containing the mac and forwarding port.')NEWLINEstaticARPIP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2, 1, 2), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticARPIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPIP.setDescription('The VLAN ID of the static ARP IP.')NEWLINEstaticARPMac = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticARPMac.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPMac.setDescription('The MAC address associated of the static ARP entry.')NEWLINEstaticARPRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2, 1, 5), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticARPRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPRowStatus.setDescription('The status of an entry in the Static ARP Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available. The trunk member port can not set up static ARP.')NEWLINEsysGratuitousARPGlobalSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 1))NEWLINEsysGratuitousARPSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2))NEWLINEsysGratuitousARPIPIfStatusUp = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPIPIfStatusUp.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPIPIfStatusUp.setDescription('This object indicates Send On IP Interface Status Up is enabled or disabled.')NEWLINEsysGratuitousARPDuplicateIPDetected = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPDuplicateIPDetected.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPDuplicateIPDetected.setDescription('This object indicates Send On Duplicate IP Detected is enabled or disabled.')NEWLINEsysGratuitousARPLearning = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPLearning.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPLearning.setDescription('This object indicates Gratuitous ARP Learning is enabled or disabled.')NEWLINEsysGratuitousARPTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2, 1), )NEWLINEif mibBuilder.loadTexts: sysGratuitousARPTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPTable.setDescription('Set/Add Gratuitous ARP interface name and interval time.')NEWLINEsysGratuitousARPEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysGratuitousARPIFName"))NEWLINEif mibBuilder.loadTexts: sysGratuitousARPEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPEntry.setDescription('The entry of gratuitous ARP!')NEWLINEsysGratuitousARPIFName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2, 1, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 24))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPIFName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPIFName.setDescription('Interface name.')NEWLINEsysGratuitousARPInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPInterval.setDescription('Gratuitous ARP interval time for each interface.')NEWLINEagentCPUutilization = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 1))NEWLINEagentMEMutilization = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 2))NEWLINEagentCPUutilizationIn5sec = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 1, 1), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn5sec.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn5sec.setDescription('The time scale is set at 5 second intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentCPUutilizationIn1min = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 1, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn1min.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn1min.setDescription('The time scale is set at 1 minute intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentCPUutilizationIn5min = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 1, 3), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn5min.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn5min.setDescription('The time scale is set at 5 minute intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentMEMutilizationIn5sec = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 2, 1), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn5sec.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn5sec.setDescription('The time scale is set at 5 second intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentMEMutilizationIn1min = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 2, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn1min.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn1min.setDescription('The time scale is set at 1 minute intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentMEMutilizationIn5min = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 2, 3), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn5min.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn5min.setDescription('The time scale is set at 5 minute intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEl2PTState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: l2PTState.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTState.setDescription('This object indicates the global state of Layer 2 protocol tunneling.')NEWLINEl2PTPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2), )NEWLINEif mibBuilder.loadTexts: l2PTPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTPortTable.setDescription('A table that cont ains the cable situation for each port.')NEWLINEl2PTEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "l2PTPortIndex"))NEWLINEif mibBuilder.loadTexts: l2PTEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTEntry.setDescription('A list of cable situations for each port on the device.')NEWLINEl2PTPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28)))NEWLINEif mibBuilder.loadTexts: l2PTPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTPortIndex.setDescription('This object indicates the port number. For all machines give maximum port number.')NEWLINEl2PTPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("uni", 2), ("nni", 3))).clone('none')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: l2PTPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTPortType.setDescription("This object indicates the Layer 2 protocol tunneling port type. The 'none' value indicates that the port is normal. Layer 2 protocol tunneling is disabled on this port. The 'uni' value indicates that the port is connected to the customer site. A Layer 2 PDU received on a UNI port can be tunneled to a remote customer site across the provider network. The 'nni' value indicates that the port is connected to the provider network. A Tunneled Layer 2 PDU received on an NNI port will be restored to its original format.")NEWLINEl2PTProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2, 1, 3), Bits().clone(namedValues=NamedValues(("stp", 0), ("gvrp", 1), ("macCC", 2), ("macCD", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: l2PTProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTProtocol.setDescription("This object indicates the tunneled protocols on this port. This object can only be applied on a UNI port. If the 'stp' BIT is set, the STP BPDU will be tunneled. If the 'gvrp' BIT is set, the GVRP PDU will be tunneled. If the 'mac-01-00-0C-CC-CC-CC' BIT is set, the PDU with the destination MAC address 01-00-0C-CC-CC-CC will be tunneled . If the 'mac-01-00-0C-CC-CC-CD' BIT is set, then the PDU with the destination MAC address 01-00-0C-CC-CC-CD will be tunneled.")NEWLINEl2PTThresholdTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 3), )NEWLINEif mibBuilder.loadTexts: l2PTThresholdTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTThresholdTable.setDescription('This table contains the protocol tunneling threshold of a UNI port.')NEWLINEl2PTThresholdEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "l2PTPortIndex"), (0, "DES-1210-28MEbx", "l2PTProtocolIndex"))NEWLINEif mibBuilder.loadTexts: l2PTThresholdEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTThresholdEntry.setDescription('A list with the Layer2 Protocol tunneling threshold.')NEWLINEl2PTProtocolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("stp", 1), ("gvrp", 2), ("macCC", 3), ("macCD", 4))))NEWLINEif mibBuilder.loadTexts: l2PTProtocolIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTProtocolIndex.setDescription('This object indicates the tunneled protocol of the port.')NEWLINEl2PTDropThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: l2PTDropThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTDropThreshold.setDescription('This object indicates the drop threshold for a given protocol on a UNI port. If the arrival rate of a tunneled protocol has reached its threshold, the received PDUs of this protocol will be dropped. The value 0 indicates there is no threshold for the protocol.')NEWLINEipv4smtpState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpState.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4smtpState.setDescription('Enable or Disable SMTP function.')NEWLINEipv4smtpServerAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpServerAddr.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4smtpServerAddr.setDescription("SMTP Server's IP Address")NEWLINEipv4smtpServerPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 3), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpServerPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4smtpServerPort.setDescription("SMTP Server's port")NEWLINEipv4smtpSelfMailAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpSelfMailAddr.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4smtpSelfMailAddr.setDescription("The sender's (DUT) mail address .")NEWLINEipv4smtpRecvMailAddrTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5), )NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrTable.setDescription("Receivers' mail address table.")NEWLINEipv4smtpRecvMailAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4smtpRecvMailAddrIndex"))NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrEntry.setDescription("Receivers' mail address entry.")NEWLINEipv4smtpRecvMailAddrIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrIndex.setDescription("Receivers' mail address index (1~8).")NEWLINEipv4smtpRecvMailAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5, 1, 2), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddr.setDescription("Receivers' mail address.")NEWLINEipv4smtpRecvMailAddrStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5, 1, 3), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrStatus.setDescription("Rowstatus of the receiver's mail address.")NEWLINEsysSMTPServerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6))NEWLINEsmtpState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpState.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpState.setDescription('Enable or Disable SMTP function.')NEWLINEsmtpServerAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 2), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpServerAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpServerAddr.setDescription("SMTP Server's IP Address")NEWLINEsmtpServerAddrType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpServerAddrType.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpServerAddrType.setDescription("SMTP Server's Address type.")NEWLINEsmtpServerAddrInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpServerAddrInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpServerAddrInterfaceName.setDescription('Specifies the interface name when the smtpServerAddrInterfaceName is linklocal address.')NEWLINEsmtpServerPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 5), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpServerPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpServerPort.setDescription("SMTP Server's port")NEWLINEsmtpSelfMailAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 6), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpSelfMailAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpSelfMailAddr.setDescription("The sender's (DUT) mail address .")NEWLINEsmtpRecvMailAddrTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7), )NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrTable.setDescription("Receivers' mail address table.")NEWLINEsmtpRecvMailAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7, 1), ).setIndexNames((0, "DES-1210-28MEbx", "smtpRecvMailAddrIndex"))NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrEntry.setDescription("Receivers' mail address entry.")NEWLINEsmtpRecvMailAddrIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrIndex.setDescription("Receivers' mail address index (1~8).")NEWLINEsmtpRecvMailAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7, 1, 2), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddr.setDescription("Receivers' mail address.")NEWLINEsmtpRecvMailAddrStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7, 1, 3), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrStatus.setDescription("Rowstatus of the receiver's mail address.")NEWLINEigmpMulticastVlanStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanStatus.setDescription('Enable/Disable IGMP Multicast Vlan function.')NEWLINEigmpMulticastVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2), )NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanTable.setDescription('Information about the IGMP snooping multicast VLAN table.')NEWLINEigmpMulticastVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igmpMulticastVlanid"))NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanEntry.setDescription('The entry of igmpMulticastVlanTable.')NEWLINEigmpMulticastVlanid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanid.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanid.setDescription('This object indicates the VLAN ID of the IGMP snooping multicast VLAN entry.')NEWLINEigmpMulticastVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanName.setDescription('This object indicates the VLAN name of the IGMP snooping multicast VLAN entry.')NEWLINEigmpMulticastVlanSourcePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanSourcePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanSourcePort.setDescription('This object indicates the port list of the source ports of the IGMP snooping multicast VLAN. The source ports will be set as tag ports of the VLAN entry and the IGMP control messages received from the member ports will be forwarded to the source ports.')NEWLINEigmpMulticastVlanMemberPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanMemberPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanMemberPort.setDescription('This object indicates the port list of the member ports of the IGMP snooping multicast VLAN. The source ports will be set as untagged ports of the VLAN entry and the IGMP control messages received from the member ports will be forwarded to the source ports.')NEWLINEigmpMulticastVlanTagMemberPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 5), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanTagMemberPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanTagMemberPort.setDescription('This object indicates the port list of the tag member ports of the IGMP snooping multicast VLAN.')NEWLINEigmpMulticastVlanUntaggedSourcePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanUntaggedSourcePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanUntaggedSourcePort.setDescription('This object indicates the port list of the untag source ports of the IGMP snooping multicast VLAN.')NEWLINEigmpMulticastVlanState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanState.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanState.setDescription('This object can be used to enable or disable the IGMP snooping multicast VLAN.')NEWLINEigmpMulticastVlanReplaceSourceIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 8), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanReplaceSourceIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanReplaceSourceIp.setDescription('The replacement source IP of this multicast VLAN.')NEWLINEigmpMulticastVlanRemapPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanRemapPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanRemapPriority.setDescription('The remap priority of this multicast VLAN.')NEWLINEigmpMulticastVlanReplacePriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanReplacePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanReplacePriority.setDescription('The replacement priority of this multicast VLAN.')NEWLINEigmpMulticastVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 11), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEigmpMulticastVlanGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3), )NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupTable.setDescription('The table containing the IGMP snooping multicast VLAN group information')NEWLINEigmpMulticastVlanGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igmpMulticastVlanGroupVid"), (0, "DES-1210-28MEbx", "igmpMulticastVlanGroupFromIp"), (0, "DES-1210-28MEbx", "igmpMulticastVlanGroupToIp"))NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupEntry.setDescription('Information about the current IGMP snooping multicast VLAN group.')NEWLINEigmpMulticastVlanGroupVid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupVid.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupVid.setDescription('This object indicates the VID of the IGMP snooping multicast VLAN group.')NEWLINEigmpMulticastVlanGroupFromIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1, 2), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupFromIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupFromIp.setDescription('Specifies the multicast address list for this VLAN.')NEWLINEigmpMulticastVlanGroupToIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1, 3), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupToIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupToIp.setDescription('Specifies the multicast address list for this VLAN.')NEWLINEigmpMulticastVlanGroupStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupStatus.setDescription('This object indicates the status of this entry.')NEWLINEmulticastVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4), )NEWLINEif mibBuilder.loadTexts: multicastVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanTable.setDescription('Information about the IGMP/MLD snooping multicast VLAN table.')NEWLINEmulticastVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "multicastVlanid"))NEWLINEif mibBuilder.loadTexts: multicastVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanEntry.setDescription('The entry of multicastVlanTable.')NEWLINEmulticastVlanid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanid.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanid.setDescription('This object indicates the VLAN ID of the IGMP/MLD snooping multicast VLAN entry.')NEWLINEmulticastVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: multicastVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanName.setDescription('This object indicates the VLAN name of the IGMP/MLD snooping multicast VLAN entry.')NEWLINEmulticastVlanSourcePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanSourcePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanSourcePort.setDescription('This object indicates the port list of the source ports of the IGMP/MLD snooping multicast VLAN. The source ports will be set as tag ports of the VLAN entry and the IGMP control messages received from themember ports will be forwarded to the source ports.')NEWLINEmulticastVlanMemberPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanMemberPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanMemberPort.setDescription('This object indicates the port list of the member ports of the IGMP/MLD snooping multicast VLAN. The source ports will be set as untagged ports of the VLAN entry and the IGMP control messages received from themember ports will be forwarded to the source ports.')NEWLINEmulticastVlanTagMemberPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 5), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanTagMemberPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanTagMemberPort.setDescription('This object indicates the port list of the tag member ports of the IGMP/MLD snooping multicast VLAN.')NEWLINEmulticastVlanUntaggedSourcePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanUntaggedSourcePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanUntaggedSourcePort.setDescription('This object indicates the port list of the untag source ports of the IGMP/MLD snooping multicast VLAN.')NEWLINEmulticastVlanState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanState.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanState.setDescription('This object can be used to enable or disable the IGMP/MLD snooping multicast VLAN.')NEWLINEmulticastVlanIgmpReplaceSourceIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 8), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanIgmpReplaceSourceIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanIgmpReplaceSourceIp.setDescription('The replacement source IP of this IGMP snooping multicast VLAN.')NEWLINEmulticastVlanMldReplaceSourceIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 9), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanMldReplaceSourceIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanMldReplaceSourceIp.setDescription('The replacement source IP of this MLD snooping multicast VLAN.')NEWLINEmulticastVlanRemapPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanRemapPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanRemapPriority.setDescription('The remap priority of this multicast VLAN.')NEWLINEmulticastVlanReplacePriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanReplacePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanReplacePriority.setDescription('The replacement priority of this multicast VLAN.')NEWLINEmulticastVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 12), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: multicastVlanRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEmulticastVlanGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5), )NEWLINEif mibBuilder.loadTexts: multicastVlanGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupTable.setDescription('The table containing the IGMP/MLD snooping multicast VLAN group information')NEWLINEmulticastVlanGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "multicastVlanGroupVid"), (0, "DES-1210-28MEbx", "multicastVlanGroupIpType"), (0, "DES-1210-28MEbx", "multicastVlanGroupFromIp"), (0, "DES-1210-28MEbx", "multicastVlanGroupToIp"))NEWLINEif mibBuilder.loadTexts: multicastVlanGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupEntry.setDescription('The entry of multicastVlanGroupTable.')NEWLINEmulticastVlanGroupVid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupVid.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupVid.setDescription('This object indicates the VID of the IGMP/MLD snooping multicast VLAN group.')NEWLINEmulticastVlanGroupIpType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupIpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupIpType.setDescription('Type of specifies the multicast address list for this VLAN.')NEWLINEmulticastVlanGroupFromIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 3), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupFromIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupFromIp.setDescription('Specifies the multicast address list for this VLAN.')NEWLINEmulticastVlanGroupToIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 4), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupToIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupToIp.setDescription('Specifies the multicast address list for this VLAN.')NEWLINEmulticastVlanGroupStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 5), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupStatus.setDescription('This object indicates the status of this entry.')NEWLINEpppoeGlobalState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoeGlobalState.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoeGlobalState.setDescription('PPPoE global state')NEWLINEpppoePortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2), )NEWLINEif mibBuilder.loadTexts: pppoePortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortTable.setDescription('A table to control PPPoE features of the device.')NEWLINEpppoePortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "pppoePortIndex"))NEWLINEif mibBuilder.loadTexts: pppoePortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortEntry.setDescription('An entry appears in PPPoE table for each interface in the system.')NEWLINEpppoePortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 6))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: pppoePortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortIndex.setDescription('Interface index of the port for the configuration in this entry applies.')NEWLINEpppoePortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortState.setDescription('PPPoE per port state')NEWLINEpppoePortCircuitIDType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("ip", 0), ("mac", 1), ("udf", 2), ("vendor2", 3), ("vendor3", 4)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortCircuitIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortCircuitIDType.setDescription('PPPoE per port circuit ID type')NEWLINEpppoePortUDFString = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortUDFString.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortUDFString.setDescription('PPPoE per port UDF string')NEWLINEpppoePortCircuitIDVendor3String = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortCircuitIDVendor3String.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortCircuitIDVendor3String.setDescription('PPPoE per port circuit ID vendor3 string')NEWLINEpppoePortRemoteIDType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("default", 0), ("vendor2", 1), ("vendor3", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortRemoteIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortRemoteIDType.setDescription('PPPoE per port remote ID type')NEWLINEpppoePortRemoteIDVendor3String = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortRemoteIDVendor3String.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortRemoteIDVendor3String.setDescription('PPPoE per port remote ID vendor3 string')NEWLINErmonGlobalState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: rmonGlobalState.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonGlobalState.setDescription('This object is for enabling or disabling RMON function.')NEWLINErmonStatistics = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2))NEWLINErmonHistory = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3))NEWLINErmonAlarm = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4))NEWLINErmonEvent = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5))NEWLINErmonStatsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1), )NEWLINEif mibBuilder.loadTexts: rmonStatsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsTable.setDescription('A list of Ethernet statistics entries.')NEWLINErmonStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "rmonStatsIndex"))NEWLINEif mibBuilder.loadTexts: rmonStatsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsEntry.setDescription('A collection of statistics kept for a particular Ethernet interface. As an example, an instance of the etherStatsPkts object might be named etherStatsPkts.1')NEWLINErmonStatsIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: rmonStatsIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsIndex.setDescription('The value of this object uniquely identifies this etherStats entry.')NEWLINErmonStatsDataSource = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonStatsDataSource.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsDataSource.setDescription('This object identifies the source of the data that this etherStats entry is configured to analyze. This source can be any ethernet interface on this device. In order to identify a particular interface, this object shall identify the instance of the ifIndex object, defined in RFC 2233 [17], for the desired interface. For example, if an entry were to receive data from interface #1, this object would be set to ifIndex.1. The statistics in this group reflect all packets on the local network segment attached to the identified interface. An agent may or may not be able to tell if fundamental changes to the media of the interface have occurred and necessitate an invalidation of this entry. For example, a hot-pluggable ethernet card could be pulled out and replaced by a token-ring card. In such a case, if the agent has such knowledge of the change, it is recommended that it invalidate this entry. This object may not be modified if the associated etherStatsStatus object is equal to valid(1).')NEWLINErmonStatsOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1, 3), OwnerString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonStatsOwner.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsOwner.setDescription('The entity that configured this entry and is therefore using the resources assigned to it.')NEWLINErmonStatsStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1, 4), RmonStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonStatsStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsStatus.setDescription('The status of this etherStats entry.')NEWLINErmonHistoryTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1), )NEWLINEif mibBuilder.loadTexts: rmonHistoryTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryTable.setDescription('A list of history control entries.')NEWLINErmonHistoryEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "rmonHistoryIndex"))NEWLINEif mibBuilder.loadTexts: rmonHistoryEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryEntry.setDescription('A list of parameters that set up a periodic sampling of statistics. As an example, an instance of the historyControlInterval object might be named historyControlInterval.2')NEWLINErmonHistoryIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: rmonHistoryIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryIndex.setDescription('An index that uniquely identifies an entry in the historyControl table. Each such entry defines a set of samples at a particular interval for an interface on the device.')NEWLINErmonHistoryDataSource = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryDataSource.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryDataSource.setDescription('This object identifies the source of the data for which historical data was collected and placed in a media-specific table on behalf of this historyControlEntry. This source can be any interface on this device. In order to identify a particular interface, this object shall identify the instance of the ifIndex object, defined in RFC 2233 [17], for the desired interface. For example, if an entry were to receive data from interface #1, this object would be set to ifIndex.1. The statistics in this group reflect all packets on the local network segment attached to the identified interface. An agent may or may not be able to tell if fundamental changes to the media of the interface have occurred and necessitate an invalidation of this entry. For example, a hot-pluggable ethernet card could be pulled out and replaced by a token-ring card. In such a case, if the agent has such knowledge of the change, it is recommended that it invalidate this entry. This object may not be modified if the associated historyControlStatus object is equal to valid(1).')NEWLINErmonHistoryBucketsRequested = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(50)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryBucketsRequested.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryBucketsRequested.setDescription('The requested number of discrete time intervals over which data is to be saved in the part of the media-specific table associated with this historyControlEntry. When this object is created or modified, the probe should set historyControlBucketsGranted as closely to this object as is possible for the particular probe implementation and available resources.')NEWLINErmonHistoryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3600)).clone(1800)).setUnits('Seconds').setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryInterval.setDescription("The interval in seconds over which the data is sampled for each bucket in the part of the media-specific table associated with this historyControlEntry. This interval can be set to any number of seconds between 1 and 3600 (1 hour). Because the counters in a bucket may overflow at their maximum value with no indication, a prudent manager will take into account the possibility of overflow in any of the associated counters. It is important to consider the minimum time in which any counter could overflow on a particular media type and set the historyControlInterval object to a value less than this interval. This is typically most important for the 'octets' counter in any media-specific table. For example, on an Ethernet network, the etherHistoryOctets counter could overflow in about one hour at the Ethernet's maximum utilization. This object may not be modified if the associated historyControlStatus object is equal to valid(1).")NEWLINErmonHistoryOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 5), OwnerString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryOwner.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryOwner.setDescription('The entity that configured this entry and is therefore using the resources assigned to it.')NEWLINErmonHistoryStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 6), RmonStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryStatus.setDescription('The status of this historyControl entry. Each instance of the media-specific table associated with this historyControlEntry will be deleted by the agent if this historyControlEntry is not equal to valid(1).')NEWLINErmonAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1), )NEWLINEif mibBuilder.loadTexts: rmonAlarmTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmTable.setDescription('A list of alarm entries.')NEWLINErmonAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "rmonAlarmIndex"))NEWLINEif mibBuilder.loadTexts: rmonAlarmEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmEntry.setDescription('A list of parameters that set up a periodic checking for alarm conditions. For example, an instance of the alarmValue object might be named alarmValue.8')NEWLINErmonAlarmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: rmonAlarmIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmIndex.setDescription('An index that uniquely identifies an entry in the alarm table. Each such entry defines a diagnostic sample at a particular interval for an object on the device.')NEWLINErmonAlarmInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 2), Integer32()).setUnits('Seconds').setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmInterval.setDescription('The interval in seconds over which the data is sampled and compared with the rising and falling thresholds. When setting this variable, care should be taken in the case of deltaValue sampling - the interval should be set short enough that the sampled variable is very unlikely to increase or decrease by more than 2^31 - 1 during a single sampling interval. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmVariable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 3), ObjectIdentifier()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmVariable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmVariable.setDescription('The object identifier of the particular variable to be sampled. Only variables that resolve to an ASN.1 primitive type of INTEGER (INTEGER, Integer32, Counter32, Counter64, Gauge, or TimeTicks) may be sampled. Because SNMP access control is articulated entirely in terms of the contents of MIB views, no access control mechanism exists that can restrict the value of this object to identify only those objects that exist in a particular MIB view. Because there is thus no acceptable means of restricting the read access that could be obtained through the alarm mechanism, the probe must only grant write access to this object in those views that have read access to all objects on the probe. During a set operation, if the supplied variable name is not available in the selected MIB view, a badValue error must be returned. If at any time the variable name of an established alarmEntry is no longer available in the selected MIB view, the probe must change the status of this alarmEntry to invalid(4). This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmSampleType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("absoluteValue", 1), ("deltaValue", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmSampleType.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmSampleType.setDescription('The method of sampling the selected variable and calculating the value to be compared against the thresholds. If the value of this object is absoluteValue(1), the value of the selected variable will be compared directly with the thresholds at the end of the sampling interval. If the value of this object is deltaValue(2), the value of the selected variable at the last sample will be subtracted from the current value, and the difference compared with the thresholds. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmRisingThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 5), Integer32()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmRisingThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmRisingThreshold.setDescription('A threshold for the sampled statistic. When the current sampled value is greater than or equal to this threshold, and the value at the last sampling interval was less than this threshold, a single event will be generated. A single event will also be generated if the first sample after this entry becomes valid is greater than or equal to this threshold and the associated alarmStartupAlarm is equal to risingAlarm(1) or risingOrFallingAlarm(3). After a rising event is generated, another such event will not be generated until the sampled value falls below this threshold and reaches the alarmFallingThreshold. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmFallingThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 6), Integer32()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmFallingThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmFallingThreshold.setDescription('A threshold for the sampled statistic. When the current sampled value is less than or equal to this threshold, and the value at the last sampling interval was greater than this threshold, a single event will be generated. A single event will also be generated if the first sample after this entry becomes valid is less than or equal to this threshold and the associated alarmStartupAlarm is equal to fallingAlarm(2) or risingOrFallingAlarm(3). After a falling event is generated, another such event will not be generated until the sampled value rises above this threshold and reaches the alarmRisingThreshold. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmRisingEventIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmRisingEventIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmRisingEventIndex.setDescription('The index of the eventEntry that is used when a rising threshold is crossed. The eventEntry identified by a particular value of this index is the same as identified by the same value of the eventIndex object. If there is no corresponding entry in the eventTable, then no association exists. In particular, if this value is zero, no associated event will be generated, as zero is not a valid event index. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmFallingEventIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmFallingEventIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmFallingEventIndex.setDescription('The index of the eventEntry that is used when a falling threshold is crossed. The eventEntry identified by a particular value of this index is the same as identified by the same value of the eventIndex object. If there is no corresponding entry in the eventTable, then no association exists. In particular, if this value is zero, no associated event will be generated, as zero is not a valid event index. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 9), OwnerString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmOwner.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmOwner.setDescription('The entity that configured this entry and is therefore using the resources assigned to it.')NEWLINErmonAlarmStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 10), RmonStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmStatus.setDescription('The status of this alarm entry.')NEWLINErmonEventTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1), )NEWLINEif mibBuilder.loadTexts: rmonEventTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventTable.setDescription('A list of events to be generated.')NEWLINErmonEventEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "rmonEventIndex"))NEWLINEif mibBuilder.loadTexts: rmonEventEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventEntry.setDescription('A set of parameters that describe an event to be generated when certain conditions are met. As an example, an instance of the eventLastTimeSent object might be named eventLastTimeSent.6')NEWLINErmonEventIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: rmonEventIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventIndex.setDescription('An index that uniquely identifies an entry in the event table. Each such entry defines one event that is to be generated when the appropriate conditions occur.')NEWLINErmonEventDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 127))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventDescription.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventDescription.setDescription('A comment describing this event entry.')NEWLINErmonEventType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("log", 2), ("snmptrap", 3), ("logandtrap", 4)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventType.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventType.setDescription('The type of notification that the probe will make about this event. In the case of log, an entry is made in the log table for each event. In the case of snmp-trap, an SNMP trap is sent to one or more management stations.')NEWLINErmonEventCommunity = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 127))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventCommunity.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventCommunity.setDescription('If an SNMP trap is to be sent, it will be sent to the SNMP community specified by this octet string.')NEWLINErmonEventOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 5), OwnerString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventOwner.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventOwner.setDescription("The entity that configured this entry and is therefore using the resources assigned to it. If this object contains a string starting with 'monitor' and has associated entries in the log table, all connected management stations should retrieve those log entries, as they may have significance to all management stations connected to this device")NEWLINErmonEventStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 6), RmonStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventStatus.setDescription('The status of this event entry. If this object is not equal to valid(1), all associated log entries shall be deleted by the agent.')NEWLINEneighborTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1), )NEWLINEif mibBuilder.loadTexts: neighborTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborTable.setDescription('A list of the Neighbor Cache Table.')NEWLINEneighborEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "neighborIfindex"), (0, "DES-1210-28MEbx", "neighborIPv6Addr"), (0, "DES-1210-28MEbx", "neighborMACAddr"))NEWLINEif mibBuilder.loadTexts: neighborEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborEntry.setDescription('A Neighbor cache entry containing the ifindex and ipv6 addr.')NEWLINEneighborIfindex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborIfindex.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborIfindex.setDescription('The interface index of the Neighbor entry. Must be conform to the existing interface name.')NEWLINEneighborIPv6Addr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 2), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborIPv6Addr.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborIPv6Addr.setDescription('Allows the entry of an IP address that will be a Neighbor entry into the Neighbor Cache Table.')NEWLINEneighborMACAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborMACAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborMACAddr.setDescription('The MAC address associated of the Neighbor entry.')NEWLINEneighborType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("static", 1), ("dynamic", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborType.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborType.setDescription('The type associated of the Neighbor entry.')NEWLINEneighborCacheState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("static", 1), ("reachable", 2), ("incomplete", 3), ("stale", 4), ("delay", 5), ("probe", 6), ("notinservice", 7)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborCacheState.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborCacheState.setDescription('The type associated of the Neighbor entry.')NEWLINEneighborActiveStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("active", 1), ("inactive", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborActiveStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborActiveStatus.setDescription('The active status of the Neighbor entry.')NEWLINEneighborRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 7), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: neighborRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborRowStatus.setDescription('The status of an entry in the Neighbor Cache Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINEdhcpv6RelayControl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 1))NEWLINEdhcpv6RelayManagement = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2))NEWLINEdhcpv6RelayOption37 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3))NEWLINEdhcpv6RelayOption38 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4))NEWLINEdhcpv6RelayOption18 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 5))NEWLINEdhcpv6RelayState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayState.setDescription('This object indicates DHCPv6 relay function is enabled or disabled.')NEWLINEdhcpv6RelayHopCount = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayHopCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayHopCount.setDescription('This object indicates the maximum number of router hops that the DHCPv6 packets can cross.')NEWLINEdhcpv6RelayInterfaceSettingsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1), )NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsTable.setDescription('This table indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpv6RelayInterfaceSettingsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpv6RelayInterface"), (0, "DES-1210-28MEbx", "dhcpv6RelayServerIP"))NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsEntry.setDescription('A list of information indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpv6RelayInterface = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 12))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterface.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterface.setDescription('This object indicates the maximum number of router hops that the DHCPv6 packets can cross.')NEWLINEdhcpv6RelayServerIP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1, 1, 2), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayServerIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayServerIP.setDescription('This object indicates the DHCP server IP address.')NEWLINEdhcpv6RelayInterfaceSettingsRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEdhcpv6RelayOption37State = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37State.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37State.setDescription('This object indicates DHCPv6 relay option 37 function is enabled or disabled.')NEWLINEdhcpv6RelayOption37CheckState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37CheckState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37CheckState.setDescription('This object indicates DHCPv6 relay option 37 Check function is enabled or disabled.')NEWLINEdhcpv6RelayOption37RemoteIDType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("default", 0), ("cid-with-user-define", 1), ("user-define", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37RemoteIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37RemoteIDType.setDescription('This object indicates the type of remote ID.')NEWLINEdhcpv6RelayOption37RemoteID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3, 4), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37RemoteID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37RemoteID.setDescription('This object displays the current remote ID of the device. If RemoteIDType is set to default, the value will be the MAC address of the device, and this object cannot be modified. If RemoteIDType is set to user-defined, a new value can be written to this object.')NEWLINEdhcpv6RelayOpt38Table = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1), )NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38Table.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38Table.setDescription('A table to control port security features of the device.')NEWLINEdhcpv6RelayOpt38Entry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpv6RelayOpt38PortIndex"))NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38Entry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38Entry.setDescription('An entry appears in port security table for each interface in the system.')NEWLINEdhcpv6RelayOpt38PortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortIndex.setDescription('The interface index for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEdhcpv6RelayOpt38PortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortState.setDescription('Enable / disable option 38 port state.')NEWLINEdhcpv6RelayOpt38PortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("default", 0), ("user-defined", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortType.setDescription('Configure option 38 port Type.')NEWLINEdhcpv6RelayOpt38PortID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1, 4), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortID.setDescription('Configure option 38 port ID. Only works when type is user-defined')NEWLINEdhcpv6RelayOption18State = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 5, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18State.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18State.setDescription('This object indicates DHCPv6 relay option 18 function is enabled or disabled.')NEWLINEdhcpv6RelayOption18CheckState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 5, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18CheckState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18CheckState.setDescription('This object indicates DHCPv6 relay option 18 Check function is enabled or disabled.')NEWLINEdhcpv6RelayOption18InterfaceIDType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 5, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("default", 0), ("cid", 1), ("vendor1", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18InterfaceIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18InterfaceIDType.setDescription('This object indicates the type of Interface ID.')NEWLINEmacBasedVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1), )NEWLINEif mibBuilder.loadTexts: macBasedVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: macBasedVlanTable.setDescription('A table that contains information on Vlan-MAC address mapping.')NEWLINEmacBasedVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "vlanMacMapIndex"))NEWLINEif mibBuilder.loadTexts: macBasedVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: macBasedVlanEntry.setDescription('Entry that contains Vlan-MAC address mapping.')NEWLINEvlanMacMapIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: vlanMacMapIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapIndex.setDescription('Index of cmMacBasedVlanEntry. This object indicates the mac vlan entry for which the configurations in cmMacBasedVlanEntry is to be done.')NEWLINEvlanMacMapAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 2), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanMacMapAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapAddr.setDescription('The Mac address for which the Vlan mapping is present in the entry.')NEWLINEvlanMacMapAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 3), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanMacMapAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapAddrMask.setDescription('The Mac address for which the Vlan mapping is present in the entry.')NEWLINEvlanMacMapVid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 4), VlanIndex()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanMacMapVid.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapVid.setDescription('The Vlan to which the mac address of this entry is mapped to.')NEWLINEvlanMacStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 5), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: vlanMacStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacStatus.setDescription('The status given to the mac-vlan entry.')NEWLINEvlanMacType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 6), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: vlanMacType.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacType.setDescription('The type given to the mac-vlan entry.')NEWLINEvlanMacMapRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 99), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanMacMapRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapRowStatus.setDescription('The row status of the entry.')NEWLINEmacBasedVlanMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("single", 1), ("range", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macBasedVlanMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: macBasedVlanMethod.setDescription('A method of Vlan-MAC address mapping.')NEWLINEsfpVendorInfoTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1), )NEWLINEif mibBuilder.loadTexts: sfpVendorInfoTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorInfoTable.setDescription('This table indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEsfpVendorInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sfpPortIndex"))NEWLINEif mibBuilder.loadTexts: sfpVendorInfoEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorInfoEntry.setDescription('A list of information indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEsfpPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpPortIndex.setDescription('The available of index for fiber ports.')NEWLINEsfpConnectorType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 2), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpConnectorType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpConnectorType.setDescription('')NEWLINEsfpTranceiverCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 3), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpTranceiverCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpTranceiverCode.setDescription('')NEWLINEsfpBaudRate = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 4), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpBaudRate.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpBaudRate.setDescription('')NEWLINEsfpVendorName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 5), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorName.setDescription('')NEWLINEsfpVendorOui = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 6), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorOui.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorOui.setDescription('')NEWLINEsfpVendorPn = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 7), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorPn.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorPn.setDescription('')NEWLINEsfpVendorRev = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 8), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorRev.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorRev.setDescription('')NEWLINEsfpWavelength = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 9), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpWavelength.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpWavelength.setDescription('')NEWLINEsfpVendorSn = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 10), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorSn.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorSn.setDescription('')NEWLINEsfpDateCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 11), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpDateCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpDateCode.setDescription('')NEWLINEddmCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1))NEWLINEddmInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2))NEWLINEddmPowerUnit = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("mw", 0), ("dbm", 1))).clone('mw')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmPowerUnit.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmPowerUnit.setDescription('This object indicates the TX/RX power global unit.')NEWLINEddmActionMgmtTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2), )NEWLINEif mibBuilder.loadTexts: ddmActionMgmtTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ddmActionMgmtTable.setDescription('This table contains the configuration of the action taken when any parameter exceeds its threshold.')NEWLINEddmActionMgmtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ddmActionPort"))NEWLINEif mibBuilder.loadTexts: ddmActionMgmtEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ddmActionMgmtEntry.setDescription('This is an entry of the swDdmConfigActionTable.')NEWLINEddmActionPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmActionPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmActionPort.setDescription('This object indicates the port. The available of index for fiber ports.')NEWLINEddmActionState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmActionState.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ddmActionState.setDescription('This object indicates the action type.')NEWLINEddmActionShutdown = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("alarm", 1), ("warning", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmActionShutdown.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ddmActionShutdown.setDescription('This object indicates the action type.')NEWLINEddmThresholdMgmtTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3), )NEWLINEif mibBuilder.loadTexts: ddmThresholdMgmtTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmThresholdMgmtTable.setDescription('This table contains DDM temperature configuration information.')NEWLINEddmThresholdMgmtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ddmThresholdPort"), (0, "DES-1210-28MEbx", "ddmThresholdType"))NEWLINEif mibBuilder.loadTexts: ddmThresholdMgmtEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmThresholdMgmtEntry.setDescription('This is an entry of the swDdmConfigThresholdTable.')NEWLINEddmThresholdPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmThresholdPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmThresholdPort.setDescription('This object indicates the port. The available of index for fiber ports.')NEWLINEddmThresholdType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("temperature", 0), ("voltage", 1), ("bias", 2), ("txPower", 3), ("rxPower", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmThresholdType.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmThresholdType.setDescription('This object indicates the threshold type.')NEWLINEddmHighAlarm = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 3), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmHighAlarm.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmHighAlarm.setDescription('This object indicates the high alarm threshold value to be configured. As the value is a floating point data type, the DisplayString type is used to define this parameter.')NEWLINEddmLowAlarm = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 4), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmLowAlarm.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmLowAlarm.setDescription('This object indicates the low alarm threshold value to be configured. As the value is a floating data type, the DisplayString type is used to define this parameter.')NEWLINEddmHighWarning = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 5), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmHighWarning.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmHighWarning.setDescription('This object indicates the high warning threshold value to be configured. As the value is a floating data type, the DisplayString type is used to define this parameter.')NEWLINEddmLowWarning = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 6), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmLowWarning.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmLowWarning.setDescription('This object indicates the low warning threshold value to be configured. As the value is a floating data type, the DisplayString type is used to define this parameter.')NEWLINEddmStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1))NEWLINEddmStatusTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1), )NEWLINEif mibBuilder.loadTexts: ddmStatusTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmStatusTable.setDescription('This table contains the DDM status information.')NEWLINEddmStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ddmStatusPort"))NEWLINEif mibBuilder.loadTexts: ddmStatusEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmStatusEntry.setDescription('This is an entry of the ddmStatusTable.')NEWLINEddmStatusPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmStatusPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmStatusPort.setDescription('This object indicates the port. The available of index for fiber ports.')NEWLINEddmTemperature = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 2), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmTemperature.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmTemperature.setDescription('This object indicates the real time value of the temperature. As the value is a floating point data type, the DisplayString type is used to define this parameter.')NEWLINEddmVoltage = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 3), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmVoltage.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmVoltage.setDescription('This object indicates the real time value of the supply voltage. As the value value is a floating point data type, the DisplayString type is used to define this parameter.')NEWLINEddmBiasCurrent = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 4), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmBiasCurrent.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmBiasCurrent.setDescription('This object indicates the real time value of the tx bias.')NEWLINEddmTxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 5), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmTxPower.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmTxPower.setDescription('This object indicates the real time value of the tx power. As the value is a floating point data type, the DisplayString type is used to define this parameter.')NEWLINEddmRxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 6), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmRxPower.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmRxPower.setDescription('This object indicates the real time value of the rx power. As the value is a floating data type, the DisplayString type is used to define this parameter.')NEWLINEftpFwTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1))NEWLINEftpConfigTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2))NEWLINEftpFwServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwServerIpAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwServerIpAddress.setDescription("The FTP server's IPv4 address or IPv6 address is used to upload or download firmware.")NEWLINEftpFwImageFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwImageFileName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwImageFileName.setDescription('Firmware file name used to upload or download firmware.')NEWLINEftpFwUsername = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwUsername.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwUsername.setDescription('FTP username to login FTP.')NEWLINEftpFwPassword = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwPassword.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwPassword.setDescription('FTP password to login FTP.')NEWLINEftpFwPath = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwPath.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwPath.setDescription('FTP path can find file folder.')NEWLINEftpFwPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwPort.setDescription('FTP port to login FTP.')NEWLINEftpFwFTPOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("download", 1), ("upload", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwFTPOperation.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwFTPOperation.setDescription('The FTP operates to perform downloading the firmware image to the unit. This object is used in conjunction with FTP settings')NEWLINEftpFwFTPOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3), ("transmit", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ftpFwFTPOperationStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwFTPOperationStatus.setDescription('The FTP operation status represent firmware backup or upgrade status.')NEWLINEftpConfigServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigServerIpAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigServerIpAddress.setDescription("The FTP server's IPv4 address or IPv6 address is used to upload or download firmware.")NEWLINEftpConfigFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigFileName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigFileName.setDescription('Config file name used to upload or download Config.')NEWLINEftpConfigUsername = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigUsername.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigUsername.setDescription('FTP username to login FTP.')NEWLINEftpConfigPassword = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigPassword.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigPassword.setDescription('FTP password to login FTP.')NEWLINEftpConfigPath = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigPath.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigPath.setDescription('FTP path can find file folder.')NEWLINEftpConfigPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigPort.setDescription('FTP port to login FTP.')NEWLINEftpConfigConfigID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("configID1", 1), ("configID2", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigConfigID.setStatus('current')NEWLINEif mibBuilder.loadTexts: ftpConfigConfigID.setDescription('Config image id can select imageid1 or imageid2 to flash')NEWLINEftpConfigFTPOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("download", 1), ("upload", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigFTPOperation.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigFTPOperation.setDescription('The FTP operates to perform downloading the config image to the unit. This object is used in conjunction with FTP settings')NEWLINEftpConfigFTPOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3), ("transmit", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ftpConfigFTPOperationStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigFTPOperationStatus.setDescription('The FTP operation status represent config backup or upgrade status.')NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", swAuthRadiusServerTable=swAuthRadiusServerTable, stpNewRootTrapStatus=stpNewRootTrapStatus, ipv4sysSNTPDSTEndMon=ipv4sysSNTPDSTEndMon, cpuFilterv6L3RuleProfileNo=cpuFilterv6L3RuleProfileNo, iPv4aacServerAuthKey=iPv4aacServerAuthKey, pppoePortRemoteIDType=pppoePortRemoteIDType, ipv4aclProfileEntry=ipv4aclProfileEntry, sysPortErrPortIndex=sysPortErrPortIndex, ipv4aclQosVlanID=ipv4aclQosVlanID, dlinklldpState=dlinklldpState, laPortControl=laPortControl, cpuFilterProfileStatus=cpuFilterProfileStatus, sfpDateCode=sfpDateCode, impbBlockListMacAddress=impbBlockListMacAddress, swAuthUserName=swAuthUserName, companyDHCPv6Relay=companyDHCPv6Relay, aclL3RuleTcpPshBit=aclL3RuleTcpPshBit, lldpXdot3RemLinkAggEntry=lldpXdot3RemLinkAggEntry, portSecFDBPermanentTable=portSecFDBPermanentTable, aacEnableMethodListEntry=aacEnableMethodListEntry, cpuFilterL3RuleSrcIpAddr=cpuFilterL3RuleSrcIpAddr, trafficCtrlTimeInterval=trafficCtrlTimeInterval, companyQoSGroup=companyQoSGroup, cpuFilterL2RuleDstMacAddrMask=cpuFilterL2RuleDstMacAddrMask, mldsHostTable=mldsHostTable, protocolVlanEntry=protocolVlanEntry, swAuthAuthConfigPortControl=swAuthAuthConfigPortControl, errorSymbolWindow=errorSymbolWindow, ipv4aclUdfOffsetBase1=ipv4aclUdfOffsetBase1, mstCistPortEntry=mstCistPortEntry, iPv4swAuthRadiusServerAuthenticationPort=iPv4swAuthRadiusServerAuthenticationPort, OwnerString=OwnerString, staticAutoLearningList=staticAutoLearningList, VlanIndex=VlanIndex, lldpXdot1RemTable=lldpXdot1RemTable, dhcpBOOTPRelayTimeThreshold=dhcpBOOTPRelayTimeThreshold, ipv4trustedHostEntry=ipv4trustedHostEntry, igmpMulticastVlanRowStatus=igmpMulticastVlanRowStatus, aclL2RuleEntry=aclL2RuleEntry, aclL3RuleAction=aclL3RuleAction, aacAccountingMethod1=aacAccountingMethod1, ftpConfigConfigID=ftpConfigConfigID, tftpCfgTargetServerIpAddress=tftpCfgTargetServerIpAddress, igmpMulticastVlanGroupToIp=igmpMulticastVlanGroupToIp, dhcpBOOTPRelayInterface=dhcpBOOTPRelayInterface, lldpXdot3RemMaxFrameSizeTable=lldpXdot3RemMaxFrameSizeTable, sysDhcpAutoConfigTimeout=sysDhcpAutoConfigTimeout, pppoePortEntry=pppoePortEntry, rmonAlarmFallingEventIndex=rmonAlarmFallingEventIndex, snmpV3GroupSecurityModel=snmpV3GroupSecurityModel, rmonAlarmTable=rmonAlarmTable, sshUserInfoID=sshUserInfoID, snmpTrapCopperLinkUpDown=snmpTrapCopperLinkUpDown, snmpV3CommunityEncryption=snmpV3CommunityEncryption, mldsVlanCfgQuerier=mldsVlanCfgQuerier, ipv4cpuFilterProfileMask=ipv4cpuFilterProfileMask, qinqEntry=qinqEntry, aclUdfOffsetMask2=aclUdfOffsetMask2, neighborActiveStatus=neighborActiveStatus, qosDiffServType31=qosDiffServType31, qosUserPriIndex=qosUserPriIndex, ipv4cpuFilterProfileTable=ipv4cpuFilterProfileTable, ipv4aclQosStatus=ipv4aclQosStatus, sysBPDUAttackRecoverTime=sysBPDUAttackRecoverTime, cosBandwidthCtrlSettings=cosBandwidthCtrlSettings, staticVlanBaseAutoLearnList3k=staticVlanBaseAutoLearnList3k, ipv4sysSNTPDSTStartDay=ipv4sysSNTPDSTStartDay, cableDiagPair1Length=cableDiagPair1Length, ipv4syslogServUDPport=ipv4syslogServUDPport, ipv4sysSNTPTimeSeconds=ipv4sysSNTPTimeSeconds, ipv4aclUdfOffsetBase4=ipv4aclUdfOffsetBase4, lldpXdot3RemLinkAggPortId=lldpXdot3RemLinkAggPortId, ftpConfigServerIpAddress=ftpConfigServerIpAddress, autoFdbMacAddress=autoFdbMacAddress, qosPriSettings=qosPriSettings, lldpPortConfigEntry=lldpPortConfigEntry, lldpXdot3RemPortAutoNegEnabled=lldpXdot3RemPortAutoNegEnabled, ipifV6AddressIpType=ipifV6AddressIpType, ipv4aclUdfOffsetByte4=ipv4aclUdfOffsetByte4, aclProfileArpSenderIpAddrMask=aclProfileArpSenderIpAddrMask, swTimeRangeThursday=swTimeRangeThursday, rmonAlarmStatus=rmonAlarmStatus, igmpMulticastVlanName=igmpMulticastVlanName, cpuFilterL3RuleTable=cpuFilterL3RuleTable, rmonStatsStatus=rmonStatsStatus, rmonHistory=rmonHistory, ddmLowWarning=ddmLowWarning, sshPublKeyRSAAdmin=sshPublKeyRSAAdmin, companySNMPV3=companySNMPV3, staticMac=staticMac, aclL3Rule=aclL3Rule, aacAccountingServiceCommand=aacAccountingServiceCommand, trafficCtrlSettings=trafficCtrlSettings, snmpV3GroupTable=snmpV3GroupTable, ipifV6AddressRowStatus=ipifV6AddressRowStatus, rmonEvent=rmonEvent, sysGratuitousARPEntry=sysGratuitousARPEntry, macNotifyCtrlTable=macNotifyCtrlTable, eoamIfIndex=eoamIfIndex, qinqVlanTranslationSVIDOperation=qinqVlanTranslationSVIDOperation, ddmThresholdMgmtTable=ddmThresholdMgmtTable, stpMaxAge=stpMaxAge, aacServerGroupName=aacServerGroupName, ftpFwImageFileName=ftpFwImageFileName, sshSecurityStatus=sshSecurityStatus, snmpV3viewTreeType=snmpV3viewTreeType, sysLBDVlanLoopEntry=sysLBDVlanLoopEntry, dhcpBOOTPRelayOption82CheckState=dhcpBOOTPRelayOption82CheckState, aclv6L3RuleTable=aclv6L3RuleTable, stpBridgeGlobal=stpBridgeGlobal, neighborMACAddr=neighborMACAddr, laStatus=laStatus, dlinklldpMsgHoldMultiplier=dlinklldpMsgHoldMultiplier, aacAPHttpLoginMethod=aacAPHttpLoginMethod, dhcpv6RelayInterfaceSettingsTable=dhcpv6RelayInterfaceSettingsTable, aclFlowMeterEntry=aclFlowMeterEntry, sysPortMediaType=sysPortMediaType, sysPortMediaTypeOui=sysPortMediaTypeOui, dhcpv6RelayOption37State=dhcpv6RelayOption37State, stpTxHoldCount=stpTxHoldCount, sshMaxSession=sshMaxSession, sysSNTPTimeSeconds=sysSNTPTimeSeconds, swAuthAuthQuietPeriod=swAuthAuthQuietPeriod, sshConnectionTimeout=sshConnectionTimeout, ipv4cpuFilterProfileRuleCount=ipv4cpuFilterProfileRuleCount, securitySSL=securitySSL, bandwidthCtrlSettings=bandwidthCtrlSettings, syslogServSrvStatus=syslogServSrvStatus, sysGratuitousARPGlobalSettings=sysGratuitousARPGlobalSettings, ftpConfigTable=ftpConfigTable, cpuFilterProfileDstPortMask=cpuFilterProfileDstPortMask, cpuFilterv6L3RuleTcpSynBit=cpuFilterv6L3RuleTcpSynBit, cpuFilterProfileMask=cpuFilterProfileMask, ipv4cpuFilterProfileSrcPortMask=ipv4cpuFilterProfileSrcPortMask, impbPortDHCPv6VlanList3k=impbPortDHCPv6VlanList3k, aRPSpoofPreventRowStatus=aRPSpoofPreventRowStatus, aacAuthParamResponseTimeout=aacAuthParamResponseTimeout, iPv4aacServerTimeout=iPv4aacServerTimeout, rmonStatistics=rmonStatistics, sysUser=sysUser, multicastVlanTable=multicastVlanTable, sysLBDRecoverTime=sysLBDRecoverTime, aclv6L3RuleRateLimit=aclv6L3RuleRateLimit, companyAuthGroup=companyAuthGroup, aclFlowMeterBurstSize=aclFlowMeterBurstSize, lldpXdot3RemPowerClass=lldpXdot3RemPowerClass, qosDiffServType10=qosDiffServType10, sfpBaudRate=sfpBaudRate, ipv4snmpV3HostTable=ipv4snmpV3HostTable, cpuFilterL3RuleDstIpAddrMask=cpuFilterL3RuleDstIpAddrMask, aclL3RuleFilterTimeRange=aclL3RuleFilterTimeRange, staticVlanBaseAutoLearnList4k=staticVlanBaseAutoLearnList4k, trafficCtrlAutoRecoverTime=trafficCtrlAutoRecoverTime, macNotifyHistorySize=macNotifyHistorySize, sysGratuitousARPIFName=sysGratuitousARPIFName, cpuFilterL3RuleTcpSynBit=cpuFilterL3RuleTcpSynBit, lldpXdot3RemPowerEntry=lldpXdot3RemPowerEntry, gvrpSettingsLeaveAllTime=gvrpSettingsLeaveAllTime, sysSNTPDSTStartMin=sysSNTPDSTStartMin, aclL3RuleTcpFinBit=aclL3RuleTcpFinBit, impbBindingtrapsign=impbBindingtrapsign, cpuFilterProfileSrcPortMask=cpuFilterProfileSrcPortMask, cableDiagLinkStatus=cableDiagLinkStatus, snmpV3viewTreeName=snmpV3viewTreeName, newRootBrgaddress=newRootBrgaddress, qosDiffServType34=qosDiffServType34, igmpMulticastVlanUntaggedSourcePort=igmpMulticastVlanUntaggedSourcePort, ipv4cpuFilterProfileDstIpAddrMask=ipv4cpuFilterProfileDstIpAddrMask, ipv4sysIpAddr=ipv4sysIpAddr, cpuFilterL3RuleIgmpType=cpuFilterL3RuleIgmpType, snmpV3HostAddress=snmpV3HostAddress, macNotifyCtrlIndex=macNotifyCtrlIndex, mldsVlanRouterVlanId=mldsVlanRouterVlanId, swTimeRangeEndYear=swTimeRangeEndYear, qosTOSType02=qosTOSType02, doSCtrlMirrorPort=doSCtrlMirrorPort, lldpXdot3LocPowerMDISupported=lldpXdot3LocPowerMDISupported, cpuFilterL3RuleAction=cpuFilterL3RuleAction, multicastVlanMldReplaceSourceIp=multicastVlanMldReplaceSourceIp, cpuFilterv6L3RuleAction=cpuFilterv6L3RuleAction, sysMirrorCtrlEgressMirroring=sysMirrorCtrlEgressMirroring, sysSNTPFirstInterfaceName=sysSNTPFirstInterfaceName, trustedHostStatus=trustedHostStatus, impbPortDHCPSnoopingState=impbPortDHCPSnoopingState, iPv4swAuthRadiusServerAddress=iPv4swAuthRadiusServerAddress, ipifV6AddressEntry=ipifV6AddressEntry, stpModuleStatus=stpModuleStatus, cpuFilterL3RuleDscp=cpuFilterL3RuleDscp, mldsVlanMulticastGroupTable=mldsVlanMulticastGroupTable, portSecEntry=portSecEntry, baudRateConfiguration=baudRateConfiguration, lldpXdot1LocProtocolIndex=lldpXdot1LocProtocolIndex, cpuFilterProfileDstIpAddrMaskType=cpuFilterProfileDstIpAddrMaskType, ipv4snmpV3HostStatus=ipv4snmpV3HostStatus, tftpCfgTargetTftpOperationStatus=tftpCfgTargetTftpOperationStatus, trafficCtrlActionMode=trafficCtrlActionMode, syslogServFacility=syslogServFacility, cpuFilterProfileType=cpuFilterProfileType, pppoeGlobalState=pppoeGlobalState, qosDiffServType55=qosDiffServType55, aclQosStatus=aclQosStatus, mstCistPort=mstCistPort, staticMcastVlanID=staticMcastVlanID, igsHostTableHostIPAddress=igsHostTableHostIPAddress, aacLoginMethodListRowStatus=aacLoginMethodListRowStatus, sysSNTPDSTStartHour=sysSNTPDSTStartHour, staticARPRowStatus=staticARPRowStatus, sysPortCtrlMediumType=sysPortCtrlMediumType, mstMstiPortTable=mstMstiPortTable, sysLoginTimeoutInterval=sysLoginTimeoutInterval, lldpXdot1RemVlanNameEntry=lldpXdot1RemVlanNameEntry, laPortChannelMode=laPortChannelMode, ipv4cpuFilterProfileEntry=ipv4cpuFilterProfileEntry, aclL2RuleEtherType=aclL2RuleEtherType, aclQosProtocol=aclQosProtocol, cpuFilterL2RuleTable=cpuFilterL2RuleTable, swAuthRadiusServerTimeout=swAuthRadiusServerTimeout, aclL3RuleTcpRstBit=aclL3RuleTcpRstBit, companyL2PT=companyL2PT, duldRecoverTime=duldRecoverTime, trafficCtrlEntry=trafficCtrlEntry, cpuFilterL3RuleDstIpAddr=cpuFilterL3RuleDstIpAddr, smtpServerAddrInterfaceName=smtpServerAddrInterfaceName, aclL3RuleTos=aclL3RuleTos, tftpCfgTargetInterfaceName=tftpCfgTargetInterfaceName, aclPacketRuleOffsetValue2=aclPacketRuleOffsetValue2, lldpXdot3RemPowerPortClass=lldpXdot3RemPowerPortClass, aacAccountingMethodListIndex=aacAccountingMethodListIndex, iPv4swAuthRadiusServerEntry=iPv4swAuthRadiusServerEntry, aclProfileTable=aclProfileTable, qosTOSType01=qosTOSType01, aacServersInGroup=aacServersInGroup, ipv4aclUdfOffsetMask2=ipv4aclUdfOffsetMask2, sysSNTPDSTRepeatStartMin=sysSNTPDSTRepeatStartMin, snmpV3viewTreeSubtree=snmpV3viewTreeSubtree, stpPortPathCost=stpPortPathCost, lldpXdot3RemPowerPairControlable=lldpXdot3RemPowerPairControlable, qosTOSType03=qosTOSType03, PYSNMP_MODULE_ID=des_1210_28mebx, qinqVlanTranslationCVIDEntry=qinqVlanTranslationCVIDEntry, aclUdfOffsetMask4=aclUdfOffsetMask4, aclL3RuleTable=aclL3RuleTable, sfpVendorOui=sfpVendorOui, igsStatus=igsStatus, impbPortState=impbPortState, autoFdbPort=autoFdbPort, ipv4snmpV3HostCommunityName=ipv4snmpV3HostCommunityName, cpuFilterL2Rule1pPriority=cpuFilterL2Rule1pPriority, lldpXdot3RemPortOperMauType=lldpXdot3RemPortOperMauType, ddmActionState=ddmActionState, aclProfileNo=aclProfileNo, lldpXdot1LocProtocolEntry=lldpXdot1LocProtocolEntry, mldsVlanMulticastGroupIpAddress=mldsVlanMulticastGroupIpAddress, protocolGroupId=protocolGroupId)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", qosDiffServType23=qosDiffServType23, aacAPLoginMethod=aacAPLoginMethod, companyIpifGroup=companyIpifGroup, sysSNTPDSTRepeatEndWeek=sysSNTPDSTRepeatEndWeek, igsHost=igsHost, eoamEntry=eoamEntry, sshCipherSuiteList=sshCipherSuiteList, ddmActionShutdown=ddmActionShutdown, cosBandwidthEffectiveTX=cosBandwidthEffectiveTX, dhcpv6RelayManagement=dhcpv6RelayManagement, rmonEventStatus=rmonEventStatus, snmpV3GroupStatus=snmpV3GroupStatus, Ipv6Address=Ipv6Address, aacEnableMethodListRowStatus=aacEnableMethodListRowStatus, sysSNTPDSTMethod=sysSNTPDSTMethod, aacLoginMethod4=aacLoginMethod4, aacServerTimeout=aacServerTimeout, companyTrapSetting=companyTrapSetting, limitIpMulticastProfileID=limitIpMulticastProfileID, ddmThresholdMgmtEntry=ddmThresholdMgmtEntry, qinqRoleState=qinqRoleState, qosDiffServType01=qosDiffServType01, qinqVlanTranslationCVID=qinqVlanTranslationCVID, sshUserInfoEntry=sshUserInfoEntry, dlinklldpMsgTxInterval=dlinklldpMsgTxInterval, sysGratuitousARPIPIfStatusUp=sysGratuitousARPIPIfStatusUp, sysSave=sysSave, sysRestart=sysRestart, dhcpv6RelayOpt38PortID=dhcpv6RelayOpt38PortID, lldpXdot3LocLinkAggPortId=lldpXdot3LocLinkAggPortId, swAuthRadiusServerAddress=swAuthRadiusServerAddress, igsVlanMulticastGroupMacAddress=igsVlanMulticastGroupMacAddress, sysLBDCtrlIndex=sysLBDCtrlIndex, aclPacketRuleOffsetValue3=aclPacketRuleOffsetValue3, aclv6L3RuleDstIpAddr=aclv6L3RuleDstIpAddr, dot1qVlanManagementOnOff=dot1qVlanManagementOnOff, aacAccountingMethod2=aacAccountingMethod2, securityPortSecurity=securityPortSecurity, impbDhcpSnoopingMacAddress=impbDhcpSnoopingMacAddress, lldpXdot1ConfigProtoVlanEntry=lldpXdot1ConfigProtoVlanEntry, bandwidthCtrlEntry=bandwidthCtrlEntry, igsVlanRobustnessValue=igsVlanRobustnessValue, vlanMacType=vlanMacType, snmpV3TrapFirmUpgrade=snmpV3TrapFirmUpgrade, companyGuestVlan=companyGuestVlan, cpuFilterProfileDstMacAddrMask=cpuFilterProfileDstMacAddrMask, cpuFilterL3RuleTcpUdpDstPort=cpuFilterL3RuleTcpUdpDstPort, ipv4cpuFilterProfileStatus=ipv4cpuFilterProfileStatus, swTimeRangeTuesday=swTimeRangeTuesday, cpuFilterv6L3RuleTcpFinBit=cpuFilterv6L3RuleTcpFinBit, sshMacSuiteList=sshMacSuiteList, mstMstiPort=mstMstiPort, cosBandwidthCtrlEntry=cosBandwidthCtrlEntry, swAuthCtrlPktFwdMode=swAuthCtrlPktFwdMode, l2PTPortTable=l2PTPortTable, aclv6L3RuleReplace1P=aclv6L3RuleReplace1P, sysPortCtrlType=sysPortCtrlType, sysLBDMode=sysLBDMode, pppoePortCircuitIDType=pppoePortCircuitIDType, duldTable=duldTable, qosDiffServType37=qosDiffServType37, ipv4sysSNTPGMTMinutes=ipv4sysSNTPGMTMinutes, sysBPDUAttackCtrlEntry=sysBPDUAttackCtrlEntry, aclL3RuleDscp=aclL3RuleDscp, limitIpMulticastIPType=limitIpMulticastIPType, companyAgentBasicInfo=companyAgentBasicInfo, newRootOlddesignatedroot=newRootOlddesignatedroot, bandwidthEffecTxThreshold=bandwidthEffecTxThreshold, sysSNTPFirstServer=sysSNTPFirstServer, igsVlanRouterTable=igsVlanRouterTable, limitIpMulticastEntryIPType=limitIpMulticastEntryIPType, duldState=duldState, aclv6L3RuleReplaceQueue=aclv6L3RuleReplaceQueue, snmpV3Trap=snmpV3Trap, igsVlanQuerierVersionStatus=igsVlanQuerierVersionStatus, ftpConfigPort=ftpConfigPort, multicastVlanUntaggedSourcePort=multicastVlanUntaggedSourcePort, companyMulticastFilter=companyMulticastFilter, sysGratuitousARPTable=sysGratuitousARPTable, sfpVendorRev=sfpVendorRev, aclUdfOffsetByte3=aclUdfOffsetByte3, aclL3RuleProtocolMask=aclL3RuleProtocolMask, vlanMacMapVid=vlanMacMapVid, lldpXdot1ConfigVlanNameTable=lldpXdot1ConfigVlanNameTable, aacServerGroupIndex=aacServerGroupIndex, aclL3RuleTcpUdpSrcPort=aclL3RuleTcpUdpSrcPort, doSCtrlMirrorRxRate=doSCtrlMirrorRxRate, cpuFilterL2RuleVlanId=cpuFilterL2RuleVlanId, aclL3RulePortList=aclL3RulePortList, sysGratuitousARPInterval=sysGratuitousARPInterval, swAuthUserPassword=swAuthUserPassword, aacServerIndex=aacServerIndex, impbBindingListTable=impbBindingListTable, igsVlanMulticastGroupIpAddress=igsVlanMulticastGroupIpAddress, rmonAlarmRisingThreshold=rmonAlarmRisingThreshold, vlanTrunkEntry=vlanTrunkEntry, lldpXdot3LocMaxFrameSizeEntry=lldpXdot3LocMaxFrameSizeEntry, companyStaticMAC=companyStaticMAC, dhcpv6RelayOption38=dhcpv6RelayOption38, impbPortDHCPMaxEntryIPv6=impbPortDHCPMaxEntryIPv6, stpRootCost=stpRootCost, aclL2RuleReplace1P=aclL2RuleReplace1P, aclQosIndex=aclQosIndex, syslogServTable=syslogServTable, lldpXdot1LocTable=lldpXdot1LocTable, sfpWavelength=sfpWavelength, multicastVlanRemapPriority=multicastVlanRemapPriority, trustedHostIPType=trustedHostIPType, trafficCtrlTrap=trafficCtrlTrap, rmonAlarmEntry=rmonAlarmEntry, qosDiffServTypeGroup=qosDiffServTypeGroup, dhcpOption12HostName=dhcpOption12HostName, companyTimeRangeMgmt=companyTimeRangeMgmt, impbBindingtrap=impbBindingtrap, multicastVlanIgmpReplaceSourceIp=multicastVlanIgmpReplaceSourceIp, qinqVlanTranslationCVIDTable=qinqVlanTranslationCVIDTable, qosUserPriorityTable=qosUserPriorityTable, qosDiffServType04=qosDiffServType04, qosAclPrioritySettings=qosAclPrioritySettings, portSecIndex=portSecIndex, iPv4swAuthRadiusServerAccountingPort=iPv4swAuthRadiusServerAccountingPort, aclUdfOffsetBase2=aclUdfOffsetBase2, stpAdminPortPathCost=stpAdminPortPathCost, aclL2RuleVlanId=aclL2RuleVlanId, ipv4sysSNTPDSTState=ipv4sysSNTPDSTState, trafficControl=trafficControl, cpuFilterv6L3RuleTrafficClass=cpuFilterv6L3RuleTrafficClass, tftpCfgTargetTftpOperation=tftpCfgTargetTftpOperation, ddmActionPort=ddmActionPort, qosDiffServType53=qosDiffServType53, cpuFilterL2AccessID=cpuFilterL2AccessID, dhcpBOOTPRelayInterfaceSettingsEntry=dhcpBOOTPRelayInterfaceSettingsEntry, limitIpMulticastPortTable=limitIpMulticastPortTable, aacServerIPType=aacServerIPType, ftpFwFTPOperationStatus=ftpFwFTPOperationStatus, swTimeRangeSettingEntry=swTimeRangeSettingEntry, qosDiffServType51=qosDiffServType51, sysLBDCtrlEntry=sysLBDCtrlEntry, ipifVLANname=ipifVLANname, igmpMulticastVlanGroupVid=igmpMulticastVlanGroupVid, multicastVlanGroupStatus=multicastVlanGroupStatus, ipv4cpuFilterProfileIPProtocol=ipv4cpuFilterProfileIPProtocol, stpInstance=stpInstance, snmpV3GroupEntry=snmpV3GroupEntry, ipv4cpuFilterProfileNo=ipv4cpuFilterProfileNo, sysSNTPDSTStartDay=sysSNTPDSTStartDay, aclUdfOffsetByte1=aclUdfOffsetByte1, dlinklldpTxDelay=dlinklldpTxDelay, qosDiffServType17=qosDiffServType17, lldpXdot1LocProtoVlanEnabled=lldpXdot1LocProtoVlanEnabled, errorFramePeriodWindow=errorFramePeriodWindow, qosDiffServType06=qosDiffServType06, snmpV3Host=snmpV3Host, gvrpSettingsIngressChecking=gvrpSettingsIngressChecking, sysSNTPDSTStartMon=sysSNTPDSTStartMon, sysBPDUAttackCtrlTable=sysBPDUAttackCtrlTable, macNotificatiotn=macNotificatiotn, qosDiffServType57=qosDiffServType57, companyTftpGroup=companyTftpGroup, swAuthRadiusServer=swAuthRadiusServer, rmonHistoryInterval=rmonHistoryInterval, aclv6L3RuleTcpUdpDstPortMask=aclv6L3RuleTcpUdpDstPortMask, dhcpBOOTPRelayState=dhcpBOOTPRelayState, mldsHost=mldsHost, autoFdbVlanID=autoFdbVlanID, impbPortDHCPv4VlanList2k=impbPortDHCPv4VlanList2k, igsVlanRouterVlanId=igsVlanRouterVlanId, eoamLinkMonitorIfIndex=eoamLinkMonitorIfIndex, swAuthAuthDirection=swAuthAuthDirection, qosDSCPTOSMode=qosDSCPTOSMode, companyTraps=companyTraps, securityTrafficSeg=securityTrafficSeg, cpuFilterv6L3RuleICMPMessageType=cpuFilterv6L3RuleICMPMessageType, companyBPDUAttack=companyBPDUAttack, sysPortMediaTypeDateCode=sysPortMediaTypeDateCode, mldsVlanFastLeave=mldsVlanFastLeave, lldpXdot3RemLinkAggTable=lldpXdot3RemLinkAggTable, aacLoginMethodListTable=aacLoginMethodListTable, mcastFilterPortTable=mcastFilterPortTable, companyDHCPRelay=companyDHCPRelay, aclUdfOffsetByte2=aclUdfOffsetByte2, aacServerRowStatus=aacServerRowStatus, mstCistVlanMapped2k=mstCistVlanMapped2k, l2PTPortType=l2PTPortType, rmonHistoryIndex=rmonHistoryIndex, ftpConfigFTPOperation=ftpConfigFTPOperation, limitIpMulticastEntryTable=limitIpMulticastEntryTable, aRPSpoofPreventPortList=aRPSpoofPreventPortList, sysTrapIMPBViolation=sysTrapIMPBViolation, stpTopologyChangeTrapStatus=stpTopologyChangeTrapStatus, impbPortNDInspectionState=impbPortNDInspectionState, qosDiffServType59=qosDiffServType59, lldpXdot1LocProtoVlanTable=lldpXdot1LocProtoVlanTable, staticARPIP=staticARPIP, snmpV3UserName=snmpV3UserName, eoamRemoteLoopback=eoamRemoteLoopback, aclProfileMask=aclProfileMask, vlanTrunkSystem=vlanTrunkSystem, aclProfileRuleCount=aclProfileRuleCount, qosDiffServType60=qosDiffServType60, snmpV3Community=snmpV3Community, rmonEventDescription=rmonEventDescription, mldsVlanFilterTable=mldsVlanFilterTable, cpuFilterL3RuleProtocolMask=cpuFilterL3RuleProtocolMask, snmpGlobalState=snmpGlobalState, cpuFilterProfileSrcMacAddrMask=cpuFilterProfileSrcMacAddrMask, qosDiffServType12=qosDiffServType12, ipv4trustedHostIpAddr=ipv4trustedHostIpAddr, qosDiffServType62=qosDiffServType62, stpProtocolVersion=stpProtocolVersion, snmpTrapIMPBv2=snmpTrapIMPBv2, limitIpMulticastPortIPType=limitIpMulticastPortIPType, ddmLowAlarm=ddmLowAlarm, ipv4syslogServEntry=ipv4syslogServEntry, aacAPSSHEnableMethod=aacAPSSHEnableMethod, sfpPortIndex=sfpPortIndex, sshAuthenMethodHostKeyAdmin=sshAuthenMethodHostKeyAdmin, aclL2RuleFilterTimeRange=aclL2RuleFilterTimeRange, qosDiffServType38=qosDiffServType38, mldsVlanRouterEntry=mldsVlanRouterEntry, cpuFilterL3RuleICMPMessageCode=cpuFilterL3RuleICMPMessageCode, duplicateIP=duplicateIP, cpuFilterProfile=cpuFilterProfile, companySTP=companySTP, igsVlanQueryMaxResponseTime=igsVlanQueryMaxResponseTime, qosPriSetPortType=qosPriSetPortType, snmpV3CommunityPolicy=snmpV3CommunityPolicy, lldpXdot1RemProtocolIndex=lldpXdot1RemProtocolIndex, mldsVlanRouterTable=mldsVlanRouterTable, gvrpSettingsGVRPState=gvrpSettingsGVRPState, snmpV3UserPrivProtocol=snmpV3UserPrivProtocol, sysBootupConfigID=sysBootupConfigID, swTimeRangeStartDay=swTimeRangeStartDay, agentMEMutilizationIn5min=agentMEMutilizationIn5min, mldsVlanDataDrivenLearningStatus=mldsVlanDataDrivenLearningStatus, qosDiffServType32=qosDiffServType32, companySfpVendorInfo=companySfpVendorInfo, aacEnableMethod3=aacEnableMethod3, eoamTable=eoamTable, aclv6L3RulePortList=aclv6L3RulePortList, swTimeRangeFriday=swTimeRangeFriday, igsVlanRtrPortList=igsVlanRtrPortList, swAuthRadiusServerInterfaceName=swAuthRadiusServerInterfaceName, pppoePortCircuitIDVendor3String=pppoePortCircuitIDVendor3String, mcastFilterPortEntry=mcastFilterPortEntry, aclL2RuleSrcMacAddrMask=aclL2RuleSrcMacAddrMask, snmpV3TrapDuplicateIPDetected=snmpV3TrapDuplicateIPDetected, companyNeighbor=companyNeighbor, cosClassEntry=cosClassEntry, qosUserPriEntry=qosUserPriEntry, aclL3RuleTcpUrgBit=aclL3RuleTcpUrgBit, aacAccountingServiceCommandOperator=aacAccountingServiceCommandOperator, staticMcastEntry=staticMcastEntry, snmpTrapSNMPAuthentication=snmpTrapSNMPAuthentication)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", cpuFilterL3Rule=cpuFilterL3Rule, impbLogState=impbLogState, mldsVlanReportSuppression=mldsVlanReportSuppression, aclL3RuleTcpUdpDstPortMask=aclL3RuleTcpUdpDstPortMask, ipv4aclProfileDstMacAddrMask=ipv4aclProfileDstMacAddrMask, sysSNTPDSTRepeatStartMon=sysSNTPDSTRepeatStartMon, trustedHostTable=trustedHostTable, staticVlanBaseDisableAutoLearn=staticVlanBaseDisableAutoLearn, cpuFilterL2RuleSrcMacAddrMask=cpuFilterL2RuleSrcMacAddrMask, aclL2RuleDstMacAddrMask=aclL2RuleDstMacAddrMask, aacLoginMethod1=aacLoginMethod1, companyProtocolVlan=companyProtocolVlan, snmpV3TrapLinkUpDown=snmpV3TrapLinkUpDown, sshSessionKeyRekeying=sshSessionKeyRekeying, tftpCfgTargetGroup=tftpCfgTargetGroup, ftpConfigFileName=ftpConfigFileName, stpPortState=stpPortState, cableDiagPair1Status=cableDiagPair1Status, ipv4cpuFilterProfileSrcIpAddrMask=ipv4cpuFilterProfileSrcIpAddrMask, qosDiffServType03=qosDiffServType03, rmonEventTable=rmonEventTable, igsVlanFilterTable=igsVlanFilterTable, aacAccountingServiceShell=aacAccountingServiceShell, limitIpMulticastendIpAddr=limitIpMulticastendIpAddr, lldpXdot3PortConfigEntry=lldpXdot3PortConfigEntry, dhcpv6RelayServerIP=dhcpv6RelayServerIP, pppoePortRemoteIDVendor3String=pppoePortRemoteIDVendor3String, swAuthUser=swAuthUser, sysSerialNumber=sysSerialNumber, qosDiffServType22=qosDiffServType22, swTimeRangeStartHour=swTimeRangeStartHour, sysLBDCtrlTable=sysLBDCtrlTable, mstMstiForcePortState=mstMstiForcePortState, qosDiffServType02=qosDiffServType02, qosDiffServType00=qosDiffServType00, snmpV3TrapIMPBViolation=snmpV3TrapIMPBViolation, impbPortDHCPv6VlanList2k=impbPortDHCPv6VlanList2k, ipv4sysSNTPSecondServer=ipv4sysSNTPSecondServer, swAuthAuthReAuthPeriod=swAuthAuthReAuthPeriod, swAuthRadiusServerStatus=swAuthRadiusServerStatus, impbBlockListPort=impbBlockListPort, impbBlockListEntry=impbBlockListEntry, rmonGlobalState=rmonGlobalState, protocolVlanGroupID=protocolVlanGroupID, syslogServSrvRowStatus=syslogServSrvRowStatus, ipv4cpuFilterProfileSrcMacAddrMask=ipv4cpuFilterProfileSrcMacAddrMask, snmpV3GroupSecurityLevel=snmpV3GroupSecurityLevel, staticARPEntry=staticARPEntry, errorFramePeriodNotifyState=errorFramePeriodNotifyState, stpPortProtocolMigration=stpPortProtocolMigration, sysWebPortNumber=sysWebPortNumber, ftpFwPassword=ftpFwPassword, aacAPTelnetEnableMethod=aacAPTelnetEnableMethod, guestVlanPort=guestVlanPort, sysMACAgingTime=sysMACAgingTime, ipv4aclProfileDstIpAddrMask=ipv4aclProfileDstIpAddrMask, sysLBDInterval=sysLBDInterval, dhcpv6RelayHopCount=dhcpv6RelayHopCount, stpNewRootTraps=stpNewRootTraps, sysGateway=sysGateway, ipifv6DHCPStatus=ipifv6DHCPStatus, igmpMulticastVlanReplacePriority=igmpMulticastVlanReplacePriority, swTimeRangeName=swTimeRangeName, sshUserInfoTable=sshUserInfoTable, staticMcastMac=staticMcastMac, doSCtrlClearFrameCount=doSCtrlClearFrameCount, protocolGroupNameEntry=protocolGroupNameEntry, neighborIPv6Addr=neighborIPv6Addr, agentCPUutilizationIn5min=agentCPUutilizationIn5min, rmonAlarmIndex=rmonAlarmIndex, qosDiffServType35=qosDiffServType35, smtpRecvMailAddrStatus=smtpRecvMailAddrStatus, dhcpServerScreenEnablePortlist=dhcpServerScreenEnablePortlist, limitIpMulticastPortProfileID=limitIpMulticastPortProfileID, impbAutoScanStatus=impbAutoScanStatus, aclL2RuleDstMacAddr=aclL2RuleDstMacAddr, smtpServerAddr=smtpServerAddr, trafficCtrlTable=trafficCtrlTable, authProtocol=authProtocol, igsVlanQueryInterval=igsVlanQueryInterval, igmpMulticastVlanGroupFromIp=igmpMulticastVlanGroupFromIp, rmonHistoryTable=rmonHistoryTable, sysPortDescIndex=sysPortDescIndex, cosWeight=cosWeight, staticMcastTable=staticMcastTable, macBasedVlanTable=macBasedVlanTable, aclv6L3RuleTcpUrgBit=aclv6L3RuleTcpUrgBit, dlinklldpReinitDelay=dlinklldpReinitDelay, impbAutoScanPort=impbAutoScanPort, lldpXdot3LocPowerPortClass=lldpXdot3LocPowerPortClass, aclPacketRuleStatus=aclPacketRuleStatus, sysContactName=sysContactName, lldpXdot1ConfigPortVlanEntry=lldpXdot1ConfigPortVlanEntry, floodfdbOnOff=floodfdbOnOff, eoamDyingGaspEnable=eoamDyingGaspEnable, cableDiagPortIndex=cableDiagPortIndex, impbVlanModeState=impbVlanModeState, snmpV3HostStatus=snmpV3HostStatus, tftpFwTargetTftpOperationStatus=tftpFwTargetTftpOperationStatus, lldpXdot3RemLinkAggStatus=lldpXdot3RemLinkAggStatus, duldMode=duldMode, ipv4aclProfileMask=ipv4aclProfileMask, ipv4cpuFilterProfileDstPortMask=ipv4cpuFilterProfileDstPortMask, vlanTrunkIfIndex=vlanTrunkIfIndex, staticEntry=staticEntry, ftpFwServerIpAddress=ftpFwServerIpAddress, portSecTable=portSecTable, aclv6L3RuleStatus=aclv6L3RuleStatus, igsVlanSnoopStatus=igsVlanSnoopStatus, aclL3RuleTcpUdpDstPort=aclL3RuleTcpUdpDstPort, aclL2ProfileID=aclL2ProfileID, autologoutConfiguration=autologoutConfiguration, portSecLockAddrMode=portSecLockAddrMode, sysPortMediaTypeEntry=sysPortMediaTypeEntry, l2PTThresholdEntry=l2PTThresholdEntry, mldsHostTablePort=mldsHostTablePort, stpPort=stpPort, aacLocalEnablePassword=aacLocalEnablePassword, swAuthAuthConfigPortNumber=swAuthAuthConfigPortNumber, mstInstanceIndex=mstInstanceIndex, mldsHostTableVLANID=mldsHostTableVLANID, aclQosIP6TC=aclQosIP6TC, l2PTState=l2PTState, ipv4trustedHostTable=ipv4trustedHostTable, portSecMLA=portSecMLA, swAuthRadiusServerRetransmit=swAuthRadiusServerRetransmit, mldsVlanQuerier=mldsVlanQuerier, mstCistPortDesignatedBridge=mstCistPortDesignatedBridge, aacServerInfoTable=aacServerInfoTable, swAuthPortAccessControlEntry=swAuthPortAccessControlEntry, sysPortMediaTypeIndex=sysPortMediaTypeIndex, aacLoginMethodListName=aacLoginMethodListName, dhcpBOOTPRelayOption82CircuitIDType=dhcpBOOTPRelayOption82CircuitIDType, ipv4aclProfileDstPortMask=ipv4aclProfileDstPortMask, qosDiffServType16=qosDiffServType16, aclFlowMeterAction=aclFlowMeterAction, stpFowardBPDU=stpFowardBPDU, trustedHostIpMask=trustedHostIpMask, aacServerAuthKey=aacServerAuthKey, cableDiagPair4Status=cableDiagPair4Status, mstCistPortPathCost=mstCistPortPathCost, ipv4sysSNTPDSTStartHour=ipv4sysSNTPDSTStartHour, portSecFDBPermIndex=portSecFDBPermIndex, ipv4aclProfileIPProtocolMask=ipv4aclProfileIPProtocolMask, lldpXdot1Objects=lldpXdot1Objects, mstCistCurrentPortRole=mstCistCurrentPortRole, smtpState=smtpState, igsVlanDataDrivenLearningStatus=igsVlanDataDrivenLearningStatus, syslogServUDPport=syslogServUDPport, swTimeRangeStartMonth=swTimeRangeStartMonth, rmonAlarmFallingThreshold=rmonAlarmFallingThreshold, aclProfileDstMacAddrMask=aclProfileDstMacAddrMask, impbPortAllowZeroIPState=impbPortAllowZeroIPState, cpuFilterL3RuleEntry=cpuFilterL3RuleEntry, ipv4aclUdfOffsetMask1=ipv4aclUdfOffsetMask1, staticVlanBaseAutoLearnList1k=staticVlanBaseAutoLearnList1k, mstInstanceVlanMapped=mstInstanceVlanMapped, ipv4syslogServFacility=ipv4syslogServFacility, aclPacketProfileID=aclPacketProfileID, qosDiffServType20=qosDiffServType20, sshMaxAuthFailAttempts=sshMaxAuthFailAttempts, aacEnableMethod2=aacEnableMethod2, sysMirrorCtrlIngressMirroring=sysMirrorCtrlIngressMirroring, rmonAlarmSampleType=rmonAlarmSampleType, multicastVlanGroupIpType=multicastVlanGroupIpType, sysBPDUAttackPortMode=sysBPDUAttackPortMode, sysPortCtrlTable=sysPortCtrlTable, snmpV3UserEntry=snmpV3UserEntry, sysSNTPDSTRepeatEndMon=sysSNTPDSTRepeatEndMon, tftpCfgTargetTftpIncrement=tftpCfgTargetTftpIncrement, mstMstiPortPathCost=mstMstiPortPathCost, aclFlowMeterRule=aclFlowMeterRule, cpuFilterL2Rule=cpuFilterL2Rule, securityIpMacPortBinding=securityIpMacPortBinding, sysSNTPSecondInterfaceName=sysSNTPSecondInterfaceName, smtpSelfMailAddr=smtpSelfMailAddr, snmpV3Group=snmpV3Group, mstMstiPortAdminPathCost=mstMstiPortAdminPathCost, cosBandwidthEffectiveRX=cosBandwidthEffectiveRX, dot1qVlanPVIDAutoAssignOnOff=dot1qVlanPVIDAutoAssignOnOff, mstCistVlanMapped3k=mstCistVlanMapped3k, vlanTrunkState=vlanTrunkState, swAuthAuthMaxReq=swAuthAuthMaxReq, dhcpLocalRelayTable=dhcpLocalRelayTable, aclv6L3RuleTrafficClass=aclv6L3RuleTrafficClass, ftpConfigFTPOperationStatus=ftpConfigFTPOperationStatus, limitIpMulticastPortMaxGrp=limitIpMulticastPortMaxGrp, impbPortIpInspectionState=impbPortIpInspectionState, ftpFwPort=ftpFwPort, aclv6L3RuleSrcIpAddr=aclv6L3RuleSrcIpAddr, ddmThresholdPort=ddmThresholdPort, igmpMulticastVlanEntry=igmpMulticastVlanEntry, companyFTPGroup=companyFTPGroup, aclL2RuleVlanIdMask=aclL2RuleVlanIdMask, companyStaticARP=companyStaticARP, tftpCfgTargetTftpConfigID=tftpCfgTargetTftpConfigID, igsVlanFilterVlanId=igsVlanFilterVlanId, sysLBDVlanLoopTable=sysLBDVlanLoopTable, sysDhcpAutoImage=sysDhcpAutoImage, sysTrapStatus=sysTrapStatus, mldsVlanMulticastGroupMacAddress=mldsVlanMulticastGroupMacAddress, sysPortCtrlOperStatus=sysPortCtrlOperStatus, dhcpBOOTPRelayOption82RemoteIDType=dhcpBOOTPRelayOption82RemoteIDType, LldpManAddress=LldpManAddress, ddmHighWarning=ddmHighWarning, gvrpSettingsAcceptableFrameType=gvrpSettingsAcceptableFrameType, ddmActionMgmtTable=ddmActionMgmtTable, qosDiffServType50=qosDiffServType50, lldpXdot3RemPowerMDISupported=lldpXdot3RemPowerMDISupported, protocolVlanTable=protocolVlanTable, snmpV3UserStatus=snmpV3UserStatus, lldpXdot1LocVlanNameEntry=lldpXdot1LocVlanNameEntry, sysSNTPDSTEndDay=sysSNTPDSTEndDay, aclL2Rule1pPriority=aclL2Rule1pPriority, stpBridgeMaxAge=stpBridgeMaxAge, aclL2AccessID=aclL2AccessID, gvrpSettingsPVID=gvrpSettingsPVID, staticVlanID=staticVlanID, ipv4sysSNTPDSTEndHour=ipv4sysSNTPDSTEndHour, aacAccountingMethodListRowStatus=aacAccountingMethodListRowStatus, cpuFilterL2RuleEtherType=cpuFilterL2RuleEtherType, ipv4smtpRecvMailAddrStatus=ipv4smtpRecvMailAddrStatus, impbAutoScanMacAddress=impbAutoScanMacAddress, lldpXdot1ConfigPortVlanTxEnable=lldpXdot1ConfigPortVlanTxEnable, impbPortDHCPMaxEntryIPv4=impbPortDHCPMaxEntryIPv4, ipv4syslogServSrvRowStatus=ipv4syslogServSrvRowStatus, mstConfigurationIdentification=mstConfigurationIdentification, tftpCfgTargetImageFileName=tftpCfgTargetImageFileName, oldDesignatedRoot=oldDesignatedRoot, dhcpBOOTPRelayOption82Policy=dhcpBOOTPRelayOption82Policy, mstCistVlanMapped=mstCistVlanMapped, swAuthAuthTxPeriod=swAuthAuthTxPeriod, aacAccountingServiceCommandAdministrator=aacAccountingServiceCommandAdministrator, sfpVendorName=sfpVendorName, aclUdfOffsetByte4=aclUdfOffsetByte4, iPv4swAuthRadiusServerKey=iPv4swAuthRadiusServerKey, snmpV3ViewTreeTable=snmpV3ViewTreeTable, cpuFilterL3RuleAccessID=cpuFilterL3RuleAccessID, filterDHCPServerVlanList=filterDHCPServerVlanList, impbAutoScanIpAddressFrom=impbAutoScanIpAddressFrom, laPortControlTable=laPortControlTable, dhcpBOOTPRelayOption82State=dhcpBOOTPRelayOption82State, aclv6L3RuleProtocol=aclv6L3RuleProtocol, sysSNTPSecondServer=sysSNTPSecondServer, dhcpv6RelayInterfaceSettingsRowStatus=dhcpv6RelayInterfaceSettingsRowStatus, mldsVlanQueryInterval=mldsVlanQueryInterval, stpBridgeForwardDelay=stpBridgeForwardDelay, mldsVlanFilterVlanId=mldsVlanFilterVlanId, companyTrafficMgmt=companyTrafficMgmt, ipv4snmpV3HostAddress=ipv4snmpV3HostAddress, sysBPDUAttackPortState=sysBPDUAttackPortState, des_1210_28mebx=des_1210_28mebx, sysPortMediaTypePn=sysPortMediaTypePn, aacServerInterfaceName=aacServerInterfaceName)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", laPortChannelTable=laPortChannelTable, mldsVlanMulticastGroupPortList=mldsVlanMulticastGroupPortList, rmonHistoryOwner=rmonHistoryOwner, sysBPDUAttackLog=sysBPDUAttackLog, aacAPConsoleEnableMethod=aacAPConsoleEnableMethod, multicastVlanMemberPort=multicastVlanMemberPort, cableDiagPair2Length=cableDiagPair2Length, qosEffectiveDefaultPriority=qosEffectiveDefaultPriority, ipv4aclQosTCPUDPPort=ipv4aclQosTCPUDPPort, sysPortCtrlSpeed=sysPortCtrlSpeed, igmpMulticastVlanTagMemberPort=igmpMulticastVlanTagMemberPort, ddmPowerUnit=ddmPowerUnit, sysTrapDHCPServerScreening=sysTrapDHCPServerScreening, ipv4syslogServIndex=ipv4syslogServIndex, lldpXdot3RemPowerPairs=lldpXdot3RemPowerPairs, igsVlanMulticastGroupEntry=igsVlanMulticastGroupEntry, aclProfileSrcIpAddrMaskType=aclProfileSrcIpAddrMaskType, cpuFilterv6L3RuleStatus=cpuFilterv6L3RuleStatus, lldpXdot3LocLinkAggEntry=lldpXdot3LocLinkAggEntry, qosDiffServType05=qosDiffServType05, dhcpServerScreenLogSuppressDuration=dhcpServerScreenLogSuppressDuration, dhcpv6RelayOption37RemoteID=dhcpv6RelayOption37RemoteID, sysBPDUAttackCtrlIndex=sysBPDUAttackCtrlIndex, lldpXdot3Config=lldpXdot3Config, iPv4aacServerInfoEntry=iPv4aacServerInfoEntry, mldsVlanQueryMaxResponseTime=mldsVlanQueryMaxResponseTime, aclL3RuleICMPMessageCode=aclL3RuleICMPMessageCode, staticARPTable=staticARPTable, LldpPortNumber=LldpPortNumber, lldpXdot1RemoteData=lldpXdot1RemoteData, mstiRevisionLevel=mstiRevisionLevel, sslCipherSuiteList=sslCipherSuiteList, sysTrapIP=sysTrapIP, cpuFilterv6L3RuleTable=cpuFilterv6L3RuleTable, cosBandwidthCtrlClassIndex=cosBandwidthCtrlClassIndex, mldsVlanSnoopStatus=mldsVlanSnoopStatus, aclPacketRuleTable=aclPacketRuleTable, protocolGroupTable=protocolGroupTable, stpPortFowardBPDU=stpPortFowardBPDU, cpuFilterProfileIPProtocol=cpuFilterProfileIPProtocol, ipv4aclQosMACAddr=ipv4aclQosMACAddr, sslSecurityHttpStatus=sslSecurityHttpStatus, aclL3RuleReplaceDSCP=aclL3RuleReplaceDSCP, snmpV3viewTreeStatus=snmpV3viewTreeStatus, protocolGroupGID=protocolGroupGID, snmpV3GroupWriteViewName=snmpV3GroupWriteViewName, aacServerAuthProtocol=aacServerAuthProtocol, dhcpLocalRelaySettingsState=dhcpLocalRelaySettingsState, dhcpBOOTPRelayControl=dhcpBOOTPRelayControl, cableDiagAction=cableDiagAction, aacServerInfoEntry=aacServerInfoEntry, neighborTable=neighborTable, eoamLinkMonitor=eoamLinkMonitor, ipv4aclUdfOffsetMask3=ipv4aclUdfOffsetMask3, qosDiffServType25=qosDiffServType25, securityDhcpServerScreen=securityDhcpServerScreen, sfpVendorInfoEntry=sfpVendorInfoEntry, multicastVlanReplacePriority=multicastVlanReplacePriority, ipv4sysSNTPFirstServer=ipv4sysSNTPFirstServer, sshUserInfoUserName=sshUserInfoUserName, mstCistForcePortState=mstCistForcePortState, dhcpBOOTPRelayOption82RemoteID=dhcpBOOTPRelayOption82RemoteID, ipv4sysIpAddrCfgMode=ipv4sysIpAddrCfgMode, aclProfileSrcPortMask=aclProfileSrcPortMask, cpuFilterL3RuleTcpRstBit=cpuFilterL3RuleTcpRstBit, mcastFilterPortIndex=mcastFilterPortIndex, cpuFilterL2RuleStatus=cpuFilterL2RuleStatus, mcastFilterPortType=mcastFilterPortType, impbAutoScanVlanId=impbAutoScanVlanId, impbAutoScanCurrentStatus=impbAutoScanCurrentStatus, qosDiffServType45=qosDiffServType45, cosBandwidthValue=cosBandwidthValue, lldpXdot3LocPortOperMauType=lldpXdot3LocPortOperMauType, mldsRouterPortPurgeInterval=mldsRouterPortPurgeInterval, aacLoginMethodListEntry=aacLoginMethodListEntry, ftpFwPath=ftpFwPath, tftpCfgServerIpAddress=tftpCfgServerIpAddress, staticVlanBaseAutoLearnList2k=staticVlanBaseAutoLearnList2k, aclL3RuleReplaceQueue=aclL3RuleReplaceQueue, companyLLDPSetting=companyLLDPSetting, laPortActorTimeout=laPortActorTimeout, iPv4aacServerIndex=iPv4aacServerIndex, cpuFilterL3RuleStatus=cpuFilterL3RuleStatus, snmpV3UserGroupName=snmpV3UserGroupName, aclProfile=aclProfile, snmpV3TrapRSTPStateChange=snmpV3TrapRSTPStateChange, rmonStatsTable=rmonStatsTable, swAuthRadiusServerIndex=swAuthRadiusServerIndex, lldpXdot1RemProtoVlanEntry=lldpXdot1RemProtoVlanEntry, aacEnableMethod4=aacEnableMethod4, cpuFilterL3RuleTcpUdpSrcPortMask=cpuFilterL3RuleTcpUdpSrcPortMask, autoFdbIPAddress=autoFdbIPAddress, qosDefaultUserPriEntry=qosDefaultUserPriEntry, limitIpMulticastProfileStatus=limitIpMulticastProfileStatus, aclL2RuleInPortList=aclL2RuleInPortList, lldpXdot1RemProtoVlanId=lldpXdot1RemProtoVlanId, lldpXdot1RemProtocolTable=lldpXdot1RemProtocolTable, macBasedVlanEntry=macBasedVlanEntry, newRootMSTibridgeregionalroot=newRootMSTibridgeregionalroot, dhcpv6RelayInterface=dhcpv6RelayInterface, aclFlowMeterStatus=aclFlowMeterStatus, ipv4smtpRecvMailAddrIndex=ipv4smtpRecvMailAddrIndex, sysPortDescMediumType=sysPortDescMediumType, mstInstanceVlanMapped2k=mstInstanceVlanMapped2k, swAuthUserTable=swAuthUserTable, sysFirmwareVersion=sysFirmwareVersion, aclQosAssignClass=aclQosAssignClass, swTimeRangeEndMonth=swTimeRangeEndMonth, tftpConfigTftpOperation=tftpConfigTftpOperation, mstCistPortAdminPathCost=mstCistPortAdminPathCost, ddmTxPower=ddmTxPower, miscReset=miscReset, companyDuld=companyDuld, lldpPortConfigTLVsTxEnable=lldpPortConfigTLVsTxEnable, aacAPConsoleLoginMethod=aacAPConsoleLoginMethod, sysPortUpLinkTime=sysPortUpLinkTime, aacEnableMethodListTable=aacEnableMethodListTable, duldSystem=duldSystem, syslogEnable=syslogEnable, sysPortErrTable=sysPortErrTable, cableDiagPair4Length=cableDiagPair4Length, ipv4sysIpSubnetMask=ipv4sysIpSubnetMask, swAuthAuthCapability=swAuthAuthCapability, companyMiscGroup=companyMiscGroup, telnetUDPPort=telnetUDPPort, qosDiffServType63=qosDiffServType63, qosDiffServType28=qosDiffServType28, lldpXdot1RemProtoVlanEnabled=lldpXdot1RemProtoVlanEnabled, igsHostTablePort=igsHostTablePort, qosDiffServType07=qosDiffServType07, cosBandwidthCtrlPortIndex=cosBandwidthCtrlPortIndex, lldpXdot1ConfigProtocolTxEnable=lldpXdot1ConfigProtocolTxEnable, telnetsettingManagementOnOff=telnetsettingManagementOnOff, rmonEventIndex=rmonEventIndex, rmonStatsDataSource=rmonStatsDataSource, companySecurity=companySecurity, mstSetVlanList=mstSetVlanList, sshAuthenMethodPassWordAdmin=sshAuthenMethodPassWordAdmin, snmpV3TrapBPDUAttack=snmpV3TrapBPDUAttack, sfpTranceiverCode=sfpTranceiverCode, swAuthMode=swAuthMode, dhcpServerScreenEnableVlanlist=dhcpServerScreenEnableVlanlist, staticMcastEgressPorts=staticMcastEgressPorts, qosDiffServType15=qosDiffServType15, igsVlanRouterEntry=igsVlanRouterEntry, dhcpv6RelayOption18CheckState=dhcpv6RelayOption18CheckState, aclL2RuleReplaceDSCP=aclL2RuleReplaceDSCP, igmpMulticastVlanTable=igmpMulticastVlanTable, lldpXdot1LocPortVlanId=lldpXdot1LocPortVlanId, ipv4smtpRecvMailAddrEntry=ipv4smtpRecvMailAddrEntry, ipv4syslogServTable=ipv4syslogServTable, doSCtrlMirrorReplace1P=doSCtrlMirrorReplace1P, limitIpMulticastProfileEntry=limitIpMulticastProfileEntry, sysIpAddr=sysIpAddr, ipv4cpuFilterProfileIPProtocolMask=ipv4cpuFilterProfileIPProtocolMask, cpuFilterL3RuleTcpUdpDstPortMask=cpuFilterL3RuleTcpUdpDstPortMask, cpuFilterL2RuleSrcMacAddr=cpuFilterL2RuleSrcMacAddr, mstMstiPortPriority=mstMstiPortPriority, aclFlowMeterProfileID=aclFlowMeterProfileID, qosTOSType04=qosTOSType04, rmonAlarmInterval=rmonAlarmInterval, aclUdfOffsetMask1=aclUdfOffsetMask1, rmonAlarmRisingEventIndex=rmonAlarmRisingEventIndex, snmpV3HostVersion=snmpV3HostVersion, eoamLinkMonitorEntry=eoamLinkMonitorEntry, dhcpLocalRelayEnablePortlist=dhcpLocalRelayEnablePortlist, swAuthRadiusServerKey=swAuthRadiusServerKey, staticTable=staticTable, companySyslog=companySyslog, qosDiffServType36=qosDiffServType36, sysSNTPDSTRepeatStartWeek=sysSNTPDSTRepeatStartWeek, aclv6L3RuleProfileNo=aclv6L3RuleProfileNo, cpuFilterv6L3RuleICMPMessageCode=cpuFilterv6L3RuleICMPMessageCode, cableDiagPair3Status=cableDiagPair3Status, aclPacketRuleOffsetValue2Mask=aclPacketRuleOffsetValue2Mask, tftpConfigFileName=tftpConfigFileName, dot1qVlanForbiddenPorts=dot1qVlanForbiddenPorts, multicastVlanSourcePort=multicastVlanSourcePort, stpBridgePriority=stpBridgePriority, sysJumboFrameEnable=sysJumboFrameEnable, ipv4sysSNTPDSTStartMon=ipv4sysSNTPDSTStartMon, lldpXdot3LocPortAutoNegSupported=lldpXdot3LocPortAutoNegSupported, dhcpv6RelayOpt38PortIndex=dhcpv6RelayOpt38PortIndex, trustedHostRowStatus=trustedHostRowStatus, syslogServInterfaceName=syslogServInterfaceName, limitIpMulticastPortState=limitIpMulticastPortState, companySMTP=companySMTP, portSecFDBPermanentEntry=portSecFDBPermanentEntry, neighborEntry=neighborEntry, cpuFilterv6L3RuleTcpUdpDstPort=cpuFilterv6L3RuleTcpUdpDstPort, lldpXdot3LocPortEntry=lldpXdot3LocPortEntry, mldsHostEntry=mldsHostEntry, igsHostPortPurgeInterval=igsHostPortPurgeInterval, snmpV3TrapPortSecurity=snmpV3TrapPortSecurity, sysPortErrPortState=sysPortErrPortState, lldpXdot1RemVlanNameTable=lldpXdot1RemVlanNameTable, dhcpBOOTPRelayHopCount=dhcpBOOTPRelayHopCount, impbBlockListVlanId=impbBlockListVlanId, ddmActionMgmtEntry=ddmActionMgmtEntry, stpPortHelloTime=stpPortHelloTime, RmonStatus=RmonStatus, cpuFilterL3RuleProfileNo=cpuFilterL3RuleProfileNo, ddmRxPower=ddmRxPower, ipv4aclQosTable=ipv4aclQosTable, cpuFilterv6L3RuleTcpUdpSrcPortMask=cpuFilterv6L3RuleTcpUdpSrcPortMask, ddmCtrl=ddmCtrl, companyLimitIp=companyLimitIp, syslogServerGroup=syslogServerGroup, sysType=sysType, sysCommandLogging=sysCommandLogging, igsVlanQuerier=igsVlanQuerier, qosDiffServType21=qosDiffServType21, aacServerAccountingPort=aacServerAccountingPort, ipv4aclQosIndex=ipv4aclQosIndex, snmpV3HostCommunityName=snmpV3HostCommunityName, lldpXdot1RemProtocolEntry=lldpXdot1RemProtocolEntry, impbAutoScanBinding=impbAutoScanBinding, eoamState=eoamState, sysLBDVlanLoopIndex=sysLBDVlanLoopIndex, vlanMacStatus=vlanMacStatus, trafficSegIfIndex=trafficSegIfIndex, qinqVlanTranslationCVIDRowStatus=qinqVlanTranslationCVIDRowStatus, multicastVlanEntry=multicastVlanEntry, igmpMulticastVlanGroupTable=igmpMulticastVlanGroupTable, cpuFilterL2RuleEntry=cpuFilterL2RuleEntry, duldDiscoveryTime=duldDiscoveryTime, doSCtrlTable=doSCtrlTable, aacEnableMethodListName=aacEnableMethodListName, igsRouterPortPurgeInterval=igsRouterPortPurgeInterval, dhcpBOOTPRelayServerIP=dhcpBOOTPRelayServerIP, syslogSettingGroup=syslogSettingGroup, snmpTrapRSTPStateChange=snmpTrapRSTPStateChange, dhcpv6RelayOpt38PortType=dhcpv6RelayOpt38PortType, ipv4syslogServSeverity=ipv4syslogServSeverity, swAuthRadiusServerAccountingPort=swAuthRadiusServerAccountingPort, aclv6L3RuleTcpPshBit=aclv6L3RuleTcpPshBit, limitIpMulticaststartIpAddr=limitIpMulticaststartIpAddr, dosCtrlTrapLogState=dosCtrlTrapLogState, cosScheduleMechanism=cosScheduleMechanism, lldpXdot3LocPowerClass=lldpXdot3LocPowerClass, guestVlanDelState=guestVlanDelState, impbAutoScanEntry=impbAutoScanEntry, autoFdbTable=autoFdbTable, lldpXdot1RemVlanName=lldpXdot1RemVlanName, sysSNTPDSTEndMon=sysSNTPDSTEndMon, ipv4aclProfileSrcIpAddrMask=ipv4aclProfileSrcIpAddrMask, impbPortDHCPv4VlanList1k=impbPortDHCPv4VlanList1k, lldpXdot1ConfigProtoVlanTxEnable=lldpXdot1ConfigProtoVlanTxEnable, qosDiffServType19=qosDiffServType19, l2PTThresholdTable=l2PTThresholdTable, ipifV6AddressIpPrefix=ipifV6AddressIpPrefix, swTimeRangeStartMinute=swTimeRangeStartMinute, snmpTrapLBD=snmpTrapLBD, aclProfileType=aclProfileType)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", cpuFilterL3RuleICMPMessageType=cpuFilterL3RuleICMPMessageType, pppoePortState=pppoePortState, companyVLANTrunk=companyVLANTrunk, snmpV3UserTable=snmpV3UserTable, sysSNTPDSTRepeatStartHour=sysSNTPDSTRepeatStartHour, aclv6L3RuleICMPMessageType=aclv6L3RuleICMPMessageType, sysPortMediaTypeRev=sysPortMediaTypeRev, mstiBridgeRegionalRoot=mstiBridgeRegionalRoot, mldsHostPortPurgeInterval=mldsHostPortPurgeInterval, dot1qVlanUntaggedPorts=dot1qVlanUntaggedPorts, lldpXdot1LocProtocolTable=lldpXdot1LocProtocolTable, igmpMulticastVlanReplaceSourceIp=igmpMulticastVlanReplaceSourceIp, dhcpLocalRelaySettingsVLANID=dhcpLocalRelaySettingsVLANID, aclQosEntry=aclQosEntry, igsVlanReportSuppression=igsVlanReportSuppression, laAlgorithm=laAlgorithm, swAuthUserStatus=swAuthUserStatus, companyRMON=companyRMON, dhcpBOOTPRelayInterfaceSettingsTable=dhcpBOOTPRelayInterfaceSettingsTable, companyQinQ=companyQinQ, aclL3RuleProfileNo=aclL3RuleProfileNo, rmonEventCommunity=rmonEventCommunity, sysSNTPDSTOffset=sysSNTPDSTOffset, aclProfileDstIpAddrMask=aclProfileDstIpAddrMask, sysFromIP=sysFromIP, swAuthPortAccessCtrl=swAuthPortAccessCtrl, qinqVLANTranslation=qinqVLANTranslation, ipv4smtpRecvMailAddrTable=ipv4smtpRecvMailAddrTable, ftpFwUsername=ftpFwUsername, bandwidthCtrlTable=bandwidthCtrlTable, vlanMacMapAddrMask=vlanMacMapAddrMask, igmpMulticastVlanRemapPriority=igmpMulticastVlanRemapPriority, qosDiffServType27=qosDiffServType27, lldpXdot1LocEntry=lldpXdot1LocEntry, cpuFilterv6L3RuleTcpRstBit=cpuFilterv6L3RuleTcpRstBit, cpuFilterL3RuleTcpUdpSrcPort=cpuFilterL3RuleTcpUdpSrcPort, iPv4aacServerIPAddr=iPv4aacServerIPAddr, dhcpv6RelayOption18InterfaceIDType=dhcpv6RelayOption18InterfaceIDType, smtpServerAddrType=smtpServerAddrType, mldsVlanGrpQueryInterval=mldsVlanGrpQueryInterval, aclQosTCPUDPPort=aclQosTCPUDPPort, sysFirmwareInfomation=sysFirmwareInfomation, swTimeRangeRowStatus=swTimeRangeRowStatus, ddmStatusPort=ddmStatusPort, lldpXdot1ConfigProtocolTable=lldpXdot1ConfigProtocolTable, aclL3RuleDstIpAddrMask=aclL3RuleDstIpAddrMask, doSCtrlEntry=doSCtrlEntry, dhcpBOOTPRelayManagement=dhcpBOOTPRelayManagement, eoamMode=eoamMode, aacLoginMethod3=aacLoginMethod3, impbAutoScanTable=impbAutoScanTable, aclQosVlanID=aclQosVlanID, ipv4aclQosType=ipv4aclQosType, multicastVlanGroupVid=multicastVlanGroupVid, stpForwardDelay=stpForwardDelay, iPv4aacServerRowStatus=iPv4aacServerRowStatus, igmpMulticastVlanStatus=igmpMulticastVlanStatus, lldpXdot3LocPortAutoNegAdvertisedCap=lldpXdot3LocPortAutoNegAdvertisedCap, sysPortCtrlFlowControlOper=sysPortCtrlFlowControlOper, mldsStatus=mldsStatus, aacAPSSHLoginMethod=aacAPSSHLoginMethod, ipv4trustedHostRowStatus=ipv4trustedHostRowStatus, pppoePortIndex=pppoePortIndex, sshUserInfoHostName=sshUserInfoHostName, aclPacketAccessID=aclPacketAccessID, snmpV3UserPrivProtocolPassword=snmpV3UserPrivProtocolPassword, sysTrapPortSecurity=sysTrapPortSecurity, d_link=d_link, swAuthRadiusIPType=swAuthRadiusIPType, aacEnableMethod1=aacEnableMethod1, macNotifyInfo=macNotifyInfo, iPv4swAuthRadiusServerTable=iPv4swAuthRadiusServerTable, lldpXdot1RemVlanId=lldpXdot1RemVlanId, stpPortRestrictedTCN=stpPortRestrictedTCN, aclv6L3RuleFilterTimeRange=aclv6L3RuleFilterTimeRange, dot1qVlanManagementid=dot1qVlanManagementid, qosUserPriClass=qosUserPriClass, aclUdfOffsetBase1=aclUdfOffsetBase1, aclPacketRuleFilterTimeRange=aclPacketRuleFilterTimeRange, multicastVlanState=multicastVlanState, aclUdfOffsetBase4=aclUdfOffsetBase4, companyMacNotify=companyMacNotify, companyCableDiagnostic=companyCableDiagnostic, mldsHostTableGroupAddress=mldsHostTableGroupAddress, autoFdbStatus=autoFdbStatus, snmpV3CommunityEntry=snmpV3CommunityEntry, ipv4aclQosEntry=ipv4aclQosEntry, swAuthAuthReAuthentication=swAuthAuthReAuthentication, gvrpSettingsLeaveTime=gvrpSettingsLeaveTime, ipv4smtpSelfMailAddr=ipv4smtpSelfMailAddr, lldpXdot1Config=lldpXdot1Config, aacAuthenAdminState=aacAuthenAdminState, qosDiffServType43=qosDiffServType43, lldpXdot1LocVlanId=lldpXdot1LocVlanId, filterDHCPServerEntry=filterDHCPServerEntry, cpuFilterv6L3RuleTcpUdpSrcPort=cpuFilterv6L3RuleTcpUdpSrcPort, LldpPowerPortClass=LldpPowerPortClass, trafficCtrlCountDown=trafficCtrlCountDown, sysSNTPDSTRepeatStartWeekDay=sysSNTPDSTRepeatStartWeekDay, aclL3RuleICMPMessageType=aclL3RuleICMPMessageType, mstCistStatus=mstCistStatus, sysIpSubnetMask=sysIpSubnetMask, ddmStatusEntry=ddmStatusEntry, aacServerIPAddr=aacServerIPAddr, snmpV3UserVersion=snmpV3UserVersion, mldsHostTableHostIPAddress=mldsHostTableHostIPAddress, aclProfileDstIpAddrMaskType=aclProfileDstIpAddrMaskType, lldpXdot3LocPortTable=lldpXdot3LocPortTable, agentMEMutilizationIn5sec=agentMEMutilizationIn5sec, igsVlanCfgQuerier=igsVlanCfgQuerier, doSCtrlFrameCount=doSCtrlFrameCount, aclPacketRuleOffsetValue1=aclPacketRuleOffsetValue1, cosClassIndex=cosClassIndex, errorFrameWindow=errorFrameWindow, mldsVlanMulticastGroupEntry=mldsVlanMulticastGroupEntry, aacServerGroupRowStatus=aacServerGroupRowStatus, rmonStatsOwner=rmonStatsOwner, snmpV3TrapWarmStart=snmpV3TrapWarmStart, macNotifyInterval=macNotifyInterval, sysVersion=sysVersion, sysSafeGuardEnable=sysSafeGuardEnable, portSecState=portSecState, cpuFilterv6L3RuleSrcIpAddr=cpuFilterv6L3RuleSrcIpAddr, qinqGlobalStatus=qinqGlobalStatus, sysTrapDuplicateIPDetected=sysTrapDuplicateIPDetected, sysLBDVlanLoopPorts=sysLBDVlanLoopPorts, qinqTable=qinqTable, aRPSpoofPreventTable=aRPSpoofPreventTable, companyEoam=companyEoam, protocolGroupRowStatus=protocolGroupRowStatus, agentMEMutilization=agentMEMutilization, dhcpBOOTPRelayEnablePortlist=dhcpBOOTPRelayEnablePortlist, swTimeRangeSaturday=swTimeRangeSaturday, mstiConfigurationName=mstiConfigurationName, dhcpBOOTPRelayInterfaceSettingsRowStatus=dhcpBOOTPRelayInterfaceSettingsRowStatus, cosBandwidthCtrlTable=cosBandwidthCtrlTable, vlanMacMapAddr=vlanMacMapAddr, eoamSystem=eoamSystem, aclL3RuleProtocol=aclL3RuleProtocol, tftpFwTargetServerIpType=tftpFwTargetServerIpType, staticDisableAutoLearn=staticDisableAutoLearn, traps=traps, aclUdfOffsetMask3=aclUdfOffsetMask3, staticMcastIpAddr=staticMcastIpAddr, multicastVlanid=multicastVlanid, errorFrameSecondsWindow=errorFrameSecondsWindow, lldpXdot1ConfigVlanNameEntry=lldpXdot1ConfigVlanNameEntry, impbPortDHCPv6VlanList4k=impbPortDHCPv6VlanList4k, cpuFilterv6L3RuleTcpAckBit=cpuFilterv6L3RuleTcpAckBit, lldpXdot3LocPowerPairControlable=lldpXdot3LocPowerPairControlable, agentCPUutilizationIn5sec=agentCPUutilizationIn5sec, qosDiffServType61=qosDiffServType61, sfpVendorPn=sfpVendorPn, staticVlanBaseTable=staticVlanBaseTable, lldpXdot3PortConfigTLVsTxEnable=lldpXdot3PortConfigTLVsTxEnable, stpBridgeHelloTime=stpBridgeHelloTime, macNotifyInfoDiscription=macNotifyInfoDiscription, lldpXdot3LocMaxFrameSizeTable=lldpXdot3LocMaxFrameSizeTable, aclProfileDstPortMask=aclProfileDstPortMask, sysPortCtrlEntry=sysPortCtrlEntry, aclPacketRuleRateLimit=aclPacketRuleRateLimit, ipv4aclProfileSrcPortMask=ipv4aclProfileSrcPortMask, ipifSupportV4V6Info=ipifSupportV4V6Info, sysPortDescriptionTable=sysPortDescriptionTable, aclProfileArpSenderMacAddrMask=aclProfileArpSenderMacAddrMask, sysSNTPSecondType=sysSNTPSecondType, impbPortArpInspectionState=impbPortArpInspectionState, aclv6L3RuleAccessID=aclv6L3RuleAccessID, limitIpMulticastPortEntry=limitIpMulticastPortEntry, igsVlanMulticastGroupTable=igsVlanMulticastGroupTable, impbBlockListIpAddress=impbBlockListIpAddress, companyACLGroup=companyACLGroup, portSecFDBPermMac=portSecFDBPermMac, aacAPAuthMethodGroup=aacAPAuthMethodGroup, sysHardwareVersion=sysHardwareVersion, aclv6L3RuleICMPMessageCode=aclv6L3RuleICMPMessageCode, ftpConfigPassword=ftpConfigPassword, ipv4aclUdfOffsetByte3=ipv4aclUdfOffsetByte3, dhcpBOOTPRelayOption82CircuitID=dhcpBOOTPRelayOption82CircuitID, qosDiffServType48=qosDiffServType48, l2PTDropThreshold=l2PTDropThreshold, companyMldsGroup=companyMldsGroup, mstCistBridgePriority=mstCistBridgePriority, companyDHCPLocalRelay=companyDHCPLocalRelay, sysPortCtrlIndex=sysPortCtrlIndex, lldpXdot3LocPowerMDIEnabled=lldpXdot3LocPowerMDIEnabled, protocolVlanRowStatus=protocolVlanRowStatus, aclQosMACAddr=aclQosMACAddr, mldsVlanFbdRtrPortList=mldsVlanFbdRtrPortList, aclv6L3RuleTcpRstBit=aclv6L3RuleTcpRstBit, igsHostTableGroupAddress=igsHostTableGroupAddress, aclL3RuleReplace1P=aclL3RuleReplace1P, sysLBDPortLoopStatus=sysLBDPortLoopStatus, ipv4smtpRecvMailAddr=ipv4smtpRecvMailAddr, ipv4aclUdfOffsetBase2=ipv4aclUdfOffsetBase2, cpuFilterProfileIPProtocolMask=cpuFilterProfileIPProtocolMask, aacLoginMethodListIndex=aacLoginMethodListIndex, vlanMacMapIndex=vlanMacMapIndex, stpRootBridge=stpRootBridge, bandwidthCtrlIndex=bandwidthCtrlIndex, aclL3RuleTcpAckBit=aclL3RuleTcpAckBit, aclv6L3RuleDstIpAddrMask=aclv6L3RuleDstIpAddrMask, rmonHistoryEntry=rmonHistoryEntry, aacAccountingServiceSystem=aacAccountingServiceSystem, laPortChannelIfIndex=laPortChannelIfIndex, dhcpLocalRelayTableEntry=dhcpLocalRelayTableEntry, rmonEventType=rmonEventType, aacAccountingServiceCommandPoweruser=aacAccountingServiceCommandPoweruser, sysPortErrEntry=sysPortErrEntry, qinqTrustCVIDState=qinqTrustCVIDState, aclL3RuleTcpUdpSrcPortMask=aclL3RuleTcpUdpSrcPortMask, doSCtrlState=doSCtrlState, PortList=PortList, ipv4cpuFilterProfileDstMacAddrMask=ipv4cpuFilterProfileDstMacAddrMask, qosDiffServTOS=qosDiffServTOS, aclFlowMeterRate=aclFlowMeterRate, aacAPEnableMethod=aacAPEnableMethod, qosDefaultUserPri=qosDefaultUserPri, qinqSystem=qinqSystem, macNotifyCtrlEntry=macNotifyCtrlEntry, dot1qVlanEntry=dot1qVlanEntry, lldpXdot1ConfigPortVlanTable=lldpXdot1ConfigPortVlanTable, macBasedVlanMethod=macBasedVlanMethod, aclv6L3RuleTcpFinBit=aclv6L3RuleTcpFinBit, multicastVlanName=multicastVlanName, dhcpv6RelayOption37=dhcpv6RelayOption37, lldpXdot3RemMaxFrameSizeEntry=lldpXdot3RemMaxFrameSizeEntry, dhcpv6RelayOption18State=dhcpv6RelayOption18State, swAuthStatus=swAuthStatus, companyIgsGroup=companyIgsGroup, neighborIfindex=neighborIfindex, sysPortMediaTypeVendorName=sysPortMediaTypeVendorName, aclv6L3RuleProtocolMask=aclv6L3RuleProtocolMask, mldsDataDrivenLearningMaxLearnedEntryVlaue=mldsDataDrivenLearningMaxLearnedEntryVlaue, stpPortPriority=stpPortPriority, doSCtrlActionType=doSCtrlActionType, ipv4aclUdfOffsetMask4=ipv4aclUdfOffsetMask4, impbAutoScanIpAddress=impbAutoScanIpAddress, aclPacketRuleOffsetValue4=aclPacketRuleOffsetValue4, swTimeRangeMonday=swTimeRangeMonday, aclv6L3RuleTcpUdpSrcPortMask=aclv6L3RuleTcpUdpSrcPortMask, aacAccountingMethodListEntry=aacAccountingMethodListEntry, impbBindingListRowStatus=impbBindingListRowStatus, ddmStatusTable=ddmStatusTable, lldpXdot1LocProtocolId=lldpXdot1LocProtocolId, cpuFilterL2ProfileID=cpuFilterL2ProfileID, companyGVRPGroup=companyGVRPGroup, aclL3RuleEntry=aclL3RuleEntry, Timeout=Timeout, aclv6L3RuleTcpSynBit=aclv6L3RuleTcpSynBit, sysSNTPState=sysSNTPState, errorFrameSecondsThreshold=errorFrameSecondsThreshold, snmpV3GroupName=snmpV3GroupName, lldpXdot1ConfigVlanNameTxEnable=lldpXdot1ConfigVlanNameTxEnable)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", ftpConfigPath=ftpConfigPath, ipv4aclUdfOffsetByte2=ipv4aclUdfOffsetByte2, snmpV3GroupNotifyViewName=snmpV3GroupNotifyViewName, snmpV3UserAuthProtocolPassword=snmpV3UserAuthProtocolPassword, BridgeId=BridgeId, aclPacketRuleOffsetValue3Mask=aclPacketRuleOffsetValue3Mask, vlanMacMapRowStatus=vlanMacMapRowStatus, laSystem=laSystem, dlink_DES1210SeriesProd=dlink_DES1210SeriesProd, protocolGroupNameTable=protocolGroupNameTable, ipv4aclProfileType=ipv4aclProfileType, ddmThresholdType=ddmThresholdType, ddmInfo=ddmInfo, iPv4aacServerInfoTable=iPv4aacServerInfoTable, limitIpMulticastProfileTable=limitIpMulticastProfileTable, aclv6L3RuleSrcIpAddrMask=aclv6L3RuleSrcIpAddrMask, lldpXdot1RemProtoVlanTable=lldpXdot1RemProtoVlanTable, multicastVlanGroupTable=multicastVlanGroupTable, autoFdbEntry=autoFdbEntry, limitIpMulticastEntryProfileID=limitIpMulticastEntryProfileID, companySystem=companySystem, aclProfileUdfOffsetMap=aclProfileUdfOffsetMap, impbPortDHCPv6VlanList1k=impbPortDHCPv6VlanList1k, sysSNTPGMTMinutes=sysSNTPGMTMinutes, mldsVlanMulticastGroupVlanId=mldsVlanMulticastGroupVlanId, aclL3RuleSrcIpAddr=aclL3RuleSrcIpAddr, aclL3RuleStatus=aclL3RuleStatus, stpPortRestrictedRole=stpPortRestrictedRole, lldpPortConfigNotificationEnable=lldpPortConfigNotificationEnable, aclFlowMeterReplaceDscp=aclFlowMeterReplaceDscp, aclv6L3RuleEntry=aclv6L3RuleEntry, rmonAlarmOwner=rmonAlarmOwner, qosTOSType00=qosTOSType00, ipv4sysIprouteHops=ipv4sysIprouteHops, limitIpMulticastProfileName=limitIpMulticastProfileName, mldsVlanRtrPortList=mldsVlanRtrPortList, cpuFilterL3RuleTcpFinBit=cpuFilterL3RuleTcpFinBit, macNotifyPortStatus=macNotifyPortStatus, rmonEventOwner=rmonEventOwner, mstResetVlanList=mstResetVlanList, cpuFilterv6L3RuleProtocol=cpuFilterv6L3RuleProtocol, aclProfileSrcMacAddrMask=aclProfileSrcMacAddrMask, tftpFwServerIpAddress=tftpFwServerIpAddress, swAuthAuthServerTimeout=swAuthAuthServerTimeout, lldpXdot3LocLinkAggStatus=lldpXdot3LocLinkAggStatus, agentCPUutilization=agentCPUutilization, cableDiagEntry=cableDiagEntry, cpuFilterL2RuleAction=cpuFilterL2RuleAction, cpuFilterL3RuleTcpUrgBit=cpuFilterL3RuleTcpUrgBit, pppoePortTable=pppoePortTable, securityTrustedHost=securityTrustedHost, syslogSaveMode=syslogSaveMode, dhcpv6RelayOption18=dhcpv6RelayOption18, eoamReceivedRemoteLoopback=eoamReceivedRemoteLoopback, impbDhcpSnoopingTable=impbDhcpSnoopingTable, aacAccountingMethod4=aacAccountingMethod4, swAuthRadiusServerEntry=swAuthRadiusServerEntry, impbBindingListPort=impbBindingListPort, snmpTrapBPDUAttack=snmpTrapBPDUAttack, duldOperState=duldOperState, snmpV3CommunityStatus=snmpV3CommunityStatus, dhcpv6RelayState=dhcpv6RelayState, aacAPTelnetLoginMethod=aacAPTelnetLoginMethod, cpuFilterL3RuleProtocol=cpuFilterL3RuleProtocol, ipv4aclProfileNo=ipv4aclProfileNo, rmonHistoryDataSource=rmonHistoryDataSource, sysPortType=sysPortType, mstMstiBridgeEntry=mstMstiBridgeEntry, aclL3RuleSrcIpAddrMask=aclL3RuleSrcIpAddrMask, swTimeRangeSunday=swTimeRangeSunday, stpPortStatus=stpPortStatus, igmpMulticastVlanid=igmpMulticastVlanid, dhcpRelayVlanSettingsVLANID=dhcpRelayVlanSettingsVLANID, bandwidthEffecRxThreshold=bandwidthEffecRxThreshold, impbPortForwardDHCPPktState=impbPortForwardDHCPPktState, sysPortDescriptionEntry=sysPortDescriptionEntry, aclPacketRuleOffsetValue4Mask=aclPacketRuleOffsetValue4Mask, lldpXdot1LocProtoVlanSupported=lldpXdot1LocProtoVlanSupported, aclL2RuleAction=aclL2RuleAction, aacAccountingServiceIndex=aacAccountingServiceIndex, sysSize=sysSize, swTimeRangeSettingTable=swTimeRangeSettingTable, sysSNTPDSTRepeatEndHour=sysSNTPDSTRepeatEndHour, aclL3RuleDstIpAddr=aclL3RuleDstIpAddr, aclL3RuleAccessID=aclL3RuleAccessID, swAuthenCtrl=swAuthenCtrl, ipv4aclQosIPAddr=ipv4aclQosIPAddr, lldpXdot1LocVlanName=lldpXdot1LocVlanName, limitIpMulticastEntry=limitIpMulticastEntry, aclProfileEntry=aclProfileEntry, qosDiffServType33=qosDiffServType33, LldpLinkAggStatusMap=LldpLinkAggStatusMap, igmpMulticastVlanMemberPort=igmpMulticastVlanMemberPort, aclPacketRuleInPortList=aclPacketRuleInPortList, lldpXdot3RemMaxFrameSize=lldpXdot3RemMaxFrameSize, ipv4dhcpOption12HostName=ipv4dhcpOption12HostName, pppoePortUDFString=pppoePortUDFString, aRPSpoofPreventIpAddr=aRPSpoofPreventIpAddr, l2PTProtocol=l2PTProtocol, multicastVlanGroupFromIp=multicastVlanGroupFromIp, filterDHCPServerTable=filterDHCPServerTable, sysSMTPServerGroup=sysSMTPServerGroup, cosOutputSchedule=cosOutputSchedule, lldpXdot3PortConfigTable=lldpXdot3PortConfigTable, multicastVlanTagMemberPort=multicastVlanTagMemberPort, lldpXdot3RemPortEntry=lldpXdot3RemPortEntry, ipv4syslogServSrvStatus=ipv4syslogServSrvStatus, swTimeRangeEndHour=swTimeRangeEndHour, companyLA=companyLA, snmpV3TrapColdStart=snmpV3TrapColdStart, lldpPortConfigTable=lldpPortConfigTable, swTimeRangeStartYear=swTimeRangeStartYear, qosDiffServType40=qosDiffServType40, aclPacketRuleReplaceDSCP=aclPacketRuleReplaceDSCP, limitIpMulticastStatus=limitIpMulticastStatus, snmpV3ViewTree=snmpV3ViewTree, stpPortEntry=stpPortEntry, impbBindingtraplog=impbBindingtraplog, cpuFilterv6L3RuleEntry=cpuFilterv6L3RuleEntry, errorFrameThreshold=errorFrameThreshold, lldpXdot3RemPowerTable=lldpXdot3RemPowerTable, protocolGroupProtocolValue=protocolGroupProtocolValue, aacLoginMethod2=aacLoginMethod2, sysUpdateTime=sysUpdateTime, companyMacBasedVlan=companyMacBasedVlan, snmpV3CommunityName=snmpV3CommunityName, igsHostTable=igsHostTable, qosPriSettingsTable=qosPriSettingsTable, cpuFilterv6L3RuleTcpUdpDstPortMask=cpuFilterv6L3RuleTcpUdpDstPortMask, qinqOuterTPID=qinqOuterTPID, lldpPortConfigPortNum=lldpPortConfigPortNum, guestVlanName=guestVlanName, impbDhcpSnoopingEntry=impbDhcpSnoopingEntry, aclQosTable=aclQosTable, sysTrapLBD=sysTrapLBD, LacpKey=LacpKey, qosPriSetPortIndex=qosPriSetPortIndex, qosDiffServType29=qosDiffServType29, ipv4sysSNTPState=ipv4sysSNTPState, cpuFilterL3RuleTcpAckBit=cpuFilterL3RuleTcpAckBit, ipv4aclUdfOffsetByte1=ipv4aclUdfOffsetByte1, aclL2RuleTable=aclL2RuleTable, lldpXdot3RemoteData=lldpXdot3RemoteData, cableDiagPair3Length=cableDiagPair3Length, cpuFilterProfileNo=cpuFilterProfileNo, mstMstiStatus=mstMstiStatus, sysBPDUAttackStateEnable=sysBPDUAttackStateEnable, qosDiffServType44=qosDiffServType44, trafficCtrlIndex=trafficCtrlIndex, companyCPUInterfaceFilterGroup=companyCPUInterfaceFilterGroup, qosDefaultPriority=qosDefaultPriority, companyGratuitousARP=companyGratuitousARP, qosDiffServType47=qosDiffServType47, ipv4aclProfileUdfOffsetMap=ipv4aclProfileUdfOffsetMap, ipifV6AddressIpAddr=ipifV6AddressIpAddr, snmpTrapFirmUpgrade=snmpTrapFirmUpgrade, impbVlanModeVlanList=impbVlanModeVlanList, dhcpv6RelayOption37RemoteIDType=dhcpv6RelayOption37RemoteIDType, bandwidthCtrlTxThreshold=bandwidthCtrlTxThreshold, aclL2RuleStatus=aclL2RuleStatus, dhcpv6RelayOpt38PortState=dhcpv6RelayOpt38PortState, lldpXdot1RemEntry=lldpXdot1RemEntry, cableDiagStatus=cableDiagStatus, mldsVlanFilterEntry=mldsVlanFilterEntry, duldEntry=duldEntry, qosDiffServType18=qosDiffServType18, lldpXdot1LocalData=lldpXdot1LocalData, agentMEMutilizationIn1min=agentMEMutilizationIn1min, laPortActorActivity=laPortActorActivity, companyMirror=companyMirror, sysPortMediaTypeSn=sysPortMediaTypeSn, swAuthPortAccessControlTable=swAuthPortAccessControlTable, aclv6L3RuleTcpUdpSrcPort=aclv6L3RuleTcpUdpSrcPort, aacAccountingMethodListName=aacAccountingMethodListName, impbPortDHCPv4VlanList4k=impbPortDHCPv4VlanList4k, swTimeRangeIndex=swTimeRangeIndex, tftpFwTargetInterfaceName=tftpFwTargetInterfaceName, multicastVlanRowStatus=multicastVlanRowStatus, impbAutoScanIpAddressTo=impbAutoScanIpAddressTo, ipifv6NSRetransmitTime=ipifv6NSRetransmitTime, mstMstiInstanceIndex=mstMstiInstanceIndex, limitIpMulticastPortID=limitIpMulticastPortID, eoamLinkMonitorTable=eoamLinkMonitorTable, impbPortDHCPv6SetVlanList=impbPortDHCPv6SetVlanList, impbDhcpSnoopingIpAddress=impbDhcpSnoopingIpAddress, cpuFilterProfileSrcIpAddrMask=cpuFilterProfileSrcIpAddrMask, swTimeRangeEndDay=swTimeRangeEndDay, mstCistVlanMapped4k=mstCistVlanMapped4k, gvrpGVRPGlobalSettingsOnOff=gvrpGVRPGlobalSettingsOnOff, dhcpv6RelayInterfaceSettingsEntry=dhcpv6RelayInterfaceSettingsEntry, snmpV3UserAuthProtocol=snmpV3UserAuthProtocol, lldpXdot3RemPowerMDIEnabled=lldpXdot3RemPowerMDIEnabled, qosTOSType06=qosTOSType06, ipv4smtpServerPort=ipv4smtpServerPort, aacAccountingMethod3=aacAccountingMethod3, laPortControlIndex=laPortControlIndex, gvrpSettingsPortControlIndex=gvrpSettingsPortControlIndex, aacServerPasswordEncryption=aacServerPasswordEncryption, sysBPDUAttackPortStatus=sysBPDUAttackPortStatus, qosUserPriority=qosUserPriority, impbDhcpSnoopingLeaseTime=impbDhcpSnoopingLeaseTime, iPv4aacServerRetryCount=iPv4aacServerRetryCount, ipv4aclProfileRuleCount=ipv4aclProfileRuleCount, dhcpv6RelayOpt38Entry=dhcpv6RelayOpt38Entry, companyDoSCtrl=companyDoSCtrl, protocolVlanVID=protocolVlanVID, ddmHighAlarm=ddmHighAlarm, sysSwitchName=sysSwitchName, portSecFDBPermVlanID=portSecFDBPermVlanID, ipv4aclProfileTable=ipv4aclProfileTable, des_1210_28me=des_1210_28me, igsVlanFastLeave=igsVlanFastLeave, iPv4swAuthRadiusServerRetransmit=iPv4swAuthRadiusServerRetransmit, miscStatisticsReset=miscStatisticsReset, ipv4sysSNTPDSTStartMin=ipv4sysSNTPDSTStartMin, lldpXdot3LocalData=lldpXdot3LocalData, mstInstanceVlanMapped4k=mstInstanceVlanMapped4k, trustedHostEntry=trustedHostEntry, ftpConfigUsername=ftpConfigUsername, igsDataDrivenLearningMaxLearnedEntryVlaue=igsDataDrivenLearningMaxLearnedEntryVlaue, multicastVlanGroupToIp=multicastVlanGroupToIp, ipv4dhcpOption12Status=ipv4dhcpOption12Status, errorFrameNotifyState=errorFrameNotifyState, qosDiffServType39=qosDiffServType39, aacAuthParamAttempt=aacAuthParamAttempt, ipifV6AddressMainIndex=ipifV6AddressMainIndex, sysTrapTwistedPortEvent=sysTrapTwistedPortEvent, staticStatus=staticStatus, sysMirrorTargetPort=sysMirrorTargetPort, qinqIfIndex=qinqIfIndex, mldsVlanRobustnessValue=mldsVlanRobustnessValue, swAuthUserEntry=swAuthUserEntry, errorSymbolNotifyState=errorSymbolNotifyState, tftpFwTftpOperationStatus=tftpFwTftpOperationStatus, qosDiffServType30=qosDiffServType30, cpuFilterL2RuleDstMacAddr=cpuFilterL2RuleDstMacAddr, lldpPortConfigAdminStatus=lldpPortConfigAdminStatus, agentCPUutilizationIn1min=agentCPUutilizationIn1min, ipv4snmpV3HostVersion=ipv4snmpV3HostVersion, sysGratuitousARPLearning=sysGratuitousARPLearning, ipv4smtpServerAddr=ipv4smtpServerAddr, aacServerAuthPort=aacServerAuthPort, qosTOSGroup=qosTOSGroup, ddmTemperature=ddmTemperature, cpuFilterv6L3RuleDstIpAddrMask=cpuFilterv6L3RuleDstIpAddrMask, sshUserInfoAuth=sshUserInfoAuth, impbBlockListStatus=impbBlockListStatus, ipv4aclProfileIPProtocol=ipv4aclProfileIPProtocol, ipv4aclProfileStatus=ipv4aclProfileStatus, lldpXdot1RemPortVlanId=lldpXdot1RemPortVlanId, sysSNTPServerTable=sysSNTPServerTable, sysSNTPDSTEndMin=sysSNTPDSTEndMin, qosDefaultUserPriTable=qosDefaultUserPriTable, rmonEventEntry=rmonEventEntry)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", dot1qVlanAdvertisementStatus=dot1qVlanAdvertisementStatus, lldpXdot3LocPowerTable=lldpXdot3LocPowerTable, qosDiffServType26=qosDiffServType26, aclv6L3RuleTcpAckBit=aclv6L3RuleTcpAckBit, filterDHCPServerRowStatus=filterDHCPServerRowStatus, impbPortIndex=impbPortIndex, ipv4trustedHostIpMask=ipv4trustedHostIpMask, ddmVoltage=ddmVoltage, aacAPHttpEnableMethod=aacAPHttpEnableMethod, swAuthAuthSuppTimeout=swAuthAuthSuppTimeout, snmpV3TrapSNMPAuthentication=snmpV3TrapSNMPAuthentication, sysPortErrPortReason=sysPortErrPortReason, staticVlanBaseEnableAutoLearn=staticVlanBaseEnableAutoLearn, gvrpSettingsJoinTime=gvrpSettingsJoinTime, macNotifyState=macNotifyState, aacServerGroupEntry=aacServerGroupEntry, igmpMulticastVlanGroupStatus=igmpMulticastVlanGroupStatus, mldsVlan=mldsVlan, impbPortDHCPv4SetVlanList=impbPortDHCPv4SetVlanList, qosTOSType05=qosTOSType05, ddmBiasCurrent=ddmBiasCurrent, cpuFilterv6L3RuleProtocolMask=cpuFilterv6L3RuleProtocolMask, qosDiffServType13=qosDiffServType13, mldsSystem=mldsSystem, staticARPMac=staticARPMac, ipv4sysSNTPDSTEndMin=ipv4sysSNTPDSTEndMin, qosTOSType07=qosTOSType07, rmonHistoryStatus=rmonHistoryStatus, tftpFwTargetTftpOperation=tftpFwTargetTftpOperation, aclQosIPv6Addr=aclQosIPv6Addr, igsVlan=igsVlan, qosDiffServType09=qosDiffServType09, lldpXdot1LocVlanNameTable=lldpXdot1LocVlanNameTable, ipv4sysIprouteGateway=ipv4sysIprouteGateway, duldLinkStatus=duldLinkStatus, stpPortTable=stpPortTable, gvrpSettingsTable=gvrpSettingsTable, dot1qVlanName=dot1qVlanName, ipifName=ipifName, trafficSegMemberList=trafficSegMemberList, swTimeRangeEndMinute=swTimeRangeEndMinute, cpuFilterv6L3RuleDstIpAddr=cpuFilterv6L3RuleDstIpAddr, sysSNTPDSTRepeatEndMin=sysSNTPDSTRepeatEndMin, sysTrapFirmUpgradeEvent=sysTrapFirmUpgradeEvent, qosDiffServType46=qosDiffServType46, l2PTPortIndex=l2PTPortIndex, aRPSpoofPreventMacAddress=aRPSpoofPreventMacAddress, cpuFilterProfileDstIpAddrMask=cpuFilterProfileDstIpAddrMask, aacAccountingServiceNetwork=aacAccountingServiceNetwork, sysPortCtrlMDI=sysPortCtrlMDI, iPv4swAuthRadiusServerStatus=iPv4swAuthRadiusServerStatus, dlink_products=dlink_products, impbBindingListMacAddress=impbBindingListMacAddress, dhcpBOOTPRelayManagementOption82=dhcpBOOTPRelayManagementOption82, aacEnableMethodListIndex=aacEnableMethodListIndex, sysSNTPPollInterval=sysSNTPPollInterval, lldpXdot3Objects=lldpXdot3Objects, sysPortCtrlCapability=sysPortCtrlCapability, mstMstiPortEntry=mstMstiPortEntry, snmpV3GroupReadViewName=snmpV3GroupReadViewName, ftpFwFTPOperation=ftpFwFTPOperation, mstMstiBridgeTable=mstMstiBridgeTable, aclProfileIPProtocol=aclProfileIPProtocol, securitySSH=securitySSH, aclL2RuleReplaceQueue=aclL2RuleReplaceQueue, qosDiffServType08=qosDiffServType08, lldpXdot3RemPortAutoNegAdvertisedCap=lldpXdot3RemPortAutoNegAdvertisedCap, trafficSegTable=trafficSegTable, snmpV3TrapDHCPServerScreening=snmpV3TrapDHCPServerScreening, mstMstiCurrentPortRole=mstMstiCurrentPortRole, dhcpv6RelayOption37CheckState=dhcpv6RelayOption37CheckState, igmpMulticastVlanSourcePort=igmpMulticastVlanSourcePort, stpInstancePortTable=stpInstancePortTable, trafficCtrlThreshold=trafficCtrlThreshold, trustedHostIpAddr=trustedHostIpAddr, ipv4snmpV3HostEntry=ipv4snmpV3HostEntry, cpuFilterv6L3RuleSrcIpAddrMask=cpuFilterv6L3RuleSrcIpAddrMask, staticPort=staticPort, companySNTPSetting=companySNTPSetting, cableDiagPortType=cableDiagPortType, snmpV3HostTable=snmpV3HostTable, aclPacketRuleReplace1P=aclPacketRuleReplace1P, igsSystem=igsSystem, dlinklldpConfigManAddrPortsTxEnable=dlinklldpConfigManAddrPortsTxEnable, impbRoamingState=impbRoamingState, sysLocationName=sysLocationName, vlanTrunkGlobalStatus=vlanTrunkGlobalStatus, rmonHistoryBucketsRequested=rmonHistoryBucketsRequested, lldpXdot3LocPowerEntry=lldpXdot3LocPowerEntry, smtpRecvMailAddrTable=smtpRecvMailAddrTable, sysPortMediaTypeTable=sysPortMediaTypeTable, sysMirrorStatus=sysMirrorStatus, syslogServEntry=syslogServEntry, aclPacketRuleOffsetValue1Mask=aclPacketRuleOffsetValue1Mask, snmpV3IPType=snmpV3IPType, securityARPSpoofPrevent=securityARPSpoofPrevent, lldpXdot3RemPortAutoNegSupported=lldpXdot3RemPortAutoNegSupported, aclv6L3RuleTcpUdpDstPort=aclv6L3RuleTcpUdpDstPort, cpuFilterv6L3RuleTcpUrgBit=cpuFilterv6L3RuleTcpUrgBit, igsVlanRouterPortList=igsVlanRouterPortList, syslogServIndex=syslogServIndex, impbPortDHCPv4VlanList3k=impbPortDHCPv4VlanList3k, companyLBD=companyLBD, aclProfileStatus=aclProfileStatus, sysWebState=sysWebState, sysIpAddrCfgMode=sysIpAddrCfgMode, rmonAlarmVariable=rmonAlarmVariable, stpRootPort=stpRootPort, sysGroupInterval=sysGroupInterval, qosDiffServType52=qosDiffServType52, tftpConfigTftpOperationStatus=tftpConfigTftpOperationStatus, aclv6L3RuleReplaceDSCP=aclv6L3RuleReplaceDSCP, lldpXdot3RemPortTable=lldpXdot3RemPortTable, ipv4smtpState=ipv4smtpState, errorFramePeriodThreshold=errorFramePeriodThreshold, protocolGroupName=protocolGroupName, PortLaMode=PortLaMode, igsVlanFbdRtrPortList=igsVlanFbdRtrPortList, ipv4sysSNTPDSTEndDay=ipv4sysSNTPDSTEndDay, qinqVLANTranslationState=qinqVLANTranslationState, snmpTrapGratuitousArp=snmpTrapGratuitousArp, igsVlanMulticastGroupVlanId=igsVlanMulticastGroupVlanId, aclFlowMeterAccessID=aclFlowMeterAccessID, dhcpRelayVlanTable=dhcpRelayVlanTable, companyDot1qVlanGroup=companyDot1qVlanGroup, portSecFDBPermPort=portSecFDBPermPort, cpuFilterProfileRuleCount=cpuFilterProfileRuleCount, snmpV3HostInterfaceName=snmpV3HostInterfaceName, ipifv6DefaultGateway=ipifv6DefaultGateway, cpuFilterProfileTable=cpuFilterProfileTable, aacAccountingServiceCommandUser=aacAccountingServiceCommandUser, cpuFilterProfileEntry=cpuFilterProfileEntry, duldIfIndex=duldIfIndex, protocolGroupEntry=protocolGroupEntry, stpPortEdge=stpPortEdge, snmpTrapPortSecurity=snmpTrapPortSecurity, l2PTProtocolIndex=l2PTProtocolIndex, smtpServerPort=smtpServerPort, ipifV6AddressTable=ipifV6AddressTable, trafficSegEntry=trafficSegEntry, qosDiffServType49=qosDiffServType49, aclQosType=aclQosType, vlanTrunkTable=vlanTrunkTable, cosClassTable=cosClassTable, mstCistPortTable=mstCistPortTable, tftpCfgTargetServerIpType=tftpCfgTargetServerIpType, qosDiffServType42=qosDiffServType42, dhcpRelayVlanTableEntry=dhcpRelayVlanTableEntry, aacServerGroupTable=aacServerGroupTable, dot1qVlanAsyOnOff=dot1qVlanAsyOnOff, protocolGroupFrameType=protocolGroupFrameType, laPortChannelMasterPort=laPortChannelMasterPort, aacAccountingMethodListTable=aacAccountingMethodListTable, l2PTEntry=l2PTEntry, igsReportToAllPort=igsReportToAllPort, neighborRowStatus=neighborRowStatus, brgAddress=brgAddress, qinqVlanTranslationSVID=qinqVlanTranslationSVID, cpuFilterL3RulePortList=cpuFilterL3RulePortList, lldpXdot3LocPowerPairs=lldpXdot3LocPowerPairs, impbPortProtocolState=impbPortProtocolState, qosPriSettingsEntry=qosPriSettingsEntry, filterDHCPServerIpAddr=filterDHCPServerIpAddr, sysGratuitousARPDuplicateIPDetected=sysGratuitousARPDuplicateIPDetected, tftpFwImageFileName=tftpFwImageFileName, ipv4aclProfileArpSenderIpAddrMask=ipv4aclProfileArpSenderIpAddrMask, syslogServAddr=syslogServAddr, sysPortCtrlFlowControl=sysPortCtrlFlowControl, aclv6L3RuleAction=aclv6L3RuleAction, lldpXdot1LocProtoVlanId=lldpXdot1LocProtoVlanId, sysPortErrPortStatus=sysPortErrPortStatus, mldsVlanRouterPortList=mldsVlanRouterPortList, laPortControlEntry=laPortControlEntry, iPv4swAuthRadiusServerTimeout=iPv4swAuthRadiusServerTimeout, ipv4aclQosProtocol=ipv4aclQosProtocol, snmpTrapWarmStart=snmpTrapWarmStart, dhcpRelayVlanSettingsState=dhcpRelayVlanSettingsState, multicastVlanGroupEntry=multicastVlanGroupEntry, autoRefreshConfiguration=autoRefreshConfiguration, filterDHCPServerPortList=filterDHCPServerPortList, topologyChange=topologyChange, securityAAC=securityAAC, lldpXdot1RemProtocolId=lldpXdot1RemProtocolId, cpuFilterProfileSrcIpAddrMaskType=cpuFilterProfileSrcIpAddrMaskType, syslogServAddrType=syslogServAddrType, ipv4syslogServerGroup=ipv4syslogServerGroup, cpuFilterv6L3RulePortList=cpuFilterv6L3RulePortList, mstCistPortPriority=mstCistPortPriority, swTimeRangeDate=swTimeRangeDate, sysDhcpAutoConfiguration=sysDhcpAutoConfiguration, sysLBDStateEnable=sysLBDStateEnable, tftpFwTargetGroup=tftpFwTargetGroup, sysSNTPDSTState=sysSNTPDSTState, igsVlanGrpQueryInterval=igsVlanGrpQueryInterval, snmpV3CommunityTable=snmpV3CommunityTable, tftpFwTftpOperation=tftpFwTftpOperation, companyDDM=companyDDM, qosDiffServType24=qosDiffServType24, igmpMulticastVlanState=igmpMulticastVlanState, aRPSpoofPreventEntry=aRPSpoofPreventEntry, snmpTrapDHCPScreen=snmpTrapDHCPScreen, smtpRecvMailAddrIndex=smtpRecvMailAddrIndex, cableDiagPair2Status=cableDiagPair2Status, aclPacketRuleReplaceQueue=aclPacketRuleReplaceQueue, impbSettingTable=impbSettingTable, impbDHCPv6PrefixDelegationSnoopState=impbDHCPv6PrefixDelegationSnoopState, protocolVlanPort=protocolVlanPort, mstMstiPortDesignatedBridge=mstMstiPortDesignatedBridge, lldpXdot1LocProtoVlanEntry=lldpXdot1LocProtoVlanEntry, sysTrapSystemEvent=sysTrapSystemEvent, ipv4aclQosAssignClass=ipv4aclQosAssignClass, lldpXdot3LocPortAutoNegEnabled=lldpXdot3LocPortAutoNegEnabled, igsVlanFilterEntry=igsVlanFilterEntry, aclProfileSrcIpAddrMask=aclProfileSrcIpAddrMask, igsHostTableVLANID=igsHostTableVLANID, aclL3RuleIgmpType=aclL3RuleIgmpType, swAuthRadiusServerAuthenticationPort=swAuthRadiusServerAuthenticationPort, sysSNTPDSTEndHour=sysSNTPDSTEndHour, lldpXdot1RemProtoVlanSupported=lldpXdot1RemProtoVlanSupported, ipv4aclProfileSrcMacAddrMask=ipv4aclProfileSrcMacAddrMask, sysTrapFiberPortEvent=sysTrapFiberPortEvent, ipv4aclUdfOffsetBase3=ipv4aclUdfOffsetBase3, lldpXdot3LocMaxFrameSize=lldpXdot3LocMaxFrameSize, iPv4aacServerAuthProtocol=iPv4aacServerAuthProtocol, trafficCtrlType=trafficCtrlType, sfpConnectorType=sfpConnectorType, companyPPPoE=companyPPPoE, syslogSaveMinutes=syslogSaveMinutes, errorFrameSecondsNotifyState=errorFrameSecondsNotifyState, cpuFilterL2RuleInPortList=cpuFilterL2RuleInPortList, ipifv6AutolinkloStatus=ipifv6AutolinkloStatus, impbBindingListEntry=impbBindingListEntry, iPv4aacServerAuthPort=iPv4aacServerAuthPort, aclProfileIPProtocolMask=aclProfileIPProtocolMask, smtpRecvMailAddrEntry=smtpRecvMailAddrEntry, laPortChannelEntry=laPortChannelEntry, tftpFwTargetServerIpAddress=tftpFwTargetServerIpAddress, rmonStatsIndex=rmonStatsIndex, ftpFwTable=ftpFwTable, laPortChannelMemberList=laPortChannelMemberList, aclPacketRule=aclPacketRule, qosDiffServType54=qosDiffServType54, cpuFilterv6L3RuleTcpPshBit=cpuFilterv6L3RuleTcpPshBit, sysARPAgingTime=sysARPAgingTime, errorSymbolThreshold=errorSymbolThreshold, qosDefaultUserPriPortIndex=qosDefaultUserPriPortIndex, aclPacketRuleAction=aclPacketRuleAction, aclL2RuleSrcMacAddr=aclL2RuleSrcMacAddr, qosDiffServType56=qosDiffServType56, snmpV3HostEntry=snmpV3HostEntry, swTimeRangeWednesday=swTimeRangeWednesday, dhcpOption12Status=dhcpOption12Status, filterDHCPServerClientMacAddr=filterDHCPServerClientMacAddr, aclL2RuleRateLimit=aclL2RuleRateLimit)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", cpuFilterL3RuleTcpPshBit=cpuFilterL3RuleTcpPshBit, sysGratuitousARPSettings=sysGratuitousARPSettings, igsVlanMulticastGroupPortList=igsVlanMulticastGroupPortList, snmpV3ViewTreeEntry=snmpV3ViewTreeEntry, sshUserInfoHostIp=sshUserInfoHostIp, autoFdbTimeStamp=autoFdbTimeStamp, mstVlanMstiMappingTable=mstVlanMstiMappingTable, igsHostEntry=igsHostEntry, sshAuthenMethodPubKeyAdmin=sshAuthenMethodPubKeyAdmin, dot1qVlanRowStatus=dot1qVlanRowStatus, staticMcastStatus=staticMcastStatus, impbDhcpSnoopingPort=impbDhcpSnoopingPort, aclL2Rule=aclL2Rule, aclFlowMeterTable=aclFlowMeterTable, sysPortDescString=sysPortDescString, aclUdfOffsetBase3=aclUdfOffsetBase3, ipv4cpuFilterProfileType=ipv4cpuFilterProfileType, sfpVendorSn=sfpVendorSn, snmpTrapColdStart=snmpTrapColdStart, impbBindingListIpAddress=impbBindingListIpAddress, mstMstiBridgePriority=mstMstiBridgePriority, dot1qVlanEgressPorts=dot1qVlanEgressPorts, cpuFilterL3RuleSrcIpAddrMask=cpuFilterL3RuleSrcIpAddrMask, aclL3RuleRateLimit=aclL3RuleRateLimit, gvrpSettingsEntry=gvrpSettingsEntry, mstInstanceVlanMapped3k=mstInstanceVlanMapped3k, doSCtrlType=doSCtrlType, aclL3RuleTcpSynBit=aclL3RuleTcpSynBit, bandwidthCtrlRxThreshold=bandwidthCtrlRxThreshold, sysTrapStateChangeEvent=sysTrapStateChangeEvent, ipifv6GlobalStatus=ipifv6GlobalStatus, rmonStatsEntry=rmonStatsEntry, stpPortAdminP2P=stpPortAdminP2P, mstVlanMstiMappingEntry=mstVlanMstiMappingEntry, iPv4swAuthRadiusServerIndex=iPv4swAuthRadiusServerIndex, qosDiffServType11=qosDiffServType11, syslogServSeverity=syslogServSeverity, dhcpv6RelayControl=dhcpv6RelayControl, sslCiphers=sslCiphers, aclQosIPAddr=aclQosIPAddr, lldpXdot1ConfigProtoVlanTable=lldpXdot1ConfigProtoVlanTable, qosDiffServType58=qosDiffServType58, ipv4sysGateway=ipv4sysGateway, impbBlockListTable=impbBlockListTable, aclPacketRuleEntry=aclPacketRuleEntry, eoamCriticalEventEnable=eoamCriticalEventEnable, snmpV3TrapLBD=snmpV3TrapLBD, sfpVendorInfoTable=sfpVendorInfoTable, ipv4aclProfileArpSenderMacAddrMask=ipv4aclProfileArpSenderMacAddrMask, dot1qVlanTable=dot1qVlanTable, lldpXdot1ConfigProtocolEntry=lldpXdot1ConfigProtocolEntry, igmpMulticastVlanGroupEntry=igmpMulticastVlanGroupEntry, cpuFilterv6L3RuleAccessID=cpuFilterv6L3RuleAccessID, sysLBDPortStatus=sysLBDPortStatus, snmpV3EngineID=snmpV3EngineID, aacServerRetryCount=aacServerRetryCount, smtpRecvMailAddr=smtpRecvMailAddr, cableDiagTable=cableDiagTable, neighborType=neighborType, ipv4syslogServAddr=ipv4syslogServAddr, tftpFwTargetImageFileName=tftpFwTargetImageFileName, dhcpv6RelayOpt38Table=dhcpv6RelayOpt38Table, ddmStatus=ddmStatus, snmpV3viewTreeMask=snmpV3viewTreeMask, companyISMVLAN=companyISMVLAN, lldpXdot3LocLinkAggTable=lldpXdot3LocLinkAggTable, sysSNTPDSTRepeatEndWeekDay=sysSNTPDSTRepeatEndWeekDay, ipv4sysSNTPDSTOffset=ipv4sysSNTPDSTOffset, neighborCacheState=neighborCacheState, igsVlanDataDrivenLearningAgeOutStatus=igsVlanDataDrivenLearningAgeOutStatus, impbSettingEntry=impbSettingEntry, snmpV3User=snmpV3User, laPortActorPortPriority=laPortActorPortPriority, dhcpLocalRelayGlobalState=dhcpLocalRelayGlobalState, companyStaticMcast=companyStaticMcast, rmonAlarm=rmonAlarm, sysSNTPFirstType=sysSNTPFirstType, qosDiffServType14=qosDiffServType14, qosDiffServType41=qosDiffServType41, ipv4sysSNTPPollInterval=ipv4sysSNTPPollInterval)NEWLINE ## This file is part of ScapyNEWLINE## See http://www.secdev.org/projects/scapy for more informationsNEWLINE## Copyright (C) Philippe Biondi NEWLINE## Copyright (C) Gabriel Potter NEWLINE## This program is published under a GPLv2 licenseNEWLINENEWLINE"""NEWLINEPython 2 and 3 link classes.NEWLINE"""NEWLINENEWLINEfrom __future__ import absolute_importNEWLINEimport base64NEWLINEimport binasciiNEWLINENEWLINEimport scapy.modules.six as sixNEWLINENEWLINE###########NEWLINE# Python3 #NEWLINE###########NEWLINENEWLINEdef cmp_to_key(mycmp):NEWLINE # TODO remove me once all 'key=cmp_to_key(..)' has been fixed in utils6.py, automaton.pyNEWLINE """Convert a cmp= function into a key= function.NEWLINE To use with sort()NEWLINENEWLINE e.g: def stg_cmp(a, b):NEWLINE return a == bNEWLINE list.sort(key=cmp_to_key(stg_cmp))NEWLINE """NEWLINE class K(object):NEWLINE def __init__(self, obj, *args):NEWLINE self.obj = objNEWLINE def __lt__(self, other):NEWLINE return mycmp(self.obj, other.obj) < 0NEWLINE def __gt__(self, other):NEWLINE return mycmp(self.obj, other.obj) > 0NEWLINE def __eq__(self, other):NEWLINE return mycmp(self.obj, other.obj) == 0NEWLINE def __le__(self, other):NEWLINE return mycmp(self.obj, other.obj) <= 0 NEWLINE def __ge__(self, other):NEWLINE return mycmp(self.obj, other.obj) >= 0NEWLINE def __ne__(self, other):NEWLINE return mycmp(self.obj, other.obj) != 0NEWLINE return KNEWLINENEWLINEdef cmp(a, b):NEWLINE """Old Python 2 function"""NEWLINE return (a > b) - (a < b)NEWLINENEWLINENEWLINEif six.PY2:NEWLINE def orb(x):NEWLINE """Return ord(x) when necessary."""NEWLINE if isinstance(x, basestring):NEWLINE return ord(x)NEWLINE return xNEWLINEelse:NEWLINE def orb(x):NEWLINE """Return ord(x) when necessary."""NEWLINE if isinstance(x, (bytes, str)):NEWLINE return ord(x)NEWLINE return xNEWLINENEWLINENEWLINEif six.PY2:NEWLINE def raw(x):NEWLINE """Convert a str, a packet to bytes"""NEWLINE if x is None:NEWLINE return NoneNEWLINE if hasattr(x, "__bytes__"):NEWLINE return x.__bytes__()NEWLINE try:NEWLINE return chr(x)NEWLINE except (ValueError, TypeError):NEWLINE return str(x)NEWLINENEWLINE def plain_str(x):NEWLINE """Convert basic byte objects to str"""NEWLINE return x if isinstance(x, basestring) else str(x)NEWLINENEWLINE def chb(x):NEWLINE """Same than chr() but encode as bytes.NEWLINENEWLINE """NEWLINE if isinstance(x, bytes):NEWLINE return xNEWLINE else:NEWLINE if hasattr(x, "__int__") and not isinstance(x, int):NEWLINE return bytes(chr(int(x)))NEWLINE return bytes(chr(x))NEWLINEelse:NEWLINE def raw(x):NEWLINE """Convert a str, an int, a list of ints, a packet to bytes"""NEWLINE try:NEWLINE return bytes(x)NEWLINE except TypeError:NEWLINE return bytes(x, encoding="utf8")NEWLINENEWLINE def plain_str(x):NEWLINE """Convert basic byte objects to str"""NEWLINE if isinstance(x, bytes):NEWLINE return x.decode('utf8')NEWLINE return x if isinstance(x, str) else str(x)NEWLINENEWLINE def chb(x):NEWLINE """Same than chr() but encode as bytes.NEWLINENEWLINE """NEWLINE if isinstance(x, bytes):NEWLINE return xNEWLINE else:NEWLINE if hasattr(x, "__int__") and not isinstance(x, int):NEWLINE return bytes([int(x)])NEWLINE return bytes([x])NEWLINENEWLINEdef bytes_hex(x):NEWLINE """Hexify a str or a bytes object"""NEWLINE return binascii.b2a_hex(raw(x))NEWLINENEWLINEdef hex_bytes(x):NEWLINE """De-hexify a str or a byte object"""NEWLINE return binascii.a2b_hex(raw(x))NEWLINENEWLINEdef base64_bytes(x):NEWLINE """Turn base64 into bytes"""NEWLINE if six.PY2:NEWLINE return base64.decodestring(x)NEWLINE return base64.decodebytes(raw(x))NEWLINENEWLINEdef bytes_base64(x):NEWLINE """Turn bytes into base64"""NEWLINE if six.PY2:NEWLINE return base64.encodestring(x).replace('\n', '')NEWLINE return base64.encodebytes(raw(x)).replace(b'\n', b'')NEWLINE # Copyright 2017 The TensorFlow Authors. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE# ==============================================================================NEWLINE"""Tests for the cost analyzer."""NEWLINENEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import print_functionNEWLINENEWLINEfrom tensorflow.python.framework import constant_opNEWLINEfrom tensorflow.python.framework import meta_graphNEWLINEfrom tensorflow.python.framework import opsNEWLINEfrom tensorflow.python.framework import test_utilNEWLINEfrom tensorflow.python.grappler import model_analyzerNEWLINEfrom tensorflow.python.ops import math_opsNEWLINEfrom tensorflow.python.platform import testNEWLINENEWLINENEWLINEclass PyWrapOptimizeGraphTest(test.TestCase):NEWLINENEWLINE @test_util.run_deprecated_v1NEWLINE def testBasic(self):NEWLINE """Make sure arguments can be passed correctly."""NEWLINE a = constant_op.constant([10, 11], name="a")NEWLINE b = constant_op.constant([10], name="b")NEWLINE c = math_ops.add(a, b, name="c")NEWLINE d = math_ops.add_n([a, c], name="d")NEWLINE train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)NEWLINE train_op.append(d)NEWLINE mg = meta_graph.create_meta_graph_def(graph=ops.get_default_graph())NEWLINENEWLINE report = model_analyzer.GenerateModelReport(mg)NEWLINENEWLINE # Check the report headersNEWLINE self.assertTrue(b"a [Const]" in report)NEWLINE self.assertTrue(b"a [Const]" in report)NEWLINE self.assertTrue(b"c [Add]" in report)NEWLINE self.assertTrue(b"d [AddN]" in report)NEWLINENEWLINE # Also print the report to make it easier to debugNEWLINE print("{}".format(report))NEWLINENEWLINE @test_util.run_deprecated_v1NEWLINE def testDebugMode(self):NEWLINE """Make sure arguments can be passed correctly."""NEWLINE a = constant_op.constant([10, 11], name="a")NEWLINE b = constant_op.constant([10], name="b")NEWLINE c = math_ops.add(a, b, name="c")NEWLINE train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)NEWLINE train_op.append(c)NEWLINE mg = meta_graph.create_meta_graph_def(graph=ops.get_default_graph())NEWLINENEWLINE report = model_analyzer.GenerateModelReport(mg, debug=True)NEWLINENEWLINE # Check the report headersNEWLINE self.assertTrue(b"input 0 (int32) has known value" in report)NEWLINE self.assertTrue(b"input 1 (int32) has known value" in report)NEWLINENEWLINE # Also print the report to make it easier to debugNEWLINE print("{}".format(report))NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE test.main()NEWLINE import ioNEWLINEimport jsonNEWLINEimport unittestNEWLINEimport tempfileNEWLINEfrom base64 import b64encodeNEWLINENEWLINEfrom ukbrest import appNEWLINEimport pandas as pdNEWLINENEWLINEfrom tests.settings import POSTGRESQL_ENGINENEWLINEfrom tests.utils import get_repository_path, DBTestNEWLINEfrom ukbrest.common.pheno2sql import Pheno2SQLNEWLINEfrom ukbrest.common.utils.auth import PasswordHasherNEWLINENEWLINENEWLINEclass TestRestApiPhenotype(DBTest):NEWLINE def _make_yaml_request(self, yaml_def, section, n_expected_rows, expected_columns):NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_def), 'data.yaml'),NEWLINE 'section': section,NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert pheno_file.shape == (n_expected_rows, len(expected_columns)), pheno_file.shapeNEWLINENEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE return pheno_fileNEWLINENEWLINE def setUp(self, filename=None, load_data=True, wipe_database=True, **kwargs):NEWLINE if wipe_database:NEWLINE super(TestRestApiPhenotype, self).setUp()NEWLINE NEWLINE # Load dataNEWLINE p2sql = self._get_p2sql(filename, **kwargs)NEWLINENEWLINE if load_data:NEWLINE p2sql.load_data()NEWLINENEWLINE app.app.config['pheno2sql'] = p2sqlNEWLINENEWLINE # ConfigureNEWLINE self.configureApp()NEWLINENEWLINE def _get_p2sql(self, filename, **kwargs):NEWLINE if filename is None:NEWLINE csv_file = get_repository_path('pheno2sql/example02.csv')NEWLINE elif isinstance(filename, (tuple, list)):NEWLINE csv_file = tuple([get_repository_path(f) for f in filename])NEWLINE elif isinstance(filename, str):NEWLINE csv_file = get_repository_path(filename)NEWLINE else:NEWLINE raise ValueError('filename unknown type')NEWLINENEWLINE if 'db_uri' not in kwargs:NEWLINE kwargs['db_uri'] = POSTGRESQL_ENGINENEWLINENEWLINE if 'n_columns_per_table' not in kwargs:NEWLINE kwargs['n_columns_per_table'] = 2NEWLINENEWLINE return Pheno2SQL(csv_file, **kwargs)NEWLINENEWLINE def configureApp(self, app_func=None):NEWLINE app.app.config['testing'] = TrueNEWLINE app.app.config['auth'] = NoneNEWLINENEWLINE if app_func is not None:NEWLINE app_func(app.app)NEWLINENEWLINE self.app = app.app.test_client()NEWLINENEWLINE def configureAppWithAuth(self, user_pass_line):NEWLINE f = tempfile.NamedTemporaryFile(delete=False)NEWLINE f.close()NEWLINENEWLINE with open(f.name, 'w') as fi:NEWLINE fi.write(user_pass_line)NEWLINENEWLINE ph = PasswordHasher(f.name, method='pbkdf2:sha256')NEWLINENEWLINE def conf(a):NEWLINE a.config['auth'] = ph.setup_http_basic_auth()NEWLINENEWLINE self.configureApp(conf)NEWLINENEWLINE def _get_http_basic_auth_header(self, user, password):NEWLINE return {'Authorization': 'Basic %s' % b64encode(f'{user}:{password}'.encode()).decode("ascii")}NEWLINENEWLINE def test_not_found(self):NEWLINE response = self.app.get('/ukbrest/api/v1.0/')NEWLINE assert response.status_code == 404, response.status_codeNEWLINENEWLINE def test_phenotype_fields(self):NEWLINE # PrepareNEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype/fields')NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE fields = json.loads(response.data.decode('utf-8'))NEWLINE assert len(fields) == 8NEWLINENEWLINE def test_phenotype_fields_http_auth_no_credentials(self):NEWLINE # PrepareNEWLINE self.configureAppWithAuth('user: thepassword2')NEWLINENEWLINE # RunNEWLINE response = self.app.get(NEWLINE '/ukbrest/api/v1.0/phenotype/fields',NEWLINE # headers=self._get_http_basic_auth_header('user', 'thepassword2'),NEWLINE )NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 401, response.status_codeNEWLINENEWLINE def test_phenotype_fields_http_auth_with_credentials(self):NEWLINE # PrepareNEWLINE self.configureAppWithAuth('user: thepassword2')NEWLINENEWLINE # RunNEWLINE response = self.app.get(NEWLINE '/ukbrest/api/v1.0/phenotype/fields',NEWLINE headers=self._get_http_basic_auth_header('user', 'thepassword2'),NEWLINE )NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE fields = json.loads(response.data.decode('utf-8'))NEWLINE assert len(fields) == 8NEWLINENEWLINE def test_phenotype_fields_http_auth_multiple_users(self):NEWLINE # PrepareNEWLINE self.configureAppWithAuth(NEWLINE 'user: thepassword2\n'NEWLINE 'another_user: another_password'NEWLINE )NEWLINENEWLINE # RunNEWLINE response = self.app.get(NEWLINE '/ukbrest/api/v1.0/phenotype/fields',NEWLINE headers=self._get_http_basic_auth_header('user', 'thepassword2'),NEWLINE )NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE fields = json.loads(response.data.decode('utf-8'))NEWLINE assert len(fields) == 8NEWLINENEWLINE # Run 2NEWLINE response = self.app.get(NEWLINE '/ukbrest/api/v1.0/phenotype/fields',NEWLINE headers=self._get_http_basic_auth_header('another_user', 'another_password'),NEWLINE )NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE fields = json.loads(response.data.decode('utf-8'))NEWLINE assert len(fields) == 8NEWLINENEWLINE def test_phenotype_query_single_column_format_csv(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE csv_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), index_col='eid', dtype=str)NEWLINE assert csv_file is not NoneNEWLINE assert not csv_file.emptyNEWLINE assert csv_file.shape == (4, 1)NEWLINENEWLINE assert csv_file.index.name == 'eid'NEWLINE assert len(csv_file.index) == 4NEWLINE assert all(x in csv_file.index for x in range(1, 4 + 1))NEWLINENEWLINE assert len(csv_file.columns) == len(columns)NEWLINE assert all(x in columns for x in csv_file.columns)NEWLINENEWLINE assert csv_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert csv_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINE assert csv_file.loc[3, 'c21_0_0'] == 'Option number 3'NEWLINE assert csv_file.loc[4, 'c21_0_0'] == 'Option number 4'NEWLINENEWLINE def test_phenotype_query_error_column_does_not_exist(self):NEWLINE # PrepareNEWLINE columns = ['nonexistent_column']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINENEWLINE # with self.app:NEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 400, response.status_codeNEWLINE data = json.load(io.StringIO(response.data.decode('utf-8')))NEWLINENEWLINE assert 'message' in data, dataNEWLINE assert 'column "nonexistent_column" does not exist' in data['message'], data['message']NEWLINENEWLINE assert 'output' not in data, dataNEWLINENEWLINE def test_phenotype_query_error_column_does_not_exist_standard_column_name(self):NEWLINE # PrepareNEWLINE columns = ['c999_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINENEWLINE # with self.app:NEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 400, response.status_codeNEWLINE data = json.load(io.StringIO(response.data.decode('utf-8')))NEWLINENEWLINE assert 'status_code' in data, dataNEWLINE assert data['status_code'] == 400, data['status_code']NEWLINENEWLINE assert 'error_type' in data, dataNEWLINE assert data['error_type'] == 'SQL_EXECUTION_ERROR'NEWLINENEWLINE assert 'message' in data, dataNEWLINE assert 'column "c999_0_0" does not exist' in data['message'], data['message']NEWLINENEWLINE assert 'output' not in data, dataNEWLINENEWLINE def test_phenotype_query_error_cannot_connect_to_database(self):NEWLINE # PrepareNEWLINE self.setUp(load_data=False, db_uri='postgresql://test:test@wronghost:5432/ukb')NEWLINENEWLINE columns = ['c21_0_0', 'invalid value here']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINENEWLINE # with self.app:NEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 500, response.status_codeNEWLINE data = json.load(io.StringIO(response.data.decode('utf-8')))NEWLINENEWLINE assert 'status_code' in data, dataNEWLINE assert data['status_code'] == 500, data['status_code']NEWLINENEWLINE assert 'error_type' in data, dataNEWLINE assert data['error_type'] == 'UNKNOWN', data['error_type']NEWLINENEWLINE assert 'message' in data, dataNEWLINE assert 'psycopg2.OperationalError' in data['message'], data['message']NEWLINE assert 'wronghost' in data['message'], data['message']NEWLINENEWLINE def test_phenotype_query_multiple_column_format_csv(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0', 'c48_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE csv_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), index_col='eid', dtype=str)NEWLINE assert csv_file is not NoneNEWLINE assert not csv_file.emptyNEWLINE assert csv_file.shape == (4, 2)NEWLINENEWLINE assert csv_file.index.name == 'eid'NEWLINE assert len(csv_file.index) == 4NEWLINE assert all(x in csv_file.index for x in range(1, 4 + 1))NEWLINENEWLINE assert len(csv_file.columns) == len(columns)NEWLINE assert all(x in columns for x in csv_file.columns)NEWLINENEWLINE assert csv_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert csv_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINE assert csv_file.loc[3, 'c21_0_0'] == 'Option number 3'NEWLINE assert csv_file.loc[4, 'c21_0_0'] == 'Option number 4'NEWLINENEWLINE assert csv_file.loc[1, 'c48_0_0'] == '2011-08-14'NEWLINE assert csv_file.loc[2, 'c48_0_0'] == '2016-11-30'NEWLINE assert csv_file.loc[3, 'c48_0_0'] == '2010-01-01'NEWLINE assert csv_file.loc[4, 'c48_0_0'] == '2011-02-15'NEWLINENEWLINE def test_phenotype_query_multiple_column_format_pheno(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0', 'c48_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 2 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINE assert pheno_file.loc[3, 'c21_0_0'] == 'Option number 3'NEWLINE assert pheno_file.loc[4, 'c21_0_0'] == 'Option number 4'NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2011-08-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2016-11-30'NEWLINE assert pheno_file.loc[3, 'c48_0_0'] == '2010-01-01'NEWLINE assert pheno_file.loc[4, 'c48_0_0'] == '2011-02-15'NEWLINENEWLINE def test_phenotype_query_multiple_column_renaming(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0 as c21', 'c31_0_0 c31', 'c48_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + ['c21', 'c31', 'c48_0_0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c21'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21'] == 'Option number 2'NEWLINE assert pheno_file.loc[3, 'c21'] == 'Option number 3'NEWLINE assert pheno_file.loc[4, 'c21'] == 'Option number 4'NEWLINENEWLINE assert pheno_file.loc[1, 'c31'] == '2012-01-05'NEWLINE assert pheno_file.loc[2, 'c31'] == '2015-12-30'NEWLINE assert pheno_file.loc[3, 'c31'] == '2007-03-19'NEWLINE assert pheno_file.loc[4, 'c31'] == '2002-05-09'NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2011-08-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2016-11-30'NEWLINE assert pheno_file.loc[3, 'c48_0_0'] == '2010-01-01'NEWLINE assert pheno_file.loc[4, 'c48_0_0'] == '2011-02-15'NEWLINENEWLINE def test_phenotype_query_filtering_with_column_no_mentioned_in_select(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0 as c21', 'c21_2_0 c21_2']NEWLINE filtering = ["c46_0_0 < 0", "c48_0_0 > '2011-01-01'"]NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'filters': filtering,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype', query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape[0] == 2NEWLINE assert pheno_file.shape[1] == 2 + 1 # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 2NEWLINE assert all(x in pheno_file.index for x in (1, 2))NEWLINENEWLINE expected_columns = ['IID'] + ['c21', 'c21_2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINENEWLINE assert pheno_file.loc[1, 'c21'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21'] == 'Option number 2'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_2'] == 'Yes'NEWLINE assert pheno_file.loc[2, 'c21_2'] == 'No'NEWLINENEWLINE def test_phenotype_query_multiple_column_integer_values(self):NEWLINE # PrepareNEWLINE columns = ['c34_0_0', 'c46_0_0', 'c47_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34_0_0'] == '21'NEWLINE assert pheno_file.loc[2, 'c34_0_0'] == '12'NEWLINE assert pheno_file.loc[3, 'c34_0_0'] == '1'NEWLINE assert pheno_file.loc[4, 'c34_0_0'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46_0_0'] == '-9'NEWLINE assert pheno_file.loc[2, 'c46_0_0'] == '-2'NEWLINE assert pheno_file.loc[3, 'c46_0_0'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46_0_0'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47_0_0'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47_0_0'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47_0_0'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47_0_0'] == '55.19832'NEWLINENEWLINE def test_phenotype_query_multiple_column_integer_values_with_nan(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example06_nan_integer.csv')NEWLINENEWLINE columns = ['c34_0_0', 'c46_0_0', 'c47_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34_0_0'] == '21'NEWLINE assert pheno_file.loc[2, 'c34_0_0'] == '12'NEWLINE assert pheno_file.loc[3, 'c34_0_0'] == '1'NEWLINE assert pheno_file.loc[4, 'c34_0_0'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46_0_0'] == '-9'NEWLINE assert pheno_file.loc[2, 'c46_0_0'] == 'NA'NEWLINE assert pheno_file.loc[3, 'c46_0_0'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46_0_0'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47_0_0'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47_0_0'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47_0_0'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47_0_0'] == '55.19832'NEWLINENEWLINE def test_phenotype_query_multiple_column_integer_values_with_nan_using_columns_renaming_with_as(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example06_nan_integer.csv')NEWLINENEWLINE columns = ['c34_0_0 as c34', 'c46_0_0 as c46', 'c47_0_0 as c47']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + ['c34', 'c46', 'c47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34'] == '21'NEWLINE assert pheno_file.loc[2, 'c34'] == '12'NEWLINE assert pheno_file.loc[3, 'c34'] == '1'NEWLINE assert pheno_file.loc[4, 'c34'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46'] == '-9', pheno_file.loc[1, 'c46']NEWLINE assert pheno_file.loc[2, 'c46'] == 'NA'NEWLINE assert pheno_file.loc[3, 'c46'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47'] == '55.19832'NEWLINENEWLINE def test_phenotype_query_multiple_column_integer_values_with_nan_using_columns_renaming_with_as_uppercase(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example06_nan_integer.csv')NEWLINENEWLINE columns = ['c34_0_0 as c34', 'c46_0_0 AS c46', 'c47_0_0 as c47']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + ['c34', 'c46', 'c47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34'] == '21'NEWLINE assert pheno_file.loc[2, 'c34'] == '12'NEWLINE assert pheno_file.loc[3, 'c34'] == '1'NEWLINE assert pheno_file.loc[4, 'c34'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46'] == '-9', pheno_file.loc[1, 'c46']NEWLINE assert pheno_file.loc[2, 'c46'] == 'NA'NEWLINE assert pheno_file.loc[3, 'c46'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47'] == '55.19832'NEWLINENEWLINE def test_phenotype_query_multiple_column_integer_values_with_nan_using_columns_renaming_with_space(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example06_nan_integer.csv')NEWLINENEWLINE columns = ['c34_0_0 as c34', 'c46_0_0 c46', 'c47_0_0 as c47']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + ['c34', 'c46', 'c47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34'] == '21'NEWLINE assert pheno_file.loc[2, 'c34'] == '12'NEWLINE assert pheno_file.loc[3, 'c34'] == '1'NEWLINE assert pheno_file.loc[4, 'c34'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46'] == '-9', pheno_file.loc[1, 'c46']NEWLINE assert pheno_file.loc[2, 'c46'] == 'NA'NEWLINE assert pheno_file.loc[3, 'c46'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47'] == '55.19832'NEWLINENEWLINE def test_phenotype_query_multiple_column_integer_values_with_nan_using_reg_exp(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example06_nan_integer.csv')NEWLINENEWLINE columns = ['c34_0_0 as c34']NEWLINE reg_exp_columns = ['c4[67]_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + ['c34', 'c46_0_0', 'c47_0_0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34'] == '21'NEWLINE assert pheno_file.loc[2, 'c34'] == '12'NEWLINE assert pheno_file.loc[3, 'c34'] == '1'NEWLINE assert pheno_file.loc[4, 'c34'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46_0_0'] == '-9', pheno_file.loc[1, 'c46']NEWLINE assert pheno_file.loc[2, 'c46_0_0'] == 'NA'NEWLINE assert pheno_file.loc[3, 'c46_0_0'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46_0_0'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47_0_0'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47_0_0'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47_0_0'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47_0_0'] == '55.19832'NEWLINENEWLINE def test_phenotype_query_multiple_column_create_field_from_integer(self):NEWLINE # PrepareNEWLINE columns = ['c34_0_0', 'c46_0_0', 'c47_0_0', 'c46_0_0^2 as squared']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 4 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x.split()[-1] in pheno_file.columns for x in expected_columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34_0_0'] == '21'NEWLINE assert pheno_file.loc[2, 'c34_0_0'] == '12'NEWLINE assert pheno_file.loc[3, 'c34_0_0'] == '1'NEWLINE assert pheno_file.loc[4, 'c34_0_0'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46_0_0'] == '-9'NEWLINE assert pheno_file.loc[2, 'c46_0_0'] == '-2'NEWLINE assert pheno_file.loc[3, 'c46_0_0'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46_0_0'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47_0_0'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47_0_0'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47_0_0'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47_0_0'] == '55.19832'NEWLINENEWLINE # square results in float typeNEWLINE assert pheno_file.loc[1, 'squared'] == '81.0'NEWLINE assert pheno_file.loc[2, 'squared'] == '4.0'NEWLINE assert pheno_file.loc[3, 'squared'] == '49.0'NEWLINE assert pheno_file.loc[4, 'squared'] == '16.0'NEWLINENEWLINE def test_phenotype_query_multiple_column_create_field_from_integer_return_integer(self):NEWLINE # PrepareNEWLINE columns = ['c34_0_0', 'c46_0_0', 'c47_0_0', 'c46_0_0 + 1 as sum']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 4 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x.split()[-1] in pheno_file.columns for x in expected_columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34_0_0'] == '21'NEWLINE assert pheno_file.loc[2, 'c34_0_0'] == '12'NEWLINE assert pheno_file.loc[3, 'c34_0_0'] == '1'NEWLINE assert pheno_file.loc[4, 'c34_0_0'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46_0_0'] == '-9'NEWLINE assert pheno_file.loc[2, 'c46_0_0'] == '-2'NEWLINE assert pheno_file.loc[3, 'c46_0_0'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46_0_0'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47_0_0'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47_0_0'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47_0_0'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47_0_0'] == '55.19832'NEWLINENEWLINE # square results in float typeNEWLINE assert pheno_file.loc[1, 'sum'] == '-8'NEWLINE assert pheno_file.loc[2, 'sum'] == '-1'NEWLINE assert pheno_file.loc[3, 'sum'] == '-6'NEWLINE assert pheno_file.loc[4, 'sum'] == '5'NEWLINENEWLINE def test_phenotype_query_multiple_column_create_field_from_float(self):NEWLINE # PrepareNEWLINE columns = ['c34_0_0', 'c46_0_0', 'c47_0_0', 'c47_0_0^2 as squared']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 4 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x.split()[-1] in pheno_file.columns for x in expected_columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34_0_0'] == '21'NEWLINE assert pheno_file.loc[2, 'c34_0_0'] == '12'NEWLINE assert pheno_file.loc[3, 'c34_0_0'] == '1'NEWLINE assert pheno_file.loc[4, 'c34_0_0'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46_0_0'] == '-9'NEWLINE assert pheno_file.loc[2, 'c46_0_0'] == '-2'NEWLINE assert pheno_file.loc[3, 'c46_0_0'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46_0_0'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47_0_0'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47_0_0'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47_0_0'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47_0_0'] == '55.19832'NEWLINENEWLINE # square results in float typeNEWLINE assert pheno_file.loc[1, 'squared'] == '2075.1778489744'NEWLINE assert pheno_file.loc[2, 'squared'] == '0.3075922521'NEWLINE assert pheno_file.loc[3, 'squared'] == '28.3525365841'NEWLINE assert pheno_file.loc[4, 'squared'] == '3046.8545308224'NEWLINENEWLINE def test_phenotype_query_multiple_column_create_field_from_str(self):NEWLINE # PrepareNEWLINE columns = ['c34_0_0', 'c46_0_0', 'c47_0_0', 'c21_0_0', '(c21_0_0 || \' end \' || eid) as result']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 5 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x.split()[-1] in pheno_file.columns for x in expected_columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE # square results in float typeNEWLINE assert pheno_file.loc[1, 'result'] == 'Option number 1 end 1'NEWLINE assert pheno_file.loc[2, 'result'] == 'Option number 2 end 2'NEWLINE assert pheno_file.loc[3, 'result'] == 'Option number 3 end 3'NEWLINE assert pheno_file.loc[4, 'result'] == 'Option number 4 end 4'NEWLINENEWLINE def test_phenotype_query_format_pheno_missing_data(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0', 'c21_1_0', 'c48_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE # na_values='' is necessary to not overwrite NA strings hereNEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t',NEWLINE na_values='', keep_default_na=False, index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINE assert pheno_file.loc[3, 'c21_0_0'] == 'Option number 3'NEWLINE assert pheno_file.loc[4, 'c21_0_0'] == 'Option number 4'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_1_0'] == 'No response'NEWLINE assert pheno_file.loc[2, 'c21_1_0'] == 'NA'NEWLINE assert pheno_file.loc[3, 'c21_1_0'] == 'Of course'NEWLINE assert pheno_file.loc[4, 'c21_1_0'] == 'I don\'t know'NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2011-08-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2016-11-30'NEWLINE assert pheno_file.loc[3, 'c48_0_0'] == '2010-01-01'NEWLINE assert pheno_file.loc[4, 'c48_0_0'] == '2011-02-15'NEWLINENEWLINE def test_phenotype_query_format_pheno_missing_date(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example05_missing_date.csv')NEWLINENEWLINE columns = ['c21_0_0', 'c21_1_0', 'c48_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE # na_values='' is necessary to not overwrite NA strings hereNEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t',NEWLINE na_values='', keep_default_na=False, index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2011-08-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2016-11-30'NEWLINE assert pheno_file.loc[3, 'c48_0_0'] == 'NA'NEWLINE assert pheno_file.loc[4, 'c48_0_0'] == '2011-02-15'NEWLINENEWLINE def test_phenotype_query_multiple_column_no_format(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0', 'c48_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 2 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINE assert pheno_file.loc[3, 'c21_0_0'] == 'Option number 3'NEWLINE assert pheno_file.loc[4, 'c21_0_0'] == 'Option number 4'NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2011-08-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2016-11-30'NEWLINE assert pheno_file.loc[3, 'c48_0_0'] == '2010-01-01'NEWLINE assert pheno_file.loc[4, 'c48_0_0'] == '2011-02-15'NEWLINENEWLINE def test_phenotype_query_multiple_column_format_not_supported(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0', 'c48_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'application/json'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 400, response.status_codeNEWLINE data = json.load(io.StringIO(response.data.decode('utf-8')))NEWLINENEWLINE assert 'status_code' in data, dataNEWLINE assert data['status_code'] == 400, data['status_code']NEWLINENEWLINE assert 'error_type' in data, dataNEWLINE assert data['error_type'] == 'UNKNOWN', data['error_type']NEWLINENEWLINE assert 'message' in data, dataNEWLINE assert 'are supported' in str(data['message']), data['message']NEWLINE assert 'text/plink2' in str(data['message']), data['message']NEWLINENEWLINE def test_phenotype_query_with_filtering(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0', 'c21_2_0', 'c47_0_0', 'c48_0_0']NEWLINE filtering = ["c48_0_0 > '2011-01-01'", "c21_2_0 <> ''"]NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'filters': filtering,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype', query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape[0] == 2NEWLINE assert pheno_file.shape[1] == 4 + 1 # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 2NEWLINE assert all(x in pheno_file.index for x in (1, 2))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_2_0'] == 'Yes'NEWLINE assert pheno_file.loc[2, 'c21_2_0'] == 'No'NEWLINENEWLINE assert pheno_file.loc[1, 'c47_0_0'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47_0_0'] == '-0.55461'NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2011-08-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2016-11-30'NEWLINENEWLINE def test_phenotype_query_columns_with_regular_expression_and_standard_columns(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example09_with_arrays.csv')NEWLINENEWLINE columns = ['c21_0_0', 'c48_0_0']NEWLINE reg_exp_columns = ['c84_0_\d+']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype', query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (5, 5 + 1), pheno_file.shape # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 5NEWLINE assert all(x in pheno_file.index for x in range(1, 5 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columns + ['c84_0_0', 'c84_0_1', 'c84_0_2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINE assert pheno_file.loc[5, 'IID'] == '5'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINE assert pheno_file.loc[3, 'c21_0_0'] == 'Option number 3'NEWLINE assert pheno_file.loc[4, 'c21_0_0'] == "Option number 4"NEWLINE assert pheno_file.loc[5, 'c21_0_0'] == "Option number 5"NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2010-07-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2017-11-30'NEWLINE assert pheno_file.loc[3, 'c48_0_0'] == '2020-01-01'NEWLINE assert pheno_file.loc[4, 'c48_0_0'] == '1990-02-15'NEWLINE assert pheno_file.loc[5, 'c48_0_0'] == '1999-10-11'NEWLINENEWLINE assert pheno_file.loc[1, 'c84_0_0'] == '11', pheno_file.loc[1, 'c84_0_0']NEWLINE assert pheno_file.loc[2, 'c84_0_0'] == '-21'NEWLINE assert pheno_file.loc[3, 'c84_0_0'] == 'NA'NEWLINE assert pheno_file.loc[4, 'c84_0_0'] == '41'NEWLINE assert pheno_file.loc[5, 'c84_0_0'] == '51'NEWLINENEWLINE assert pheno_file.loc[1, 'c84_0_1'] == '1', pheno_file.loc[1, 'c84_0_1']NEWLINE assert pheno_file.loc[2, 'c84_0_1'] == '99'NEWLINE assert pheno_file.loc[3, 'c84_0_1'] == '98'NEWLINE assert pheno_file.loc[4, 'c84_0_1'] == '-37'NEWLINE assert pheno_file.loc[5, 'c84_0_1'] == '36'NEWLINENEWLINE assert pheno_file.loc[1, 'c84_0_2'] == '999'NEWLINE assert pheno_file.loc[2, 'c84_0_2'] == '152'NEWLINE assert pheno_file.loc[3, 'c84_0_2'] == '-68'NEWLINE assert pheno_file.loc[4, 'c84_0_2'] == 'NA'NEWLINE assert pheno_file.loc[5, 'c84_0_2'] == '-445'NEWLINENEWLINE def test_phenotype_query_columns_with_regular_expression_only(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example09_with_arrays.csv')NEWLINENEWLINE reg_exp_columns = ['c84_0_\d+']NEWLINENEWLINE parameters = {NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype', query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (5, 3 + 1), pheno_file.shape # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 5NEWLINE assert all(x in pheno_file.index for x in range(1, 5 + 1))NEWLINENEWLINE expected_columns = ['IID'] + ['c84_0_0', 'c84_0_1', 'c84_0_2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINE assert pheno_file.loc[5, 'IID'] == '5'NEWLINENEWLINE assert pheno_file.loc[1, 'c84_0_0'] == '11', pheno_file.loc[1, 'c84_0_0']NEWLINE assert pheno_file.loc[2, 'c84_0_0'] == '-21'NEWLINE assert pheno_file.loc[3, 'c84_0_0'] == 'NA'NEWLINE assert pheno_file.loc[4, 'c84_0_0'] == '41'NEWLINE assert pheno_file.loc[5, 'c84_0_0'] == '51'NEWLINENEWLINE assert pheno_file.loc[1, 'c84_0_1'] == '1', pheno_file.loc[1, 'c84_0_1']NEWLINE assert pheno_file.loc[2, 'c84_0_1'] == '99'NEWLINE assert pheno_file.loc[3, 'c84_0_1'] == '98'NEWLINE assert pheno_file.loc[4, 'c84_0_1'] == '-37'NEWLINE assert pheno_file.loc[5, 'c84_0_1'] == '36'NEWLINENEWLINE assert pheno_file.loc[1, 'c84_0_2'] == '999'NEWLINE assert pheno_file.loc[2, 'c84_0_2'] == '152'NEWLINE assert pheno_file.loc[3, 'c84_0_2'] == '-68'NEWLINE assert pheno_file.loc[4, 'c84_0_2'] == 'NA'NEWLINE assert pheno_file.loc[5, 'c84_0_2'] == '-445'NEWLINENEWLINE def test_phenotype_query_columns_pheno2sql_instance_not_loaded(self):NEWLINE """This test uses a different Pheno2SQL instance without previous loading"""NEWLINENEWLINE # PrepareNEWLINE csv01 = get_repository_path('pheno2sql/example08_01.csv')NEWLINE csv02 = get_repository_path('pheno2sql/example08_02.csv')NEWLINE csvs = (csv01, csv02)NEWLINENEWLINE # first load dataNEWLINE self.setUp(csvs)NEWLINENEWLINE # then create another instance without executing load_data methodNEWLINE self.setUp(csvs, load_data=False, wipe_database=False)NEWLINENEWLINE columns = ['c48_0_0', 'c120_0_0 as c120', 'c150_0_0 c150']NEWLINE reg_exp_columns = ['c21_[01]_0', 'c100_\d_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype', query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (5, 8 + 1), pheno_file.shape # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 5NEWLINE assert all(x in pheno_file.index for x in range(1, 5 + 1))NEWLINENEWLINE expected_columns = ['IID'] + ['c21_0_0', 'c21_1_0', 'c48_0_0', 'c120', 'c150', 'c100_0_0', 'c100_1_0', 'c100_2_0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINE assert pheno_file.loc[5, 'IID'] == '5'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINE assert pheno_file.loc[3, 'c21_0_0'] == 'Option number 3'NEWLINE assert pheno_file.loc[4, 'c21_0_0'] == 'Option number 4'NEWLINE assert pheno_file.loc[5, 'c21_0_0'] == 'Option number 5'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_1_0'] == 'No response'NEWLINE assert pheno_file.loc[2, 'c21_1_0'] == 'NA'NEWLINE assert pheno_file.loc[3, 'c21_1_0'] == 'Of course'NEWLINE assert pheno_file.loc[4, 'c21_1_0'] == "I don't know"NEWLINE assert pheno_file.loc[5, 'c21_1_0'] == 'Maybe'NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2010-07-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2017-11-30'NEWLINE assert pheno_file.loc[3, 'c48_0_0'] == '2020-01-01'NEWLINE assert pheno_file.loc[4, 'c48_0_0'] == '1990-02-15'NEWLINE assert pheno_file.loc[5, 'c48_0_0'] == '1999-10-11'NEWLINENEWLINE assert pheno_file.loc[1, 'c100_0_0'] == '-9', pheno_file.loc[1, 'c100_0_0']NEWLINE assert pheno_file.loc[2, 'c100_0_0'] == '-2'NEWLINE assert pheno_file.loc[3, 'c100_0_0'] == 'NA'NEWLINE assert pheno_file.loc[4, 'c100_0_0'] == 'NA'NEWLINE assert pheno_file.loc[5, 'c100_0_0'] == 'NA'NEWLINENEWLINE assert pheno_file.loc[1, 'c100_1_0'] == '3', pheno_file.loc[1, 'c100_1_0']NEWLINE assert pheno_file.loc[2, 'c100_1_0'] == '3'NEWLINE assert pheno_file.loc[3, 'c100_1_0'] == '-4'NEWLINE assert pheno_file.loc[4, 'c100_1_0'] == 'NA'NEWLINE assert pheno_file.loc[5, 'c100_1_0'] == 'NA'NEWLINENEWLINE assert pheno_file.loc[1, 'c100_2_0'] == 'NA', pheno_file.loc[1, 'c100_2_0']NEWLINE assert pheno_file.loc[2, 'c100_2_0'] == '1'NEWLINE assert pheno_file.loc[3, 'c100_2_0'] == '-10'NEWLINE assert pheno_file.loc[4, 'c100_2_0'] == 'NA'NEWLINE assert pheno_file.loc[5, 'c100_2_0'] == 'NA'NEWLINENEWLINE def test_phenotype_query_http_basic_auth_is_null(self):NEWLINE # PrepareNEWLINE csv01 = get_repository_path('pheno2sql/example08_01.csv')NEWLINE csv02 = get_repository_path('pheno2sql/example08_02.csv')NEWLINE csvs = (csv01, csv02)NEWLINENEWLINE # first load dataNEWLINE self.setUp(csvs)NEWLINENEWLINE # then create another instance without executing load_data methodNEWLINE self.setUp(csvs, load_data=False, wipe_database=False)NEWLINENEWLINE def configure_http_auth(theapp):NEWLINE theapp.config['auth'] = NoneNEWLINENEWLINE self.configureApp(configure_http_auth)NEWLINENEWLINE columns = ['c48_0_0', 'c120_0_0 as c120', 'c150_0_0 c150']NEWLINE reg_exp_columns = ['c21_[01]_0', 'c100_\d_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype', query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE # unauthorizedNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE def test_phenotype_query_http_basic_auth_no_user_pass(self):NEWLINE # PrepareNEWLINE csv01 = get_repository_path('pheno2sql/example08_01.csv')NEWLINE csv02 = get_repository_path('pheno2sql/example08_02.csv')NEWLINE csvs = (csv01, csv02)NEWLINENEWLINE # first load dataNEWLINE self.setUp(csvs)NEWLINENEWLINE # then create another instance without executing load_data methodNEWLINE self.setUp(csvs, load_data=False, wipe_database=False)NEWLINENEWLINE self.configureAppWithAuth('user: thepassword2')NEWLINENEWLINE columns = ['c48_0_0', 'c120_0_0 as c120', 'c150_0_0 c150']NEWLINE reg_exp_columns = ['c21_[01]_0', 'c100_\d_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype', query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE # unauthorizedNEWLINE assert response.status_code == 401, response.status_codeNEWLINENEWLINE def test_phenotype_query_http_basic_auth_with_user_pass(self):NEWLINE # PrepareNEWLINE csv01 = get_repository_path('pheno2sql/example08_01.csv')NEWLINE csv02 = get_repository_path('pheno2sql/example08_02.csv')NEWLINE csvs = (csv01, csv02)NEWLINENEWLINE # first load dataNEWLINE self.setUp(csvs)NEWLINENEWLINE # then create another instance without executing load_data methodNEWLINE self.setUp(csvs, load_data=False, wipe_database=False)NEWLINENEWLINE self.configureAppWithAuth('user: thepassword2')NEWLINENEWLINE columns = ['c48_0_0', 'c120_0_0 as c120', 'c150_0_0 c150']NEWLINE reg_exp_columns = ['c21_[01]_0', 'c100_\d_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get(NEWLINE '/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters,NEWLINE headers=self._get_http_basic_auth_header('user', 'thepassword2'),NEWLINE )NEWLINENEWLINE # ValidateNEWLINE # unauthorizedNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (5, 8 + 1), pheno_file.shape # plus IIDNEWLINENEWLINE def test_phenotype_query_http_basic_auth_with_wrong_pass(self):NEWLINE # PrepareNEWLINE csv01 = get_repository_path('pheno2sql/example08_01.csv')NEWLINE csv02 = get_repository_path('pheno2sql/example08_02.csv')NEWLINE csvs = (csv01, csv02)NEWLINENEWLINE # first load dataNEWLINE self.setUp(csvs)NEWLINENEWLINE # then create another instance without executing load_data methodNEWLINE self.setUp(csvs, load_data=False, wipe_database=False)NEWLINENEWLINE self.configureAppWithAuth('user: anotherpass')NEWLINENEWLINE columns = ['c48_0_0', 'c120_0_0 as c120', 'c150_0_0 c150']NEWLINE reg_exp_columns = ['c21_[01]_0', 'c100_\d_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get(NEWLINE '/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters,NEWLINE headers=self._get_http_basic_auth_header('user', 'thepassword2')NEWLINE )NEWLINENEWLINE # ValidateNEWLINE # unauthorizedNEWLINE assert response.status_code == 401, response.status_codeNEWLINENEWLINE def test_phenotype_query_http_basic_auth_with_wrong_user(self):NEWLINE # PrepareNEWLINE csv01 = get_repository_path('pheno2sql/example08_01.csv')NEWLINE csv02 = get_repository_path('pheno2sql/example08_02.csv')NEWLINE csvs = (csv01, csv02)NEWLINENEWLINE # first load dataNEWLINE self.setUp(csvs)NEWLINENEWLINE # then create another instance without executing load_data methodNEWLINE self.setUp(csvs, load_data=False, wipe_database=False)NEWLINENEWLINE self.configureAppWithAuth('anotheruser: thepassword2')NEWLINENEWLINE columns = ['c48_0_0', 'c120_0_0 as c120', 'c150_0_0 c150']NEWLINE reg_exp_columns = ['c21_[01]_0', 'c100_\d_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get(NEWLINE '/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters,NEWLINE headers=self._get_http_basic_auth_header('user', 'thepassword2'),NEWLINE )NEWLINENEWLINE # ValidateNEWLINE # unauthorizedNEWLINE assert response.status_code == 401, response.status_codeNEWLINENEWLINE def test_phenotype_query_yaml_get_covariates(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE covariates:NEWLINE field_name_34: c34_0_0NEWLINE field_name_47: c47_0_0NEWLINE NEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0NEWLINE instance2: c21_2_0NEWLINE """NEWLINENEWLINE # RunNEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'covariates',NEWLINE })NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str,NEWLINE na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (5, 2 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert all(x in pheno_file.index for x in (1000010, 1000020, 1000030, 1000040, 1000050))NEWLINENEWLINE expected_columns = ['IID'] + ['field_name_34', 'field_name_47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1000010, 'IID'] == '1000010'NEWLINE assert pheno_file.loc[1000010, 'field_name_34'] == '-33'NEWLINE assert pheno_file.loc[1000010, 'field_name_47'] == '41.55312'NEWLINENEWLINE assert pheno_file.loc[1000020, 'IID'] == '1000020'NEWLINE assert pheno_file.loc[1000020, 'field_name_34'] == '34'NEWLINE assert pheno_file.loc[1000020, 'field_name_47'] == '-10.51461'NEWLINENEWLINE assert pheno_file.loc[1000030, 'IID'] == '1000030'NEWLINE assert pheno_file.loc[1000030, 'field_name_34'] == '0'NEWLINE assert pheno_file.loc[1000030, 'field_name_47'] == '-35.31471'NEWLINENEWLINE assert pheno_file.loc[1000040, 'IID'] == '1000040'NEWLINE assert pheno_file.loc[1000040, 'field_name_34'] == '3'NEWLINE assert pheno_file.loc[1000040, 'field_name_47'] == '5.20832'NEWLINENEWLINE assert pheno_file.loc[1000050, 'IID'] == '1000050'NEWLINE assert pheno_file.loc[1000050, 'field_name_34'] == '-4'NEWLINE assert pheno_file.loc[1000050, 'field_name_47'] == 'NA'NEWLINENEWLINE def test_phenotype_query_yaml_get_covariates_http_auth_with_no_credentials(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE self.configureAppWithAuth('user: thepassword2')NEWLINENEWLINE yaml_data = b"""NEWLINE covariates:NEWLINE field_name_34: c34_0_0NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0NEWLINE instance2: c21_2_0NEWLINE """NEWLINENEWLINE # RunNEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'covariates',NEWLINE })NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 401, response.status_codeNEWLINENEWLINE def test_phenotype_query_yaml_get_covariates_http_auth_with_credentials(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE self.configureAppWithAuth('user: thepassword2')NEWLINENEWLINE yaml_data = b"""NEWLINE covariates:NEWLINE field_name_34: c34_0_0NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0NEWLINE instance2: c21_2_0NEWLINE """NEWLINENEWLINE # RunNEWLINE response = self.app.post(NEWLINE '/ukbrest/api/v1.0/query',NEWLINE data={NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'covariates',NEWLINE },NEWLINE headers=self._get_http_basic_auth_header('user', 'thepassword2'),NEWLINE )NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str,NEWLINE na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (5, 2 + 1) # plus IIDNEWLINENEWLINE def test_phenotype_query_yaml_get_fields(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0 NEWLINE instance2: c21_2_0 NEWLINE """NEWLINENEWLINE # RunNEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'fields',NEWLINE })NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str,NEWLINE na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (5, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert all(x in pheno_file.index for x in (1000010, 1000020, 1000030, 1000040, 1000050))NEWLINENEWLINE expected_columns = ['IID'] + ['instance0', 'instance1', 'instance2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1000010, 'IID'] == '1000010'NEWLINE assert pheno_file.loc[1000010, 'instance0'] == 'Option number 1'NEWLINE assert pheno_file.loc[1000010, 'instance1'] == 'No response'NEWLINE assert pheno_file.loc[1000010, 'instance2'] == 'Yes'NEWLINENEWLINE assert pheno_file.loc[1000040, 'IID'] == '1000040'NEWLINE assert pheno_file.loc[1000040, 'instance0'] == 'Option number 4'NEWLINE assert pheno_file.loc[1000040, 'instance1'] == "I don't know"NEWLINE assert pheno_file.loc[1000040, 'instance2'] == 'NA'NEWLINENEWLINE def test_phenotype_query_yaml_filter_samples_with_include_only(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c47_0_0 > 0NEWLINE NEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0 NEWLINE instance2: c21_2_0 NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 2NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'fields',NEWLINE })NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str,NEWLINE na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3 + 1), pheno_file.shape # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert all(x in pheno_file.index for x in (1000010, 1000040)), pheno_file.index.tolist()NEWLINENEWLINE expected_columns = ['IID'] + ['instance0', 'instance1', 'instance2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1000010, 'IID'] == '1000010'NEWLINE assert pheno_file.loc[1000010, 'instance0'] == 'Option number 1'NEWLINE assert pheno_file.loc[1000010, 'instance1'] == 'No response'NEWLINE assert pheno_file.loc[1000010, 'instance2'] == 'Yes'NEWLINENEWLINE assert pheno_file.loc[1000040, 'IID'] == '1000040'NEWLINE assert pheno_file.loc[1000040, 'instance0'] == 'Option number 4'NEWLINE assert pheno_file.loc[1000040, 'instance1'] == "I don't know"NEWLINE assert pheno_file.loc[1000040, 'instance2'] == 'NA'NEWLINENEWLINE #NEWLINE # Ask covariatesNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'covariates',NEWLINE })NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str,NEWLINE na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 2 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert all(x in pheno_file.index for x in (1000010, 1000040))NEWLINENEWLINE expected_columns = ['IID'] + ['field_name_34', 'field_name_47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1000010, 'IID'] == '1000010'NEWLINE assert pheno_file.loc[1000010, 'field_name_34'] == '-33'NEWLINE assert pheno_file.loc[1000010, 'field_name_47'] == '41.55312'NEWLINENEWLINE assert pheno_file.loc[1000040, 'IID'] == '1000040'NEWLINE assert pheno_file.loc[1000040, 'field_name_34'] == '3'NEWLINE assert pheno_file.loc[1000040, 'field_name_47'] == '5.20832'NEWLINENEWLINE def test_phenotype_query_yaml_filter_samples_condition_breaking_for_fields_and_covariates(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c47_0_0 > 0NEWLINE - c46_0_0 < 0 or c46_0_0 = 4 or c46_0_0 = 1NEWLINENEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0 NEWLINE instance2: c21_2_0 NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 2NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'fields',NEWLINE })NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str,NEWLINE na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3 + 1), pheno_file.shape # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert all(x in pheno_file.index for x in (1000010, 1000040)), pheno_file.index.tolist()NEWLINENEWLINE expected_columns = ['IID'] + ['instance0', 'instance1', 'instance2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1000010, 'IID'] == '1000010'NEWLINE assert pheno_file.loc[1000010, 'instance0'] == 'Option number 1'NEWLINE assert pheno_file.loc[1000010, 'instance1'] == 'No response'NEWLINE assert pheno_file.loc[1000010, 'instance2'] == 'Yes'NEWLINENEWLINE assert pheno_file.loc[1000040, 'IID'] == '1000040'NEWLINE assert pheno_file.loc[1000040, 'instance0'] == 'Option number 4'NEWLINE assert pheno_file.loc[1000040, 'instance1'] == "I don't know"NEWLINE assert pheno_file.loc[1000040, 'instance2'] == 'NA'NEWLINENEWLINE #NEWLINE # Ask covariatesNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'covariates',NEWLINE })NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str,NEWLINE na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 2 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert all(x in pheno_file.index for x in (1000010, 1000040))NEWLINENEWLINE expected_columns = ['IID'] + ['field_name_34', 'field_name_47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1000010, 'IID'] == '1000010'NEWLINE assert pheno_file.loc[1000010, 'field_name_34'] == '-33'NEWLINE assert pheno_file.loc[1000010, 'field_name_47'] == '41.55312'NEWLINENEWLINE assert pheno_file.loc[1000040, 'IID'] == '1000040'NEWLINE assert pheno_file.loc[1000040, 'field_name_34'] == '3'NEWLINE assert pheno_file.loc[1000040, 'field_name_47'] == '5.20832'NEWLINENEWLINE def test_phenotype_query_yaml_specify_bgenie_format(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c47_0_0 > 0NEWLINENEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0 NEWLINE instance2: c21_2_0 NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 5NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'fields',NEWLINE 'missing_code': '-999',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3), pheno_file.shapeNEWLINENEWLINE expected_columns = ['instance0', 'instance1', 'instance2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'instance0'] == '-999', pheno_file.loc[0, 'instance0']NEWLINE assert pheno_file.loc[0, 'instance1'] == '-999'NEWLINE assert pheno_file.loc[0, 'instance2'] == '-999'NEWLINENEWLINE assert pheno_file.loc[1, 'instance0'] == '-999'NEWLINE assert pheno_file.loc[1, 'instance1'] == '-999'NEWLINE assert pheno_file.loc[1, 'instance2'] == '-999'NEWLINENEWLINE assert pheno_file.loc[2, 'instance0'] == 'Option number 4'NEWLINE assert pheno_file.loc[2, 'instance1'] == "I don't know"NEWLINE assert pheno_file.loc[2, 'instance2'] == '-999'NEWLINENEWLINE assert pheno_file.loc[3, 'instance0'] == 'Option number 1'NEWLINE assert pheno_file.loc[3, 'instance1'] == 'No response'NEWLINE assert pheno_file.loc[3, 'instance2'] == 'Yes'NEWLINENEWLINE assert pheno_file.loc[4, 'instance0'] == '-999'NEWLINE assert pheno_file.loc[4, 'instance1'] == '-999'NEWLINE assert pheno_file.loc[4, 'instance2'] == '-999'NEWLINENEWLINE #NEWLINE # Ask covariatesNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'covariates',NEWLINE 'missing_code': '-999',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 2)NEWLINENEWLINE expected_columns = ['field_name_34', 'field_name_47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'field_name_34'] == '-999'NEWLINE assert pheno_file.loc[0, 'field_name_47'] == '-999'NEWLINENEWLINE assert pheno_file.loc[1, 'field_name_34'] == '-999'NEWLINE assert pheno_file.loc[1, 'field_name_47'] == '-999'NEWLINENEWLINE assert pheno_file.loc[2, 'field_name_34'] == '3'NEWLINE assert pheno_file.loc[2, 'field_name_47'] == '5.20832'NEWLINENEWLINE assert pheno_file.loc[3, 'field_name_34'] == '-33'NEWLINE assert pheno_file.loc[3, 'field_name_47'] == '41.55312'NEWLINENEWLINE assert pheno_file.loc[4, 'field_name_34'] == '-999'NEWLINE assert pheno_file.loc[4, 'field_name_47'] == '-999'NEWLINENEWLINE def test_phenotype_query_yaml_specify_csv_format(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c47_0_0 > 0NEWLINENEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0 NEWLINE instance2: c21_2_0 NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 2NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'fields',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3), pheno_file.shapeNEWLINENEWLINE expected_columns = ['instance0', 'instance1', 'instance2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000040, 'instance0'] == 'Option number 4'NEWLINE assert pheno_file.loc[1000040, 'instance1'] == "I don't know"NEWLINE assert pheno_file.loc[1000040, 'instance2'] == 'NA'NEWLINENEWLINE assert pheno_file.loc[1000010, 'instance0'] == 'Option number 1'NEWLINE assert pheno_file.loc[1000010, 'instance1'] == 'No response'NEWLINE assert pheno_file.loc[1000010, 'instance2'] == 'Yes'NEWLINENEWLINE #NEWLINE # Ask covariatesNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'covariates',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 2)NEWLINENEWLINE expected_columns = ['field_name_34', 'field_name_47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000040, 'field_name_34'] == '3'NEWLINE assert pheno_file.loc[1000040, 'field_name_47'] == '5.20832'NEWLINENEWLINE assert pheno_file.loc[1000010, 'field_name_34'] == '-33'NEWLINE assert pheno_file.loc[1000010, 'field_name_47'] == '41.55312'NEWLINENEWLINE def test_phenotype_query_yaml_specify_bgenie_format_missing_code_default(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c47_0_0 > 0NEWLINENEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0 NEWLINE instance2: c21_2_0 NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 5NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'fields',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3), pheno_file.shapeNEWLINENEWLINE expected_columns = ['instance0', 'instance1', 'instance2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'instance0'] == 'NA'NEWLINE assert pheno_file.loc[0, 'instance1'] == 'NA'NEWLINE assert pheno_file.loc[0, 'instance2'] == 'NA'NEWLINENEWLINE assert pheno_file.loc[1, 'instance0'] == 'NA'NEWLINE assert pheno_file.loc[1, 'instance1'] == 'NA'NEWLINE assert pheno_file.loc[1, 'instance2'] == 'NA'NEWLINENEWLINE assert pheno_file.loc[2, 'instance0'] == 'Option number 4'NEWLINE assert pheno_file.loc[2, 'instance1'] == "I don't know"NEWLINE assert pheno_file.loc[2, 'instance2'] == 'NA'NEWLINENEWLINE assert pheno_file.loc[3, 'instance0'] == 'Option number 1'NEWLINE assert pheno_file.loc[3, 'instance1'] == 'No response'NEWLINE assert pheno_file.loc[3, 'instance2'] == 'Yes'NEWLINENEWLINE assert pheno_file.loc[4, 'instance0'] == 'NA'NEWLINE assert pheno_file.loc[4, 'instance1'] == 'NA'NEWLINE assert pheno_file.loc[4, 'instance2'] == 'NA'NEWLINENEWLINE def test_phenotype_query_yaml_specify_csv_format_missing_code_changed(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c47_0_0 > 0NEWLINENEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0 NEWLINE instance2: c21_2_0 NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 2NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'fields',NEWLINE 'missing_code': '-999',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3), pheno_file.shapeNEWLINENEWLINE expected_columns = ['instance0', 'instance1', 'instance2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000040, 'instance0'] == 'Option number 4'NEWLINE assert pheno_file.loc[1000040, 'instance1'] == "I don't know"NEWLINE assert pheno_file.loc[1000040, 'instance2'] == '-999'NEWLINENEWLINE assert pheno_file.loc[1000010, 'instance0'] == 'Option number 1'NEWLINE assert pheno_file.loc[1000010, 'instance1'] == 'No response'NEWLINE assert pheno_file.loc[1000010, 'instance2'] == 'Yes'NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_first_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=10)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c34_0_0 >= -5NEWLINE NEWLINE data:NEWLINE disease0:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [N308]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['disease0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'disease0'] == '0' # 1000050NEWLINE assert pheno_file.loc[1, 'disease0'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'disease0'] == '1' # 1000040NEWLINE assert pheno_file.loc[3, 'disease0'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'disease0'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'disease0'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_second_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=20)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c34_0_0 >= -5NEWLINENEWLINE data:NEWLINE disease0:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['disease0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'disease0'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'disease0'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'disease0'] == '1' # 1000040NEWLINE assert pheno_file.loc[3, 'disease0'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'disease0'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'disease0'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_different_filter_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=20)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c31_0_0 > '2001-01-01'NEWLINENEWLINE data:NEWLINE disease0:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['disease0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'disease0'] == 'NA' # 1000050NEWLINE assert pheno_file.loc[1, 'disease0'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'disease0'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'disease0'] == '1' # 1000010NEWLINE assert pheno_file.loc[4, 'disease0'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'disease0'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_filter_includes_nulls_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=20)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c31_0_0 is null or c31_0_0 > '2001-01-01'NEWLINENEWLINE data:NEWLINE disease0:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['disease0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'disease0'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'disease0'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'disease0'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'disease0'] == '1' # 1000010NEWLINE assert pheno_file.loc[4, 'disease0'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'disease0'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_multiple_filters_using_like_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=20)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c31_0_0 is null or c31_0_0 > '2001-01-01'NEWLINE - c21_2_0 not like '%%obab%%'NEWLINENEWLINE data:NEWLINE disease0:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['disease0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'disease0'] == 'NA' # 1000050NEWLINE assert pheno_file.loc[1, 'disease0'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'disease0'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'disease0'] == '1' # 1000010NEWLINE assert pheno_file.loc[4, 'disease0'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'disease0'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_fields_in_filters_are_in_different_tables_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c21_1_0 not like '%%respo%%'NEWLINE - c47_0_0 > 0NEWLINENEWLINE data:NEWLINE disease0:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [Q750]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['disease0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'disease0'] == 'NA' # 1000050NEWLINE assert pheno_file.loc[1, 'disease0'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'disease0'] == '1' # 1000040NEWLINE assert pheno_file.loc[3, 'disease0'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'disease0'] == 'NA' # 1000020NEWLINE assert pheno_file.loc[5, 'disease0'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_different_data_field_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - eid not in (select eid from events where field_id = 84 and event in ('Q750'))NEWLINE NEWLINE data:NEWLINE disease0:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [1114]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['disease0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'disease0'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'disease0'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'disease0'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'disease0'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'disease0'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'disease0'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_different_disease_name_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - eid not in (select eid from events where field_id = 84 and event in ('Q750'))NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [1114]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'another_disease_name'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'another_disease_name'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'another_disease_name'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'another_disease_name'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'another_disease_name'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_coding_not_list_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - eid not in (select eid from events where field_id = 84 and event in ('Q750'))NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: 1114NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'another_disease_name'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'another_disease_name'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'another_disease_name'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'another_disease_name'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'another_disease_name'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_coding_not_list_csv(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - eid not in (select eid from events where field_id = 84 and event in ('Q750'))NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: 1114NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 4NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'another_disease_name'] == '1' # 1000050NEWLINE # assert pheno_file.loc[1000030, 'another_disease_name'] == '0' # 1000030NEWLINE # assert pheno_file.loc['1000040', 'another_disease_name'] == 'NA' # 1000040NEWLINE # assert pheno_file.loc[1000010, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '1' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '0' # 1000070NEWLINE assert pheno_file.loc[1000060, 'another_disease_name'] == '1' # 1000060NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_many_codings_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe')NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [1114, 1701]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'another_disease_name'] == 'NA' # 1000050NEWLINE assert pheno_file.loc[1, 'another_disease_name'] == '0' # 1000030NEWLINE assert pheno_file.loc[2, 'another_disease_name'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[4, 'another_disease_name'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'another_disease_name'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_many_codings_csv(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe')NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [1114, 1701]NEWLINE """NEWLINENEWLINE # text/csv does not fetch all samples in 'samples' table by defaultNEWLINE N_EXPECTED_SAMPLES = 5NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE # assert pheno_file.loc['1000050', 'another_disease_name'] == 'NA' # 1000050NEWLINE assert pheno_file.loc[1000030, 'another_disease_name'] == '0' # 1000030NEWLINE # assert pheno_file.loc['1000040', 'another_disease_name'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[1000010, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '1' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '0' # 1000070NEWLINE assert pheno_file.loc[1000060, 'another_disease_name'] == '1' # 1000060NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_many_data_fields_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c21_2_0 is null or lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [978, 1701]NEWLINE 84:NEWLINE coding: [Z876, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[2, 'another_disease_name'] == '0' # 1000040NEWLINE assert pheno_file.loc[3, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[4, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[5, 'another_disease_name'] == '1' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_many_data_fields_csv(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c21_2_0 is null or lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [978, 1701]NEWLINE 84:NEWLINE coding: [Z876, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 7NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[1000040, 'another_disease_name'] == '0' # 1000040NEWLINE assert pheno_file.loc[1000010, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '1' # 1000070NEWLINE assert pheno_file.loc[1000060, 'another_disease_name'] == '1' # 1000060NEWLINENEWLINE def test_phenotype_query_yaml_disease_filters_not_referencing_table_bgenie(self):NEWLINE """This test forces a global table to obtain eid from for controls"""NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - 1 = 1NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [978, 1701]NEWLINE 84:NEWLINE coding: [Z876, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[2, 'another_disease_name'] == '0' # 1000040NEWLINE assert pheno_file.loc[3, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[4, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[5, 'another_disease_name'] == '1' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_filters_not_referencing_table_csv(self):NEWLINE """This test forces a global table to obtain eid from for controls"""NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - 1 = 1NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [978, 1701]NEWLINE 84:NEWLINE coding: [Z876, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 7NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[1000040, 'another_disease_name'] == '0' # 1000040NEWLINE assert pheno_file.loc[1000010, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '1' # 1000070NEWLINE assert pheno_file.loc[1000060, 'another_disease_name'] == '1' # 1000060NEWLINENEWLINE def test_phenotype_query_yaml_disease_no_filters_csv(self):NEWLINE """This test forces a global table to obtain eid from for controls"""NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [978, 1701]NEWLINE 84:NEWLINE coding: [Z876, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 7NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[1000040, 'another_disease_name'] == '0' # 1000040NEWLINE assert pheno_file.loc[1000010, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '1' # 1000070NEWLINE assert pheno_file.loc[1000060, 'another_disease_name'] == '1' # 1000060NEWLINENEWLINE def test_phenotype_query_yaml_disease_many_columns_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 > -10NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [978, 1701]NEWLINE 84:NEWLINE coding: [Z876, Z678]NEWLINE second_column:NEWLINE case_control:NEWLINE 85:NEWLINE coding: 1114NEWLINE third_column:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name', 'second_column', 'third_column']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[2, 'another_disease_name'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'another_disease_name'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[5, 'another_disease_name'] == '1' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE assert pheno_file.loc[0, 'second_column'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'second_column'] == '0' # 1000030NEWLINE assert pheno_file.loc[2, 'second_column'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'second_column'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'second_column'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'second_column'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE assert pheno_file.loc[0, 'third_column'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'third_column'] == '0' # 1000030NEWLINE assert pheno_file.loc[2, 'third_column'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'third_column'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'third_column'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'third_column'] == '1' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_many_columns_csv(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 > -10NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [978, 1701]NEWLINE 84:NEWLINE coding: [Z876, Z678]NEWLINE second_column:NEWLINE case_control:NEWLINE 85:NEWLINE coding: 1114NEWLINE third_column:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 4NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name', 'second_column', 'third_column']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '1' # 1000070NEWLINENEWLINE assert pheno_file.loc[1000050, 'second_column'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'second_column'] == '0' # 1000030NEWLINE assert pheno_file.loc[1000020, 'second_column'] == '1' # 1000020NEWLINE assert pheno_file.loc[1000070, 'second_column'] == '0' # 1000070NEWLINENEWLINE assert pheno_file.loc[1000050, 'third_column'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'third_column'] == '0' # 1000030NEWLINE assert pheno_file.loc[1000020, 'third_column'] == '1' # 1000020NEWLINE assert pheno_file.loc[1000070, 'third_column'] == '1' # 1000070NEWLINENEWLINE def test_phenotype_query_yaml_disease_sql_alone_csv(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10NEWLINENEWLINE data:NEWLINE mydisease:NEWLINE sql:NEWLINE 1: c46_0_0 > 0NEWLINE 0: c46_0_0 < 0NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 4NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['mydisease']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'mydisease'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'mydisease'] == '0' # 1000030NEWLINE assert pheno_file.loc[1000020, 'mydisease'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'mydisease'] == '1' # 1000070NEWLINENEWLINE @unittest.skip("We should check if there are repeated eid values, like in this case, due to bad specification of conditions for categories")NEWLINE def test_phenotype_query_yaml_disease_sql_conflicting_duplicated_samples_csv(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10NEWLINENEWLINE data:NEWLINE mydisease:NEWLINE sql:NEWLINE 1: c46_0_0 >= 1NEWLINE 0: c46_0_0 <= 1NEWLINE """NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 400, response.status_codeNEWLINENEWLINE def test_phenotype_query_yaml_disease_sql_with_many_columns_csv(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # Here I emulate case_control with sqlNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 > -10NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE sql:NEWLINE 1: >NEWLINE eid in (select eid from events where field_id = 85 and event in ('978', '1701'))NEWLINE ORNEWLINE eid in (select eid from events where field_id = 84 and event in ('Z876', 'Z678'))NEWLINE 0: >NEWLINE eid not in (NEWLINE (select eid from events where field_id = 85 and event in ('978', '1701'))NEWLINE unionNEWLINE (select eid from events where field_id = 84 and event in ('Z876', 'Z678'))NEWLINE )NEWLINE second_column:NEWLINE case_control:NEWLINE 85:NEWLINE coding: 1114NEWLINE third_column:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 4NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name', 'second_column', 'third_column']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '1' # 1000070NEWLINENEWLINE assert pheno_file.loc[1000050, 'second_column'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'second_column'] == '0' # 1000030NEWLINE assert pheno_file.loc[1000020, 'second_column'] == '1' # 1000020NEWLINE assert pheno_file.loc[1000070, 'second_column'] == '0' # 1000070NEWLINENEWLINE assert pheno_file.loc[1000050, 'third_column'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'third_column'] == '0' # 1000030NEWLINE assert pheno_file.loc[1000020, 'third_column'] == '1' # 1000020NEWLINE assert pheno_file.loc[1000070, 'third_column'] == '1' # 1000070NEWLINENEWLINE def test_phenotype_query_yaml_disease_sql_no_filters_csv(self):NEWLINE """This test forces a global table to obtain eid from for controls"""NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE data:NEWLINE another_disease_name:NEWLINE sql:NEWLINE 1: >NEWLINE eid in (select eid from events where field_id = 85 and event in ('978', '1701'))NEWLINE ORNEWLINE eid in (select eid from events where field_id = 84 and event in ('Z876', 'Z678'))NEWLINE 0: >NEWLINE eid not in (NEWLINE (select eid from events where field_id = 85 and event in ('978', '1701'))NEWLINE unionNEWLINE (select eid from events where field_id = 84 and event in ('Z876', 'Z678'))NEWLINE )NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 7NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[1000040, 'another_disease_name'] == '0' # 1000040NEWLINE assert pheno_file.loc[1000010, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '1' # 1000070NEWLINE assert pheno_file.loc[1000060, 'another_disease_name'] == '1' # 1000060NEWLINENEWLINE def test_phenotype_query_yaml_samples_filters_condition_breaking_for_data(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case there is an or condition that could break all if it is not surrounding by ()NEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10 or c34_0_0 > -11NEWLINENEWLINE data:NEWLINE mydisease:NEWLINE sql:NEWLINE 1: c46_0_0 > 0NEWLINE 0: c46_0_0 < 0NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 4NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['mydisease']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'mydisease'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'mydisease'] == '0' # 1000030NEWLINE assert pheno_file.loc[1000020, 'mydisease'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'mydisease'] == '1' # 1000070NEWLINENEWLINE def test_phenotype_query_yaml_samples_including_numerical(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case there is an or condition that could break all if it is not surrounding by ()NEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10 or c34_0_0 > -11NEWLINENEWLINE data:NEWLINE continuous_data: c47_0_0NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 5NEWLINE expected_columns = ['continuous_data']NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, len(expected_columns)), pheno_file.shapeNEWLINENEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'continuous_data'] == 'NA'NEWLINE assert pheno_file.loc[1000030, 'continuous_data'] == '-35.31471'NEWLINE assert pheno_file.loc[1000020, 'continuous_data'] == '-10.51461'NEWLINE assert pheno_file.loc[1000060, 'continuous_data'] == '-0.5864'NEWLINE assert pheno_file.loc[1000070, 'continuous_data'] == '3.5584'NEWLINENEWLINE def test_phenotype_query_yaml_samples_including_numerical_integer(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case there is an or condition that could break all if it is not surrounding by ()NEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10 or c34_0_0 > -11NEWLINENEWLINE data:NEWLINE integer_data:NEWLINE (case when c46_0_0 < -5 then NULL else c46_0_0 end)NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 5NEWLINE expected_columns = ['integer_data']NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, len(expected_columns)), pheno_file.shapeNEWLINENEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'integer_data'] == '1'NEWLINE assert pheno_file.loc[1000030, 'integer_data'] == 'NA'NEWLINE assert pheno_file.loc[1000020, 'integer_data'] == '-2'NEWLINE assert pheno_file.loc[1000060, 'integer_data'] == 'NA'NEWLINE assert pheno_file.loc[1000070, 'integer_data'] == '2'NEWLINENEWLINE def test_phenotype_query_yaml_samples_including_categorical_and_numerical(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case there is an or condition that could break all if it is not surrounding by ()NEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10 or c34_0_0 > -11NEWLINENEWLINE data:NEWLINE mydisease:NEWLINE sql:NEWLINE 1: c46_0_0 > 0NEWLINE 0: c46_0_0 < 0NEWLINE NEWLINE third_column:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103, Z678]NEWLINE NEWLINE continuous_data:NEWLINE c47_0_0NEWLINE NEWLINE integer_data: (case when c46_0_0 < 0 then NULL else c46_0_0 end)NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 5NEWLINE expected_columns = ['mydisease', 'third_column', 'continuous_data', 'integer_data']NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, len(expected_columns)), pheno_file.shapeNEWLINENEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'mydisease'] == '1'NEWLINE assert pheno_file.loc[1000030, 'mydisease'] == '0'NEWLINE assert pheno_file.loc[1000020, 'mydisease'] == '0'NEWLINE assert pheno_file.loc[1000060, 'mydisease'] == 'NA'NEWLINE assert pheno_file.loc[1000070, 'mydisease'] == '1'NEWLINENEWLINE assert pheno_file.loc[1000050, 'third_column'] == '1'NEWLINE assert pheno_file.loc[1000030, 'third_column'] == '0'NEWLINE assert pheno_file.loc[1000020, 'third_column'] == '1'NEWLINE assert pheno_file.loc[1000060, 'third_column'] == '0'NEWLINE assert pheno_file.loc[1000070, 'third_column'] == '1'NEWLINENEWLINE assert pheno_file.loc[1000050, 'continuous_data'] == 'NA'NEWLINE assert pheno_file.loc[1000030, 'continuous_data'] == '-35.31471'NEWLINE assert pheno_file.loc[1000020, 'continuous_data'] == '-10.51461'NEWLINE assert pheno_file.loc[1000060, 'continuous_data'] == '-0.5864'NEWLINE assert pheno_file.loc[1000070, 'continuous_data'] == '3.5584'NEWLINENEWLINE assert pheno_file.loc[1000050, 'integer_data'] == '1'NEWLINE assert pheno_file.loc[1000030, 'integer_data'] == 'NA'NEWLINE assert pheno_file.loc[1000020, 'integer_data'] == 'NA'NEWLINE assert pheno_file.loc[1000060, 'integer_data'] == 'NA'NEWLINE assert pheno_file.loc[1000070, 'integer_data'] == '2'NEWLINENEWLINE def test_phenotype_query_yaml_multiple_files_in_one_yaml(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case there is an or condition that could break all if it is not surrounding by ()NEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10 or c34_0_0 > -11NEWLINENEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE my_first_dataset:NEWLINE mydisease:NEWLINE sql:NEWLINE 1: c46_0_0 > 0NEWLINE 0: c46_0_0 < 0NEWLINENEWLINE continuous_data:NEWLINE c47_0_0NEWLINENEWLINE my_second_dataset:NEWLINE third_column:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103, Z678]NEWLINENEWLINE integer_data: (case when c46_0_0 < 0 then NULL else c46_0_0 end)NEWLINE """NEWLINENEWLINE # covariatesNEWLINE data_fetched =\NEWLINE self._make_yaml_request(NEWLINE yaml_data, 'covariates', 5,NEWLINE ['field_name_34', 'field_name_47']NEWLINE )NEWLINENEWLINE assert data_fetched.loc[1000020, 'field_name_34'] == '34'NEWLINE assert data_fetched.loc[1000030, 'field_name_34'] == '-6'NEWLINE assert data_fetched.loc[1000050, 'field_name_34'] == '-4'NEWLINE assert data_fetched.loc[1000060, 'field_name_34'] == 'NA'NEWLINE assert data_fetched.loc[1000070, 'field_name_34'] == '-5'NEWLINENEWLINE # my_first_datasetNEWLINE data_fetched =\NEWLINE self._make_yaml_request(NEWLINE yaml_data, 'my_first_dataset', 5,NEWLINE ['mydisease', 'continuous_data']NEWLINE )NEWLINENEWLINE assert data_fetched.loc[1000050, 'mydisease'] == '1'NEWLINE assert data_fetched.loc[1000030, 'mydisease'] == '0'NEWLINE assert data_fetched.loc[1000020, 'mydisease'] == '0'NEWLINE assert data_fetched.loc[1000060, 'mydisease'] == 'NA'NEWLINE assert data_fetched.loc[1000070, 'mydisease'] == '1'NEWLINENEWLINE assert data_fetched.loc[1000050, 'continuous_data'] == 'NA'NEWLINE assert data_fetched.loc[1000030, 'continuous_data'] == '-35.31471'NEWLINE assert data_fetched.loc[1000020, 'continuous_data'] == '-10.51461'NEWLINE assert data_fetched.loc[1000060, 'continuous_data'] == '-0.5864'NEWLINE assert data_fetched.loc[1000070, 'continuous_data'] == '3.5584'NEWLINENEWLINE # my_second_datasetNEWLINE data_fetched =\NEWLINE self._make_yaml_request(NEWLINE yaml_data, 'my_second_dataset', 5,NEWLINE ['third_column', 'integer_data']NEWLINE )NEWLINENEWLINE assert data_fetched.loc[1000050, 'third_column'] == '1'NEWLINE assert data_fetched.loc[1000030, 'third_column'] == '0'NEWLINE assert data_fetched.loc[1000020, 'third_column'] == '1'NEWLINE assert data_fetched.loc[1000060, 'third_column'] == '0'NEWLINE assert data_fetched.loc[1000070, 'third_column'] == '1'NEWLINENEWLINE assert data_fetched.loc[1000050, 'integer_data'] == '1'NEWLINE assert data_fetched.loc[1000030, 'integer_data'] == 'NA'NEWLINE assert data_fetched.loc[1000020, 'integer_data'] == 'NA'NEWLINE assert data_fetched.loc[1000060, 'integer_data'] == 'NA'NEWLINE assert data_fetched.loc[1000070, 'integer_data'] == '2'NEWLINENEWLINE def test_phenotype_query_yaml_simple_query(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # this type of query, with 'simple_' at the begining of the data section, makes direct queries to theNEWLINE # databaseNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10 or c34_0_0 > -11NEWLINENEWLINE simple_covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINE """NEWLINENEWLINE # simple_covariatesNEWLINE data_fetched =\NEWLINE self._make_yaml_request(NEWLINE yaml_data, 'simple_covariates', 5,NEWLINE ['field_name_34', 'field_name_47']NEWLINE )NEWLINENEWLINE assert data_fetched.loc[1000020, 'field_name_34'] == '34'NEWLINE assert data_fetched.loc[1000030, 'field_name_34'] == '-6'NEWLINE assert data_fetched.loc[1000050, 'field_name_34'] == '-4'NEWLINE assert data_fetched.loc[1000060, 'field_name_34'] == 'NA'NEWLINE assert data_fetched.loc[1000070, 'field_name_34'] == '-5'NEWLINE from unittest import TestCaseNEWLINENEWLINEclass TestArmLexer(TestCase): from .get_script import get_script # noqaNEWLINEfrom scripts import custom # noqaNEWLINE from datetime import dateNEWLINEfrom datetime import datetimeNEWLINEfrom datetime import timedelta as deltaNEWLINENEWLINEimport sysNEWLINEimport numpy as npNEWLINEimport xarray as xrNEWLINENEWLINEfrom parcels.grid import GridCodeNEWLINEfrom parcels.grid import CurvilinearGridNEWLINEfrom parcels.kernel import KernelNEWLINEfrom parcels.particle import JITParticleNEWLINEfrom parcels.particlefile import ParticleFileNEWLINEfrom parcels.tools.statuscodes import StateCodeNEWLINEfrom .baseparticleset import BaseParticleSetNEWLINEfrom .collectionsoa import ParticleCollectionSOANEWLINEfrom .collectionsoa import ParticleCollectionIteratorSOANEWLINEfrom parcels.tools.converters import _get_cftime_calendarsNEWLINEfrom parcels.tools.loggers import loggerNEWLINEtry:NEWLINE from mpi4py import MPINEWLINEexcept:NEWLINE MPI = NoneNEWLINE# == comment CK: prevents us from adding KDTree as 'mandatory' dependency == #NEWLINEtry:NEWLINE from pykdtree.kdtree import KDTreeNEWLINEexcept:NEWLINE KDTree = NoneNEWLINENEWLINE__all__ = ['ParticleSet', 'ParticleSetSOA']NEWLINENEWLINENEWLINEdef _convert_to_array(var):NEWLINE """Convert lists and single integers/floats to one-dimensional numpyNEWLINE arraysNEWLINE """NEWLINE if isinstance(var, np.ndarray):NEWLINE return var.flatten()NEWLINE elif isinstance(var, (int, float, np.float32, np.int32)):NEWLINE return np.array([var])NEWLINE else:NEWLINE return np.array(var)NEWLINENEWLINENEWLINEdef _convert_to_reltime(time):NEWLINE """Check to determine if the value of the time parameter needs to beNEWLINE converted to a relative value (relative to the time_origin).NEWLINE """NEWLINE if isinstance(time, np.datetime64) or (hasattr(time, 'calendar') and time.calendar in _get_cftime_calendars()):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINEclass ParticleSetSOA(BaseParticleSet):NEWLINE """Container class for storing particle and executing kernel over them.NEWLINENEWLINE Please note that this currently only supports fixed size particle sets.NEWLINENEWLINE :param fieldset: :mod:`parcels.fieldset.FieldSet` object from which to sample velocity.NEWLINE While fieldset=None is supported, this will throw a warning as it breaks most Parcels functionalityNEWLINE :param pclass: Optional :mod:`parcels.particle.JITParticle` orNEWLINE :mod:`parcels.particle.ScipyParticle` object that defines custom particleNEWLINE :param lon: List of initial longitude values for particlesNEWLINE :param lat: List of initial latitude values for particlesNEWLINE :param depth: Optional list of initial depth values for particles. Default is 0mNEWLINE :param time: Optional list of initial time values for particles. Default is fieldset.U.grid.time[0]NEWLINE :param repeatdt: Optional interval (in seconds) on which to repeat the release of the ParticleSetNEWLINE :param lonlatdepth_dtype: Floating precision for lon, lat, depth particle coordinates.NEWLINE It is either np.float32 or np.float64. Default is np.float32 if fieldset.U.interp_method is 'linear'NEWLINE and np.float64 if the interpolation method is 'cgrid_velocity'NEWLINE :param pid_orig: Optional list of (offsets for) the particle IDsNEWLINE :param partitions: List of cores on which to distribute the particles for MPI runs. Default: None, in which case particlesNEWLINE are distributed automatically on the processorsNEWLINENEWLINE Other Variables can be initialised using further arguments (e.g. v=... for a Variable named 'v')NEWLINE """NEWLINENEWLINE def __init__(self, fieldset=None, pclass=JITParticle, lon=None, lat=None, depth=None, time=None, repeatdt=None, lonlatdepth_dtype=None, pid_orig=None, **kwargs):NEWLINE super(ParticleSetSOA, self).__init__()NEWLINE self.fieldset = fieldsetNEWLINE if self.fieldset is None:NEWLINE logger.warning_once("No FieldSet provided in ParticleSet generation. "NEWLINE "This breaks most Parcels functionality")NEWLINE else:NEWLINE self.fieldset.check_complete()NEWLINE partitions = kwargs.pop('partitions', None)NEWLINENEWLINE lon = np.empty(shape=0) if lon is None else _convert_to_array(lon)NEWLINE lat = np.empty(shape=0) if lat is None else _convert_to_array(lat)NEWLINENEWLINE if isinstance(pid_orig, (type(None), type(False))):NEWLINE pid_orig = np.arange(lon.size)NEWLINENEWLINE if depth is None:NEWLINE mindepth = self.fieldset.gridset.dimrange('depth')[0] if self.fieldset is not None else 0NEWLINE depth = np.ones(lon.size) * mindepthNEWLINE else:NEWLINE depth = _convert_to_array(depth)NEWLINE assert lon.size == lat.size and lon.size == depth.size, (NEWLINE 'lon, lat, depth don''t all have the same lenghts')NEWLINENEWLINE time = _convert_to_array(time)NEWLINE time = np.repeat(time, lon.size) if time.size == 1 else timeNEWLINENEWLINE if time.size > 0 and type(time[0]) in [datetime, date]:NEWLINE time = np.array([np.datetime64(t) for t in time])NEWLINE self.time_origin = fieldset.time_origin if self.fieldset is not None else 0NEWLINE if time.size > 0 and isinstance(time[0], np.timedelta64) and not self.time_origin:NEWLINE raise NotImplementedError('If fieldset.time_origin is not a date, time of a particle must be a double')NEWLINE time = np.array([self.time_origin.reltime(t) if _convert_to_reltime(t) else t for t in time])NEWLINE assert lon.size == time.size, (NEWLINE 'time and positions (lon, lat, depth) don''t have the same lengths.')NEWLINENEWLINE if lonlatdepth_dtype is None:NEWLINE if fieldset is not None:NEWLINE lonlatdepth_dtype = self.lonlatdepth_dtype_from_field_interp_method(fieldset.U)NEWLINE else:NEWLINE lonlatdepth_dtype = np.float32NEWLINE assert lonlatdepth_dtype in [np.float32, np.float64], \NEWLINE 'lon lat depth precision should be set to either np.float32 or np.float64'NEWLINENEWLINE for kwvar in kwargs:NEWLINE kwargs[kwvar] = _convert_to_array(kwargs[kwvar])NEWLINE assert lon.size == kwargs[kwvar].size, (NEWLINE '%s and positions (lon, lat, depth) don''t have the same lengths.' % kwvar)NEWLINENEWLINE self.repeatdt = repeatdt.total_seconds() if isinstance(repeatdt, delta) else repeatdtNEWLINE if self.repeatdt:NEWLINE if self.repeatdt <= 0:NEWLINE raise('Repeatdt should be > 0')NEWLINE if time[0] and not np.allclose(time, time[0]):NEWLINE raise ('All Particle.time should be the same when repeatdt is not None')NEWLINE self.repeatpclass = pclassNEWLINE self.repeatkwargs = kwargsNEWLINENEWLINE ngrids = fieldset.gridset.size if fieldset is not None else 1NEWLINE self._collection = ParticleCollectionSOA(pclass, lon=lon, lat=lat, depth=depth, time=time, lonlatdepth_dtype=lonlatdepth_dtype, pid_orig=pid_orig, partitions=partitions, ngrid=ngrids, **kwargs)NEWLINENEWLINE if self.repeatdt:NEWLINE if len(time) > 0 and time[0] is None:NEWLINE self.repeat_starttime = time[0]NEWLINE else:NEWLINE if self._collection.data['time'][0] and not np.allclose(self._collection.data['time'], self._collection.data['time'][0]):NEWLINE raise ValueError('All Particle.time should be the same when repeatdt is not None')NEWLINE self.repeat_starttime = self._collection.data['time'][0]NEWLINE self.repeatlon = self._collection.data['lon']NEWLINE self.repeatlat = self._collection.data['lat']NEWLINE self.repeatdepth = self._collection.data['depth']NEWLINE for kwvar in kwargs:NEWLINE self.repeatkwargs[kwvar] = self._collection.data[kwvar]NEWLINENEWLINE if self.repeatdt:NEWLINE if MPI and self._collection.pu_indicators is not None:NEWLINE mpi_comm = MPI.COMM_WORLDNEWLINE mpi_rank = mpi_comm.Get_rank()NEWLINE self.repeatpid = pid_orig[self._collection.pu_indicators == mpi_rank]NEWLINENEWLINE self.kernel = NoneNEWLINENEWLINE def _set_particle_vector(self, name, value):NEWLINE """Set attributes of all particles to new values.NEWLINENEWLINE :param name: Name of the attribute (str).NEWLINE :param value: New value to set the attribute of the particles to.NEWLINE """NEWLINE self.collection._data[name][:] = valueNEWLINENEWLINE def _impute_release_times(self, default):NEWLINE """Set attribute 'time' to default if encountering NaN values.NEWLINENEWLINE :param default: Default release time.NEWLINE :return: Minimum and maximum release times.NEWLINE """NEWLINE if np.any(np.isnan(self._collection.data['time'])):NEWLINE self._collection.data['time'][np.isnan(self._collection.data['time'])] = defaultNEWLINE return np.min(self._collection.data['time']), np.max(self._collection.data['time'])NEWLINENEWLINE def data_indices(self, variable_name, compare_values, invert=False):NEWLINE """Get the indices of all particles where the value ofNEWLINE `variable_name` equals (one of) `compare_values`.NEWLINENEWLINE :param variable_name: Name of the variable to check.NEWLINE :param compare_values: Value or list of values to compare to.NEWLINE :param invert: Whether to invert the selection. I.e., when True,NEWLINE return all indices that do not equal (one of)NEWLINE `compare_values`.NEWLINE :return: Numpy array of indices that satisfy the test.NEWLINE """NEWLINE compare_values = np.array([compare_values, ]) if type(compare_values) not in [list, dict, np.ndarray] else compare_valuesNEWLINE return np.where(np.isin(self._collection.data[variable_name], compare_values, invert=invert))[0]NEWLINENEWLINE def indexed_subset(self, indices):NEWLINE return ParticleCollectionIteratorSOA(self._collection,NEWLINE subset=indices)NEWLINENEWLINE def populate_indices(self):NEWLINE """Pre-populate guesses of particle xi/yi indices using a kdtree.NEWLINENEWLINE This is only intended for curvilinear grids, where the initial index searchNEWLINE may be quite expensive.NEWLINE """NEWLINENEWLINE if self.fieldset is None:NEWLINE # we need to be attached to a fieldset to have a validNEWLINE # gridset to search for indicesNEWLINE returnNEWLINENEWLINE if KDTree is None:NEWLINE returnNEWLINE else:NEWLINE for i, grid in enumerate(self.fieldset.gridset.grids):NEWLINE if not isinstance(grid, CurvilinearGrid):NEWLINE continueNEWLINENEWLINE tree_data = np.stack((grid.lon.flat, grid.lat.flat), axis=-1)NEWLINE tree = KDTree(tree_data)NEWLINE # stack all the particle positions for a single queryNEWLINE pts = np.stack((self._collection.data['lon'], self._collection.data['lat']), axis=-1)NEWLINE # query datatype needs to match tree datatypeNEWLINE _, idx = tree.query(pts.astype(tree_data.dtype))NEWLINE yi, xi = np.unravel_index(idx, grid.lon.shape)NEWLINENEWLINE self._collection.data['xi'][:, i] = xiNEWLINE self._collection.data['yi'][:, i] = yiNEWLINENEWLINE @propertyNEWLINE def error_particles(self):NEWLINE """Get an iterator over all particles that are in an error state.NEWLINENEWLINE :return: Collection iterator over error particles.NEWLINE """NEWLINE error_indices = self.data_indices('state', [StateCode.Success, StateCode.Evaluate], invert=True)NEWLINE return ParticleCollectionIteratorSOA(self._collection, subset=error_indices)NEWLINENEWLINE @propertyNEWLINE def num_error_particles(self):NEWLINE """Get the number of particles that are in an error state.NEWLINENEWLINE :return: The number of error particles.NEWLINE """NEWLINE return np.sum(np.isin(NEWLINE self._collection.data['state'],NEWLINE [StateCode.Success, StateCode.Evaluate], invert=True))NEWLINENEWLINE def __getitem__(self, index):NEWLINE """Get a single particle by index"""NEWLINE return self._collection.get_single_by_index(index)NEWLINENEWLINE def cstruct(self):NEWLINE """NEWLINE 'cstruct' returns the ctypes mapping of the combined collections cstruct and the fieldset cstruct.NEWLINE This depends on the specific structure in question.NEWLINE """NEWLINE cstruct = self._collection.cstruct()NEWLINE return cstructNEWLINENEWLINE @propertyNEWLINE def ctypes_struct(self):NEWLINE return self.cstruct()NEWLINENEWLINE @classmethodNEWLINE def monte_carlo_sample(cls, start_field, size, mode='monte_carlo'):NEWLINE """NEWLINE Converts a starting field into a monte-carlo sample of lons and lats.NEWLINENEWLINE :param start_field: :mod:`parcels.fieldset.Field` object for initialising particles stochastically (horizontally) according to the presented density field.NEWLINENEWLINE returns list(lon), list(lat)NEWLINE """NEWLINE if mode == 'monte_carlo':NEWLINE data = start_field.data if isinstance(start_field.data, np.ndarray) else np.array(start_field.data)NEWLINE if start_field.interp_method == 'cgrid_tracer':NEWLINE p_interior = np.squeeze(data[0, 1:, 1:])NEWLINE else: # if A-gridNEWLINE d = dataNEWLINE p_interior = (d[0, :-1, :-1] + d[0, 1:, :-1] + d[0, :-1, 1:] + d[0, 1:, 1:])/4.NEWLINE p_interior = np.where(d[0, :-1, :-1] == 0, 0, p_interior)NEWLINE p_interior = np.where(d[0, 1:, :-1] == 0, 0, p_interior)NEWLINE p_interior = np.where(d[0, 1:, 1:] == 0, 0, p_interior)NEWLINE p_interior = np.where(d[0, :-1, 1:] == 0, 0, p_interior)NEWLINE p = np.reshape(p_interior, (1, p_interior.size))NEWLINE inds = np.random.choice(p_interior.size, size, replace=True, p=p[0] / np.sum(p))NEWLINE xsi = np.random.uniform(size=len(inds))NEWLINE eta = np.random.uniform(size=len(inds))NEWLINE j, i = np.unravel_index(inds, p_interior.shape)NEWLINE grid = start_field.gridNEWLINE lon, lat = ([], [])NEWLINE if grid.gtype in [GridCode.RectilinearZGrid, GridCode.RectilinearSGrid]:NEWLINE lon = grid.lon[i] + xsi * (grid.lon[i + 1] - grid.lon[i])NEWLINE lat = grid.lat[j] + eta * (grid.lat[j + 1] - grid.lat[j])NEWLINE else:NEWLINE lons = np.array([grid.lon[j, i], grid.lon[j, i+1], grid.lon[j+1, i+1], grid.lon[j+1, i]])NEWLINE if grid.mesh == 'spherical':NEWLINE lons[1:] = np.where(lons[1:] - lons[0] > 180, lons[1:]-360, lons[1:])NEWLINE lons[1:] = np.where(-lons[1:] + lons[0] > 180, lons[1:]+360, lons[1:])NEWLINE lon = (1-xsi)*(1-eta) * lons[0] +\NEWLINE xsi*(1-eta) * lons[1] +\NEWLINE xsi*eta * lons[2] +\NEWLINE (1-xsi)*eta * lons[3]NEWLINE lat = (1-xsi)*(1-eta) * grid.lat[j, i] +\NEWLINE xsi*(1-eta) * grid.lat[j, i+1] +\NEWLINE xsi*eta * grid.lat[j+1, i+1] +\NEWLINE (1-xsi)*eta * grid.lat[j+1, i]NEWLINE return list(lon), list(lat)NEWLINE else:NEWLINE raise NotImplementedError('Mode %s not implemented. Please use "monte carlo" algorithm instead.' % mode)NEWLINENEWLINE @classmethodNEWLINE def from_field(cls, fieldset, pclass, start_field, size, mode='monte_carlo', depth=None, time=None, repeatdt=None, lonlatdepth_dtype=None):NEWLINE """Initialise the ParticleSet randomly drawn according to distribution from a fieldNEWLINENEWLINE :param fieldset: :mod:`parcels.fieldset.FieldSet` object from which to sample velocityNEWLINE :param pclass: mod:`parcels.particle.JITParticle` or :mod:`parcels.particle.ScipyParticle`NEWLINE object that defines custom particleNEWLINE :param start_field: Field for initialising particles stochastically (horizontally) according to the presented density field.NEWLINE :param size: Initial size of particle setNEWLINE :param mode: Type of random sampling. Currently only 'monte_carlo' is implementedNEWLINE :param depth: Optional list of initial depth values for particles. Default is 0mNEWLINE :param time: Optional start time value for particles. Default is fieldset.U.time[0]NEWLINE :param repeatdt: Optional interval (in seconds) on which to repeat the release of the ParticleSetNEWLINE :param lonlatdepth_dtype: Floating precision for lon, lat, depth particle coordinates.NEWLINE It is either np.float32 or np.float64. Default is np.float32 if fieldset.U.interp_method is 'linear'NEWLINE and np.float64 if the interpolation method is 'cgrid_velocity'NEWLINE """NEWLINE lon, lat = cls.monte_carlo_sample(start_field, size, mode)NEWLINENEWLINE return cls(fieldset=fieldset, pclass=pclass, lon=lon, lat=lat, depth=depth, time=time,NEWLINE lonlatdepth_dtype=lonlatdepth_dtype, repeatdt=repeatdt)NEWLINENEWLINE @classmethodNEWLINE def from_particlefile(cls, fieldset, pclass, filename, restart=True, restarttime=None, repeatdt=None, lonlatdepth_dtype=None, **kwargs):NEWLINE """Initialise the ParticleSet from a netcdf ParticleFile.NEWLINE This creates a new ParticleSet based on locations of all particles writtenNEWLINE in a netcdf ParticleFile at a certain time. Particle IDs are preserved if restart=TrueNEWLINENEWLINE :param fieldset: :mod:`parcels.fieldset.FieldSet` object from which to sample velocityNEWLINE :param pclass: mod:`parcels.particle.JITParticle` or :mod:`parcels.particle.ScipyParticle`NEWLINE object that defines custom particleNEWLINE :param filename: Name of the particlefile from which to read initial conditionsNEWLINE :param restart: Boolean to signal if pset is used for a restart (default is True).NEWLINE In that case, Particle IDs are preserved.NEWLINE :param restarttime: time at which the Particles will be restarted. Default is the last time written.NEWLINE Alternatively, restarttime could be a time value (including np.datetime64) orNEWLINE a callable function such as np.nanmin. The last is useful when running with dt < 0.NEWLINE :param repeatdt: Optional interval (in seconds) on which to repeat the release of the ParticleSetNEWLINE :param lonlatdepth_dtype: Floating precision for lon, lat, depth particle coordinates.NEWLINE It is either np.float32 or np.float64. Default is np.float32 if fieldset.U.interp_method is 'linear'NEWLINE and np.float64 if the interpolation method is 'cgrid_velocity'NEWLINE """NEWLINENEWLINE if repeatdt is not None:NEWLINE logger.warning('Note that the `repeatdt` argument is not retained from %s, and that 'NEWLINE 'setting a new repeatdt will start particles from the _new_ particle 'NEWLINE 'locations.' % filename)NEWLINENEWLINE pfile = xr.open_dataset(str(filename), decode_cf=True)NEWLINE pfile_vars = [v for v in pfile.data_vars]NEWLINENEWLINE vars = {}NEWLINE to_write = {}NEWLINE for v in pclass.getPType().variables:NEWLINE if v.name in pfile_vars:NEWLINE vars[v.name] = np.ma.filled(pfile.variables[v.name], np.nan)NEWLINE elif v.name not in ['xi', 'yi', 'zi', 'ti', 'dt', '_next_dt', 'depth', 'id', 'fileid', 'state'] \NEWLINE and v.to_write:NEWLINE raise RuntimeError('Variable %s is in pclass but not in the particlefile' % v.name)NEWLINE to_write[v.name] = v.to_writeNEWLINE vars['depth'] = np.ma.filled(pfile.variables['z'], np.nan)NEWLINE vars['id'] = np.ma.filled(pfile.variables['trajectory'], np.nan)NEWLINENEWLINE if isinstance(vars['time'][0, 0], np.timedelta64):NEWLINE vars['time'] = np.array([t/np.timedelta64(1, 's') for t in vars['time']])NEWLINENEWLINE if restarttime is None:NEWLINE restarttime = np.nanmax(vars['time'])NEWLINE elif callable(restarttime):NEWLINE restarttime = restarttime(vars['time'])NEWLINE else:NEWLINE restarttime = restarttimeNEWLINENEWLINE inds = np.where(vars['time'] == restarttime)NEWLINE for v in vars:NEWLINE if to_write[v] is True:NEWLINE vars[v] = vars[v][inds]NEWLINE elif to_write[v] == 'once':NEWLINE vars[v] = vars[v][inds[0]]NEWLINE if v not in ['lon', 'lat', 'depth', 'time', 'id']:NEWLINE kwargs[v] = vars[v]NEWLINENEWLINE if restart:NEWLINE pclass.setLastID(0) # reset to zero offsetNEWLINE else:NEWLINE vars['id'] = NoneNEWLINENEWLINE return cls(fieldset=fieldset, pclass=pclass, lon=vars['lon'], lat=vars['lat'],NEWLINE depth=vars['depth'], time=vars['time'], pid_orig=vars['id'],NEWLINE lonlatdepth_dtype=lonlatdepth_dtype, repeatdt=repeatdt, **kwargs)NEWLINENEWLINE def to_dict(self, pfile, time, deleted_only=False):NEWLINE """NEWLINE Convert all Particle data from one time step to a python dictionary.NEWLINE :param pfile: ParticleFile object requesting the conversionNEWLINE :param time: Time at which to write ParticleSetNEWLINE :param deleted_only: Flag to write only the deleted ParticlesNEWLINE returns two dictionaries: one for all variables to be written each outputdt,NEWLINE and one for all variables to be written onceNEWLINE """NEWLINE return self._collection.toDictionary(pfile=pfile, time=time,NEWLINE deleted_only=deleted_only)NEWLINENEWLINE @propertyNEWLINE def size(self):NEWLINE # ==== to change at some point - len and size are different things ==== #NEWLINE return len(self._collection)NEWLINENEWLINE def __repr__(self):NEWLINE return "\n".join([str(p) for p in self])NEWLINENEWLINE def __len__(self):NEWLINE return len(self._collection)NEWLINENEWLINE def __sizeof__(self):NEWLINE return sys.getsizeof(self._collection)NEWLINENEWLINE def __iadd__(self, particles):NEWLINE """Add particles to the ParticleSet. Note that this is anNEWLINE incremental add, the particles will be added to the ParticleSetNEWLINE on which this function is called.NEWLINENEWLINE :param particles: Another ParticleSet containing particles to addNEWLINE to this one.NEWLINE :return: The current ParticleSetNEWLINE """NEWLINE self.add(particles)NEWLINE return selfNEWLINENEWLINE def add(self, particles):NEWLINE """Add particles to the ParticleSet. Note that this is anNEWLINE incremental add, the particles will be added to the ParticleSetNEWLINE on which this function is called.NEWLINENEWLINE :param particles: Another ParticleSet containing particles to addNEWLINE to this one.NEWLINE :return: The current ParticleSetNEWLINE """NEWLINE if isinstance(particles, BaseParticleSet):NEWLINE particles = particles.collectionNEWLINE self._collection += particlesNEWLINE return selfNEWLINENEWLINE def remove_indices(self, indices):NEWLINE """Method to remove particles from the ParticleSet, based on their `indices`"""NEWLINE if type(indices) in [int, np.int32, np.intp]:NEWLINE self._collection.remove_single_by_index(indices)NEWLINE else:NEWLINE self._collection.remove_multi_by_indices(indices)NEWLINENEWLINE def remove_booleanvector(self, indices):NEWLINE """Method to remove particles from the ParticleSet, based on an array of booleans"""NEWLINE self.remove_indices(np.where(indices)[0])NEWLINENEWLINE def show(self, with_particles=True, show_time=None, field=None, domain=None, projection=None,NEWLINE land=True, vmin=None, vmax=None, savefile=None, animation=False, **kwargs):NEWLINE """Method to 'show' a Parcels ParticleSetNEWLINENEWLINE :param with_particles: Boolean whether to show particlesNEWLINE :param show_time: Time at which to show the ParticleSetNEWLINE :param field: Field to plot under particles (either None, a Field object, or 'vector')NEWLINE :param domain: dictionary (with keys 'N', 'S', 'E', 'W') defining domain to showNEWLINE :param projection: type of cartopy projection to use (default PlateCarree)NEWLINE :param land: Boolean whether to show land. This is ignored for flat meshesNEWLINE :param vmin: minimum colour scale (only in single-plot mode)NEWLINE :param vmax: maximum colour scale (only in single-plot mode)NEWLINE :param savefile: Name of a file to save the plot toNEWLINE :param animation: Boolean whether result is a single plot, or an animationNEWLINE """NEWLINE from parcels.plotting import plotparticlesNEWLINE plotparticles(particles=self, with_particles=with_particles, show_time=show_time, field=field, domain=domain,NEWLINE projection=projection, land=land, vmin=vmin, vmax=vmax, savefile=savefile, animation=animation, **kwargs)NEWLINENEWLINE def density(self, field_name=None, particle_val=None, relative=False, area_scale=False):NEWLINE """Method to calculate the density of particles in a ParticleSet from their locations,NEWLINE through a 2D histogram.NEWLINENEWLINE :param field: Optional :mod:`parcels.field.Field` object to calculate the histogramNEWLINE on. Default is `fieldset.U`NEWLINE :param particle_val: Optional numpy-array of values to weigh each particle with,NEWLINE or string name of particle variable to use weigh particles with.NEWLINE Default is None, resulting in a value of 1 for each particleNEWLINE :param relative: Boolean to control whether the density is scaled by the totalNEWLINE weight of all particles. Default is FalseNEWLINE :param area_scale: Boolean to control whether the density is scaled by the areaNEWLINE (in m^2) of each grid cell. Default is FalseNEWLINE """NEWLINENEWLINE field_name = field_name if field_name else "U"NEWLINE field = getattr(self.fieldset, field_name)NEWLINENEWLINE f_str = """NEWLINEdef search_kernel(particle, fieldset, time):NEWLINE x = fieldset.{}[time, particle.depth, particle.lat, particle.lon]NEWLINE """.format(field_name)NEWLINENEWLINE k = Kernel(NEWLINE self.fieldset,NEWLINE self._collection.ptype,NEWLINE funcname="search_kernel",NEWLINE funcvars=["particle", "fieldset", "time", "x"],NEWLINE funccode=f_str,NEWLINE )NEWLINE self.execute(pyfunc=k, runtime=0)NEWLINENEWLINE if isinstance(particle_val, str):NEWLINE particle_val = self._collection._data[particle_val]NEWLINE else:NEWLINE particle_val = particle_val if particle_val else np.ones(self.size)NEWLINE density = np.zeros((field.grid.lat.size, field.grid.lon.size), dtype=np.float32)NEWLINENEWLINE for i, p in enumerate(self):NEWLINE try: # breaks if either p.xi, p.yi, p.zi, p.ti do not exist (in scipy) or field not in fieldsetNEWLINE if p.ti[field.igrid] < 0: # xi, yi, zi, ti, not initialisedNEWLINE raise('error')NEWLINE xi = p.xi[field.igrid]NEWLINE yi = p.yi[field.igrid]NEWLINE except:NEWLINE _, _, _, xi, yi, _ = field.search_indices(p.lon, p.lat, p.depth, 0, 0, search2D=True)NEWLINE density[yi, xi] += particle_val[i]NEWLINENEWLINE if relative:NEWLINE density /= np.sum(particle_val)NEWLINENEWLINE if area_scale:NEWLINE density /= field.cell_areas()NEWLINENEWLINE return densityNEWLINENEWLINE def Kernel(self, pyfunc, c_include="", delete_cfiles=True):NEWLINE """Wrapper method to convert a `pyfunc` into a :class:`parcels.kernel.Kernel` objectNEWLINE based on `fieldset` and `ptype` of the ParticleSetNEWLINENEWLINE :param delete_cfiles: Boolean whether to delete the C-files after compilation in JIT mode (default is True)NEWLINE """NEWLINE return Kernel(self.fieldset, self.collection.ptype, pyfunc=pyfunc, c_include=c_include,NEWLINE delete_cfiles=delete_cfiles)NEWLINENEWLINE def ParticleFile(self, *args, **kwargs):NEWLINE """Wrapper method to initialise a :class:`parcels.particlefile.ParticleFile`NEWLINE object from the ParticleSet"""NEWLINE return ParticleFile(*args, particleset=self, **kwargs)NEWLINENEWLINE def set_variable_write_status(self, var, write_status):NEWLINE """NEWLINE Method to set the write status of a VariableNEWLINE :param var: Name of the variable (string)NEWLINE :param write_status: Write status of the variable (True, False orNEWLINE 'once')NEWLINE """NEWLINE self._collection.set_variable_write_status(var, write_status)NEWLINENEWLINENEWLINE# ParticleSet is an alias for ParticleSetSOA, i.e. the defaultNEWLINE# implementation for storing particles is the Structure of ArraysNEWLINE# approach.NEWLINEParticleSet = ParticleSetSOANEWLINE import osNEWLINEimport sysNEWLINEimport pytestNEWLINEfrom fastapi.testclient import TestClientNEWLINEfrom typer.testing import CliRunnerNEWLINEfrom sqlalchemy.exc import IntegrityErrorNEWLINENEWLINE# This next line ensures tests uses its own database and settings environmentNEWLINEos.environ["FORCE_ENV_FOR_DYNACONF"] = "testing" # noqaNEWLINE# WARNING: Ensure imports from `fastapi_sqlmodel_demo` comes after this lineNEWLINEfrom fastapi_sqlmodel_demo import app, settings, db # noqaNEWLINEfrom fastapi_sqlmodel_demo.cli import create_user, cli # noqaNEWLINENEWLINENEWLINE# each test runs on cwd to its temp dirNEWLINE@pytest.fixture(autouse=True)NEWLINEdef go_to_tmpdir(request):NEWLINE # Get the fixture dynamically by its name.NEWLINE tmpdir = request.getfixturevalue("tmpdir")NEWLINE # ensure local test created packages can be importedNEWLINE sys.path.insert(0, str(tmpdir))NEWLINE # Chdir only for the duration of the test.NEWLINE with tmpdir.as_cwd():NEWLINE yieldNEWLINENEWLINENEWLINE@pytest.fixture(scope="function", name="app")NEWLINEdef _app():NEWLINE return appNEWLINENEWLINENEWLINE@pytest.fixture(scope="function", name="cli")NEWLINEdef _cli():NEWLINE return cliNEWLINENEWLINENEWLINE@pytest.fixture(scope="function", name="settings")NEWLINEdef _settings():NEWLINE return settingsNEWLINENEWLINENEWLINE@pytest.fixture(scope="function")NEWLINEdef api_client():NEWLINE return TestClient(app)NEWLINENEWLINENEWLINE@pytest.fixture(scope="function")NEWLINEdef api_client_authenticated():NEWLINENEWLINE try:NEWLINE create_user("admin", "admin", superuser=True)NEWLINE except IntegrityError:NEWLINE passNEWLINENEWLINE client = TestClient(app)NEWLINE token = client.post(NEWLINE "/token",NEWLINE data={"username": "admin", "password": "admin"},NEWLINE headers={"Content-Type": "application/x-www-form-urlencoded"},NEWLINE ).json()["access_token"]NEWLINE client.headers["Authorization"] = f"Bearer {token}"NEWLINE return clientNEWLINENEWLINENEWLINE@pytest.fixture(scope="function")NEWLINEdef cli_client():NEWLINE return CliRunner()NEWLINENEWLINENEWLINEdef remove_db():NEWLINE # Remove the database fileNEWLINE try:NEWLINE os.remove("testing.db")NEWLINE except FileNotFoundError:NEWLINE passNEWLINENEWLINENEWLINE@pytest.fixture(scope="session", autouse=True)NEWLINEdef initialize_db(request):NEWLINE db.create_db_and_tables(db.engine)NEWLINE request.addfinalizer(remove_db)NEWLINE # Copyright: 2019, NLnet Labs and the Internet.nl contributorsNEWLINE# SPDX-License-Identifier: Apache-2.0NEWLINEfrom datetime import timedeltaNEWLINEimport randomNEWLINEfrom timeit import default_timer as timerNEWLINENEWLINEfrom internetnl.celery import appNEWLINEfrom celery.utils.log import get_task_loggerNEWLINEfrom django.conf import settingsNEWLINEfrom django.core.cache import cacheNEWLINEfrom django.utils import timezoneNEWLINEfrom pyrabbit import ClientNEWLINEfrom pyrabbit.http import HTTPError, NetworkErrorNEWLINEfrom pyrabbit.api import APIError, PermissionErrorNEWLINENEWLINEfrom . import utilNEWLINEfrom .. import batch_shared_task, redis_idNEWLINEfrom ..probes import batch_webprobes, batch_mailprobesNEWLINEfrom ..tasks.dnssec import batch_web_registered as dnssec_web_tasksetNEWLINEfrom ..tasks.dnssec import batch_mail_registered as dnssec_mail_tasksetNEWLINEfrom ..tasks.ipv6 import batch_web_registered as ipv6_web_tasksetNEWLINEfrom ..tasks.ipv6 import batch_mail_registered as ipv6_mail_tasksetNEWLINEfrom ..tasks.mail import batch_mail_registered as auth_mail_tasksetNEWLINEfrom ..tasks.tls import batch_web_registered as tls_web_tasksetNEWLINEfrom ..tasks.tls import batch_mail_registered as tls_mail_tasksetNEWLINEfrom ..tasks.appsecpriv import batch_web_registered as appsecpriv_web_tasksetNEWLINEfrom ..tasks import dispatcherNEWLINEfrom ..models import BatchRequest, BatchRequestStatus, BatchDomainNEWLINEfrom ..models import BatchDomainStatus, BatchTestStatusNEWLINEfrom ..models import BatchWebTestNEWLINEfrom ..models import WebTestTls, WebTestAppsecprivNEWLINEfrom ..models import DomainTestReport, MailTestReport, MailTestTlsNEWLINEfrom ..models import MailTestDnssec, DomainTestDnssecNEWLINENEWLINElogger = get_task_logger(__name__)NEWLINENEWLINEBATCH_WEBTEST = {NEWLINE 'subtests': {NEWLINE 'ipv6': ipv6_web_taskset,NEWLINE 'dnssec': dnssec_web_taskset,NEWLINE 'tls': tls_web_taskset,NEWLINE 'appsecpriv': appsecpriv_web_taskset,NEWLINE },NEWLINE 'report': {NEWLINE 'name': 'domaintestreport'NEWLINE }NEWLINE}NEWLINEBATCH_MAILTEST = {NEWLINE 'subtests': {NEWLINE 'ipv6': ipv6_mail_taskset,NEWLINE 'dnssec': dnssec_mail_taskset,NEWLINE 'auth': auth_mail_taskset,NEWLINE 'tls': tls_mail_taskset,NEWLINE },NEWLINE 'report': {NEWLINE 'name': 'mailtestreport'NEWLINE }NEWLINE}NEWLINENEWLINENEWLINEclass Rabbit():NEWLINE """NEWLINE Wrapper class for the pyrabbit client.NEWLINENEWLINE """NEWLINENEWLINE def __init__(self, rabbit, user, password):NEWLINE self._rabbit = rabbitNEWLINE self._user = userNEWLINE self._pass = passwordNEWLINENEWLINE def _get_client(self):NEWLINE """NEWLINE Get a client connection to rabbitmq.NEWLINENEWLINE """NEWLINE try:NEWLINE self._cl = Client(self._rabbit, self._user, self._pass)NEWLINE return TrueNEWLINE except (HTTPError, NetworkError, APIError, PermissionError):NEWLINE return NoneNEWLINENEWLINE def get_queue_depth(self, host, queue):NEWLINE """NEWLINE Get the size of a queue on a rabbitmq virtual host.NEWLINE In case of a random exception, retry before failing.NEWLINENEWLINE """NEWLINE tries = 5NEWLINE while tries > 0:NEWLINE try:NEWLINE return self._cl.get_queue_depth(host, queue)NEWLINE except (AttributeError, HTTPError, NetworkError, APIError,NEWLINE PermissionError) as e:NEWLINE self._get_client()NEWLINE tries -= 1NEWLINE if tries <= 0:NEWLINE raise eNEWLINENEWLINENEWLINEdef is_queue_loaded(client):NEWLINE """NEWLINE Check if we consider the monitor queue loaded.NEWLINENEWLINE """NEWLINE current_load = client.get_queue_depth(NEWLINE settings.RABBIT_VHOST, settings.RABBIT_MON_QUEUE)NEWLINE if current_load >= settings.RABBIT_MON_THRESHOLD:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINEdef get_live_requests():NEWLINE """NEWLINE Return a dictionary with active users as keys and their earliestNEWLINE live batch request as value.NEWLINENEWLINE """NEWLINE live_requests = dict()NEWLINE batch_requests = BatchRequest.objects.filter(NEWLINE status=BatchRequestStatus.live).order_by('submit_date')NEWLINE for request in batch_requests:NEWLINE if not live_requests.get(request.user):NEWLINE live_requests[request.user] = requestNEWLINE return live_requestsNEWLINENEWLINENEWLINEdef get_user_and_request(live_requests):NEWLINE """NEWLINE Pick a user and his request from the available live_requests.NEWLINE Users are fairly chosen regardless of the number of submitted tests.NEWLINENEWLINE """NEWLINE if not live_requests:NEWLINE return None, NoneNEWLINENEWLINE user = random.choice(list(live_requests.keys()))NEWLINE batch_request = live_requests[user]NEWLINE return user, batch_requestNEWLINENEWLINENEWLINEdef pick_domain(batch_request):NEWLINE """NEWLINE Pick a domain to test.NEWLINE Selects the first available domain.NEWLINENEWLINE """NEWLINE try:NEWLINE return BatchDomain.objects.filter(NEWLINE status=BatchDomainStatus.waiting, batch_request=batch_request)[:1].get() #.first()NEWLINE except BatchDomain.DoesNotExist:NEWLINE return NoneNEWLINENEWLINENEWLINEdef check_for_result_or_start_test(batch_domain, batch_test, subtest, taskset):NEWLINE """NEWLINE Link the result if already available or start a test.NEWLINENEWLINE """NEWLINE started_test = FalseNEWLINE subtest_model = batch_test._meta.get_field(subtest).remote_field.modelNEWLINE result = find_result(batch_domain, subtest_model)NEWLINE if result:NEWLINE save_result(batch_test, subtest, result)NEWLINE else:NEWLINE start_test(batch_domain, batch_test, subtest, taskset)NEWLINE started_test = TrueNEWLINE return started_testNEWLINENEWLINENEWLINEdef find_result(batch_domain, model):NEWLINE """NEWLINE Check if we already have results for the domain. Viable results areNEWLINE ones recorded after the batch submission.NEWLINENEWLINE """NEWLINE submit_date = batch_domain.batch_request.submit_dateNEWLINE try:NEWLINE if model is WebTestTls:NEWLINE result = model.objects.filter(NEWLINE domain=batch_domain.domain,NEWLINE webtestset__timestamp__gte=submit_date).latest('id')NEWLINE elif model is MailTestTls:NEWLINE result = model.objects.filter(NEWLINE domain=batch_domain.domain,NEWLINE testset__timestamp__gte=submit_date).latest('id')NEWLINE elif model is MailTestDnssec:NEWLINE result = model.objects.filter(NEWLINE domain=batch_domain.domain,NEWLINE testset__timestamp__gte=submit_date).latest('id')NEWLINE elif model is WebTestAppsecpriv:NEWLINE result = model.objects.filter(NEWLINE domain=batch_domain.domain,NEWLINE webtestset__timestamp__gte=submit_date).latest('id')NEWLINE elif model is DomainTestDnssec:NEWLINE result = model.objects.filter(NEWLINE domain=batch_domain.domain,NEWLINE maildomain_id=None,NEWLINE timestamp__gte=submit_date).latest('id')NEWLINE else:NEWLINE result = model.objects.filter(NEWLINE domain=batch_domain.domain,NEWLINE timestamp__gte=submit_date).latest('id')NEWLINE except model.DoesNotExist:NEWLINE result = NoneNEWLINE return resultNEWLINENEWLINENEWLINEdef save_result(batch_test, subtest, result):NEWLINE """NEWLINE Link results and save model.NEWLINENEWLINE """NEWLINE setattr(batch_test, subtest, result)NEWLINE setattr(batch_test, '{}_status'.format(subtest), BatchTestStatus.done)NEWLINE batch_test.save(update_fields=[NEWLINE '{}_id'.format(subtest),NEWLINE '{}_status'.format(subtest)])NEWLINENEWLINENEWLINEdef start_test(batch_domain, batch_test, subtest, taskset):NEWLINE """NEWLINE Submit test and change status to running.NEWLINENEWLINE """NEWLINE submit_test(batch_domain, subtest, taskset)NEWLINE setattr(batch_test, '{}_status'.format(subtest), BatchTestStatus.running)NEWLINE batch_test.save(update_fields=['{}_status'.format(subtest)])NEWLINENEWLINENEWLINEdef submit_test(batch_domain, test, checks_registry):NEWLINE """NEWLINE Submit the test in celery.NEWLINENEWLINE """NEWLINE url = batch_domain.domainNEWLINE task_set = dispatcher.submit_task_set(NEWLINE url, checks_registry, error_cb=error_callback)NEWLINE # Need to cache it in redis, then the callback can look it up basedNEWLINE # on the task id.NEWLINE cache_id = redis_id.running_batch_test.id.format(task_set.id)NEWLINE cache_ttl = redis_id.running_batch_test.ttlNEWLINE cache.set(cache_id, (batch_domain.id, test), cache_ttl)NEWLINENEWLINE return task_setNEWLINENEWLINENEWLINEdef check_any_subtest_for_status(batch_test, status):NEWLINE """NEWLINE Check if any of the subtests has a given status.NEWLINENEWLINE """NEWLINE if isinstance(batch_test, BatchWebTest):NEWLINE subtests = BATCH_WEBTEST['subtests']NEWLINE else:NEWLINE subtests = BATCH_MAILTEST['subtests']NEWLINENEWLINE for subtest in subtests:NEWLINE if getattr(batch_test, "{}_status".format(subtest)) == status:NEWLINE return TrueNEWLINENEWLINE return FalseNEWLINENEWLINENEWLINEdef find_or_create_report(batch_domain):NEWLINE report = get_common_report(batch_domain)NEWLINE if report:NEWLINE batch_test = batch_domain.get_batch_test()NEWLINE batch_test.report = reportNEWLINE batch_test.save(update_fields=['report'])NEWLINE else:NEWLINE create_report(batch_domain)NEWLINENEWLINENEWLINEdef get_common_report(batch_domain):NEWLINE """NEWLINE Try to find the most recent common report for all subtests.NEWLINE If no such report exists or at least one of the subtests is not yetNEWLINE part of a report return nothing.NEWLINENEWLINE """NEWLINE batch_test = batch_domain.get_batch_test()NEWLINE if isinstance(batch_test, BatchWebTest):NEWLINE subtests = BATCH_WEBTEST['subtests']NEWLINE report_details = BATCH_WEBTEST['report']NEWLINE else:NEWLINE subtests = BATCH_MAILTEST['subtests']NEWLINE report_details = BATCH_MAILTEST['report']NEWLINENEWLINE report_ids = {}NEWLINE for subtest in subtests:NEWLINE report_ids[subtest] = set()NEWLINE # example: batch_test.ipv6.mailtestreport_set.all()NEWLINE for report in getattr(NEWLINE getattr(batch_test, subtest),NEWLINE '{}_set'.format(report_details['name'])).all():NEWLINE report_ids[subtest].add(report.id)NEWLINENEWLINE if not report_ids[subtest]:NEWLINE return NoneNEWLINENEWLINE for i, subtest in enumerate(report_ids):NEWLINE if i == 0:NEWLINE common_report_ids = report_ids[subtest]NEWLINE else:NEWLINE common_report_ids.intersection_update(report_ids[subtest])NEWLINENEWLINE if common_report_ids:NEWLINE common_report_id = max(common_report_ids)NEWLINE report_model = batch_test._meta.get_field('report').remote_field.modelNEWLINE try:NEWLINE return report_model.objects.get(id=common_report_id)NEWLINE except report_model.DoesNotExist:NEWLINE passNEWLINE return NoneNEWLINENEWLINENEWLINEdef create_report(batch_domain):NEWLINE """NEWLINE Create the report for this domain.NEWLINE Similar to when a user is redirected to the results page.NEWLINENEWLINE """NEWLINE domain = batch_domain.domainNEWLINE if batch_domain.webtest:NEWLINE batch_test = batch_domain.webtestNEWLINE report = DomainTestReport(NEWLINE domain=domain,NEWLINE ipv6=batch_test.ipv6,NEWLINE dnssec=batch_test.dnssec,NEWLINE tls=batch_test.tls,NEWLINE appsecpriv=batch_test.appsecpriv)NEWLINE probe_reports = batch_webprobes.get_probe_reports(report)NEWLINE score = batch_webprobes.count_probe_reports_score(probe_reports)NEWLINE else:NEWLINE batch_test = batch_domain.mailtestNEWLINE report = MailTestReport(NEWLINE domain=domain,NEWLINE ipv6=batch_test.ipv6,NEWLINE dnssec=batch_test.dnssec,NEWLINE auth=batch_test.auth,NEWLINE tls=batch_test.tls)NEWLINE probe_reports = batch_mailprobes.get_probe_reports(report)NEWLINE score = batch_mailprobes.count_probe_reports_score(probe_reports)NEWLINENEWLINE report.registrar = "-Not available in batch-"NEWLINE report.score = scoreNEWLINE report.save()NEWLINE batch_test.report = reportNEWLINE batch_test.save()NEWLINENEWLINENEWLINEdef update_domain_status(batch_domain):NEWLINE """NEWLINE Check the status of the individual tests and update the domain'sNEWLINE entry status.NEWLINENEWLINE """NEWLINE if batch_domain.status == BatchDomainStatus.cancelled:NEWLINE returnNEWLINENEWLINE batch_test = batch_domain.get_batch_test()NEWLINENEWLINE if check_any_subtest_for_status(batch_test, BatchTestStatus.error):NEWLINE batch_domain.status = BatchDomainStatus.errorNEWLINE elif check_any_subtest_for_status(batch_test, BatchTestStatus.waiting):NEWLINE batch_domain.status = BatchDomainStatus.waitingNEWLINE elif check_any_subtest_for_status(batch_test, BatchTestStatus.running):NEWLINE batch_domain.status = BatchDomainStatus.runningNEWLINE else:NEWLINE batch_domain.status = BatchDomainStatus.doneNEWLINE find_or_create_report(batch_domain)NEWLINE batch_domain.status_changed = timezone.now()NEWLINE batch_domain.save(update_fields=['status_changed', 'status'])NEWLINENEWLINENEWLINEdef update_batch_status(batch_request):NEWLINE """NEWLINE Check the status of the submitted domains and update the batchNEWLINE request's status if necessary.NEWLINENEWLINE """NEWLINE if batch_request.status in (BatchRequestStatus.cancelled,NEWLINE BatchRequestStatus.done,NEWLINE BatchRequestStatus.registering,NEWLINE BatchRequestStatus.error):NEWLINE returnNEWLINENEWLINE waiting = batch_request.domains.filter(NEWLINE status=BatchDomainStatus.waiting).exists()NEWLINE running = batch_request.domains.filter(NEWLINE status=BatchDomainStatus.running).exists()NEWLINE if not waiting:NEWLINE if running:NEWLINE batch_request.status = BatchRequestStatus.runningNEWLINE else:NEWLINE batch_request.status = BatchRequestStatus.doneNEWLINE batch_request.finished_date = timezone.now()NEWLINE else:NEWLINE batch_request.status = BatchRequestStatus.liveNEWLINE batch_request.save(update_fields=['status', 'finished_date'])NEWLINENEWLINENEWLINEdef batch_callback_hook(result, task_id):NEWLINE """NEWLINE Link the result and change the status of the running test.NEWLINENEWLINE """NEWLINE if not result:NEWLINE logger.error("Post callback, no result!")NEWLINE returnNEWLINENEWLINE cache_id = redis_id.running_batch_test.id.format(task_id)NEWLINE cached = cache.get(cache_id)NEWLINE if not cached:NEWLINE logger.error(NEWLINE "Post callback, could not find task id '{}'"NEWLINE "".format(task_id))NEWLINE returnNEWLINENEWLINE batch_domain_id, subtest = cachedNEWLINE batch_domain = BatchDomain.objects.get(id=batch_domain_id)NEWLINE if batch_domain.status == BatchDomainStatus.cancelled:NEWLINE returnNEWLINENEWLINE batch_test = batch_domain.get_batch_test()NEWLINENEWLINE save_result(batch_test, subtest, result)NEWLINE cache.delete(cache_id)NEWLINE update_domain_status(batch_domain)NEWLINENEWLINENEWLINE@batch_shared_task()NEWLINEdef error_callback(request, exc, traceback):NEWLINE """NEWLINE Increase error count and change status, if an error occurs.NEWLINENEWLINE .. note:: Celery only calls this when there is an exception in the chordNEWLINE callback. This is a bug in celery. To compensate we periodicallyNEWLINE check for tests stuck in the running state withNEWLINE find_stalled_tests_and_update_db().NEWLINENEWLINE """NEWLINE logger.error("Task {0!r} raised error: {1!r}".format(request.id, exc))NEWLINE cache_id = redis_id.running_batch_test.id.format(request.id)NEWLINE cached = cache.get(cache_id)NEWLINE if not cached:NEWLINE logger.error(NEWLINE "Error callback, could not find task id '{}'"NEWLINE "".format(request.id))NEWLINE returnNEWLINENEWLINE batch_domain_id, test = cachedNEWLINE batch_domain = BatchDomain.objects.get(id=batch_domain_id)NEWLINE if batch_domain.status == BatchDomainStatus.cancelled:NEWLINE returnNEWLINENEWLINE batch_test = batch_domain.get_batch_test()NEWLINE record_subtest_error(batch_test, test)NEWLINE update_domain_status(batch_domain)NEWLINE cache.delete(cache_id)NEWLINENEWLINENEWLINEdef record_subtest_error(batch_test, subtest):NEWLINE """NEWLINE Increase and return the error count for the given subtest. Also changeNEWLINE the status if appropriate.NEWLINENEWLINE """NEWLINE error_count = getattr(batch_test, '{}_errors'.format(subtest))NEWLINE status = getattr(batch_test, '{}_status'.format(subtest))NEWLINE error_count += 1NEWLINE if status != BatchTestStatus.cancelled:NEWLINE if error_count > 2:NEWLINE status = BatchTestStatus.errorNEWLINE else:NEWLINE status = BatchTestStatus.waitingNEWLINE setattr(batch_test, '{}_status'.format(subtest), status)NEWLINE setattr(batch_test, '{}_errors'.format(subtest), error_count)NEWLINE batch_test.save(update_fields=[NEWLINE '{}_status'.format(subtest),NEWLINE '{}_errors'.format(subtest)])NEWLINE return error_countNEWLINENEWLINENEWLINEdef find_stalled_tests_and_update_db():NEWLINE """NEWLINE Find tests that have been in the running state for more than a givenNEWLINE threshold and update their status.NEWLINENEWLINE """NEWLINE running_domains = BatchDomain.objects.filter(NEWLINE status=BatchDomainStatus.running)NEWLINE now = timezone.now()NEWLINE for batch_domain in running_domains:NEWLINE timediff = (now - batch_domain.status_changed).total_seconds()NEWLINE if timediff >= settings.BATCH_MAX_RUNNING_TIME:NEWLINE if batch_domain.webtest:NEWLINE batch_test = batch_domain.webtestNEWLINE subtests = BATCH_WEBTEST['subtests']NEWLINE else:NEWLINE batch_test = batch_domain.mailtestNEWLINE subtests = BATCH_MAILTEST['subtests']NEWLINENEWLINE for subtest in subtests:NEWLINE status = getattr(batch_test, '{}_status'.format(subtest))NEWLINE if status == BatchTestStatus.running:NEWLINE errors = record_subtest_error(batch_test, subtest)NEWLINE logger.info(NEWLINE "{} errors for {}({})"NEWLINE "".format(errors, batch_domain.domain, subtest))NEWLINE update_domain_status(batch_domain)NEWLINENEWLINENEWLINEdef update_batch_request_status():NEWLINE batch_requests = BatchRequest.objects.filter(NEWLINE status__in=(BatchRequestStatus.live, BatchRequestStatus.running))NEWLINE for batch_request in batch_requests:NEWLINE update_batch_status(batch_request)NEWLINENEWLINENEWLINEdef _run_scheduler():NEWLINE """NEWLINE Submit a fixed number of domains for testing if the queue is notNEWLINE considered loaded.NEWLINENEWLINE """NEWLINE client = Rabbit(NEWLINE settings.RABBIT, settings.RABBIT_USER, settings.RABBIT_PASS)NEWLINE domains_to_test = settings.BATCH_SCHEDULER_DOMAINSNEWLINENEWLINE start_time = timer()NEWLINE find_stalled_tests_and_update_db()NEWLINE logger.info("Find stalled duration: {}".format(timer() - start_time))NEWLINENEWLINE start_time = timer()NEWLINE update_batch_request_status()NEWLINE logger.info("Update status duration: {}".format(timer() - start_time))NEWLINENEWLINE submitted = 0NEWLINE found = 0NEWLINE if not is_queue_loaded(client):NEWLINE start_time = timer()NEWLINE live_requests = get_live_requests()NEWLINE while domains_to_test > 0:NEWLINE user, batch_request = get_user_and_request(live_requests)NEWLINE if not (user or batch_request):NEWLINE breakNEWLINENEWLINE batch_domain = pick_domain(batch_request)NEWLINE if not batch_domain:NEWLINE breakNEWLINENEWLINE subtests_started = 0NEWLINE batch_test = batch_domain.get_batch_test()NEWLINE if isinstance(batch_test, BatchWebTest):NEWLINE subtests = BATCH_WEBTEST['subtests']NEWLINE else:NEWLINE subtests = BATCH_MAILTEST['subtests']NEWLINENEWLINE for subtest in subtests:NEWLINE if (getattr(batch_test, '{}_status'.format(subtest))NEWLINE == BatchTestStatus.waiting):NEWLINE started_test = check_for_result_or_start_test(NEWLINE batch_domain, batch_test, subtest,NEWLINE subtests[subtest])NEWLINE if started_test:NEWLINE subtests_started += 1NEWLINENEWLINE if subtests_started > 0:NEWLINE submitted += 1NEWLINE domains_to_test -= 1NEWLINE else:NEWLINE found += 1NEWLINE update_domain_status(batch_domain)NEWLINE logger.info("Submission duration: {}".format(timer() - start_time))NEWLINENEWLINE submitted_domains = settings.BATCH_SCHEDULER_DOMAINS - domains_to_testNEWLINE submitted_domains = submittedNEWLINE found_domains = foundNEWLINE logger.info("Submitted {} domains".format(submitted_domains))NEWLINE logger.info("Found {} domains".format(found_domains))NEWLINENEWLINENEWLINE@batch_shared_taskNEWLINEdef run():NEWLINE """NEWLINE Run the scheduler every interval only if it is not running already.NEWLINENEWLINE """NEWLINE lock_id = redis_id.batch_scheduler_lock.idNEWLINE lock_ttl = redis_id.batch_scheduler_lock.ttlNEWLINE with util.memcache_lock(lock_id, lock_ttl) as acquired:NEWLINE if acquired:NEWLINE _run_scheduler()NEWLINE returnNEWLINE logger.info("Already running...")NEWLINE """NEWLINEThe script is for creating a new graphml including nodes and edges NEWLINEbased on the subset geopackage created by "sv_createSubsetData.py".NEWLINEThis can reduce the volume of graphml, which can reduce the usage of memory in pc and NEWLINEimprove performace.NEWLINENEWLINE"""NEWLINEimport osmnx as oxNEWLINEimport networkx as nxNEWLINEimport osNEWLINEimport pandas as pdNEWLINEimport geopandas as gpdNEWLINEimport timeNEWLINENEWLINENEWLINEdef creatSubGraph(graphPath, gpkg_path, graphOutput):NEWLINE print('read original grapml, and save nodes and edges to geopackage.')NEWLINE G = ox.load_graphml(graphPath)NEWLINE nodes, edges = ox.graph_to_gdfs(G)NEWLINE # nodes = nodes.astype(str)NEWLINE columns = edges.columns.tolist()NEWLINE columns.remove('geometry')NEWLINE edges[columns] = edges[columns].astype(str)NEWLINE nodes.to_file(gpkg_path, layer='nodes_original', driver='GPKG')NEWLINE edges.to_file(gpkg_path, layer='edges_original', driver='GPKG')NEWLINE # sp = gpd.read_file(gpkg_path, layer='urban_sample_points')NEWLINE # nodesIds = pd.concat([sp.n1, sp.n2])NEWLINE # node_drop = nodesIds.drop_duplicates()NEWLINE # nodes = node_drop.tolist()NEWLINE # nodes_int = list(map(int, nodes))NEWLINE print('select nodes within study region buffer.')NEWLINE region_buffer = gpd.read_file(gpkg_path,NEWLINE layer='urban_study_region_buffered')NEWLINE nodes_withinbuffer = gpd.sjoin(nodes,NEWLINE region_buffer,NEWLINE how='inner',NEWLINE op='within')NEWLINE nodes_withinbuffer = nodes_withinbuffer.drop_duplicates(subset='osmid')NEWLINE nodesIds = nodes_withinbuffer.osmid.tolist()NEWLINE nodes_int = list(map(int, nodesIds))NEWLINE print('create sub grapml.')NEWLINE G_sub = G.subgraph(nodes_int).copy()NEWLINE # print(G_sub.nodes)NEWLINE print('save sub nodes and edges to geopackage.')NEWLINE nodes_sub, edges_sub = ox.graph_to_gdfs(G_sub)NEWLINE # nodes_sub = nodes_sub.astype(str)NEWLINE cols = edges_sub.columns.tolist()NEWLINE cols.remove('geometry')NEWLINE edges_sub[cols] = edges_sub[cols].astype(str)NEWLINE nodes_sub.to_file(gpkg_path, layer='nodes_subset', driver='GPKG')NEWLINE edges_sub.to_file(gpkg_path, layer='edges_subset', driver='GPKG')NEWLINE del nodes, edgesNEWLINE del edges_sub, nodes_subNEWLINE ox.save_graphml(G_sub,NEWLINE filename=graphOutput,NEWLINE folder=os.path.join(dirname, 'data'))NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE startTime = time.time()NEWLINE print('begin to process')NEWLINE dirname = os.path.abspath('')NEWLINE graph_path = os.path.join(NEWLINE dirname,NEWLINE 'data/phoenix_us_2019_10000m_pedestrian_osm_20190902_proj.graphml')NEWLINE gpkg_path = os.path.join(dirname,NEWLINE 'data/phoenix_us_2019_subset.gpkg')NEWLINE graph_output = 'phoenix_us_2019_10000m_pedestrian_osm_20190902_proj_subset.graphml'NEWLINE creatSubGraph(graph_path, gpkg_path, graph_output)NEWLINE print("finished, time is {}".format(time.time() - startTime)) #!/usr/bin/env pythonNEWLINE#NEWLINE# ontoviz documentation build configuration file, created byNEWLINE# sphinx-quickstart on Fri Jun 9 13:47:02 2017.NEWLINE#NEWLINE# This file is execfile()d with the current directory set to itsNEWLINE# containing dir.NEWLINE#NEWLINE# Note that not all possible configuration values are present in thisNEWLINE# autogenerated file.NEWLINE#NEWLINE# All configuration values have a default; values that are commented outNEWLINE# serve to show the default.NEWLINENEWLINE# If extensions (or modules to document with autodoc) are in anotherNEWLINE# directory, add these directories to sys.path here. If the directory isNEWLINE# relative to the documentation root, use os.path.abspath to make itNEWLINE# absolute, like shown here.NEWLINE#NEWLINEimport sysNEWLINEfrom pathlib import PathNEWLINENEWLINEthis_dir = Path(__file__).resolve().parentNEWLINEroot_dir = (this_dir / '..').resolve()NEWLINEsys.path.insert(0, str(root_dir))NEWLINEsys.path.insert(0, str(this_dir))NEWLINENEWLINEimport ontovizNEWLINENEWLINE# -- General configuration ---------------------------------------------NEWLINENEWLINE# If your documentation needs a minimal Sphinx version, state it here.NEWLINE#NEWLINE# needs_sphinx = '1.0'NEWLINENEWLINE# Add any Sphinx extension module names here, as strings. They can beNEWLINE# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.NEWLINEextensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', "autoapi", "myst_nb"]NEWLINENEWLINE# Add any paths that contain templates here, relative to this directory.NEWLINEtemplates_path = ['_templates']NEWLINENEWLINE# The suffix(es) of source filenames.NEWLINE# You can specify multiple suffix as a list of string:NEWLINE#NEWLINE# source_suffix = ['.rst', '.md']NEWLINEsource_suffix = {NEWLINE '.rst': 'restructuredtext',NEWLINE '.ipynb': 'myst-nb',NEWLINE '.md': 'myst-nb',NEWLINE}NEWLINENEWLINE# The master toctree document.NEWLINEmaster_doc = 'index'NEWLINENEWLINE# General information about the project.NEWLINEproject = 'ontoviz'NEWLINEcopyright = "2021, René Fritze"NEWLINEauthor = "René Fritze"NEWLINENEWLINE# The version info for the project you're documenting, acts as replacementNEWLINE# for |version| and |release|, also used in various other places throughoutNEWLINE# the built documents.NEWLINE#NEWLINE# The short X.Y version.NEWLINEversion = ontoviz.__version__NEWLINE# The full version, including alpha/beta/rc tags.NEWLINErelease = ontoviz.__version__NEWLINENEWLINE# The language for content autogenerated by Sphinx. Refer to documentationNEWLINE# for a list of supported languages.NEWLINE#NEWLINE# This is also used if you do content translation via gettext catalogs.NEWLINE# Usually you set "language" from the command line for these cases.NEWLINElanguage = NoneNEWLINENEWLINE# List of patterns, relative to source directory, that match files andNEWLINE# directories to ignore when looking for source files.NEWLINE# This patterns also effect to html_static_path and html_extra_pathNEWLINEexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']NEWLINENEWLINE# The name of the Pygments (syntax highlighting) style to use.NEWLINEpygments_style = 'sphinx'NEWLINENEWLINE# If true, `todo` and `todoList` produce output, else they produce nothing.NEWLINEtodo_include_todos = TrueNEWLINENEWLINENEWLINE# -- Options for HTML output -------------------------------------------NEWLINENEWLINE# The theme to use for HTML and HTML Help pages. See the documentation forNEWLINE# a list of builtin themes.NEWLINE#NEWLINEhtml_theme = 'alabaster'NEWLINENEWLINE# Theme options are theme-specific and customize the look and feel of aNEWLINE# theme further. For a list of options available for each theme, see theNEWLINE# documentation.NEWLINE#NEWLINE# html_theme_options = {}NEWLINENEWLINE# Add any paths that contain custom static files (such as style sheets) here,NEWLINE# relative to this directory. They are copied after the builtin static files,NEWLINE# so a file named "default.css" will overwrite the builtin "default.css".NEWLINEhtml_static_path = ['_static']NEWLINENEWLINENEWLINE# -- Options for HTMLHelp output ---------------------------------------NEWLINENEWLINE# Output file base name for HTML help builder.NEWLINEhtmlhelp_basename = 'ontovizdoc'NEWLINENEWLINENEWLINE# -- Options for LaTeX output ------------------------------------------NEWLINENEWLINElatex_elements = {NEWLINE # The paper size ('letterpaper' or 'a4paper').NEWLINE #NEWLINE # 'papersize': 'letterpaper',NEWLINE # The font size ('10pt', '11pt' or '12pt').NEWLINE #NEWLINE # 'pointsize': '10pt',NEWLINE # Additional stuff for the LaTeX preamble.NEWLINE #NEWLINE # 'preamble': '',NEWLINE # Latex figure (float) alignmentNEWLINE #NEWLINE # 'figure_align': 'htbp',NEWLINE}NEWLINENEWLINE# Grouping the document tree into LaTeX files. List of tuplesNEWLINE# (source start file, target name, title, author, documentclassNEWLINE# [howto, manual, or own class]).NEWLINElatex_documents = [NEWLINE (master_doc, 'ontoviz.tex', 'ontoviz Documentation', 'René Fritze', 'manual'),NEWLINE]NEWLINENEWLINENEWLINE# -- Options for manual page output ------------------------------------NEWLINENEWLINE# One entry per manual page. List of tuplesNEWLINE# (source start file, name, description, authors, manual section).NEWLINEman_pages = [(master_doc, 'ontoviz', 'ontoviz Documentation', [author], 1)]NEWLINENEWLINENEWLINE# -- Options for Texinfo output ----------------------------------------NEWLINENEWLINE# Grouping the document tree into Texinfo files. List of tuplesNEWLINE# (source start file, target name, title, author,NEWLINE# dir menu entry, description, category)NEWLINEtexinfo_documents = [NEWLINE (NEWLINE master_doc,NEWLINE 'ontoviz',NEWLINE 'ontoviz Documentation',NEWLINE author,NEWLINE 'ontoviz',NEWLINE 'One line description of project.',NEWLINE 'Miscellaneous',NEWLINE ),NEWLINE]NEWLINENEWLINEautoapi_python_use_implicit_namespaces = TrueNEWLINEautoapi_dirs = [root_dir / 'ontoviz']NEWLINEautoapi_type = 'python'NEWLINE# allows incremental buildNEWLINEautoapi_keep_files = TrueNEWLINEautoapi_template_dir = this_dir / '_templates' / 'autoapi'NEWLINENEWLINEnb_execution_mode = "cache"NEWLINE import asyncioNEWLINENEWLINEfrom unittest.mock import patch, MagicMockNEWLINENEWLINEfrom icap import ICAPRequest, HeadersDict, handlerNEWLINEfrom icap.session import make_session_id, should_finalize_session, get_session, SessionStorageNEWLINEfrom icap.criteria import _HANDLERSNEWLINENEWLINENEWLINEdef test_make_session_id():NEWLINE req = ICAPRequest()NEWLINE with patch('icap.session.uuid.uuid4') as mock_uuid:NEWLINE mock_uuid.return_value.hex = 'cool hash'NEWLINE assert make_session_id(req) == 'cool hash'NEWLINENEWLINE req.headers['X-Session-ID'] = 'cool session id'NEWLINENEWLINE assert make_session_id(req) == 'cool session id'NEWLINENEWLINENEWLINEdef test_SessionStorage():NEWLINE t = SessionStorage.get('foo', MagicMock())NEWLINENEWLINE assert t['id'] == 'foo'NEWLINE assert 'foo' in SessionStorage.sessionsNEWLINE assert SessionStorage.get('foo', MagicMock()) is tNEWLINENEWLINE assert SessionStorage.finalize('foo')NEWLINE assert not SessionStorage.finalize('foo')NEWLINENEWLINE assert 'foo' not in SessionStorage.sessionsNEWLINE assert SessionStorage.get('foo', MagicMock()) is not tNEWLINENEWLINENEWLINEdef test_get_session():NEWLINE request = MagicMock(headers=HeadersDict())NEWLINE request.http.request_line.uri = 'foo'NEWLINE request.headers['X-Session-ID'] = 'bar'NEWLINENEWLINE session = asyncio.get_event_loop().run_until_complete(get_session(request))NEWLINENEWLINE assert session['url'] == 'foo'NEWLINE assert session['id'] == 'bar'NEWLINENEWLINENEWLINEdef test_should_finalize_session():NEWLINE _HANDLERS.clear()NEWLINENEWLINE assert not should_finalize_session(MagicMock(is_options=True))NEWLINE assert should_finalize_session(MagicMock(is_options=False, is_respmod=True))NEWLINE assert should_finalize_session(MagicMock(is_options=False, is_respmod=False, headers=HeadersDict()))NEWLINENEWLINE request = MagicMock(is_options=False, is_respmod=False, headers=HeadersDict())NEWLINE request.headers['X-Session-ID'] = 'foo'NEWLINENEWLINE @handler()NEWLINE def respmod(request):NEWLINE passNEWLINENEWLINE @handler(name='foo')NEWLINE def respmod(request):NEWLINE passNEWLINENEWLINE for p in ['/reqmod', '/reqmod/', '/foo/reqmod', '/foo/reqmod/']:NEWLINE request.request_line.uri.path = pNEWLINE assert not should_finalize_session(request)NEWLINENEWLINE for p in ['/bar/reqmod', '/bar/reqmod/']:NEWLINE request.request_line.uri.path = pNEWLINE assert should_finalize_session(request)NEWLINE # Licensed to the Apache Software Foundation (ASF) under oneNEWLINE# or more contributor license agreements. See the NOTICE fileNEWLINE# distributed with this work for additional informationNEWLINE# regarding copyright ownership. The ASF licenses this fileNEWLINE# to you under the Apache License, Version 2.0 (theNEWLINE# "License"); you may not use this file except in complianceNEWLINE# with the License. You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing,NEWLINE# software distributed under the License is distributed on anNEWLINE# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANYNEWLINE# KIND, either express or implied. See the License for theNEWLINE# specific language governing permissions and limitationsNEWLINE# under the License.NEWLINE"""Test code for 3d convolution with winograd."""NEWLINENEWLINEimport numpy as npNEWLINEimport tvmNEWLINEfrom tvm import teNEWLINEfrom tvm import autotvmNEWLINEfrom tvm import topiNEWLINEimport tvm.testingNEWLINEimport tvm.topi.testingNEWLINEfrom tvm.contrib.pickle_memoize import memoizeNEWLINEfrom tvm.topi.nn.utils import get_pad_tuple3dNEWLINEfrom tvm.topi.utils import get_const_tupleNEWLINENEWLINENEWLINE_conv3d_ncdhw_implement = {NEWLINE "gpu": (topi.cuda.conv3d_ncdhw_winograd, topi.cuda.schedule_conv3d_ncdhw_winograd),NEWLINE}NEWLINENEWLINENEWLINEdef verify_conv3d_ncdhw(NEWLINE batch,NEWLINE in_channel,NEWLINE in_size,NEWLINE num_filter,NEWLINE depth_kernel,NEWLINE space_kernel,NEWLINE stride,NEWLINE padding,NEWLINE dilation=1,NEWLINE add_bias=False,NEWLINE add_relu=False,NEWLINE):NEWLINE pad_front, pad_top, pad_left, pad_back, pad_bottom, pad_right = get_pad_tuple3d(NEWLINE padding, (depth_kernel, space_kernel, space_kernel)NEWLINE )NEWLINE padding_sum = pad_front + pad_back + pad_top + pad_left + pad_bottom + pad_rightNEWLINE print(NEWLINE "Workload: (%d, %d, %d, %d, %d, %d, %d, %d)"NEWLINE % (batch, in_channel, in_size, num_filter, space_kernel, stride, padding_sum, dilation)NEWLINE )NEWLINENEWLINE in_depth = in_height = in_width = in_sizeNEWLINENEWLINE A = te.placeholder((batch, in_channel, in_depth, in_height, in_width), name="A")NEWLINE W = te.placeholder((num_filter, in_channel, depth_kernel, space_kernel, space_kernel), name="W")NEWLINE bias = te.placeholder((num_filter, 1, 1, 1), name="bias")NEWLINENEWLINE a_shape = get_const_tuple(A.shape)NEWLINE w_shape = get_const_tuple(W.shape)NEWLINE bias_shape = get_const_tuple(bias.shape)NEWLINE dtype = A.dtypeNEWLINENEWLINE @memoize("topi.tests.test_topi_conv3d_ncdhw.verify_conv3d_ncdhw")NEWLINE def get_ref_data():NEWLINE a_np = np.random.uniform(size=a_shape).astype(dtype)NEWLINE w_np = np.random.uniform(size=w_shape).astype(dtype)NEWLINE b_np = np.random.uniform(size=bias_shape).astype(dtype)NEWLINE dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation, dilation))NEWLINE c_np = tvm.topi.testing.conv3d_ncdhw_python(a_np, dw_np, stride, padding)NEWLINE if add_bias:NEWLINE c_np += b_npNEWLINE if add_relu:NEWLINE c_np = np.maximum(c_np, 0)NEWLINE return a_np, w_np, b_np, c_npNEWLINENEWLINE a_np, w_np, b_np, c_np = get_ref_data()NEWLINENEWLINE def check_device(device):NEWLINE ctx = tvm.context(device, 0)NEWLINE if not tvm.testing.device_enabled(device):NEWLINE print("Skip because %s is not enabled" % device)NEWLINE returnNEWLINE print("Running on target: %s" % device)NEWLINE fcompute, fschedule = tvm.topi.testing.dispatch(device, _conv3d_ncdhw_implement)NEWLINE with tvm.target.Target(device):NEWLINE C = fcompute(NEWLINE A, W, (stride, stride, stride), padding, (dilation, dilation, dilation), dtypeNEWLINE )NEWLINE if add_bias:NEWLINE C = topi.add(C, bias)NEWLINE if add_relu:NEWLINE C = topi.nn.relu(C)NEWLINE s = fschedule([C])NEWLINENEWLINE a = tvm.nd.array(a_np, ctx)NEWLINE w = tvm.nd.array(w_np, ctx)NEWLINE b = tvm.nd.array(b_np, ctx)NEWLINE c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), ctx)NEWLINE if add_bias:NEWLINE func = tvm.build(NEWLINE s,NEWLINE [A, W, bias, C],NEWLINE device,NEWLINE name="relu_%d_%d_%d_%d_%d_%d_%d_%d"NEWLINE % (NEWLINE batch,NEWLINE in_channel,NEWLINE in_size,NEWLINE num_filter,NEWLINE space_kernel,NEWLINE stride,NEWLINE padding_sum,NEWLINE dilation,NEWLINE ),NEWLINE )NEWLINE func(a, w, b, c)NEWLINE else:NEWLINE func = tvm.build(NEWLINE s,NEWLINE [A, W, C],NEWLINE device,NEWLINE name="relu_%d_%d_%d_%d_%d_%d_%d_%d"NEWLINE % (NEWLINE batch,NEWLINE in_channel,NEWLINE in_size,NEWLINE num_filter,NEWLINE space_kernel,NEWLINE stride,NEWLINE padding_sum,NEWLINE dilation,NEWLINE ),NEWLINE )NEWLINE func(a, w, c)NEWLINE tvm.testing.assert_allclose(c.asnumpy(), c_np, rtol=1e-4)NEWLINENEWLINE for device in ["cuda"]:NEWLINE with autotvm.tophub.context(device): # load tophub pre-tuned parametersNEWLINE check_device(device)NEWLINENEWLINENEWLINE@tvm.testing.requires_gpuNEWLINEdef test_conv3d_ncdhw():NEWLINE # Try without depth transformationNEWLINE # 3DCNN workloadsNEWLINE verify_conv3d_ncdhw(1, 61, 20, 120, 3, 3, 1, 0)NEWLINE verify_conv3d_ncdhw(1, 61, 20, 120, 1, 3, 1, 0)NEWLINE verify_conv3d_ncdhw(1, 61, 20, 120, 5, 3, 1, 0)NEWLINE verify_conv3d_ncdhw(1, 61, 20, 120, 5, 5, 1, 2)NEWLINE verify_conv3d_ncdhw(1, 61, 20, 120, 1, 5, 1, 2)NEWLINE verify_conv3d_ncdhw(1, 61, 20, 120, 7, 7, 1, 3)NEWLINE verify_conv3d_ncdhw(1, 128, 12, 256, 3, 3, 1, 1)NEWLINE verify_conv3d_ncdhw(1, 64, 12, 128, 3, 3, 1, 1)NEWLINENEWLINE # bias, reluNEWLINE verify_conv3d_ncdhw(1, 64, 12, 128, 3, 3, 1, 1, add_relu=True)NEWLINE verify_conv3d_ncdhw(1, 64, 12, 128, 3, 3, 1, 1, add_relu=True, add_bias=True)NEWLINE verify_conv3d_ncdhw(1, 64, 12, 128, 1, 3, 1, 1, add_relu=True, add_bias=True)NEWLINENEWLINE # dilation = 2NEWLINE verify_conv3d_ncdhw(1, 16, 12, 16, 3, 3, 1, "VALID", dilation=2)NEWLINE verify_conv3d_ncdhw(1, 16, 12, 16, 1, 3, 1, "VALID", dilation=2)NEWLINENEWLINE # batch sizeNEWLINE verify_conv3d_ncdhw(4, 32, 12, 64, 3, 3, 1, 1)NEWLINE verify_conv3d_ncdhw(4, 32, 12, 64, 1, 3, 1, 1)NEWLINENEWLINE # weird workloadsNEWLINE verify_conv3d_ncdhw(2, 2, 2, 2, 3, 3, 1, 2)NEWLINE verify_conv3d_ncdhw(3, 3, 3, 3, 3, 3, 1, 3)NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE test_conv3d_ncdhw()NEWLINE import osNEWLINEimport shutilNEWLINENEWLINEimport mathNEWLINEimport sysNEWLINENEWLINEANSI_ESCAPE_SEQUENCE_START = '\x1b'NEWLINEANSI_ESCAPE_SEQUENCE_END = 'm'NEWLINENEWLINENEWLINEdef get_terminal_width():NEWLINE # when piping stdout linux is executing commands in separate process (terminal-less), that's why shutil won't workNEWLINE # so instead of "echo x | program.py | cat" you should use "echo x | (export COLUMNS; program.py | cat"NEWLINENEWLINE # because PyCharm is using separate process for execution, shutil.get_terminal_size() is giving 80, 24NEWLINE if "PYCHARM_HOSTED" in os.environ:NEWLINE return 210NEWLINENEWLINE return shutil.get_terminal_size().columnsNEWLINENEWLINENEWLINEdef get_terminal_height():NEWLINE # when piping stdout linux is executing commands in separate process (terminal-less), that's why shutil won't workNEWLINE # so instead of "echo x | program.py | cat" you should use "echo x | (export COLUMNS; program.py | cat"NEWLINENEWLINE # because PyCharm is using separate process for execution, shutil.get_terminal_size() is giving 80, 24NEWLINE if "PYCHARM_HOSTED" in os.environ:NEWLINE return 40NEWLINENEWLINE return shutil.get_terminal_size().linesNEWLINENEWLINENEWLINEdef fit_text(text, width=None, already_used_characters=0, postfix='...'):NEWLINE width = width or get_terminal_width()NEWLINE if already_used_characters + len(text) > width - len(postfix):NEWLINE return text[:width - already_used_characters - len(postfix)] + postfixNEWLINE else:NEWLINE return textNEWLINENEWLINENEWLINE# TODO: instead of three letter "..." use one character elypsisis: "…" (few places here and maybe another elsewhere?)NEWLINEdef fit_text_printable_part_only(text, width=None, already_used_characters=0, postfix_if_cant_fit='...'):NEWLINE width = width or get_terminal_width()NEWLINE return get_printable_text_substring(text, 0, width - already_used_characters,NEWLINE postfix_if_cant_fit=postfix_if_cant_fit)NEWLINENEWLINENEWLINEdef get_printable_text_substring(text, _from, _len, postfix_if_cant_fit='...'):NEWLINE # print(f'get_printable_text_substring({repr(text)}, {_from}, {_len})')NEWLINE # TODO: https://unix.stackexchange.com/questions/111899/how-to-strip-color-codes-out-of-stdout-and-pipe-to-file-and-stdoutNEWLINE escape_sequence_in_progress = FalseNEWLINE printable_characters = 0NEWLINE output = []NEWLINE flags = []NEWLINE characters_to_skip = _fromNEWLINE characters_skipped = 0NEWLINE for character in text:NEWLINE if character == ANSI_ESCAPE_SEQUENCE_START:NEWLINE escape_sequence_in_progress = TrueNEWLINENEWLINE if printable_characters >= _len and not escape_sequence_in_progress: # text is longer than we can fitNEWLINE if len(postfix_if_cant_fit) > 0:NEWLINE removed_so_far = 0NEWLINE for i in range(len(output) - 1, 0, -1):NEWLINE if not flags[i]: # not non-printable = printableNEWLINE removed_so_far += 1NEWLINE del output[i]NEWLINE if removed_so_far == len(postfix_if_cant_fit):NEWLINE breakNEWLINENEWLINE output.extend(list(postfix_if_cant_fit))NEWLINE breakNEWLINENEWLINE if characters_skipped < characters_to_skip: # if we still skipping X printable charactersNEWLINE if not escape_sequence_in_progress:NEWLINE characters_skipped += 1NEWLINE else: # normal mode (after skipping)NEWLINE output.append(character)NEWLINE flags.append(escape_sequence_in_progress)NEWLINENEWLINE if not escape_sequence_in_progress:NEWLINE printable_characters += 1NEWLINENEWLINE if escape_sequence_in_progress and character == ANSI_ESCAPE_SEQUENCE_END:NEWLINE escape_sequence_in_progress = FalseNEWLINENEWLINE return ''.join(output)NEWLINENEWLINENEWLINEdef get_printable_text_length(text):NEWLINE escape_sequence_in_progress = FalseNEWLINE printable_characters = 0NEWLINE current_sequence_length = 0NEWLINE for character in text.rstrip():NEWLINE if character == ANSI_ESCAPE_SEQUENCE_START:NEWLINE escape_sequence_in_progress = TrueNEWLINE current_sequence_length = 0NEWLINENEWLINE if not escape_sequence_in_progress:NEWLINE printable_characters += 1NEWLINE else:NEWLINE current_sequence_length += 1NEWLINENEWLINE if escape_sequence_in_progress and character == ANSI_ESCAPE_SEQUENCE_END:NEWLINE escape_sequence_in_progress = FalseNEWLINE current_sequence_length = 0NEWLINENEWLINE printable_characters += current_sequence_lengthNEWLINENEWLINE return printable_charactersNEWLINENEWLINENEWLINEdef get_last_ansi_sequence(text):NEWLINE starting_pos = text.rfind(ANSI_ESCAPE_SEQUENCE_START)NEWLINE if starting_pos == -1:NEWLINE return ''NEWLINE ending_pos = text.find(ANSI_ESCAPE_SEQUENCE_END, starting_pos)NEWLINE if ending_pos == -1:NEWLINE return ''NEWLINENEWLINE return text[starting_pos:ending_pos + 1]NEWLINENEWLINENEWLINEdef colorized_center(text, width, fill_char, left_color, middle_color, right_color, rainbow=False):NEWLINE output = ''NEWLINE text_len = len(str(text))NEWLINE remaining_len = width - text_lenNEWLINE for i in range(int(math.floor(remaining_len / 2))):NEWLINE cur_color_index = left_color if not rainbow else i % 16NEWLINE output += colorize_text(fill_char, cur_color_index)NEWLINE output += colorize_text(text, middle_color)NEWLINE for i in range(int(math.ceil(remaining_len / 2))):NEWLINE cur_color_index = right_color if not rainbow else i % 16NEWLINE output += colorize_text(fill_char, cur_color_index)NEWLINE output += colorize_text('', 255)NEWLINE return outputNEWLINENEWLINENEWLINE# TODO: split into color_start, color_end then implement:NEWLINE# def colorize_text(text, color, normal_color):NEWLINE# return color_start(color) + text + color_end(normal_color)NEWLINENEWLINENEWLINEdef colorize_text(text, color):NEWLINE return f'\x1b[38;5;{color}m{text}'NEWLINENEWLINENEWLINEdef reset_color():NEWLINE return '\x1b[39m'NEWLINENEWLINENEWLINEdef clear_to_end_of_line():NEWLINE return '\x1b[K'NEWLINENEWLINENEWLINEdef clear_to_end_of_screen():NEWLINE return '\x1b[J'NEWLINENEWLINENEWLINEdef get_underscore_start():NEWLINE return '\x1b[4m'NEWLINENEWLINENEWLINEdef get_underscore_end():NEWLINE return '\x1b[24m'NEWLINENEWLINENEWLINEdef get_move_left(character_count):NEWLINE if character_count > 0:NEWLINE return f'\x1b[{character_count}D'NEWLINE else:NEWLINE return ''NEWLINENEWLINENEWLINEdef get_move_up(lines):NEWLINE return f'\x1b[{lines}A'NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE orig = '12345\x1b[38;5;m1'NEWLINE for i in range(4, 6 + 1):NEWLINE out_dots = get_printable_text_substring(orig, 0, i)NEWLINE out_empty = get_printable_text_substring(orig, 0, i, postfix_if_cant_fit="")NEWLINE print(f'{i}# {orig} + "..." -> {out_dots} ({len(out_dots)}:{get_printable_text_length(out_dots)})')NEWLINE print(f'{i}# {orig} + "" -> {out_empty} ({len(out_empty)}:{get_printable_text_length(out_empty)})')NEWLINENEWLINENEWLINEdef replace_whitespace_characters_by_their_representations(original_lines):NEWLINE # TODO: use string.translateNEWLINE replace_pairs = [['\n', '\\n'], ['\t', '\\t'], ['\r', '\\r'], ['\f', '\\f'], ['\b', '\\b'], ['\x0b', '\\x0b']]NEWLINE text = original_linesNEWLINE for replace_from, replace_to in replace_pairs:NEWLINE text = text.replace(replace_from, replace_to)NEWLINE return textNEWLINENEWLINENEWLINEdef is_piping_text():NEWLINE return not os.isatty(sys.stdin.fileno())NEWLINENEWLINENEWLINEdef read_text_from_pipe(encoding='utf8', errors='replace'):NEWLINE return sys.stdin.buffer.read().decode(encoding, errors)NEWLINE from django.core.cache import get_cacheNEWLINEfrom avocado.conf import settingsNEWLINEfrom .model import instance_cache_key, NEVER_EXPIRENEWLINENEWLINENEWLINEdef post_save_cache(sender, instance, **kwargs):NEWLINE """General post-save handler for caching model instances. NOTE: This mustNEWLINE be used in conjunction with the `pre_delete_uncache` since the cache is setNEWLINE to never expire.NEWLINE """NEWLINE cache = get_cache(settings.DATA_CACHE)NEWLINE cache.set(instance_cache_key(instance), instance, timeout=NEVER_EXPIRE)NEWLINENEWLINENEWLINEdef pre_delete_uncache(sender, instance, **kwargs):NEWLINE "General post-delete handler for removing cache for model instances."NEWLINE cache = get_cache(settings.DATA_CACHE)NEWLINE cache.delete(instance_cache_key(instance))NEWLINE NEWLINEimport sys, jsonNEWLINEimport cv2NEWLINEimport torchNEWLINENEWLINEPATH_EL = "../entity-linking/"NEWLINEsys.path.insert(0, PATH_EL)NEWLINENEWLINEimport clickNEWLINEimport tqdmNEWLINEfrom pycorenlp import StanfordCoreNLPNEWLINENEWLINEfrom entitylinking import core as ELNEWLINEfrom entitylinking.core.sentence import SentenceEncoderNEWLINENEWLINENEWLINEcorenlp = StanfordCoreNLP('http://semanticparsing:9000')NEWLINEcorenlp_properties = {NEWLINE 'annotators': 'tokenize, pos, ner',NEWLINE 'outputFormat': 'json'NEWLINE}NEWLINENEWLINEEL.candidate_retrieval.entity_linking_p['max.match.diff'] = 0NEWLINENEWLINEEL.mention_extraction.np_parser = EL.mention_extraction.NgramNpParser(NEWLINE exclude_pos={".", "ORDINAL", "TIME", "PERCENT", "NUMBER"},NEWLINE exclude_if_first={"WDT", "WP", "WP$", "WRB", "VBZ", "VB", "VBP"},NEWLINE exclude_prefix={"IN", "DT", "CC", "POS"},NEWLINE exclude_suffix={"IN", "DT", "CC", "JJ", "RB", "JJR", "JJS", "RBR", "RBS"},NEWLINE exclude_alone={"IN", "DT", "PDT", "POS", "PRP", "PRP$", "CC", "TO",NEWLINE "VBZ", "VBD", "VBP", "VB", "VBG", "VBN",NEWLINE "JJ", "RB", "JJR", "JJS", "RBR", "RBS",NEWLINE "MD", "WDT", "WP", "WP$", "WRB"NEWLINE })NEWLINENEWLINENEWLINE@click.command()NEWLINE@click.argument('path_to_file')NEWLINE@click.argument('output_file')NEWLINEdef apply(path_to_file, output_file):NEWLINENEWLINE entitylinker = EL.MLLinker(path_to_model="../entity-linking/trainedmodels/VectorModel_137.torchweights",NEWLINE confidence=0.01,NEWLINE num_candidates=3,NEWLINE max_mention_len=2)NEWLINENEWLINE with open(path_to_file) as f:NEWLINE input_data = [l.strip().split(",") for l in f.readlines()][1:]NEWLINENEWLINE output_data = {}NEWLINE for parts in tqdm.tqdm(input_data):NEWLINE output_per_story = []NEWLINE for i in range(1, 7):NEWLINE s = parts[i]NEWLINE sent = entitylinker.link_entities_in_sentence_obj(EL.sentence.Sentence(input_text=s))NEWLINE sent.entities = [{k: e[k] for k in {'type', 'linkings', 'token_ids', 'poss', 'tokens', 'drop_score'}}NEWLINE for e in sent.entities if len(e['linkings']) > 0]NEWLINE for e in sent.entities:NEWLINE e['linkings'] = [(l.get('kbID'), l.get('label')) for l in e['linkings']]NEWLINE output_per_story.append(sent)NEWLINE output_data[parts[0]] = output_per_storyNEWLINE with open(output_file, "w") as out:NEWLINE json.dump(output_data, out, sort_keys=True, indent=4, cls=SentenceEncoder)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE apply()NEWLINE # Copyright 2021 Arbaaz LaskarNEWLINENEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINENEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINENEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINEfrom typing import TupleNEWLINEimport reNEWLINEimport osNEWLINEimport sysNEWLINEimport hashlibNEWLINENEWLINEfrom colorama import Fore, StyleNEWLINEfrom tqdm import tqdmNEWLINEfrom loguru import loggerNEWLINEimport typerNEWLINENEWLINEfrom .fichub import FicHubNEWLINEfrom .logging import downloaded_logNEWLINENEWLINENEWLINEdef get_format_type(_format: str = "epub") -> int:NEWLINE if re.search(r"\bepub\b", _format, re.I):NEWLINE format_type = 0NEWLINENEWLINE elif re.search(r"\bmobi\b", _format, re.I):NEWLINE format_type = 1NEWLINENEWLINE elif re.search(r"\bpdf\b", _format, re.I):NEWLINE format_type = 2NEWLINENEWLINE elif re.search(r"\bhtml\b", _format, re.I):NEWLINE format_type = 3NEWLINENEWLINE else: # default epub formatNEWLINE format_type = 0NEWLINENEWLINE return format_typeNEWLINENEWLINENEWLINEdef check_url(url: str, debug: bool = False,NEWLINE exit_status: int = 0) -> Tuple[bool, int]:NEWLINENEWLINE if re.search(r"\barchiveofourown.org/series\b", url):NEWLINE unsupported_flag = TrueNEWLINENEWLINE elif re.search(r"\bfanfiction.net/u\b", url):NEWLINE unsupported_flag = TrueNEWLINENEWLINE else:NEWLINE unsupported_flag = FalseNEWLINENEWLINE if unsupported_flag:NEWLINE with open("err.log", "a") as file:NEWLINE file.write(url)NEWLINENEWLINE exit_status = 1NEWLINENEWLINE if debug:NEWLINE logger.error(NEWLINE f"Skipping unsupported URL: {url}")NEWLINE else:NEWLINE tqdm.write(NEWLINE Fore.RED + f"\nSkipping unsupported URL: {url}" +NEWLINE Style.RESET_ALL + Fore.CYAN +NEWLINE "\nTo see the supported site list, use " + Fore.YELLOW +NEWLINE "fichub_cli -ss" + Style.RESET_ALL + Fore.CYAN +NEWLINE "\nReport the error if the URL is supported!\n")NEWLINENEWLINE return False, exit_statusNEWLINENEWLINE else: # for supported urlsNEWLINE return True, exit_statusNEWLINENEWLINENEWLINEdef save_data(out_dir: str, file_name: str, download_url: str,NEWLINE debug: bool, force: bool, cache_hash: str,NEWLINE exit_status: int, automated: bool) -> int:NEWLINENEWLINE ebook_file = os.path.join(out_dir, file_name)NEWLINE try:NEWLINE hash_flag = check_hash(ebook_file, cache_hash)NEWLINENEWLINE except FileNotFoundError:NEWLINE hash_flag = FalseNEWLINENEWLINE if os.path.exists(ebook_file) and force is False and hash_flag is True:NEWLINENEWLINE exit_status = 1NEWLINE if debug:NEWLINE logger.warning(NEWLINE "The hash of the local file & the remote file is the same.")NEWLINENEWLINE logger.error(NEWLINE f"{ebook_file} is already the latest version. Skipping download. Use --force flag to overwrite.")NEWLINENEWLINE else:NEWLINE tqdm.write(NEWLINE Fore.RED +NEWLINE f"{ebook_file} is already the latest version. Skipping download." +NEWLINE Style.RESET_ALL + Fore.CYAN + " Use --force flag to overwrite.")NEWLINENEWLINE else:NEWLINE if force and debug:NEWLINE logger.warning(NEWLINE f"--force flag was passed. Overwriting {ebook_file}")NEWLINENEWLINE fic = FicHub(debug, automated, exit_status)NEWLINE fic.get_fic_data(download_url)NEWLINENEWLINE try:NEWLINE with open(ebook_file, "wb") as f:NEWLINE if debug:NEWLINE logger.info(NEWLINE f"Saving {ebook_file}")NEWLINE f.write(fic.response_data.content)NEWLINE downloaded_log(debug, file_name)NEWLINE except FileNotFoundError:NEWLINE tqdm.write(Fore.RED + "Output directory doesn't exist. Exiting!")NEWLINE sys.exit(1)NEWLINENEWLINE return exit_statusNEWLINENEWLINENEWLINEdef check_hash(ebook_file: str, cache_hash: str) -> bool:NEWLINENEWLINE with open(ebook_file, 'rb') as file:NEWLINE data = file.read()NEWLINENEWLINE ebook_hash = hashlib.md5(data).hexdigest()NEWLINENEWLINE if ebook_hash.strip() == cache_hash.strip():NEWLINE hash_flag = TrueNEWLINE else:NEWLINE hash_flag = FalseNEWLINENEWLINE return hash_flagNEWLINENEWLINENEWLINEdef out_dir_exists_check(out_dir):NEWLINE """Check if the output directory exists"""NEWLINE if not os.path.isdir(out_dir):NEWLINE mkdir_prompt = typer.prompt(NEWLINE Fore.RED+"Output directory doesn't exist!" + Style.RESET_ALL +NEWLINE Fore.BLUE + f"\nShould the CLI create {out_dir}?(y/n)")NEWLINE if mkdir_prompt == 'y':NEWLINE os.mkdir(out_dir)NEWLINE # Copyright (C) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.NEWLINE#NEWLINE# This work is made available under the Nvidia Source Code License-NC.NEWLINE# To view a copy of this license, check out LICENSE.mdNEWLINE# import torchNEWLINEimport mathNEWLINENEWLINEfrom torch.optim.optimizer import Optimizer, requiredNEWLINENEWLINENEWLINEclass Fromage(Optimizer):NEWLINE r"""Fromage optimizer implementation (https://arxiv.org/abs/2002.03432)"""NEWLINENEWLINE def __init__(self, params, lr=required, momentum=0):NEWLINE if lr is not required and lr < 0.0:NEWLINE raise ValueError("Invalid learning rate: {}".format(lr))NEWLINE defaults = dict(lr=lr, momentum=momentum)NEWLINE super(Fromage, self).__init__(params, defaults)NEWLINENEWLINE def step(self, closure=None):NEWLINE r"""Performs a single optimization step.NEWLINENEWLINE Args:NEWLINE closure (callable, optional): A closure that reevaluates the modelNEWLINE and returns the loss.NEWLINE """NEWLINE loss = NoneNEWLINE if closure is not None:NEWLINE loss = closure()NEWLINENEWLINE for group in self.param_groups:NEWLINE for p in group['params']:NEWLINE if p.grad is None:NEWLINE continueNEWLINE d_p = p.grad.dataNEWLINE d_p_norm = p.grad.norm()NEWLINE p_norm = p.norm()NEWLINE if p_norm > 0.0 and d_p_norm > 0.0:NEWLINE p.data.add_(-group['lr'], d_p * (p_norm / d_p_norm))NEWLINE else:NEWLINE p.data.add_(-group['lr'], d_p)NEWLINE p.data /= math.sqrt(1 + group['lr'] ** 2)NEWLINENEWLINE return lossNEWLINE # Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINE"""UI tests for /bundle page"""NEWLINENEWLINEimport osNEWLINEfrom typing import ListNEWLINENEWLINEimport allureNEWLINEimport pytestNEWLINEfrom adcm_client.objects import ADCMClient, BundleNEWLINEfrom adcm_pytest_plugin import utilsNEWLINEfrom adcm_pytest_plugin.utils import catch_failedNEWLINEfrom selenium.common.exceptions import ElementClickInterceptedExceptionNEWLINENEWLINEfrom tests.conftest import DUMMY_CLUSTER_BUNDLENEWLINEfrom tests.ui_tests.app.app import ADCMTestNEWLINEfrom tests.ui_tests.app.page.admin.page import AdminIntroPageNEWLINEfrom tests.ui_tests.app.page.bundle.page import BundlePageNEWLINEfrom tests.ui_tests.app.page.bundle_list.page import BundleListPage, BundleInfoNEWLINEfrom tests.ui_tests.app.page.cluster_list.page import ClusterListPageNEWLINEfrom tests.ui_tests.app.page.host_list.page import HostListPageNEWLINENEWLINELICENSE_FP = os.path.join(utils.get_data_dir(__file__), 'license.txt')NEWLINENEWLINECLUSTER_CE_CONFIG = DUMMY_CLUSTER_BUNDLENEWLINENEWLINECLUSTER_EE_CONFIG = [NEWLINE {NEWLINE **CLUSTER_CE_CONFIG[0],NEWLINE 'description': 'enterprise description',NEWLINE 'license': 'license.txt',NEWLINE 'edition': 'enterprise',NEWLINE }NEWLINE]NEWLINENEWLINEPROVIDER_CONFIG = [NEWLINE {NEWLINE 'type': 'provider',NEWLINE 'name': 'test_provider',NEWLINE 'version': '2.15-dev',NEWLINE },NEWLINE {NEWLINE 'type': 'host',NEWLINE 'name': 'Test Host',NEWLINE 'description': 'Test Host Description',NEWLINE 'version': '2.15-dev',NEWLINE },NEWLINE]NEWLINENEWLINENEWLINEdef _assert_bundle_info_value(attribute: str, actual_info: BundleInfo, expected_info: BundleInfo):NEWLINE actual_value = getattr(actual_info, attribute)NEWLINE expected_value = getattr(expected_info, attribute)NEWLINE assert actual_value == expected_value, f"Bundle's {attribute} should be {expected_value}, not {actual_value}"NEWLINENEWLINENEWLINE# pylint: disable=redefined-outer-nameNEWLINE@allure.step('Check bundle list is empty')NEWLINEdef _check_bundle_list_is_empty(page: BundleListPage):NEWLINE assert (row_count := page.table.row_count) == 0, f'Bundle list should be empty, but {row_count} records was found'NEWLINENEWLINENEWLINE@allure.step('Check bundle is listed in table')NEWLINEdef _open_bundle_list_and_check_info(page: BundleListPage, expected_info: BundleInfo):NEWLINE """NEWLINE Open bundle list page, check that exactly 1 row is presented and check it's infoNEWLINE """NEWLINE page.open()NEWLINE assert (NEWLINE row_count := page.table.row_countNEWLINE ) == 1, f'Bundle list should have exactly 1 record, but {row_count} was found'NEWLINE bundle_info = page.get_bundle_info()NEWLINE check_bundle_info_is_equal(bundle_info, expected_info)NEWLINENEWLINENEWLINE@allure.step('Check bundle info')NEWLINEdef check_bundle_info_is_equal(actual_info: BundleInfo, expected_info: BundleInfo):NEWLINE """Assert bundle attrs values"""NEWLINE for attr in ('name', 'description', 'version', 'edition'):NEWLINE _assert_bundle_info_value(attr, actual_info, expected_info)NEWLINENEWLINENEWLINE@pytest.fixture()NEWLINE# pylint: disable-next=unused-argumentNEWLINEdef page(app_fs: ADCMTest, login_to_adcm_over_api) -> BundleListPage:NEWLINE """Get BundleListPage after authorization"""NEWLINE return BundleListPage(app_fs.driver, app_fs.adcm.url).open()NEWLINENEWLINENEWLINE@allure.title("Upload bundles")NEWLINE@pytest.fixture()NEWLINEdef upload_bundles(create_bundle_archives: List[str], sdk_client_fs: ADCMClient) -> List[Bundle]:NEWLINE """Upload bundles to ADCM"""NEWLINE return [sdk_client_fs.upload_from_fs(path) for path in create_bundle_archives]NEWLINENEWLINENEWLINE@pytest.fixture()NEWLINEdef _create_cluster(upload_bundles: List[Bundle]):NEWLINE """Upload bundles and create cluster from first bundle"""NEWLINE upload_bundles[0].cluster_create('Best Cluster Ever')NEWLINENEWLINENEWLINE@pytest.mark.smoke()NEWLINEdef test_ce_bundle_upload(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload community bundle"""NEWLINE bundle_params = BundleInfo(NEWLINE name="test_cluster", version="1.5", edition="community", description="community description"NEWLINE )NEWLINE page.upload_bundle(create_bundle_archives[0])NEWLINE bundle_info = page.get_bundle_info()NEWLINE check_bundle_info_is_equal(bundle_info, bundle_params)NEWLINENEWLINENEWLINE@pytest.mark.smoke()NEWLINE@pytest.mark.parametrize("create_bundle_archives", [([CLUSTER_EE_CONFIG], LICENSE_FP)], indirect=True)NEWLINEdef test_ee_bundle_upload(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload enterprise bundle and accept licence"""NEWLINE bundle_params = BundleInfo(NEWLINE name='test_cluster',NEWLINE version='1.5',NEWLINE edition='enterprise',NEWLINE description='enterprise description',NEWLINE )NEWLINE page.upload_bundle(create_bundle_archives[0])NEWLINE page.accept_licence()NEWLINE bundle_info = page.get_bundle_info()NEWLINE check_bundle_info_is_equal(bundle_info, bundle_params)NEWLINENEWLINENEWLINE@pytest.mark.smoke()NEWLINEdef test_delete_bundle(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload bundle and delete it"""NEWLINE with allure.step('Upload bundle'):NEWLINE page.upload_bundle(create_bundle_archives[0])NEWLINE assert page.table.row_count == 1, 'One bundle should be uploaded'NEWLINE with allure.step('Delete bundle'):NEWLINE page.delete_bundle()NEWLINE assert page.table.row_count == 0, 'No bundle should be listed in the table'NEWLINENEWLINENEWLINE@pytest.mark.parametrize(NEWLINE "create_bundle_archives", [([CLUSTER_CE_CONFIG, CLUSTER_EE_CONFIG], LICENSE_FP)], indirect=TrueNEWLINE)NEWLINEdef test_two_bundles(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload two bundles"""NEWLINE with allure.step('Upload 1st bundle'), page.table.wait_rows_change():NEWLINE page.upload_bundle(create_bundle_archives[0])NEWLINE with allure.step('Upload 2nd bundle'), page.table.wait_rows_change():NEWLINE page.upload_bundle(create_bundle_archives[1])NEWLINE with allure.step('Check there are exactly 2 rows'):NEWLINE rows = page.table.row_countNEWLINE assert rows == 2, f'Row amount should be 2, but only {rows} is presented'NEWLINENEWLINENEWLINE@allure.issue("https://arenadata.atlassian.net/browse/ADCM-2010")NEWLINE@pytest.mark.skip(reason="Not worked using selenoid https://github.com/aerokube/selenoid/issues/844")NEWLINE@pytest.mark.parametrize(NEWLINE "create_bundle_archives", [([CLUSTER_CE_CONFIG, CLUSTER_EE_CONFIG], LICENSE_FP)], indirect=TrueNEWLINE)NEWLINEdef test_accept_license_with_two_bundles_upload_at_once(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload two bundles and accept license"""NEWLINE with page.table.wait_rows_change():NEWLINE page.upload_bundles(create_bundle_archives)NEWLINE with catch_failed(ElementClickInterceptedException, "License was not accepted by single button click"):NEWLINE page.accept_licence(row_num=1)NEWLINENEWLINENEWLINE@pytest.mark.smoke()NEWLINEdef test_open_bundle_from_table(page: BundleListPage, upload_bundles: List[Bundle]):NEWLINE """Test open bundle object page from list of bundles"""NEWLINE with allure.step('Open bundle object page from bundle list'):NEWLINE page.click_bundle_in_row(page.table.get_row())NEWLINE with allure.step('Check object page is opened'):NEWLINE object_page = BundlePage(page.driver, page.base_url, upload_bundles[0].id)NEWLINE object_page.wait_page_is_opened()NEWLINENEWLINENEWLINE@pytest.mark.smoke()NEWLINEdef test_open_main_menu_on_bundle_page(page: BundleListPage, upload_bundles: List[Bundle]):NEWLINE """Open main menu on bundle detailed page"""NEWLINE with allure.step('Open bundle object page'):NEWLINE object_page = BundlePage(page.driver, page.base_url, upload_bundles[0].id)NEWLINE object_page.open()NEWLINE object_page.open_main_menu()NEWLINE object_page.check_all_main_menu_fields_are_presented()NEWLINENEWLINENEWLINE@pytest.mark.usefixtures('upload_bundles')NEWLINEdef test_open_adcm_main_menu(page: BundleListPage):NEWLINE """Open main menu by clicking on the menu icon in toolbar"""NEWLINE page.click_on_home_button_on_tooltip()NEWLINE AdminIntroPage(page.driver, page.base_url).wait_page_is_opened()NEWLINENEWLINENEWLINE@pytest.mark.usefixtures("_create_cluster")NEWLINEdef test_delete_bundle_with_created_cluster(page: BundleListPage):NEWLINE """NEWLINE Bundle should not be deleted if an object defined in it is createdNEWLINE """NEWLINE page.delete_bundle()NEWLINE page.check_at_least_one_bundle_is_presented()NEWLINENEWLINENEWLINE@pytest.mark.smoke()NEWLINE@pytest.mark.parametrize(NEWLINE "create_bundle_archives",NEWLINE [[PROVIDER_CONFIG]],NEWLINE indirect=True,NEWLINE ids=['provider_bundle'],NEWLINE)NEWLINEdef test_upload_provider_bundle_from_another_page(NEWLINE page: BundleListPage, app_fs: ADCMTest, create_bundle_archives: List[str]NEWLINE):NEWLINE """NEWLINE Upload bundle from host list and check it is presented in tableNEWLINE """NEWLINE expected_info = BundleInfo(name='test_provider', version='2.15-dev', edition='community', description='')NEWLINE _check_bundle_list_is_empty(page)NEWLINE with allure.step('Create bundle from host creation popup'):NEWLINE host_list_page = HostListPage(app_fs.driver, app_fs.adcm.url).open()NEWLINE host_list_page.upload_bundle_from_host_create_popup(create_bundle_archives[0])NEWLINE _open_bundle_list_and_check_info(page, expected_info)NEWLINENEWLINENEWLINE@pytest.mark.smoke()NEWLINE@pytest.mark.parametrize(NEWLINE "create_bundle_archives",NEWLINE [[CLUSTER_CE_CONFIG]],NEWLINE indirect=True,NEWLINE ids=['cluster_bundle'],NEWLINE)NEWLINEdef test_upload_cluster_bundle_from_another_page(NEWLINE page: BundleListPage, app_fs: ADCMTest, create_bundle_archives: List[str]NEWLINE):NEWLINE """Upload bundle from cluster list and check it is presented in table"""NEWLINE expected_info = BundleInfo(NEWLINE name='test_cluster', version='1.5', edition='community', description='community description'NEWLINE )NEWLINE _check_bundle_list_is_empty(page)NEWLINE with allure.step('Create bundle from cluster creation popup'):NEWLINE cluster_page = ClusterListPage(app_fs.driver, app_fs.adcm.url).open()NEWLINE cluster_page.upload_bundle_from_cluster_create_popup(create_bundle_archives[0])NEWLINE _open_bundle_list_and_check_info(page, expected_info)NEWLINENEWLINENEWLINE@pytest.mark.parametrize(NEWLINE "create_bundle_archives",NEWLINE [[[{'type': 'cluster', 'name': f'ihavetodance-{i}', 'version': f'{i}-ver'}] for i in range(12)]],NEWLINE indirect=True,NEWLINE)NEWLINE@pytest.mark.usefixtures("upload_bundles")NEWLINEdef test_bundle_list_pagination(page: BundleListPage):NEWLINE """Upload 12 bundles and check pagination"""NEWLINE params = {'on_first_page': 10, 'on_second_page': 2}NEWLINE page.close_info_popup()NEWLINE page.table.check_pagination(params['on_second_page'])NEWLINE NEWLINEimport loggingNEWLINEfrom deep_lyric_visualizer.helpers import setup_logger, _extract_name_from_pathNEWLINEfrom deep_lyric_visualizer.generator.generation_environment import (GenerationEnvironment,NEWLINE WikipediaBigGANGenerationEnviornment)NEWLINEfrom deep_lyric_visualizer.generator.generatorio import PickleGeneratorIO, YAMLGeneratorIONEWLINENEWLINEfrom deep_lyric_visualizer.nlp.vectorizer import VectorizerNEWLINEimport numpy as npNEWLINEsetup_logger()NEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINENEWLINEclass ImageCategoryVectorizer(Vectorizer):NEWLINE def __init__(self, gen_env=None):NEWLINE """A vectorizer specific to image categories. Inherits from theNEWLINE Vectorizer class in the nlp section of this package.NEWLINENEWLINE Args:NEWLINE Vectorizer (nlp.Vectorizer): the Vectorizer class, from which thisNEWLINE class inherits.NEWLINE gen_env (generator.GenerationEnvironment, optional): aNEWLINE GenerationEnvironment instance. If None, uses the default .NEWLINE Defaults to None.NEWLINE """NEWLINE super().__init__(gen_env)NEWLINENEWLINE self.name = __name__ if __name__ != '__main__' else _extract_name_from_path(NEWLINE __file__)NEWLINE self.vectorized_dict = NoneNEWLINENEWLINE self.attrs = ['vectorized_dict']NEWLINENEWLINE def _mean_strategy(self, category_tokens):NEWLINE """Defines the so-called 'mean' strategy for vectorizing a list ofNEWLINE list of tokens for a category. Each sub-category or topic is treatedNEWLINE first, averaging the embeddings for the tokens in that category.NEWLINE Then, the results from each sub-category/topic are averaged together.NEWLINENEWLINE Args:NEWLINE category_tokens (list): This is a list of lists, one list of tokensNEWLINE for each topic in the category.NEWLINENEWLINE Returns:NEWLINE np.array: A so-called category vector, an embedding for theNEWLINE category.NEWLINE """NEWLINENEWLINE wordvec_sum = np.zeros(self.env.wordvec_dim)NEWLINE n_phrases = 0NEWLINENEWLINE for tokens in category_tokens:NEWLINE n = len(tokens)NEWLINE if n == 0:NEWLINE continueNEWLINENEWLINE vec = np.zeros(self.env.wordvec_dim)NEWLINE n_vectorizable_phrases = 0NEWLINE for token in tokens:NEWLINE try:NEWLINE vectorized = self.vectorize_word(token)NEWLINE except KeyError:NEWLINE passNEWLINE else:NEWLINE n_vectorizable_phrases += 1NEWLINE vec += vectorizedNEWLINE if n_vectorizable_phrases == 0:NEWLINE continueNEWLINE else:NEWLINE n_phrases += 1NEWLINE vec = vec / n_vectorizable_phrasesNEWLINE wordvec_sum += vecNEWLINE mean_wordvec = (NEWLINE wordvec_sum / n_phrases) if n_phrases != 0 else wordvec_sumNEWLINENEWLINE return mean_wordvecNEWLINENEWLINE def vectorize_category(self, category_tokens, strategy='mean'):NEWLINE """Handles the vectorization of a cateogry by a particular strategy.NEWLINE At the moment, the only considered strategy is the mean strategy.NEWLINENEWLINE Args:NEWLINE category_tokens (list [list [str]]): This is a list of lists,NEWLINE one list of tokens for each topic in the category.NEWLINE strategy (str, optional): One of {"mean"}. The strategy to useNEWLINE Currently only the mean strategy is supported.NEWLINE Defaults to 'mean'.NEWLINENEWLINE Returns:NEWLINE np.array: An array with the vector representing the categoryNEWLINE """NEWLINE if strategy == 'mean':NEWLINE return self._mean_strategy(category_tokens)NEWLINENEWLINE def vectorize_categories(self, categories_tokens, strategy='mean'):NEWLINE """Vectorize a set of categories given their lists of lists of tokens.NEWLINENEWLINE Args:NEWLINE categories_tokens (dict): A dictionary representing the id numberNEWLINE for a category to the list of lists of tokens for that category.NEWLINE strategy (str, optional): One of {"mean"}. The strategy to useNEWLINE Currently only the mean strategy is supported.NEWLINE Defaults to 'mean'.NEWLINENEWLINE Returns:NEWLINE dict: Dictionary with embeddings for each category_id.NEWLINE """NEWLINE self.vectorized_dict = {id_: self.vectorize_category(NEWLINE category) for id_, category in categories_tokens.items()}NEWLINE return self.vectorized_dictNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE im_vec = ImageCategoryVectorizer()NEWLINE im_vec.load()NEWLINE print(im_vec.vectorized_dict)NEWLINE from storages.backends.s3boto3 import S3Boto3StorageNEWLINENEWLINEStatRootS3BotoStorage = lambda: S3Boto3Storage(location='static')NEWLINENEWLINEMediaRootS3BotoStorage = lambda: S3Boto3Storage(location='media')NEWLINE from django.conf import settingsNEWLINEfrom hashids import HashidsNEWLINENEWLINENEWLINEdef get_hashids():NEWLINE return Hashids(NEWLINE salt=settings.SECRET_KEY, min_length=4, alphabet="abcdefghijklmnopqrstuvwxyz"NEWLINE )NEWLINENEWLINENEWLINEdef decode_hashid(hashid):NEWLINE hashids = get_hashids()NEWLINENEWLINE return hashids.decode(hashid)[0]NEWLINENEWLINENEWLINEdef encode_hashid(value):NEWLINE hashids = get_hashids()NEWLINENEWLINE return hashids.encode(value)NEWLINE from dataclasses import dataclassNEWLINEfrom math import asin, cos, radians, sin, sqrtNEWLINENEWLINENEWLINE@dataclassNEWLINEclass Position:NEWLINE name: strNEWLINE lon: float = 0.0NEWLINE lat: float = 0.0NEWLINENEWLINE def distance_to(self, other):NEWLINE r = 6371 # Earth radius in kilometersNEWLINE lam_1, lam_2 = radians(self.lon), radians(self.lat)NEWLINE phi_1, phi_2 = radians(self.lat), radians(other.lat)NEWLINE h = (sin((phi_2 - phi_1) / 2)**2NEWLINE + cos(phi_1) * cos(phi_2) * sin((lam_2 - lam_1) / 2)**2)NEWLINE return 2 * r * asin(sqrt(h))NEWLINENEWLINENEWLINEoslo = Position('Oslo', 10.8, 59.9)NEWLINEvancouver = Position('Vancouver', -123.1, 49.3)NEWLINEoslo.distance_to(vancouver)NEWLINE import FWCore.ParameterSet.Config as cmsNEWLINENEWLINEpixelPluginsPhase1=cms.VPSet()NEWLINENEWLINENEWLINE#=====================================================================================NEWLINE#--- Phase 1 Pixel BarrelNEWLINE#NEWLINE# Layer Template Cluster file Resolution histogramsNEWLINE# -----------------------------------------------------------------------------NEWLINE# BPL1 2403 template_events_d63207.out.gz pixel_histos63207_2403.rootNEWLINE#NEWLINE#--- Layer 1NEWLINE#NEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select = cms.string("subdetId==BPX && pxbLayer==1"),NEWLINE isBarrel = cms.bool(True),NEWLINE name = cms.string("pixelSmearerBarrelLayer1"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2403 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos63207_2403_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINE#NEWLINE#--- Layer 2NEWLINE# BPL2 2413 template_events_d63507.out.gz pixel_histos63507_2413.rootNEWLINE#NEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select = cms.string("subdetId==BPX && pxbLayer==2"),NEWLINE isBarrel = cms.bool(True),NEWLINE name = cms.string("pixelSmearerBarrelLayer2"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2413 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos63507_2413_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINE#NEWLINE#--- Layer 3NEWLINE# BPL3 2423 template_events_d63807.out.gz pixel_histos63807_2423.rootNEWLINE#NEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select = cms.string("subdetId==BPX && pxbLayer==3"),NEWLINE isBarrel = cms.bool(True),NEWLINE name = cms.string("pixelSmearerBarrelLayer3"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2413 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos63807_2423_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINENEWLINE#NEWLINE#--- Layer 4NEWLINE# BPL4 2433 template_events_d63807.out.gz pixel_histos64107_2433.rootNEWLINE#NEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select = cms.string("subdetId==BPX && pxbLayer==4"),NEWLINE isBarrel = cms.bool(True),NEWLINE name = cms.string("pixelSmearerBarrelLayer4"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2413 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos64107_2433_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINENEWLINENEWLINENEWLINE#=====================================================================================NEWLINE#--- Phase 1 Pixel ForwardNEWLINE#NEWLINE# Panel Template Cluster file Resolution histogramsNEWLINE# -----------------------------------------------------------------------------NEWLINE# FPR2P1 2443 template_events_d64237.out.gz pixel_histos64237_2443.rootNEWLINE#NEWLINE#--- Ring 2, Panel 1NEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select=cms.string("subdetId==FPX && pxfBlade>22 && pxfPanel==1"), ## 1-56 (Ring 1 is 1-22, Ring 2 is 23-56)NEWLINE isBarrel = cms.bool(False),NEWLINE name = cms.string("pixelSmearerForwardRing2Panel1"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2443 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos64237_2443_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINENEWLINENEWLINE#--- Ring 1, Panel 1NEWLINE# FPR1P1 2453 template_events_d64367.out.gz pixel_histos64367_2453.rootNEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select=cms.string("subdetId==FPX && pxfBlade<23 && pxfPanel==1"), ## 1-56 (Ring 1 is 1-22, Ring 2 is 23-56)NEWLINE isBarrel = cms.bool(False),NEWLINE name = cms.string("pixelSmearerForwardRing1Panel1"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2453 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos64367_2453_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINENEWLINE#--- Ring 1, Panel 2NEWLINE# FPR1P2 2463 template_events_d64497.out.gz pixel_histos64497_2463.rootNEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select=cms.string("subdetId==FPX && pxfBlade<23 && pxfPanel==2"), ## 1-56 (Ring 1 is 1-22, Ring 2 is 23-56)NEWLINE isBarrel = cms.bool(False),NEWLINE name = cms.string("pixelSmearerForwardRing1Panel2"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2463 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos64497_2463_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINE#--- Ring 2, Panel 2NEWLINE# FPR2P2 2473 template_events_d64627.out.gz pixel_histos64627_2473.rootNEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select=cms.string("subdetId==FPX && pxfBlade>22 && pxfPanel==2"), ## 1-56 (Ring 1 is 1-22, Ring 2 is 23-56)NEWLINE isBarrel = cms.bool(False),NEWLINE name = cms.string("pixelSmearerForwardRing2Panel2"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2473 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos64627_2473_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINE # coding=utf-8NEWLINE# *** WARNING: this file was generated by crd2pulumi. ***NEWLINE# *** Do not edit by hand unless you're certain you know what you are doing! ***NEWLINENEWLINESNAKE_TO_CAMEL_CASE_TABLE = {NEWLINE "active_directory": "activeDirectory",NEWLINE "api_version": "apiVersion",NEWLINE "augmented_active_directory": "augmentedActiveDirectory",NEWLINE "base_dn": "baseDN",NEWLINE "ca_secret": "caSecret",NEWLINE "credentials_secret": "credentialsSecret",NEWLINE "deref_aliases": "derefAliases",NEWLINE "group_membership_attributes": "groupMembershipAttributes",NEWLINE "group_name_attributes": "groupNameAttributes",NEWLINE "group_uid_attribute": "groupUIDAttribute",NEWLINE "group_uid_name_mapping": "groupUIDNameMapping",NEWLINE "groups_query": "groupsQuery",NEWLINE "last_sync_success_time": "lastSyncSuccessTime",NEWLINE "last_transition_time": "lastTransitionTime",NEWLINE "login_realm": "loginRealm",NEWLINE "page_size": "pageSize",NEWLINE "tolerate_member_not_found_errors": "tolerateMemberNotFoundErrors",NEWLINE "tolerate_member_out_of_scope_errors": "tolerateMemberOutOfScopeErrors",NEWLINE "user_name_attributes": "userNameAttributes",NEWLINE "user_uid_attribute": "userUIDAttribute",NEWLINE "users_query": "usersQuery",NEWLINE}NEWLINENEWLINECAMEL_TO_SNAKE_CASE_TABLE = {NEWLINE "activeDirectory": "active_directory",NEWLINE "apiVersion": "api_version",NEWLINE "augmentedActiveDirectory": "augmented_active_directory",NEWLINE "baseDN": "base_dn",NEWLINE "caSecret": "ca_secret",NEWLINE "credentialsSecret": "credentials_secret",NEWLINE "derefAliases": "deref_aliases",NEWLINE "groupMembershipAttributes": "group_membership_attributes",NEWLINE "groupNameAttributes": "group_name_attributes",NEWLINE "groupUIDAttribute": "group_uid_attribute",NEWLINE "groupUIDNameMapping": "group_uid_name_mapping",NEWLINE "groupsQuery": "groups_query",NEWLINE "lastSyncSuccessTime": "last_sync_success_time",NEWLINE "lastTransitionTime": "last_transition_time",NEWLINE "loginRealm": "login_realm",NEWLINE "pageSize": "page_size",NEWLINE "tolerateMemberNotFoundErrors": "tolerate_member_not_found_errors",NEWLINE "tolerateMemberOutOfScopeErrors": "tolerate_member_out_of_scope_errors",NEWLINE "userNameAttributes": "user_name_attributes",NEWLINE "userUIDAttribute": "user_uid_attribute",NEWLINE "usersQuery": "users_query",NEWLINE}NEWLINE import mathNEWLINENEWLINEr= float(input("Radius:"))NEWLINEri=int(r)NEWLINEwhile r>ri:NEWLINE ri=ri+1NEWLINEx= float(input("x-coordinate:"))NEWLINEwhile x>r or x<-r:NEWLINE print ("x-coordinate cannot be larger than radius")NEWLINE x= float(input("x-coordinate:"))NEWLINEy= float(input("y-coordinate:"))NEWLINEwhile y>r or y<-r:NEWLINE print ("y-coordinate cannot be larger than radius")NEWLINE y= float(input("y-coordinate:"))NEWLINEz= float(input("z-coordinate:"))NEWLINEwhile z>r or z<-r:NEWLINE print ("z-coordinate cannot be larger than radius")NEWLINE z= float(input("z-coordinate:"))NEWLINErij=math.sqrt(((x)**2)+((y)**2)+((z)**2))NEWLINEwhile rij>((math.sqrt(3))*r):NEWLINE print ("point is outside the cube")NEWLINE x=float(input("x-coordinate:"))NEWLINE while x>r or x<-r:NEWLINE print ("x-coordinate cannot be larger than radius")NEWLINE x=float(input("x-coordinate:"))NEWLINE y=float(input("y-coordinate:"))NEWLINE while y>r or y<-r:NEWLINE print ("y-coordinate cannot be larger than radius")NEWLINE y=float(input("y-coordinate:"))NEWLINE z=float(input("z-coordinate:"))NEWLINE while z>r or z<-r:NEWLINE print ("z-coordinate cannot be larger than radius")NEWLINE z=float(input("z-coordinate:"))NEWLINE rij=math.sqrt(((x)**2)+((y)**2)+((z)**2))NEWLINEprint ('Point:(',x,',',y,',',z,')')NEWLINENEWLINEwhile x<0:NEWLINE x=x*(-1)NEWLINEwhile y<0:NEWLINE y=y*(-1)NEWLINEwhile z<0:NEWLINE z=z*(-1)NEWLINENEWLINExone=ri-xNEWLINEyone=ri-yNEWLINEzone=ri-zNEWLINExtwo=(-1)*(x+ri)NEWLINEytwo=(-1)*(y+ri)NEWLINEztwo=(-1)*(z+ri)NEWLINEtotalx=0NEWLINEtotaly=0NEWLINEtotalz=0NEWLINENEWLINEwhile xone>=xtwo:NEWLINE while yone>=ytwo:NEWLINE while zone>=ztwo:NEWLINE if xone==0 and yone==0 and zone==0:NEWLINE zone=zone-1NEWLINE else:NEWLINE rij=math.sqrt(((xone)**2)+((yone)**2)+((zone)**2))NEWLINE rijc=math.sqrt(((x+xone)**2)+((y+yone)**2)+((z+zone)**2))NEWLINE if rijc>((math.sqrt(3))*r):NEWLINE zone=zone-1NEWLINE else:NEWLINE Hx=((3*xone*zone)/((rij)**5))NEWLINE Hy=((3*yone*zone)/((rij)**5))NEWLINE Hz=(((2*((zone)**2))-((xone)**2)-((yone)**2))/((rij)**5))NEWLINE totalx=totalx+HxNEWLINE totaly=totaly+HyNEWLINE totalz=totalz+HzNEWLINE zone=zone-1NEWLINE yone=yone-1NEWLINE zone=ri+zNEWLINE xone=xone-1NEWLINE yone=ri+yNEWLINENEWLINEH=math.sqrt(((totalx)**2)+((totaly)**2)+((totalz)**2))NEWLINEif H<(10**(-10)):NEWLINE print ("total H: 0.0")NEWLINEelse:NEWLINE print ("total H:",H)NEWLINENEWLINE NEWLINENEWLINENEWLINE from .jkgat import JKGATNEWLINENEWLINE__all__ = ['JKGAT']NEWLINE # -*- coding: utf-8 -*-NEWLINE# Copyright 2020 Google LLCNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE#NEWLINEfrom collections import OrderedDictNEWLINEfrom typing import Dict, TypeNEWLINENEWLINEfrom .base import ProfileServiceTransportNEWLINEfrom .grpc import ProfileServiceGrpcTransportNEWLINEfrom .grpc_asyncio import ProfileServiceGrpcAsyncIOTransportNEWLINENEWLINENEWLINE# Compile a registry of transports.NEWLINE_transport_registry = OrderedDict() # type: Dict[str, Type[ProfileServiceTransport]]NEWLINE_transport_registry['grpc'] = ProfileServiceGrpcTransportNEWLINE_transport_registry['grpc_asyncio'] = ProfileServiceGrpcAsyncIOTransportNEWLINENEWLINE__all__ = (NEWLINE 'ProfileServiceTransport',NEWLINE 'ProfileServiceGrpcTransport',NEWLINE 'ProfileServiceGrpcAsyncIOTransport',NEWLINE)NEWLINE # -*- coding: utf-8 -*-NEWLINE#NEWLINE# dengueAI documentation build configuration file, created byNEWLINE# sphinx-quickstart.NEWLINE#NEWLINE# This file is execfile()d with the current directory set to its containing dir.NEWLINE#NEWLINE# Note that not all possible configuration values are present in thisNEWLINE# autogenerated file.NEWLINE#NEWLINE# All configuration values have a default; values that are commented outNEWLINE# serve to show the default.NEWLINENEWLINEimport osNEWLINEimport sysNEWLINENEWLINE# If extensions (or modules to document with autodoc) are in another directory,NEWLINE# add these directories to sys.path here. If the directory is relative to theNEWLINE# documentation root, use os.path.abspath to make it absolute, like shown here.NEWLINE# sys.path.insert(0, os.path.abspath('.'))NEWLINENEWLINE# -- General configuration -----------------------------------------------------NEWLINENEWLINE# If your documentation needs a minimal Sphinx version, state it here.NEWLINE# needs_sphinx = '1.0'NEWLINENEWLINE# Add any Sphinx extension module names here, as strings. They can be extensionsNEWLINE# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.NEWLINEextensions = []NEWLINENEWLINE# Add any paths that contain templates here, relative to this directory.NEWLINEtemplates_path = ['_templates']NEWLINENEWLINE# The suffix of source filenames.NEWLINEsource_suffix = '.rst'NEWLINENEWLINE# The encoding of source files.NEWLINE# source_encoding = 'utf-8-sig'NEWLINENEWLINE# The master toctree document.NEWLINEmaster_doc = 'index'NEWLINENEWLINE# General information about the project.NEWLINEproject = u'dengueAI'NEWLINENEWLINE# The version info for the project you're documenting, acts as replacement forNEWLINE# |version| and |release|, also used in various other places throughout theNEWLINE# built documents.NEWLINE#NEWLINE# The short X.Y version.NEWLINEversion = '0.1'NEWLINE# The full version, including alpha/beta/rc tags.NEWLINErelease = '0.1'NEWLINENEWLINE# The language for content autogenerated by Sphinx. Refer to documentationNEWLINE# for a list of supported languages.NEWLINE# language = NoneNEWLINENEWLINE# There are two options for replacing |today|: either, you set today to someNEWLINE# non-false value, then it is used:NEWLINE# today = ''NEWLINE# Else, today_fmt is used as the format for a strftime call.NEWLINE# today_fmt = '%B %d, %Y'NEWLINENEWLINE# List of patterns, relative to source directory, that match files andNEWLINE# directories to ignore when looking for source files.NEWLINEexclude_patterns = ['_build']NEWLINENEWLINE# The reST default role (used for this markup: `text`) to use for all documents.NEWLINE# default_role = NoneNEWLINENEWLINE# If true, '()' will be appended to :func: etc. cross-reference text.NEWLINE# add_function_parentheses = TrueNEWLINENEWLINE# If true, the current module name will be prepended to all descriptionNEWLINE# unit titles (such as .. function::).NEWLINE# add_module_names = TrueNEWLINENEWLINE# If true, sectionauthor and moduleauthor directives will be shown in theNEWLINE# output. They are ignored by default.NEWLINE# show_authors = FalseNEWLINENEWLINE# The name of the Pygments (syntax highlighting) style to use.NEWLINEpygments_style = 'sphinx'NEWLINENEWLINE# A list of ignored prefixes for module index sorting.NEWLINE# modindex_common_prefix = []NEWLINENEWLINENEWLINE# -- Options for HTML output ---------------------------------------------------NEWLINENEWLINE# The theme to use for HTML and HTML Help pages. See the documentation forNEWLINE# a list of builtin themes.NEWLINEhtml_theme = 'default'NEWLINENEWLINE# Theme options are theme-specific and customize the look and feel of a themeNEWLINE# further. For a list of options available for each theme, see theNEWLINE# documentation.NEWLINE# html_theme_options = {}NEWLINENEWLINE# Add any paths that contain custom themes here, relative to this directory.NEWLINE# html_theme_path = []NEWLINENEWLINE# The name for this set of Sphinx documents. If None, it defaults toNEWLINE# " v documentation".NEWLINE# html_title = NoneNEWLINENEWLINE# A shorter title for the navigation bar. Default is the same as html_title.NEWLINE# html_short_title = NoneNEWLINENEWLINE# The name of an image file (relative to this directory) to place at the topNEWLINE# of the sidebar.NEWLINE# html_logo = NoneNEWLINENEWLINE# The name of an image file (within the static path) to use as favicon of theNEWLINE# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32NEWLINE# pixels large.NEWLINE# html_favicon = NoneNEWLINENEWLINE# Add any paths that contain custom static files (such as style sheets) here,NEWLINE# relative to this directory. They are copied after the builtin static files,NEWLINE# so a file named "default.css" will overwrite the builtin "default.css".NEWLINEhtml_static_path = ['_static']NEWLINENEWLINE# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,NEWLINE# using the given strftime format.NEWLINE# html_last_updated_fmt = '%b %d, %Y'NEWLINENEWLINE# If true, SmartyPants will be used to convert quotes and dashes toNEWLINE# typographically correct entities.NEWLINE# html_use_smartypants = TrueNEWLINENEWLINE# Custom sidebar templates, maps document names to template names.NEWLINE# html_sidebars = {}NEWLINENEWLINE# Additional templates that should be rendered to pages, maps page names toNEWLINE# template names.NEWLINE# html_additional_pages = {}NEWLINENEWLINE# If false, no module index is generated.NEWLINE# html_domain_indices = TrueNEWLINENEWLINE# If false, no index is generated.NEWLINE# html_use_index = TrueNEWLINENEWLINE# If true, the index is split into individual pages for each letter.NEWLINE# html_split_index = FalseNEWLINENEWLINE# If true, links to the reST sources are added to the pages.NEWLINE# html_show_sourcelink = TrueNEWLINENEWLINE# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.NEWLINE# html_show_sphinx = TrueNEWLINENEWLINE# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.NEWLINE# html_show_copyright = TrueNEWLINENEWLINE# If true, an OpenSearch description file will be output, and all pages willNEWLINE# contain a tag referring to it. The value of this option must be theNEWLINE# base URL from which the finished HTML is served.NEWLINE# html_use_opensearch = ''NEWLINENEWLINE# This is the file name suffix for HTML files (e.g. ".xhtml").NEWLINE# html_file_suffix = NoneNEWLINENEWLINE# Output file base name for HTML help builder.NEWLINEhtmlhelp_basename = 'dengueaidoc'NEWLINENEWLINENEWLINE# -- Options for LaTeX output --------------------------------------------------NEWLINENEWLINElatex_elements = {NEWLINE # The paper size ('letterpaper' or 'a4paper').NEWLINE # 'papersize': 'letterpaper',NEWLINENEWLINE # The font size ('10pt', '11pt' or '12pt').NEWLINE # 'pointsize': '10pt',NEWLINENEWLINE # Additional stuff for the LaTeX preamble.NEWLINE # 'preamble': '',NEWLINE}NEWLINENEWLINE# Grouping the document tree into LaTeX files. List of tuplesNEWLINE# (source start file, target name, title, author, documentclass [howto/manual]).NEWLINElatex_documents = [NEWLINE ('index',NEWLINE 'dengueai.tex',NEWLINE u'dengueAI Documentation',NEWLINE u"John Keating", 'manual'),NEWLINE]NEWLINENEWLINE# The name of an image file (relative to this directory) to place at the top ofNEWLINE# the title page.NEWLINE# latex_logo = NoneNEWLINENEWLINE# For "manual" documents, if this is true, then toplevel headings are parts,NEWLINE# not chapters.NEWLINE# latex_use_parts = FalseNEWLINENEWLINE# If true, show page references after internal links.NEWLINE# latex_show_pagerefs = FalseNEWLINENEWLINE# If true, show URL addresses after external links.NEWLINE# latex_show_urls = FalseNEWLINENEWLINE# Documents to append as an appendix to all manuals.NEWLINE# latex_appendices = []NEWLINENEWLINE# If false, no module index is generated.NEWLINE# latex_domain_indices = TrueNEWLINENEWLINENEWLINE# -- Options for manual page output --------------------------------------------NEWLINENEWLINE# One entry per manual page. List of tuplesNEWLINE# (source start file, name, description, authors, manual section).NEWLINEman_pages = [NEWLINE ('index', 'dengueai', u'dengueAI Documentation',NEWLINE [u"John Keating"], 1)NEWLINE]NEWLINENEWLINE# If true, show URL addresses after external links.NEWLINE# man_show_urls = FalseNEWLINENEWLINENEWLINE# -- Options for Texinfo output ------------------------------------------------NEWLINENEWLINE# Grouping the document tree into Texinfo files. List of tuplesNEWLINE# (source start file, target name, title, author,NEWLINE# dir menu entry, description, category)NEWLINEtexinfo_documents = [NEWLINE ('index', 'dengueai', u'dengueAI Documentation',NEWLINE u"John Keating", 'dengueAI',NEWLINE 'DengueAI is a DrivenData competition designed to find a means of predicting the spread of Dengue Fever/', 'Miscellaneous'),NEWLINE]NEWLINENEWLINE# Documents to append as an appendix to all manuals.NEWLINE# texinfo_appendices = []NEWLINENEWLINE# If false, no module index is generated.NEWLINE# texinfo_domain_indices = TrueNEWLINENEWLINE# How to display URL addresses: 'footnote', 'no', or 'inline'.NEWLINE# texinfo_show_urls = 'footnote'NEWLINE # Licensed to the Apache Software Foundation (ASF) under one or moreNEWLINE# contributor license agreements. See the NOTICE file distributed withNEWLINE# this work for additional information regarding copyright ownership.NEWLINE# The ASF licenses this file to You under the Apache License, Version 2.0NEWLINE# (the "License"); you may not use this file except in compliance withNEWLINE# the License. You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINEimport reNEWLINEimport sysNEWLINEfrom setuptools import find_packages, setupNEWLINEfrom setuptools.command.test import test as TestCommandNEWLINENEWLINEversion = ''NEWLINEwith open('kafkatest/__init__.py', 'r') as fd:NEWLINE version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1)NEWLINENEWLINENEWLINEclass PyTest(TestCommand):NEWLINE user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]NEWLINENEWLINE def initialize_options(self):NEWLINE TestCommand.initialize_options(self)NEWLINE self.pytest_args = []NEWLINENEWLINE def finalize_options(self):NEWLINE TestCommand.finalize_options(self)NEWLINE self.test_args = []NEWLINE self.test_suite = TrueNEWLINENEWLINE def run_tests(self):NEWLINE # import here, cause outside the eggs aren't loadedNEWLINE import pytestNEWLINE print(self.pytest_args)NEWLINE errno = pytest.main(self.pytest_args)NEWLINE sys.exit(errno)NEWLINENEWLINE# Note: when changing the version of ducktape, also revise tests/docker/DockerfileNEWLINEsetup(name="kafkatest",NEWLINE version=version,NEWLINE description="Apache Kafka System Tests",NEWLINE author="Apache Kafka",NEWLINE platforms=["any"],NEWLINE license="apache2.0",NEWLINE packages=find_packages(),NEWLINE include_package_data=True,NEWLINE install_requires=["ducktape>0.8", "requests==2.24.0"],NEWLINE tests_require=["pytest", "mock"],NEWLINE cmdclass={'test': PyTest},NEWLINE zip_safe=FalseNEWLINE )NEWLINE # Time: O(n)NEWLINE# Space: O(k)NEWLINENEWLINEclass Solution:NEWLINE def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:NEWLINE """NEWLINE modified sliding window, using a mapNEWLINE """NEWLINENEWLINE if not s or not k:NEWLINE return 0NEWLINENEWLINE left = 0NEWLINE index = 0NEWLINE imap = collections.defaultdict(int)NEWLINE max_dist = float('-inf')NEWLINENEWLINE while indexk and left 5:NEWLINE from typing import TextIONEWLINEelse:NEWLINE from typing.io import TextIONEWLINENEWLINENEWLINENEWLINEdef serializedATN():NEWLINE with StringIO() as buf:NEWLINE buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\u008d")NEWLINE buf.write("\u072b\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7")NEWLINE buf.write("\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r")NEWLINE buf.write("\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23")NEWLINE buf.write("\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30")NEWLINE buf.write("\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36")NEWLINE buf.write("\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%")NEWLINE buf.write("\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t,\4-\t-\4.")NEWLINE buf.write("\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63\t\63\4\64")NEWLINE buf.write("\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\49\t9\4:\t:")NEWLINE buf.write("\4;\t;\4<\t<\4=\t=\4>\t>\4?\t?\4@\t@\4A\tA\4B\tB\4C\t")NEWLINE buf.write("C\4D\tD\4E\tE\4F\tF\4G\tG\4H\tH\4I\tI\4J\tJ\4K\tK\4L\t")NEWLINE buf.write("L\4M\tM\4N\tN\4O\tO\4P\tP\4Q\tQ\4R\tR\4S\tS\4T\tT\4U\t")NEWLINE buf.write("U\4V\tV\4W\tW\4X\tX\4Y\tY\4Z\tZ\4[\t[\4\\\t\\\4]\t]\4")NEWLINE buf.write("^\t^\4_\t_\4`\t`\4a\ta\4b\tb\4c\tc\4d\td\4e\te\4f\tf\4")NEWLINE buf.write("g\tg\4h\th\4i\ti\4j\tj\4k\tk\4l\tl\4m\tm\4n\tn\4o\to\4")NEWLINE buf.write("p\tp\4q\tq\4r\tr\4s\ts\4t\tt\4u\tu\4v\tv\4w\tw\4x\tx\4")NEWLINE buf.write("y\ty\4z\tz\4{\t{\4|\t|\4}\t}\4~\t~\4\177\t\177\4\u0080")NEWLINE buf.write("\t\u0080\4\u0081\t\u0081\4\u0082\t\u0082\4\u0083\t\u0083")NEWLINE buf.write("\4\u0084\t\u0084\4\u0085\t\u0085\4\u0086\t\u0086\4\u0087")NEWLINE buf.write("\t\u0087\4\u0088\t\u0088\4\u0089\t\u0089\4\u008a\t\u008a")NEWLINE buf.write("\4\u008b\t\u008b\4\u008c\t\u008c\4\u008d\t\u008d\4\u008e")NEWLINE buf.write("\t\u008e\4\u008f\t\u008f\4\u0090\t\u0090\4\u0091\t\u0091")NEWLINE buf.write("\4\u0092\t\u0092\4\u0093\t\u0093\4\u0094\t\u0094\4\u0095")NEWLINE buf.write("\t\u0095\3\2\3\2\3\2\3\2\3\3\3\3\7\3\u0132\n\3\f\3\16")NEWLINE buf.write("\3\u0135\13\3\3\3\3\3\3\4\3\4\3\5\3\5\3\6\3\6\3\7\3\7")NEWLINE buf.write("\3\7\7\7\u0142\n\7\f\7\16\7\u0145\13\7\3\7\3\7\3\b\3\b")NEWLINE buf.write("\3\b\7\b\u014c\n\b\f\b\16\b\u014f\13\b\3\b\3\b\3\t\3\t")NEWLINE buf.write("\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3")NEWLINE buf.write("\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\5\t\u016a\n\t\3\n\3\n\3")NEWLINE buf.write("\n\3\n\3\13\3\13\3\13\3\13\3\13\3\f\3\f\3\f\3\f\3\r\3")NEWLINE buf.write("\r\3\r\3\r\3\r\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16")NEWLINE buf.write("\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16")NEWLINE buf.write("\3\16\3\17\3\17\3\17\3\17\3\17\3\17\3\20\3\20\3\20\3\20")NEWLINE buf.write("\3\20\3\20\3\21\3\21\3\21\3\21\3\21\3\21\3\21\3\21\3\21")NEWLINE buf.write("\3\21\3\21\3\21\3\21\3\21\3\21\3\22\3\22\3\22\3\22\3\22")NEWLINE buf.write("\3\22\3\22\3\22\3\22\3\22\3\22\3\23\3\23\3\23\3\23\3\23")NEWLINE buf.write("\3\23\3\24\3\24\3\24\3\24\3\24\3\24\3\24\3\25\3\25\3\25")NEWLINE buf.write("\3\25\3\26\3\26\3\26\3\26\3\26\3\26\3\26\3\26\3\27\3\27")NEWLINE buf.write("\3\27\3\27\3\27\3\27\3\27\3\30\3\30\3\30\3\30\3\30\3\31")NEWLINE buf.write("\3\31\3\31\3\31\3\31\3\31\3\31\3\31\3\32\3\32\3\32\3\32")NEWLINE buf.write("\3\32\3\32\3\32\3\32\3\32\3\32\3\32\3\32\3\33\3\33\3\33")NEWLINE buf.write("\3\33\3\33\3\33\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\35")NEWLINE buf.write("\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35")NEWLINE buf.write("\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3\37\3\37")NEWLINE buf.write("\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3 \3 \3 \3 \3")NEWLINE buf.write(" \3 \3 \3 \3 \3 \3 \3 \3 \3 \3 \3 \3 \3 \3 \3!\3!\3!\3")NEWLINE buf.write("!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3\"\3\"\3\"\3\"")NEWLINE buf.write("\3\"\3\"\3\"\3#\3#\3#\3#\3#\3#\3#\3#\3#\3$\3$\3$\3$\3")NEWLINE buf.write("$\3$\3$\3$\3$\3%\3%\3%\3%\3%\3%\3%\3%\3%\3%\3%\3%\3%\3")NEWLINE buf.write("%\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3")NEWLINE buf.write("\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'")NEWLINE buf.write("\3\'\3\'\3\'\3\'\3\'\3(\3(\3(\3(\3(\3(\3(\3(\3(\3(\3(")NEWLINE buf.write("\3(\3(\3(\3(\3(\3(\3(\3)\3)\3)\3)\3)\3)\3)\3)\3)\3)\3")NEWLINE buf.write(")\3)\3)\3)\3)\3)\3)\3)\3)\3)\3*\3*\3*\3*\3*\3*\3*\3*\3")NEWLINE buf.write("*\3*\3*\3*\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3,\3")NEWLINE buf.write(",\3,\3,\3,\3,\3,\3-\3-\3-\3-\3-\3-\3-\3-\3-\3-\3-\3.\3")NEWLINE buf.write(".\3.\3.\3.\3.\3.\3.\3.\3.\3.\3.\3.\3/\3/\3/\3/\3/\3/\3")NEWLINE buf.write("/\3/\3/\3/\3/\3/\3/\3/\3/\3\60\3\60\3\60\3\60\3\60\3\60")NEWLINE buf.write("\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\61")NEWLINE buf.write("\3\61\3\61\3\61\3\61\3\61\3\61\3\61\3\61\3\61\3\61\3\61")NEWLINE buf.write("\3\62\3\62\3\62\3\62\3\62\3\62\3\62\3\62\3\63\3\63\3\63")NEWLINE buf.write("\3\63\3\63\3\64\3\64\3\64\3\64\3\64\3\65\3\65\3\65\3\65")NEWLINE buf.write("\3\65\3\66\3\66\3\66\3\66\3\66\3\66\3\66\3\66\3\66\3\66")NEWLINE buf.write("\3\66\3\66\3\66\3\66\3\66\3\67\3\67\3\67\3\67\3\67\3\67")NEWLINE buf.write("\3\67\3\67\3\67\3\67\3\67\3\67\3\67\3\67\3\67\38\38\3")NEWLINE buf.write("8\38\38\38\38\38\38\38\38\38\38\38\38\39\39\39\39\39\3")NEWLINE buf.write("9\39\39\39\3:\3:\3:\3:\3:\3:\3:\3:\3:\3:\3;\3;\3;\3;\3")NEWLINE buf.write(";\3;\3;\3;\3;\3;\3;\3;\3<\3<\3<\3<\3<\3<\3<\3<\3<\3<\3")NEWLINE buf.write("<\3=\3=\3=\3=\3=\3=\3=\3=\3=\3=\3=\3=\3>\3>\3>\3>\3>\3")NEWLINE buf.write(">\3>\3>\3>\3>\3?\3?\3?\3?\3?\3?\3?\3?\3?\3?\3?\3?\3?\3")NEWLINE buf.write("?\3?\3?\3?\3?\3?\3?\3?\3?\3@\3@\3@\3@\3@\3@\3@\3@\3@\3")NEWLINE buf.write("@\3@\3@\3@\3@\3@\3A\3A\3A\3A\3A\3A\3A\3A\3A\3A\3B\3B\3")NEWLINE buf.write("B\3B\3C\3C\3C\3C\3C\3D\3D\3D\3D\3D\3D\3E\3E\3E\3E\3E\3")NEWLINE buf.write("E\3E\3E\3E\3E\3E\3E\3E\3E\3E\3E\3E\3F\3F\3F\3F\3F\3F\3")NEWLINE buf.write("F\3F\3F\3G\3G\3G\3G\3G\3G\3G\3G\3G\3G\3H\3H\3H\3H\3H\3")NEWLINE buf.write("H\3H\3H\3H\3H\3H\3I\3I\3I\3I\3I\3J\3J\3J\3J\3J\3J\3J\3")NEWLINE buf.write("J\3J\3K\3K\3K\3K\3K\3K\3K\3K\3K\3L\3L\3L\3L\3L\3L\3L\3")NEWLINE buf.write("L\3M\3M\3M\3M\3M\3M\3M\3M\3M\3M\3M\3M\3N\3N\3N\3N\3N\3")NEWLINE buf.write("N\3N\3O\3O\3O\3O\3O\3O\3O\3O\3P\3P\3P\3P\3P\3P\3P\3P\3")NEWLINE buf.write("P\3P\3P\3P\3P\3Q\3Q\3R\3R\3S\3S\3S\3T\3T\3T\3T\3T\3T\3")NEWLINE buf.write("T\3U\3U\3U\3U\3U\3U\3U\3U\3V\3V\3V\3V\3V\3V\3V\3W\3W\3")NEWLINE buf.write("W\3W\3W\3W\3W\3W\3W\3W\3W\3W\3X\3X\3X\3X\3X\3X\3X\3Y\3")NEWLINE buf.write("Y\3Y\3Y\3Z\3Z\3Z\3Z\3Z\3Z\3[\3[\3[\3[\3[\3[\3[\3[\3\\")NEWLINE buf.write("\3\\\3\\\3\\\3]\3]\3]\7]\u0495\n]\f]\16]\u0498\13]\5]")NEWLINE buf.write("\u049a\n]\3^\3^\3^\3^\6^\u04a0\n^\r^\16^\u04a1\3_\3_\3")NEWLINE buf.write("_\3_\6_\u04a8\n_\r_\16_\u04a9\3`\3`\3`\7`\u04af\n`\f`")NEWLINE buf.write("\16`\u04b2\13`\3`\3`\3a\3a\3b\3b\3c\3c\3d\3d\3e\3e\3f")NEWLINE buf.write("\3f\5f\u04c2\nf\3g\3g\5g\u04c6\ng\3h\3h\5h\u04ca\nh\3")NEWLINE buf.write("i\3i\3i\3j\3j\3k\3k\3k\3k\3k\3k\3k\3k\3k\3k\3k\3k\3k\3")NEWLINE buf.write("k\3k\3k\3l\3l\3l\3l\3l\3l\3l\3l\3l\3l\3l\3l\3l\3l\3l\3")NEWLINE buf.write("l\3l\3l\3l\3l\3l\3l\3l\3l\3m\3m\3m\3m\3m\3m\3m\3m\3m\3")NEWLINE buf.write("n\3n\3n\3n\3n\3n\3n\3n\3n\3n\3o\3o\3o\3o\3o\3o\3o\3o\3")NEWLINE buf.write("o\3o\3o\3p\3p\3p\3p\3p\3p\3p\3p\3p\3p\3p\3p\3q\3q\3q\3")NEWLINE buf.write("q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3")NEWLINE buf.write("q\3q\3q\3q\3q\3q\3r\3r\3r\3r\3r\3r\3r\3r\3r\3r\3r\3r\3")NEWLINE buf.write("r\3r\3r\3r\3s\3s\3s\3s\3s\3s\3s\3s\3s\3s\3s\3s\3t\3t\3")NEWLINE buf.write("t\3t\3t\3t\3u\3u\3u\3u\3u\3u\3u\3u\3u\3u\3u\3u\3u\3u\3")NEWLINE buf.write("u\3u\3u\3u\3v\3v\3v\3v\3v\3v\3v\3v\3v\3v\3v\3v\3v\3v\3")NEWLINE buf.write("v\3v\3v\3v\3v\3v\3v\3w\3w\3w\3w\3w\3w\3w\3w\3w\3w\3w\3")NEWLINE buf.write("w\3w\3w\3w\3w\3w\3w\3x\3x\3x\3x\3x\3x\3x\3x\3x\3x\3y\3")NEWLINE buf.write("y\3y\3y\3y\3y\3y\3y\3y\3y\3y\3y\3z\3z\3z\3z\3z\3z\3z\3")NEWLINE buf.write("z\3z\3{\3{\3{\3{\3{\3{\3{\3|\3|\3|\3|\3|\3|\3}\3}\3}\3")NEWLINE buf.write("}\3}\3}\3}\3~\3~\3~\3~\3~\3~\3~\3~\3~\3\177\3\177\3\177")NEWLINE buf.write("\3\177\3\177\3\177\3\177\3\177\3\177\3\177\3\177\3\177")NEWLINE buf.write("\3\177\3\177\3\177\3\u0080\3\u0080\3\u0080\3\u0080\3\u0080")NEWLINE buf.write("\3\u0080\3\u0080\3\u0080\3\u0080\3\u0080\3\u0080\3\u0080")NEWLINE buf.write("\3\u0080\3\u0080\3\u0080\3\u0080\3\u0080\3\u0080\3\u0080")NEWLINE buf.write("\3\u0080\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081")NEWLINE buf.write("\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081")NEWLINE buf.write("\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081")NEWLINE buf.write("\3\u0081\3\u0082\3\u0082\3\u0082\3\u0082\3\u0082\3\u0082")NEWLINE buf.write("\3\u0082\3\u0082\3\u0082\3\u0082\3\u0082\3\u0082\3\u0082")NEWLINE buf.write("\3\u0082\3\u0082\3\u0082\3\u0083\3\u0083\3\u0083\3\u0083")NEWLINE buf.write("\3\u0083\3\u0083\3\u0083\3\u0083\3\u0083\3\u0083\3\u0083")NEWLINE buf.write("\3\u0083\3\u0083\3\u0083\3\u0083\3\u0083\3\u0084\3\u0084")NEWLINE buf.write("\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084")NEWLINE buf.write("\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084")NEWLINE buf.write("\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084")NEWLINE buf.write("\3\u0084\3\u0084\3\u0084\3\u0084\3\u0085\3\u0085\3\u0085")NEWLINE buf.write("\3\u0085\3\u0085\3\u0085\3\u0085\3\u0085\3\u0085\3\u0085")NEWLINE buf.write("\3\u0085\3\u0085\3\u0085\3\u0085\3\u0085\3\u0085\3\u0085")NEWLINE buf.write("\3\u0085\3\u0085\3\u0085\3\u0085\3\u0086\3\u0086\3\u0086")NEWLINE buf.write("\3\u0086\3\u0086\3\u0086\3\u0086\3\u0086\3\u0086\3\u0086")NEWLINE buf.write("\3\u0086\3\u0086\3\u0086\3\u0087\3\u0087\3\u0087\3\u0087")NEWLINE buf.write("\3\u0087\3\u0087\3\u0087\3\u0087\3\u0087\3\u0087\3\u0087")NEWLINE buf.write("\3\u0087\3\u0087\3\u0087\3\u0087\3\u0087\3\u0088\3\u0088")NEWLINE buf.write("\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088")NEWLINE buf.write("\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088")NEWLINE buf.write("\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088")NEWLINE buf.write("\3\u0088\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089")NEWLINE buf.write("\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089")NEWLINE buf.write("\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089")NEWLINE buf.write("\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089")NEWLINE buf.write("\3\u0089\3\u0089\3\u008a\3\u008a\3\u008a\3\u008a\3\u008a")NEWLINE buf.write("\3\u008a\3\u008a\3\u008a\3\u008a\3\u008a\3\u008a\3\u008a")NEWLINE buf.write("\3\u008a\3\u008b\3\u008b\3\u008b\3\u008b\3\u008b\3\u008b")NEWLINE buf.write("\3\u008b\3\u008b\3\u008b\3\u008b\3\u008b\3\u008b\3\u008b")NEWLINE buf.write("\3\u008b\3\u008b\3\u008b\3\u008b\3\u008c\3\u008c\3\u008c")NEWLINE buf.write("\3\u008c\3\u008c\3\u008c\3\u008c\3\u008d\3\u008d\3\u008d")NEWLINE buf.write("\3\u008d\3\u008d\3\u008d\3\u008d\3\u008d\3\u008d\3\u008d")NEWLINE buf.write("\3\u008d\3\u008d\3\u008d\3\u008d\3\u008d\3\u008d\3\u008d")NEWLINE buf.write("\3\u008d\3\u008d\3\u008e\3\u008e\3\u008e\3\u008e\3\u008e")NEWLINE buf.write("\3\u008e\3\u008e\3\u008e\3\u008f\3\u008f\3\u008f\3\u008f")NEWLINE buf.write("\3\u008f\3\u008f\3\u008f\3\u008f\3\u0090\3\u0090\3\u0090")NEWLINE buf.write("\3\u0090\3\u0090\3\u0090\3\u0090\3\u0090\3\u0090\3\u0090")NEWLINE buf.write("\3\u0091\3\u0091\3\u0091\3\u0091\3\u0091\3\u0091\3\u0091")NEWLINE buf.write("\3\u0091\3\u0092\3\u0092\3\u0092\3\u0092\3\u0092\3\u0092")NEWLINE buf.write("\3\u0092\3\u0092\3\u0092\3\u0092\3\u0092\3\u0093\3\u0093")NEWLINE buf.write("\3\u0093\3\u0093\3\u0093\3\u0093\3\u0093\3\u0093\3\u0093")NEWLINE buf.write("\3\u0094\3\u0094\3\u0094\7\u0094\u0720\n\u0094\f\u0094")NEWLINE buf.write("\16\u0094\u0723\13\u0094\3\u0095\6\u0095\u0726\n\u0095")NEWLINE buf.write("\r\u0095\16\u0095\u0727\3\u0095\3\u0095\2\2\u0096\3\3")NEWLINE buf.write("\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16")NEWLINE buf.write("\33\17\35\20\37\21!\22#\23%\24\'\25)\26+\27-\30/\31\61")NEWLINE buf.write("\32\63\33\65\34\67\359\36;\37= ?!A\"C#E$G%I&K\'M(O)Q*")NEWLINE buf.write("S+U,W-Y.[/]\60_\61a\62c\63e\64g\65i\66k\67m8o9q:s;u{?}@\177A\u0081B\u0083C\u0085D\u0087E\u0089F\u008b")NEWLINE buf.write("G\u008dH\u008fI\u0091J\u0093K\u0095L\u0097M\u0099N\u009b")NEWLINE buf.write("O\u009dP\u009fQ\u00a1R\u00a3S\u00a5T\u00a7U\u00a9V\u00ab")NEWLINE buf.write("W\u00adX\u00afY\u00b1Z\u00b3[\u00b5\\\u00b7]\u00b9^\u00bb")NEWLINE buf.write("_\u00bd`\u00bfa\u00c1\2\u00c3b\u00c5\2\u00c7\2\u00c9\2")NEWLINE buf.write("\u00cb\2\u00cd\2\u00cf\2\u00d1\2\u00d3\2\u00d5c\u00d7")NEWLINE buf.write("d\u00d9e\u00dbf\u00ddg\u00dfh\u00e1i\u00e3j\u00e5k\u00e7")NEWLINE buf.write("l\u00e9m\u00ebn\u00edo\u00efp\u00f1q\u00f3r\u00f5s\u00f7")NEWLINE buf.write("t\u00f9u\u00fbv\u00fdw\u00ffx\u0101y\u0103z\u0105{\u0107")NEWLINE buf.write("|\u0109}\u010b~\u010d\177\u010f\u0080\u0111\u0081\u0113")NEWLINE buf.write("\u0082\u0115\u0083\u0117\u0084\u0119\u0085\u011b\u0086")NEWLINE buf.write("\u011d\u0087\u011f\u0088\u0121\u0089\u0123\u008a\u0125")NEWLINE buf.write("\u008b\u0127\u008c\u0129\u008d\3\2\f\4\2\f\f\17\17\3\2")NEWLINE buf.write("\63;\5\2\62;CHch\3\2\62;\20\2##&(,-/\61>\\`ac|\u0080\u0080")NEWLINE buf.write("\u00c6\u00c6\u00d8\u00d8\u00de\u00de\u00e6\u00e6\u00f8")NEWLINE buf.write("\u00f8\u00fe\u00fe\3\2\62\63\4\2\"\u0080\u0082\1\5\2\"")NEWLINE buf.write("#%\u0080\u0082\1\6\2\"]_}\177\u0080\u0082\1\5\2\13\f\17")NEWLINE buf.write("\17\"\"\2\u0733\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2")NEWLINE buf.write("\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21")NEWLINE buf.write("\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3")NEWLINE buf.write("\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\2\37\3\2\2\2\2!\3\2\2")NEWLINE buf.write("\2\2#\3\2\2\2\2%\3\2\2\2\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2")NEWLINE buf.write("\2\2\2-\3\2\2\2\2/\3\2\2\2\2\61\3\2\2\2\2\63\3\2\2\2\2")NEWLINE buf.write("\65\3\2\2\2\2\67\3\2\2\2\29\3\2\2\2\2;\3\2\2\2\2=\3\2")NEWLINE buf.write("\2\2\2?\3\2\2\2\2A\3\2\2\2\2C\3\2\2\2\2E\3\2\2\2\2G\3")NEWLINE buf.write("\2\2\2\2I\3\2\2\2\2K\3\2\2\2\2M\3\2\2\2\2O\3\2\2\2\2Q")NEWLINE buf.write("\3\2\2\2\2S\3\2\2\2\2U\3\2\2\2\2W\3\2\2\2\2Y\3\2\2\2\2")NEWLINE buf.write("[\3\2\2\2\2]\3\2\2\2\2_\3\2\2\2\2a\3\2\2\2\2c\3\2\2\2")NEWLINE buf.write("\2e\3\2\2\2\2g\3\2\2\2\2i\3\2\2\2\2k\3\2\2\2\2m\3\2\2")NEWLINE buf.write("\2\2o\3\2\2\2\2q\3\2\2\2\2s\3\2\2\2\2u\3\2\2\2\2w\3\2")NEWLINE buf.write("\2\2\2y\3\2\2\2\2{\3\2\2\2\2}\3\2\2\2\2\177\3\2\2\2\2")NEWLINE buf.write("\u0081\3\2\2\2\2\u0083\3\2\2\2\2\u0085\3\2\2\2\2\u0087")NEWLINE buf.write("\3\2\2\2\2\u0089\3\2\2\2\2\u008b\3\2\2\2\2\u008d\3\2\2")NEWLINE buf.write("\2\2\u008f\3\2\2\2\2\u0091\3\2\2\2\2\u0093\3\2\2\2\2\u0095")NEWLINE buf.write("\3\2\2\2\2\u0097\3\2\2\2\2\u0099\3\2\2\2\2\u009b\3\2\2")NEWLINE buf.write("\2\2\u009d\3\2\2\2\2\u009f\3\2\2\2\2\u00a1\3\2\2\2\2\u00a3")NEWLINE buf.write("\3\2\2\2\2\u00a5\3\2\2\2\2\u00a7\3\2\2\2\2\u00a9\3\2\2")NEWLINE buf.write("\2\2\u00ab\3\2\2\2\2\u00ad\3\2\2\2\2\u00af\3\2\2\2\2\u00b1")NEWLINE buf.write("\3\2\2\2\2\u00b3\3\2\2\2\2\u00b5\3\2\2\2\2\u00b7\3\2\2")NEWLINE buf.write("\2\2\u00b9\3\2\2\2\2\u00bb\3\2\2\2\2\u00bd\3\2\2\2\2\u00bf")NEWLINE buf.write("\3\2\2\2\2\u00c3\3\2\2\2\2\u00d5\3\2\2\2\2\u00d7\3\2\2")NEWLINE buf.write("\2\2\u00d9\3\2\2\2\2\u00db\3\2\2\2\2\u00dd\3\2\2\2\2\u00df")NEWLINE buf.write("\3\2\2\2\2\u00e1\3\2\2\2\2\u00e3\3\2\2\2\2\u00e5\3\2\2")NEWLINE buf.write("\2\2\u00e7\3\2\2\2\2\u00e9\3\2\2\2\2\u00eb\3\2\2\2\2\u00ed")NEWLINE buf.write("\3\2\2\2\2\u00ef\3\2\2\2\2\u00f1\3\2\2\2\2\u00f3\3\2\2")NEWLINE buf.write("\2\2\u00f5\3\2\2\2\2\u00f7\3\2\2\2\2\u00f9\3\2\2\2\2\u00fb")NEWLINE buf.write("\3\2\2\2\2\u00fd\3\2\2\2\2\u00ff\3\2\2\2\2\u0101\3\2\2")NEWLINE buf.write("\2\2\u0103\3\2\2\2\2\u0105\3\2\2\2\2\u0107\3\2\2\2\2\u0109")NEWLINE buf.write("\3\2\2\2\2\u010b\3\2\2\2\2\u010d\3\2\2\2\2\u010f\3\2\2")NEWLINE buf.write("\2\2\u0111\3\2\2\2\2\u0113\3\2\2\2\2\u0115\3\2\2\2\2\u0117")NEWLINE buf.write("\3\2\2\2\2\u0119\3\2\2\2\2\u011b\3\2\2\2\2\u011d\3\2\2")NEWLINE buf.write("\2\2\u011f\3\2\2\2\2\u0121\3\2\2\2\2\u0123\3\2\2\2\2\u0125")NEWLINE buf.write("\3\2\2\2\2\u0127\3\2\2\2\2\u0129\3\2\2\2\3\u012b\3\2\2")NEWLINE buf.write("\2\5\u012f\3\2\2\2\7\u0138\3\2\2\2\t\u013a\3\2\2\2\13")NEWLINE buf.write("\u013c\3\2\2\2\r\u013e\3\2\2\2\17\u0148\3\2\2\2\21\u0169")NEWLINE buf.write("\3\2\2\2\23\u016b\3\2\2\2\25\u016f\3\2\2\2\27\u0174\3")NEWLINE buf.write("\2\2\2\31\u0178\3\2\2\2\33\u017d\3\2\2\2\35\u0191\3\2")NEWLINE buf.write("\2\2\37\u0197\3\2\2\2!\u019d\3\2\2\2#\u01ac\3\2\2\2%\u01b7")NEWLINE buf.write("\3\2\2\2\'\u01bd\3\2\2\2)\u01c4\3\2\2\2+\u01c8\3\2\2\2")NEWLINE buf.write("-\u01d0\3\2\2\2/\u01d7\3\2\2\2\61\u01dc\3\2\2\2\63\u01e4")NEWLINE buf.write("\3\2\2\2\65\u01f0\3\2\2\2\67\u01f6\3\2\2\29\u01fd\3\2")NEWLINE buf.write("\2\2;\u0209\3\2\2\2=\u0212\3\2\2\2?\u021c\3\2\2\2A\u022f")NEWLINE buf.write("\3\2\2\2C\u023f\3\2\2\2E\u0246\3\2\2\2G\u024f\3\2\2\2")NEWLINE buf.write("I\u0258\3\2\2\2K\u0266\3\2\2\2M\u0277\3\2\2\2O\u028a\3")NEWLINE buf.write("\2\2\2Q\u029c\3\2\2\2S\u02b0\3\2\2\2U\u02bc\3\2\2\2W\u02c9")NEWLINE buf.write("\3\2\2\2Y\u02d0\3\2\2\2[\u02db\3\2\2\2]\u02e8\3\2\2\2")NEWLINE buf.write("_\u02f7\3\2\2\2a\u0307\3\2\2\2c\u0313\3\2\2\2e\u031b\3")NEWLINE buf.write("\2\2\2g\u0320\3\2\2\2i\u0325\3\2\2\2k\u032a\3\2\2\2m\u0339")NEWLINE buf.write("\3\2\2\2o\u0348\3\2\2\2q\u0357\3\2\2\2s\u0360\3\2\2\2")NEWLINE buf.write("u\u036a\3\2\2\2w\u0376\3\2\2\2y\u0381\3\2\2\2{\u038d\3")NEWLINE buf.write("\2\2\2}\u0397\3\2\2\2\177\u03ad\3\2\2\2\u0081\u03bc\3")NEWLINE buf.write("\2\2\2\u0083\u03c6\3\2\2\2\u0085\u03ca\3\2\2\2\u0087\u03cf")NEWLINE buf.write("\3\2\2\2\u0089\u03d5\3\2\2\2\u008b\u03e6\3\2\2\2\u008d")NEWLINE buf.write("\u03ef\3\2\2\2\u008f\u03f9\3\2\2\2\u0091\u0404\3\2\2\2")NEWLINE buf.write("\u0093\u0409\3\2\2\2\u0095\u0412\3\2\2\2\u0097\u041b\3")NEWLINE buf.write("\2\2\2\u0099\u0423\3\2\2\2\u009b\u042f\3\2\2\2\u009d\u0436")NEWLINE buf.write("\3\2\2\2\u009f\u043e\3\2\2\2\u00a1\u044b\3\2\2\2\u00a3")NEWLINE buf.write("\u044d\3\2\2\2\u00a5\u044f\3\2\2\2\u00a7\u0452\3\2\2\2")NEWLINE buf.write("\u00a9\u0459\3\2\2\2\u00ab\u0461\3\2\2\2\u00ad\u0468\3")NEWLINE buf.write("\2\2\2\u00af\u0474\3\2\2\2\u00b1\u047b\3\2\2\2\u00b3\u047f")NEWLINE buf.write("\3\2\2\2\u00b5\u0485\3\2\2\2\u00b7\u048d\3\2\2\2\u00b9")NEWLINE buf.write("\u0499\3\2\2\2\u00bb\u049b\3\2\2\2\u00bd\u04a3\3\2\2\2")NEWLINE buf.write("\u00bf\u04ab\3\2\2\2\u00c1\u04b5\3\2\2\2\u00c3\u04b7\3")NEWLINE buf.write("\2\2\2\u00c5\u04b9\3\2\2\2\u00c7\u04bb\3\2\2\2\u00c9\u04bd")NEWLINE buf.write("\3\2\2\2\u00cb\u04c1\3\2\2\2\u00cd\u04c5\3\2\2\2\u00cf")NEWLINE buf.write("\u04c9\3\2\2\2\u00d1\u04cb\3\2\2\2\u00d3\u04ce\3\2\2\2")NEWLINE buf.write("\u00d5\u04d0\3\2\2\2\u00d7\u04e0\3\2\2\2\u00d9\u04f8\3")NEWLINE buf.write("\2\2\2\u00db\u0501\3\2\2\2\u00dd\u050b\3\2\2\2\u00df\u0516")NEWLINE buf.write("\3\2\2\2\u00e1\u0522\3\2\2\2\u00e3\u053d\3\2\2\2\u00e5")NEWLINE buf.write("\u054d\3\2\2\2\u00e7\u0559\3\2\2\2\u00e9\u055f\3\2\2\2")NEWLINE buf.write("\u00eb\u0571\3\2\2\2\u00ed\u0586\3\2\2\2\u00ef\u0598\3")NEWLINE buf.write("\2\2\2\u00f1\u05a2\3\2\2\2\u00f3\u05ae\3\2\2\2\u00f5\u05b7")NEWLINE buf.write("\3\2\2\2\u00f7\u05be\3\2\2\2\u00f9\u05c4\3\2\2\2\u00fb")NEWLINE buf.write("\u05cb\3\2\2\2\u00fd\u05d4\3\2\2\2\u00ff\u05e3\3\2\2\2")NEWLINE buf.write("\u0101\u05f7\3\2\2\2\u0103\u060c\3\2\2\2\u0105\u061c\3")NEWLINE buf.write("\2\2\2\u0107\u062c\3\2\2\2\u0109\u0647\3\2\2\2\u010b\u065c")NEWLINE buf.write("\3\2\2\2\u010d\u0669\3\2\2\2\u010f\u0679\3\2\2\2\u0111")NEWLINE buf.write("\u0691\3\2\2\2\u0113\u06ae\3\2\2\2\u0115\u06bb\3\2\2\2")NEWLINE buf.write("\u0117\u06cc\3\2\2\2\u0119\u06d3\3\2\2\2\u011b\u06e6\3")NEWLINE buf.write("\2\2\2\u011d\u06ee\3\2\2\2\u011f\u06f6\3\2\2\2\u0121\u0700")NEWLINE buf.write("\3\2\2\2\u0123\u0708\3\2\2\2\u0125\u0713\3\2\2\2\u0127")NEWLINE buf.write("\u071c\3\2\2\2\u0129\u0725\3\2\2\2\u012b\u012c\7\"\2\2")NEWLINE buf.write("\u012c\u012d\7d\2\2\u012d\u012e\7x\2\2\u012e\4\3\2\2\2")NEWLINE buf.write("\u012f\u0133\5\13\6\2\u0130\u0132\n\2\2\2\u0131\u0130")NEWLINE buf.write("\3\2\2\2\u0132\u0135\3\2\2\2\u0133\u0131\3\2\2\2\u0133")NEWLINE buf.write("\u0134\3\2\2\2\u0134\u0136\3\2\2\2\u0135\u0133\3\2\2\2")NEWLINE buf.write("\u0136\u0137\b\3\2\2\u0137\6\3\2\2\2\u0138\u0139\7*\2")NEWLINE buf.write("\2\u0139\b\3\2\2\2\u013a\u013b\7+\2\2\u013b\n\3\2\2\2")NEWLINE buf.write("\u013c\u013d\7=\2\2\u013d\f\3\2\2\2\u013e\u0143\7$\2\2")NEWLINE buf.write("\u013f\u0142\5\u00cdg\2\u0140\u0142\5\u00d3j\2\u0141\u013f")NEWLINE buf.write("\3\2\2\2\u0141\u0140\3\2\2\2\u0142\u0145\3\2\2\2\u0143")NEWLINE buf.write("\u0141\3\2\2\2\u0143\u0144\3\2\2\2\u0144\u0146\3\2\2\2")NEWLINE buf.write("\u0145\u0143\3\2\2\2\u0146\u0147\7$\2\2\u0147\16\3\2\2")NEWLINE buf.write("\2\u0148\u014d\7~\2\2\u0149\u014c\5\u00cfh\2\u014a\u014c")NEWLINE buf.write("\5\u00d3j\2\u014b\u0149\3\2\2\2\u014b\u014a\3\2\2\2\u014c")NEWLINE buf.write("\u014f\3\2\2\2\u014d\u014b\3\2\2\2\u014d\u014e\3\2\2\2")NEWLINE buf.write("\u014e\u0150\3\2\2\2\u014f\u014d\3\2\2\2\u0150\u0151\7")NEWLINE buf.write("~\2\2\u0151\20\3\2\2\2\u0152\u0153\7t\2\2\u0153\u0154")NEWLINE buf.write("\7g\2\2\u0154\u0155\7\60\2\2\u0155\u0156\7p\2\2\u0156")NEWLINE buf.write("\u0157\7q\2\2\u0157\u0158\7p\2\2\u0158\u016a\7g\2\2\u0159")NEWLINE buf.write("\u015a\7t\2\2\u015a\u015b\7g\2\2\u015b\u015c\7\60\2\2")NEWLINE buf.write("\u015c\u015d\7c\2\2\u015d\u015e\7n\2\2\u015e\u016a\7n")NEWLINE buf.write("\2\2\u015f\u0160\7t\2\2\u0160\u0161\7g\2\2\u0161\u0162")NEWLINE buf.write("\7\60\2\2\u0162\u0163\7c\2\2\u0163\u0164\7n\2\2\u0164")NEWLINE buf.write("\u0165\7n\2\2\u0165\u0166\7e\2\2\u0166\u0167\7j\2\2\u0167")NEWLINE buf.write("\u0168\7c\2\2\u0168\u016a\7t\2\2\u0169\u0152\3\2\2\2\u0169")NEWLINE buf.write("\u0159\3\2\2\2\u0169\u015f\3\2\2\2\u016a\22\3\2\2\2\u016b")NEWLINE buf.write("\u016c\7p\2\2\u016c\u016d\7q\2\2\u016d\u016e\7v\2\2\u016e")NEWLINE buf.write("\24\3\2\2\2\u016f\u0170\7D\2\2\u0170\u0171\7q\2\2\u0171")NEWLINE buf.write("\u0172\7q\2\2\u0172\u0173\7n\2\2\u0173\26\3\2\2\2\u0174")NEWLINE buf.write("\u0175\7K\2\2\u0175\u0176\7p\2\2\u0176\u0177\7v\2\2\u0177")NEWLINE buf.write("\30\3\2\2\2\u0178\u0179\7T\2\2\u0179\u017a\7g\2\2\u017a")NEWLINE buf.write("\u017b\7c\2\2\u017b\u017c\7n\2\2\u017c\32\3\2\2\2\u017d")NEWLINE buf.write("\u017e\7e\2\2\u017e\u017f\7q\2\2\u017f\u0180\7p\2\2\u0180")NEWLINE buf.write("\u0181\7v\2\2\u0181\u0182\7k\2\2\u0182\u0183\7p\2\2\u0183")NEWLINE buf.write("\u0184\7w\2\2\u0184\u0185\7g\2\2\u0185\u0186\7f\2\2\u0186")NEWLINE buf.write("\u0187\7/\2\2\u0187\u0188\7g\2\2\u0188\u0189\7z\2\2\u0189")NEWLINE buf.write("\u018a\7g\2\2\u018a\u018b\7e\2\2\u018b\u018c\7w\2\2\u018c")NEWLINE buf.write("\u018d\7v\2\2\u018d\u018e\7k\2\2\u018e\u018f\7q\2\2\u018f")NEWLINE buf.write("\u0190\7p\2\2\u0190\34\3\2\2\2\u0191\u0192\7g\2\2\u0192")NEWLINE buf.write("\u0193\7t\2\2\u0193\u0194\7t\2\2\u0194\u0195\7q\2\2\u0195")NEWLINE buf.write("\u0196\7t\2\2\u0196\36\3\2\2\2\u0197\u0198\7h\2\2\u0198")NEWLINE buf.write("\u0199\7c\2\2\u0199\u019a\7n\2\2\u019a\u019b\7u\2\2\u019b")NEWLINE buf.write("\u019c\7g\2\2\u019c \3\2\2\2\u019d\u019e\7k\2\2\u019e")NEWLINE buf.write("\u019f\7o\2\2\u019f\u01a0\7o\2\2\u01a0\u01a1\7g\2\2\u01a1")NEWLINE buf.write("\u01a2\7f\2\2\u01a2\u01a3\7k\2\2\u01a3\u01a4\7c\2\2\u01a4")NEWLINE buf.write("\u01a5\7v\2\2\u01a5\u01a6\7g\2\2\u01a6\u01a7\7/\2\2\u01a7")NEWLINE buf.write("\u01a8\7g\2\2\u01a8\u01a9\7z\2\2\u01a9\u01aa\7k\2\2\u01aa")NEWLINE buf.write("\u01ab\7v\2\2\u01ab\"\3\2\2\2\u01ac\u01ad\7k\2\2\u01ad")NEWLINE buf.write("\u01ae\7p\2\2\u01ae\u01af\7e\2\2\u01af\u01b0\7q\2\2\u01b0")NEWLINE buf.write("\u01b1\7o\2\2\u01b1\u01b2\7r\2\2\u01b2\u01b3\7n\2\2\u01b3")NEWLINE buf.write("\u01b4\7g\2\2\u01b4\u01b5\7v\2\2\u01b5\u01b6\7g\2\2\u01b6")NEWLINE buf.write("$\3\2\2\2\u01b7\u01b8\7n\2\2\u01b8\u01b9\7q\2\2\u01b9")NEWLINE buf.write("\u01ba\7i\2\2\u01ba\u01bb\7k\2\2\u01bb\u01bc\7e\2\2\u01bc")NEWLINE buf.write("&\3\2\2\2\u01bd\u01be\7o\2\2\u01be\u01bf\7g\2\2\u01bf")NEWLINE buf.write("\u01c0\7o\2\2\u01c0\u01c1\7q\2\2\u01c1\u01c2\7w\2\2\u01c2")NEWLINE buf.write("\u01c3\7v\2\2\u01c3(\3\2\2\2\u01c4\u01c5\7u\2\2\u01c5")NEWLINE buf.write("\u01c6\7c\2\2\u01c6\u01c7\7v\2\2\u01c7*\3\2\2\2\u01c8")NEWLINE buf.write("\u01c9\7u\2\2\u01c9\u01ca\7w\2\2\u01ca\u01cb\7e\2\2\u01cb")NEWLINE buf.write("\u01cc\7e\2\2\u01cc\u01cd\7g\2\2\u01cd\u01ce\7u\2\2\u01ce")NEWLINE buf.write("\u01cf\7u\2\2\u01cf,\3\2\2\2\u01d0\u01d1\7v\2\2\u01d1")NEWLINE buf.write("\u01d2\7j\2\2\u01d2\u01d3\7g\2\2\u01d3\u01d4\7q\2\2\u01d4")NEWLINE buf.write("\u01d5\7t\2\2\u01d5\u01d6\7{\2\2\u01d6.\3\2\2\2\u01d7")NEWLINE buf.write("\u01d8\7v\2\2\u01d8\u01d9\7t\2\2\u01d9\u01da\7w\2\2\u01da")NEWLINE buf.write("\u01db\7g\2\2\u01db\60\3\2\2\2\u01dc\u01dd\7w\2\2\u01dd")NEWLINE buf.write("\u01de\7p\2\2\u01de\u01df\7m\2\2\u01df\u01e0\7p\2\2\u01e0")NEWLINE buf.write("\u01e1\7q\2\2\u01e1\u01e2\7y\2\2\u01e2\u01e3\7p\2\2\u01e3")NEWLINE buf.write("\62\3\2\2\2\u01e4\u01e5\7w\2\2\u01e5\u01e6\7p\2\2\u01e6")NEWLINE buf.write("\u01e7\7u\2\2\u01e7\u01e8\7w\2\2\u01e8\u01e9\7r\2\2\u01e9")NEWLINE buf.write("\u01ea\7r\2\2\u01ea\u01eb\7q\2\2\u01eb\u01ec\7t\2\2\u01ec")NEWLINE buf.write("\u01ed\7v\2\2\u01ed\u01ee\7g\2\2\u01ee\u01ef\7f\2\2\u01ef")NEWLINE buf.write("\64\3\2\2\2\u01f0\u01f1\7w\2\2\u01f1\u01f2\7p\2\2\u01f2")NEWLINE buf.write("\u01f3\7u\2\2\u01f3\u01f4\7c\2\2\u01f4\u01f5\7v\2\2\u01f5")NEWLINE buf.write("\66\3\2\2\2\u01f6\u01f7\7c\2\2\u01f7\u01f8\7u\2\2\u01f8")NEWLINE buf.write("\u01f9\7u\2\2\u01f9\u01fa\7g\2\2\u01fa\u01fb\7t\2\2\u01fb")NEWLINE buf.write("\u01fc\7v\2\2\u01fc8\3\2\2\2\u01fd\u01fe\7c\2\2\u01fe")NEWLINE buf.write("\u01ff\7u\2\2\u01ff\u0200\7u\2\2\u0200\u0201\7g\2\2\u0201")NEWLINE buf.write("\u0202\7t\2\2\u0202\u0203\7v\2\2\u0203\u0204\7/\2\2\u0204")NEWLINE buf.write("\u0205\7u\2\2\u0205\u0206\7q\2\2\u0206\u0207\7h\2\2\u0207")NEWLINE buf.write("\u0208\7v\2\2\u0208:\3\2\2\2\u0209\u020a\7u\2\2\u020a")NEWLINE buf.write("\u020b\7k\2\2\u020b\u020c\7o\2\2\u020c\u020d\7r\2\2\u020d")NEWLINE buf.write("\u020e\7n\2\2\u020e\u020f\7k\2\2\u020f\u0210\7h\2\2\u0210")NEWLINE buf.write("\u0211\7{\2\2\u0211<\3\2\2\2\u0212\u0213\7e\2\2\u0213")NEWLINE buf.write("\u0214\7j\2\2\u0214\u0215\7g\2\2\u0215\u0216\7e\2\2\u0216")NEWLINE buf.write("\u0217\7m\2\2\u0217\u0218\7/\2\2\u0218\u0219\7u\2\2\u0219")NEWLINE buf.write("\u021a\7c\2\2\u021a\u021b\7v\2\2\u021b>\3\2\2\2\u021c")NEWLINE buf.write("\u021d\7e\2\2\u021d\u021e\7j\2\2\u021e\u021f\7g\2\2\u021f")NEWLINE buf.write("\u0220\7e\2\2\u0220\u0221\7m\2\2\u0221\u0222\7/\2\2\u0222")NEWLINE buf.write("\u0223\7u\2\2\u0223\u0224\7c\2\2\u0224\u0225\7v\2\2\u0225")NEWLINE buf.write("\u0226\7/\2\2\u0226\u0227\7c\2\2\u0227\u0228\7u\2\2\u0228")NEWLINE buf.write("\u0229\7u\2\2\u0229\u022a\7w\2\2\u022a\u022b\7o\2\2\u022b")NEWLINE buf.write("\u022c\7k\2\2\u022c\u022d\7p\2\2\u022d\u022e\7i\2\2\u022e")NEWLINE buf.write("@\3\2\2\2\u022f\u0230\7e\2\2\u0230\u0231\7j\2\2\u0231")NEWLINE buf.write("\u0232\7g\2\2\u0232\u0233\7e\2\2\u0233\u0234\7m\2\2\u0234")NEWLINE buf.write("\u0235\7/\2\2\u0235\u0236\7u\2\2\u0236\u0237\7c\2\2\u0237")NEWLINE buf.write("\u0238\7v\2\2\u0238\u0239\7/\2\2\u0239\u023a\7w\2\2\u023a")NEWLINE buf.write("\u023b\7u\2\2\u023b\u023c\7k\2\2\u023c\u023d\7p\2\2\u023d")NEWLINE buf.write("\u023e\7i\2\2\u023eB\3\2\2\2\u023f\u0240\7n\2\2\u0240")NEWLINE buf.write("\u0241\7c\2\2\u0241\u0242\7d\2\2\u0242\u0243\7g\2\2\u0243")NEWLINE buf.write("\u0244\7n\2\2\u0244\u0245\7u\2\2\u0245D\3\2\2\2\u0246")NEWLINE buf.write("\u0247\7o\2\2\u0247\u0248\7k\2\2\u0248\u0249\7p\2\2\u0249")NEWLINE buf.write("\u024a\7k\2\2\u024a\u024b\7o\2\2\u024b\u024c\7k\2\2\u024c")NEWLINE buf.write("\u024d\7|\2\2\u024d\u024e\7g\2\2\u024eF\3\2\2\2\u024f")NEWLINE buf.write("\u0250\7o\2\2\u0250\u0251\7c\2\2\u0251\u0252\7z\2\2\u0252")NEWLINE buf.write("\u0253\7k\2\2\u0253\u0254\7o\2\2\u0254\u0255\7k\2\2\u0255")NEWLINE buf.write("\u0256\7|\2\2\u0256\u0257\7g\2\2\u0257H\3\2\2\2\u0258")NEWLINE buf.write("\u0259\7f\2\2\u0259\u025a\7g\2\2\u025a\u025b\7e\2\2\u025b")NEWLINE buf.write("\u025c\7n\2\2\u025c\u025d\7c\2\2\u025d\u025e\7t\2\2\u025e")NEWLINE buf.write("\u025f\7g\2\2\u025f\u0260\7/\2\2\u0260\u0261\7e\2\2\u0261")NEWLINE buf.write("\u0262\7q\2\2\u0262\u0263\7p\2\2\u0263\u0264\7u\2\2\u0264")NEWLINE buf.write("\u0265\7v\2\2\u0265J\3\2\2\2\u0266\u0267\7f\2\2\u0267")NEWLINE buf.write("\u0268\7g\2\2\u0268\u0269\7e\2\2\u0269\u026a\7n\2\2\u026a")NEWLINE buf.write("\u026b\7c\2\2\u026b\u026c\7t\2\2\u026c\u026d\7g\2\2\u026d")NEWLINE buf.write("\u026e\7/\2\2\u026e\u026f\7f\2\2\u026f\u0270\7c\2\2\u0270")NEWLINE buf.write("\u0271\7v\2\2\u0271\u0272\7c\2\2\u0272\u0273\7v\2\2\u0273")NEWLINE buf.write("\u0274\7{\2\2\u0274\u0275\7r\2\2\u0275\u0276\7g\2\2\u0276")NEWLINE buf.write("L\3\2\2\2\u0277\u0278\7f\2\2\u0278\u0279\7g\2\2\u0279")NEWLINE buf.write("\u027a\7e\2\2\u027a\u027b\7n\2\2\u027b\u027c\7c\2\2\u027c")NEWLINE buf.write("\u027d\7t\2\2\u027d\u027e\7g\2\2\u027e\u027f\7/\2\2\u027f")NEWLINE buf.write("\u0280\7e\2\2\u0280\u0281\7q\2\2\u0281\u0282\7f\2\2\u0282")NEWLINE buf.write("\u0283\7c\2\2\u0283\u0284\7v\2\2\u0284\u0285\7c\2\2\u0285")NEWLINE buf.write("\u0286\7v\2\2\u0286\u0287\7{\2\2\u0287\u0288\7r\2\2\u0288")NEWLINE buf.write("\u0289\7g\2\2\u0289N\3\2\2\2\u028a\u028b\7f\2\2\u028b")NEWLINE buf.write("\u028c\7g\2\2\u028c\u028d\7e\2\2\u028d\u028e\7n\2\2\u028e")NEWLINE buf.write("\u028f\7c\2\2\u028f\u0290\7t\2\2\u0290\u0291\7g\2\2\u0291")NEWLINE buf.write("\u0292\7/\2\2\u0292\u0293\7f\2\2\u0293\u0294\7c\2\2\u0294")NEWLINE buf.write("\u0295\7v\2\2\u0295\u0296\7c\2\2\u0296\u0297\7v\2\2\u0297")NEWLINE buf.write("\u0298\7{\2\2\u0298\u0299\7r\2\2\u0299\u029a\7g\2\2\u029a")NEWLINE buf.write("\u029b\7u\2\2\u029bP\3\2\2\2\u029c\u029d\7f\2\2\u029d")NEWLINE buf.write("\u029e\7g\2\2\u029e\u029f\7e\2\2\u029f\u02a0\7n\2\2\u02a0")NEWLINE buf.write("\u02a1\7c\2\2\u02a1\u02a2\7t\2\2\u02a2\u02a3\7g\2\2\u02a3")NEWLINE buf.write("\u02a4\7/\2\2\u02a4\u02a5\7e\2\2\u02a5\u02a6\7q\2\2\u02a6")NEWLINE buf.write("\u02a7\7f\2\2\u02a7\u02a8\7c\2\2\u02a8\u02a9\7v\2\2\u02a9")NEWLINE buf.write("\u02aa\7c\2\2\u02aa\u02ab\7v\2\2\u02ab\u02ac\7{\2\2\u02ac")NEWLINE buf.write("\u02ad\7r\2\2\u02ad\u02ae\7g\2\2\u02ae\u02af\7u\2\2\u02af")NEWLINE buf.write("R\3\2\2\2\u02b0\u02b1\7f\2\2\u02b1\u02b2\7g\2\2\u02b2")NEWLINE buf.write("\u02b3\7e\2\2\u02b3\u02b4\7n\2\2\u02b4\u02b5\7c\2\2\u02b5")NEWLINE buf.write("\u02b6\7t\2\2\u02b6\u02b7\7g\2\2\u02b7\u02b8\7/\2\2\u02b8")NEWLINE buf.write("\u02b9\7h\2\2\u02b9\u02ba\7w\2\2\u02ba\u02bb\7p\2\2\u02bb")NEWLINE buf.write("T\3\2\2\2\u02bc\u02bd\7f\2\2\u02bd\u02be\7g\2\2\u02be")NEWLINE buf.write("\u02bf\7e\2\2\u02bf\u02c0\7n\2\2\u02c0\u02c1\7c\2\2\u02c1")NEWLINE buf.write("\u02c2\7t\2\2\u02c2\u02c3\7g\2\2\u02c3\u02c4\7/\2\2\u02c4")NEWLINE buf.write("\u02c5\7u\2\2\u02c5\u02c6\7q\2\2\u02c6\u02c7\7t\2\2\u02c7")NEWLINE buf.write("\u02c8\7v\2\2\u02c8V\3\2\2\2\u02c9\u02ca\7f\2\2\u02ca")NEWLINE buf.write("\u02cb\7g\2\2\u02cb\u02cc\7h\2\2\u02cc\u02cd\7k\2\2\u02cd")NEWLINE buf.write("\u02ce\7p\2\2\u02ce\u02cf\7g\2\2\u02cfX\3\2\2\2\u02d0")NEWLINE buf.write("\u02d1\7f\2\2\u02d1\u02d2\7g\2\2\u02d2\u02d3\7h\2\2\u02d3")NEWLINE buf.write("\u02d4\7k\2\2\u02d4\u02d5\7p\2\2\u02d5\u02d6\7g\2\2\u02d6")NEWLINE buf.write("\u02d7\7/\2\2\u02d7\u02d8\7h\2\2\u02d8\u02d9\7w\2\2\u02d9")NEWLINE buf.write("\u02da\7p\2\2\u02daZ\3\2\2\2\u02db\u02dc\7f\2\2\u02dc")NEWLINE buf.write("\u02dd\7g\2\2\u02dd\u02de\7h\2\2\u02de\u02df\7k\2\2\u02df")NEWLINE buf.write("\u02e0\7p\2\2\u02e0\u02e1\7g\2\2\u02e1\u02e2\7/\2\2\u02e2")NEWLINE buf.write("\u02e3\7e\2\2\u02e3\u02e4\7q\2\2\u02e4\u02e5\7p\2\2\u02e5")NEWLINE buf.write("\u02e6\7u\2\2\u02e6\u02e7\7v\2\2\u02e7\\\3\2\2\2\u02e8")NEWLINE buf.write("\u02e9\7f\2\2\u02e9\u02ea\7g\2\2\u02ea\u02eb\7h\2\2\u02eb")NEWLINE buf.write("\u02ec\7k\2\2\u02ec\u02ed\7p\2\2\u02ed\u02ee\7g\2\2\u02ee")NEWLINE buf.write("\u02ef\7/\2\2\u02ef\u02f0\7h\2\2\u02f0\u02f1\7w\2\2\u02f1")NEWLINE buf.write("\u02f2\7p\2\2\u02f2\u02f3\7/\2\2\u02f3\u02f4\7t\2\2\u02f4")NEWLINE buf.write("\u02f5\7g\2\2\u02f5\u02f6\7e\2\2\u02f6^\3\2\2\2\u02f7")NEWLINE buf.write("\u02f8\7f\2\2\u02f8\u02f9\7g\2\2\u02f9\u02fa\7h\2\2\u02fa")NEWLINE buf.write("\u02fb\7k\2\2\u02fb\u02fc\7p\2\2\u02fc\u02fd\7g\2\2\u02fd")NEWLINE buf.write("\u02fe\7/\2\2\u02fe\u02ff\7h\2\2\u02ff\u0300\7w\2\2\u0300")NEWLINE buf.write("\u0301\7p\2\2\u0301\u0302\7u\2\2\u0302\u0303\7/\2\2\u0303")NEWLINE buf.write("\u0304\7t\2\2\u0304\u0305\7g\2\2\u0305\u0306\7e\2\2\u0306")NEWLINE buf.write("`\3\2\2\2\u0307\u0308\7f\2\2\u0308\u0309\7g\2\2\u0309")NEWLINE buf.write("\u030a\7h\2\2\u030a\u030b\7k\2\2\u030b\u030c\7p\2\2\u030c")NEWLINE buf.write("\u030d\7g\2\2\u030d\u030e\7/\2\2\u030e\u030f\7u\2\2\u030f")NEWLINE buf.write("\u0310\7q\2\2\u0310\u0311\7t\2\2\u0311\u0312\7v\2\2\u0312")NEWLINE buf.write("b\3\2\2\2\u0313\u0314\7f\2\2\u0314\u0315\7k\2\2\u0315")NEWLINE buf.write("\u0316\7u\2\2\u0316\u0317\7r\2\2\u0317\u0318\7n\2\2\u0318")NEWLINE buf.write("\u0319\7c\2\2\u0319\u031a\7{\2\2\u031ad\3\2\2\2\u031b")NEWLINE buf.write("\u031c\7g\2\2\u031c\u031d\7e\2\2\u031d\u031e\7j\2\2\u031e")NEWLINE buf.write("\u031f\7q\2\2\u031ff\3\2\2\2\u0320\u0321\7g\2\2\u0321")NEWLINE buf.write("\u0322\7x\2\2\u0322\u0323\7c\2\2\u0323\u0324\7n\2\2\u0324")NEWLINE buf.write("h\3\2\2\2\u0325\u0326\7g\2\2\u0326\u0327\7z\2\2\u0327")NEWLINE buf.write("\u0328\7k\2\2\u0328\u0329\7v\2\2\u0329j\3\2\2\2\u032a")NEWLINE buf.write("\u032b\7i\2\2\u032b\u032c\7g\2\2\u032c\u032d\7v\2\2\u032d")NEWLINE buf.write("\u032e\7/\2\2\u032e\u032f\7q\2\2\u032f\u0330\7d\2\2\u0330")NEWLINE buf.write("\u0331\7l\2\2\u0331\u0332\7g\2\2\u0332\u0333\7e\2\2\u0333")NEWLINE buf.write("\u0334\7v\2\2\u0334\u0335\7k\2\2\u0335\u0336\7x\2\2\u0336")NEWLINE buf.write("\u0337\7g\2\2\u0337\u0338\7u\2\2\u0338l\3\2\2\2\u0339")NEWLINE buf.write("\u033a\7i\2\2\u033a\u033b\7g\2\2\u033b\u033c\7v\2\2\u033c")NEWLINE buf.write("\u033d\7/\2\2\u033d\u033e\7c\2\2\u033e\u033f\7u\2\2\u033f")NEWLINE buf.write("\u0340\7u\2\2\u0340\u0341\7g\2\2\u0341\u0342\7t\2\2\u0342")NEWLINE buf.write("\u0343\7v\2\2\u0343\u0344\7k\2\2\u0344\u0345\7q\2\2\u0345")NEWLINE buf.write("\u0346\7p\2\2\u0346\u0347\7u\2\2\u0347n\3\2\2\2\u0348")NEWLINE buf.write("\u0349\7i\2\2\u0349\u034a\7g\2\2\u034a\u034b\7v\2\2\u034b")NEWLINE buf.write("\u034c\7/\2\2\u034c\u034d\7c\2\2\u034d\u034e\7u\2\2\u034e")NEWLINE buf.write("\u034f\7u\2\2\u034f\u0350\7k\2\2\u0350\u0351\7i\2\2\u0351")NEWLINE buf.write("\u0352\7p\2\2\u0352\u0353\7o\2\2\u0353\u0354\7g\2\2\u0354")NEWLINE buf.write("\u0355\7p\2\2\u0355\u0356\7v\2\2\u0356p\3\2\2\2\u0357")NEWLINE buf.write("\u0358\7i\2\2\u0358\u0359\7g\2\2\u0359\u035a\7v\2\2\u035a")NEWLINE buf.write("\u035b\7/\2\2\u035b\u035c\7k\2\2\u035c\u035d\7p\2\2\u035d")NEWLINE buf.write("\u035e\7h\2\2\u035e\u035f\7q\2\2\u035fr\3\2\2\2\u0360")NEWLINE buf.write("\u0361\7i\2\2\u0361\u0362\7g\2\2\u0362\u0363\7v\2\2\u0363")NEWLINE buf.write("\u0364\7/\2\2\u0364\u0365\7o\2\2\u0365\u0366\7q\2\2\u0366")NEWLINE buf.write("\u0367\7f\2\2\u0367\u0368\7g\2\2\u0368\u0369\7n\2\2\u0369")NEWLINE buf.write("t\3\2\2\2\u036a\u036b\7d\2\2\u036b\u036c\7n\2\2\u036c")NEWLINE buf.write("\u036d\7q\2\2\u036d\u036e\7e\2\2\u036e\u036f\7m\2\2\u036f")NEWLINE buf.write("\u0370\7/\2\2\u0370\u0371\7o\2\2\u0371\u0372\7q\2\2\u0372")NEWLINE buf.write("\u0373\7f\2\2\u0373\u0374\7g\2\2\u0374\u0375\7n\2\2\u0375")NEWLINE buf.write("v\3\2\2\2\u0376\u0377\7i\2\2\u0377\u0378\7g\2\2\u0378")NEWLINE buf.write("\u0379\7v\2\2\u0379\u037a\7/\2\2\u037a\u037b\7q\2\2\u037b")NEWLINE buf.write("\u037c\7r\2\2\u037c\u037d\7v\2\2\u037d\u037e\7k\2\2\u037e")NEWLINE buf.write("\u037f\7q\2\2\u037f\u0380\7p\2\2\u0380x\3\2\2\2\u0381")NEWLINE buf.write("\u0382\7r\2\2\u0382\u0383\7q\2\2\u0383\u0384\7n\2\2\u0384")NEWLINE buf.write("\u0385\7{\2\2\u0385\u0386\7\61\2\2\u0386\u0387\7h\2\2")NEWLINE buf.write("\u0387\u0388\7c\2\2\u0388\u0389\7e\2\2\u0389\u038a\7v")NEWLINE buf.write("\2\2\u038a\u038b\7q\2\2\u038b\u038c\7t\2\2\u038cz\3\2")NEWLINE buf.write("\2\2\u038d\u038e\7i\2\2\u038e\u038f\7g\2\2\u038f\u0390")NEWLINE buf.write("\7v\2\2\u0390\u0391\7/\2\2\u0391\u0392\7r\2\2\u0392\u0393")NEWLINE buf.write("\7t\2\2\u0393\u0394\7q\2\2\u0394\u0395\7q\2\2\u0395\u0396")NEWLINE buf.write("\7h\2\2\u0396|\3\2\2\2\u0397\u0398\7i\2\2\u0398\u0399")NEWLINE buf.write("\7g\2\2\u0399\u039a\7v\2\2\u039a\u039b\7/\2\2\u039b\u039c")NEWLINE buf.write("\7w\2\2\u039c\u039d\7p\2\2\u039d\u039e\7u\2\2\u039e\u039f")NEWLINE buf.write("\7c\2\2\u039f\u03a0\7v\2\2\u03a0\u03a1\7/\2\2\u03a1\u03a2")NEWLINE buf.write("\7c\2\2\u03a2\u03a3\7u\2\2\u03a3\u03a4\7u\2\2\u03a4\u03a5")NEWLINE buf.write("\7w\2\2\u03a5\u03a6\7o\2\2\u03a6\u03a7\7r\2\2\u03a7\u03a8")NEWLINE buf.write("\7v\2\2\u03a8\u03a9\7k\2\2\u03a9\u03aa\7q\2\2\u03aa\u03ab")NEWLINE buf.write("\7p\2\2\u03ab\u03ac\7u\2\2\u03ac~\3\2\2\2\u03ad\u03ae")NEWLINE buf.write("\7i\2\2\u03ae\u03af\7g\2\2\u03af\u03b0\7v\2\2\u03b0\u03b1")NEWLINE buf.write("\7/\2\2\u03b1\u03b2\7w\2\2\u03b2\u03b3\7p\2\2\u03b3\u03b4")NEWLINE buf.write("\7u\2\2\u03b4\u03b5\7c\2\2\u03b5\u03b6\7v\2\2\u03b6\u03b7")NEWLINE buf.write("\7/\2\2\u03b7\u03b8\7e\2\2\u03b8\u03b9\7q\2\2\u03b9\u03ba")NEWLINE buf.write("\7t\2\2\u03ba\u03bb\7g\2\2\u03bb\u0080\3\2\2\2\u03bc\u03bd")NEWLINE buf.write("\7i\2\2\u03bd\u03be\7g\2\2\u03be\u03bf\7v\2\2\u03bf\u03c0")NEWLINE buf.write("\7/\2\2\u03c0\u03c1\7x\2\2\u03c1\u03c2\7c\2\2\u03c2\u03c3")NEWLINE buf.write("\7n\2\2\u03c3\u03c4\7w\2\2\u03c4\u03c5\7g\2\2\u03c5\u0082")NEWLINE buf.write("\3\2\2\2\u03c6\u03c7\7r\2\2\u03c7\u03c8\7q\2\2\u03c8\u03c9")NEWLINE buf.write("\7r\2\2\u03c9\u0084\3\2\2\2\u03ca\u03cb\7r\2\2\u03cb\u03cc")NEWLINE buf.write("\7w\2\2\u03cc\u03cd\7u\2\2\u03cd\u03ce\7j\2\2\u03ce\u0086")NEWLINE buf.write("\3\2\2\2\u03cf\u03d0\7t\2\2\u03d0\u03d1\7g\2\2\u03d1\u03d2")NEWLINE buf.write("\7u\2\2\u03d2\u03d3\7g\2\2\u03d3\u03d4\7v\2\2\u03d4\u0088")NEWLINE buf.write("\3\2\2\2\u03d5\u03d6\7t\2\2\u03d6\u03d7\7g\2\2\u03d7\u03d8")NEWLINE buf.write("\7u\2\2\u03d8\u03d9\7g\2\2\u03d9\u03da\7v\2\2\u03da\u03db")NEWLINE buf.write("\7/\2\2\u03db\u03dc\7c\2\2\u03dc\u03dd\7u\2\2\u03dd\u03de")NEWLINE buf.write("\7u\2\2\u03de\u03df\7g\2\2\u03df\u03e0\7t\2\2\u03e0\u03e1")NEWLINE buf.write("\7v\2\2\u03e1\u03e2\7k\2\2\u03e2\u03e3\7q\2\2\u03e3\u03e4")NEWLINE buf.write("\7p\2\2\u03e4\u03e5\7u\2\2\u03e5\u008a\3\2\2\2\u03e6\u03e7")NEWLINE buf.write("\7u\2\2\u03e7\u03e8\7g\2\2\u03e8\u03e9\7v\2\2\u03e9\u03ea")NEWLINE buf.write("\7/\2\2\u03ea\u03eb\7k\2\2\u03eb\u03ec\7p\2\2\u03ec\u03ed")NEWLINE buf.write("\7h\2\2\u03ed\u03ee\7q\2\2\u03ee\u008c\3\2\2\2\u03ef\u03f0")NEWLINE buf.write("\7u\2\2\u03f0\u03f1\7g\2\2\u03f1\u03f2\7v\2\2\u03f2\u03f3")NEWLINE buf.write("\7/\2\2\u03f3\u03f4\7n\2\2\u03f4\u03f5\7q\2\2\u03f5\u03f6")NEWLINE buf.write("\7i\2\2\u03f6\u03f7\7k\2\2\u03f7\u03f8\7e\2\2\u03f8\u008e")NEWLINE buf.write("\3\2\2\2\u03f9\u03fa\7u\2\2\u03fa\u03fb\7g\2\2\u03fb\u03fc")NEWLINE buf.write("\7v\2\2\u03fc\u03fd\7/\2\2\u03fd\u03fe\7q\2\2\u03fe\u03ff")NEWLINE buf.write("\7r\2\2\u03ff\u0400\7v\2\2\u0400\u0401\7k\2\2\u0401\u0402")NEWLINE buf.write("\7q\2\2\u0402\u0403\7p\2\2\u0403\u0090\3\2\2\2\u0404\u0405")NEWLINE buf.write("\7v\2\2\u0405\u0406\7j\2\2\u0406\u0407\7g\2\2\u0407\u0408")NEWLINE buf.write("\7p\2\2\u0408\u0092\3\2\2\2\u0409\u040a\7c\2\2\u040a\u040b")NEWLINE buf.write("\7p\2\2\u040b\u040c\7f\2\2\u040c\u040d\7/\2\2\u040d\u040e")NEWLINE buf.write("\7v\2\2\u040e\u040f\7j\2\2\u040f\u0410\7g\2\2\u0410\u0411")NEWLINE buf.write("\7p\2\2\u0411\u0094\3\2\2\2\u0412\u0413\7r\2\2\u0413\u0414")NEWLINE buf.write("\7c\2\2\u0414\u0415\7t\2\2\u0415\u0416\7/\2\2\u0416\u0417")NEWLINE buf.write("\7v\2\2\u0417\u0418\7j\2\2\u0418\u0419\7g\2\2\u0419\u041a")NEWLINE buf.write("\7p\2\2\u041a\u0096\3\2\2\2\u041b\u041c\7q\2\2\u041c\u041d")NEWLINE buf.write("\7t\2\2\u041d\u041e\7/\2\2\u041e\u041f\7g\2\2\u041f\u0420")NEWLINE buf.write("\7n\2\2\u0420\u0421\7u\2\2\u0421\u0422\7g\2\2\u0422\u0098")NEWLINE buf.write("\3\2\2\2\u0423\u0424\7r\2\2\u0424\u0425\7c\2\2\u0425\u0426")NEWLINE buf.write("\7t\2\2\u0426\u0427\7/\2\2\u0427\u0428\7q\2\2\u0428\u0429")NEWLINE buf.write("\7t\2\2\u0429\u042a\7/\2\2\u042a\u042b\7g\2\2\u042b\u042c")NEWLINE buf.write("\7n\2\2\u042c\u042d\7u\2\2\u042d\u042e\7g\2\2\u042e\u009a")NEWLINE buf.write("\3\2\2\2\u042f\u0430\7r\2\2\u0430\u0431\7c\2\2\u0431\u0432")NEWLINE buf.write("\7t\2\2\u0432\u0433\7/\2\2\u0433\u0434\7q\2\2\u0434\u0435")NEWLINE buf.write("\7t\2\2\u0435\u009c\3\2\2\2\u0436\u0437\7v\2\2\u0437\u0438")NEWLINE buf.write("\7t\2\2\u0438\u0439\7{\2\2\u0439\u043a\7/\2\2\u043a\u043b")NEWLINE buf.write("\7h\2\2\u043b\u043c\7q\2\2\u043c\u043d\7t\2\2\u043d\u009e")NEWLINE buf.write("\3\2\2\2\u043e\u043f\7w\2\2\u043f\u0440\7u\2\2\u0440\u0441")NEWLINE buf.write("\7k\2\2\u0441\u0442\7p\2\2\u0442\u0443\7i\2\2\u0443\u0444")NEWLINE buf.write("\7/\2\2\u0444\u0445\7r\2\2\u0445\u0446\7c\2\2\u0446\u0447")NEWLINE buf.write("\7t\2\2\u0447\u0448\7c\2\2\u0448\u0449\7o\2\2\u0449\u044a")NEWLINE buf.write("\7u\2\2\u044a\u00a0\3\2\2\2\u044b\u044c\7#\2\2\u044c\u00a2")NEWLINE buf.write("\3\2\2\2\u044d\u044e\7a\2\2\u044e\u00a4\3\2\2\2\u044f")NEWLINE buf.write("\u0450\7c\2\2\u0450\u0451\7u\2\2\u0451\u00a6\3\2\2\2\u0452")NEWLINE buf.write("\u0453\7D\2\2\u0453\u0454\7K\2\2\u0454\u0455\7P\2\2\u0455")NEWLINE buf.write("\u0456\7C\2\2\u0456\u0457\7T\2\2\u0457\u0458\7[\2\2\u0458")NEWLINE buf.write("\u00a8\3\2\2\2\u0459\u045a\7F\2\2\u045a\u045b\7G\2\2\u045b")NEWLINE buf.write("\u045c\7E\2\2\u045c\u045d\7K\2\2\u045d\u045e\7O\2\2\u045e")NEWLINE buf.write("\u045f\7C\2\2\u045f\u0460\7N\2\2\u0460\u00aa\3\2\2\2\u0461")NEWLINE buf.write("\u0462\7g\2\2\u0462\u0463\7z\2\2\u0463\u0464\7k\2\2\u0464")NEWLINE buf.write("\u0465\7u\2\2\u0465\u0466\7v\2\2\u0466\u0467\7u\2\2\u0467")NEWLINE buf.write("\u00ac\3\2\2\2\u0468\u0469\7J\2\2\u0469\u046a\7G\2\2\u046a")NEWLINE buf.write("\u046b\7Z\2\2\u046b\u046c\7C\2\2\u046c\u046d\7F\2\2\u046d")NEWLINE buf.write("\u046e\7G\2\2\u046e\u046f\7E\2\2\u046f\u0470\7K\2\2\u0470")NEWLINE buf.write("\u0471\7O\2\2\u0471\u0472\7C\2\2\u0472\u0473\7N\2\2\u0473")NEWLINE buf.write("\u00ae\3\2\2\2\u0474\u0475\7h\2\2\u0475\u0476\7q\2\2\u0476")NEWLINE buf.write("\u0477\7t\2\2\u0477\u0478\7c\2\2\u0478\u0479\7n\2\2\u0479")NEWLINE buf.write("\u047a\7n\2\2\u047a\u00b0\3\2\2\2\u047b\u047c\7n\2\2\u047c")NEWLINE buf.write("\u047d\7g\2\2\u047d\u047e\7v\2\2\u047e\u00b2\3\2\2\2\u047f")NEWLINE buf.write("\u0480\7o\2\2\u0480\u0481\7c\2\2\u0481\u0482\7v\2\2\u0482")NEWLINE buf.write("\u0483\7e\2\2\u0483\u0484\7j\2\2\u0484\u00b4\3\2\2\2\u0485")NEWLINE buf.write("\u0486\7P\2\2\u0486\u0487\7W\2\2\u0487\u0488\7O\2\2\u0488")NEWLINE buf.write("\u0489\7G\2\2\u0489\u048a\7T\2\2\u048a\u048b\7C\2\2\u048b")NEWLINE buf.write("\u048c\7N\2\2\u048c\u00b6\3\2\2\2\u048d\u048e\7r\2\2\u048e")NEWLINE buf.write("\u048f\7c\2\2\u048f\u0490\7t\2\2\u0490\u00b8\3\2\2\2\u0491")NEWLINE buf.write("\u049a\7\62\2\2\u0492\u0496\t\3\2\2\u0493\u0495\5\u00c5")NEWLINE buf.write("c\2\u0494\u0493\3\2\2\2\u0495\u0498\3\2\2\2\u0496\u0494")NEWLINE buf.write("\3\2\2\2\u0496\u0497\3\2\2\2\u0497\u049a\3\2\2\2\u0498")NEWLINE buf.write("\u0496\3\2\2\2\u0499\u0491\3\2\2\2\u0499\u0492\3\2\2\2")NEWLINE buf.write("\u049a\u00ba\3\2\2\2\u049b\u049c\7%\2\2\u049c\u049d\7")NEWLINE buf.write("d\2\2\u049d\u049f\3\2\2\2\u049e\u04a0\5\u00c9e\2\u049f")NEWLINE buf.write("\u049e\3\2\2\2\u04a0\u04a1\3\2\2\2\u04a1\u049f\3\2\2\2")NEWLINE buf.write("\u04a1\u04a2\3\2\2\2\u04a2\u00bc\3\2\2\2\u04a3\u04a4\7")NEWLINE buf.write("%\2\2\u04a4\u04a5\7z\2\2\u04a5\u04a7\3\2\2\2\u04a6\u04a8")NEWLINE buf.write("\5\u00c1a\2\u04a7\u04a6\3\2\2\2\u04a8\u04a9\3\2\2\2\u04a9")NEWLINE buf.write("\u04a7\3\2\2\2\u04a9\u04aa\3\2\2\2\u04aa\u00be\3\2\2\2")NEWLINE buf.write("\u04ab\u04ac\5\u00b9]\2\u04ac\u04b0\7\60\2\2\u04ad\u04af")NEWLINE buf.write("\7\62\2\2\u04ae\u04ad\3\2\2\2\u04af\u04b2\3\2\2\2\u04b0")NEWLINE buf.write("\u04ae\3\2\2\2\u04b0\u04b1\3\2\2\2\u04b1\u04b3\3\2\2\2")NEWLINE buf.write("\u04b2\u04b0\3\2\2\2\u04b3\u04b4\5\u00b9]\2\u04b4\u00c0")NEWLINE buf.write("\3\2\2\2\u04b5\u04b6\t\4\2\2\u04b6\u00c2\3\2\2\2\u04b7")NEWLINE buf.write("\u04b8\7<\2\2\u04b8\u00c4\3\2\2\2\u04b9\u04ba\t\5\2\2")NEWLINE buf.write("\u04ba\u00c6\3\2\2\2\u04bb\u04bc\t\6\2\2\u04bc\u00c8\3")NEWLINE buf.write("\2\2\2\u04bd\u04be\t\7\2\2\u04be\u00ca\3\2\2\2\u04bf\u04c2")NEWLINE buf.write("\t\b\2\2\u04c0\u04c2\5\u00d1i\2\u04c1\u04bf\3\2\2\2\u04c1")NEWLINE buf.write("\u04c0\3\2\2\2\u04c2\u00cc\3\2\2\2\u04c3\u04c6\t\t\2\2")NEWLINE buf.write("\u04c4\u04c6\5\u00d1i\2\u04c5\u04c3\3\2\2\2\u04c5\u04c4")NEWLINE buf.write("\3\2\2\2\u04c6\u00ce\3\2\2\2\u04c7\u04ca\t\n\2\2\u04c8")NEWLINE buf.write("\u04ca\5\u00d1i\2\u04c9\u04c7\3\2\2\2\u04c9\u04c8\3\2")NEWLINE buf.write("\2\2\u04ca\u00d0\3\2\2\2\u04cb\u04cc\7$\2\2\u04cc\u04cd")NEWLINE buf.write("\7$\2\2\u04cd\u00d2\3\2\2\2\u04ce\u04cf\t\13\2\2\u04cf")NEWLINE buf.write("\u00d4\3\2\2\2\u04d0\u04d1\7<\2\2\u04d1\u04d2\7c\2\2\u04d2")NEWLINE buf.write("\u04d3\7n\2\2\u04d3\u04d4\7n\2\2\u04d4\u04d5\7/\2\2\u04d5")NEWLINE buf.write("\u04d6\7u\2\2\u04d6\u04d7\7v\2\2\u04d7\u04d8\7c\2\2\u04d8")NEWLINE buf.write("\u04d9\7v\2\2\u04d9\u04da\7k\2\2\u04da\u04db\7u\2\2\u04db")NEWLINE buf.write("\u04dc\7v\2\2\u04dc\u04dd\7k\2\2\u04dd\u04de\7e\2\2\u04de")NEWLINE buf.write("\u04df\7u\2\2\u04df\u00d6\3\2\2\2\u04e0\u04e1\7<\2\2\u04e1")NEWLINE buf.write("\u04e2\7c\2\2\u04e2\u04e3\7u\2\2\u04e3\u04e4\7u\2\2\u04e4")NEWLINE buf.write("\u04e5\7g\2\2\u04e5\u04e6\7t\2\2\u04e6\u04e7\7v\2\2\u04e7")NEWLINE buf.write("\u04e8\7k\2\2\u04e8\u04e9\7q\2\2\u04e9\u04ea\7p\2\2\u04ea")NEWLINE buf.write("\u04eb\7/\2\2\u04eb\u04ec\7u\2\2\u04ec\u04ed\7v\2\2\u04ed")NEWLINE buf.write("\u04ee\7c\2\2\u04ee\u04ef\7e\2\2\u04ef\u04f0\7m\2\2\u04f0")NEWLINE buf.write("\u04f1\7/\2\2\u04f1\u04f2\7n\2\2\u04f2\u04f3\7g\2\2\u04f3")NEWLINE buf.write("\u04f4\7x\2\2\u04f4\u04f5\7g\2\2\u04f5\u04f6\7n\2\2\u04f6")NEWLINE buf.write("\u04f7\7u\2\2\u04f7\u00d8\3\2\2\2\u04f8\u04f9\7<\2\2\u04f9")NEWLINE buf.write("\u04fa\7c\2\2\u04fa\u04fb\7w\2\2\u04fb\u04fc\7v\2\2\u04fc")NEWLINE buf.write("\u04fd\7j\2\2\u04fd\u04fe\7q\2\2\u04fe\u04ff\7t\2\2\u04ff")NEWLINE buf.write("\u0500\7u\2\2\u0500\u00da\3\2\2\2\u0501\u0502\7<\2\2\u0502")NEWLINE buf.write("\u0503\7e\2\2\u0503\u0504\7c\2\2\u0504\u0505\7v\2\2\u0505")NEWLINE buf.write("\u0506\7g\2\2\u0506\u0507\7i\2\2\u0507\u0508\7q\2\2\u0508")NEWLINE buf.write("\u0509\7t\2\2\u0509\u050a\7{\2\2\u050a\u00dc\3\2\2\2\u050b")NEWLINE buf.write("\u050c\7<\2\2\u050c\u050d\7e\2\2\u050d\u050e\7j\2\2\u050e")NEWLINE buf.write("\u050f\7c\2\2\u050f\u0510\7k\2\2\u0510\u0511\7p\2\2\u0511")NEWLINE buf.write("\u0512\7c\2\2\u0512\u0513\7d\2\2\u0513\u0514\7n\2\2\u0514")NEWLINE buf.write("\u0515\7g\2\2\u0515\u00de\3\2\2\2\u0516\u0517\7<\2\2\u0517")NEWLINE buf.write("\u0518\7f\2\2\u0518\u0519\7g\2\2\u0519\u051a\7h\2\2\u051a")NEWLINE buf.write("\u051b\7k\2\2\u051b\u051c\7p\2\2\u051c\u051d\7k\2\2\u051d")NEWLINE buf.write("\u051e\7v\2\2\u051e\u051f\7k\2\2\u051f\u0520\7q\2\2\u0520")NEWLINE buf.write("\u0521\7p\2\2\u0521\u00e0\3\2\2\2\u0522\u0523\7<\2\2\u0523")NEWLINE buf.write("\u0524\7f\2\2\u0524\u0525\7k\2\2\u0525\u0526\7c\2\2\u0526")NEWLINE buf.write("\u0527\7i\2\2\u0527\u0528\7p\2\2\u0528\u0529\7q\2\2\u0529")NEWLINE buf.write("\u052a\7u\2\2\u052a\u052b\7v\2\2\u052b\u052c\7k\2\2\u052c")NEWLINE buf.write("\u052d\7e\2\2\u052d\u052e\7/\2\2\u052e\u052f\7q\2\2\u052f")NEWLINE buf.write("\u0530\7w\2\2\u0530\u0531\7v\2\2\u0531\u0532\7r\2\2\u0532")NEWLINE buf.write("\u0533\7w\2\2\u0533\u0534\7v\2\2\u0534\u0535\7/\2\2\u0535")NEWLINE buf.write("\u0536\7e\2\2\u0536\u0537\7j\2\2\u0537\u0538\7c\2\2\u0538")NEWLINE buf.write("\u0539\7p\2\2\u0539\u053a\7p\2\2\u053a\u053b\7g\2\2\u053b")NEWLINE buf.write("\u053c\7n\2\2\u053c\u00e2\3\2\2\2\u053d\u053e\7<\2\2\u053e")NEWLINE buf.write("\u053f\7g\2\2\u053f\u0540\7t\2\2\u0540\u0541\7t\2\2\u0541")NEWLINE buf.write("\u0542\7q\2\2\u0542\u0543\7t\2\2\u0543\u0544\7/\2\2\u0544")NEWLINE buf.write("\u0545\7d\2\2\u0545\u0546\7g\2\2\u0546\u0547\7j\2\2\u0547")NEWLINE buf.write("\u0548\7c\2\2\u0548\u0549\7x\2\2\u0549\u054a\7k\2\2\u054a")NEWLINE buf.write("\u054b\7q\2\2\u054b\u054c\7t\2\2\u054c\u00e4\3\2\2\2\u054d")NEWLINE buf.write("\u054e\7<\2\2\u054e\u054f\7g\2\2\u054f\u0550\7z\2\2\u0550")NEWLINE buf.write("\u0551\7v\2\2\u0551\u0552\7g\2\2\u0552\u0553\7p\2\2\u0553")NEWLINE buf.write("\u0554\7u\2\2\u0554\u0555\7k\2\2\u0555\u0556\7q\2\2\u0556")NEWLINE buf.write("\u0557\7p\2\2\u0557\u0558\7u\2\2\u0558\u00e6\3\2\2\2\u0559")NEWLINE buf.write("\u055a\7<\2\2\u055a\u055b\7h\2\2\u055b\u055c\7w\2\2\u055c")NEWLINE buf.write("\u055d\7p\2\2\u055d\u055e\7u\2\2\u055e\u00e8\3\2\2\2\u055f")NEWLINE buf.write("\u0560\7<\2\2\u0560\u0561\7h\2\2\u0561\u0562\7w\2\2\u0562")NEWLINE buf.write("\u0563\7p\2\2\u0563\u0564\7u\2\2\u0564\u0565\7/\2\2\u0565")NEWLINE buf.write("\u0566\7f\2\2\u0566\u0567\7g\2\2\u0567\u0568\7u\2\2\u0568")NEWLINE buf.write("\u0569\7e\2\2\u0569\u056a\7t\2\2\u056a\u056b\7k\2\2\u056b")NEWLINE buf.write("\u056c\7r\2\2\u056c\u056d\7v\2\2\u056d\u056e\7k\2\2\u056e")NEWLINE buf.write("\u056f\7q\2\2\u056f\u0570\7p\2\2\u0570\u00ea\3\2\2\2\u0571")NEWLINE buf.write("\u0572\7<\2\2\u0572\u0573\7i\2\2\u0573\u0574\7n\2\2\u0574")NEWLINE buf.write("\u0575\7q\2\2\u0575\u0576\7d\2\2\u0576\u0577\7c\2\2\u0577")NEWLINE buf.write("\u0578\7n\2\2\u0578\u0579\7/\2\2\u0579\u057a\7f\2\2\u057a")NEWLINE buf.write("\u057b\7g\2\2\u057b\u057c\7e\2\2\u057c\u057d\7n\2\2\u057d")NEWLINE buf.write("\u057e\7c\2\2\u057e\u057f\7t\2\2\u057f\u0580\7c\2\2\u0580")NEWLINE buf.write("\u0581\7v\2\2\u0581\u0582\7k\2\2\u0582\u0583\7q\2\2\u0583")NEWLINE buf.write("\u0584\7p\2\2\u0584\u0585\7u\2\2\u0585\u00ec\3\2\2\2\u0586")NEWLINE buf.write("\u0587\7<\2\2\u0587\u0588\7k\2\2\u0588\u0589\7p\2\2\u0589")NEWLINE buf.write("\u058a\7v\2\2\u058a\u058b\7g\2\2\u058b\u058c\7t\2\2\u058c")NEWLINE buf.write("\u058d\7c\2\2\u058d\u058e\7e\2\2\u058e\u058f\7v\2\2\u058f")NEWLINE buf.write("\u0590\7k\2\2\u0590\u0591\7x\2\2\u0591\u0592\7g\2\2\u0592")NEWLINE buf.write("\u0593\7/\2\2\u0593\u0594\7o\2\2\u0594\u0595\7q\2\2\u0595")NEWLINE buf.write("\u0596\7f\2\2\u0596\u0597\7g\2\2\u0597\u00ee\3\2\2\2\u0598")NEWLINE buf.write("\u0599\7<\2\2\u0599\u059a\7n\2\2\u059a\u059b\7c\2\2\u059b")NEWLINE buf.write("\u059c\7p\2\2\u059c\u059d\7i\2\2\u059d\u059e\7w\2\2\u059e")NEWLINE buf.write("\u059f\7c\2\2\u059f\u05a0\7i\2\2\u05a0\u05a1\7g\2\2\u05a1")NEWLINE buf.write("\u00f0\3\2\2\2\u05a2\u05a3\7<\2\2\u05a3\u05a4\7n\2\2\u05a4")NEWLINE buf.write("\u05a5\7g\2\2\u05a5\u05a6\7h\2\2\u05a6\u05a7\7v\2\2\u05a7")NEWLINE buf.write("\u05a8\7/\2\2\u05a8\u05a9\7c\2\2\u05a9\u05aa\7u\2\2\u05aa")NEWLINE buf.write("\u05ab\7u\2\2\u05ab\u05ac\7q\2\2\u05ac\u05ad\7e\2\2\u05ad")NEWLINE buf.write("\u00f2\3\2\2\2\u05ae\u05af\7<\2\2\u05af\u05b0\7n\2\2\u05b0")NEWLINE buf.write("\u05b1\7k\2\2\u05b1\u05b2\7e\2\2\u05b2\u05b3\7g\2\2\u05b3")NEWLINE buf.write("\u05b4\7p\2\2\u05b4\u05b5\7u\2\2\u05b5\u05b6\7g\2\2\u05b6")NEWLINE buf.write("\u00f4\3\2\2\2\u05b7\u05b8\7<\2\2\u05b8\u05b9\7p\2\2\u05b9")NEWLINE buf.write("\u05ba\7c\2\2\u05ba\u05bb\7o\2\2\u05bb\u05bc\7g\2\2\u05bc")NEWLINE buf.write("\u05bd\7f\2\2\u05bd\u00f6\3\2\2\2\u05be\u05bf\7<\2\2\u05bf")NEWLINE buf.write("\u05c0\7p\2\2\u05c0\u05c1\7c\2\2\u05c1\u05c2\7o\2\2\u05c2")NEWLINE buf.write("\u05c3\7g\2\2\u05c3\u00f8\3\2\2\2\u05c4\u05c5\7<\2\2\u05c5")NEWLINE buf.write("\u05c6\7p\2\2\u05c6\u05c7\7q\2\2\u05c7\u05c8\7v\2\2\u05c8")NEWLINE buf.write("\u05c9\7g\2\2\u05c9\u05ca\7u\2\2\u05ca\u00fa\3\2\2\2\u05cb")NEWLINE buf.write("\u05cc\7<\2\2\u05cc\u05cd\7r\2\2\u05cd\u05ce\7c\2\2\u05ce")NEWLINE buf.write("\u05cf\7v\2\2\u05cf\u05d0\7v\2\2\u05d0\u05d1\7g\2\2\u05d1")NEWLINE buf.write("\u05d2\7t\2\2\u05d2\u05d3\7p\2\2\u05d3\u00fc\3\2\2\2\u05d4")NEWLINE buf.write("\u05d5\7<\2\2\u05d5\u05d6\7r\2\2\u05d6\u05d7\7t\2\2\u05d7")NEWLINE buf.write("\u05d8\7k\2\2\u05d8\u05d9\7p\2\2\u05d9\u05da\7v\2\2\u05da")NEWLINE buf.write("\u05db\7/\2\2\u05db\u05dc\7u\2\2\u05dc\u05dd\7w\2\2\u05dd")NEWLINE buf.write("\u05de\7e\2\2\u05de\u05df\7e\2\2\u05df\u05e0\7g\2\2\u05e0")NEWLINE buf.write("\u05e1\7u\2\2\u05e1\u05e2\7u\2\2\u05e2\u00fe\3\2\2\2\u05e3")NEWLINE buf.write("\u05e4\7<\2\2\u05e4\u05e5\7r\2\2\u05e5\u05e6\7t\2\2\u05e6")NEWLINE buf.write("\u05e7\7q\2\2\u05e7\u05e8\7f\2\2\u05e8\u05e9\7w\2\2\u05e9")NEWLINE buf.write("\u05ea\7e\2\2\u05ea\u05eb\7g\2\2\u05eb\u05ec\7/\2\2\u05ec")NEWLINE buf.write("\u05ed\7c\2\2\u05ed\u05ee\7u\2\2\u05ee\u05ef\7u\2\2\u05ef")NEWLINE buf.write("\u05f0\7g\2\2\u05f0\u05f1\7t\2\2\u05f1\u05f2\7v\2\2\u05f2")NEWLINE buf.write("\u05f3\7k\2\2\u05f3\u05f4\7q\2\2\u05f4\u05f5\7p\2\2\u05f5")NEWLINE buf.write("\u05f6\7u\2\2\u05f6\u0100\3\2\2\2\u05f7\u05f8\7<\2\2\u05f8")NEWLINE buf.write("\u05f9\7r\2\2\u05f9\u05fa\7t\2\2\u05fa\u05fb\7q\2\2\u05fb")NEWLINE buf.write("\u05fc\7f\2\2\u05fc\u05fd\7w\2\2\u05fd\u05fe\7e\2\2\u05fe")NEWLINE buf.write("\u05ff\7g\2\2\u05ff\u0600\7/\2\2\u0600\u0601\7c\2\2\u0601")NEWLINE buf.write("\u0602\7u\2\2\u0602\u0603\7u\2\2\u0603\u0604\7k\2\2\u0604")NEWLINE buf.write("\u0605\7i\2\2\u0605\u0606\7p\2\2\u0606\u0607\7o\2\2\u0607")NEWLINE buf.write("\u0608\7g\2\2\u0608\u0609\7p\2\2\u0609\u060a\7v\2\2\u060a")NEWLINE buf.write("\u060b\7u\2\2\u060b\u0102\3\2\2\2\u060c\u060d\7<\2\2\u060d")NEWLINE buf.write("\u060e\7r\2\2\u060e\u060f\7t\2\2\u060f\u0610\7q\2\2\u0610")NEWLINE buf.write("\u0611\7f\2\2\u0611\u0612\7w\2\2\u0612\u0613\7e\2\2\u0613")NEWLINE buf.write("\u0614\7g\2\2\u0614\u0615\7/\2\2\u0615\u0616\7o\2\2\u0616")NEWLINE buf.write("\u0617\7q\2\2\u0617\u0618\7f\2\2\u0618\u0619\7g\2\2\u0619")NEWLINE buf.write("\u061a\7n\2\2\u061a\u061b\7u\2\2\u061b\u0104\3\2\2\2\u061c")NEWLINE buf.write("\u061d\7<\2\2\u061d\u061e\7r\2\2\u061e\u061f\7t\2\2\u061f")NEWLINE buf.write("\u0620\7q\2\2\u0620\u0621\7f\2\2\u0621\u0622\7w\2\2\u0622")NEWLINE buf.write("\u0623\7e\2\2\u0623\u0624\7g\2\2\u0624\u0625\7/\2\2\u0625")NEWLINE buf.write("\u0626\7r\2\2\u0626\u0627\7t\2\2\u0627\u0628\7q\2\2\u0628")NEWLINE buf.write("\u0629\7q\2\2\u0629\u062a\7h\2\2\u062a\u062b\7u\2\2\u062b")NEWLINE buf.write("\u0106\3\2\2\2\u062c\u062d\7<\2\2\u062d\u062e\7r\2\2\u062e")NEWLINE buf.write("\u062f\7t\2\2\u062f\u0630\7q\2\2\u0630\u0631\7f\2\2\u0631")NEWLINE buf.write("\u0632\7w\2\2\u0632\u0633\7e\2\2\u0633\u0634\7g\2\2\u0634")NEWLINE buf.write("\u0635\7/\2\2\u0635\u0636\7w\2\2\u0636\u0637\7p\2\2\u0637")NEWLINE buf.write("\u0638\7u\2\2\u0638\u0639\7c\2\2\u0639\u063a\7v\2\2\u063a")NEWLINE buf.write("\u063b\7/\2\2\u063b\u063c\7c\2\2\u063c\u063d\7u\2\2\u063d")NEWLINE buf.write("\u063e\7u\2\2\u063e\u063f\7w\2\2\u063f\u0640\7o\2\2\u0640")NEWLINE buf.write("\u0641\7r\2\2\u0641\u0642\7v\2\2\u0642\u0643\7k\2\2\u0643")NEWLINE buf.write("\u0644\7q\2\2\u0644\u0645\7p\2\2\u0645\u0646\7u\2\2\u0646")NEWLINE buf.write("\u0108\3\2\2\2\u0647\u0648\7<\2\2\u0648\u0649\7r\2\2\u0649")NEWLINE buf.write("\u064a\7t\2\2\u064a\u064b\7q\2\2\u064b\u064c\7f\2\2\u064c")NEWLINE buf.write("\u064d\7w\2\2\u064d\u064e\7e\2\2\u064e\u064f\7g\2\2\u064f")NEWLINE buf.write("\u0650\7/\2\2\u0650\u0651\7w\2\2\u0651\u0652\7p\2\2\u0652")NEWLINE buf.write("\u0653\7u\2\2\u0653\u0654\7c\2\2\u0654\u0655\7v\2\2\u0655")NEWLINE buf.write("\u0656\7/\2\2\u0656\u0657\7e\2\2\u0657\u0658\7q\2\2\u0658")NEWLINE buf.write("\u0659\7t\2\2\u0659\u065a\7g\2\2\u065a\u065b\7u\2\2\u065b")NEWLINE buf.write("\u010a\3\2\2\2\u065c\u065d\7<\2\2\u065d\u065e\7t\2\2\u065e")NEWLINE buf.write("\u065f\7c\2\2\u065f\u0660\7p\2\2\u0660\u0661\7f\2\2\u0661")NEWLINE buf.write("\u0662\7q\2\2\u0662\u0663\7o\2\2\u0663\u0664\7/\2\2\u0664")NEWLINE buf.write("\u0665\7u\2\2\u0665\u0666\7g\2\2\u0666\u0667\7g\2\2\u0667")NEWLINE buf.write("\u0668\7f\2\2\u0668\u010c\3\2\2\2\u0669\u066a\7<\2\2\u066a")NEWLINE buf.write("\u066b\7t\2\2\u066b\u066c\7g\2\2\u066c\u066d\7c\2\2\u066d")NEWLINE buf.write("\u066e\7u\2\2\u066e\u066f\7q\2\2\u066f\u0670\7p\2\2\u0670")NEWLINE buf.write("\u0671\7/\2\2\u0671\u0672\7w\2\2\u0672\u0673\7p\2\2\u0673")NEWLINE buf.write("\u0674\7m\2\2\u0674\u0675\7p\2\2\u0675\u0676\7q\2\2\u0676")NEWLINE buf.write("\u0677\7y\2\2\u0677\u0678\7p\2\2\u0678\u010e\3\2\2\2\u0679")NEWLINE buf.write("\u067a\7<\2\2\u067a\u067b\7t\2\2\u067b\u067c\7g\2\2\u067c")NEWLINE buf.write("\u067d\7i\2\2\u067d\u067e\7w\2\2\u067e\u067f\7n\2\2\u067f")NEWLINE buf.write("\u0680\7c\2\2\u0680\u0681\7t\2\2\u0681\u0682\7/\2\2\u0682")NEWLINE buf.write("\u0683\7q\2\2\u0683\u0684\7w\2\2\u0684\u0685\7v\2\2\u0685")NEWLINE buf.write("\u0686\7r\2\2\u0686\u0687\7w\2\2\u0687\u0688\7v\2\2\u0688")NEWLINE buf.write("\u0689\7/\2\2\u0689\u068a\7e\2\2\u068a\u068b\7j\2\2\u068b")NEWLINE buf.write("\u068c\7c\2\2\u068c\u068d\7p\2\2\u068d\u068e\7p\2\2\u068e")NEWLINE buf.write("\u068f\7g\2\2\u068f\u0690\7n\2\2\u0690\u0110\3\2\2\2\u0691")NEWLINE buf.write("\u0692\7<\2\2\u0692\u0693\7t\2\2\u0693\u0694\7g\2\2\u0694")NEWLINE buf.write("\u0695\7r\2\2\u0695\u0696\7t\2\2\u0696\u0697\7q\2\2\u0697")NEWLINE buf.write("\u0698\7f\2\2\u0698\u0699\7w\2\2\u0699\u069a\7e\2\2\u069a")NEWLINE buf.write("\u069b\7k\2\2\u069b\u069c\7d\2\2\u069c\u069d\7n\2\2\u069d")NEWLINE buf.write("\u069e\7g\2\2\u069e\u069f\7/\2\2\u069f\u06a0\7t\2\2\u06a0")NEWLINE buf.write("\u06a1\7g\2\2\u06a1\u06a2\7u\2\2\u06a2\u06a3\7q\2\2\u06a3")NEWLINE buf.write("\u06a4\7w\2\2\u06a4\u06a5\7t\2\2\u06a5\u06a6\7e\2\2\u06a6")NEWLINE buf.write("\u06a7\7g\2\2\u06a7\u06a8\7/\2\2\u06a8\u06a9\7n\2\2\u06a9")NEWLINE buf.write("\u06aa\7k\2\2\u06aa\u06ab\7o\2\2\u06ab\u06ac\7k\2\2\u06ac")NEWLINE buf.write("\u06ad\7v\2\2\u06ad\u0112\3\2\2\2\u06ae\u06af\7<\2\2\u06af")NEWLINE buf.write("\u06b0\7t\2\2\u06b0\u06b1\7k\2\2\u06b1\u06b2\7i\2\2\u06b2")NEWLINE buf.write("\u06b3\7j\2\2\u06b3\u06b4\7v\2\2\u06b4\u06b5\7/\2\2\u06b5")NEWLINE buf.write("\u06b6\7c\2\2\u06b6\u06b7\7u\2\2\u06b7\u06b8\7u\2\2\u06b8")NEWLINE buf.write("\u06b9\7q\2\2\u06b9\u06ba\7e\2\2\u06ba\u0114\3\2\2\2\u06bb")NEWLINE buf.write("\u06bc\7<\2\2\u06bc\u06bd\7u\2\2\u06bd\u06be\7o\2\2\u06be")NEWLINE buf.write("\u06bf\7v\2\2\u06bf\u06c0\7/\2\2\u06c0\u06c1\7n\2\2\u06c1")NEWLINE buf.write("\u06c2\7k\2\2\u06c2\u06c3\7d\2\2\u06c3\u06c4\7/\2\2\u06c4")NEWLINE buf.write("\u06c5\7x\2\2\u06c5\u06c6\7g\2\2\u06c6\u06c7\7t\2\2\u06c7")NEWLINE buf.write("\u06c8\7u\2\2\u06c8\u06c9\7k\2\2\u06c9\u06ca\7q\2\2\u06ca")NEWLINE buf.write("\u06cb\7p\2\2\u06cb\u0116\3\2\2\2\u06cc\u06cd\7<\2\2\u06cd")NEWLINE buf.write("\u06ce\7u\2\2\u06ce\u06cf\7q\2\2\u06cf\u06d0\7t\2\2\u06d0")NEWLINE buf.write("\u06d1\7v\2\2\u06d1\u06d2\7u\2\2\u06d2\u0118\3\2\2\2\u06d3")NEWLINE buf.write("\u06d4\7<\2\2\u06d4\u06d5\7u\2\2\u06d5\u06d6\7q\2\2\u06d6")NEWLINE buf.write("\u06d7\7t\2\2\u06d7\u06d8\7v\2\2\u06d8\u06d9\7u\2\2\u06d9")NEWLINE buf.write("\u06da\7/\2\2\u06da\u06db\7f\2\2\u06db\u06dc\7g\2\2\u06dc")NEWLINE buf.write("\u06dd\7u\2\2\u06dd\u06de\7e\2\2\u06de\u06df\7t\2\2\u06df")NEWLINE buf.write("\u06e0\7k\2\2\u06e0\u06e1\7r\2\2\u06e1\u06e2\7v\2\2\u06e2")NEWLINE buf.write("\u06e3\7k\2\2\u06e3\u06e4\7q\2\2\u06e4\u06e5\7p\2\2\u06e5")NEWLINE buf.write("\u011a\3\2\2\2\u06e6\u06e7\7<\2\2\u06e7\u06e8\7u\2\2\u06e8")NEWLINE buf.write("\u06e9\7q\2\2\u06e9\u06ea\7w\2\2\u06ea\u06eb\7t\2\2\u06eb")NEWLINE buf.write("\u06ec\7e\2\2\u06ec\u06ed\7g\2\2\u06ed\u011c\3\2\2\2\u06ee")NEWLINE buf.write("\u06ef\7<\2\2\u06ef\u06f0\7u\2\2\u06f0\u06f1\7v\2\2\u06f1")NEWLINE buf.write("\u06f2\7c\2\2\u06f2\u06f3\7v\2\2\u06f3\u06f4\7w\2\2\u06f4")NEWLINE buf.write("\u06f5\7u\2\2\u06f5\u011e\3\2\2\2\u06f6\u06f7\7<\2\2\u06f7")NEWLINE buf.write("\u06f8\7v\2\2\u06f8\u06f9\7j\2\2\u06f9\u06fa\7g\2\2\u06fa")NEWLINE buf.write("\u06fb\7q\2\2\u06fb\u06fc\7t\2\2\u06fc\u06fd\7k\2\2\u06fd")NEWLINE buf.write("\u06fe\7g\2\2\u06fe\u06ff\7u\2\2\u06ff\u0120\3\2\2\2\u0700")NEWLINE buf.write("\u0701\7<\2\2\u0701\u0702\7x\2\2\u0702\u0703\7c\2\2\u0703")NEWLINE buf.write("\u0704\7n\2\2\u0704\u0705\7w\2\2\u0705\u0706\7g\2\2\u0706")NEWLINE buf.write("\u0707\7u\2\2\u0707\u0122\3\2\2\2\u0708\u0709\7<\2\2\u0709")NEWLINE buf.write("\u070a\7x\2\2\u070a\u070b\7g\2\2\u070b\u070c\7t\2\2\u070c")NEWLINE buf.write("\u070d\7d\2\2\u070d\u070e\7q\2\2\u070e\u070f\7u\2\2\u070f")NEWLINE buf.write("\u0710\7k\2\2\u0710\u0711\7v\2\2\u0711\u0712\7{\2\2\u0712")NEWLINE buf.write("\u0124\3\2\2\2\u0713\u0714\7<\2\2\u0714\u0715\7x\2\2\u0715")NEWLINE buf.write("\u0716\7g\2\2\u0716\u0717\7t\2\2\u0717\u0718\7u\2\2\u0718")NEWLINE buf.write("\u0719\7k\2\2\u0719\u071a\7q\2\2\u071a\u071b\7p\2\2\u071b")NEWLINE buf.write("\u0126\3\2\2\2\u071c\u0721\5\u00c7d\2\u071d\u0720\5\u00c5")NEWLINE buf.write("c\2\u071e\u0720\5\u00c7d\2\u071f\u071d\3\2\2\2\u071f\u071e")NEWLINE buf.write("\3\2\2\2\u0720\u0723\3\2\2\2\u0721\u071f\3\2\2\2\u0721")NEWLINE buf.write("\u0722\3\2\2\2\u0722\u0128\3\2\2\2\u0723\u0721\3\2\2\2")NEWLINE buf.write("\u0724\u0726\t\13\2\2\u0725\u0724\3\2\2\2\u0726\u0727")NEWLINE buf.write("\3\2\2\2\u0727\u0725\3\2\2\2\u0727\u0728\3\2\2\2\u0728")NEWLINE buf.write("\u0729\3\2\2\2\u0729\u072a\b\u0095\2\2\u072a\u012a\3\2")NEWLINE buf.write("\2\2\24\2\u0133\u0141\u0143\u014b\u014d\u0169\u0496\u0499")NEWLINE buf.write("\u04a1\u04a9\u04b0\u04c1\u04c5\u04c9\u071f\u0721\u0727")NEWLINE buf.write("\3\b\2\2")NEWLINE return buf.getvalue()NEWLINENEWLINENEWLINEclass SMTLIBv2Lexer(Lexer):NEWLINENEWLINE atn = ATNDeserializer().deserialize(serializedATN())NEWLINENEWLINE decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]NEWLINENEWLINE T__0 = 1NEWLINE Comment = 2NEWLINE ParOpen = 3NEWLINE ParClose = 4NEWLINE Semicolon = 5NEWLINE String = 6NEWLINE QuotedSymbol = 7NEWLINE RegConst = 8NEWLINE PS_Not = 9NEWLINE PS_Bool = 10NEWLINE PS_Int = 11NEWLINE PS_Real = 12NEWLINE PS_ContinuedExecution = 13NEWLINE PS_Error = 14NEWLINE PS_False = 15NEWLINE PS_ImmediateExit = 16NEWLINE PS_Incomplete = 17NEWLINE PS_Logic = 18NEWLINE PS_Memout = 19NEWLINE PS_Sat = 20NEWLINE PS_Success = 21NEWLINE PS_Theory = 22NEWLINE PS_True = 23NEWLINE PS_Unknown = 24NEWLINE PS_Unsupported = 25NEWLINE PS_Unsat = 26NEWLINE CMD_Assert = 27NEWLINE CMD_AssertSoft = 28NEWLINE Simplify = 29NEWLINE CMD_CheckSat = 30NEWLINE CMD_CheckSatAssuming = 31NEWLINE CMD_CheckSatUsing = 32NEWLINE CMD_Labels = 33NEWLINE CMD_Minimize = 34NEWLINE CMD_Maximize = 35NEWLINE CMD_DeclareConst = 36NEWLINE CMD_DeclareDatatype = 37NEWLINE CMD_DeclareCodatatype = 38NEWLINE CMD_DeclareDatatypes = 39NEWLINE CMD_DeclareCodatatypes = 40NEWLINE CMD_DeclareFun = 41NEWLINE CMD_DeclareSort = 42NEWLINE CMD_Define = 43NEWLINE CMD_DefineFun = 44NEWLINE CMD_DefineConst = 45NEWLINE CMD_DefineFunRec = 46NEWLINE CMD_DefineFunsRec = 47NEWLINE CMD_DefineSort = 48NEWLINE CMD_Display = 49NEWLINE CMD_Echo = 50NEWLINE CMD_Eval = 51NEWLINE CMD_Exit = 52NEWLINE CMD_GetObjectives = 53NEWLINE CMD_GetAssertions = 54NEWLINE CMD_GetAssignment = 55NEWLINE CMD_GetInfo = 56NEWLINE CMD_GetModel = 57NEWLINE CMD_BlockModel = 58NEWLINE CMD_GetOption = 59NEWLINE CMD_PolyFactor = 60NEWLINE CMD_GetProof = 61NEWLINE CMD_GetUnsatAssumptions = 62NEWLINE CMD_GetUnsatCore = 63NEWLINE CMD_GetValue = 64NEWLINE CMD_Pop = 65NEWLINE CMD_Push = 66NEWLINE CMD_Reset = 67NEWLINE CMD_ResetAssertions = 68NEWLINE CMD_SetInfo = 69NEWLINE CMD_SetLogic = 70NEWLINE CMD_SetOption = 71NEWLINE TAC_Then = 72NEWLINE TAC_AndThen = 73NEWLINE TAC_ParThen = 74NEWLINE TAC_OrElse = 75NEWLINE TAC_ParOrElse = 76NEWLINE TAC_ParOr = 77NEWLINE TAC_TryFor = 78NEWLINE TAC_UsingParams = 79NEWLINE GRW_Exclamation = 80NEWLINE GRW_Underscore = 81NEWLINE GRW_As = 82NEWLINE GRW_Binary = 83NEWLINE GRW_Decimal = 84NEWLINE GRW_Exists = 85NEWLINE GRW_Hexadecimal = 86NEWLINE GRW_Forall = 87NEWLINE GRW_Let = 88NEWLINE GRW_Match = 89NEWLINE GRW_Numeral = 90NEWLINE GRW_Par = 91NEWLINE Numeral = 92NEWLINE Binary = 93NEWLINE HexDecimal = 94NEWLINE Decimal = 95NEWLINE Colon = 96NEWLINE PK_AllStatistics = 97NEWLINE PK_AssertionStackLevels = 98NEWLINE PK_Authors = 99NEWLINE PK_Category = 100NEWLINE PK_Chainable = 101NEWLINE PK_Definition = 102NEWLINE PK_DiagnosticOutputChannel = 103NEWLINE PK_ErrorBehaviour = 104NEWLINE PK_Extension = 105NEWLINE PK_Funs = 106NEWLINE PK_FunsDescription = 107NEWLINE PK_GlobalDeclarations = 108NEWLINE PK_InteractiveMode = 109NEWLINE PK_Language = 110NEWLINE PK_LeftAssoc = 111NEWLINE PK_License = 112NEWLINE PK_Named = 113NEWLINE PK_Name = 114NEWLINE PK_Notes = 115NEWLINE PK_Pattern = 116NEWLINE PK_PrintSuccess = 117NEWLINE PK_ProduceAssertions = 118NEWLINE PK_ProduceAssignments = 119NEWLINE PK_ProduceModels = 120NEWLINE PK_ProduceProofs = 121NEWLINE PK_ProduceUnsatAssumptions = 122NEWLINE PK_ProduceUnsatCores = 123NEWLINE PK_RandomSeed = 124NEWLINE PK_ReasonUnknown = 125NEWLINE PK_RegularOutputChannel = 126NEWLINE PK_ReproducibleResourceLimit = 127NEWLINE PK_RightAssoc = 128NEWLINE PK_SmtLibVersion = 129NEWLINE PK_Sorts = 130NEWLINE PK_SortsDescription = 131NEWLINE PK_Source = 132NEWLINE PK_Status = 133NEWLINE PK_Theories = 134NEWLINE PK_Values = 135NEWLINE PK_Verbosity = 136NEWLINE PK_Version = 137NEWLINE UndefinedSymbol = 138NEWLINE WS = 139NEWLINENEWLINE channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]NEWLINENEWLINE modeNames = [ "DEFAULT_MODE" ]NEWLINENEWLINE literalNames = [ "",NEWLINE "' bv'", "'('", "')'", "';'", "'not'", "'Bool'", "'Int'", "'Real'", NEWLINE "'continued-execution'", "'error'", "'false'", "'immediate-exit'", NEWLINE "'incomplete'", "'logic'", "'memout'", "'sat'", "'success'", NEWLINE "'theory'", "'true'", "'unknown'", "'unsupported'", "'unsat'", NEWLINE "'assert'", "'assert-soft'", "'simplify'", "'check-sat'", "'check-sat-assuming'", NEWLINE "'check-sat-using'", "'labels'", "'minimize'", "'maximize'", NEWLINE "'declare-const'", "'declare-datatype'", "'declare-codatatype'", NEWLINE "'declare-datatypes'", "'declare-codatatypes'", "'declare-fun'", NEWLINE "'declare-sort'", "'define'", "'define-fun'", "'define-const'", NEWLINE "'define-fun-rec'", "'define-funs-rec'", "'define-sort'", "'display'", NEWLINE "'echo'", "'eval'", "'exit'", "'get-objectives'", "'get-assertions'", NEWLINE "'get-assignment'", "'get-info'", "'get-model'", "'block-model'", NEWLINE "'get-option'", "'poly/factor'", "'get-proof'", "'get-unsat-assumptions'", NEWLINE "'get-unsat-core'", "'get-value'", "'pop'", "'push'", "'reset'", NEWLINE "'reset-assertions'", "'set-info'", "'set-logic'", "'set-option'", NEWLINE "'then'", "'and-then'", "'par-then'", "'or-else'", "'par-or-else'", NEWLINE "'par-or'", "'try-for'", "'using-params'", "'!'", "'_'", "'as'", NEWLINE "'BINARY'", "'DECIMAL'", "'exists'", "'HEXADECIMAL'", "'forall'", NEWLINE "'let'", "'match'", "'NUMERAL'", "'par'", "':'", "':all-statistics'", NEWLINE "':assertion-stack-levels'", "':authors'", "':category'", "':chainable'", NEWLINE "':definition'", "':diagnostic-output-channel'", "':error-behavior'", NEWLINE "':extensions'", "':funs'", "':funs-description'", "':global-declarations'", NEWLINE "':interactive-mode'", "':language'", "':left-assoc'", "':license'", NEWLINE "':named'", "':name'", "':notes'", "':pattern'", "':print-success'", NEWLINE "':produce-assertions'", "':produce-assignments'", "':produce-models'", NEWLINE "':produce-proofs'", "':produce-unsat-assumptions'", "':produce-unsat-cores'", NEWLINE "':random-seed'", "':reason-unknown'", "':regular-output-channel'", NEWLINE "':reproducible-resource-limit'", "':right-assoc'", "':smt-lib-version'", NEWLINE "':sorts'", "':sorts-description'", "':source'", "':status'", NEWLINE "':theories'", "':values'", "':verbosity'", "':version'" ]NEWLINENEWLINE symbolicNames = [ "",NEWLINE "Comment", "ParOpen", "ParClose", "Semicolon", "String", "QuotedSymbol", NEWLINE "RegConst", "PS_Not", "PS_Bool", "PS_Int", "PS_Real", "PS_ContinuedExecution", NEWLINE "PS_Error", "PS_False", "PS_ImmediateExit", "PS_Incomplete", NEWLINE "PS_Logic", "PS_Memout", "PS_Sat", "PS_Success", "PS_Theory", NEWLINE "PS_True", "PS_Unknown", "PS_Unsupported", "PS_Unsat", "CMD_Assert", NEWLINE "CMD_AssertSoft", "Simplify", "CMD_CheckSat", "CMD_CheckSatAssuming", NEWLINE "CMD_CheckSatUsing", "CMD_Labels", "CMD_Minimize", "CMD_Maximize", NEWLINE "CMD_DeclareConst", "CMD_DeclareDatatype", "CMD_DeclareCodatatype", NEWLINE "CMD_DeclareDatatypes", "CMD_DeclareCodatatypes", "CMD_DeclareFun", NEWLINE "CMD_DeclareSort", "CMD_Define", "CMD_DefineFun", "CMD_DefineConst", NEWLINE "CMD_DefineFunRec", "CMD_DefineFunsRec", "CMD_DefineSort", "CMD_Display", NEWLINE "CMD_Echo", "CMD_Eval", "CMD_Exit", "CMD_GetObjectives", "CMD_GetAssertions", NEWLINE "CMD_GetAssignment", "CMD_GetInfo", "CMD_GetModel", "CMD_BlockModel", NEWLINE "CMD_GetOption", "CMD_PolyFactor", "CMD_GetProof", "CMD_GetUnsatAssumptions", NEWLINE "CMD_GetUnsatCore", "CMD_GetValue", "CMD_Pop", "CMD_Push", "CMD_Reset", NEWLINE "CMD_ResetAssertions", "CMD_SetInfo", "CMD_SetLogic", "CMD_SetOption", NEWLINE "TAC_Then", "TAC_AndThen", "TAC_ParThen", "TAC_OrElse", "TAC_ParOrElse", NEWLINE "TAC_ParOr", "TAC_TryFor", "TAC_UsingParams", "GRW_Exclamation", NEWLINE "GRW_Underscore", "GRW_As", "GRW_Binary", "GRW_Decimal", "GRW_Exists", NEWLINE "GRW_Hexadecimal", "GRW_Forall", "GRW_Let", "GRW_Match", "GRW_Numeral", NEWLINE "GRW_Par", "Numeral", "Binary", "HexDecimal", "Decimal", "Colon", NEWLINE "PK_AllStatistics", "PK_AssertionStackLevels", "PK_Authors", NEWLINE "PK_Category", "PK_Chainable", "PK_Definition", "PK_DiagnosticOutputChannel", NEWLINE "PK_ErrorBehaviour", "PK_Extension", "PK_Funs", "PK_FunsDescription", NEWLINE "PK_GlobalDeclarations", "PK_InteractiveMode", "PK_Language", NEWLINE "PK_LeftAssoc", "PK_License", "PK_Named", "PK_Name", "PK_Notes", NEWLINE "PK_Pattern", "PK_PrintSuccess", "PK_ProduceAssertions", "PK_ProduceAssignments", NEWLINE "PK_ProduceModels", "PK_ProduceProofs", "PK_ProduceUnsatAssumptions", NEWLINE "PK_ProduceUnsatCores", "PK_RandomSeed", "PK_ReasonUnknown", NEWLINE "PK_RegularOutputChannel", "PK_ReproducibleResourceLimit", "PK_RightAssoc", NEWLINE "PK_SmtLibVersion", "PK_Sorts", "PK_SortsDescription", "PK_Source", NEWLINE "PK_Status", "PK_Theories", "PK_Values", "PK_Verbosity", "PK_Version", NEWLINE "UndefinedSymbol", "WS" ]NEWLINENEWLINE ruleNames = [ "T__0", "Comment", "ParOpen", "ParClose", "Semicolon", NEWLINE "String", "QuotedSymbol", "RegConst", "PS_Not", "PS_Bool", NEWLINE "PS_Int", "PS_Real", "PS_ContinuedExecution", "PS_Error", NEWLINE "PS_False", "PS_ImmediateExit", "PS_Incomplete", "PS_Logic", NEWLINE "PS_Memout", "PS_Sat", "PS_Success", "PS_Theory", "PS_True", NEWLINE "PS_Unknown", "PS_Unsupported", "PS_Unsat", "CMD_Assert", NEWLINE "CMD_AssertSoft", "Simplify", "CMD_CheckSat", "CMD_CheckSatAssuming", NEWLINE "CMD_CheckSatUsing", "CMD_Labels", "CMD_Minimize", "CMD_Maximize", NEWLINE "CMD_DeclareConst", "CMD_DeclareDatatype", "CMD_DeclareCodatatype", NEWLINE "CMD_DeclareDatatypes", "CMD_DeclareCodatatypes", "CMD_DeclareFun", NEWLINE "CMD_DeclareSort", "CMD_Define", "CMD_DefineFun", "CMD_DefineConst", NEWLINE "CMD_DefineFunRec", "CMD_DefineFunsRec", "CMD_DefineSort", NEWLINE "CMD_Display", "CMD_Echo", "CMD_Eval", "CMD_Exit", "CMD_GetObjectives", NEWLINE "CMD_GetAssertions", "CMD_GetAssignment", "CMD_GetInfo", NEWLINE "CMD_GetModel", "CMD_BlockModel", "CMD_GetOption", "CMD_PolyFactor", NEWLINE "CMD_GetProof", "CMD_GetUnsatAssumptions", "CMD_GetUnsatCore", NEWLINE "CMD_GetValue", "CMD_Pop", "CMD_Push", "CMD_Reset", "CMD_ResetAssertions", NEWLINE "CMD_SetInfo", "CMD_SetLogic", "CMD_SetOption", "TAC_Then", NEWLINE "TAC_AndThen", "TAC_ParThen", "TAC_OrElse", "TAC_ParOrElse", NEWLINE "TAC_ParOr", "TAC_TryFor", "TAC_UsingParams", "GRW_Exclamation", NEWLINE "GRW_Underscore", "GRW_As", "GRW_Binary", "GRW_Decimal", NEWLINE "GRW_Exists", "GRW_Hexadecimal", "GRW_Forall", "GRW_Let", NEWLINE "GRW_Match", "GRW_Numeral", "GRW_Par", "Numeral", "Binary", NEWLINE "HexDecimal", "Decimal", "HexDigit", "Colon", "Digit", NEWLINE "Sym", "BinaryDigit", "PrintableChar", "PrintableCharNoDquote", NEWLINE "PrintableCharNoBackslash", "EscapedSpace", "WhiteSpaceChar", NEWLINE "PK_AllStatistics", "PK_AssertionStackLevels", "PK_Authors", NEWLINE "PK_Category", "PK_Chainable", "PK_Definition", "PK_DiagnosticOutputChannel", NEWLINE "PK_ErrorBehaviour", "PK_Extension", "PK_Funs", "PK_FunsDescription", NEWLINE "PK_GlobalDeclarations", "PK_InteractiveMode", "PK_Language", NEWLINE "PK_LeftAssoc", "PK_License", "PK_Named", "PK_Name", "PK_Notes", NEWLINE "PK_Pattern", "PK_PrintSuccess", "PK_ProduceAssertions", NEWLINE "PK_ProduceAssignments", "PK_ProduceModels", "PK_ProduceProofs", NEWLINE "PK_ProduceUnsatAssumptions", "PK_ProduceUnsatCores", NEWLINE "PK_RandomSeed", "PK_ReasonUnknown", "PK_RegularOutputChannel", NEWLINE "PK_ReproducibleResourceLimit", "PK_RightAssoc", "PK_SmtLibVersion", NEWLINE "PK_Sorts", "PK_SortsDescription", "PK_Source", "PK_Status", NEWLINE "PK_Theories", "PK_Values", "PK_Verbosity", "PK_Version", NEWLINE "UndefinedSymbol", "WS" ]NEWLINENEWLINE grammarFileName = "SMTLIBv2.g4"NEWLINENEWLINE def __init__(self, input=None, output:TextIO = sys.stdout):NEWLINE super().__init__(input, output)NEWLINE self.checkVersion("4.9.2")NEWLINE self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())NEWLINE self._actions = NoneNEWLINE self._predicates = NoneNEWLINENEWLINENEWLINE """JSON Web Encryption utilities."""NEWLINENEWLINEimport binasciiNEWLINEimport jsonNEWLINENEWLINEfrom collections import OrderedDictNEWLINEfrom typing import Any, Dict, Iterable, List, Mapping, Optional, UnionNEWLINENEWLINEfrom marshmallow import fields, Schema, ValidationErrorNEWLINENEWLINEfrom ..wallet.util import b64_to_bytes, bytes_to_b64NEWLINENEWLINEIDENT_ENC_KEY = "encrypted_key"NEWLINEIDENT_HEADER = "header"NEWLINEIDENT_PROTECTED = "protected"NEWLINEIDENT_RECIPIENTS = "recipients"NEWLINENEWLINENEWLINEdef b64url(value: Union[bytes, str]) -> str:NEWLINE """Encode a string or bytes value as unpadded base64-URL."""NEWLINE if isinstance(value, str):NEWLINE value = value.encode("utf-8")NEWLINE return bytes_to_b64(value, urlsafe=True, pad=False)NEWLINENEWLINENEWLINEdef from_b64url(value: str) -> bytes:NEWLINE """Decode an unpadded base64-URL value."""NEWLINE try:NEWLINE return b64_to_bytes(value, urlsafe=True)NEWLINE except binascii.Error:NEWLINE raise ValidationError("Error decoding base64 value")NEWLINENEWLINENEWLINEclass B64Value(fields.Str):NEWLINE """A marshmallow-compatible wrapper for base64-URL values."""NEWLINENEWLINE def _serialize(self, value, attr, obj, **kwargs) -> Optional[str]:NEWLINE if value is None:NEWLINE return NoneNEWLINE if not isinstance(value, bytes):NEWLINE return TypeError("Expected bytes")NEWLINE return b64url(value)NEWLINENEWLINE def _deserialize(self, value, attr, data, **kwargs) -> Any:NEWLINE value = super()._deserialize(value, attr, data, **kwargs)NEWLINE return from_b64url(value)NEWLINENEWLINENEWLINEclass JweSchema(Schema):NEWLINE """JWE envelope schema."""NEWLINENEWLINE protected = fields.Str(required=True)NEWLINE unprotected = fields.Dict(required=False)NEWLINE recipients = fields.List(fields.Dict(), required=False)NEWLINE ciphertext = B64Value(required=True)NEWLINE iv = B64Value(required=True)NEWLINE tag = B64Value(required=True)NEWLINE aad = B64Value(required=False)NEWLINE # flattened:NEWLINE header = fields.Dict(required=False)NEWLINE encrypted_key = B64Value(required=False)NEWLINENEWLINENEWLINEclass JweRecipientSchema(Schema):NEWLINE """JWE recipient schema."""NEWLINENEWLINE encrypted_key = B64Value(required=True)NEWLINE header = fields.Dict(many=True, required=False)NEWLINENEWLINENEWLINEclass JweRecipient:NEWLINE """A single message recipient."""NEWLINENEWLINE def __init__(self, *, encrypted_key: bytes, header: dict = None) -> "JweRecipient":NEWLINE """Initialize the JWE recipient."""NEWLINE self.encrypted_key = encrypted_keyNEWLINE self.header = header or {}NEWLINENEWLINE @classmethodNEWLINE def deserialize(cls, entry: Mapping[str, Any]) -> "JweRecipient":NEWLINE """Deserialize a JWE recipient from a mapping."""NEWLINE vals = JweRecipientSchema().load(entry)NEWLINE return cls(**vals)NEWLINENEWLINE def serialize(self) -> dict:NEWLINE """Serialize the JWE recipient to a mapping."""NEWLINE ret = OrderedDict([("encrypted_key", b64url(self.encrypted_key))])NEWLINE if self.header:NEWLINE ret["header"] = self.headerNEWLINE return retNEWLINENEWLINENEWLINEclass JweEnvelope:NEWLINE """JWE envelope instance."""NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE protected: dict = None,NEWLINE protected_b64: bytes = None,NEWLINE unprotected: dict = None,NEWLINE ciphertext: bytes = None,NEWLINE iv: bytes = None,NEWLINE tag: bytes = None,NEWLINE aad: bytes = None,NEWLINE with_protected_recipients: bool = False,NEWLINE with_flatten_recipients: bool = True,NEWLINE ):NEWLINE """Initialize a new JWE envelope instance."""NEWLINE self.protected = protectedNEWLINE self.protected_b64 = protected_b64NEWLINE self.unprotected = unprotected or OrderedDict()NEWLINE self.ciphertext = ciphertextNEWLINE self.iv = ivNEWLINE self.tag = tagNEWLINE self.aad = aadNEWLINE self.with_protected_recipients = with_protected_recipientsNEWLINE self.with_flatten_recipients = with_flatten_recipientsNEWLINE self._recipients: List[JweRecipient] = []NEWLINENEWLINE @classmethodNEWLINE def from_json(cls, message: Union[bytes, str]) -> "JweEnvelope":NEWLINE """Decode a JWE envelope from a JSON string or bytes value."""NEWLINE try:NEWLINE return cls._deserialize(JweSchema().loads(message))NEWLINE except json.JSONDecodeError:NEWLINE raise ValidationError("Invalid JWE: not JSON")NEWLINENEWLINE @classmethodNEWLINE def deserialize(cls, message: Mapping[str, Any]) -> "JweEnvelope":NEWLINE """Deserialize a JWE envelope from a mapping."""NEWLINE return cls._deserialize(JweSchema().load(message))NEWLINENEWLINE @classmethodNEWLINE def _deserialize(cls, parsed: Mapping[str, Any]) -> "JweEnvelope":NEWLINE protected_b64 = parsed[IDENT_PROTECTED]NEWLINE try:NEWLINE protected: dict = json.loads(from_b64url(protected_b64))NEWLINE except json.JSONDecodeError:NEWLINE raise ValidationError(NEWLINE "Invalid JWE: invalid JSON for protected headers"NEWLINE ) from NoneNEWLINE unprotected = parsed.get("unprotected") or dict()NEWLINE if protected.keys() & unprotected.keys():NEWLINE raise ValidationError("Invalid JWE: duplicate header")NEWLINENEWLINE encrypted_key = protected.get(IDENT_ENC_KEY) or parsed.get(IDENT_ENC_KEY)NEWLINE recipients = NoneNEWLINE protected_recipients = FalseNEWLINE flat_recipients = FalseNEWLINENEWLINE if IDENT_RECIPIENTS in protected:NEWLINE recipients = protected.pop(IDENT_RECIPIENTS)NEWLINE if IDENT_RECIPIENTS in parsed:NEWLINE raise ValidationError("Invalid JWE: duplicate recipients block")NEWLINE protected_recipients = TrueNEWLINE elif IDENT_RECIPIENTS in parsed:NEWLINE recipients = parsed[IDENT_RECIPIENTS]NEWLINENEWLINE if IDENT_ENC_KEY in protected:NEWLINE encrypted_key = from_b64url(protected.pop(IDENT_ENC_KEY))NEWLINE header = protected.pop(IDENT_HEADER) if IDENT_HEADER in protected else NoneNEWLINE protected_recipients = TrueNEWLINE elif IDENT_ENC_KEY in parsed:NEWLINE encrypted_key = parsed[IDENT_ENC_KEY]NEWLINE header = parsed.get(IDENT_HEADER)NEWLINENEWLINE if recipients:NEWLINE if encrypted_key:NEWLINE raise ValidationError("Invalid JWE: flattened form with 'recipients'")NEWLINE recipients = [JweRecipient.deserialize(recip) for recip in recipients]NEWLINE elif encrypted_key:NEWLINE recipients = [NEWLINE JweRecipient(NEWLINE encrypted_key=encrypted_key,NEWLINE header=header,NEWLINE )NEWLINE ]NEWLINE flat_recipients = TrueNEWLINE else:NEWLINE raise ValidationError("Invalid JWE: no recipients")NEWLINENEWLINE inst = cls(NEWLINE protected=protected,NEWLINE protected_b64=protected_b64,NEWLINE unprotected=unprotected,NEWLINE ciphertext=parsed["ciphertext"],NEWLINE iv=parsed.get("iv"),NEWLINE tag=parsed["tag"],NEWLINE aad=parsed.get("aad"),NEWLINE with_protected_recipients=protected_recipients,NEWLINE with_flatten_recipients=flat_recipients,NEWLINE )NEWLINE all_h = protected.keys() | unprotected.keys()NEWLINE for recip in recipients:NEWLINE if recip.header and recip.header.keys() & all_h:NEWLINE raise ValidationError("Invalid JWE: duplicate header")NEWLINE inst.add_recipient(recip)NEWLINENEWLINE return instNEWLINENEWLINE def serialize(self) -> dict:NEWLINE """Serialize the JWE envelope to a mapping."""NEWLINE if self.protected_b64 is None:NEWLINE raise ValidationError("Missing protected: use set_protected")NEWLINE if self.ciphertext is None:NEWLINE raise ValidationError("Missing ciphertext for JWE")NEWLINE if self.iv is None:NEWLINE raise ValidationError("Missing iv (nonce) for JWE")NEWLINE if self.tag is None:NEWLINE raise ValidationError("Missing tag for JWE")NEWLINE env = OrderedDict()NEWLINE env["protected"] = self.protected_b64NEWLINE if self.unprotected:NEWLINE env["unprotected"] = self.unprotected.copy()NEWLINE if not self.with_protected_recipients:NEWLINE recipients = self.recipients_jsonNEWLINE if self.with_flatten_recipients and len(recipients) == 1:NEWLINE for k in recipients[0]:NEWLINE env[k] = recipients[0][k]NEWLINE elif recipients:NEWLINE env[IDENT_RECIPIENTS] = recipientsNEWLINE else:NEWLINE raise ValidationError("Missing message recipients")NEWLINE env["iv"] = b64url(self.iv)NEWLINE env["ciphertext"] = b64url(self.ciphertext)NEWLINE env["tag"] = b64url(self.tag)NEWLINE if self.aad:NEWLINE env["aad"] = b64url(self.aad)NEWLINE return envNEWLINENEWLINE def to_json(self) -> str:NEWLINE """Serialize the JWE envelope to a JSON string."""NEWLINE return json.dumps(self.serialize())NEWLINENEWLINE def add_recipient(self, recip: JweRecipient):NEWLINE """Add a recipient to the JWE envelope."""NEWLINE self._recipients.append(recip)NEWLINENEWLINE def set_protected(NEWLINE self,NEWLINE protected: Mapping[str, Any],NEWLINE ):NEWLINE """Set the protected headers of the JWE envelope."""NEWLINE protected = OrderedDict(protected.items())NEWLINE if self.with_protected_recipients:NEWLINE recipients = self.recipients_jsonNEWLINE if self.with_flatten_recipients and len(recipients) == 1:NEWLINE protected.update(recipients[0])NEWLINE elif recipients:NEWLINE protected[IDENT_RECIPIENTS] = recipientsNEWLINE else:NEWLINE raise ValidationError("Missing message recipients")NEWLINE self.protected_b64 = b64url(json.dumps(protected))NEWLINENEWLINE @propertyNEWLINE def protected_bytes(self) -> bytes:NEWLINE """Access the protected data encoded as bytes.NEWLINENEWLINE This value is used in the additional authenticated data when encrypting.NEWLINE """NEWLINE return (NEWLINE self.protected_b64.encode("utf-8")NEWLINE if self.protected_b64 is not NoneNEWLINE else NoneNEWLINE )NEWLINENEWLINE def set_payload(self, ciphertext: bytes, iv: bytes, tag: bytes, aad: bytes = None):NEWLINE """Set the payload of the JWE envelope."""NEWLINE self.ciphertext = ciphertextNEWLINE self.iv = ivNEWLINE self.tag = tagNEWLINE self.aad = aadNEWLINENEWLINE @propertyNEWLINE def recipients(self) -> Iterable[JweRecipient]:NEWLINE """Accessor for an iterator over the JWE recipients.NEWLINENEWLINE The headers for each recipient include protected and unprotected headers from theNEWLINE outer envelope.NEWLINE """NEWLINE header = self.protected.copy()NEWLINE header.update(self.unprotected)NEWLINE for recip in self._recipients:NEWLINE if recip.header:NEWLINE recip_h = header.copy()NEWLINE recip_h.update(recip.header)NEWLINE yield JweRecipient(encrypted_key=recip.encrypted_key, header=recip_h)NEWLINE else:NEWLINE yield JweRecipient(encrypted_key=recip.encrypted_key, header=header)NEWLINENEWLINE @propertyNEWLINE def recipients_json(self) -> List[Dict[str, Any]]:NEWLINE """Encode the current recipients for JSON."""NEWLINE return [recip.serialize() for recip in self._recipients]NEWLINENEWLINE @propertyNEWLINE def recipient_key_ids(self) -> Iterable[JweRecipient]:NEWLINE """Accessor for an iterator over the JWE recipient key identifiers."""NEWLINE for recip in self._recipients:NEWLINE if recip.header and "kid" in recip.header:NEWLINE yield recip.header["kid"]NEWLINENEWLINE def get_recipient(self, kid: str) -> JweRecipient:NEWLINE """Find a recipient by key ID."""NEWLINE for recip in self._recipients:NEWLINE if recip.header and recip.header.get("kid") == kid:NEWLINE header = self.protected.copy()NEWLINE header.update(self.unprotected)NEWLINE header.update(recip.header)NEWLINE return JweRecipient(encrypted_key=recip.encrypted_key, header=header)NEWLINENEWLINE @propertyNEWLINE def combined_aad(self) -> bytes:NEWLINE """Accessor for the additional authenticated data."""NEWLINE aad = self.protected_bytesNEWLINE if self.aad:NEWLINE aad += b"." + b64url(self.aad).encode("utf-8")NEWLINE return aadNEWLINE # generated by datamodel-codegen:NEWLINE# filename: schema/api/services/updateDatabaseService.jsonNEWLINE# timestamp: 2021-10-01T19:50:55+00:00NEWLINENEWLINEfrom __future__ import annotationsNEWLINENEWLINEfrom typing import OptionalNEWLINENEWLINEfrom pydantic import BaseModel, FieldNEWLINENEWLINEfrom ...type import jdbcConnection, scheduleNEWLINENEWLINENEWLINEclass UpdateDatabaseServiceEntityRequest(BaseModel):NEWLINE description: Optional[str] = Field(NEWLINE None, description='Description of Database service entity.'NEWLINE )NEWLINE jdbc: Optional[jdbcConnection.JdbcInfo] = NoneNEWLINE ingestionSchedule: Optional[schedule.Schedule] = Field(NEWLINE None, description='Schedule for running metadata ingestion jobs'NEWLINE )NEWLINE class ServerFlushed:NEWLINE def __init__(self, request):NEWLINE self.request = requestNEWLINE _base_ = [NEWLINE 'r50_sz224_4xb64_head1_lr0_1_step_ep20.py',NEWLINE]NEWLINENEWLINE# optimizerNEWLINEoptimizer = dict(paramwise_options={'\\Ahead.': dict(lr_mult=100)})NEWLINE NEWLINEimport reNEWLINENEWLINENEWLINEclass RegexValidator(object):NEWLINE def __init__(self, pattern, excludes):NEWLINE if not pattern or pattern == '':NEWLINE pattern = '.*' # match anythingNEWLINE if not excludes or excludes == '':NEWLINE excludes = 'a^' # match nothingNEWLINENEWLINE self._pattern = re.compile(pattern)NEWLINE self._excludes = re.compile(excludes)NEWLINENEWLINE def is_valid(self, string):NEWLINE return self._pattern.match(string) and not self._excludes.match(string)NEWLINENEWLINENEWLINEclass FilesPathValidator(RegexValidator):NEWLINE def __init__(self, excluded_paths, pattern_regex, excludes_regex):NEWLINE self._excluded_paths = excluded_pathsNEWLINENEWLINE super(FilesPathValidator, self).__init__(pattern_regex, excludes_regex)NEWLINENEWLINE def is_valid(self, string):NEWLINE if string not in self._excluded_paths:NEWLINE return super(FilesPathValidator, self).is_valid(string)NEWLINE return FalseNEWLINENEWLINE # -*- coding: utf-8 -*-NEWLINEfrom __future__ import absolute_import, division, print_function, unicode_literalsNEWLINENEWLINEfrom copy import deepcopyNEWLINENEWLINEfrom django.test.testcases import TestCaseNEWLINENEWLINEfrom djstripe.models import CouponNEWLINENEWLINEfrom . import FAKE_COUPONNEWLINENEWLINENEWLINEclass TransferTest(TestCase):NEWLINE def test_retrieve_coupon(self):NEWLINE coupon_data = deepcopy(FAKE_COUPON)NEWLINE coupon = Coupon.sync_from_stripe_data(coupon_data)NEWLINE self.assertEqual(coupon.stripe_id, FAKE_COUPON["id"])NEWLINENEWLINENEWLINEclass HumanReadableCouponTest(TestCase):NEWLINE def test_human_readable_usd_off_forever(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-amount-off-forever", amount_off=10, currency="usd",NEWLINE duration="forever",NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "$10.00 USD off forever")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_eur_off_forever(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-amount-off-forever", amount_off=10, currency="eur",NEWLINE duration="forever",NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "€10.00 EUR off forever")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_percent_off_forever(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-percent-off-forever", percent_off=10, currency="usd",NEWLINE duration="forever",NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "10% off forever")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_percent_off_once(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-percent-off-once", percent_off=10, currency="usd",NEWLINE duration="once",NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "10% off once")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_percent_off_one_month(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-percent-off-1month", percent_off=10, currency="usd",NEWLINE duration="repeating", duration_in_months=1,NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "10% off for 1 month")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_percent_off_three_months(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-percent-off-3month", percent_off=10, currency="usd",NEWLINE duration="repeating", duration_in_months=3,NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "10% off for 3 months")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINE # (C) Datadog, Inc. 2018-presentNEWLINE# All rights reservedNEWLINE# Licensed under Simplified BSD License (see LICENSE)NEWLINENEWLINEimport copyNEWLINEimport loggingNEWLINEimport osNEWLINENEWLINEfrom datadog_checks.base.stubs.aggregator import AggregatorStubNEWLINEfrom datadog_checks.base.utils.common import get_docker_hostnameNEWLINEfrom datadog_checks.dev.docker import get_container_ipNEWLINEfrom datadog_checks.snmp import SnmpCheckNEWLINENEWLINElog = logging.getLogger(__name__)NEWLINENEWLINEHOST = get_docker_hostname()NEWLINEPORT = 1161NEWLINEHERE = os.path.dirname(os.path.abspath(__file__))NEWLINECOMPOSE_DIR = os.path.join(HERE, 'compose')NEWLINENEWLINEAUTH_PROTOCOLS = {'MD5': 'usmHMACMD5AuthProtocol', 'SHA': 'usmHMACSHAAuthProtocol'}NEWLINEPRIV_PROTOCOLS = {'DES': 'usmDESPrivProtocol', 'AES': 'usmAesCfb128Protocol'}NEWLINEAUTH_KEY = 'doggiepass'NEWLINEPRIV_KEY = 'doggiePRIVkey'NEWLINESNMP_CONTAINER_NAME = 'dd-snmp'NEWLINENEWLINECHECK_TAGS = ['snmp_device:{}'.format(HOST)]NEWLINENEWLINESNMP_CONF = {'name': 'snmp_conf', 'ip_address': HOST, 'port': PORT, 'community_string': 'public'}NEWLINENEWLINESNMP_V3_CONF = {NEWLINE 'name': 'snmp_v3_conf',NEWLINE 'ip_address': HOST,NEWLINE 'port': PORT,NEWLINE 'user': None,NEWLINE 'authKey': None,NEWLINE 'privKey': None,NEWLINE 'authProtocol': None,NEWLINE 'privProtocol': None,NEWLINE 'context_name': 'public',NEWLINE}NEWLINENEWLINEMIBS_FOLDER = {'mibs_folder': os.path.join(HERE, "mibs")}NEWLINENEWLINEIGNORE_NONINCREASING_OID = {'ignore_nonincreasing_oid': True}NEWLINENEWLINESUPPORTED_METRIC_TYPES = [NEWLINE {'OID': "1.3.6.1.2.1.7.1.0", 'name': "IAmACounter32"}, # Counter32NEWLINE {'OID': "1.3.6.1.2.1.4.31.1.1.6.1", 'name': "IAmACounter64"}, # Counter64NEWLINE {'OID': "1.3.6.1.2.1.4.24.6.0", 'name': "IAmAGauge32"}, # Gauge32NEWLINE {'OID': "1.3.6.1.2.1.88.1.1.1.0", 'name': "IAmAnInteger"}, # IntegerNEWLINE]NEWLINENEWLINEUNSUPPORTED_METRICS = [{'OID': "1.3.6.1.2.1.25.6.3.1.5.1", 'name': "IAmString"}] # String (not supported)NEWLINENEWLINECAST_METRICS = [NEWLINE {'OID': "1.3.6.1.4.1.2021.10.1.3.1", 'name': "cpuload1"}, # OctetStringNEWLINE {'OID': "1.3.6.1.4.1.2021.10.1.6.1", 'name': "cpuload2"}, # OpaqueNEWLINE]NEWLINENEWLINECONSTRAINED_OID = [{"MIB": "RFC1213-MIB", "symbol": "tcpRtoAlgorithm"}]NEWLINENEWLINEDUMMY_MIB_OID = [NEWLINE ({"MIB": "DUMMY-MIB", "symbol": "scalar"}, AggregatorStub.GAUGE, 10), # IntegerNEWLINE # Additional types we support but that are not part of the original SNMP protocol.NEWLINE ({"MIB": "DUMMY-MIB", "symbol": "dummyCounterGauge"}, AggregatorStub.GAUGE, 90), # CounterBasedGauge64NEWLINE ({"MIB": "DUMMY-MIB", "symbol": "dummyZeroCounter"}, AggregatorStub.RATE, 120), # ZeroBasedCounter64NEWLINE]NEWLINENEWLINEFORCED_METRICS = [NEWLINE {'OID': "1.3.6.1.2.1.4.24.6.0", 'name': "IAmAGauge32", 'forced_type': 'counter'}, # Gauge32NEWLINE {'OID': "1.3.6.1.2.1.4.31.1.1.6.1", 'name': "IAmACounter64", 'forced_type': 'gauge'}, # Counter32NEWLINE]NEWLINEINVALID_FORCED_METRICS = [NEWLINE {'OID': "1.3.6.1.2.1.4.24.6.0", 'name': "IAmAGauge32", 'forced_type': 'counter'}, # Gauge32NEWLINE {'OID': "1.3.6.1.2.1.4.31.1.1.6.1", 'name': "IAmACounter64", 'forced_type': 'histogram'}, # Counter32NEWLINE]NEWLINENEWLINESCALAR_OBJECTS = [NEWLINE {'OID': "1.3.6.1.2.1.7.1.0", 'name': "udpDatagrams"},NEWLINE {'OID': "1.3.6.1.2.1.6.10.0", 'name': "tcpInSegs"},NEWLINE {'OID': ".1.3.6.1.6.3.10.2.1.3.0", 'name': "snmpEngineTime"}, # OID with leading dotNEWLINE {'MIB': "TCP-MIB", 'symbol': "tcpCurrEstab"},NEWLINE]NEWLINENEWLINESCALAR_OBJECTS_WITH_TAGS = [NEWLINE {'OID': "1.3.6.1.2.1.7.1.0", 'name': "udpDatagrams", 'metric_tags': ['udpdgrams', 'UDP']},NEWLINE {'OID': "1.3.6.1.2.1.6.10.0", 'name': "tcpInSegs", 'metric_tags': ['tcpinsegs', 'TCP']},NEWLINE {'MIB': "TCP-MIB", 'symbol': "tcpCurrEstab", 'metric_tags': ['MIB', 'TCP', 'estab']},NEWLINE]NEWLINENEWLINETABULAR_OBJECTS = [NEWLINE {NEWLINE 'MIB': "IF-MIB",NEWLINE 'table': "ifTable",NEWLINE 'symbols': ["ifInOctets", "ifOutOctets"],NEWLINE 'metric_tags': [{'tag': "interface", 'column': "ifDescr"}, {'tag': "dumbindex", 'index': 1}],NEWLINE }NEWLINE]NEWLINENEWLINEBULK_TABULAR_OBJECTS = [NEWLINE {NEWLINE 'MIB': "IF-MIB",NEWLINE 'table': "ifTable",NEWLINE 'symbols': [NEWLINE "ifInOctets",NEWLINE "ifOutOctets",NEWLINE "ifInUcastPkts",NEWLINE "ifInUcastPkts",NEWLINE "ifInNUcastPkts",NEWLINE "ifInDiscards",NEWLINE "ifInErrors",NEWLINE "ifInUnknownProtos",NEWLINE ],NEWLINE 'metric_tags': [{'tag': "interface", 'column': "ifDescr"}, {'tag': "dumbindex", 'index': 1}],NEWLINE },NEWLINE {NEWLINE 'MIB': "IP-MIB",NEWLINE 'table': "ipSystemStatsTable",NEWLINE 'symbols': [NEWLINE "ipSystemStatsInReceives",NEWLINE "ipSystemStatsHCInReceives",NEWLINE "ipSystemStatsInOctets",NEWLINE "ipSystemStatsHCInOctets",NEWLINE "ipSystemStatsInHdrErrors",NEWLINE "ipSystemStatsInNoRoutes",NEWLINE "ipSystemStatsInAddrErrors",NEWLINE "ipSystemStatsInUnknownProtos",NEWLINE "ipSystemStatsInTruncatedPkts",NEWLINE "ipSystemStatsInForwDatagrams",NEWLINE "ipSystemStatsHCInForwDatagrams",NEWLINE "ipSystemStatsReasmReqds",NEWLINE "ipSystemStatsReasmOKs",NEWLINE "ipSystemStatsReasmFails",NEWLINE "ipSystemStatsInDiscards",NEWLINE "ipSystemStatsInDelivers",NEWLINE "ipSystemStatsHCInDelivers",NEWLINE "ipSystemStatsOutRequests",NEWLINE "ipSystemStatsHCOutRequests",NEWLINE "ipSystemStatsOutNoRoutes",NEWLINE "ipSystemStatsOutForwDatagrams",NEWLINE "ipSystemStatsHCOutForwDatagrams",NEWLINE "ipSystemStatsOutDiscards",NEWLINE "ipSystemStatsOutFragReqds",NEWLINE "ipSystemStatsOutFragOKs",NEWLINE "ipSystemStatsOutFragFails",NEWLINE "ipSystemStatsOutFragCreates",NEWLINE "ipSystemStatsOutTransmits",NEWLINE "ipSystemStatsHCOutTransmits",NEWLINE "ipSystemStatsOutOctets",NEWLINE "ipSystemStatsHCOutOctets",NEWLINE "ipSystemStatsInMcastPkts",NEWLINE ],NEWLINE },NEWLINE]NEWLINENEWLINEINVALID_METRICS = [{'MIB': "IF-MIB", 'table': "noIdeaWhatIAmDoingHere", 'symbols': ["ImWrong", "MeToo"]}]NEWLINENEWLINEPLAY_WITH_GET_NEXT_METRICS = [NEWLINE {"OID": "1.3.6.1.2.1.4.31.3.1.3.2", "name": "needFallback"},NEWLINE {"OID": "1.3.6.1.2.1.4.31.3.1.3.2.1", "name": "noFallbackAndSameResult"},NEWLINE]NEWLINENEWLINERESOLVED_TABULAR_OBJECTS = [NEWLINE {NEWLINE "MIB": "IF-MIB",NEWLINE "table": "ifTable",NEWLINE "symbols": [NEWLINE {"name": "ifInOctets", "OID": "1.3.6.1.2.1.2.2.1.10"},NEWLINE {"name": "ifOutOctets", "OID": "1.3.6.1.2.1.2.2.1.16"},NEWLINE ],NEWLINE "metric_tags": [NEWLINE {"tag": "interface", "column": {"name": "ifDescr", "OID": "1.3.6.1.2.1.2.2.1.2"}},NEWLINE {"tag": "dumbindex", "index": 1, "mapping": {1: "one", 2: "two", 3: "three", 90: "other"}},NEWLINE ],NEWLINE }NEWLINE]NEWLINENEWLINENEWLINEdef generate_instance_config(metrics, template=None):NEWLINE template = template if template else SNMP_CONFNEWLINE instance_config = copy.copy(template)NEWLINE instance_config['metrics'] = metricsNEWLINE instance_config['name'] = HOSTNEWLINE return instance_configNEWLINENEWLINENEWLINEdef generate_container_instance_config(metrics):NEWLINE conf = copy.deepcopy(SNMP_CONF)NEWLINE conf['ip_address'] = get_container_ip(SNMP_CONTAINER_NAME)NEWLINE return generate_instance_config(metrics, template=conf)NEWLINENEWLINENEWLINEdef generate_v3_instance_config(metrics, name=None, user=None, auth=None, auth_key=None, priv=None, priv_key=None):NEWLINE instance_config = generate_instance_config(metrics, SNMP_V3_CONF)NEWLINENEWLINE if name:NEWLINE instance_config['name'] = nameNEWLINE if user:NEWLINE instance_config['user'] = userNEWLINE if auth:NEWLINE instance_config['authProtocol'] = authNEWLINE if auth_key:NEWLINE instance_config['authKey'] = auth_keyNEWLINE if priv:NEWLINE instance_config['privProtocol'] = privNEWLINE if priv_key:NEWLINE instance_config['privKey'] = priv_keyNEWLINENEWLINE return instance_configNEWLINENEWLINENEWLINEdef create_check(instance):NEWLINE return SnmpCheck('snmp', {}, [instance])NEWLINE formatter = "%r %r %r %r"NEWLINEprint (formatter % (1 ,2 ,3 , 4))NEWLINEprint (formatter % ("one","two","three","four"))NEWLINEprint (formatter % (True, False, False, True))NEWLINEprint (formatter % (formatter ,formatter, formatter, formatter))NEWLINEprint (formatter % NEWLINE ("I had this thing.",NEWLINE "That you could type up right.",NEWLINE "But it didn't sing.",NEWLINE "So I said goodnight.")NEWLINE )NEWLINE NEWLINE #!/usr/bin/pythonNEWLINE# Copyright 2012 William YuNEWLINE# wyu@ateneo.eduNEWLINE#NEWLINE# This file is part of POX.NEWLINE#NEWLINE# POX is free software: you can redistribute it and/or modifyNEWLINE# it under the terms of the GNU General Public License as published byNEWLINE# the Free Software Foundation, either version 3 of the License, orNEWLINE# (at your option) any later version.NEWLINE#NEWLINE# POX is distributed in the hope that it will be useful,NEWLINE# but WITHOUT ANY WARRANTY; without even the implied warranty ofNEWLINE# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theNEWLINE# GNU General Public License for more details.NEWLINE#NEWLINE# You should have received a copy of the GNU General Public LicenseNEWLINE# along with POX. If not, see .NEWLINE#NEWLINENEWLINE"""NEWLINEThis is a demonstration file created to show how to obtain flowNEWLINEand port statistics from OpenFlow 1.0-enabled switches. The flowNEWLINEstatistics handler contains a summary of web-only traffic.NEWLINE"""NEWLINENEWLINE# standard includesNEWLINEfrom pox.core import coreNEWLINEfrom pox.lib.util import dpidToStrNEWLINEimport pox.openflow.libopenflow_01 as ofNEWLINEfrom collections import defaultdictNEWLINENEWLINE# include as part of the betta branchNEWLINEfrom pox.openflow.of_json import *NEWLINENEWLINEfrom pox.forwarding.my_l2_multi import SwitchNEWLINENEWLINENEWLINEtime_period = 5 # time between stats requestsNEWLINEthreshhold = 2000000 # = 3Mbit/s na 8 dla allNEWLINEpaths = defaultdict(lambda:defaultdict(lambda:[]))NEWLINElog = core.getLogger()NEWLINEsws = {} # switchesNEWLINE#host_switch_pair = defaultdict(lambda:None)NEWLINENEWLINENEWLINE# get paths from my_l2_multi moduleNEWLINEdef get_paths():NEWLINE global swsNEWLINE from pox.forwarding.my_l2_multi import switchesNEWLINE if sws != switches:NEWLINE sws = switchesNEWLINE log.debug("NOT EQUAL - switches has changed since last time we checked")NEWLINE # to do - > add some clearing for statsNEWLINE else:NEWLINE # log.debug("EQUAL")NEWLINE passNEWLINE for sw in sws.values():NEWLINE #log.debug("Switch %s, ports %s", dpidToStr(sw.dpid), sw.ports)NEWLINE passNEWLINENEWLINE global pathsNEWLINE from pox.forwarding.my_l2_multi import all_cooked_pathsNEWLINE if paths != all_cooked_paths:NEWLINE paths = all_cooked_pathsNEWLINE log.debug("NOT EQUAL - paths has changed since last time we checked")NEWLINE # to do - > add some clearing for statsNEWLINE else:NEWLINE log.debug("EQUAL - paths has not changed since last time we checked")NEWLINENEWLINENEWLINE from pox.forwarding.my_l2_multi import path_mapNEWLINE global path_mapNEWLINENEWLINE from pox.forwarding.my_l2_multi import host_switch_pairNEWLINE global host_switch_pairNEWLINENEWLINENEWLINENEWLINE# when _handle_portstats_received will receive stats for port on switchNEWLINE# it will send them here to be applied for paths,NEWLINE# stats here are bytes sent by this portNEWLINEdef apply_stats_to_paths(switch, port, stats):NEWLINE # global pathsNEWLINE # log.debug("Checking switch %s port %s ", switch, port )NEWLINE # for src in sws.values():NEWLINE # for dst in sws.values():NEWLINE # for path in paths[src][dst]:NEWLINE # for switch_port_pair in path:NEWLINE # #log.debug("switch-port pair %s, %s", dpidToStr(switch_port_pair[0].dpid), switch_port_pair[1] )NEWLINE # if switch == dpidToStr(switch_port_pair[0].dpid) and port == switch_port_pair[1]:NEWLINE # # log.debug("switch-port pair %s, %s", dpidToStr(switch_port_pair[0].dpid), switch_port_pair[1] )NEWLINE # # log.debug(path)NEWLINE # # switch_port_pair.append(stats) -> this isn't working, what is better?NEWLINE # # to do -> how append stats?NEWLINE # # print statsNEWLINE # passNEWLINE from pox.forwarding.my_l2_multi import CookedPathNEWLINE for cookedpathobj in CookedPath:NEWLINE for switch_port_pair in cookedpathobj.cooked_path:NEWLINE if switch == dpidToStr(switch_port_pair[0].dpid) and port == switch_port_pair[2]:NEWLINE cookedpathobj.bytes_diff_list[cookedpathobj.cooked_path.index(switch_port_pair)] = \NEWLINE stats - cookedpathobj.bytes_diff_list[cookedpathobj.cooked_path.index(switch_port_pair)]NEWLINE # log.debug("Switch-port pair %s, %s", dpidToStr(switch_port_pair[0].dpid), switch_port_pair[2])NEWLINE # log.debug("Bytes sent overall: %s", stats)NEWLINE log.debug("Path: %s", cookedpathobj.cooked_path)NEWLINE log.debug("Bytes diff list: %s", cookedpathobj.bytes_diff_list)NEWLINE cookedpathobj.path_coefficient = max(cookedpathobj.bytes_diff_list[:-1])NEWLINE # log.debug("Path coeff: %s", cookedpathobj.path_coefficient)NEWLINENEWLINE# handler for timer function that sends the requests to all theNEWLINE# switches connected to the controller.NEWLINEdef _timer_func ():NEWLINE get_paths()NEWLINE for connection in core.openflow._connections.values():NEWLINE connection.send(of.ofp_stats_request(body=of.ofp_flow_stats_request()))NEWLINE connection.send(of.ofp_stats_request(body=of.ofp_port_stats_request()))NEWLINE log.debug("Sent %i flow/port stats request(s)", len(core.openflow._connections))NEWLINENEWLINE# handler to display flow statistics received in JSON formatNEWLINE# structure of event.stats is defined by ofp_flow_stats()NEWLINEdef _handle_flowstats_received (event):NEWLINE stats = flow_stats_to_list(event.stats)NEWLINE #log.debug("FlowStatsReceived from %s: %s",NEWLINE # dpidToStr(event.connection.dpid), stats)NEWLINE for flow_stats in event.stats:NEWLINE # log.debug("Bytes in flow match%s: %s",NEWLINE # flow_stats.match, flow_stats.byte_count)NEWLINENEWLINE # ALL THIS HAS TO BE CHECK YET !!! - > no duplications, add flow deleting after some time, etc.NEWLINE # We want to gather stats for flow only in switch connected to src hostNEWLINE # to avoid duplicationNEWLINE if host_switch_pair[flow_stats.match.dl_src][0] == event.connection.dpid:NEWLINE # log.debug("Flow stats found ", flow_stats.match.dl_src, host_switch_pair[flow_stats.match.dl_src], event.connection.dpid)NEWLINE # Only IP flowsNEWLINE if flow_stats.match.dl_type == 0x800:NEWLINE log.debug('IP Matched')NEWLINE flow_match5 = [flow_stats.match.nw_proto, flow_stats.match.nw_src, flow_stats.match.nw_dst, \NEWLINE flow_stats.match.tp_src, flow_stats.match.tp_dst]NEWLINE from pox.forwarding.my_l2_multi import flow_listNEWLINE for flow in flow_list:NEWLINE #print "Flow match stat", flow_match5NEWLINE #print "Flow match List", flow.match, "\n"NEWLINE if flow.match5 == flow_match5:NEWLINE log.debug("Flow 5 Match found")NEWLINE if flow.changed == 1:NEWLINE break # we only change path onceNEWLINE # TO DO -> handle timeouts, different switches etc.NEWLINE # we want to take stats only from switch connected to host to avoid complicationsNEWLINE flow.byte_diff = flow_stats.byte_count - flow.byte_countNEWLINE log.debug("Bytes: received from stats %s, from this flow last checked %s, diff %s, bandwith in bits %s",NEWLINE flow_stats.byte_count, flow.byte_count, flow.byte_diff, flow.byte_diff/time_period*8)NEWLINE flow.byte_count = flow_stats.byte_countNEWLINENEWLINE if flow.byte_diff/time_period*8 > threshhold:NEWLINE log.debug("Uuuuuu, found big flow! %s", flow.match)NEWLINE print "Sw src, sw dst: ", flow.switch_src, flow.switch_dstNEWLINE intermediate = path_map[flow.switch_src][flow.switch_dst][1]NEWLINE if intermediate is None:NEWLINE print "Directly connected"NEWLINENEWLINE best_path = find_best_path(flow.switch_src, flow.switch_dst)NEWLINE print "best path, flow path:"NEWLINE print best_path, "\n", flow.pathNEWLINE if best_path != flow.path and best_path is not None:NEWLINE print "\nPath of big flow is not the best path - moved!\n"NEWLINE Switch.delete_path(sws[event.connection.dpid], flow.path, flow.match)NEWLINE Switch._install_path(sws[event.connection.dpid], best_path, flow.match)NEWLINE flow.path = best_pathNEWLINE flow.changed = 1NEWLINENEWLINE breakNEWLINENEWLINENEWLINE# handler to display port statistics received in JSON formatNEWLINEdef _handle_portstats_received (event):NEWLINE stats = flow_stats_to_list(event.stats)NEWLINE # log.debug("PortStatsReceived from %s: %s",NEWLINE # dpidToStr(event.connection.dpid), stats)NEWLINENEWLINE for f in event.stats:NEWLINE if int(f.port_no)<65534:NEWLINE apply_stats_to_paths(dpidToStr(event.connection.dpid), f.port_no, f.tx_bytes)NEWLINENEWLINENEWLINEdef find_best_path(src, dst):NEWLINE best_path_coeff = NoneNEWLINE best_path = NoneNEWLINE from pox.forwarding.my_l2_multi import CookedPathNEWLINE print "Cooked paths:"NEWLINE for cookedpathobj in CookedPath:NEWLINE if cookedpathobj.switch_src == src and cookedpathobj.switch_dst == dst:NEWLINE print cookedpathobj.cooked_pathNEWLINE print cookedpathobj.bytes_diff_list, cookedpathobj.path_coefficientNEWLINENEWLINE if best_path_coeff is None:NEWLINE best_path_coeff = cookedpathobj.path_coefficientNEWLINE best_path = cookedpathobj.cooked_pathNEWLINE log.debug("Best path: %s, coeff: %s", best_path, best_path_coeff)NEWLINE elif cookedpathobj.path_coefficient < best_path_coeff:NEWLINE best_path_coeff = cookedpathobj.path_coefficientNEWLINE best_path = cookedpathobj.cooked_pathNEWLINE log.debug("Best path: %s, coeff: %s", best_path, best_path_coeff)NEWLINE return best_pathNEWLINENEWLINENEWLINENEWLINENEWLINE# main functiont to launch the moduleNEWLINEdef launch ():NEWLINE from pox.lib.recoco import TimerNEWLINENEWLINE # attach handsers to listnersNEWLINE core.openflow.addListenerByName("FlowStatsReceived",NEWLINE _handle_flowstats_received)NEWLINE core.openflow.addListenerByName("PortStatsReceived",NEWLINE _handle_portstats_received)NEWLINENEWLINE # timer set to execute every five secondsNEWLINE Timer(time_period, _timer_func, recurring=True) import pickleNEWLINEimport sysNEWLINEimport warningsNEWLINEfrom copy import copy, deepcopyNEWLINEfrom io import StringIONEWLINEfrom textwrap import dedentNEWLINENEWLINEimport numpy as npNEWLINEimport pandas as pdNEWLINEimport pytestNEWLINENEWLINEimport xarray as xrNEWLINEfrom xarray import (NEWLINE DataArray,NEWLINE Dataset,NEWLINE IndexVariable,NEWLINE MergeError,NEWLINE Variable,NEWLINE align,NEWLINE backends,NEWLINE broadcast,NEWLINE open_dataset,NEWLINE set_options,NEWLINE)NEWLINEfrom xarray.core import dtypes, indexing, utilsNEWLINEfrom xarray.core.common import duck_array_ops, full_likeNEWLINEfrom xarray.core.npcompat import IS_NEP18_ACTIVENEWLINEfrom xarray.core.pycompat import integer_typesNEWLINENEWLINEfrom . import (NEWLINE InaccessibleArray,NEWLINE LooseVersion,NEWLINE UnexpectedDataAccess,NEWLINE assert_allclose,NEWLINE assert_array_equal,NEWLINE assert_equal,NEWLINE assert_identical,NEWLINE has_cftime,NEWLINE has_dask,NEWLINE raises_regex,NEWLINE requires_bottleneck,NEWLINE requires_cftime,NEWLINE requires_dask,NEWLINE requires_numbagg,NEWLINE requires_scipy,NEWLINE requires_sparse,NEWLINE source_ndarray,NEWLINE)NEWLINENEWLINEtry:NEWLINE import dask.array as daNEWLINEexcept ImportError:NEWLINE passNEWLINENEWLINENEWLINEdef create_test_data(seed=None):NEWLINE rs = np.random.RandomState(seed)NEWLINE _vars = {NEWLINE "var1": ["dim1", "dim2"],NEWLINE "var2": ["dim1", "dim2"],NEWLINE "var3": ["dim3", "dim1"],NEWLINE }NEWLINE _dims = {"dim1": 8, "dim2": 9, "dim3": 10}NEWLINENEWLINE obj = Dataset()NEWLINE obj["time"] = ("time", pd.date_range("2000-01-01", periods=20))NEWLINE obj["dim2"] = ("dim2", 0.5 * np.arange(_dims["dim2"]))NEWLINE obj["dim3"] = ("dim3", list("abcdefghij"))NEWLINE for v, dims in sorted(_vars.items()):NEWLINE data = rs.normal(size=tuple(_dims[d] for d in dims))NEWLINE obj[v] = (dims, data, {"foo": "variable"})NEWLINE obj.coords["numbers"] = (NEWLINE "dim3",NEWLINE np.array([0, 1, 2, 0, 0, 1, 1, 2, 2, 3], dtype="int64"),NEWLINE )NEWLINE obj.encoding = {"foo": "bar"}NEWLINE assert all(obj.data.flags.writeable for obj in obj.variables.values())NEWLINE return objNEWLINENEWLINENEWLINEdef create_append_test_data(seed=None):NEWLINE rs = np.random.RandomState(seed)NEWLINENEWLINE lat = [2, 1, 0]NEWLINE lon = [0, 1, 2]NEWLINE nt1 = 3NEWLINE nt2 = 2NEWLINE time1 = pd.date_range("2000-01-01", periods=nt1)NEWLINE time2 = pd.date_range("2000-02-01", periods=nt2)NEWLINE string_var = np.array(["ae", "bc", "df"], dtype=object)NEWLINE string_var_to_append = np.array(["asdf", "asdfg"], dtype=object)NEWLINE unicode_var = ["áó", "áó", "áó"]NEWLINENEWLINE ds = xr.Dataset(NEWLINE data_vars={NEWLINE "da": xr.DataArray(NEWLINE rs.rand(3, 3, nt1),NEWLINE coords=[lat, lon, time1],NEWLINE dims=["lat", "lon", "time"],NEWLINE ),NEWLINE "string_var": xr.DataArray(string_var, coords=[time1], dims=["time"]),NEWLINE "unicode_var": xr.DataArray(NEWLINE unicode_var, coords=[time1], dims=["time"]NEWLINE ).astype(np.unicode_),NEWLINE }NEWLINE )NEWLINENEWLINE ds_to_append = xr.Dataset(NEWLINE data_vars={NEWLINE "da": xr.DataArray(NEWLINE rs.rand(3, 3, nt2),NEWLINE coords=[lat, lon, time2],NEWLINE dims=["lat", "lon", "time"],NEWLINE ),NEWLINE "string_var": xr.DataArray(NEWLINE string_var_to_append, coords=[time2], dims=["time"]NEWLINE ),NEWLINE "unicode_var": xr.DataArray(NEWLINE unicode_var[:nt2], coords=[time2], dims=["time"]NEWLINE ).astype(np.unicode_),NEWLINE }NEWLINE )NEWLINENEWLINE ds_with_new_var = xr.Dataset(NEWLINE data_vars={NEWLINE "new_var": xr.DataArray(NEWLINE rs.rand(3, 3, nt1 + nt2),NEWLINE coords=[lat, lon, time1.append(time2)],NEWLINE dims=["lat", "lon", "time"],NEWLINE )NEWLINE }NEWLINE )NEWLINENEWLINE assert all(objp.data.flags.writeable for objp in ds.variables.values())NEWLINE assert all(objp.data.flags.writeable for objp in ds_to_append.variables.values())NEWLINE return ds, ds_to_append, ds_with_new_varNEWLINENEWLINENEWLINEdef create_test_multiindex():NEWLINE mindex = pd.MultiIndex.from_product(NEWLINE [["a", "b"], [1, 2]], names=("level_1", "level_2")NEWLINE )NEWLINE return Dataset({}, {"x": mindex})NEWLINENEWLINENEWLINEdef create_test_stacked_array():NEWLINE x = DataArray(pd.Index(np.r_[:10], name="x"))NEWLINE y = DataArray(pd.Index(np.r_[:20], name="y"))NEWLINE a = x * yNEWLINE b = x * y * yNEWLINE return a, bNEWLINENEWLINENEWLINEclass InaccessibleVariableDataStore(backends.InMemoryDataStore):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINE self._indexvars = set()NEWLINENEWLINE def store(self, variables, *args, **kwargs):NEWLINE super().store(variables, *args, **kwargs)NEWLINE for k, v in variables.items():NEWLINE if isinstance(v, IndexVariable):NEWLINE self._indexvars.add(k)NEWLINENEWLINE def get_variables(self):NEWLINE def lazy_inaccessible(k, v):NEWLINE if k in self._indexvars:NEWLINE return vNEWLINE data = indexing.LazilyOuterIndexedArray(InaccessibleArray(v.values))NEWLINE return Variable(v.dims, data, v.attrs)NEWLINENEWLINE return {k: lazy_inaccessible(k, v) for k, v in self._variables.items()}NEWLINENEWLINENEWLINEclass TestDataset:NEWLINE def test_repr(self):NEWLINE data = create_test_data(seed=123)NEWLINE data.attrs["foo"] = "bar"NEWLINE # need to insert str dtype at runtime to handle different endiannessNEWLINE expected = dedent(NEWLINE """\NEWLINE NEWLINE Dimensions: (dim1: 8, dim2: 9, dim3: 10, time: 20)NEWLINE Coordinates:NEWLINE * time (time) datetime64[ns] 2000-01-01 2000-01-02 ... 2000-01-20NEWLINE * dim2 (dim2) float64 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0NEWLINE * dim3 (dim3) %s 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j'NEWLINE numbers (dim3) int64 0 1 2 0 0 1 1 2 2 3NEWLINE Dimensions without coordinates: dim1NEWLINE Data variables:NEWLINE var1 (dim1, dim2) float64 -1.086 0.9973 0.283 ... 0.1995 0.4684 -0.8312NEWLINE var2 (dim1, dim2) float64 1.162 -1.097 -2.123 ... 0.1302 1.267 0.3328NEWLINE var3 (dim3, dim1) float64 0.5565 -0.2121 0.4563 ... -0.2452 -0.3616NEWLINE Attributes:NEWLINE foo: bar"""NEWLINE % data["dim3"].dtypeNEWLINE )NEWLINE actual = "\n".join(x.rstrip() for x in repr(data).split("\n"))NEWLINE print(actual)NEWLINE assert expected == actualNEWLINENEWLINE with set_options(display_width=100):NEWLINE max_len = max(map(len, repr(data).split("\n")))NEWLINE assert 90 < max_len < 100NEWLINENEWLINE expected = dedent(NEWLINE """\NEWLINE NEWLINE Dimensions: ()NEWLINE Data variables:NEWLINE *empty*"""NEWLINE )NEWLINE actual = "\n".join(x.rstrip() for x in repr(Dataset()).split("\n"))NEWLINE print(actual)NEWLINE assert expected == actualNEWLINENEWLINE # verify that ... doesn't appear for scalar coordinatesNEWLINE data = Dataset({"foo": ("x", np.ones(10))}).mean()NEWLINE expected = dedent(NEWLINE """\NEWLINE NEWLINE Dimensions: ()NEWLINE Data variables:NEWLINE foo float64 1.0"""NEWLINE )NEWLINE actual = "\n".join(x.rstrip() for x in repr(data).split("\n"))NEWLINE print(actual)NEWLINE assert expected == actualNEWLINENEWLINE # verify long attributes are truncatedNEWLINE data = Dataset(attrs={"foo": "bar" * 1000})NEWLINE assert len(repr(data)) < 1000NEWLINENEWLINE def test_repr_multiindex(self):NEWLINE data = create_test_multiindex()NEWLINE expected = dedent(NEWLINE """\NEWLINE NEWLINE Dimensions: (x: 4)NEWLINE Coordinates:NEWLINE * x (x) MultiIndexNEWLINE - level_1 (x) object 'a' 'a' 'b' 'b'NEWLINE - level_2 (x) int64 1 2 1 2NEWLINE Data variables:NEWLINE *empty*"""NEWLINE )NEWLINE actual = "\n".join(x.rstrip() for x in repr(data).split("\n"))NEWLINE print(actual)NEWLINE assert expected == actualNEWLINENEWLINE # verify that long level names are not truncatedNEWLINE mindex = pd.MultiIndex.from_product(NEWLINE [["a", "b"], [1, 2]], names=("a_quite_long_level_name", "level_2")NEWLINE )NEWLINE data = Dataset({}, {"x": mindex})NEWLINE expected = dedent(NEWLINE """\NEWLINE NEWLINE Dimensions: (x: 4)NEWLINE Coordinates:NEWLINE * x (x) MultiIndexNEWLINE - a_quite_long_level_name (x) object 'a' 'a' 'b' 'b'NEWLINE - level_2 (x) int64 1 2 1 2NEWLINE Data variables:NEWLINE *empty*"""NEWLINE )NEWLINE actual = "\n".join(x.rstrip() for x in repr(data).split("\n"))NEWLINE print(actual)NEWLINE assert expected == actualNEWLINENEWLINE def test_repr_period_index(self):NEWLINE data = create_test_data(seed=456)NEWLINE data.coords["time"] = pd.period_range("2000-01-01", periods=20, freq="B")NEWLINENEWLINE # check that creating the repr doesn't raise an error #GH645NEWLINE repr(data)NEWLINENEWLINE def test_unicode_data(self):NEWLINE # regression test for GH834NEWLINE data = Dataset({"foø": ["ba®"]}, attrs={"å": "∑"})NEWLINE repr(data) # should not raiseNEWLINENEWLINE byteorder = "<" if sys.byteorder == "little" else ">"NEWLINE expected = dedent(NEWLINE """\NEWLINE NEWLINE Dimensions: (foø: 1)NEWLINE Coordinates:NEWLINE * foø (foø) %cU3 %rNEWLINE Data variables:NEWLINE *empty*NEWLINE Attributes:NEWLINE å: ∑"""NEWLINE % (byteorder, "ba®")NEWLINE )NEWLINE actual = str(data)NEWLINE assert expected == actualNEWLINENEWLINE @pytest.mark.skipif(not IS_NEP18_ACTIVE, reason="requires __array_function__")NEWLINE def test_repr_nep18(self):NEWLINE class Array:NEWLINE def __init__(self):NEWLINE self.shape = (2,)NEWLINE self.dtype = np.dtype(np.float64)NEWLINENEWLINE def __array_function__(self, *args, **kwargs):NEWLINE passNEWLINENEWLINE def __repr__(self):NEWLINE return "Custom\nArray"NEWLINENEWLINE dataset = Dataset({"foo": ("x", Array())})NEWLINE expected = dedent(NEWLINE """\NEWLINE NEWLINE Dimensions: (x: 2)NEWLINE Dimensions without coordinates: xNEWLINE Data variables:NEWLINE foo (x) float64 Custom Array"""NEWLINE )NEWLINE assert expected == repr(dataset)NEWLINENEWLINE def test_info(self):NEWLINE ds = create_test_data(seed=123)NEWLINE ds = ds.drop_vars("dim3") # string type prints differently in PY2 vs PY3NEWLINE ds.attrs["unicode_attr"] = "ba®"NEWLINE ds.attrs["string_attr"] = "bar"NEWLINENEWLINE buf = StringIO()NEWLINE ds.info(buf=buf)NEWLINENEWLINE expected = dedent(NEWLINE """\NEWLINE xarray.Dataset {NEWLINE dimensions:NEWLINE \tdim1 = 8 ;NEWLINE \tdim2 = 9 ;NEWLINE \tdim3 = 10 ;NEWLINE \ttime = 20 ;NEWLINENEWLINE variables:NEWLINE \tdatetime64[ns] time(time) ;NEWLINE \tfloat64 dim2(dim2) ;NEWLINE \tfloat64 var1(dim1, dim2) ;NEWLINE \t\tvar1:foo = variable ;NEWLINE \tfloat64 var2(dim1, dim2) ;NEWLINE \t\tvar2:foo = variable ;NEWLINE \tfloat64 var3(dim3, dim1) ;NEWLINE \t\tvar3:foo = variable ;NEWLINE \tint64 numbers(dim3) ;NEWLINENEWLINE // global attributes:NEWLINE \t:unicode_attr = ba® ;NEWLINE \t:string_attr = bar ;NEWLINE }"""NEWLINE )NEWLINE actual = buf.getvalue()NEWLINE assert expected == actualNEWLINE buf.close()NEWLINENEWLINE def test_constructor(self):NEWLINE x1 = ("x", 2 * np.arange(100))NEWLINE x2 = ("x", np.arange(1000))NEWLINE z = (["x", "y"], np.arange(1000).reshape(100, 10))NEWLINENEWLINE with raises_regex(ValueError, "conflicting sizes"):NEWLINE Dataset({"a": x1, "b": x2})NEWLINE with raises_regex(ValueError, "disallows such variables"):NEWLINE Dataset({"a": x1, "x": z})NEWLINE with raises_regex(TypeError, "tuple of form"):NEWLINE Dataset({"x": (1, 2, 3, 4, 5, 6, 7)})NEWLINE with raises_regex(ValueError, "already exists as a scalar"):NEWLINE Dataset({"x": 0, "y": ("x", [1, 2, 3])})NEWLINENEWLINE # verify handling of DataArraysNEWLINE expected = Dataset({"x": x1, "z": z})NEWLINE actual = Dataset({"z": expected["z"]})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_constructor_invalid_dims(self):NEWLINE # regression for GH1120NEWLINE with pytest.raises(MergeError):NEWLINE Dataset(NEWLINE data_vars=dict(v=("y", [1, 2, 3, 4])),NEWLINE coords=dict(y=DataArray([0.1, 0.2, 0.3, 0.4], dims="x")),NEWLINE )NEWLINENEWLINE def test_constructor_1d(self):NEWLINE expected = Dataset({"x": (["x"], 5.0 + np.arange(5))})NEWLINE actual = Dataset({"x": 5.0 + np.arange(5)})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = Dataset({"x": [5, 6, 7, 8, 9]})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_constructor_0d(self):NEWLINE expected = Dataset({"x": ([], 1)})NEWLINE for arg in [1, np.array(1), expected["x"]]:NEWLINE actual = Dataset({"x": arg})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE class Arbitrary:NEWLINE passNEWLINENEWLINE d = pd.Timestamp("2000-01-01T12")NEWLINE args = [NEWLINE True,NEWLINE None,NEWLINE 3.4,NEWLINE np.nan,NEWLINE "hello",NEWLINE b"raw",NEWLINE np.datetime64("2000-01-01"),NEWLINE d,NEWLINE d.to_pydatetime(),NEWLINE Arbitrary(),NEWLINE ]NEWLINE for arg in args:NEWLINE print(arg)NEWLINE expected = Dataset({"x": ([], arg)})NEWLINE actual = Dataset({"x": arg})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_constructor_deprecated(self):NEWLINE with raises_regex(ValueError, "DataArray dimensions"):NEWLINE DataArray([1, 2, 3], coords={"x": [0, 1, 2]})NEWLINENEWLINE def test_constructor_auto_align(self):NEWLINE a = DataArray([1, 2], [("x", [0, 1])])NEWLINE b = DataArray([3, 4], [("x", [1, 2])])NEWLINENEWLINE # verify align uses outer joinNEWLINE expected = Dataset(NEWLINE {"a": ("x", [1, 2, np.nan]), "b": ("x", [np.nan, 3, 4])}, {"x": [0, 1, 2]}NEWLINE )NEWLINE actual = Dataset({"a": a, "b": b})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # regression test for GH346NEWLINE assert isinstance(actual.variables["x"], IndexVariable)NEWLINENEWLINE # variable with different dimensionsNEWLINE c = ("y", [3, 4])NEWLINE expected2 = expected.merge({"c": c})NEWLINE actual = Dataset({"a": a, "b": b, "c": c})NEWLINE assert_identical(expected2, actual)NEWLINENEWLINE # variable that is only aligned against the aligned variablesNEWLINE d = ("x", [3, 2, 1])NEWLINE expected3 = expected.merge({"d": d})NEWLINE actual = Dataset({"a": a, "b": b, "d": d})NEWLINE assert_identical(expected3, actual)NEWLINENEWLINE e = ("x", [0, 0])NEWLINE with raises_regex(ValueError, "conflicting sizes"):NEWLINE Dataset({"a": a, "b": b, "e": e})NEWLINENEWLINE def test_constructor_pandas_sequence(self):NEWLINENEWLINE ds = self.make_example_math_dataset()NEWLINE pandas_objs = {NEWLINE var_name: ds[var_name].to_pandas() for var_name in ["foo", "bar"]NEWLINE }NEWLINE ds_based_on_pandas = Dataset(pandas_objs, ds.coords, attrs=ds.attrs)NEWLINE del ds_based_on_pandas["x"]NEWLINE assert_equal(ds, ds_based_on_pandas)NEWLINENEWLINE # reindex pandas obj, check align worksNEWLINE rearranged_index = reversed(pandas_objs["foo"].index)NEWLINE pandas_objs["foo"] = pandas_objs["foo"].reindex(rearranged_index)NEWLINE ds_based_on_pandas = Dataset(pandas_objs, ds.coords, attrs=ds.attrs)NEWLINE del ds_based_on_pandas["x"]NEWLINE assert_equal(ds, ds_based_on_pandas)NEWLINENEWLINE def test_constructor_pandas_single(self):NEWLINENEWLINE das = [NEWLINE DataArray(np.random.rand(4), dims=["a"]), # seriesNEWLINE DataArray(np.random.rand(4, 3), dims=["a", "b"]), # dfNEWLINE ]NEWLINENEWLINE if LooseVersion(pd.__version__) < "0.25.0":NEWLINE das.append(DataArray(np.random.rand(4, 3, 2), dims=["a", "b", "c"]))NEWLINENEWLINE with warnings.catch_warnings():NEWLINE warnings.filterwarnings("ignore", r"\W*Panel is deprecated")NEWLINE for a in das:NEWLINE pandas_obj = a.to_pandas()NEWLINE ds_based_on_pandas = Dataset(pandas_obj)NEWLINE for dim in ds_based_on_pandas.data_vars:NEWLINE assert_array_equal(ds_based_on_pandas[dim], pandas_obj[dim])NEWLINENEWLINE def test_constructor_compat(self):NEWLINE data = {"x": DataArray(0, coords={"y": 1}), "y": ("z", [1, 1, 1])}NEWLINE expected = Dataset({"x": 0}, {"y": ("z", [1, 1, 1])})NEWLINE actual = Dataset(data)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE data = {"y": ("z", [1, 1, 1]), "x": DataArray(0, coords={"y": 1})}NEWLINE actual = Dataset(data)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE original = Dataset(NEWLINE {"a": (("x", "y"), np.ones((2, 3)))},NEWLINE {"c": (("x", "y"), np.zeros((2, 3))), "x": [0, 1]},NEWLINE )NEWLINE expected = Dataset(NEWLINE {"a": ("x", np.ones(2)), "b": ("y", np.ones(3))},NEWLINE {"c": (("x", "y"), np.zeros((2, 3))), "x": [0, 1]},NEWLINE )NEWLINENEWLINE actual = Dataset(NEWLINE {"a": original["a"][:, 0], "b": original["a"][0].drop_vars("x")}NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE data = {"x": DataArray(0, coords={"y": 3}), "y": ("z", [1, 1, 1])}NEWLINE with pytest.raises(MergeError):NEWLINE Dataset(data)NEWLINENEWLINE data = {"x": DataArray(0, coords={"y": 1}), "y": [1, 1]}NEWLINE actual = Dataset(data)NEWLINE expected = Dataset({"x": 0}, {"y": [1, 1]})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_constructor_with_coords(self):NEWLINE with raises_regex(ValueError, "found in both data_vars and"):NEWLINE Dataset({"a": ("x", [1])}, {"a": ("x", [1])})NEWLINENEWLINE ds = Dataset({}, {"a": ("x", [1])})NEWLINE assert not ds.data_varsNEWLINE assert list(ds.coords.keys()) == ["a"]NEWLINENEWLINE mindex = pd.MultiIndex.from_product(NEWLINE [["a", "b"], [1, 2]], names=("level_1", "level_2")NEWLINE )NEWLINE with raises_regex(ValueError, "conflicting MultiIndex"):NEWLINE Dataset({}, {"x": mindex, "y": mindex})NEWLINE Dataset({}, {"x": mindex, "level_1": range(4)})NEWLINENEWLINE def test_properties(self):NEWLINE ds = create_test_data()NEWLINE assert ds.dims == {"dim1": 8, "dim2": 9, "dim3": 10, "time": 20}NEWLINE assert list(ds.dims) == sorted(ds.dims)NEWLINE assert ds.sizes == ds.dimsNEWLINENEWLINE # These exact types aren't public API, but this makes sure we don'tNEWLINE # change them inadvertently:NEWLINE assert isinstance(ds.dims, utils.Frozen)NEWLINE assert isinstance(ds.dims.mapping, utils.SortedKeysDict)NEWLINE assert type(ds.dims.mapping.mapping) is dictNEWLINENEWLINE assert list(ds) == list(ds.data_vars)NEWLINE assert list(ds.keys()) == list(ds.data_vars)NEWLINE assert "aasldfjalskdfj" not in ds.variablesNEWLINE assert "dim1" in repr(ds.variables)NEWLINE assert len(ds) == 3NEWLINE assert bool(ds)NEWLINENEWLINE assert list(ds.data_vars) == ["var1", "var2", "var3"]NEWLINE assert list(ds.data_vars.keys()) == ["var1", "var2", "var3"]NEWLINE assert "var1" in ds.data_varsNEWLINE assert "dim1" not in ds.data_varsNEWLINE assert "numbers" not in ds.data_varsNEWLINE assert len(ds.data_vars) == 3NEWLINENEWLINE assert set(ds.indexes) == {"dim2", "dim3", "time"}NEWLINE assert len(ds.indexes) == 3NEWLINE assert "dim2" in repr(ds.indexes)NEWLINENEWLINE assert list(ds.coords) == ["time", "dim2", "dim3", "numbers"]NEWLINE assert "dim2" in ds.coordsNEWLINE assert "numbers" in ds.coordsNEWLINE assert "var1" not in ds.coordsNEWLINE assert "dim1" not in ds.coordsNEWLINE assert len(ds.coords) == 4NEWLINENEWLINE assert Dataset({"x": np.int64(1), "y": np.float32([1, 2])}).nbytes == 16NEWLINENEWLINE def test_asarray(self):NEWLINE ds = Dataset({"x": 0})NEWLINE with raises_regex(TypeError, "cannot directly convert"):NEWLINE np.asarray(ds)NEWLINENEWLINE def test_get_index(self):NEWLINE ds = Dataset({"foo": (("x", "y"), np.zeros((2, 3)))}, coords={"x": ["a", "b"]})NEWLINE assert ds.get_index("x").equals(pd.Index(["a", "b"]))NEWLINE assert ds.get_index("y").equals(pd.Index([0, 1, 2]))NEWLINE with pytest.raises(KeyError):NEWLINE ds.get_index("z")NEWLINENEWLINE def test_attr_access(self):NEWLINE ds = Dataset(NEWLINE {"tmin": ("x", [42], {"units": "Celcius"})}, attrs={"title": "My test data"}NEWLINE )NEWLINE assert_identical(ds.tmin, ds["tmin"])NEWLINE assert_identical(ds.tmin.x, ds.x)NEWLINENEWLINE assert ds.title == ds.attrs["title"]NEWLINE assert ds.tmin.units == ds["tmin"].attrs["units"]NEWLINENEWLINE assert {"tmin", "title"} <= set(dir(ds))NEWLINE assert "units" in set(dir(ds.tmin))NEWLINENEWLINE # should defer to variable of same nameNEWLINE ds.attrs["tmin"] = -999NEWLINE assert ds.attrs["tmin"] == -999NEWLINE assert_identical(ds.tmin, ds["tmin"])NEWLINENEWLINE def test_variable(self):NEWLINE a = Dataset()NEWLINE d = np.random.random((10, 3))NEWLINE a["foo"] = (("time", "x"), d)NEWLINE assert "foo" in a.variablesNEWLINE assert "foo" in aNEWLINE a["bar"] = (("time", "x"), d)NEWLINE # order of creation is preservedNEWLINE assert list(a.variables) == ["foo", "bar"]NEWLINE assert_array_equal(a["foo"].values, d)NEWLINE # try to add variable with dim (10,3) with data that's (3,10)NEWLINE with pytest.raises(ValueError):NEWLINE a["qux"] = (("time", "x"), d.T)NEWLINENEWLINE def test_modify_inplace(self):NEWLINE a = Dataset()NEWLINE vec = np.random.random((10,))NEWLINE attributes = {"foo": "bar"}NEWLINE a["x"] = ("x", vec, attributes)NEWLINE assert "x" in a.coordsNEWLINE assert isinstance(a.coords["x"].to_index(), pd.Index)NEWLINE assert_identical(a.coords["x"].variable, a.variables["x"])NEWLINE b = Dataset()NEWLINE b["x"] = ("x", vec, attributes)NEWLINE assert_identical(a["x"], b["x"])NEWLINE assert a.dims == b.dimsNEWLINE # this should workNEWLINE a["x"] = ("x", vec[:5])NEWLINE a["z"] = ("x", np.arange(5))NEWLINE with pytest.raises(ValueError):NEWLINE # now it shouldn't, since there is a conflicting lengthNEWLINE a["x"] = ("x", vec[:4])NEWLINE arr = np.random.random((10, 1))NEWLINE scal = np.array(0)NEWLINE with pytest.raises(ValueError):NEWLINE a["y"] = ("y", arr)NEWLINE with pytest.raises(ValueError):NEWLINE a["y"] = ("y", scal)NEWLINE assert "y" not in a.dimsNEWLINENEWLINE def test_coords_properties(self):NEWLINE # use int64 for repr consistency on windowsNEWLINE data = Dataset(NEWLINE {NEWLINE "x": ("x", np.array([-1, -2], "int64")),NEWLINE "y": ("y", np.array([0, 1, 2], "int64")),NEWLINE "foo": (["x", "y"], np.random.randn(2, 3)),NEWLINE },NEWLINE {"a": ("x", np.array([4, 5], "int64")), "b": np.int64(-10)},NEWLINE )NEWLINENEWLINE assert 4 == len(data.coords)NEWLINENEWLINE assert ["x", "y", "a", "b"] == list(data.coords)NEWLINENEWLINE assert_identical(data.coords["x"].variable, data["x"].variable)NEWLINE assert_identical(data.coords["y"].variable, data["y"].variable)NEWLINENEWLINE assert "x" in data.coordsNEWLINE assert "a" in data.coordsNEWLINE assert 0 not in data.coordsNEWLINE assert "foo" not in data.coordsNEWLINENEWLINE with pytest.raises(KeyError):NEWLINE data.coords["foo"]NEWLINE with pytest.raises(KeyError):NEWLINE data.coords[0]NEWLINENEWLINE expected = dedent(NEWLINE """\NEWLINE Coordinates:NEWLINE * x (x) int64 -1 -2NEWLINE * y (y) int64 0 1 2NEWLINE a (x) int64 4 5NEWLINE b int64 -10"""NEWLINE )NEWLINE actual = repr(data.coords)NEWLINE assert expected == actualNEWLINENEWLINE assert {"x": 2, "y": 3} == data.coords.dimsNEWLINENEWLINE def test_coords_modify(self):NEWLINE data = Dataset(NEWLINE {NEWLINE "x": ("x", [-1, -2]),NEWLINE "y": ("y", [0, 1, 2]),NEWLINE "foo": (["x", "y"], np.random.randn(2, 3)),NEWLINE },NEWLINE {"a": ("x", [4, 5]), "b": -10},NEWLINE )NEWLINENEWLINE actual = data.copy(deep=True)NEWLINE actual.coords["x"] = ("x", ["a", "b"])NEWLINE assert_array_equal(actual["x"], ["a", "b"])NEWLINENEWLINE actual = data.copy(deep=True)NEWLINE actual.coords["z"] = ("z", ["a", "b"])NEWLINE assert_array_equal(actual["z"], ["a", "b"])NEWLINENEWLINE actual = data.copy(deep=True)NEWLINE with raises_regex(ValueError, "conflicting sizes"):NEWLINE actual.coords["x"] = ("x", [-1])NEWLINE assert_identical(actual, data) # should not be modifiedNEWLINENEWLINE actual = data.copy()NEWLINE del actual.coords["b"]NEWLINE expected = data.reset_coords("b", drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with pytest.raises(KeyError):NEWLINE del data.coords["not_found"]NEWLINENEWLINE with pytest.raises(KeyError):NEWLINE del data.coords["foo"]NEWLINENEWLINE actual = data.copy(deep=True)NEWLINE actual.coords.update({"c": 11})NEWLINE expected = data.merge({"c": 11}).set_coords("c")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_update_index(self):NEWLINE actual = Dataset(coords={"x": [1, 2, 3]})NEWLINE actual["x"] = ["a", "b", "c"]NEWLINE assert actual.indexes["x"].equals(pd.Index(["a", "b", "c"]))NEWLINENEWLINE def test_coords_setitem_with_new_dimension(self):NEWLINE actual = Dataset()NEWLINE actual.coords["foo"] = ("x", [1, 2, 3])NEWLINE expected = Dataset(coords={"foo": ("x", [1, 2, 3])})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_coords_setitem_multiindex(self):NEWLINE data = create_test_multiindex()NEWLINE with raises_regex(ValueError, "conflicting MultiIndex"):NEWLINE data.coords["level_1"] = range(4)NEWLINENEWLINE def test_coords_set(self):NEWLINE one_coord = Dataset({"x": ("x", [0]), "yy": ("x", [1]), "zzz": ("x", [2])})NEWLINE two_coords = Dataset({"zzz": ("x", [2])}, {"x": ("x", [0]), "yy": ("x", [1])})NEWLINE all_coords = Dataset(NEWLINE coords={"x": ("x", [0]), "yy": ("x", [1]), "zzz": ("x", [2])}NEWLINE )NEWLINENEWLINE actual = one_coord.set_coords("x")NEWLINE assert_identical(one_coord, actual)NEWLINE actual = one_coord.set_coords(["x"])NEWLINE assert_identical(one_coord, actual)NEWLINENEWLINE actual = one_coord.set_coords("yy")NEWLINE assert_identical(two_coords, actual)NEWLINENEWLINE actual = one_coord.set_coords(["yy", "zzz"])NEWLINE assert_identical(all_coords, actual)NEWLINENEWLINE actual = one_coord.reset_coords()NEWLINE assert_identical(one_coord, actual)NEWLINE actual = two_coords.reset_coords()NEWLINE assert_identical(one_coord, actual)NEWLINE actual = all_coords.reset_coords()NEWLINE assert_identical(one_coord, actual)NEWLINENEWLINE actual = all_coords.reset_coords(["yy", "zzz"])NEWLINE assert_identical(one_coord, actual)NEWLINE actual = all_coords.reset_coords("zzz")NEWLINE assert_identical(two_coords, actual)NEWLINENEWLINE with raises_regex(ValueError, "cannot remove index"):NEWLINE one_coord.reset_coords("x")NEWLINENEWLINE actual = all_coords.reset_coords("zzz", drop=True)NEWLINE expected = all_coords.drop_vars("zzz")NEWLINE assert_identical(expected, actual)NEWLINE expected = two_coords.drop_vars("zzz")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_coords_to_dataset(self):NEWLINE orig = Dataset({"foo": ("y", [-1, 0, 1])}, {"x": 10, "y": [2, 3, 4]})NEWLINE expected = Dataset(coords={"x": 10, "y": [2, 3, 4]})NEWLINE actual = orig.coords.to_dataset()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_coords_merge(self):NEWLINE orig_coords = Dataset(coords={"a": ("x", [1, 2]), "x": [0, 1]}).coordsNEWLINE other_coords = Dataset(coords={"b": ("x", ["a", "b"]), "x": [0, 1]}).coordsNEWLINE expected = Dataset(NEWLINE coords={"a": ("x", [1, 2]), "b": ("x", ["a", "b"]), "x": [0, 1]}NEWLINE )NEWLINE actual = orig_coords.merge(other_coords)NEWLINE assert_identical(expected, actual)NEWLINE actual = other_coords.merge(orig_coords)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE other_coords = Dataset(coords={"x": ("x", ["a"])}).coordsNEWLINE with pytest.raises(MergeError):NEWLINE orig_coords.merge(other_coords)NEWLINE other_coords = Dataset(coords={"x": ("x", ["a", "b"])}).coordsNEWLINE with pytest.raises(MergeError):NEWLINE orig_coords.merge(other_coords)NEWLINE other_coords = Dataset(coords={"x": ("x", ["a", "b", "c"])}).coordsNEWLINE with pytest.raises(MergeError):NEWLINE orig_coords.merge(other_coords)NEWLINENEWLINE other_coords = Dataset(coords={"a": ("x", [8, 9])}).coordsNEWLINE expected = Dataset(coords={"x": range(2)})NEWLINE actual = orig_coords.merge(other_coords)NEWLINE assert_identical(expected, actual)NEWLINE actual = other_coords.merge(orig_coords)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE other_coords = Dataset(coords={"x": np.nan}).coordsNEWLINE actual = orig_coords.merge(other_coords)NEWLINE assert_identical(orig_coords.to_dataset(), actual)NEWLINE actual = other_coords.merge(orig_coords)NEWLINE assert_identical(orig_coords.to_dataset(), actual)NEWLINENEWLINE def test_coords_merge_mismatched_shape(self):NEWLINE orig_coords = Dataset(coords={"a": ("x", [1, 1])}).coordsNEWLINE other_coords = Dataset(coords={"a": 1}).coordsNEWLINE expected = orig_coords.to_dataset()NEWLINE actual = orig_coords.merge(other_coords)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE other_coords = Dataset(coords={"a": ("y", [1])}).coordsNEWLINE expected = Dataset(coords={"a": (["x", "y"], [[1], [1]])})NEWLINE actual = orig_coords.merge(other_coords)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = other_coords.merge(orig_coords)NEWLINE assert_identical(expected.transpose(), actual)NEWLINENEWLINE orig_coords = Dataset(coords={"a": ("x", [np.nan])}).coordsNEWLINE other_coords = Dataset(coords={"a": np.nan}).coordsNEWLINE expected = orig_coords.to_dataset()NEWLINE actual = orig_coords.merge(other_coords)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_data_vars_properties(self):NEWLINE ds = Dataset()NEWLINE ds["foo"] = (("x",), [1.0])NEWLINE ds["bar"] = 2.0NEWLINENEWLINE assert set(ds.data_vars) == {"foo", "bar"}NEWLINE assert "foo" in ds.data_varsNEWLINE assert "x" not in ds.data_varsNEWLINE assert_identical(ds["foo"], ds.data_vars["foo"])NEWLINENEWLINE expected = dedent(NEWLINE """\NEWLINE Data variables:NEWLINE foo (x) float64 1.0NEWLINE bar float64 2.0"""NEWLINE )NEWLINE actual = repr(ds.data_vars)NEWLINE assert expected == actualNEWLINENEWLINE def test_equals_and_identical(self):NEWLINE data = create_test_data(seed=42)NEWLINE assert data.equals(data)NEWLINE assert data.identical(data)NEWLINENEWLINE data2 = create_test_data(seed=42)NEWLINE data2.attrs["foobar"] = "baz"NEWLINE assert data.equals(data2)NEWLINE assert not data.identical(data2)NEWLINENEWLINE del data2["time"]NEWLINE assert not data.equals(data2)NEWLINENEWLINE data = create_test_data(seed=42).rename({"var1": None})NEWLINE assert data.equals(data)NEWLINE assert data.identical(data)NEWLINENEWLINE data2 = data.reset_coords()NEWLINE assert not data2.equals(data)NEWLINE assert not data2.identical(data)NEWLINENEWLINE def test_equals_failures(self):NEWLINE data = create_test_data()NEWLINE assert not data.equals("foo")NEWLINE assert not data.identical(123)NEWLINE assert not data.broadcast_equals({1: 2})NEWLINENEWLINE def test_broadcast_equals(self):NEWLINE data1 = Dataset(coords={"x": 0})NEWLINE data2 = Dataset(coords={"x": [0]})NEWLINE assert data1.broadcast_equals(data2)NEWLINE assert not data1.equals(data2)NEWLINE assert not data1.identical(data2)NEWLINENEWLINE def test_attrs(self):NEWLINE data = create_test_data(seed=42)NEWLINE data.attrs = {"foobar": "baz"}NEWLINE assert data.attrs["foobar"], "baz"NEWLINE assert isinstance(data.attrs, dict)NEWLINENEWLINE @requires_daskNEWLINE def test_chunk(self):NEWLINE data = create_test_data()NEWLINE for v in data.variables.values():NEWLINE assert isinstance(v.data, np.ndarray)NEWLINE assert data.chunks == {}NEWLINENEWLINE reblocked = data.chunk()NEWLINE for k, v in reblocked.variables.items():NEWLINE if k in reblocked.dims:NEWLINE assert isinstance(v.data, np.ndarray)NEWLINE else:NEWLINE assert isinstance(v.data, da.Array)NEWLINENEWLINE expected_chunks = {"dim1": (8,), "dim2": (9,), "dim3": (10,)}NEWLINE assert reblocked.chunks == expected_chunksNEWLINENEWLINE reblocked = data.chunk({"time": 5, "dim1": 5, "dim2": 5, "dim3": 5})NEWLINE # time is not a dim in any of the data_vars, so itNEWLINE # doesn't get chunkedNEWLINE expected_chunks = {"dim1": (5, 3), "dim2": (5, 4), "dim3": (5, 5)}NEWLINE assert reblocked.chunks == expected_chunksNEWLINENEWLINE reblocked = data.chunk(expected_chunks)NEWLINE assert reblocked.chunks == expected_chunksNEWLINENEWLINE # reblock on already blocked dataNEWLINE reblocked = reblocked.chunk(expected_chunks)NEWLINE assert reblocked.chunks == expected_chunksNEWLINE assert_identical(reblocked, data)NEWLINENEWLINE with raises_regex(ValueError, "some chunks"):NEWLINE data.chunk({"foo": 10})NEWLINENEWLINE @requires_daskNEWLINE def test_dask_is_lazy(self):NEWLINE store = InaccessibleVariableDataStore()NEWLINE create_test_data().dump_to_store(store)NEWLINE ds = open_dataset(store).chunk()NEWLINENEWLINE with pytest.raises(UnexpectedDataAccess):NEWLINE ds.load()NEWLINE with pytest.raises(UnexpectedDataAccess):NEWLINE ds["var1"].valuesNEWLINENEWLINE # these should not raise UnexpectedDataAccess:NEWLINE ds.var1.dataNEWLINE ds.isel(time=10)NEWLINE ds.isel(time=slice(10), dim1=[0]).isel(dim1=0, dim2=-1)NEWLINE ds.transpose()NEWLINE ds.mean()NEWLINE ds.fillna(0)NEWLINE ds.rename({"dim1": "foobar"})NEWLINE ds.set_coords("var1")NEWLINE ds.drop_vars("var1")NEWLINENEWLINE def test_isel(self):NEWLINE data = create_test_data()NEWLINE slicers = {"dim1": slice(None, None, 2), "dim2": slice(0, 2)}NEWLINE ret = data.isel(**slicers)NEWLINENEWLINE # Verify that only the specified dimension was alteredNEWLINE assert list(data.dims) == list(ret.dims)NEWLINE for d in data.dims:NEWLINE if d in slicers:NEWLINE assert ret.dims[d] == np.arange(data.dims[d])[slicers[d]].sizeNEWLINE else:NEWLINE assert data.dims[d] == ret.dims[d]NEWLINE # Verify that the data is what we expectNEWLINE for v in data.variables:NEWLINE assert data[v].dims == ret[v].dimsNEWLINE assert data[v].attrs == ret[v].attrsNEWLINE slice_list = [slice(None)] * data[v].values.ndimNEWLINE for d, s in slicers.items():NEWLINE if d in data[v].dims:NEWLINE inds = np.nonzero(np.array(data[v].dims) == d)[0]NEWLINE for ind in inds:NEWLINE slice_list[ind] = sNEWLINE expected = data[v].values[tuple(slice_list)]NEWLINE actual = ret[v].valuesNEWLINE np.testing.assert_array_equal(expected, actual)NEWLINENEWLINE with pytest.raises(ValueError):NEWLINE data.isel(not_a_dim=slice(0, 2))NEWLINENEWLINE ret = data.isel(dim1=0)NEWLINE assert {"time": 20, "dim2": 9, "dim3": 10} == ret.dimsNEWLINE assert set(data.data_vars) == set(ret.data_vars)NEWLINE assert set(data.coords) == set(ret.coords)NEWLINE assert set(data.indexes) == set(ret.indexes)NEWLINENEWLINE ret = data.isel(time=slice(2), dim1=0, dim2=slice(5))NEWLINE assert {"time": 2, "dim2": 5, "dim3": 10} == ret.dimsNEWLINE assert set(data.data_vars) == set(ret.data_vars)NEWLINE assert set(data.coords) == set(ret.coords)NEWLINE assert set(data.indexes) == set(ret.indexes)NEWLINENEWLINE ret = data.isel(time=0, dim1=0, dim2=slice(5))NEWLINE assert {"dim2": 5, "dim3": 10} == ret.dimsNEWLINE assert set(data.data_vars) == set(ret.data_vars)NEWLINE assert set(data.coords) == set(ret.coords)NEWLINE assert set(data.indexes) == set(list(ret.indexes) + ["time"])NEWLINENEWLINE def test_isel_fancy(self):NEWLINE # isel with fancy indexing.NEWLINE data = create_test_data()NEWLINENEWLINE pdim1 = [1, 2, 3]NEWLINE pdim2 = [4, 5, 1]NEWLINE pdim3 = [1, 2, 3]NEWLINE actual = data.isel(NEWLINE dim1=(("test_coord",), pdim1),NEWLINE dim2=(("test_coord",), pdim2),NEWLINE dim3=(("test_coord",), pdim3),NEWLINE )NEWLINE assert "test_coord" in actual.dimsNEWLINE assert actual.coords["test_coord"].shape == (len(pdim1),)NEWLINENEWLINE # Should work with DataArrayNEWLINE actual = data.isel(NEWLINE dim1=DataArray(pdim1, dims="test_coord"),NEWLINE dim2=(("test_coord",), pdim2),NEWLINE dim3=(("test_coord",), pdim3),NEWLINE )NEWLINE assert "test_coord" in actual.dimsNEWLINE assert actual.coords["test_coord"].shape == (len(pdim1),)NEWLINE expected = data.isel(NEWLINE dim1=(("test_coord",), pdim1),NEWLINE dim2=(("test_coord",), pdim2),NEWLINE dim3=(("test_coord",), pdim3),NEWLINE )NEWLINE assert_identical(actual, expected)NEWLINENEWLINE # DataArray with coordinateNEWLINE idx1 = DataArray(pdim1, dims=["a"], coords={"a": np.random.randn(3)})NEWLINE idx2 = DataArray(pdim2, dims=["b"], coords={"b": np.random.randn(3)})NEWLINE idx3 = DataArray(pdim3, dims=["c"], coords={"c": np.random.randn(3)})NEWLINE # Should work with DataArrayNEWLINE actual = data.isel(dim1=idx1, dim2=idx2, dim3=idx3)NEWLINE assert "a" in actual.dimsNEWLINE assert "b" in actual.dimsNEWLINE assert "c" in actual.dimsNEWLINE assert "time" in actual.coordsNEWLINE assert "dim2" in actual.coordsNEWLINE assert "dim3" in actual.coordsNEWLINE expected = data.isel(NEWLINE dim1=(("a",), pdim1), dim2=(("b",), pdim2), dim3=(("c",), pdim3)NEWLINE )NEWLINE expected = expected.assign_coords(a=idx1["a"], b=idx2["b"], c=idx3["c"])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE idx1 = DataArray(pdim1, dims=["a"], coords={"a": np.random.randn(3)})NEWLINE idx2 = DataArray(pdim2, dims=["a"])NEWLINE idx3 = DataArray(pdim3, dims=["a"])NEWLINE # Should work with DataArrayNEWLINE actual = data.isel(dim1=idx1, dim2=idx2, dim3=idx3)NEWLINE assert "a" in actual.dimsNEWLINE assert "time" in actual.coordsNEWLINE assert "dim2" in actual.coordsNEWLINE assert "dim3" in actual.coordsNEWLINE expected = data.isel(NEWLINE dim1=(("a",), pdim1), dim2=(("a",), pdim2), dim3=(("a",), pdim3)NEWLINE )NEWLINE expected = expected.assign_coords(a=idx1["a"])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = data.isel(dim1=(("points",), pdim1), dim2=(("points",), pdim2))NEWLINE assert "points" in actual.dimsNEWLINE assert "dim3" in actual.dimsNEWLINE assert "dim3" not in actual.data_varsNEWLINE np.testing.assert_array_equal(data["dim2"][pdim2], actual["dim2"])NEWLINENEWLINE # test that the order of the indexers doesn't matterNEWLINE assert_identical(NEWLINE data.isel(dim1=(("points",), pdim1), dim2=(("points",), pdim2)),NEWLINE data.isel(dim2=(("points",), pdim2), dim1=(("points",), pdim1)),NEWLINE )NEWLINE # make sure we're raising errors in the right placesNEWLINE with raises_regex(IndexError, "Dimensions of indexers mismatch"):NEWLINE data.isel(dim1=(("points",), [1, 2]), dim2=(("points",), [1, 2, 3]))NEWLINE with raises_regex(TypeError, "cannot use a Dataset"):NEWLINE data.isel(dim1=Dataset({"points": [1, 2]}))NEWLINENEWLINE # test to be sure we keep around variables that were not indexedNEWLINE ds = Dataset({"x": [1, 2, 3, 4], "y": 0})NEWLINE actual = ds.isel(x=(("points",), [0, 1, 2]))NEWLINE assert_identical(ds["y"], actual["y"])NEWLINENEWLINE # tests using index or DataArray as indexersNEWLINE stations = Dataset()NEWLINE stations["station"] = (("station",), ["A", "B", "C"])NEWLINE stations["dim1s"] = (("station",), [1, 2, 3])NEWLINE stations["dim2s"] = (("station",), [4, 5, 1])NEWLINENEWLINE actual = data.isel(dim1=stations["dim1s"], dim2=stations["dim2s"])NEWLINE assert "station" in actual.coordsNEWLINE assert "station" in actual.dimsNEWLINE assert_identical(actual["station"].drop_vars(["dim2"]), stations["station"])NEWLINENEWLINE with raises_regex(ValueError, "conflicting values for "):NEWLINE data.isel(NEWLINE dim1=DataArray(NEWLINE [0, 1, 2], dims="station", coords={"station": [0, 1, 2]}NEWLINE ),NEWLINE dim2=DataArray(NEWLINE [0, 1, 2], dims="station", coords={"station": [0, 1, 3]}NEWLINE ),NEWLINE )NEWLINENEWLINE # multi-dimensional selectionNEWLINE stations = Dataset()NEWLINE stations["a"] = (("a",), ["A", "B", "C"])NEWLINE stations["b"] = (("b",), [0, 1])NEWLINE stations["dim1s"] = (("a", "b"), [[1, 2], [2, 3], [3, 4]])NEWLINE stations["dim2s"] = (("a",), [4, 5, 1])NEWLINE actual = data.isel(dim1=stations["dim1s"], dim2=stations["dim2s"])NEWLINE assert "a" in actual.coordsNEWLINE assert "a" in actual.dimsNEWLINE assert "b" in actual.coordsNEWLINE assert "b" in actual.dimsNEWLINE assert "dim2" in actual.coordsNEWLINE assert "a" in actual["dim2"].dimsNEWLINENEWLINE assert_identical(actual["a"].drop_vars(["dim2"]), stations["a"])NEWLINE assert_identical(actual["b"], stations["b"])NEWLINE expected_var1 = data["var1"].variable[NEWLINE stations["dim1s"].variable, stations["dim2s"].variableNEWLINE ]NEWLINE expected_var2 = data["var2"].variable[NEWLINE stations["dim1s"].variable, stations["dim2s"].variableNEWLINE ]NEWLINE expected_var3 = data["var3"].variable[slice(None), stations["dim1s"].variable]NEWLINE assert_equal(actual["a"].drop_vars("dim2"), stations["a"])NEWLINE assert_array_equal(actual["var1"], expected_var1)NEWLINE assert_array_equal(actual["var2"], expected_var2)NEWLINE assert_array_equal(actual["var3"], expected_var3)NEWLINENEWLINE def test_isel_dataarray(self):NEWLINE """ Test for indexing by DataArray """NEWLINE data = create_test_data()NEWLINE # indexing with DataArray with same-name coordinates.NEWLINE indexing_da = DataArray(NEWLINE np.arange(1, 4), dims=["dim1"], coords={"dim1": np.random.randn(3)}NEWLINE )NEWLINE actual = data.isel(dim1=indexing_da)NEWLINE assert_identical(indexing_da["dim1"], actual["dim1"])NEWLINE assert_identical(data["dim2"], actual["dim2"])NEWLINENEWLINE # Conflict in the dimension coordinateNEWLINE indexing_da = DataArray(NEWLINE np.arange(1, 4), dims=["dim2"], coords={"dim2": np.random.randn(3)}NEWLINE )NEWLINE with raises_regex(IndexError, "dimension coordinate 'dim2'"):NEWLINE actual = data.isel(dim2=indexing_da)NEWLINE # Also the case for DataArrayNEWLINE with raises_regex(IndexError, "dimension coordinate 'dim2'"):NEWLINE actual = data["var2"].isel(dim2=indexing_da)NEWLINE with raises_regex(IndexError, "dimension coordinate 'dim2'"):NEWLINE data["dim2"].isel(dim2=indexing_da)NEWLINENEWLINE # same name coordinate which does not conflictNEWLINE indexing_da = DataArray(NEWLINE np.arange(1, 4), dims=["dim2"], coords={"dim2": data["dim2"].values[1:4]}NEWLINE )NEWLINE actual = data.isel(dim2=indexing_da)NEWLINE assert_identical(actual["dim2"], indexing_da["dim2"])NEWLINENEWLINE # Silently drop conflicted (non-dimensional) coordinate of indexerNEWLINE indexing_da = DataArray(NEWLINE np.arange(1, 4),NEWLINE dims=["dim2"],NEWLINE coords={NEWLINE "dim2": data["dim2"].values[1:4],NEWLINE "numbers": ("dim2", np.arange(2, 5)),NEWLINE },NEWLINE )NEWLINE actual = data.isel(dim2=indexing_da)NEWLINE assert_identical(actual["numbers"], data["numbers"])NEWLINENEWLINE # boolean data array with coordinate with the same nameNEWLINE indexing_da = DataArray(NEWLINE np.arange(1, 10), dims=["dim2"], coords={"dim2": data["dim2"].values}NEWLINE )NEWLINE indexing_da = indexing_da < 3NEWLINE actual = data.isel(dim2=indexing_da)NEWLINE assert_identical(actual["dim2"], data["dim2"][:2])NEWLINENEWLINE # boolean data array with non-dimensioncoordinateNEWLINE indexing_da = DataArray(NEWLINE np.arange(1, 10),NEWLINE dims=["dim2"],NEWLINE coords={NEWLINE "dim2": data["dim2"].values,NEWLINE "non_dim": (("dim2",), np.random.randn(9)),NEWLINE "non_dim2": 0,NEWLINE },NEWLINE )NEWLINE indexing_da = indexing_da < 3NEWLINE actual = data.isel(dim2=indexing_da)NEWLINE assert_identical(NEWLINE actual["dim2"].drop_vars("non_dim").drop_vars("non_dim2"), data["dim2"][:2]NEWLINE )NEWLINE assert_identical(actual["non_dim"], indexing_da["non_dim"][:2])NEWLINE assert_identical(actual["non_dim2"], indexing_da["non_dim2"])NEWLINENEWLINE # non-dimension coordinate will be also attachedNEWLINE indexing_da = DataArray(NEWLINE np.arange(1, 4),NEWLINE dims=["dim2"],NEWLINE coords={"non_dim": (("dim2",), np.random.randn(3))},NEWLINE )NEWLINE actual = data.isel(dim2=indexing_da)NEWLINE assert "non_dim" in actualNEWLINE assert "non_dim" in actual.coordsNEWLINENEWLINE # Index by a scalar DataArrayNEWLINE indexing_da = DataArray(3, dims=[], coords={"station": 2})NEWLINE actual = data.isel(dim2=indexing_da)NEWLINE assert "station" in actualNEWLINE actual = data.isel(dim2=indexing_da["station"])NEWLINE assert "station" in actualNEWLINENEWLINE # indexer generated from coordinatesNEWLINE indexing_ds = Dataset({}, coords={"dim2": [0, 1, 2]})NEWLINE with raises_regex(IndexError, "dimension coordinate 'dim2'"):NEWLINE actual = data.isel(dim2=indexing_ds["dim2"])NEWLINENEWLINE def test_sel(self):NEWLINE data = create_test_data()NEWLINE int_slicers = {"dim1": slice(None, None, 2), "dim2": slice(2), "dim3": slice(3)}NEWLINE loc_slicers = {NEWLINE "dim1": slice(None, None, 2),NEWLINE "dim2": slice(0, 0.5),NEWLINE "dim3": slice("a", "c"),NEWLINE }NEWLINE assert_equal(data.isel(**int_slicers), data.sel(**loc_slicers))NEWLINE data["time"] = ("time", pd.date_range("2000-01-01", periods=20))NEWLINE assert_equal(data.isel(time=0), data.sel(time="2000-01-01"))NEWLINE assert_equal(NEWLINE data.isel(time=slice(10)), data.sel(time=slice("2000-01-01", "2000-01-10"))NEWLINE )NEWLINE assert_equal(data, data.sel(time=slice("1999", "2005")))NEWLINE times = pd.date_range("2000-01-01", periods=3)NEWLINE assert_equal(data.isel(time=slice(3)), data.sel(time=times))NEWLINE assert_equal(NEWLINE data.isel(time=slice(3)), data.sel(time=(data["time.dayofyear"] <= 3))NEWLINE )NEWLINENEWLINE td = pd.to_timedelta(np.arange(3), unit="days")NEWLINE data = Dataset({"x": ("td", np.arange(3)), "td": td})NEWLINE assert_equal(data, data.sel(td=td))NEWLINE assert_equal(data, data.sel(td=slice("3 days")))NEWLINE assert_equal(data.isel(td=0), data.sel(td=pd.Timedelta("0 days")))NEWLINE assert_equal(data.isel(td=0), data.sel(td=pd.Timedelta("0h")))NEWLINE assert_equal(data.isel(td=slice(1, 3)), data.sel(td=slice("1 days", "2 days")))NEWLINENEWLINE def test_sel_dataarray(self):NEWLINE data = create_test_data()NEWLINENEWLINE ind = DataArray([0.0, 0.5, 1.0], dims=["dim2"])NEWLINE actual = data.sel(dim2=ind)NEWLINE assert_equal(actual, data.isel(dim2=[0, 1, 2]))NEWLINENEWLINE # with different dimensionNEWLINE ind = DataArray([0.0, 0.5, 1.0], dims=["new_dim"])NEWLINE actual = data.sel(dim2=ind)NEWLINE expected = data.isel(dim2=Variable("new_dim", [0, 1, 2]))NEWLINE assert "new_dim" in actual.dimsNEWLINE assert_equal(actual, expected)NEWLINENEWLINE # Multi-dimensionalNEWLINE ind = DataArray([[0.0], [0.5], [1.0]], dims=["new_dim", "new_dim2"])NEWLINE actual = data.sel(dim2=ind)NEWLINE expected = data.isel(dim2=Variable(("new_dim", "new_dim2"), [[0], [1], [2]]))NEWLINE assert "new_dim" in actual.dimsNEWLINE assert "new_dim2" in actual.dimsNEWLINE assert_equal(actual, expected)NEWLINENEWLINE # with coordinateNEWLINE ind = DataArray(NEWLINE [0.0, 0.5, 1.0], dims=["new_dim"], coords={"new_dim": ["a", "b", "c"]}NEWLINE )NEWLINE actual = data.sel(dim2=ind)NEWLINE expected = data.isel(dim2=[0, 1, 2]).rename({"dim2": "new_dim"})NEWLINE assert "new_dim" in actual.dimsNEWLINE assert "new_dim" in actual.coordsNEWLINE assert_equal(NEWLINE actual.drop_vars("new_dim").drop_vars("dim2"), expected.drop_vars("new_dim")NEWLINE )NEWLINE assert_equal(actual["new_dim"].drop_vars("dim2"), ind["new_dim"])NEWLINENEWLINE # with conflicted coordinate (silently ignored)NEWLINE ind = DataArray(NEWLINE [0.0, 0.5, 1.0], dims=["dim2"], coords={"dim2": ["a", "b", "c"]}NEWLINE )NEWLINE actual = data.sel(dim2=ind)NEWLINE expected = data.isel(dim2=[0, 1, 2])NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # with conflicted coordinate (silently ignored)NEWLINE ind = DataArray(NEWLINE [0.0, 0.5, 1.0],NEWLINE dims=["new_dim"],NEWLINE coords={"new_dim": ["a", "b", "c"], "dim2": 3},NEWLINE )NEWLINE actual = data.sel(dim2=ind)NEWLINE assert_equal(NEWLINE actual["new_dim"].drop_vars("dim2"), ind["new_dim"].drop_vars("dim2")NEWLINE )NEWLINE expected = data.isel(dim2=[0, 1, 2])NEWLINE expected["dim2"] = (("new_dim"), expected["dim2"].values)NEWLINE assert_equal(actual["dim2"].drop_vars("new_dim"), expected["dim2"])NEWLINE assert actual["var1"].dims == ("dim1", "new_dim")NEWLINENEWLINE # with non-dimensional coordinateNEWLINE ind = DataArray(NEWLINE [0.0, 0.5, 1.0],NEWLINE dims=["dim2"],NEWLINE coords={NEWLINE "dim2": ["a", "b", "c"],NEWLINE "numbers": ("dim2", [0, 1, 2]),NEWLINE "new_dim": ("dim2", [1.1, 1.2, 1.3]),NEWLINE },NEWLINE )NEWLINE actual = data.sel(dim2=ind)NEWLINE expected = data.isel(dim2=[0, 1, 2])NEWLINE assert_equal(actual.drop_vars("new_dim"), expected)NEWLINE assert np.allclose(actual["new_dim"].values, ind["new_dim"].values)NEWLINENEWLINE def test_sel_dataarray_mindex(self):NEWLINE midx = pd.MultiIndex.from_product([list("abc"), [0, 1]], names=("one", "two"))NEWLINE mds = xr.Dataset(NEWLINE {"var": (("x", "y"), np.random.rand(6, 3))},NEWLINE coords={"x": midx, "y": range(3)},NEWLINE )NEWLINENEWLINE actual_isel = mds.isel(x=xr.DataArray(np.arange(3), dims="x"))NEWLINE actual_sel = mds.sel(x=DataArray(mds.indexes["x"][:3], dims="x"))NEWLINE assert actual_isel["x"].dims == ("x",)NEWLINE assert actual_sel["x"].dims == ("x",)NEWLINE assert_identical(actual_isel, actual_sel)NEWLINENEWLINE actual_isel = mds.isel(x=xr.DataArray(np.arange(3), dims="z"))NEWLINE actual_sel = mds.sel(x=Variable("z", mds.indexes["x"][:3]))NEWLINE assert actual_isel["x"].dims == ("z",)NEWLINE assert actual_sel["x"].dims == ("z",)NEWLINE assert_identical(actual_isel, actual_sel)NEWLINENEWLINE # with coordinateNEWLINE actual_isel = mds.isel(NEWLINE x=xr.DataArray(np.arange(3), dims="z", coords={"z": [0, 1, 2]})NEWLINE )NEWLINE actual_sel = mds.sel(NEWLINE x=xr.DataArray(mds.indexes["x"][:3], dims="z", coords={"z": [0, 1, 2]})NEWLINE )NEWLINE assert actual_isel["x"].dims == ("z",)NEWLINE assert actual_sel["x"].dims == ("z",)NEWLINE assert_identical(actual_isel, actual_sel)NEWLINENEWLINE # Vectorized indexing with level-variables raises an errorNEWLINE with raises_regex(ValueError, "Vectorized selection is "):NEWLINE mds.sel(one=["a", "b"])NEWLINENEWLINE with raises_regex(NEWLINE ValueError,NEWLINE "Vectorized selection is " "not available along MultiIndex variable:" " x",NEWLINE ):NEWLINE mds.sel(NEWLINE x=xr.DataArray(NEWLINE [np.array(midx[:2]), np.array(midx[-2:])], dims=["a", "b"]NEWLINE )NEWLINE )NEWLINENEWLINE def test_sel_drop(self):NEWLINE data = Dataset({"foo": ("x", [1, 2, 3])}, {"x": [0, 1, 2]})NEWLINE expected = Dataset({"foo": 1})NEWLINE selected = data.sel(x=0, drop=True)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE expected = Dataset({"foo": 1}, {"x": 0})NEWLINE selected = data.sel(x=0, drop=False)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE data = Dataset({"foo": ("x", [1, 2, 3])})NEWLINE expected = Dataset({"foo": 1})NEWLINE selected = data.sel(x=0, drop=True)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE def test_isel_drop(self):NEWLINE data = Dataset({"foo": ("x", [1, 2, 3])}, {"x": [0, 1, 2]})NEWLINE expected = Dataset({"foo": 1})NEWLINE selected = data.isel(x=0, drop=True)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE expected = Dataset({"foo": 1}, {"x": 0})NEWLINE selected = data.isel(x=0, drop=False)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE def test_head(self):NEWLINE data = create_test_data()NEWLINENEWLINE expected = data.isel(time=slice(5), dim2=slice(6))NEWLINE actual = data.head(time=5, dim2=6)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE expected = data.isel(time=slice(0))NEWLINE actual = data.head(time=0)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE expected = data.isel({dim: slice(6) for dim in data.dims})NEWLINE actual = data.head(6)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE expected = data.isel({dim: slice(5) for dim in data.dims})NEWLINE actual = data.head()NEWLINE assert_equal(expected, actual)NEWLINENEWLINE with raises_regex(TypeError, "either dict-like or a single int"):NEWLINE data.head([3])NEWLINE with raises_regex(TypeError, "expected integer type"):NEWLINE data.head(dim2=3.1)NEWLINE with raises_regex(ValueError, "expected positive int"):NEWLINE data.head(time=-3)NEWLINENEWLINE def test_tail(self):NEWLINE data = create_test_data()NEWLINENEWLINE expected = data.isel(time=slice(-5, None), dim2=slice(-6, None))NEWLINE actual = data.tail(time=5, dim2=6)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE expected = data.isel(dim1=slice(0))NEWLINE actual = data.tail(dim1=0)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE expected = data.isel({dim: slice(-6, None) for dim in data.dims})NEWLINE actual = data.tail(6)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE expected = data.isel({dim: slice(-5, None) for dim in data.dims})NEWLINE actual = data.tail()NEWLINE assert_equal(expected, actual)NEWLINENEWLINE with raises_regex(TypeError, "either dict-like or a single int"):NEWLINE data.tail([3])NEWLINE with raises_regex(TypeError, "expected integer type"):NEWLINE data.tail(dim2=3.1)NEWLINE with raises_regex(ValueError, "expected positive int"):NEWLINE data.tail(time=-3)NEWLINENEWLINE def test_thin(self):NEWLINE data = create_test_data()NEWLINENEWLINE expected = data.isel(time=slice(None, None, 5), dim2=slice(None, None, 6))NEWLINE actual = data.thin(time=5, dim2=6)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE expected = data.isel({dim: slice(None, None, 6) for dim in data.dims})NEWLINE actual = data.thin(6)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE with raises_regex(TypeError, "either dict-like or a single int"):NEWLINE data.thin([3])NEWLINE with raises_regex(TypeError, "expected integer type"):NEWLINE data.thin(dim2=3.1)NEWLINE with raises_regex(ValueError, "cannot be zero"):NEWLINE data.thin(time=0)NEWLINE with raises_regex(ValueError, "expected positive int"):NEWLINE data.thin(time=-3)NEWLINENEWLINE @pytest.mark.filterwarnings("ignore::DeprecationWarning")NEWLINE def test_sel_fancy(self):NEWLINE data = create_test_data()NEWLINENEWLINE # add in a range() indexNEWLINE data["dim1"] = data.dim1NEWLINENEWLINE pdim1 = [1, 2, 3]NEWLINE pdim2 = [4, 5, 1]NEWLINE pdim3 = [1, 2, 3]NEWLINE expected = data.isel(NEWLINE dim1=Variable(("test_coord",), pdim1),NEWLINE dim2=Variable(("test_coord",), pdim2),NEWLINE dim3=Variable(("test_coord"), pdim3),NEWLINE )NEWLINE actual = data.sel(NEWLINE dim1=Variable(("test_coord",), data.dim1[pdim1]),NEWLINE dim2=Variable(("test_coord",), data.dim2[pdim2]),NEWLINE dim3=Variable(("test_coord",), data.dim3[pdim3]),NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # DataArray IndexerNEWLINE idx_t = DataArray(NEWLINE data["time"][[3, 2, 1]].values, dims=["a"], coords={"a": ["a", "b", "c"]}NEWLINE )NEWLINE idx_2 = DataArray(NEWLINE data["dim2"][[3, 2, 1]].values, dims=["a"], coords={"a": ["a", "b", "c"]}NEWLINE )NEWLINE idx_3 = DataArray(NEWLINE data["dim3"][[3, 2, 1]].values, dims=["a"], coords={"a": ["a", "b", "c"]}NEWLINE )NEWLINE actual = data.sel(time=idx_t, dim2=idx_2, dim3=idx_3)NEWLINE expected = data.isel(NEWLINE time=Variable(("a",), [3, 2, 1]),NEWLINE dim2=Variable(("a",), [3, 2, 1]),NEWLINE dim3=Variable(("a",), [3, 2, 1]),NEWLINE )NEWLINE expected = expected.assign_coords(a=idx_t["a"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE idx_t = DataArray(NEWLINE data["time"][[3, 2, 1]].values, dims=["a"], coords={"a": ["a", "b", "c"]}NEWLINE )NEWLINE idx_2 = DataArray(NEWLINE data["dim2"][[2, 1, 3]].values, dims=["b"], coords={"b": [0, 1, 2]}NEWLINE )NEWLINE idx_3 = DataArray(NEWLINE data["dim3"][[1, 2, 1]].values, dims=["c"], coords={"c": [0.0, 1.1, 2.2]}NEWLINE )NEWLINE actual = data.sel(time=idx_t, dim2=idx_2, dim3=idx_3)NEWLINE expected = data.isel(NEWLINE time=Variable(("a",), [3, 2, 1]),NEWLINE dim2=Variable(("b",), [2, 1, 3]),NEWLINE dim3=Variable(("c",), [1, 2, 1]),NEWLINE )NEWLINE expected = expected.assign_coords(a=idx_t["a"], b=idx_2["b"], c=idx_3["c"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # test from sel_pointsNEWLINE data = Dataset({"foo": (("x", "y"), np.arange(9).reshape(3, 3))})NEWLINE data.coords.update({"x": [0, 1, 2], "y": [0, 1, 2]})NEWLINENEWLINE expected = Dataset(NEWLINE {"foo": ("points", [0, 4, 8])},NEWLINE coords={NEWLINE "x": Variable(("points",), [0, 1, 2]),NEWLINE "y": Variable(("points",), [0, 1, 2]),NEWLINE },NEWLINE )NEWLINE actual = data.sel(NEWLINE x=Variable(("points",), [0, 1, 2]), y=Variable(("points",), [0, 1, 2])NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected.coords.update({"x": ("points", [0, 1, 2]), "y": ("points", [0, 1, 2])})NEWLINE actual = data.sel(NEWLINE x=Variable(("points",), [0.1, 1.1, 2.5]),NEWLINE y=Variable(("points",), [0, 1.2, 2.0]),NEWLINE method="pad",NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE idx_x = DataArray([0, 1, 2], dims=["a"], coords={"a": ["a", "b", "c"]})NEWLINE idx_y = DataArray([0, 2, 1], dims=["b"], coords={"b": [0, 3, 6]})NEWLINE expected_ary = data["foo"][[0, 1, 2], [0, 2, 1]]NEWLINE actual = data.sel(x=idx_x, y=idx_y)NEWLINE assert_array_equal(expected_ary, actual["foo"])NEWLINE assert_identical(actual["a"].drop_vars("x"), idx_x["a"])NEWLINE assert_identical(actual["b"].drop_vars("y"), idx_y["b"])NEWLINENEWLINE with pytest.raises(KeyError):NEWLINE data.sel(x=[2.5], y=[2.0], method="pad", tolerance=1e-3)NEWLINENEWLINE def test_sel_method(self):NEWLINE data = create_test_data()NEWLINENEWLINE expected = data.sel(dim2=1)NEWLINE actual = data.sel(dim2=0.95, method="nearest")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = data.sel(dim2=0.95, method="nearest", tolerance=1)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with pytest.raises(KeyError):NEWLINE actual = data.sel(dim2=np.pi, method="nearest", tolerance=0)NEWLINENEWLINE expected = data.sel(dim2=[1.5])NEWLINE actual = data.sel(dim2=[1.45], method="backfill")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(NotImplementedError, "slice objects"):NEWLINE data.sel(dim2=slice(1, 3), method="ffill")NEWLINENEWLINE with raises_regex(TypeError, "``method``"):NEWLINE # this should not pass silentlyNEWLINE data.sel(method=data)NEWLINENEWLINE # cannot pass method if there is no associated coordinateNEWLINE with raises_regex(ValueError, "cannot supply"):NEWLINE data.sel(dim1=0, method="nearest")NEWLINENEWLINE def test_loc(self):NEWLINE data = create_test_data()NEWLINE expected = data.sel(dim3="a")NEWLINE actual = data.loc[dict(dim3="a")]NEWLINE assert_identical(expected, actual)NEWLINE with raises_regex(TypeError, "can only lookup dict"):NEWLINE data.loc["a"]NEWLINE with pytest.raises(TypeError):NEWLINE data.loc[dict(dim3="a")] = 0NEWLINENEWLINE def test_selection_multiindex(self):NEWLINE mindex = pd.MultiIndex.from_product(NEWLINE [["a", "b"], [1, 2], [-1, -2]], names=("one", "two", "three")NEWLINE )NEWLINE mdata = Dataset(data_vars={"var": ("x", range(8))}, coords={"x": mindex})NEWLINENEWLINE def test_sel(lab_indexer, pos_indexer, replaced_idx=False, renamed_dim=None):NEWLINE ds = mdata.sel(x=lab_indexer)NEWLINE expected_ds = mdata.isel(x=pos_indexer)NEWLINE if not replaced_idx:NEWLINE assert_identical(ds, expected_ds)NEWLINE else:NEWLINE if renamed_dim:NEWLINE assert ds["var"].dims[0] == renamed_dimNEWLINE ds = ds.rename({renamed_dim: "x"})NEWLINE assert_identical(ds["var"].variable, expected_ds["var"].variable)NEWLINE assert not ds["x"].equals(expected_ds["x"])NEWLINENEWLINE test_sel(("a", 1, -1), 0)NEWLINE test_sel(("b", 2, -2), -1)NEWLINE test_sel(("a", 1), [0, 1], replaced_idx=True, renamed_dim="three")NEWLINE test_sel(("a",), range(4), replaced_idx=True)NEWLINE test_sel("a", range(4), replaced_idx=True)NEWLINE test_sel([("a", 1, -1), ("b", 2, -2)], [0, 7])NEWLINE test_sel(slice("a", "b"), range(8))NEWLINE test_sel(slice(("a", 1), ("b", 1)), range(6))NEWLINE test_sel({"one": "a", "two": 1, "three": -1}, 0)NEWLINE test_sel({"one": "a", "two": 1}, [0, 1], replaced_idx=True, renamed_dim="three")NEWLINE test_sel({"one": "a"}, range(4), replaced_idx=True)NEWLINENEWLINE assert_identical(mdata.loc[{"x": {"one": "a"}}], mdata.sel(x={"one": "a"}))NEWLINE assert_identical(mdata.loc[{"x": "a"}], mdata.sel(x="a"))NEWLINE assert_identical(mdata.loc[{"x": ("a", 1)}], mdata.sel(x=("a", 1)))NEWLINE assert_identical(mdata.loc[{"x": ("a", 1, -1)}], mdata.sel(x=("a", 1, -1)))NEWLINENEWLINE assert_identical(mdata.sel(x={"one": "a", "two": 1}), mdata.sel(one="a", two=1))NEWLINENEWLINE def test_broadcast_like(self):NEWLINE original1 = DataArray(NEWLINE np.random.randn(5), [("x", range(5))], name="a"NEWLINE ).to_dataset()NEWLINENEWLINE original2 = DataArray(np.random.randn(6), [("y", range(6))], name="b")NEWLINENEWLINE expected1, expected2 = broadcast(original1, original2)NEWLINENEWLINE assert_identical(NEWLINE original1.broadcast_like(original2), expected1.transpose("y", "x")NEWLINE )NEWLINENEWLINE assert_identical(original2.broadcast_like(original1), expected2)NEWLINENEWLINE def test_reindex_like(self):NEWLINE data = create_test_data()NEWLINE data["letters"] = ("dim3", 10 * ["a"])NEWLINENEWLINE expected = data.isel(dim1=slice(10), time=slice(13))NEWLINE actual = data.reindex_like(expected)NEWLINE assert_identical(actual, expected)NEWLINENEWLINE expected = data.copy(deep=True)NEWLINE expected["dim3"] = ("dim3", list("cdefghijkl"))NEWLINE expected["var3"][:-2] = expected["var3"][2:].valuesNEWLINE expected["var3"][-2:] = np.nanNEWLINE expected["letters"] = expected["letters"].astype(object)NEWLINE expected["letters"][-2:] = np.nanNEWLINE expected["numbers"] = expected["numbers"].astype(float)NEWLINE expected["numbers"][:-2] = expected["numbers"][2:].valuesNEWLINE expected["numbers"][-2:] = np.nanNEWLINE actual = data.reindex_like(expected)NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_reindex(self):NEWLINE data = create_test_data()NEWLINE assert_identical(data, data.reindex())NEWLINENEWLINE expected = data.assign_coords(dim1=data["dim1"])NEWLINE actual = data.reindex(dim1=data["dim1"])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = data.reindex(dim1=data["dim1"].values)NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = data.reindex(dim1=data["dim1"].to_index())NEWLINE assert_identical(actual, expected)NEWLINENEWLINE with raises_regex(ValueError, "cannot reindex or align along dimension"):NEWLINE data.reindex(dim1=data["dim1"][:5])NEWLINENEWLINE expected = data.isel(dim2=slice(5))NEWLINE actual = data.reindex(dim2=data["dim2"][:5])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE # test dict-like argumentNEWLINE actual = data.reindex({"dim2": data["dim2"]})NEWLINE expected = dataNEWLINE assert_identical(actual, expected)NEWLINE with raises_regex(ValueError, "cannot specify both"):NEWLINE data.reindex({"x": 0}, x=0)NEWLINE with raises_regex(ValueError, "dictionary"):NEWLINE data.reindex("foo")NEWLINENEWLINE # invalid dimensionNEWLINE with raises_regex(ValueError, "invalid reindex dim"):NEWLINE data.reindex(invalid=0)NEWLINENEWLINE # out of orderNEWLINE expected = data.sel(dim2=data["dim2"][:5:-1])NEWLINE actual = data.reindex(dim2=data["dim2"][:5:-1])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE # regression test for #279NEWLINE expected = Dataset({"x": ("time", np.random.randn(5))}, {"time": range(5)})NEWLINE time2 = DataArray(np.arange(5), dims="time2")NEWLINE with pytest.raises(ValueError):NEWLINE actual = expected.reindex(time=time2)NEWLINENEWLINE # another regression testNEWLINE ds = Dataset(NEWLINE {"foo": (["x", "y"], np.zeros((3, 4)))}, {"x": range(3), "y": range(4)}NEWLINE )NEWLINE expected = Dataset(NEWLINE {"foo": (["x", "y"], np.zeros((3, 2)))}, {"x": [0, 1, 3], "y": [0, 1]}NEWLINE )NEWLINE expected["foo"][-1] = np.nanNEWLINE actual = ds.reindex(x=[0, 1, 3], y=[0, 1])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_reindex_warning(self):NEWLINE data = create_test_data()NEWLINENEWLINE with pytest.raises(ValueError):NEWLINE # DataArray with different dimension raises Future warningNEWLINE ind = xr.DataArray([0.0, 1.0], dims=["new_dim"], name="ind")NEWLINE data.reindex(dim2=ind)NEWLINENEWLINE # Should not warnNEWLINE ind = xr.DataArray([0.0, 1.0], dims=["dim2"], name="ind")NEWLINE with pytest.warns(None) as ws:NEWLINE data.reindex(dim2=ind)NEWLINE assert len(ws) == 0NEWLINENEWLINE def test_reindex_variables_copied(self):NEWLINE data = create_test_data()NEWLINE reindexed_data = data.reindex(copy=False)NEWLINE for k in data.variables:NEWLINE assert reindexed_data.variables[k] is not data.variables[k]NEWLINENEWLINE def test_reindex_method(self):NEWLINE ds = Dataset({"x": ("y", [10, 20]), "y": [0, 1]})NEWLINE y = [-0.5, 0.5, 1.5]NEWLINE actual = ds.reindex(y=y, method="backfill")NEWLINE expected = Dataset({"x": ("y", [10, 20, np.nan]), "y": y})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.reindex(y=y, method="backfill", tolerance=0.1)NEWLINE expected = Dataset({"x": ("y", 3 * [np.nan]), "y": y})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.reindex(y=y, method="pad")NEWLINE expected = Dataset({"x": ("y", [np.nan, 10, 20]), "y": y})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE alt = Dataset({"y": y})NEWLINE actual = ds.reindex_like(alt, method="pad")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE @pytest.mark.parametrize("fill_value", [dtypes.NA, 2, 2.0])NEWLINE def test_reindex_fill_value(self, fill_value):NEWLINE ds = Dataset({"x": ("y", [10, 20]), "y": [0, 1]})NEWLINE y = [0, 1, 2]NEWLINE actual = ds.reindex(y=y, fill_value=fill_value)NEWLINE if fill_value == dtypes.NA:NEWLINE # if we supply the default, we expect the missing value for aNEWLINE # float arrayNEWLINE fill_value = np.nanNEWLINE expected = Dataset({"x": ("y", [10, 20, fill_value]), "y": y})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE @pytest.mark.parametrize("fill_value", [dtypes.NA, 2, 2.0])NEWLINE def test_reindex_like_fill_value(self, fill_value):NEWLINE ds = Dataset({"x": ("y", [10, 20]), "y": [0, 1]})NEWLINE y = [0, 1, 2]NEWLINE alt = Dataset({"y": y})NEWLINE actual = ds.reindex_like(alt, fill_value=fill_value)NEWLINE if fill_value == dtypes.NA:NEWLINE # if we supply the default, we expect the missing value for aNEWLINE # float arrayNEWLINE fill_value = np.nanNEWLINE expected = Dataset({"x": ("y", [10, 20, fill_value]), "y": y})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE @pytest.mark.parametrize("fill_value", [dtypes.NA, 2, 2.0])NEWLINE def test_align_fill_value(self, fill_value):NEWLINE x = Dataset({"foo": DataArray([1, 2], dims=["x"], coords={"x": [1, 2]})})NEWLINE y = Dataset({"bar": DataArray([1, 2], dims=["x"], coords={"x": [1, 3]})})NEWLINE x2, y2 = align(x, y, join="outer", fill_value=fill_value)NEWLINE if fill_value == dtypes.NA:NEWLINE # if we supply the default, we expect the missing value for aNEWLINE # float arrayNEWLINE fill_value = np.nanNEWLINENEWLINE expected_x2 = Dataset(NEWLINE {"foo": DataArray([1, 2, fill_value], dims=["x"], coords={"x": [1, 2, 3]})}NEWLINE )NEWLINE expected_y2 = Dataset(NEWLINE {"bar": DataArray([1, fill_value, 2], dims=["x"], coords={"x": [1, 2, 3]})}NEWLINE )NEWLINE assert_identical(expected_x2, x2)NEWLINE assert_identical(expected_y2, y2)NEWLINENEWLINE def test_align(self):NEWLINE left = create_test_data()NEWLINE right = left.copy(deep=True)NEWLINE right["dim3"] = ("dim3", list("cdefghijkl"))NEWLINE right["var3"][:-2] = right["var3"][2:].valuesNEWLINE right["var3"][-2:] = np.random.randn(*right["var3"][-2:].shape)NEWLINE right["numbers"][:-2] = right["numbers"][2:].valuesNEWLINE right["numbers"][-2:] = -10NEWLINENEWLINE intersection = list("cdefghij")NEWLINE union = list("abcdefghijkl")NEWLINENEWLINE left2, right2 = align(left, right, join="inner")NEWLINE assert_array_equal(left2["dim3"], intersection)NEWLINE assert_identical(left2, right2)NEWLINENEWLINE left2, right2 = align(left, right, join="outer")NEWLINENEWLINE assert_array_equal(left2["dim3"], union)NEWLINE assert_equal(left2["dim3"].variable, right2["dim3"].variable)NEWLINENEWLINE assert_identical(left2.sel(dim3=intersection), right2.sel(dim3=intersection))NEWLINE assert np.isnan(left2["var3"][-2:]).all()NEWLINE assert np.isnan(right2["var3"][:2]).all()NEWLINENEWLINE left2, right2 = align(left, right, join="left")NEWLINE assert_equal(left2["dim3"].variable, right2["dim3"].variable)NEWLINE assert_equal(left2["dim3"].variable, left["dim3"].variable)NEWLINENEWLINE assert_identical(left2.sel(dim3=intersection), right2.sel(dim3=intersection))NEWLINE assert np.isnan(right2["var3"][:2]).all()NEWLINENEWLINE left2, right2 = align(left, right, join="right")NEWLINE assert_equal(left2["dim3"].variable, right2["dim3"].variable)NEWLINE assert_equal(left2["dim3"].variable, right["dim3"].variable)NEWLINENEWLINE assert_identical(left2.sel(dim3=intersection), right2.sel(dim3=intersection))NEWLINENEWLINE assert np.isnan(left2["var3"][-2:]).all()NEWLINENEWLINE with raises_regex(ValueError, "invalid value for join"):NEWLINE align(left, right, join="foobar")NEWLINE with pytest.raises(TypeError):NEWLINE align(left, right, foo="bar")NEWLINENEWLINE def test_align_exact(self):NEWLINE left = xr.Dataset(coords={"x": [0, 1]})NEWLINE right = xr.Dataset(coords={"x": [1, 2]})NEWLINENEWLINE left1, left2 = xr.align(left, left, join="exact")NEWLINE assert_identical(left1, left)NEWLINE assert_identical(left2, left)NEWLINENEWLINE with raises_regex(ValueError, "indexes .* not equal"):NEWLINE xr.align(left, right, join="exact")NEWLINENEWLINE def test_align_override(self):NEWLINE left = xr.Dataset(coords={"x": [0, 1, 2]})NEWLINE right = xr.Dataset(coords={"x": [0.1, 1.1, 2.1], "y": [1, 2, 3]})NEWLINE expected_right = xr.Dataset(coords={"x": [0, 1, 2], "y": [1, 2, 3]})NEWLINENEWLINE new_left, new_right = xr.align(left, right, join="override")NEWLINE assert_identical(left, new_left)NEWLINE assert_identical(new_right, expected_right)NEWLINENEWLINE new_left, new_right = xr.align(left, right, exclude="x", join="override")NEWLINE assert_identical(left, new_left)NEWLINE assert_identical(right, new_right)NEWLINENEWLINE new_left, new_right = xr.align(NEWLINE left.isel(x=0, drop=True), right, exclude="x", join="override"NEWLINE )NEWLINE assert_identical(left.isel(x=0, drop=True), new_left)NEWLINE assert_identical(right, new_right)NEWLINENEWLINE with raises_regex(ValueError, "Indexes along dimension 'x' don't have"):NEWLINE xr.align(left.isel(x=0).expand_dims("x"), right, join="override")NEWLINENEWLINE def test_align_exclude(self):NEWLINE x = Dataset(NEWLINE {NEWLINE "foo": DataArray(NEWLINE [[1, 2], [3, 4]], dims=["x", "y"], coords={"x": [1, 2], "y": [3, 4]}NEWLINE )NEWLINE }NEWLINE )NEWLINE y = Dataset(NEWLINE {NEWLINE "bar": DataArray(NEWLINE [[1, 2], [3, 4]], dims=["x", "y"], coords={"x": [1, 3], "y": [5, 6]}NEWLINE )NEWLINE }NEWLINE )NEWLINE x2, y2 = align(x, y, exclude=["y"], join="outer")NEWLINENEWLINE expected_x2 = Dataset(NEWLINE {NEWLINE "foo": DataArray(NEWLINE [[1, 2], [3, 4], [np.nan, np.nan]],NEWLINE dims=["x", "y"],NEWLINE coords={"x": [1, 2, 3], "y": [3, 4]},NEWLINE )NEWLINE }NEWLINE )NEWLINE expected_y2 = Dataset(NEWLINE {NEWLINE "bar": DataArray(NEWLINE [[1, 2], [np.nan, np.nan], [3, 4]],NEWLINE dims=["x", "y"],NEWLINE coords={"x": [1, 2, 3], "y": [5, 6]},NEWLINE )NEWLINE }NEWLINE )NEWLINE assert_identical(expected_x2, x2)NEWLINE assert_identical(expected_y2, y2)NEWLINENEWLINE def test_align_nocopy(self):NEWLINE x = Dataset({"foo": DataArray([1, 2, 3], coords=[("x", [1, 2, 3])])})NEWLINE y = Dataset({"foo": DataArray([1, 2], coords=[("x", [1, 2])])})NEWLINE expected_x2 = xNEWLINE expected_y2 = Dataset(NEWLINE {"foo": DataArray([1, 2, np.nan], coords=[("x", [1, 2, 3])])}NEWLINE )NEWLINENEWLINE x2, y2 = align(x, y, copy=False, join="outer")NEWLINE assert_identical(expected_x2, x2)NEWLINE assert_identical(expected_y2, y2)NEWLINE assert source_ndarray(x["foo"].data) is source_ndarray(x2["foo"].data)NEWLINENEWLINE x2, y2 = align(x, y, copy=True, join="outer")NEWLINE assert source_ndarray(x["foo"].data) is not source_ndarray(x2["foo"].data)NEWLINE assert_identical(expected_x2, x2)NEWLINE assert_identical(expected_y2, y2)NEWLINENEWLINE def test_align_indexes(self):NEWLINE x = Dataset({"foo": DataArray([1, 2, 3], dims="x", coords=[("x", [1, 2, 3])])})NEWLINE (x2,) = align(x, indexes={"x": [2, 3, 1]})NEWLINE expected_x2 = Dataset(NEWLINE {"foo": DataArray([2, 3, 1], dims="x", coords={"x": [2, 3, 1]})}NEWLINE )NEWLINENEWLINE assert_identical(expected_x2, x2)NEWLINENEWLINE def test_align_non_unique(self):NEWLINE x = Dataset({"foo": ("x", [3, 4, 5]), "x": [0, 0, 1]})NEWLINE x1, x2 = align(x, x)NEWLINE assert x1.identical(x) and x2.identical(x)NEWLINENEWLINE y = Dataset({"bar": ("x", [6, 7]), "x": [0, 1]})NEWLINE with raises_regex(ValueError, "cannot reindex or align"):NEWLINE align(x, y)NEWLINENEWLINE def test_broadcast(self):NEWLINE ds = Dataset(NEWLINE {"foo": 0, "bar": ("x", [1]), "baz": ("y", [2, 3])}, {"c": ("x", [4])}NEWLINE )NEWLINE expected = Dataset(NEWLINE {NEWLINE "foo": (("x", "y"), [[0, 0]]),NEWLINE "bar": (("x", "y"), [[1, 1]]),NEWLINE "baz": (("x", "y"), [[2, 3]]),NEWLINE },NEWLINE {"c": ("x", [4])},NEWLINE )NEWLINE (actual,) = broadcast(ds)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE ds_x = Dataset({"foo": ("x", [1])})NEWLINE ds_y = Dataset({"bar": ("y", [2, 3])})NEWLINE expected_x = Dataset({"foo": (("x", "y"), [[1, 1]])})NEWLINE expected_y = Dataset({"bar": (("x", "y"), [[2, 3]])})NEWLINE actual_x, actual_y = broadcast(ds_x, ds_y)NEWLINE assert_identical(expected_x, actual_x)NEWLINE assert_identical(expected_y, actual_y)NEWLINENEWLINE array_y = ds_y["bar"]NEWLINE expected_y = expected_y["bar"]NEWLINE actual_x, actual_y = broadcast(ds_x, array_y)NEWLINE assert_identical(expected_x, actual_x)NEWLINE assert_identical(expected_y, actual_y)NEWLINENEWLINE def test_broadcast_nocopy(self):NEWLINE # Test that data is not copied if not neededNEWLINE x = Dataset({"foo": (("x", "y"), [[1, 1]])})NEWLINE y = Dataset({"bar": ("y", [2, 3])})NEWLINENEWLINE (actual_x,) = broadcast(x)NEWLINE assert_identical(x, actual_x)NEWLINE assert source_ndarray(actual_x["foo"].data) is source_ndarray(x["foo"].data)NEWLINENEWLINE actual_x, actual_y = broadcast(x, y)NEWLINE assert_identical(x, actual_x)NEWLINE assert source_ndarray(actual_x["foo"].data) is source_ndarray(x["foo"].data)NEWLINENEWLINE def test_broadcast_exclude(self):NEWLINE x = Dataset(NEWLINE {NEWLINE "foo": DataArray(NEWLINE [[1, 2], [3, 4]], dims=["x", "y"], coords={"x": [1, 2], "y": [3, 4]}NEWLINE ),NEWLINE "bar": DataArray(5),NEWLINE }NEWLINE )NEWLINE y = Dataset(NEWLINE {NEWLINE "foo": DataArray(NEWLINE [[1, 2]], dims=["z", "y"], coords={"z": [1], "y": [5, 6]}NEWLINE )NEWLINE }NEWLINE )NEWLINE x2, y2 = broadcast(x, y, exclude=["y"])NEWLINENEWLINE expected_x2 = Dataset(NEWLINE {NEWLINE "foo": DataArray(NEWLINE [[[1, 2]], [[3, 4]]],NEWLINE dims=["x", "z", "y"],NEWLINE coords={"z": [1], "x": [1, 2], "y": [3, 4]},NEWLINE ),NEWLINE "bar": DataArray(NEWLINE [[5], [5]], dims=["x", "z"], coords={"x": [1, 2], "z": [1]}NEWLINE ),NEWLINE }NEWLINE )NEWLINE expected_y2 = Dataset(NEWLINE {NEWLINE "foo": DataArray(NEWLINE [[[1, 2]], [[1, 2]]],NEWLINE dims=["x", "z", "y"],NEWLINE coords={"z": [1], "x": [1, 2], "y": [5, 6]},NEWLINE )NEWLINE }NEWLINE )NEWLINE assert_identical(expected_x2, x2)NEWLINE assert_identical(expected_y2, y2)NEWLINENEWLINE def test_broadcast_misaligned(self):NEWLINE x = Dataset({"foo": DataArray([1, 2, 3], coords=[("x", [-1, -2, -3])])})NEWLINE y = Dataset(NEWLINE {NEWLINE "bar": DataArray(NEWLINE [[1, 2], [3, 4]],NEWLINE dims=["y", "x"],NEWLINE coords={"y": [1, 2], "x": [10, -3]},NEWLINE )NEWLINE }NEWLINE )NEWLINE x2, y2 = broadcast(x, y)NEWLINE expected_x2 = Dataset(NEWLINE {NEWLINE "foo": DataArray(NEWLINE [[3, 3], [2, 2], [1, 1], [np.nan, np.nan]],NEWLINE dims=["x", "y"],NEWLINE coords={"y": [1, 2], "x": [-3, -2, -1, 10]},NEWLINE )NEWLINE }NEWLINE )NEWLINE expected_y2 = Dataset(NEWLINE {NEWLINE "bar": DataArray(NEWLINE [[2, 4], [np.nan, np.nan], [np.nan, np.nan], [1, 3]],NEWLINE dims=["x", "y"],NEWLINE coords={"y": [1, 2], "x": [-3, -2, -1, 10]},NEWLINE )NEWLINE }NEWLINE )NEWLINE assert_identical(expected_x2, x2)NEWLINE assert_identical(expected_y2, y2)NEWLINENEWLINE def test_variable_indexing(self):NEWLINE data = create_test_data()NEWLINE v = data["var1"]NEWLINE d1 = data["dim1"]NEWLINE d2 = data["dim2"]NEWLINE assert_equal(v, v[d1.values])NEWLINE assert_equal(v, v[d1])NEWLINE assert_equal(v[:3], v[d1 < 3])NEWLINE assert_equal(v[:, 3:], v[:, d2 >= 1.5])NEWLINE assert_equal(v[:3, 3:], v[d1 < 3, d2 >= 1.5])NEWLINE assert_equal(v[:3, :2], v[range(3), range(2)])NEWLINE assert_equal(v[:3, :2], v.loc[d1[:3], d2[:2]])NEWLINENEWLINE def test_drop_variables(self):NEWLINE data = create_test_data()NEWLINENEWLINE assert_identical(data, data.drop_vars([]))NEWLINENEWLINE expected = Dataset({k: data[k] for k in data.variables if k != "time"})NEWLINE actual = data.drop_vars("time")NEWLINE assert_identical(expected, actual)NEWLINE actual = data.drop_vars(["time"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(ValueError, "cannot be found"):NEWLINE data.drop_vars("not_found_here")NEWLINENEWLINE actual = data.drop_vars("not_found_here", errors="ignore")NEWLINE assert_identical(data, actual)NEWLINENEWLINE actual = data.drop_vars(["not_found_here"], errors="ignore")NEWLINE assert_identical(data, actual)NEWLINENEWLINE actual = data.drop_vars(["time", "not_found_here"], errors="ignore")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # deprecated approach with `drop` works (straight copy paste from above)NEWLINENEWLINE with pytest.warns(PendingDeprecationWarning):NEWLINE actual = data.drop("not_found_here", errors="ignore")NEWLINE assert_identical(data, actual)NEWLINENEWLINE with pytest.warns(PendingDeprecationWarning):NEWLINE actual = data.drop(["not_found_here"], errors="ignore")NEWLINE assert_identical(data, actual)NEWLINENEWLINE with pytest.warns(PendingDeprecationWarning):NEWLINE actual = data.drop(["time", "not_found_here"], errors="ignore")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_drop_index_labels(self):NEWLINE data = Dataset({"A": (["x", "y"], np.random.randn(2, 3)), "x": ["a", "b"]})NEWLINENEWLINE with pytest.warns(DeprecationWarning):NEWLINE actual = data.drop(["a"], dim="x")NEWLINE expected = data.isel(x=[1])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with pytest.warns(DeprecationWarning):NEWLINE actual = data.drop(["a", "b"], dim="x")NEWLINE expected = data.isel(x=slice(0, 0))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with pytest.raises(KeyError):NEWLINE # not contained in axisNEWLINE with pytest.warns(DeprecationWarning):NEWLINE data.drop(["c"], dim="x")NEWLINENEWLINE with pytest.warns(DeprecationWarning):NEWLINE actual = data.drop(["c"], dim="x", errors="ignore")NEWLINE assert_identical(data, actual)NEWLINENEWLINE with pytest.raises(ValueError):NEWLINE with pytest.warns(DeprecationWarning):NEWLINE data.drop(["c"], dim="x", errors="wrong_value")NEWLINENEWLINE with pytest.warns(DeprecationWarning):NEWLINE actual = data.drop(["a", "b", "c"], "x", errors="ignore")NEWLINE expected = data.isel(x=slice(0, 0))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # DataArrays as labels are a nasty corner case as they are notNEWLINE # Iterable[Hashable] - DataArray.__iter__ yields scalar DataArrays.NEWLINE actual = data.drop_sel(x=DataArray(["a", "b", "c"]), errors="ignore")NEWLINE expected = data.isel(x=slice(0, 0))NEWLINE assert_identical(expected, actual)NEWLINE with pytest.warns(DeprecationWarning):NEWLINE data.drop(DataArray(["a", "b", "c"]), dim="x", errors="ignore")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(ValueError, "does not have coordinate labels"):NEWLINE data.drop_sel(y=1)NEWLINENEWLINE def test_drop_labels_by_keyword(self):NEWLINE data = Dataset(NEWLINE {"A": (["x", "y"], np.random.randn(2, 6)), "x": ["a", "b"], "y": range(6)}NEWLINE )NEWLINE # Basic functionality.NEWLINE assert len(data.coords["x"]) == 2NEWLINENEWLINE with pytest.warns(DeprecationWarning):NEWLINE ds1 = data.drop(["a"], dim="x")NEWLINE ds2 = data.drop_sel(x="a")NEWLINE ds3 = data.drop_sel(x=["a"])NEWLINE ds4 = data.drop_sel(x=["a", "b"])NEWLINE ds5 = data.drop_sel(x=["a", "b"], y=range(0, 6, 2))NEWLINENEWLINE arr = DataArray(range(3), dims=["c"])NEWLINE with pytest.warns(FutureWarning):NEWLINE data.drop(arr.coords)NEWLINE with pytest.warns(FutureWarning):NEWLINE data.drop(arr.indexes)NEWLINENEWLINE assert_array_equal(ds1.coords["x"], ["b"])NEWLINE assert_array_equal(ds2.coords["x"], ["b"])NEWLINE assert_array_equal(ds3.coords["x"], ["b"])NEWLINE assert ds4.coords["x"].size == 0NEWLINE assert ds5.coords["x"].size == 0NEWLINE assert_array_equal(ds5.coords["y"], [1, 3, 5])NEWLINENEWLINE # Error handling if user tries both approaches.NEWLINE with pytest.raises(ValueError):NEWLINE data.drop(labels=["a"], x="a")NEWLINE with pytest.raises(ValueError):NEWLINE data.drop(labels=["a"], dim="x", x="a")NEWLINE warnings.filterwarnings("ignore", r"\W*drop")NEWLINE with pytest.raises(ValueError):NEWLINE data.drop(dim="x", x="a")NEWLINENEWLINE def test_drop_dims(self):NEWLINE data = xr.Dataset(NEWLINE {NEWLINE "A": (["x", "y"], np.random.randn(2, 3)),NEWLINE "B": ("x", np.random.randn(2)),NEWLINE "x": ["a", "b"],NEWLINE "z": np.pi,NEWLINE }NEWLINE )NEWLINENEWLINE actual = data.drop_dims("x")NEWLINE expected = data.drop_vars(["A", "B", "x"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = data.drop_dims("y")NEWLINE expected = data.drop_vars("A")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = data.drop_dims(["x", "y"])NEWLINE expected = data.drop_vars(["A", "B", "x"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with pytest.raises((ValueError, KeyError)):NEWLINE data.drop_dims("z") # not a dimensionNEWLINENEWLINE with pytest.raises((ValueError, KeyError)):NEWLINE data.drop_dims(None)NEWLINENEWLINE actual = data.drop_dims("z", errors="ignore")NEWLINE assert_identical(data, actual)NEWLINENEWLINE actual = data.drop_dims(None, errors="ignore")NEWLINE assert_identical(data, actual)NEWLINENEWLINE with pytest.raises(ValueError):NEWLINE actual = data.drop_dims("z", errors="wrong_value")NEWLINENEWLINE actual = data.drop_dims(["x", "y", "z"], errors="ignore")NEWLINE expected = data.drop_vars(["A", "B", "x"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_copy(self):NEWLINE data = create_test_data()NEWLINE data.attrs["Test"] = [1, 2, 3]NEWLINENEWLINE for copied in [data.copy(deep=False), copy(data)]:NEWLINE assert_identical(data, copied)NEWLINE assert data.encoding == copied.encodingNEWLINE # Note: IndexVariable objects with string dtype are alwaysNEWLINE # copied because of xarray.core.util.safe_cast_to_index.NEWLINE # Limiting the test to data variables.NEWLINE for k in data.data_vars:NEWLINE v0 = data.variables[k]NEWLINE v1 = copied.variables[k]NEWLINE assert source_ndarray(v0.data) is source_ndarray(v1.data)NEWLINE copied["foo"] = ("z", np.arange(5))NEWLINE assert "foo" not in dataNEWLINENEWLINE copied.attrs["foo"] = "bar"NEWLINE assert "foo" not in data.attrsNEWLINE assert data.attrs["Test"] is copied.attrs["Test"]NEWLINENEWLINE for copied in [data.copy(deep=True), deepcopy(data)]:NEWLINE assert_identical(data, copied)NEWLINE for k, v0 in data.variables.items():NEWLINE v1 = copied.variables[k]NEWLINE assert v0 is not v1NEWLINENEWLINE assert data.attrs["Test"] is not copied.attrs["Test"]NEWLINENEWLINE def test_copy_with_data(self):NEWLINE orig = create_test_data()NEWLINE new_data = {k: np.random.randn(*v.shape) for k, v in orig.data_vars.items()}NEWLINE actual = orig.copy(data=new_data)NEWLINENEWLINE expected = orig.copy()NEWLINE for k, v in new_data.items():NEWLINE expected[k].data = vNEWLINE assert_identical(expected, actual)NEWLINENEWLINE @pytest.mark.xfail(raises=AssertionError)NEWLINE @pytest.mark.parametrize(NEWLINE "deep, expected_orig",NEWLINE [NEWLINE [NEWLINE True,NEWLINE xr.DataArray(NEWLINE xr.IndexVariable("a", np.array([1, 2])),NEWLINE coords={"a": [1, 2]},NEWLINE dims=["a"],NEWLINE ),NEWLINE ],NEWLINE [NEWLINE False,NEWLINE xr.DataArray(NEWLINE xr.IndexVariable("a", np.array([999, 2])),NEWLINE coords={"a": [999, 2]},NEWLINE dims=["a"],NEWLINE ),NEWLINE ],NEWLINE ],NEWLINE )NEWLINE def test_copy_coords(self, deep, expected_orig):NEWLINE """The test fails for the shallow copy, and apparently only on WindowsNEWLINE for some reason. In windows coords seem to be immutable unless it's oneNEWLINE dataset deep copied from another."""NEWLINE ds = xr.DataArray(NEWLINE np.ones([2, 2, 2]),NEWLINE coords={"a": [1, 2], "b": ["x", "y"], "c": [0, 1]},NEWLINE dims=["a", "b", "c"],NEWLINE name="value",NEWLINE ).to_dataset()NEWLINE ds_cp = ds.copy(deep=deep)NEWLINE ds_cp.coords["a"].data[0] = 999NEWLINENEWLINE expected_cp = xr.DataArray(NEWLINE xr.IndexVariable("a", np.array([999, 2])),NEWLINE coords={"a": [999, 2]},NEWLINE dims=["a"],NEWLINE )NEWLINE assert_identical(ds_cp.coords["a"], expected_cp)NEWLINENEWLINE assert_identical(ds.coords["a"], expected_orig)NEWLINENEWLINE def test_copy_with_data_errors(self):NEWLINE orig = create_test_data()NEWLINE new_var1 = np.arange(orig["var1"].size).reshape(orig["var1"].shape)NEWLINE with raises_regex(ValueError, "Data must be dict-like"):NEWLINE orig.copy(data=new_var1)NEWLINE with raises_regex(ValueError, "only contain variables in original"):NEWLINE orig.copy(data={"not_in_original": new_var1})NEWLINE with raises_regex(ValueError, "contain all variables in original"):NEWLINE orig.copy(data={"var1": new_var1})NEWLINENEWLINE def test_rename(self):NEWLINE data = create_test_data()NEWLINE newnames = {"var1": "renamed_var1", "dim2": "renamed_dim2"}NEWLINE renamed = data.rename(newnames)NEWLINENEWLINE variables = dict(data.variables)NEWLINE for k, v in newnames.items():NEWLINE variables[v] = variables.pop(k)NEWLINENEWLINE for k, v in variables.items():NEWLINE dims = list(v.dims)NEWLINE for name, newname in newnames.items():NEWLINE if name in dims:NEWLINE dims[dims.index(name)] = newnameNEWLINENEWLINE assert_equal(NEWLINE Variable(dims, v.values, v.attrs),NEWLINE renamed[k].variable.to_base_variable(),NEWLINE )NEWLINE assert v.encoding == renamed[k].encodingNEWLINE assert type(v) is type(renamed.variables[k]) # noqa: E721NEWLINENEWLINE assert "var1" not in renamedNEWLINE assert "dim2" not in renamedNEWLINENEWLINE with raises_regex(ValueError, "cannot rename 'not_a_var'"):NEWLINE data.rename({"not_a_var": "nada"})NEWLINENEWLINE with raises_regex(ValueError, "'var1' conflicts"):NEWLINE data.rename({"var2": "var1"})NEWLINENEWLINE # verify that we can rename a variable without accessing the dataNEWLINE var1 = data["var1"]NEWLINE data["var1"] = (var1.dims, InaccessibleArray(var1.values))NEWLINE renamed = data.rename(newnames)NEWLINE with pytest.raises(UnexpectedDataAccess):NEWLINE renamed["renamed_var1"].valuesNEWLINENEWLINE renamed_kwargs = data.rename(**newnames)NEWLINE assert_identical(renamed, renamed_kwargs)NEWLINENEWLINE def test_rename_old_name(self):NEWLINE # regtest for GH1477NEWLINE data = create_test_data()NEWLINENEWLINE with raises_regex(ValueError, "'samecol' conflicts"):NEWLINE data.rename({"var1": "samecol", "var2": "samecol"})NEWLINENEWLINE # This shouldn't cause any problems.NEWLINE data.rename({"var1": "var2", "var2": "var1"})NEWLINENEWLINE def test_rename_same_name(self):NEWLINE data = create_test_data()NEWLINE newnames = {"var1": "var1", "dim2": "dim2"}NEWLINE renamed = data.rename(newnames)NEWLINE assert_identical(renamed, data)NEWLINENEWLINE def test_rename_inplace(self):NEWLINE times = pd.date_range("2000-01-01", periods=3)NEWLINE data = Dataset({"z": ("x", [2, 3, 4]), "t": ("t", times)})NEWLINE with pytest.raises(TypeError):NEWLINE data.rename({"x": "y"}, inplace=True)NEWLINENEWLINE def test_rename_dims(self):NEWLINE original = Dataset({"x": ("x", [0, 1, 2]), "y": ("x", [10, 11, 12]), "z": 42})NEWLINE expected = Dataset(NEWLINE {"x": ("x_new", [0, 1, 2]), "y": ("x_new", [10, 11, 12]), "z": 42}NEWLINE )NEWLINE expected = expected.set_coords("x")NEWLINE dims_dict = {"x": "x_new"}NEWLINE actual = original.rename_dims(dims_dict)NEWLINE assert_identical(expected, actual)NEWLINE actual_2 = original.rename_dims(**dims_dict)NEWLINE assert_identical(expected, actual_2)NEWLINENEWLINE # Test to raise ValueErrorNEWLINE dims_dict_bad = {"x_bad": "x_new"}NEWLINE with pytest.raises(ValueError):NEWLINE original.rename_dims(dims_dict_bad)NEWLINENEWLINE def test_rename_vars(self):NEWLINE original = Dataset({"x": ("x", [0, 1, 2]), "y": ("x", [10, 11, 12]), "z": 42})NEWLINE expected = Dataset(NEWLINE {"x_new": ("x", [0, 1, 2]), "y": ("x", [10, 11, 12]), "z": 42}NEWLINE )NEWLINE expected = expected.set_coords("x_new")NEWLINE name_dict = {"x": "x_new"}NEWLINE actual = original.rename_vars(name_dict)NEWLINE assert_identical(expected, actual)NEWLINE actual_2 = original.rename_vars(**name_dict)NEWLINE assert_identical(expected, actual_2)NEWLINENEWLINE # Test to raise ValueErrorNEWLINE names_dict_bad = {"x_bad": "x_new"}NEWLINE with pytest.raises(ValueError):NEWLINE original.rename_vars(names_dict_bad)NEWLINENEWLINE def test_swap_dims(self):NEWLINE original = Dataset({"x": [1, 2, 3], "y": ("x", list("abc")), "z": 42})NEWLINE expected = Dataset({"z": 42}, {"x": ("y", [1, 2, 3]), "y": list("abc")})NEWLINE actual = original.swap_dims({"x": "y"})NEWLINE assert_identical(expected, actual)NEWLINE assert isinstance(actual.variables["y"], IndexVariable)NEWLINE assert isinstance(actual.variables["x"], Variable)NEWLINE assert actual.indexes["y"].equals(pd.Index(list("abc")))NEWLINENEWLINE roundtripped = actual.swap_dims({"y": "x"})NEWLINE assert_identical(original.set_coords("y"), roundtripped)NEWLINENEWLINE with raises_regex(ValueError, "cannot swap"):NEWLINE original.swap_dims({"y": "x"})NEWLINE with raises_regex(ValueError, "replacement dimension"):NEWLINE original.swap_dims({"x": "z"})NEWLINENEWLINE def test_expand_dims_error(self):NEWLINE original = Dataset(NEWLINE {NEWLINE "x": ("a", np.random.randn(3)),NEWLINE "y": (["b", "a"], np.random.randn(4, 3)),NEWLINE "z": ("a", np.random.randn(3)),NEWLINE },NEWLINE coords={NEWLINE "a": np.linspace(0, 1, 3),NEWLINE "b": np.linspace(0, 1, 4),NEWLINE "c": np.linspace(0, 1, 5),NEWLINE },NEWLINE attrs={"key": "entry"},NEWLINE )NEWLINENEWLINE with raises_regex(ValueError, "already exists"):NEWLINE original.expand_dims(dim=["x"])NEWLINENEWLINE # Make sure it raises true error also for non-dimensional coordinatesNEWLINE # which has dimension.NEWLINE original = original.set_coords("z")NEWLINE with raises_regex(ValueError, "already exists"):NEWLINE original.expand_dims(dim=["z"])NEWLINENEWLINE original = Dataset(NEWLINE {NEWLINE "x": ("a", np.random.randn(3)),NEWLINE "y": (["b", "a"], np.random.randn(4, 3)),NEWLINE "z": ("a", np.random.randn(3)),NEWLINE },NEWLINE coords={NEWLINE "a": np.linspace(0, 1, 3),NEWLINE "b": np.linspace(0, 1, 4),NEWLINE "c": np.linspace(0, 1, 5),NEWLINE },NEWLINE attrs={"key": "entry"},NEWLINE )NEWLINE with raises_regex(TypeError, "value of new dimension"):NEWLINE original.expand_dims({"d": 3.2})NEWLINE with raises_regex(ValueError, "both keyword and positional"):NEWLINE original.expand_dims({"d": 4}, e=4)NEWLINENEWLINE def test_expand_dims_int(self):NEWLINE original = Dataset(NEWLINE {"x": ("a", np.random.randn(3)), "y": (["b", "a"], np.random.randn(4, 3))},NEWLINE coords={NEWLINE "a": np.linspace(0, 1, 3),NEWLINE "b": np.linspace(0, 1, 4),NEWLINE "c": np.linspace(0, 1, 5),NEWLINE },NEWLINE attrs={"key": "entry"},NEWLINE )NEWLINENEWLINE actual = original.expand_dims(["z"], [1])NEWLINE expected = Dataset(NEWLINE {NEWLINE "x": original["x"].expand_dims("z", 1),NEWLINE "y": original["y"].expand_dims("z", 1),NEWLINE },NEWLINE coords={NEWLINE "a": np.linspace(0, 1, 3),NEWLINE "b": np.linspace(0, 1, 4),NEWLINE "c": np.linspace(0, 1, 5),NEWLINE },NEWLINE attrs={"key": "entry"},NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINE # make sure squeeze restores the original data set.NEWLINE roundtripped = actual.squeeze("z")NEWLINE assert_identical(original, roundtripped)NEWLINENEWLINE # another test with a negative axisNEWLINE actual = original.expand_dims(["z"], [-1])NEWLINE expected = Dataset(NEWLINE {NEWLINE "x": original["x"].expand_dims("z", -1),NEWLINE "y": original["y"].expand_dims("z", -1),NEWLINE },NEWLINE coords={NEWLINE "a": np.linspace(0, 1, 3),NEWLINE "b": np.linspace(0, 1, 4),NEWLINE "c": np.linspace(0, 1, 5),NEWLINE },NEWLINE attrs={"key": "entry"},NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINE # make sure squeeze restores the original data set.NEWLINE roundtripped = actual.squeeze("z")NEWLINE assert_identical(original, roundtripped)NEWLINENEWLINE def test_expand_dims_coords(self):NEWLINE original = Dataset({"x": ("a", np.array([1, 2, 3]))})NEWLINE expected = Dataset(NEWLINE {"x": (("b", "a"), np.array([[1, 2, 3], [1, 2, 3]]))}, coords={"b": [1, 2]}NEWLINE )NEWLINE actual = original.expand_dims(dict(b=[1, 2]))NEWLINE assert_identical(expected, actual)NEWLINE assert "b" not in original._coord_namesNEWLINENEWLINE def test_expand_dims_existing_scalar_coord(self):NEWLINE original = Dataset({"x": 1}, {"a": 2})NEWLINE expected = Dataset({"x": (("a",), [1])}, {"a": [2]})NEWLINE actual = original.expand_dims("a")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_isel_expand_dims_roundtrip(self):NEWLINE original = Dataset({"x": (("a",), [1])}, {"a": [2]})NEWLINE actual = original.isel(a=0).expand_dims("a")NEWLINE assert_identical(actual, original)NEWLINENEWLINE def test_expand_dims_mixed_int_and_coords(self):NEWLINE # Test expanding one dimension to have size > 1 that doesn't haveNEWLINE # coordinates, and also expanding another dimension to have size > 1NEWLINE # that DOES have coordinates.NEWLINE original = Dataset(NEWLINE {"x": ("a", np.random.randn(3)), "y": (["b", "a"], np.random.randn(4, 3))},NEWLINE coords={NEWLINE "a": np.linspace(0, 1, 3),NEWLINE "b": np.linspace(0, 1, 4),NEWLINE "c": np.linspace(0, 1, 5),NEWLINE },NEWLINE )NEWLINENEWLINE actual = original.expand_dims({"d": 4, "e": ["l", "m", "n"]})NEWLINENEWLINE expected = Dataset(NEWLINE {NEWLINE "x": xr.DataArray(NEWLINE original["x"].values * np.ones([4, 3, 3]),NEWLINE coords=dict(d=range(4), e=["l", "m", "n"], a=np.linspace(0, 1, 3)),NEWLINE dims=["d", "e", "a"],NEWLINE ).drop_vars("d"),NEWLINE "y": xr.DataArray(NEWLINE original["y"].values * np.ones([4, 3, 4, 3]),NEWLINE coords=dict(NEWLINE d=range(4),NEWLINE e=["l", "m", "n"],NEWLINE b=np.linspace(0, 1, 4),NEWLINE a=np.linspace(0, 1, 3),NEWLINE ),NEWLINE dims=["d", "e", "b", "a"],NEWLINE ).drop_vars("d"),NEWLINE },NEWLINE coords={"c": np.linspace(0, 1, 5)},NEWLINE )NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_expand_dims_kwargs_python36plus(self):NEWLINE original = Dataset(NEWLINE {"x": ("a", np.random.randn(3)), "y": (["b", "a"], np.random.randn(4, 3))},NEWLINE coords={NEWLINE "a": np.linspace(0, 1, 3),NEWLINE "b": np.linspace(0, 1, 4),NEWLINE "c": np.linspace(0, 1, 5),NEWLINE },NEWLINE attrs={"key": "entry"},NEWLINE )NEWLINE other_way = original.expand_dims(e=["l", "m", "n"])NEWLINE other_way_expected = Dataset(NEWLINE {NEWLINE "x": xr.DataArray(NEWLINE original["x"].values * np.ones([3, 3]),NEWLINE coords=dict(e=["l", "m", "n"], a=np.linspace(0, 1, 3)),NEWLINE dims=["e", "a"],NEWLINE ),NEWLINE "y": xr.DataArray(NEWLINE original["y"].values * np.ones([3, 4, 3]),NEWLINE coords=dict(NEWLINE e=["l", "m", "n"],NEWLINE b=np.linspace(0, 1, 4),NEWLINE a=np.linspace(0, 1, 3),NEWLINE ),NEWLINE dims=["e", "b", "a"],NEWLINE ),NEWLINE },NEWLINE coords={"c": np.linspace(0, 1, 5)},NEWLINE attrs={"key": "entry"},NEWLINE )NEWLINE assert_identical(other_way_expected, other_way)NEWLINENEWLINE def test_set_index(self):NEWLINE expected = create_test_multiindex()NEWLINE mindex = expected["x"].to_index()NEWLINE indexes = [mindex.get_level_values(n) for n in mindex.names]NEWLINE coords = {idx.name: ("x", idx) for idx in indexes}NEWLINE ds = Dataset({}, coords=coords)NEWLINENEWLINE obj = ds.set_index(x=mindex.names)NEWLINE assert_identical(obj, expected)NEWLINENEWLINE with pytest.raises(TypeError):NEWLINE ds.set_index(x=mindex.names, inplace=True)NEWLINE assert_identical(ds, expected)NEWLINENEWLINE # ensure set_index with no existing index and a single data var givenNEWLINE # doesn't return multi-indexNEWLINE ds = Dataset(data_vars={"x_var": ("x", [0, 1, 2])})NEWLINE expected = Dataset(coords={"x": [0, 1, 2]})NEWLINE assert_identical(ds.set_index(x="x_var"), expected)NEWLINENEWLINE # Issue 3176: Ensure clear error message on key error.NEWLINE with pytest.raises(ValueError) as excinfo:NEWLINE ds.set_index(foo="bar")NEWLINE assert str(excinfo.value) == "bar is not the name of an existing variable."NEWLINENEWLINE def test_reset_index(self):NEWLINE ds = create_test_multiindex()NEWLINE mindex = ds["x"].to_index()NEWLINE indexes = [mindex.get_level_values(n) for n in mindex.names]NEWLINE coords = {idx.name: ("x", idx) for idx in indexes}NEWLINE expected = Dataset({}, coords=coords)NEWLINENEWLINE obj = ds.reset_index("x")NEWLINE assert_identical(obj, expected)NEWLINENEWLINE with pytest.raises(TypeError):NEWLINE ds.reset_index("x", inplace=True)NEWLINENEWLINE def test_reorder_levels(self):NEWLINE ds = create_test_multiindex()NEWLINE mindex = ds["x"].to_index()NEWLINE midx = mindex.reorder_levels(["level_2", "level_1"])NEWLINE expected = Dataset({}, coords={"x": midx})NEWLINENEWLINE reindexed = ds.reorder_levels(x=["level_2", "level_1"])NEWLINE assert_identical(reindexed, expected)NEWLINENEWLINE with pytest.raises(TypeError):NEWLINE ds.reorder_levels(x=["level_2", "level_1"], inplace=True)NEWLINENEWLINE ds = Dataset({}, coords={"x": [1, 2]})NEWLINE with raises_regex(ValueError, "has no MultiIndex"):NEWLINE ds.reorder_levels(x=["level_1", "level_2"])NEWLINENEWLINE def test_stack(self):NEWLINE ds = Dataset(NEWLINE {"a": ("x", [0, 1]), "b": (("x", "y"), [[0, 1], [2, 3]]), "y": ["a", "b"]}NEWLINE )NEWLINENEWLINE exp_index = pd.MultiIndex.from_product([[0, 1], ["a", "b"]], names=["x", "y"])NEWLINE expected = Dataset(NEWLINE {"a": ("z", [0, 0, 1, 1]), "b": ("z", [0, 1, 2, 3]), "z": exp_index}NEWLINE )NEWLINE actual = ds.stack(z=["x", "y"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE exp_index = pd.MultiIndex.from_product([["a", "b"], [0, 1]], names=["y", "x"])NEWLINE expected = Dataset(NEWLINE {"a": ("z", [0, 1, 0, 1]), "b": ("z", [0, 2, 1, 3]), "z": exp_index}NEWLINE )NEWLINE actual = ds.stack(z=["y", "x"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_unstack(self):NEWLINE index = pd.MultiIndex.from_product([[0, 1], ["a", "b"]], names=["x", "y"])NEWLINE ds = Dataset({"b": ("z", [0, 1, 2, 3]), "z": index})NEWLINE expected = Dataset(NEWLINE {"b": (("x", "y"), [[0, 1], [2, 3]]), "x": [0, 1], "y": ["a", "b"]}NEWLINE )NEWLINE for dim in ["z", ["z"], None]:NEWLINE actual = ds.unstack(dim)NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_unstack_errors(self):NEWLINE ds = Dataset({"x": [1, 2, 3]})NEWLINE with raises_regex(ValueError, "does not contain the dimensions"):NEWLINE ds.unstack("foo")NEWLINE with raises_regex(ValueError, "do not have a MultiIndex"):NEWLINE ds.unstack("x")NEWLINENEWLINE def test_stack_unstack_fast(self):NEWLINE ds = Dataset(NEWLINE {NEWLINE "a": ("x", [0, 1]),NEWLINE "b": (("x", "y"), [[0, 1], [2, 3]]),NEWLINE "x": [0, 1],NEWLINE "y": ["a", "b"],NEWLINE }NEWLINE )NEWLINE actual = ds.stack(z=["x", "y"]).unstack("z")NEWLINE assert actual.broadcast_equals(ds)NEWLINENEWLINE actual = ds[["b"]].stack(z=["x", "y"]).unstack("z")NEWLINE assert actual.identical(ds[["b"]])NEWLINENEWLINE def test_stack_unstack_slow(self):NEWLINE ds = Dataset(NEWLINE {NEWLINE "a": ("x", [0, 1]),NEWLINE "b": (("x", "y"), [[0, 1], [2, 3]]),NEWLINE "x": [0, 1],NEWLINE "y": ["a", "b"],NEWLINE }NEWLINE )NEWLINE stacked = ds.stack(z=["x", "y"])NEWLINE actual = stacked.isel(z=slice(None, None, -1)).unstack("z")NEWLINE assert actual.broadcast_equals(ds)NEWLINENEWLINE stacked = ds[["b"]].stack(z=["x", "y"])NEWLINE actual = stacked.isel(z=slice(None, None, -1)).unstack("z")NEWLINE assert actual.identical(ds[["b"]])NEWLINENEWLINE def test_to_stacked_array_invalid_sample_dims(self):NEWLINE data = xr.Dataset(NEWLINE data_vars={"a": (("x", "y"), [[0, 1, 2], [3, 4, 5]]), "b": ("x", [6, 7])},NEWLINE coords={"y": ["u", "v", "w"]},NEWLINE )NEWLINE with pytest.raises(ValueError):NEWLINE data.to_stacked_array("features", sample_dims=["y"])NEWLINENEWLINE def test_to_stacked_array_name(self):NEWLINE name = "adf9d"NEWLINENEWLINE # make a two dimensional datasetNEWLINE a, b = create_test_stacked_array()NEWLINE D = xr.Dataset({"a": a, "b": b})NEWLINE sample_dims = ["x"]NEWLINENEWLINE y = D.to_stacked_array("features", sample_dims, name=name)NEWLINE assert y.name == nameNEWLINENEWLINE def test_to_stacked_array_dtype_dims(self):NEWLINE # make a two dimensional datasetNEWLINE a, b = create_test_stacked_array()NEWLINE D = xr.Dataset({"a": a, "b": b})NEWLINE sample_dims = ["x"]NEWLINE y = D.to_stacked_array("features", sample_dims)NEWLINE assert y.indexes["features"].levels[1].dtype == D.y.dtypeNEWLINE assert y.dims == ("x", "features")NEWLINENEWLINE def test_to_stacked_array_to_unstacked_dataset(self):NEWLINE # make a two dimensional datasetNEWLINE a, b = create_test_stacked_array()NEWLINE D = xr.Dataset({"a": a, "b": b})NEWLINE sample_dims = ["x"]NEWLINE y = D.to_stacked_array("features", sample_dims).transpose("x", "features")NEWLINENEWLINE x = y.to_unstacked_dataset("features")NEWLINE assert_identical(D, x)NEWLINENEWLINE # test on just one sampleNEWLINE x0 = y[0].to_unstacked_dataset("features")NEWLINE d0 = D.isel(x=0)NEWLINE assert_identical(d0, x0)NEWLINENEWLINE def test_to_stacked_array_to_unstacked_dataset_different_dimension(self):NEWLINE # test when variables have different dimensionalityNEWLINE a, b = create_test_stacked_array()NEWLINE sample_dims = ["x"]NEWLINE D = xr.Dataset({"a": a, "b": b.isel(y=0)})NEWLINENEWLINE y = D.to_stacked_array("features", sample_dims)NEWLINE x = y.to_unstacked_dataset("features")NEWLINE assert_identical(D, x)NEWLINENEWLINE def test_update(self):NEWLINE data = create_test_data(seed=0)NEWLINE expected = data.copy()NEWLINE var2 = Variable("dim1", np.arange(8))NEWLINE actual = data.update({"var2": var2})NEWLINE expected["var2"] = var2NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = data.copy()NEWLINE actual_result = actual.update(data)NEWLINE assert actual_result is actualNEWLINE assert_identical(expected, actual)NEWLINENEWLINE with pytest.raises(TypeError):NEWLINE actual = data.update(data, inplace=False)NEWLINENEWLINE other = Dataset(attrs={"new": "attr"})NEWLINE actual = data.copy()NEWLINE actual.update(other)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_update_overwrite_coords(self):NEWLINE data = Dataset({"a": ("x", [1, 2])}, {"b": 3})NEWLINE data.update(Dataset(coords={"b": 4}))NEWLINE expected = Dataset({"a": ("x", [1, 2])}, {"b": 4})NEWLINE assert_identical(data, expected)NEWLINENEWLINE data = Dataset({"a": ("x", [1, 2])}, {"b": 3})NEWLINE data.update(Dataset({"c": 5}, coords={"b": 4}))NEWLINE expected = Dataset({"a": ("x", [1, 2]), "c": 5}, {"b": 4})NEWLINE assert_identical(data, expected)NEWLINENEWLINE data = Dataset({"a": ("x", [1, 2])}, {"b": 3})NEWLINE data.update({"c": DataArray(5, coords={"b": 4})})NEWLINE expected = Dataset({"a": ("x", [1, 2]), "c": 5}, {"b": 3})NEWLINE assert_identical(data, expected)NEWLINENEWLINE def test_update_auto_align(self):NEWLINE ds = Dataset({"x": ("t", [3, 4])}, {"t": [0, 1]})NEWLINENEWLINE expected = Dataset({"x": ("t", [3, 4]), "y": ("t", [np.nan, 5])}, {"t": [0, 1]})NEWLINE actual = ds.copy()NEWLINE other = {"y": ("t", [5]), "t": [1]}NEWLINE with raises_regex(ValueError, "conflicting sizes"):NEWLINE actual.update(other)NEWLINE actual.update(Dataset(other))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.copy()NEWLINE other = Dataset({"y": ("t", [5]), "t": [100]})NEWLINE actual.update(other)NEWLINE expected = Dataset(NEWLINE {"x": ("t", [3, 4]), "y": ("t", [np.nan] * 2)}, {"t": [0, 1]}NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_getitem(self):NEWLINE data = create_test_data()NEWLINE assert isinstance(data["var1"], DataArray)NEWLINE assert_equal(data["var1"].variable, data.variables["var1"])NEWLINE with pytest.raises(KeyError):NEWLINE data["notfound"]NEWLINE with pytest.raises(KeyError):NEWLINE data[["var1", "notfound"]]NEWLINENEWLINE actual = data[["var1", "var2"]]NEWLINE expected = Dataset({"var1": data["var1"], "var2": data["var2"]})NEWLINE assert_equal(expected, actual)NEWLINENEWLINE actual = data["numbers"]NEWLINE expected = DataArray(NEWLINE data["numbers"].variable,NEWLINE {"dim3": data["dim3"], "numbers": data["numbers"]},NEWLINE dims="dim3",NEWLINE name="numbers",NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = data[dict(dim1=0)]NEWLINE expected = data.isel(dim1=0)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_getitem_hashable(self):NEWLINE data = create_test_data()NEWLINE data[(3, 4)] = data["var1"] + 1NEWLINE expected = data["var1"] + 1NEWLINE expected.name = (3, 4)NEWLINE assert_identical(expected, data[(3, 4)])NEWLINE with raises_regex(KeyError, "('var1', 'var2')"):NEWLINE data[("var1", "var2")]NEWLINENEWLINE def test_virtual_variables_default_coords(self):NEWLINE dataset = Dataset({"foo": ("x", range(10))})NEWLINE expected = DataArray(range(10), dims="x", name="x")NEWLINE actual = dataset["x"]NEWLINE assert_identical(expected, actual)NEWLINE assert isinstance(actual.variable, IndexVariable)NEWLINENEWLINE actual = dataset[["x", "foo"]]NEWLINE expected = dataset.assign_coords(x=range(10))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_virtual_variables_time(self):NEWLINE # access virtual variablesNEWLINE data = create_test_data()NEWLINE expected = DataArray(NEWLINE 1 + np.arange(20), coords=[data["time"]], dims="time", name="dayofyear"NEWLINE )NEWLINENEWLINE assert_array_equal(NEWLINE data["time.month"].values, data.variables["time"].to_index().monthNEWLINE )NEWLINE assert_array_equal(data["time.season"].values, "DJF")NEWLINE # test virtual variable mathNEWLINE assert_array_equal(data["time.dayofyear"] + 1, 2 + np.arange(20))NEWLINE assert_array_equal(np.sin(data["time.dayofyear"]), np.sin(1 + np.arange(20)))NEWLINE # ensure they become coordinatesNEWLINE expected = Dataset({}, {"dayofyear": data["time.dayofyear"]})NEWLINE actual = data[["time.dayofyear"]]NEWLINE assert_equal(expected, actual)NEWLINE # non-coordinate variablesNEWLINE ds = Dataset({"t": ("x", pd.date_range("2000-01-01", periods=3))})NEWLINE assert (ds["t.year"] == 2000).all()NEWLINENEWLINE def test_virtual_variable_same_name(self):NEWLINE # regression test for GH367NEWLINE times = pd.date_range("2000-01-01", freq="H", periods=5)NEWLINE data = Dataset({"time": times})NEWLINE actual = data["time.time"]NEWLINE expected = DataArray(times.time, [("time", times)], name="time")NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_virtual_variable_multiindex(self):NEWLINE # access multi-index levels as virtual variablesNEWLINE data = create_test_multiindex()NEWLINE expected = DataArray(NEWLINE ["a", "a", "b", "b"],NEWLINE name="level_1",NEWLINE coords=[data["x"].to_index()],NEWLINE dims="x",NEWLINE )NEWLINE assert_identical(expected, data["level_1"])NEWLINENEWLINE # combine multi-index level and datetimeNEWLINE dr_index = pd.date_range("1/1/2011", periods=4, freq="H")NEWLINE mindex = pd.MultiIndex.from_arrays(NEWLINE [["a", "a", "b", "b"], dr_index], names=("level_str", "level_date")NEWLINE )NEWLINE data = Dataset({}, {"x": mindex})NEWLINE expected = DataArray(NEWLINE mindex.get_level_values("level_date").hour,NEWLINE name="hour",NEWLINE coords=[mindex],NEWLINE dims="x",NEWLINE )NEWLINE assert_identical(expected, data["level_date.hour"])NEWLINENEWLINE # attribute style accessNEWLINE assert_identical(data.level_str, data["level_str"])NEWLINENEWLINE def test_time_season(self):NEWLINE ds = Dataset({"t": pd.date_range("2000-01-01", periods=12, freq="M")})NEWLINE seas = ["DJF"] * 2 + ["MAM"] * 3 + ["JJA"] * 3 + ["SON"] * 3 + ["DJF"]NEWLINE assert_array_equal(seas, ds["t.season"])NEWLINENEWLINE def test_slice_virtual_variable(self):NEWLINE data = create_test_data()NEWLINE assert_equal(NEWLINE data["time.dayofyear"][:10].variable, Variable(["time"], 1 + np.arange(10))NEWLINE )NEWLINE assert_equal(data["time.dayofyear"][0].variable, Variable([], 1))NEWLINENEWLINE def test_setitem(self):NEWLINE # assign a variableNEWLINE var = Variable(["dim1"], np.random.randn(8))NEWLINE data1 = create_test_data()NEWLINE data1["A"] = varNEWLINE data2 = data1.copy()NEWLINE data2["A"] = varNEWLINE assert_identical(data1, data2)NEWLINE # assign a dataset arrayNEWLINE dv = 2 * data2["A"]NEWLINE data1["B"] = dv.variableNEWLINE data2["B"] = dvNEWLINE assert_identical(data1, data2)NEWLINE # can't assign an ND array without dimensionsNEWLINE with raises_regex(ValueError, "without explicit dimension names"):NEWLINE data2["C"] = var.values.reshape(2, 4)NEWLINE # but can assign a 1D arrayNEWLINE data1["C"] = var.valuesNEWLINE data2["C"] = ("C", var.values)NEWLINE assert_identical(data1, data2)NEWLINE # can assign a scalarNEWLINE data1["scalar"] = 0NEWLINE data2["scalar"] = ([], 0)NEWLINE assert_identical(data1, data2)NEWLINE # can't use the same dimension name as a scalar varNEWLINE with raises_regex(ValueError, "already exists as a scalar"):NEWLINE data1["newvar"] = ("scalar", [3, 4, 5])NEWLINE # can't resize a used dimensionNEWLINE with raises_regex(ValueError, "arguments without labels"):NEWLINE data1["dim1"] = data1["dim1"][:5]NEWLINE # override an existing valueNEWLINE data1["A"] = 3 * data2["A"]NEWLINE assert_equal(data1["A"], 3 * data2["A"])NEWLINENEWLINE with pytest.raises(NotImplementedError):NEWLINE data1[{"x": 0}] = 0NEWLINENEWLINE def test_setitem_pandas(self):NEWLINENEWLINE ds = self.make_example_math_dataset()NEWLINE ds["x"] = np.arange(3)NEWLINE ds_copy = ds.copy()NEWLINE ds_copy["bar"] = ds["bar"].to_pandas()NEWLINENEWLINE assert_equal(ds, ds_copy)NEWLINENEWLINE def test_setitem_auto_align(self):NEWLINE ds = Dataset()NEWLINE ds["x"] = ("y", range(3))NEWLINE ds["y"] = 1 + np.arange(3)NEWLINE expected = Dataset({"x": ("y", range(3)), "y": 1 + np.arange(3)})NEWLINE assert_identical(ds, expected)NEWLINENEWLINE ds["y"] = DataArray(range(3), dims="y")NEWLINE expected = Dataset({"x": ("y", range(3))}, {"y": range(3)})NEWLINE assert_identical(ds, expected)NEWLINENEWLINE ds["x"] = DataArray([1, 2], coords=[("y", [0, 1])])NEWLINE expected = Dataset({"x": ("y", [1, 2, np.nan])}, {"y": range(3)})NEWLINE assert_identical(ds, expected)NEWLINENEWLINE ds["x"] = 42NEWLINE expected = Dataset({"x": 42, "y": range(3)})NEWLINE assert_identical(ds, expected)NEWLINENEWLINE ds["x"] = DataArray([4, 5, 6, 7], coords=[("y", [0, 1, 2, 3])])NEWLINE expected = Dataset({"x": ("y", [4, 5, 6])}, {"y": range(3)})NEWLINE assert_identical(ds, expected)NEWLINENEWLINE def test_setitem_dimension_override(self):NEWLINE # regression test for GH-3377NEWLINE ds = xr.Dataset({"x": [0, 1, 2]})NEWLINE ds["x"] = ds["x"][:2]NEWLINE expected = Dataset({"x": [0, 1]})NEWLINE assert_identical(ds, expected)NEWLINENEWLINE ds = xr.Dataset({"x": [0, 1, 2]})NEWLINE ds["x"] = np.array([0, 1])NEWLINE assert_identical(ds, expected)NEWLINENEWLINE ds = xr.Dataset({"x": [0, 1, 2]})NEWLINE ds.coords["x"] = [0, 1]NEWLINE assert_identical(ds, expected)NEWLINENEWLINE def test_setitem_with_coords(self):NEWLINE # Regression test for GH:2068NEWLINE ds = create_test_data()NEWLINENEWLINE other = DataArray(NEWLINE np.arange(10), dims="dim3", coords={"numbers": ("dim3", np.arange(10))}NEWLINE )NEWLINE expected = ds.copy()NEWLINE expected["var3"] = other.drop_vars("numbers")NEWLINE actual = ds.copy()NEWLINE actual["var3"] = otherNEWLINE assert_identical(expected, actual)NEWLINE assert "numbers" in other.coords # should not change otherNEWLINENEWLINE # with alignmentNEWLINE other = ds["var3"].isel(dim3=slice(1, -1))NEWLINE other["numbers"] = ("dim3", np.arange(8))NEWLINE actual = ds.copy()NEWLINE actual["var3"] = otherNEWLINE assert "numbers" in other.coords # should not change otherNEWLINE expected = ds.copy()NEWLINE expected["var3"] = ds["var3"].isel(dim3=slice(1, -1))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # with non-duplicate coordsNEWLINE other = ds["var3"].isel(dim3=slice(1, -1))NEWLINE other["numbers"] = ("dim3", np.arange(8))NEWLINE other["position"] = ("dim3", np.arange(8))NEWLINE actual = ds.copy()NEWLINE actual["var3"] = otherNEWLINE assert "position" in actualNEWLINE assert "position" in other.coordsNEWLINENEWLINE # assigning a coordinate-only dataarrayNEWLINE actual = ds.copy()NEWLINE other = actual["numbers"]NEWLINE other[0] = 10NEWLINE actual["numbers"] = otherNEWLINE assert actual["numbers"][0] == 10NEWLINENEWLINE # GH: 2099NEWLINE ds = Dataset(NEWLINE {"var": ("x", [1, 2, 3])},NEWLINE coords={"x": [0, 1, 2], "z1": ("x", [1, 2, 3]), "z2": ("x", [1, 2, 3])},NEWLINE )NEWLINE ds["var"] = ds["var"] * 2NEWLINE assert np.allclose(ds["var"], [2, 4, 6])NEWLINENEWLINE def test_setitem_align_new_indexes(self):NEWLINE ds = Dataset({"foo": ("x", [1, 2, 3])}, {"x": [0, 1, 2]})NEWLINE ds["bar"] = DataArray([2, 3, 4], [("x", [1, 2, 3])])NEWLINE expected = Dataset(NEWLINE {"foo": ("x", [1, 2, 3]), "bar": ("x", [np.nan, 2, 3])}, {"x": [0, 1, 2]}NEWLINE )NEWLINE assert_identical(ds, expected)NEWLINENEWLINE def test_assign(self):NEWLINE ds = Dataset()NEWLINE actual = ds.assign(x=[0, 1, 2], y=2)NEWLINE expected = Dataset({"x": [0, 1, 2], "y": 2})NEWLINE assert_identical(actual, expected)NEWLINE assert list(actual.variables) == ["x", "y"]NEWLINE assert_identical(ds, Dataset())NEWLINENEWLINE actual = actual.assign(y=lambda ds: ds.x ** 2)NEWLINE expected = Dataset({"y": ("x", [0, 1, 4]), "x": [0, 1, 2]})NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = actual.assign_coords(z=2)NEWLINE expected = Dataset({"y": ("x", [0, 1, 4])}, {"z": 2, "x": [0, 1, 2]})NEWLINE assert_identical(actual, expected)NEWLINENEWLINE ds = Dataset({"a": ("x", range(3))}, {"b": ("x", ["A"] * 2 + ["B"])})NEWLINE actual = ds.groupby("b").assign(c=lambda ds: 2 * ds.a)NEWLINE expected = ds.merge({"c": ("x", [0, 2, 4])})NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.groupby("b").assign(c=lambda ds: ds.a.sum())NEWLINE expected = ds.merge({"c": ("x", [1, 1, 2])})NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.groupby("b").assign_coords(c=lambda ds: ds.a.sum())NEWLINE expected = expected.set_coords("c")NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_assign_coords(self):NEWLINE ds = Dataset()NEWLINENEWLINE actual = ds.assign(x=[0, 1, 2], y=2)NEWLINE actual = actual.assign_coords(x=list("abc"))NEWLINE expected = Dataset({"x": list("abc"), "y": 2})NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.assign(x=[0, 1, 2], y=[2, 3])NEWLINE actual = actual.assign_coords({"y": [2.0, 3.0]})NEWLINE expected = ds.assign(x=[0, 1, 2], y=[2.0, 3.0])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_assign_attrs(self):NEWLINE expected = Dataset(attrs=dict(a=1, b=2))NEWLINE new = Dataset()NEWLINE actual = new.assign_attrs(a=1, b=2)NEWLINE assert_identical(actual, expected)NEWLINE assert new.attrs == {}NEWLINENEWLINE expected.attrs["c"] = 3NEWLINE new_actual = actual.assign_attrs({"c": 3})NEWLINE assert_identical(new_actual, expected)NEWLINE assert actual.attrs == dict(a=1, b=2)NEWLINENEWLINE def test_assign_multiindex_level(self):NEWLINE data = create_test_multiindex()NEWLINE with raises_regex(ValueError, "conflicting MultiIndex"):NEWLINE data.assign(level_1=range(4))NEWLINE data.assign_coords(level_1=range(4))NEWLINE # raise an Error when any level name is used as dimension GH:2299NEWLINE with pytest.raises(ValueError):NEWLINE data["y"] = ("level_1", [0, 1])NEWLINENEWLINE def test_merge_multiindex_level(self):NEWLINE data = create_test_multiindex()NEWLINE other = Dataset({"z": ("level_1", [0, 1])}) # conflict dimensionNEWLINE with pytest.raises(ValueError):NEWLINE data.merge(other)NEWLINE other = Dataset({"level_1": ("x", [0, 1])}) # conflict variable nameNEWLINE with pytest.raises(ValueError):NEWLINE data.merge(other)NEWLINENEWLINE def test_setitem_original_non_unique_index(self):NEWLINE # regression test for GH943NEWLINE original = Dataset({"data": ("x", np.arange(5))}, coords={"x": [0, 1, 2, 0, 1]})NEWLINE expected = Dataset({"data": ("x", np.arange(5))}, {"x": range(5)})NEWLINENEWLINE actual = original.copy()NEWLINE actual["x"] = list(range(5))NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = original.copy()NEWLINE actual["x"] = ("x", list(range(5)))NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = original.copy()NEWLINE actual.coords["x"] = list(range(5))NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_setitem_both_non_unique_index(self):NEWLINE # regression test for GH956NEWLINE names = ["joaquin", "manolo", "joaquin"]NEWLINE values = np.random.randint(0, 256, (3, 4, 4))NEWLINE array = DataArray(NEWLINE values, dims=["name", "row", "column"], coords=[names, range(4), range(4)]NEWLINE )NEWLINE expected = Dataset({"first": array, "second": array})NEWLINE actual = array.rename("first").to_dataset()NEWLINE actual["second"] = arrayNEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_setitem_multiindex_level(self):NEWLINE data = create_test_multiindex()NEWLINE with raises_regex(ValueError, "conflicting MultiIndex"):NEWLINE data["level_1"] = range(4)NEWLINENEWLINE def test_delitem(self):NEWLINE data = create_test_data()NEWLINE all_items = set(data.variables)NEWLINE assert set(data.variables) == all_itemsNEWLINE del data["var1"]NEWLINE assert set(data.variables) == all_items - {"var1"}NEWLINE del data["numbers"]NEWLINE assert set(data.variables) == all_items - {"var1", "numbers"}NEWLINE assert "numbers" not in data.coordsNEWLINENEWLINE expected = Dataset()NEWLINE actual = Dataset({"y": ("x", [1, 2])})NEWLINE del actual["y"]NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_squeeze(self):NEWLINE data = Dataset({"foo": (["x", "y", "z"], [[[1], [2]]])})NEWLINE for args in [[], [["x"]], [["x", "z"]]]:NEWLINENEWLINE def get_args(v):NEWLINE return [set(args[0]) & set(v.dims)] if args else []NEWLINENEWLINE expected = Dataset(NEWLINE {k: v.squeeze(*get_args(v)) for k, v in data.variables.items()}NEWLINE )NEWLINE expected = expected.set_coords(data.coords)NEWLINE assert_identical(expected, data.squeeze(*args))NEWLINE # invalid squeezeNEWLINE with raises_regex(ValueError, "cannot select a dimension"):NEWLINE data.squeeze("y")NEWLINENEWLINE def test_squeeze_drop(self):NEWLINE data = Dataset({"foo": ("x", [1])}, {"x": [0]})NEWLINE expected = Dataset({"foo": 1})NEWLINE selected = data.squeeze(drop=True)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE expected = Dataset({"foo": 1}, {"x": 0})NEWLINE selected = data.squeeze(drop=False)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE data = Dataset({"foo": (("x", "y"), [[1]])}, {"x": [0], "y": [0]})NEWLINE expected = Dataset({"foo": 1})NEWLINE selected = data.squeeze(drop=True)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE expected = Dataset({"foo": ("x", [1])}, {"x": [0]})NEWLINE selected = data.squeeze(dim="y", drop=True)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE data = Dataset({"foo": (("x",), [])}, {"x": []})NEWLINE selected = data.squeeze(drop=True)NEWLINE assert_identical(data, selected)NEWLINENEWLINE def test_groupby(self):NEWLINE data = Dataset(NEWLINE {"z": (["x", "y"], np.random.randn(3, 5))},NEWLINE {"x": ("x", list("abc")), "c": ("x", [0, 1, 0]), "y": range(5)},NEWLINE )NEWLINE groupby = data.groupby("x")NEWLINE assert len(groupby) == 3NEWLINE expected_groups = {"a": 0, "b": 1, "c": 2}NEWLINE assert groupby.groups == expected_groupsNEWLINE expected_items = [NEWLINE ("a", data.isel(x=0)),NEWLINE ("b", data.isel(x=1)),NEWLINE ("c", data.isel(x=2)),NEWLINE ]NEWLINE for actual, expected in zip(groupby, expected_items):NEWLINE assert actual[0] == expected[0]NEWLINE assert_equal(actual[1], expected[1])NEWLINENEWLINE def identity(x):NEWLINE return xNEWLINENEWLINE for k in ["x", "c", "y"]:NEWLINE actual = data.groupby(k, squeeze=False).map(identity)NEWLINE assert_equal(data, actual)NEWLINENEWLINE def test_groupby_returns_new_type(self):NEWLINE data = Dataset({"z": (["x", "y"], np.random.randn(3, 5))})NEWLINENEWLINE actual = data.groupby("x").map(lambda ds: ds["z"])NEWLINE expected = data["z"]NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = data["z"].groupby("x").map(lambda x: x.to_dataset())NEWLINE expected = dataNEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_groupby_iter(self):NEWLINE data = create_test_data()NEWLINE for n, (t, sub) in enumerate(list(data.groupby("dim1"))[:3]):NEWLINE assert data["dim1"][n] == tNEWLINE assert_equal(data["var1"][n], sub["var1"])NEWLINE assert_equal(data["var2"][n], sub["var2"])NEWLINE assert_equal(data["var3"][:, n], sub["var3"])NEWLINENEWLINE def test_groupby_errors(self):NEWLINE data = create_test_data()NEWLINE with raises_regex(TypeError, "`group` must be"):NEWLINE data.groupby(np.arange(10))NEWLINE with raises_regex(ValueError, "length does not match"):NEWLINE data.groupby(data["dim1"][:3])NEWLINE with raises_regex(TypeError, "`group` must be"):NEWLINE data.groupby(data.coords["dim1"].to_index())NEWLINENEWLINE def test_groupby_reduce(self):NEWLINE data = Dataset(NEWLINE {NEWLINE "xy": (["x", "y"], np.random.randn(3, 4)),NEWLINE "xonly": ("x", np.random.randn(3)),NEWLINE "yonly": ("y", np.random.randn(4)),NEWLINE "letters": ("y", ["a", "a", "b", "b"]),NEWLINE }NEWLINE )NEWLINENEWLINE expected = data.mean("y")NEWLINE expected["yonly"] = expected["yonly"].variable.set_dims({"x": 3})NEWLINE actual = data.groupby("x").mean(...)NEWLINE assert_allclose(expected, actual)NEWLINENEWLINE actual = data.groupby("x").mean("y")NEWLINE assert_allclose(expected, actual)NEWLINENEWLINE letters = data["letters"]NEWLINE expected = Dataset(NEWLINE {NEWLINE "xy": data["xy"].groupby(letters).mean(...),NEWLINE "xonly": (data["xonly"].mean().variable.set_dims({"letters": 2})),NEWLINE "yonly": data["yonly"].groupby(letters).mean(),NEWLINE }NEWLINE )NEWLINE actual = data.groupby("letters").mean(...)NEWLINE assert_allclose(expected, actual)NEWLINENEWLINE def test_groupby_math(self):NEWLINE def reorder_dims(x):NEWLINE return x.transpose("dim1", "dim2", "dim3", "time")NEWLINENEWLINE ds = create_test_data()NEWLINE ds["dim1"] = ds["dim1"]NEWLINE for squeeze in [True, False]:NEWLINE grouped = ds.groupby("dim1", squeeze=squeeze)NEWLINENEWLINE expected = reorder_dims(ds + ds.coords["dim1"])NEWLINE actual = grouped + ds.coords["dim1"]NEWLINE assert_identical(expected, reorder_dims(actual))NEWLINENEWLINE actual = ds.coords["dim1"] + groupedNEWLINE assert_identical(expected, reorder_dims(actual))NEWLINENEWLINE ds2 = 2 * dsNEWLINE expected = reorder_dims(ds + ds2)NEWLINE actual = grouped + ds2NEWLINE assert_identical(expected, reorder_dims(actual))NEWLINENEWLINE actual = ds2 + groupedNEWLINE assert_identical(expected, reorder_dims(actual))NEWLINENEWLINE grouped = ds.groupby("numbers")NEWLINE zeros = DataArray([0, 0, 0, 0], [("numbers", range(4))])NEWLINE expected = (ds + Variable("dim3", np.zeros(10))).transpose(NEWLINE "dim3", "dim1", "dim2", "time"NEWLINE )NEWLINE actual = grouped + zerosNEWLINE assert_equal(expected, actual)NEWLINENEWLINE actual = zeros + groupedNEWLINE assert_equal(expected, actual)NEWLINENEWLINE with raises_regex(ValueError, "incompat.* grouped binary"):NEWLINE grouped + dsNEWLINE with raises_regex(ValueError, "incompat.* grouped binary"):NEWLINE ds + groupedNEWLINE with raises_regex(TypeError, "only support binary ops"):NEWLINE grouped + 1NEWLINE with raises_regex(TypeError, "only support binary ops"):NEWLINE grouped + groupedNEWLINE with raises_regex(TypeError, "in-place operations"):NEWLINE ds += groupedNEWLINENEWLINE ds = Dataset(NEWLINE {NEWLINE "x": ("time", np.arange(100)),NEWLINE "time": pd.date_range("2000-01-01", periods=100),NEWLINE }NEWLINE )NEWLINE with raises_regex(ValueError, "incompat.* grouped binary"):NEWLINE ds + ds.groupby("time.month")NEWLINENEWLINE def test_groupby_math_virtual(self):NEWLINE ds = Dataset(NEWLINE {"x": ("t", [1, 2, 3])}, {"t": pd.date_range("20100101", periods=3)}NEWLINE )NEWLINE grouped = ds.groupby("t.day")NEWLINE actual = grouped - grouped.mean(...)NEWLINE expected = Dataset({"x": ("t", [0, 0, 0])}, ds[["t", "t.day"]])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_groupby_nan(self):NEWLINE # nan should be excluded from groupbyNEWLINE ds = Dataset({"foo": ("x", [1, 2, 3, 4])}, {"bar": ("x", [1, 1, 2, np.nan])})NEWLINE actual = ds.groupby("bar").mean(...)NEWLINE expected = Dataset({"foo": ("bar", [1.5, 3]), "bar": [1, 2]})NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_groupby_order(self):NEWLINE # groupby should preserve variables orderNEWLINE ds = Dataset()NEWLINE for vn in ["a", "b", "c"]:NEWLINE ds[vn] = DataArray(np.arange(10), dims=["t"])NEWLINE data_vars_ref = list(ds.data_vars.keys())NEWLINE ds = ds.groupby("t").mean(...)NEWLINE data_vars = list(ds.data_vars.keys())NEWLINE assert data_vars == data_vars_refNEWLINE # coords are now at the end of the list, so the test below failsNEWLINE # all_vars = list(ds.variables.keys())NEWLINE # all_vars_ref = list(ds.variables.keys())NEWLINE # self.assertEqual(all_vars, all_vars_ref)NEWLINENEWLINE def test_resample_and_first(self):NEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=10)NEWLINE ds = Dataset(NEWLINE {NEWLINE "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)),NEWLINE "bar": ("time", np.random.randn(10), {"meta": "data"}),NEWLINE "time": times,NEWLINE }NEWLINE )NEWLINENEWLINE actual = ds.resample(time="1D").first(keep_attrs=True)NEWLINE expected = ds.isel(time=[0, 4, 8])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # upsamplingNEWLINE expected_time = pd.date_range("2000-01-01", freq="3H", periods=19)NEWLINE expected = ds.reindex(time=expected_time)NEWLINE actual = ds.resample(time="3H")NEWLINE for how in ["mean", "sum", "first", "last"]:NEWLINE method = getattr(actual, how)NEWLINE result = method()NEWLINE assert_equal(expected, result)NEWLINE for method in [np.mean]:NEWLINE result = actual.reduce(method)NEWLINE assert_equal(expected, result)NEWLINENEWLINE def test_resample_min_count(self):NEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=10)NEWLINE ds = Dataset(NEWLINE {NEWLINE "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)),NEWLINE "bar": ("time", np.random.randn(10), {"meta": "data"}),NEWLINE "time": times,NEWLINE }NEWLINE )NEWLINE # inject nanNEWLINE ds["foo"] = xr.where(ds["foo"] > 2.0, np.nan, ds["foo"])NEWLINENEWLINE actual = ds.resample(time="1D").sum(min_count=1)NEWLINE expected = xr.concat(NEWLINE [NEWLINE ds.isel(time=slice(i * 4, (i + 1) * 4)).sum("time", min_count=1)NEWLINE for i in range(3)NEWLINE ],NEWLINE dim=actual["time"],NEWLINE )NEWLINE assert_equal(expected, actual)NEWLINENEWLINE def test_resample_by_mean_with_keep_attrs(self):NEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=10)NEWLINE ds = Dataset(NEWLINE {NEWLINE "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)),NEWLINE "bar": ("time", np.random.randn(10), {"meta": "data"}),NEWLINE "time": times,NEWLINE }NEWLINE )NEWLINE ds.attrs["dsmeta"] = "dsdata"NEWLINENEWLINE resampled_ds = ds.resample(time="1D").mean(keep_attrs=True)NEWLINE actual = resampled_ds["bar"].attrsNEWLINE expected = ds["bar"].attrsNEWLINE assert expected == actualNEWLINENEWLINE actual = resampled_ds.attrsNEWLINE expected = ds.attrsNEWLINE assert expected == actualNEWLINENEWLINE def test_resample_loffset(self):NEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=10)NEWLINE ds = Dataset(NEWLINE {NEWLINE "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)),NEWLINE "bar": ("time", np.random.randn(10), {"meta": "data"}),NEWLINE "time": times,NEWLINE }NEWLINE )NEWLINE ds.attrs["dsmeta"] = "dsdata"NEWLINENEWLINE actual = ds.resample(time="24H", loffset="-12H").mean("time").timeNEWLINE expected = xr.DataArray(NEWLINE ds.bar.to_series().resample("24H", loffset="-12H").mean()NEWLINE ).timeNEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_resample_by_mean_discarding_attrs(self):NEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=10)NEWLINE ds = Dataset(NEWLINE {NEWLINE "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)),NEWLINE "bar": ("time", np.random.randn(10), {"meta": "data"}),NEWLINE "time": times,NEWLINE }NEWLINE )NEWLINE ds.attrs["dsmeta"] = "dsdata"NEWLINENEWLINE resampled_ds = ds.resample(time="1D").mean(keep_attrs=False)NEWLINENEWLINE assert resampled_ds["bar"].attrs == {}NEWLINE assert resampled_ds.attrs == {}NEWLINENEWLINE def test_resample_by_last_discarding_attrs(self):NEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=10)NEWLINE ds = Dataset(NEWLINE {NEWLINE "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)),NEWLINE "bar": ("time", np.random.randn(10), {"meta": "data"}),NEWLINE "time": times,NEWLINE }NEWLINE )NEWLINE ds.attrs["dsmeta"] = "dsdata"NEWLINENEWLINE resampled_ds = ds.resample(time="1D").last(keep_attrs=False)NEWLINENEWLINE assert resampled_ds["bar"].attrs == {}NEWLINE assert resampled_ds.attrs == {}NEWLINENEWLINE @requires_scipyNEWLINE def test_resample_drop_nondim_coords(self):NEWLINE xs = np.arange(6)NEWLINE ys = np.arange(3)NEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=5)NEWLINE data = np.tile(np.arange(5), (6, 3, 1))NEWLINE xx, yy = np.meshgrid(xs * 5, ys * 2.5)NEWLINE tt = np.arange(len(times), dtype=int)NEWLINE array = DataArray(data, {"time": times, "x": xs, "y": ys}, ("x", "y", "time"))NEWLINE xcoord = DataArray(xx.T, {"x": xs, "y": ys}, ("x", "y"))NEWLINE ycoord = DataArray(yy.T, {"x": xs, "y": ys}, ("x", "y"))NEWLINE tcoord = DataArray(tt, {"time": times}, ("time",))NEWLINE ds = Dataset({"data": array, "xc": xcoord, "yc": ycoord, "tc": tcoord})NEWLINE ds = ds.set_coords(["xc", "yc", "tc"])NEWLINENEWLINE # Re-sampleNEWLINE actual = ds.resample(time="12H").mean("time")NEWLINE assert "tc" not in actual.coordsNEWLINENEWLINE # Up-sample - fillingNEWLINE actual = ds.resample(time="1H").ffill()NEWLINE assert "tc" not in actual.coordsNEWLINENEWLINE # Up-sample - interpolationNEWLINE actual = ds.resample(time="1H").interpolate("linear")NEWLINE assert "tc" not in actual.coordsNEWLINENEWLINE def test_resample_old_api(self):NEWLINENEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=10)NEWLINE ds = Dataset(NEWLINE {NEWLINE "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)),NEWLINE "bar": ("time", np.random.randn(10), {"meta": "data"}),NEWLINE "time": times,NEWLINE }NEWLINE )NEWLINENEWLINE with raises_regex(TypeError, r"resample\(\) no longer supports"):NEWLINE ds.resample("1D", "time")NEWLINENEWLINE with raises_regex(TypeError, r"resample\(\) no longer supports"):NEWLINE ds.resample("1D", dim="time", how="mean")NEWLINENEWLINE with raises_regex(TypeError, r"resample\(\) no longer supports"):NEWLINE ds.resample("1D", dim="time")NEWLINENEWLINE def test_resample_ds_da_are_the_same(self):NEWLINE time = pd.date_range("2000-01-01", freq="6H", periods=365 * 4)NEWLINE ds = xr.Dataset(NEWLINE {NEWLINE "foo": (("time", "x"), np.random.randn(365 * 4, 5)),NEWLINE "time": time,NEWLINE "x": np.arange(5),NEWLINE }NEWLINE )NEWLINE assert_identical(NEWLINE ds.resample(time="M").mean()["foo"], ds.foo.resample(time="M").mean()NEWLINE )NEWLINENEWLINE def test_ds_resample_apply_func_args(self):NEWLINE def func(arg1, arg2, arg3=0.0):NEWLINE return arg1.mean("time") + arg2 + arg3NEWLINENEWLINE times = pd.date_range("2000", freq="D", periods=3)NEWLINE ds = xr.Dataset({"foo": ("time", [1.0, 1.0, 1.0]), "time": times})NEWLINE expected = xr.Dataset({"foo": ("time", [3.0, 3.0, 3.0]), "time": times})NEWLINE actual = ds.resample(time="D").map(func, args=(1.0,), arg3=1.0)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_to_array(self):NEWLINE ds = Dataset(NEWLINE {"a": 1, "b": ("x", [1, 2, 3])},NEWLINE coords={"c": 42},NEWLINE attrs={"Conventions": "None"},NEWLINE )NEWLINE data = [[1, 1, 1], [1, 2, 3]]NEWLINE coords = {"c": 42, "variable": ["a", "b"]}NEWLINE dims = ("variable", "x")NEWLINE expected = DataArray(data, coords, dims, attrs=ds.attrs)NEWLINE actual = ds.to_array()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.to_array("abc", name="foo")NEWLINE expected = expected.rename({"variable": "abc"}).rename("foo")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_to_and_from_dataframe(self):NEWLINE x = np.random.randn(10)NEWLINE y = np.random.randn(10)NEWLINE t = list("abcdefghij")NEWLINE ds = Dataset({"a": ("t", x), "b": ("t", y), "t": ("t", t)})NEWLINE expected = pd.DataFrame(NEWLINE np.array([x, y]).T, columns=["a", "b"], index=pd.Index(t, name="t")NEWLINE )NEWLINE actual = ds.to_dataframe()NEWLINE # use the .equals method to check all DataFrame metadataNEWLINE assert expected.equals(actual), (expected, actual)NEWLINENEWLINE # verify coords are includedNEWLINE actual = ds.set_coords("b").to_dataframe()NEWLINE assert expected.equals(actual), (expected, actual)NEWLINENEWLINE # check roundtripNEWLINE assert_identical(ds, Dataset.from_dataframe(actual))NEWLINENEWLINE # test a case with a MultiIndexNEWLINE w = np.random.randn(2, 3)NEWLINE ds = Dataset({"w": (("x", "y"), w)})NEWLINE ds["y"] = ("y", list("abc"))NEWLINE exp_index = pd.MultiIndex.from_arrays(NEWLINE [[0, 0, 0, 1, 1, 1], ["a", "b", "c", "a", "b", "c"]], names=["x", "y"]NEWLINE )NEWLINE expected = pd.DataFrame(w.reshape(-1), columns=["w"], index=exp_index)NEWLINE actual = ds.to_dataframe()NEWLINE assert expected.equals(actual)NEWLINENEWLINE # check roundtripNEWLINE assert_identical(ds.assign_coords(x=[0, 1]), Dataset.from_dataframe(actual))NEWLINENEWLINE # check pathological casesNEWLINE df = pd.DataFrame([1])NEWLINE actual = Dataset.from_dataframe(df)NEWLINE expected = Dataset({0: ("index", [1])}, {"index": [0]})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE df = pd.DataFrame()NEWLINE actual = Dataset.from_dataframe(df)NEWLINE expected = Dataset(coords={"index": []})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # GH697NEWLINE df = pd.DataFrame({"A": []})NEWLINE actual = Dataset.from_dataframe(df)NEWLINE expected = Dataset({"A": DataArray([], dims=("index",))}, {"index": []})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # regression test for GH278NEWLINE # use int64 to ensure consistent results for the pandas .equals methodNEWLINE # on windows (which requires the same dtype)NEWLINE ds = Dataset({"x": pd.Index(["bar"]), "a": ("y", np.array([1], "int64"))}).isel(NEWLINE x=0NEWLINE )NEWLINE # use .loc to ensure consistent results on Python 3NEWLINE actual = ds.to_dataframe().loc[:, ["a", "x"]]NEWLINE expected = pd.DataFrame(NEWLINE [[1, "bar"]], index=pd.Index([0], name="y"), columns=["a", "x"]NEWLINE )NEWLINE assert expected.equals(actual), (expected, actual)NEWLINENEWLINE ds = Dataset({"x": np.array([0], "int64"), "y": np.array([1], "int64")})NEWLINE actual = ds.to_dataframe()NEWLINE idx = pd.MultiIndex.from_arrays([[0], [1]], names=["x", "y"])NEWLINE expected = pd.DataFrame([[]], index=idx)NEWLINE assert expected.equals(actual), (expected, actual)NEWLINENEWLINE @requires_sparseNEWLINE def test_from_dataframe_sparse(self):NEWLINE import sparseNEWLINENEWLINE df_base = pd.DataFrame(NEWLINE {"x": range(10), "y": list("abcdefghij"), "z": np.arange(0, 100, 10)}NEWLINE )NEWLINENEWLINE ds_sparse = Dataset.from_dataframe(df_base.set_index("x"), sparse=True)NEWLINE ds_dense = Dataset.from_dataframe(df_base.set_index("x"), sparse=False)NEWLINE assert isinstance(ds_sparse["y"].data, sparse.COO)NEWLINE assert isinstance(ds_sparse["z"].data, sparse.COO)NEWLINE ds_sparse["y"].data = ds_sparse["y"].data.todense()NEWLINE ds_sparse["z"].data = ds_sparse["z"].data.todense()NEWLINE assert_identical(ds_dense, ds_sparse)NEWLINENEWLINE ds_sparse = Dataset.from_dataframe(df_base.set_index(["x", "y"]), sparse=True)NEWLINE ds_dense = Dataset.from_dataframe(df_base.set_index(["x", "y"]), sparse=False)NEWLINE assert isinstance(ds_sparse["z"].data, sparse.COO)NEWLINE ds_sparse["z"].data = ds_sparse["z"].data.todense()NEWLINE assert_identical(ds_dense, ds_sparse)NEWLINENEWLINE def test_to_and_from_empty_dataframe(self):NEWLINE # GH697NEWLINE expected = pd.DataFrame({"foo": []})NEWLINE ds = Dataset.from_dataframe(expected)NEWLINE assert len(ds["foo"]) == 0NEWLINE actual = ds.to_dataframe()NEWLINE assert len(actual) == 0NEWLINE assert expected.equals(actual)NEWLINENEWLINE def test_from_dataframe_non_unique_columns(self):NEWLINE # regression test for GH449NEWLINE df = pd.DataFrame(np.zeros((2, 2)))NEWLINE df.columns = ["foo", "foo"]NEWLINE with raises_regex(ValueError, "non-unique columns"):NEWLINE Dataset.from_dataframe(df)NEWLINENEWLINE def test_convert_dataframe_with_many_types_and_multiindex(self):NEWLINE # regression test for GH737NEWLINE df = pd.DataFrame(NEWLINE {NEWLINE "a": list("abc"),NEWLINE "b": list(range(1, 4)),NEWLINE "c": np.arange(3, 6).astype("u1"),NEWLINE "d": np.arange(4.0, 7.0, dtype="float64"),NEWLINE "e": [True, False, True],NEWLINE "f": pd.Categorical(list("abc")),NEWLINE "g": pd.date_range("20130101", periods=3),NEWLINE "h": pd.date_range("20130101", periods=3, tz="US/Eastern"),NEWLINE }NEWLINE )NEWLINE df.index = pd.MultiIndex.from_product([["a"], range(3)], names=["one", "two"])NEWLINE roundtripped = Dataset.from_dataframe(df).to_dataframe()NEWLINE # we can't do perfectly, but we should be at least as faithful asNEWLINE # np.asarrayNEWLINE expected = df.apply(np.asarray)NEWLINE assert roundtripped.equals(expected)NEWLINENEWLINE def test_to_and_from_dict(self):NEWLINE # NEWLINE # Dimensions: (t: 10)NEWLINE # Coordinates:NEWLINE # * t (t) U1"NEWLINE expected_no_data["coords"]["t"].update({"dtype": endiantype, "shape": (10,)})NEWLINE expected_no_data["data_vars"]["a"].update({"dtype": "float64", "shape": (10,)})NEWLINE expected_no_data["data_vars"]["b"].update({"dtype": "float64", "shape": (10,)})NEWLINE actual_no_data = ds.to_dict(data=False)NEWLINE assert expected_no_data == actual_no_dataNEWLINENEWLINE # verify coords are included roundtripNEWLINE expected_ds = ds.set_coords("b")NEWLINE actual = Dataset.from_dict(expected_ds.to_dict())NEWLINENEWLINE assert_identical(expected_ds, actual)NEWLINENEWLINE # test some incomplete dicts:NEWLINE # this one has no attrs field, the dims are strings, and x, y areNEWLINE # np.arraysNEWLINENEWLINE d = {NEWLINE "coords": {"t": {"dims": "t", "data": t}},NEWLINE "dims": "t",NEWLINE "data_vars": {"a": {"dims": "t", "data": x}, "b": {"dims": "t", "data": y}},NEWLINE }NEWLINE assert_identical(ds, Dataset.from_dict(d))NEWLINENEWLINE # this is kind of a flattened version with no coords, or data_varsNEWLINE d = {NEWLINE "a": {"dims": "t", "data": x},NEWLINE "t": {"data": t, "dims": "t"},NEWLINE "b": {"dims": "t", "data": y},NEWLINE }NEWLINE assert_identical(ds, Dataset.from_dict(d))NEWLINENEWLINE # this one is missing some necessary informationNEWLINE d = {NEWLINE "a": {"data": x},NEWLINE "t": {"data": t, "dims": "t"},NEWLINE "b": {"dims": "t", "data": y},NEWLINE }NEWLINE with raises_regex(ValueError, "cannot convert dict " "without the key 'dims'"):NEWLINE Dataset.from_dict(d)NEWLINENEWLINE def test_to_and_from_dict_with_time_dim(self):NEWLINE x = np.random.randn(10, 3)NEWLINE y = np.random.randn(10, 3)NEWLINE t = pd.date_range("20130101", periods=10)NEWLINE lat = [77.7, 83.2, 76]NEWLINE ds = Dataset(NEWLINE {NEWLINE "a": (["t", "lat"], x),NEWLINE "b": (["t", "lat"], y),NEWLINE "t": ("t", t),NEWLINE "lat": ("lat", lat),NEWLINE }NEWLINE )NEWLINE roundtripped = Dataset.from_dict(ds.to_dict())NEWLINE assert_identical(ds, roundtripped)NEWLINENEWLINE def test_to_and_from_dict_with_nan_nat(self):NEWLINE x = np.random.randn(10, 3)NEWLINE y = np.random.randn(10, 3)NEWLINE y[2] = np.nanNEWLINE t = pd.Series(pd.date_range("20130101", periods=10))NEWLINE t[2] = np.nanNEWLINENEWLINE lat = [77.7, 83.2, 76]NEWLINE ds = Dataset(NEWLINE {NEWLINE "a": (["t", "lat"], x),NEWLINE "b": (["t", "lat"], y),NEWLINE "t": ("t", t),NEWLINE "lat": ("lat", lat),NEWLINE }NEWLINE )NEWLINE roundtripped = Dataset.from_dict(ds.to_dict())NEWLINE assert_identical(ds, roundtripped)NEWLINENEWLINE def test_to_dict_with_numpy_attrs(self):NEWLINE # this doesn't need to roundtripNEWLINE x = np.random.randn(10)NEWLINE y = np.random.randn(10)NEWLINE t = list("abcdefghij")NEWLINE attrs = {NEWLINE "created": np.float64(1998),NEWLINE "coords": np.array([37, -110.1, 100]),NEWLINE "maintainer": "bar",NEWLINE }NEWLINE ds = Dataset({"a": ("t", x, attrs), "b": ("t", y, attrs), "t": ("t", t)})NEWLINE expected_attrs = {NEWLINE "created": attrs["created"].item(),NEWLINE "coords": attrs["coords"].tolist(),NEWLINE "maintainer": "bar",NEWLINE }NEWLINE actual = ds.to_dict()NEWLINENEWLINE # check that they are identicalNEWLINE assert expected_attrs == actual["data_vars"]["a"]["attrs"]NEWLINENEWLINE def test_pickle(self):NEWLINE data = create_test_data()NEWLINE roundtripped = pickle.loads(pickle.dumps(data))NEWLINE assert_identical(data, roundtripped)NEWLINE # regression test for #167:NEWLINE assert data.dims == roundtripped.dimsNEWLINENEWLINE def test_lazy_load(self):NEWLINE store = InaccessibleVariableDataStore()NEWLINE create_test_data().dump_to_store(store)NEWLINENEWLINE for decode_cf in [True, False]:NEWLINE ds = open_dataset(store, decode_cf=decode_cf)NEWLINE with pytest.raises(UnexpectedDataAccess):NEWLINE ds.load()NEWLINE with pytest.raises(UnexpectedDataAccess):NEWLINE ds["var1"].valuesNEWLINENEWLINE # these should not raise UnexpectedDataAccess:NEWLINE ds.isel(time=10)NEWLINE ds.isel(time=slice(10), dim1=[0]).isel(dim1=0, dim2=-1)NEWLINENEWLINE def test_dropna(self):NEWLINE x = np.random.randn(4, 4)NEWLINE x[::2, 0] = np.nanNEWLINE y = np.random.randn(4)NEWLINE y[-1] = np.nanNEWLINE ds = Dataset({"foo": (("a", "b"), x), "bar": (("b", y))})NEWLINENEWLINE expected = ds.isel(a=slice(1, None, 2))NEWLINE actual = ds.dropna("a")NEWLINE assert_identical(actual, expected)NEWLINENEWLINE expected = ds.isel(b=slice(1, 3))NEWLINE actual = ds.dropna("b")NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.dropna("b", subset=["foo", "bar"])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE expected = ds.isel(b=slice(1, None))NEWLINE actual = ds.dropna("b", subset=["foo"])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE expected = ds.isel(b=slice(3))NEWLINE actual = ds.dropna("b", subset=["bar"])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.dropna("a", subset=[])NEWLINE assert_identical(actual, ds)NEWLINENEWLINE actual = ds.dropna("a", subset=["bar"])NEWLINE assert_identical(actual, ds)NEWLINENEWLINE actual = ds.dropna("a", how="all")NEWLINE assert_identical(actual, ds)NEWLINENEWLINE actual = ds.dropna("b", how="all", subset=["bar"])NEWLINE expected = ds.isel(b=[0, 1, 2])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.dropna("b", thresh=1, subset=["bar"])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.dropna("b", thresh=2)NEWLINE assert_identical(actual, ds)NEWLINENEWLINE actual = ds.dropna("b", thresh=4)NEWLINE expected = ds.isel(b=[1, 2, 3])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.dropna("a", thresh=3)NEWLINE expected = ds.isel(a=[1, 3])NEWLINE assert_identical(actual, ds)NEWLINENEWLINE with raises_regex(ValueError, "a single dataset dimension"):NEWLINE ds.dropna("foo")NEWLINE with raises_regex(ValueError, "invalid how"):NEWLINE ds.dropna("a", how="somehow")NEWLINE with raises_regex(TypeError, "must specify how or thresh"):NEWLINE ds.dropna("a", how=None)NEWLINENEWLINE def test_fillna(self):NEWLINE ds = Dataset({"a": ("x", [np.nan, 1, np.nan, 3])}, {"x": [0, 1, 2, 3]})NEWLINENEWLINE # fill with -1NEWLINE actual = ds.fillna(-1)NEWLINE expected = Dataset({"a": ("x", [-1, 1, -1, 3])}, {"x": [0, 1, 2, 3]})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.fillna({"a": -1})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE other = Dataset({"a": -1})NEWLINE actual = ds.fillna(other)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.fillna({"a": other.a})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # fill with range(4)NEWLINE b = DataArray(range(4), coords=[("x", range(4))])NEWLINE actual = ds.fillna(b)NEWLINE expected = b.rename("a").to_dataset()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.fillna(expected)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.fillna(range(4))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.fillna(b[:3])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # okay to only include some data variablesNEWLINE ds["b"] = np.nanNEWLINE actual = ds.fillna({"a": -1})NEWLINE expected = Dataset(NEWLINE {"a": ("x", [-1, 1, -1, 3]), "b": np.nan}, {"x": [0, 1, 2, 3]}NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # but new data variables is not okayNEWLINE with raises_regex(ValueError, "must be contained"):NEWLINE ds.fillna({"x": 0})NEWLINENEWLINE # empty argument should be OKNEWLINE result = ds.fillna({})NEWLINE assert_identical(ds, result)NEWLINENEWLINE result = ds.fillna(Dataset(coords={"c": 42}))NEWLINE expected = ds.assign_coords(c=42)NEWLINE assert_identical(expected, result)NEWLINENEWLINE # groupbyNEWLINE expected = Dataset({"a": ("x", range(4))}, {"x": [0, 1, 2, 3]})NEWLINE for target in [ds, expected]:NEWLINE target.coords["b"] = ("x", [0, 0, 1, 1])NEWLINE actual = ds.groupby("b").fillna(DataArray([0, 2], dims="b"))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.groupby("b").fillna(Dataset({"a": ("b", [0, 2])}))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # attrs with groupbyNEWLINE ds.attrs["attr"] = "ds"NEWLINE ds.a.attrs["attr"] = "da"NEWLINE actual = ds.groupby("b").fillna(Dataset({"a": ("b", [0, 2])}))NEWLINE assert actual.attrs == ds.attrsNEWLINE assert actual.a.name == "a"NEWLINE assert actual.a.attrs == ds.a.attrsNEWLINENEWLINE da = DataArray(range(5), name="a", attrs={"attr": "da"})NEWLINE actual = da.fillna(1)NEWLINE assert actual.name == "a"NEWLINE assert actual.attrs == da.attrsNEWLINENEWLINE ds = Dataset({"a": da}, attrs={"attr": "ds"})NEWLINE actual = ds.fillna({"a": 1})NEWLINE assert actual.attrs == ds.attrsNEWLINE assert actual.a.name == "a"NEWLINE assert actual.a.attrs == ds.a.attrsNEWLINENEWLINE def test_where(self):NEWLINE ds = Dataset({"a": ("x", range(5))})NEWLINE expected = Dataset({"a": ("x", [np.nan, np.nan, 2, 3, 4])})NEWLINE actual = ds.where(ds > 1)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.where(ds.a > 1)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.where(ds.a.values > 1)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.where(True)NEWLINE assert_identical(ds, actual)NEWLINENEWLINE expected = ds.copy(deep=True)NEWLINE expected["a"].values = [np.nan] * 5NEWLINE actual = ds.where(False)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # 2dNEWLINE ds = Dataset({"a": (("x", "y"), [[0, 1], [2, 3]])})NEWLINE expected = Dataset({"a": (("x", "y"), [[np.nan, 1], [2, 3]])})NEWLINE actual = ds.where(ds > 0)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # groupbyNEWLINE ds = Dataset({"a": ("x", range(5))}, {"c": ("x", [0, 0, 1, 1, 1])})NEWLINE cond = Dataset({"a": ("c", [True, False])})NEWLINE expected = ds.copy(deep=True)NEWLINE expected["a"].values = [0, 1] + [np.nan] * 3NEWLINE actual = ds.groupby("c").where(cond)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # attrs with groupbyNEWLINE ds.attrs["attr"] = "ds"NEWLINE ds.a.attrs["attr"] = "da"NEWLINE actual = ds.groupby("c").where(cond)NEWLINE assert actual.attrs == ds.attrsNEWLINE assert actual.a.name == "a"NEWLINE assert actual.a.attrs == ds.a.attrsNEWLINENEWLINE # attrsNEWLINE da = DataArray(range(5), name="a", attrs={"attr": "da"})NEWLINE actual = da.where(da.values > 1)NEWLINE assert actual.name == "a"NEWLINE assert actual.attrs == da.attrsNEWLINENEWLINE ds = Dataset({"a": da}, attrs={"attr": "ds"})NEWLINE actual = ds.where(ds > 0)NEWLINE assert actual.attrs == ds.attrsNEWLINE assert actual.a.name == "a"NEWLINE assert actual.a.attrs == ds.a.attrsNEWLINENEWLINE def test_where_other(self):NEWLINE ds = Dataset({"a": ("x", range(5))}, {"x": range(5)})NEWLINE expected = Dataset({"a": ("x", [-1, -1, 2, 3, 4])}, {"x": range(5)})NEWLINE actual = ds.where(ds > 1, -1)NEWLINE assert_equal(expected, actual)NEWLINE assert actual.a.dtype == intNEWLINENEWLINE with raises_regex(ValueError, "cannot set"):NEWLINE ds.where(ds > 1, other=0, drop=True)NEWLINENEWLINE with raises_regex(ValueError, "indexes .* are not equal"):NEWLINE ds.where(ds > 1, ds.isel(x=slice(3)))NEWLINENEWLINE with raises_regex(ValueError, "exact match required"):NEWLINE ds.where(ds > 1, ds.assign(b=2))NEWLINENEWLINE def test_where_drop(self):NEWLINE # if drop=TrueNEWLINENEWLINE # 1dNEWLINE # data array caseNEWLINE array = DataArray(range(5), coords=[range(5)], dims=["x"])NEWLINE expected = DataArray(range(5)[2:], coords=[range(5)[2:]], dims=["x"])NEWLINE actual = array.where(array > 1, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # dataset caseNEWLINE ds = Dataset({"a": array})NEWLINE expected = Dataset({"a": expected})NEWLINENEWLINE actual = ds.where(ds > 1, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.where(ds.a > 1, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(TypeError, "must be a"):NEWLINE ds.where(np.arange(5) > 1, drop=True)NEWLINENEWLINE # 1d with odd coordinatesNEWLINE array = DataArray(NEWLINE np.array([2, 7, 1, 8, 3]), coords=[np.array([3, 1, 4, 5, 9])], dims=["x"]NEWLINE )NEWLINE expected = DataArray(NEWLINE np.array([7, 8, 3]), coords=[np.array([1, 5, 9])], dims=["x"]NEWLINE )NEWLINE actual = array.where(array > 2, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # 1d multiple variablesNEWLINE ds = Dataset({"a": (("x"), [0, 1, 2, 3]), "b": (("x"), [4, 5, 6, 7])})NEWLINE expected = Dataset(NEWLINE {"a": (("x"), [np.nan, 1, 2, 3]), "b": (("x"), [4, 5, 6, np.nan])}NEWLINE )NEWLINE actual = ds.where((ds > 0) & (ds < 7), drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # 2dNEWLINE ds = Dataset({"a": (("x", "y"), [[0, 1], [2, 3]])})NEWLINE expected = Dataset({"a": (("x", "y"), [[np.nan, 1], [2, 3]])})NEWLINE actual = ds.where(ds > 0, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # 2d with odd coordinatesNEWLINE ds = Dataset(NEWLINE {"a": (("x", "y"), [[0, 1], [2, 3]])},NEWLINE coords={NEWLINE "x": [4, 3],NEWLINE "y": [1, 2],NEWLINE "z": (["x", "y"], [[np.e, np.pi], [np.pi * np.e, np.pi * 3]]),NEWLINE },NEWLINE )NEWLINE expected = Dataset(NEWLINE {"a": (("x", "y"), [[3]])},NEWLINE coords={"x": [3], "y": [2], "z": (["x", "y"], [[np.pi * 3]])},NEWLINE )NEWLINE actual = ds.where(ds > 2, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # 2d multiple variablesNEWLINE ds = Dataset(NEWLINE {"a": (("x", "y"), [[0, 1], [2, 3]]), "b": (("x", "y"), [[4, 5], [6, 7]])}NEWLINE )NEWLINE expected = Dataset(NEWLINE {NEWLINE "a": (("x", "y"), [[np.nan, 1], [2, 3]]),NEWLINE "b": (("x", "y"), [[4, 5], [6, 7]]),NEWLINE }NEWLINE )NEWLINE actual = ds.where(ds > 0, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_where_drop_empty(self):NEWLINE # regression test for GH1341NEWLINE array = DataArray(np.random.rand(100, 10), dims=["nCells", "nVertLevels"])NEWLINE mask = DataArray(np.zeros((100,), dtype="bool"), dims="nCells")NEWLINE actual = array.where(mask, drop=True)NEWLINE expected = DataArray(np.zeros((0, 10)), dims=["nCells", "nVertLevels"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_where_drop_no_indexes(self):NEWLINE ds = Dataset({"foo": ("x", [0.0, 1.0])})NEWLINE expected = Dataset({"foo": ("x", [1.0])})NEWLINE actual = ds.where(ds == 1, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_reduce(self):NEWLINE data = create_test_data()NEWLINENEWLINE assert len(data.mean().coords) == 0NEWLINENEWLINE actual = data.max()NEWLINE expected = Dataset({k: v.max() for k, v in data.data_vars.items()})NEWLINE assert_equal(expected, actual)NEWLINENEWLINE assert_equal(data.min(dim=["dim1"]), data.min(dim="dim1"))NEWLINENEWLINE for reduct, expected in [NEWLINE ("dim2", ["dim1", "dim3", "time"]),NEWLINE (["dim2", "time"], ["dim1", "dim3"]),NEWLINE (("dim2", "time"), ["dim1", "dim3"]),NEWLINE ((), ["dim1", "dim2", "dim3", "time"]),NEWLINE ]:NEWLINE actual = list(data.min(dim=reduct).dims)NEWLINE assert actual == expectedNEWLINENEWLINE assert_equal(data.mean(dim=[]), data)NEWLINENEWLINE def test_reduce_coords(self):NEWLINE # regression test for GH1470NEWLINE data = xr.Dataset({"a": ("x", [1, 2, 3])}, coords={"b": 4})NEWLINE expected = xr.Dataset({"a": 2}, coords={"b": 4})NEWLINE actual = data.mean("x")NEWLINE assert_identical(actual, expected)NEWLINENEWLINE # should be consistentNEWLINE actual = data["a"].mean("x").to_dataset()NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_mean_uint_dtype(self):NEWLINE data = xr.Dataset(NEWLINE {NEWLINE "a": (("x", "y"), np.arange(6).reshape(3, 2).astype("uint")),NEWLINE "b": (("x",), np.array([0.1, 0.2, np.nan])),NEWLINE }NEWLINE )NEWLINE actual = data.mean("x", skipna=True)NEWLINE expected = xr.Dataset(NEWLINE {"a": data["a"].mean("x"), "b": data["b"].mean("x", skipna=True)}NEWLINE )NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_reduce_bad_dim(self):NEWLINE data = create_test_data()NEWLINE with raises_regex(ValueError, "Dataset does not contain"):NEWLINE data.mean(dim="bad_dim")NEWLINENEWLINE def test_reduce_cumsum(self):NEWLINE data = xr.Dataset(NEWLINE {"a": 1, "b": ("x", [1, 2]), "c": (("x", "y"), [[np.nan, 3], [0, 4]])}NEWLINE )NEWLINE assert_identical(data.fillna(0), data.cumsum("y"))NEWLINENEWLINE expected = xr.Dataset(NEWLINE {"a": 1, "b": ("x", [1, 3]), "c": (("x", "y"), [[0, 3], [0, 7]])}NEWLINE )NEWLINE assert_identical(expected, data.cumsum())NEWLINENEWLINE def test_reduce_cumsum_test_dims(self):NEWLINE data = create_test_data()NEWLINE for cumfunc in ["cumsum", "cumprod"]:NEWLINE with raises_regex(ValueError, "Dataset does not contain"):NEWLINE getattr(data, cumfunc)(dim="bad_dim")NEWLINENEWLINE # ensure dimensions are correctNEWLINE for reduct, expected in [NEWLINE ("dim1", ["dim1", "dim2", "dim3", "time"]),NEWLINE ("dim2", ["dim1", "dim2", "dim3", "time"]),NEWLINE ("dim3", ["dim1", "dim2", "dim3", "time"]),NEWLINE ("time", ["dim1", "dim2", "dim3"]),NEWLINE ]:NEWLINE actual = getattr(data, cumfunc)(dim=reduct).dimsNEWLINE assert list(actual) == expectedNEWLINENEWLINE def test_reduce_non_numeric(self):NEWLINE data1 = create_test_data(seed=44)NEWLINE data2 = create_test_data(seed=44)NEWLINE add_vars = {"var4": ["dim1", "dim2"]}NEWLINE for v, dims in sorted(add_vars.items()):NEWLINE size = tuple(data1.dims[d] for d in dims)NEWLINE data = np.random.randint(0, 100, size=size).astype(np.str_)NEWLINE data1[v] = (dims, data, {"foo": "variable"})NEWLINENEWLINE assert "var4" not in data1.mean()NEWLINE assert_equal(data1.mean(), data2.mean())NEWLINE assert_equal(data1.mean(dim="dim1"), data2.mean(dim="dim1"))NEWLINENEWLINE def test_reduce_strings(self):NEWLINE expected = Dataset({"x": "a"})NEWLINE ds = Dataset({"x": ("y", ["a", "b"])})NEWLINE actual = ds.min()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"x": "b"})NEWLINE actual = ds.max()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"x": 0})NEWLINE actual = ds.argmin()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"x": 1})NEWLINE actual = ds.argmax()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"x": b"a"})NEWLINE ds = Dataset({"x": ("y", np.array(["a", "b"], "S1"))})NEWLINE actual = ds.min()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"x": "a"})NEWLINE ds = Dataset({"x": ("y", np.array(["a", "b"], "U1"))})NEWLINE actual = ds.min()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_reduce_dtypes(self):NEWLINE # regression test for GH342NEWLINE expected = Dataset({"x": 1})NEWLINE actual = Dataset({"x": True}).sum()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # regression test for GH505NEWLINE expected = Dataset({"x": 3})NEWLINE actual = Dataset({"x": ("y", np.array([1, 2], "uint16"))}).sum()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"x": 1 + 1j})NEWLINE actual = Dataset({"x": ("y", [1, 1j])}).sum()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_reduce_keep_attrs(self):NEWLINE data = create_test_data()NEWLINE _attrs = {"attr1": "value1", "attr2": 2929}NEWLINENEWLINE attrs = dict(_attrs)NEWLINE data.attrs = attrsNEWLINENEWLINE # Test dropped attrsNEWLINE ds = data.mean()NEWLINE assert ds.attrs == {}NEWLINE for v in ds.data_vars.values():NEWLINE assert v.attrs == {}NEWLINENEWLINE # Test kept attrsNEWLINE ds = data.mean(keep_attrs=True)NEWLINE assert ds.attrs == attrsNEWLINE for k, v in ds.data_vars.items():NEWLINE assert v.attrs == data[k].attrsNEWLINENEWLINE def test_reduce_argmin(self):NEWLINE # regression test for #205NEWLINE ds = Dataset({"a": ("x", [0, 1])})NEWLINE expected = Dataset({"a": ([], 0)})NEWLINE actual = ds.argmin()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.argmin("x")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_reduce_scalars(self):NEWLINE ds = Dataset({"x": ("a", [2, 2]), "y": 2, "z": ("b", [2])})NEWLINE expected = Dataset({"x": 0, "y": 0, "z": 0})NEWLINE actual = ds.var()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"x": 0, "y": 0, "z": ("b", [0])})NEWLINE actual = ds.var("a")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_reduce_only_one_axis(self):NEWLINE def mean_only_one_axis(x, axis):NEWLINE if not isinstance(axis, integer_types):NEWLINE raise TypeError("non-integer axis")NEWLINE return x.mean(axis)NEWLINENEWLINE ds = Dataset({"a": (["x", "y"], [[0, 1, 2, 3, 4]])})NEWLINE expected = Dataset({"a": ("x", [2])})NEWLINE actual = ds.reduce(mean_only_one_axis, "y")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(NEWLINE TypeError, "missing 1 required positional argument: " "'axis'"NEWLINE ):NEWLINE ds.reduce(mean_only_one_axis)NEWLINENEWLINE with raises_regex(TypeError, "non-integer axis"):NEWLINE ds.reduce(mean_only_one_axis, axis=["x", "y"])NEWLINENEWLINE def test_reduce_no_axis(self):NEWLINE def total_sum(x):NEWLINE return np.sum(x.flatten())NEWLINENEWLINE ds = Dataset({"a": (["x", "y"], [[0, 1, 2, 3, 4]])})NEWLINE expected = Dataset({"a": ((), 10)})NEWLINE actual = ds.reduce(total_sum)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(TypeError, "unexpected keyword argument 'axis'"):NEWLINE ds.reduce(total_sum, axis=0)NEWLINENEWLINE with raises_regex(TypeError, "unexpected keyword argument 'axis'"):NEWLINE ds.reduce(total_sum, dim="x")NEWLINENEWLINE def test_reduce_keepdims(self):NEWLINE ds = Dataset(NEWLINE {"a": (["x", "y"], [[0, 1, 2, 3, 4]])},NEWLINE coords={NEWLINE "y": [0, 1, 2, 3, 4],NEWLINE "x": [0],NEWLINE "lat": (["x", "y"], [[0, 1, 2, 3, 4]]),NEWLINE "c": -999.0,NEWLINE },NEWLINE )NEWLINENEWLINE # Shape should match behaviour of numpy reductions with keepdims=TrueNEWLINE # Coordinates involved in the reduction should be removedNEWLINE actual = ds.mean(keepdims=True)NEWLINE expected = Dataset(NEWLINE {"a": (["x", "y"], np.mean(ds.a, keepdims=True))}, coords={"c": ds.c}NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.mean("x", keepdims=True)NEWLINE expected = Dataset(NEWLINE {"a": (["x", "y"], np.mean(ds.a, axis=0, keepdims=True))},NEWLINE coords={"y": ds.y, "c": ds.c},NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_quantile(self):NEWLINENEWLINE ds = create_test_data(seed=123)NEWLINENEWLINE for q in [0.25, [0.50], [0.25, 0.75]]:NEWLINE for dim in [None, "dim1", ["dim1"]]:NEWLINE ds_quantile = ds.quantile(q, dim=dim)NEWLINE assert "quantile" in ds_quantileNEWLINE for var, dar in ds.data_vars.items():NEWLINE assert var in ds_quantileNEWLINE assert_identical(ds_quantile[var], dar.quantile(q, dim=dim))NEWLINE dim = ["dim1", "dim2"]NEWLINE ds_quantile = ds.quantile(q, dim=dim)NEWLINE assert "dim3" in ds_quantile.dimsNEWLINE assert all(d not in ds_quantile.dims for d in dim)NEWLINENEWLINE @requires_bottleneckNEWLINE def test_rank(self):NEWLINE ds = create_test_data(seed=1234)NEWLINE # only ds.var3 depends on dim3NEWLINE z = ds.rank("dim3")NEWLINE assert ["var3"] == list(z.data_vars)NEWLINE # same as dataarray versionNEWLINE x = z.var3NEWLINE y = ds.var3.rank("dim3")NEWLINE assert_equal(x, y)NEWLINE # coordinates stickNEWLINE assert list(z.coords) == list(ds.coords)NEWLINE assert list(x.coords) == list(y.coords)NEWLINE # invalid dimNEWLINE with raises_regex(ValueError, "does not contain"):NEWLINE x.rank("invalid_dim")NEWLINENEWLINE def test_count(self):NEWLINE ds = Dataset({"x": ("a", [np.nan, 1]), "y": 0, "z": np.nan})NEWLINE expected = Dataset({"x": 1, "y": 1, "z": 0})NEWLINE actual = ds.count()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_map(self):NEWLINE data = create_test_data()NEWLINE data.attrs["foo"] = "bar"NEWLINENEWLINE assert_identical(data.map(np.mean), data.mean())NEWLINENEWLINE expected = data.mean(keep_attrs=True)NEWLINE actual = data.map(lambda x: x.mean(keep_attrs=True), keep_attrs=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE assert_identical(data.map(lambda x: x, keep_attrs=True), data.drop_vars("time"))NEWLINENEWLINE def scale(x, multiple=1):NEWLINE return multiple * xNEWLINENEWLINE actual = data.map(scale, multiple=2)NEWLINE assert_equal(actual["var1"], 2 * data["var1"])NEWLINE assert_identical(actual["numbers"], data["numbers"])NEWLINENEWLINE actual = data.map(np.asarray)NEWLINE expected = data.drop_vars("time") # time is not used on a data varNEWLINE assert_equal(expected, actual)NEWLINENEWLINE def test_apply_pending_deprecated_map(self):NEWLINE data = create_test_data()NEWLINE data.attrs["foo"] = "bar"NEWLINENEWLINE with pytest.warns(PendingDeprecationWarning):NEWLINE assert_identical(data.apply(np.mean), data.mean())NEWLINENEWLINE def make_example_math_dataset(self):NEWLINE variables = {NEWLINE "bar": ("x", np.arange(100, 400, 100)),NEWLINE "foo": (("x", "y"), 1.0 * np.arange(12).reshape(3, 4)),NEWLINE }NEWLINE coords = {"abc": ("x", ["a", "b", "c"]), "y": 10 * np.arange(4)}NEWLINE ds = Dataset(variables, coords)NEWLINE ds["foo"][0, 0] = np.nanNEWLINE return dsNEWLINENEWLINE def test_dataset_number_math(self):NEWLINE ds = self.make_example_math_dataset()NEWLINENEWLINE assert_identical(ds, +ds)NEWLINE assert_identical(ds, ds + 0)NEWLINE assert_identical(ds, 0 + ds)NEWLINE assert_identical(ds, ds + np.array(0))NEWLINE assert_identical(ds, np.array(0) + ds)NEWLINENEWLINE actual = ds.copy(deep=True)NEWLINE actual += 0NEWLINE assert_identical(ds, actual)NEWLINENEWLINE def test_unary_ops(self):NEWLINE ds = self.make_example_math_dataset()NEWLINENEWLINE assert_identical(ds.map(abs), abs(ds))NEWLINE assert_identical(ds.map(lambda x: x + 4), ds + 4)NEWLINENEWLINE for func in [NEWLINE lambda x: x.isnull(),NEWLINE lambda x: x.round(),NEWLINE lambda x: x.astype(int),NEWLINE ]:NEWLINE assert_identical(ds.map(func), func(ds))NEWLINENEWLINE assert_identical(ds.isnull(), ~ds.notnull())NEWLINENEWLINE # don't actually patch these methods inNEWLINE with pytest.raises(AttributeError):NEWLINE ds.itemNEWLINE with pytest.raises(AttributeError):NEWLINE ds.searchsortedNEWLINENEWLINE def test_dataset_array_math(self):NEWLINE ds = self.make_example_math_dataset()NEWLINENEWLINE expected = ds.map(lambda x: x - ds["foo"])NEWLINE assert_identical(expected, ds - ds["foo"])NEWLINE assert_identical(expected, -ds["foo"] + ds)NEWLINE assert_identical(expected, ds - ds["foo"].variable)NEWLINE assert_identical(expected, -ds["foo"].variable + ds)NEWLINE actual = ds.copy(deep=True)NEWLINE actual -= ds["foo"]NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = ds.map(lambda x: x + ds["bar"])NEWLINE assert_identical(expected, ds + ds["bar"])NEWLINE actual = ds.copy(deep=True)NEWLINE actual += ds["bar"]NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"bar": ds["bar"] + np.arange(3)})NEWLINE assert_identical(expected, ds[["bar"]] + np.arange(3))NEWLINE assert_identical(expected, np.arange(3) + ds[["bar"]])NEWLINENEWLINE def test_dataset_dataset_math(self):NEWLINE ds = self.make_example_math_dataset()NEWLINENEWLINE assert_identical(ds, ds + 0 * ds)NEWLINE assert_identical(ds, ds + {"foo": 0, "bar": 0})NEWLINENEWLINE expected = ds.map(lambda x: 2 * x)NEWLINE assert_identical(expected, 2 * ds)NEWLINE assert_identical(expected, ds + ds)NEWLINE assert_identical(expected, ds + ds.data_vars)NEWLINE assert_identical(expected, ds + dict(ds.data_vars))NEWLINENEWLINE actual = ds.copy(deep=True)NEWLINE expected_id = id(actual)NEWLINE actual += dsNEWLINE assert_identical(expected, actual)NEWLINE assert expected_id == id(actual)NEWLINENEWLINE assert_identical(ds == ds, ds.notnull())NEWLINENEWLINE subsampled = ds.isel(y=slice(2))NEWLINE expected = 2 * subsampledNEWLINE assert_identical(expected, subsampled + ds)NEWLINE assert_identical(expected, ds + subsampled)NEWLINENEWLINE def test_dataset_math_auto_align(self):NEWLINE ds = self.make_example_math_dataset()NEWLINE subset = ds.isel(y=[1, 3])NEWLINE expected = 2 * subsetNEWLINE actual = ds + subsetNEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.isel(y=slice(1)) + ds.isel(y=slice(1, None))NEWLINE expected = 2 * ds.drop_sel(y=ds.y)NEWLINE assert_equal(actual, expected)NEWLINENEWLINE actual = ds + ds[["bar"]]NEWLINE expected = (2 * ds[["bar"]]).merge(ds.coords)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE assert_identical(ds + Dataset(), ds.coords.to_dataset())NEWLINE assert_identical(Dataset() + Dataset(), Dataset())NEWLINENEWLINE ds2 = Dataset(coords={"bar": 42})NEWLINE assert_identical(ds + ds2, ds.coords.merge(ds2))NEWLINENEWLINE # maybe unary arithmetic with empty datasets should raise instead?NEWLINE assert_identical(Dataset() + 1, Dataset())NEWLINENEWLINE actual = ds.copy(deep=True)NEWLINE other = ds.isel(y=slice(2))NEWLINE actual += otherNEWLINE expected = ds + other.reindex_like(ds)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_dataset_math_errors(self):NEWLINE ds = self.make_example_math_dataset()NEWLINENEWLINE with pytest.raises(TypeError):NEWLINE ds["foo"] += dsNEWLINE with pytest.raises(TypeError):NEWLINE ds["foo"].variable += dsNEWLINE with raises_regex(ValueError, "must have the same"):NEWLINE ds += ds[["bar"]]NEWLINENEWLINE # verify we can rollback in-place operations if something goes wrongNEWLINE # nb. inplace datetime64 math actually will work with an integer arrayNEWLINE # but not floats thanks to numpy's inconsistent handlingNEWLINE other = DataArray(np.datetime64("2000-01-01"), coords={"c": 2})NEWLINE actual = ds.copy(deep=True)NEWLINE with pytest.raises(TypeError):NEWLINE actual += otherNEWLINE assert_identical(actual, ds)NEWLINENEWLINE def test_dataset_transpose(self):NEWLINE ds = Dataset(NEWLINE {NEWLINE "a": (("x", "y"), np.random.randn(3, 4)),NEWLINE "b": (("y", "x"), np.random.randn(4, 3)),NEWLINE },NEWLINE coords={NEWLINE "x": range(3),NEWLINE "y": range(4),NEWLINE "xy": (("x", "y"), np.random.randn(3, 4)),NEWLINE },NEWLINE )NEWLINENEWLINE actual = ds.transpose()NEWLINE expected = Dataset(NEWLINE {"a": (("y", "x"), ds.a.values.T), "b": (("x", "y"), ds.b.values.T)},NEWLINE coords={NEWLINE "x": ds.x.values,NEWLINE "y": ds.y.values,NEWLINE "xy": (("y", "x"), ds.xy.values.T),NEWLINE },NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.transpose(...)NEWLINE expected = dsNEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.transpose("x", "y")NEWLINE expected = ds.map(lambda x: x.transpose("x", "y", transpose_coords=True))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE ds = create_test_data()NEWLINE actual = ds.transpose()NEWLINE for k in ds.variables:NEWLINE assert actual[k].dims[::-1] == ds[k].dimsNEWLINENEWLINE new_order = ("dim2", "dim3", "dim1", "time")NEWLINE actual = ds.transpose(*new_order)NEWLINE for k in ds.variables:NEWLINE expected_dims = tuple(d for d in new_order if d in ds[k].dims)NEWLINE assert actual[k].dims == expected_dimsNEWLINENEWLINE # same as above but with ellipsisNEWLINE new_order = ("dim2", "dim3", "dim1", "time")NEWLINE actual = ds.transpose("dim2", "dim3", ...)NEWLINE for k in ds.variables:NEWLINE expected_dims = tuple(d for d in new_order if d in ds[k].dims)NEWLINE assert actual[k].dims == expected_dimsNEWLINENEWLINE with raises_regex(ValueError, "permuted"):NEWLINE ds.transpose("dim1", "dim2", "dim3")NEWLINE with raises_regex(ValueError, "permuted"):NEWLINE ds.transpose("dim1", "dim2", "dim3", "time", "extra_dim")NEWLINENEWLINE assert "T" not in dir(ds)NEWLINENEWLINE def test_dataset_ellipsis_transpose_different_ordered_vars(self):NEWLINE # https://github.com/pydata/xarray/issues/1081#issuecomment-544350457NEWLINE ds = Dataset(NEWLINE dict(NEWLINE a=(("w", "x", "y", "z"), np.ones((2, 3, 4, 5))),NEWLINE b=(("x", "w", "y", "z"), np.zeros((3, 2, 4, 5))),NEWLINE )NEWLINE )NEWLINE result = ds.transpose(..., "z", "y")NEWLINE assert list(result["a"].dims) == list("wxzy")NEWLINE assert list(result["b"].dims) == list("xwzy")NEWLINENEWLINE def test_dataset_retains_period_index_on_transpose(self):NEWLINENEWLINE ds = create_test_data()NEWLINE ds["time"] = pd.period_range("2000-01-01", periods=20)NEWLINENEWLINE transposed = ds.transpose()NEWLINENEWLINE assert isinstance(transposed.time.to_index(), pd.PeriodIndex)NEWLINENEWLINE def test_dataset_diff_n1_simple(self):NEWLINE ds = Dataset({"foo": ("x", [5, 5, 6, 6])})NEWLINE actual = ds.diff("x")NEWLINE expected = Dataset({"foo": ("x", [0, 1, 0])})NEWLINE assert_equal(expected, actual)NEWLINENEWLINE def test_dataset_diff_n1_label(self):NEWLINE ds = Dataset({"foo": ("x", [5, 5, 6, 6])}, {"x": [0, 1, 2, 3]})NEWLINE actual = ds.diff("x", label="lower")NEWLINE expected = Dataset({"foo": ("x", [0, 1, 0])}, {"x": [0, 1, 2]})NEWLINE assert_equal(expected, actual)NEWLINENEWLINE actual = ds.diff("x", label="upper")NEWLINE expected = Dataset({"foo": ("x", [0, 1, 0])}, {"x": [1, 2, 3]})NEWLINE assert_equal(expected, actual)NEWLINENEWLINE def test_dataset_diff_n1(self):NEWLINE ds = create_test_data(seed=1)NEWLINE actual = ds.diff("dim2")NEWLINE expected = {}NEWLINE expected["var1"] = DataArray(NEWLINE np.diff(ds["var1"].values, axis=1),NEWLINE {"dim2": ds["dim2"].values[1:]},NEWLINE ["dim1", "dim2"],NEWLINE )NEWLINE expected["var2"] = DataArray(NEWLINE np.diff(ds["var2"].values, axis=1),NEWLINE {"dim2": ds["dim2"].values[1:]},NEWLINE ["dim1", "dim2"],NEWLINE )NEWLINE expected["var3"] = ds["var3"]NEWLINE expected = Dataset(expected, coords={"time": ds["time"].values})NEWLINE expected.coords["numbers"] = ("dim3", ds["numbers"].values)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE def test_dataset_diff_n2(self):NEWLINE ds = create_test_data(seed=1)NEWLINE actual = ds.diff("dim2", n=2)NEWLINE expected = {}NEWLINE expected["var1"] = DataArray(NEWLINE np.diff(ds["var1"].values, axis=1, n=2),NEWLINE {"dim2": ds["dim2"].values[2:]},NEWLINE ["dim1", "dim2"],NEWLINE )NEWLINE expected["var2"] = DataArray(NEWLINE np.diff(ds["var2"].values, axis=1, n=2),NEWLINE {"dim2": ds["dim2"].values[2:]},NEWLINE ["dim1", "dim2"],NEWLINE )NEWLINE expected["var3"] = ds["var3"]NEWLINE expected = Dataset(expected, coords={"time": ds["time"].values})NEWLINE expected.coords["numbers"] = ("dim3", ds["numbers"].values)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE def test_dataset_diff_exception_n_neg(self):NEWLINE ds = create_test_data(seed=1)NEWLINE with raises_regex(ValueError, "must be non-negative"):NEWLINE ds.diff("dim2", n=-1)NEWLINENEWLINE def test_dataset_diff_exception_label_str(self):NEWLINE ds = create_test_data(seed=1)NEWLINE with raises_regex(ValueError, "'label' argument has to"):NEWLINE ds.diff("dim2", label="raise_me")NEWLINENEWLINE @pytest.mark.parametrize("fill_value", [dtypes.NA, 2, 2.0])NEWLINE def test_shift(self, fill_value):NEWLINE coords = {"bar": ("x", list("abc")), "x": [-4, 3, 2]}NEWLINE attrs = {"meta": "data"}NEWLINE ds = Dataset({"foo": ("x", [1, 2, 3])}, coords, attrs)NEWLINE actual = ds.shift(x=1, fill_value=fill_value)NEWLINE if fill_value == dtypes.NA:NEWLINE # if we supply the default, we expect the missing value for aNEWLINE # float arrayNEWLINE fill_value = np.nanNEWLINE expected = Dataset({"foo": ("x", [fill_value, 1, 2])}, coords, attrs)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(ValueError, "dimensions"):NEWLINE ds.shift(foo=123)NEWLINENEWLINE def test_roll_coords(self):NEWLINE coords = {"bar": ("x", list("abc")), "x": [-4, 3, 2]}NEWLINE attrs = {"meta": "data"}NEWLINE ds = Dataset({"foo": ("x", [1, 2, 3])}, coords, attrs)NEWLINE actual = ds.roll(x=1, roll_coords=True)NEWLINENEWLINE ex_coords = {"bar": ("x", list("cab")), "x": [2, -4, 3]}NEWLINE expected = Dataset({"foo": ("x", [3, 1, 2])}, ex_coords, attrs)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(ValueError, "dimensions"):NEWLINE ds.roll(foo=123, roll_coords=True)NEWLINENEWLINE def test_roll_no_coords(self):NEWLINE coords = {"bar": ("x", list("abc")), "x": [-4, 3, 2]}NEWLINE attrs = {"meta": "data"}NEWLINE ds = Dataset({"foo": ("x", [1, 2, 3])}, coords, attrs)NEWLINE actual = ds.roll(x=1, roll_coords=False)NEWLINENEWLINE expected = Dataset({"foo": ("x", [3, 1, 2])}, coords, attrs)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(ValueError, "dimensions"):NEWLINE ds.roll(abc=321, roll_coords=False)NEWLINENEWLINE def test_roll_coords_none(self):NEWLINE coords = {"bar": ("x", list("abc")), "x": [-4, 3, 2]}NEWLINE attrs = {"meta": "data"}NEWLINE ds = Dataset({"foo": ("x", [1, 2, 3])}, coords, attrs)NEWLINENEWLINE with pytest.warns(FutureWarning):NEWLINE actual = ds.roll(x=1, roll_coords=None)NEWLINENEWLINE ex_coords = {"bar": ("x", list("cab")), "x": [2, -4, 3]}NEWLINE expected = Dataset({"foo": ("x", [3, 1, 2])}, ex_coords, attrs)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_roll_multidim(self):NEWLINE # regression test for 2445NEWLINE arr = xr.DataArray(NEWLINE [[1, 2, 3], [4, 5, 6]],NEWLINE coords={"x": range(3), "y": range(2)},NEWLINE dims=("y", "x"),NEWLINE )NEWLINE actual = arr.roll(x=1, roll_coords=True)NEWLINE expected = xr.DataArray(NEWLINE [[3, 1, 2], [6, 4, 5]], coords=[("y", [0, 1]), ("x", [2, 0, 1])]NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_real_and_imag(self):NEWLINE attrs = {"foo": "bar"}NEWLINE ds = Dataset({"x": ((), 1 + 2j, attrs)}, attrs=attrs)NEWLINENEWLINE expected_re = Dataset({"x": ((), 1, attrs)}, attrs=attrs)NEWLINE assert_identical(ds.real, expected_re)NEWLINENEWLINE expected_im = Dataset({"x": ((), 2, attrs)}, attrs=attrs)NEWLINE assert_identical(ds.imag, expected_im)NEWLINENEWLINE def test_setattr_raises(self):NEWLINE ds = Dataset({}, coords={"scalar": 1}, attrs={"foo": "bar"})NEWLINE with raises_regex(AttributeError, "cannot set attr"):NEWLINE ds.scalar = 2NEWLINE with raises_regex(AttributeError, "cannot set attr"):NEWLINE ds.foo = 2NEWLINE with raises_regex(AttributeError, "cannot set attr"):NEWLINE ds.other = 2NEWLINENEWLINE def test_filter_by_attrs(self):NEWLINE precip = dict(standard_name="convective_precipitation_flux")NEWLINE temp0 = dict(standard_name="air_potential_temperature", height="0 m")NEWLINE temp10 = dict(standard_name="air_potential_temperature", height="10 m")NEWLINE ds = Dataset(NEWLINE {NEWLINE "temperature_0": (["t"], [0], temp0),NEWLINE "temperature_10": (["t"], [0], temp10),NEWLINE "precipitation": (["t"], [0], precip),NEWLINE },NEWLINE coords={"time": (["t"], [0], dict(axis="T", long_name="time_in_seconds"))},NEWLINE )NEWLINENEWLINE # Test return empty Dataset.NEWLINE ds.filter_by_attrs(standard_name="invalid_standard_name")NEWLINE new_ds = ds.filter_by_attrs(standard_name="invalid_standard_name")NEWLINE assert not bool(new_ds.data_vars)NEWLINENEWLINE # Test return one DataArray.NEWLINE new_ds = ds.filter_by_attrs(standard_name="convective_precipitation_flux")NEWLINE assert new_ds["precipitation"].standard_name == "convective_precipitation_flux"NEWLINENEWLINE assert_equal(new_ds["precipitation"], ds["precipitation"])NEWLINENEWLINE # Test filter coordinatesNEWLINE new_ds = ds.filter_by_attrs(long_name="time_in_seconds")NEWLINE assert new_ds["time"].long_name == "time_in_seconds"NEWLINE assert not bool(new_ds.data_vars)NEWLINENEWLINE # Test return more than one DataArray.NEWLINE new_ds = ds.filter_by_attrs(standard_name="air_potential_temperature")NEWLINE assert len(new_ds.data_vars) == 2NEWLINE for var in new_ds.data_vars:NEWLINE assert new_ds[var].standard_name == "air_potential_temperature"NEWLINENEWLINE # Test callable.NEWLINE new_ds = ds.filter_by_attrs(height=lambda v: v is not None)NEWLINE assert len(new_ds.data_vars) == 2NEWLINE for var in new_ds.data_vars:NEWLINE assert new_ds[var].standard_name == "air_potential_temperature"NEWLINENEWLINE new_ds = ds.filter_by_attrs(height="10 m")NEWLINE assert len(new_ds.data_vars) == 1NEWLINE for var in new_ds.data_vars:NEWLINE assert new_ds[var].height == "10 m"NEWLINENEWLINE # Test return empty Dataset due to conflicting filtersNEWLINE new_ds = ds.filter_by_attrs(NEWLINE standard_name="convective_precipitation_flux", height="0 m"NEWLINE )NEWLINE assert not bool(new_ds.data_vars)NEWLINENEWLINE # Test return one DataArray with two filter conditionsNEWLINE new_ds = ds.filter_by_attrs(NEWLINE standard_name="air_potential_temperature", height="0 m"NEWLINE )NEWLINE for var in new_ds.data_vars:NEWLINE assert new_ds[var].standard_name == "air_potential_temperature"NEWLINE assert new_ds[var].height == "0 m"NEWLINE assert new_ds[var].height != "10 m"NEWLINENEWLINE # Test return empty Dataset due to conflicting callablesNEWLINE new_ds = ds.filter_by_attrs(NEWLINE standard_name=lambda v: False, height=lambda v: TrueNEWLINE )NEWLINE assert not bool(new_ds.data_vars)NEWLINENEWLINE def test_binary_op_propagate_indexes(self):NEWLINE ds = Dataset(NEWLINE {"d1": DataArray([1, 2, 3], dims=["x"], coords={"x": [10, 20, 30]})}NEWLINE )NEWLINE expected = ds.indexes["x"]NEWLINE actual = (ds * 2).indexes["x"]NEWLINE assert expected is actualNEWLINENEWLINE def test_binary_op_join_setting(self):NEWLINE # arithmetic_join applies to data array coordinatesNEWLINE missing_2 = xr.Dataset({"x": [0, 1]})NEWLINE missing_0 = xr.Dataset({"x": [1, 2]})NEWLINE with xr.set_options(arithmetic_join="outer"):NEWLINE actual = missing_2 + missing_0NEWLINE expected = xr.Dataset({"x": [0, 1, 2]})NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # arithmetic join also applies to data_varsNEWLINE ds1 = xr.Dataset({"foo": 1, "bar": 2})NEWLINE ds2 = xr.Dataset({"bar": 2, "baz": 3})NEWLINE expected = xr.Dataset({"bar": 4}) # default is inner joiningNEWLINE actual = ds1 + ds2NEWLINE assert_equal(actual, expected)NEWLINENEWLINE with xr.set_options(arithmetic_join="outer"):NEWLINE expected = xr.Dataset({"foo": np.nan, "bar": 4, "baz": np.nan})NEWLINE actual = ds1 + ds2NEWLINE assert_equal(actual, expected)NEWLINENEWLINE with xr.set_options(arithmetic_join="left"):NEWLINE expected = xr.Dataset({"foo": np.nan, "bar": 4})NEWLINE actual = ds1 + ds2NEWLINE assert_equal(actual, expected)NEWLINENEWLINE with xr.set_options(arithmetic_join="right"):NEWLINE expected = xr.Dataset({"bar": 4, "baz": np.nan})NEWLINE actual = ds1 + ds2NEWLINE assert_equal(actual, expected)NEWLINENEWLINE def test_full_like(self):NEWLINE # For more thorough tests, see test_variable.pyNEWLINE # Note: testing data_vars with mismatched dtypesNEWLINE ds = Dataset(NEWLINE {NEWLINE "d1": DataArray([1, 2, 3], dims=["x"], coords={"x": [10, 20, 30]}),NEWLINE "d2": DataArray([1.1, 2.2, 3.3], dims=["y"]),NEWLINE },NEWLINE attrs={"foo": "bar"},NEWLINE )NEWLINE actual = full_like(ds, 2)NEWLINENEWLINE expect = ds.copy(deep=True)NEWLINE expect["d1"].values = [2, 2, 2]NEWLINE expect["d2"].values = [2.0, 2.0, 2.0]NEWLINE assert expect["d1"].dtype == intNEWLINE assert expect["d2"].dtype == floatNEWLINE assert_identical(expect, actual)NEWLINENEWLINE # override dtypeNEWLINE actual = full_like(ds, fill_value=True, dtype=bool)NEWLINE expect = ds.copy(deep=True)NEWLINE expect["d1"].values = [True, True, True]NEWLINE expect["d2"].values = [True, True, True]NEWLINE assert expect["d1"].dtype == boolNEWLINE assert expect["d2"].dtype == boolNEWLINE assert_identical(expect, actual)NEWLINENEWLINE def test_combine_first(self):NEWLINE dsx0 = DataArray([0, 0], [("x", ["a", "b"])]).to_dataset(name="dsx0")NEWLINE dsx1 = DataArray([1, 1], [("x", ["b", "c"])]).to_dataset(name="dsx1")NEWLINENEWLINE actual = dsx0.combine_first(dsx1)NEWLINE expected = Dataset(NEWLINE {"dsx0": ("x", [0, 0, np.nan]), "dsx1": ("x", [np.nan, 1, 1])},NEWLINE coords={"x": ["a", "b", "c"]},NEWLINE )NEWLINE assert_equal(actual, expected)NEWLINE assert_equal(actual, xr.merge([dsx0, dsx1]))NEWLINENEWLINE # works just like xr.merge([self, other])NEWLINE dsy2 = DataArray([2, 2, 2], [("x", ["b", "c", "d"])]).to_dataset(name="dsy2")NEWLINE actual = dsx0.combine_first(dsy2)NEWLINE expected = xr.merge([dsy2, dsx0])NEWLINE assert_equal(actual, expected)NEWLINENEWLINE def test_sortby(self):NEWLINE ds = Dataset(NEWLINE {NEWLINE "A": DataArray(NEWLINE [[1, 2], [3, 4], [5, 6]], [("x", ["c", "b", "a"]), ("y", [1, 0])]NEWLINE ),NEWLINE "B": DataArray([[5, 6], [7, 8], [9, 10]], dims=["x", "y"]),NEWLINE }NEWLINE )NEWLINENEWLINE sorted1d = Dataset(NEWLINE {NEWLINE "A": DataArray(NEWLINE [[5, 6], [3, 4], [1, 2]], [("x", ["a", "b", "c"]), ("y", [1, 0])]NEWLINE ),NEWLINE "B": DataArray([[9, 10], [7, 8], [5, 6]], dims=["x", "y"]),NEWLINE }NEWLINE )NEWLINENEWLINE sorted2d = Dataset(NEWLINE {NEWLINE "A": DataArray(NEWLINE [[6, 5], [4, 3], [2, 1]], [("x", ["a", "b", "c"]), ("y", [0, 1])]NEWLINE ),NEWLINE "B": DataArray([[10, 9], [8, 7], [6, 5]], dims=["x", "y"]),NEWLINE }NEWLINE )NEWLINENEWLINE expected = sorted1dNEWLINE dax = DataArray([100, 99, 98], [("x", ["c", "b", "a"])])NEWLINE actual = ds.sortby(dax)NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # test descending order sortNEWLINE actual = ds.sortby(dax, ascending=False)NEWLINE assert_equal(actual, ds)NEWLINENEWLINE # test alignment (fills in nan for 'c')NEWLINE dax_short = DataArray([98, 97], [("x", ["b", "a"])])NEWLINE actual = ds.sortby(dax_short)NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # test 1-D lexsortNEWLINE # dax0 is sorted first to give indices of [1, 2, 0]NEWLINE # and then dax1 would be used to move index 2 ahead of 1NEWLINE dax0 = DataArray([100, 95, 95], [("x", ["c", "b", "a"])])NEWLINE dax1 = DataArray([0, 1, 0], [("x", ["c", "b", "a"])])NEWLINE actual = ds.sortby([dax0, dax1]) # lexsort underneath gives [2, 1, 0]NEWLINE assert_equal(actual, expected)NEWLINENEWLINE expected = sorted2dNEWLINE # test multi-dim sort by 1D dataarray valuesNEWLINE day = DataArray([90, 80], [("y", [1, 0])])NEWLINE actual = ds.sortby([day, dax])NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # test exception-raisingNEWLINE with pytest.raises(KeyError) as excinfo:NEWLINE actual = ds.sortby("z")NEWLINENEWLINE with pytest.raises(ValueError) as excinfo:NEWLINE actual = ds.sortby(ds["A"])NEWLINE assert "DataArray is not 1-D" in str(excinfo.value)NEWLINENEWLINE expected = sorted1dNEWLINE actual = ds.sortby("x")NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # test pandas.MultiIndexNEWLINE indices = (("b", 1), ("b", 0), ("a", 1), ("a", 0))NEWLINE midx = pd.MultiIndex.from_tuples(indices, names=["one", "two"])NEWLINE ds_midx = Dataset(NEWLINE {NEWLINE "A": DataArray(NEWLINE [[1, 2], [3, 4], [5, 6], [7, 8]], [("x", midx), ("y", [1, 0])]NEWLINE ),NEWLINE "B": DataArray([[5, 6], [7, 8], [9, 10], [11, 12]], dims=["x", "y"]),NEWLINE }NEWLINE )NEWLINE actual = ds_midx.sortby("x")NEWLINE midx_reversed = pd.MultiIndex.from_tuples(NEWLINE tuple(reversed(indices)), names=["one", "two"]NEWLINE )NEWLINE expected = Dataset(NEWLINE {NEWLINE "A": DataArray(NEWLINE [[7, 8], [5, 6], [3, 4], [1, 2]],NEWLINE [("x", midx_reversed), ("y", [1, 0])],NEWLINE ),NEWLINE "B": DataArray([[11, 12], [9, 10], [7, 8], [5, 6]], dims=["x", "y"]),NEWLINE }NEWLINE )NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # multi-dim sort by coordinate objectsNEWLINE expected = sorted2dNEWLINE actual = ds.sortby(["x", "y"])NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # test descending order sortNEWLINE actual = ds.sortby(["x", "y"], ascending=False)NEWLINE assert_equal(actual, ds)NEWLINENEWLINE def test_attribute_access(self):NEWLINE ds = create_test_data(seed=1)NEWLINE for key in ["var1", "var2", "var3", "time", "dim1", "dim2", "dim3", "numbers"]:NEWLINE assert_equal(ds[key], getattr(ds, key))NEWLINE assert key in dir(ds)NEWLINENEWLINE for key in ["dim3", "dim1", "numbers"]:NEWLINE assert_equal(ds["var3"][key], getattr(ds.var3, key))NEWLINE assert key in dir(ds["var3"])NEWLINE # attrsNEWLINE assert ds["var3"].attrs["foo"] == ds.var3.fooNEWLINE assert "foo" in dir(ds["var3"])NEWLINENEWLINE def test_ipython_key_completion(self):NEWLINE ds = create_test_data(seed=1)NEWLINE actual = ds._ipython_key_completions_()NEWLINE expected = ["var1", "var2", "var3", "time", "dim1", "dim2", "dim3", "numbers"]NEWLINE for item in actual:NEWLINE ds[item] # should not raiseNEWLINE assert sorted(actual) == sorted(expected)NEWLINENEWLINE # for dataarrayNEWLINE actual = ds["var3"]._ipython_key_completions_()NEWLINE expected = ["dim3", "dim1", "numbers"]NEWLINE for item in actual:NEWLINE ds["var3"][item] # should not raiseNEWLINE assert sorted(actual) == sorted(expected)NEWLINENEWLINE # MultiIndexNEWLINE ds_midx = ds.stack(dim12=["dim1", "dim2"])NEWLINE actual = ds_midx._ipython_key_completions_()NEWLINE expected = [NEWLINE "var1",NEWLINE "var2",NEWLINE "var3",NEWLINE "time",NEWLINE "dim1",NEWLINE "dim2",NEWLINE "dim3",NEWLINE "numbers",NEWLINE "dim12",NEWLINE ]NEWLINE for item in actual:NEWLINE ds_midx[item] # should not raiseNEWLINE assert sorted(actual) == sorted(expected)NEWLINENEWLINE # coordsNEWLINE actual = ds.coords._ipython_key_completions_()NEWLINE expected = ["time", "dim1", "dim2", "dim3", "numbers"]NEWLINE for item in actual:NEWLINE ds.coords[item] # should not raiseNEWLINE assert sorted(actual) == sorted(expected)NEWLINENEWLINE actual = ds["var3"].coords._ipython_key_completions_()NEWLINE expected = ["dim1", "dim3", "numbers"]NEWLINE for item in actual:NEWLINE ds["var3"].coords[item] # should not raiseNEWLINE assert sorted(actual) == sorted(expected)NEWLINENEWLINE # data_varsNEWLINE actual = ds.data_vars._ipython_key_completions_()NEWLINE expected = ["var1", "var2", "var3", "dim1"]NEWLINE for item in actual:NEWLINE ds.data_vars[item] # should not raiseNEWLINE assert sorted(actual) == sorted(expected)NEWLINENEWLINENEWLINE# Py.test testsNEWLINENEWLINENEWLINE@pytest.fixture(params=[None])NEWLINEdef data_set(request):NEWLINE return create_test_data(request.param)NEWLINENEWLINENEWLINE@pytest.mark.parametrize("test_elements", ([1, 2], np.array([1, 2]), DataArray([1, 2])))NEWLINEdef test_isin(test_elements):NEWLINE expected = Dataset(NEWLINE data_vars={NEWLINE "var1": (("dim1",), [0, 1]),NEWLINE "var2": (("dim1",), [1, 1]),NEWLINE "var3": (("dim1",), [0, 1]),NEWLINE }NEWLINE ).astype("bool")NEWLINENEWLINE result = Dataset(NEWLINE data_vars={NEWLINE "var1": (("dim1",), [0, 1]),NEWLINE "var2": (("dim1",), [1, 2]),NEWLINE "var3": (("dim1",), [0, 1]),NEWLINE }NEWLINE ).isin(test_elements)NEWLINENEWLINE assert_equal(result, expected)NEWLINENEWLINENEWLINE@pytest.mark.skipif(not has_dask, reason="requires dask")NEWLINE@pytest.mark.parametrize("test_elements", ([1, 2], np.array([1, 2]), DataArray([1, 2])))NEWLINEdef test_isin_dask(test_elements):NEWLINE expected = Dataset(NEWLINE data_vars={NEWLINE "var1": (("dim1",), [0, 1]),NEWLINE "var2": (("dim1",), [1, 1]),NEWLINE "var3": (("dim1",), [0, 1]),NEWLINE }NEWLINE ).astype("bool")NEWLINENEWLINE result = (NEWLINE Dataset(NEWLINE data_vars={NEWLINE "var1": (("dim1",), [0, 1]),NEWLINE "var2": (("dim1",), [1, 2]),NEWLINE "var3": (("dim1",), [0, 1]),NEWLINE }NEWLINE )NEWLINE .chunk(1)NEWLINE .isin(test_elements)NEWLINE .compute()NEWLINE )NEWLINENEWLINE assert_equal(result, expected)NEWLINENEWLINENEWLINEdef test_isin_dataset():NEWLINE ds = Dataset({"x": [1, 2]})NEWLINE with pytest.raises(TypeError):NEWLINE ds.isin(ds)NEWLINENEWLINENEWLINE@pytest.mark.parametrize(NEWLINE "unaligned_coords",NEWLINE (NEWLINE {"x": [2, 1, 0]},NEWLINE {"x": (["x"], np.asarray([2, 1, 0]))},NEWLINE {"x": (["x"], np.asarray([1, 2, 0]))},NEWLINE {"x": pd.Index([2, 1, 0])},NEWLINE {"x": Variable(dims="x", data=[0, 2, 1])},NEWLINE {"x": IndexVariable(dims="x", data=[0, 1, 2])},NEWLINE {"y": 42},NEWLINE {"y": ("x", [2, 1, 0])},NEWLINE {"y": ("x", np.asarray([2, 1, 0]))},NEWLINE {"y": (["x"], np.asarray([2, 1, 0]))},NEWLINE ),NEWLINE)NEWLINE@pytest.mark.parametrize("coords", ({"x": ("x", [0, 1, 2])}, {"x": [0, 1, 2]}))NEWLINEdef test_dataset_constructor_aligns_to_explicit_coords(unaligned_coords, coords):NEWLINENEWLINE a = xr.DataArray([1, 2, 3], dims=["x"], coords=unaligned_coords)NEWLINENEWLINE expected = xr.Dataset(coords=coords)NEWLINE expected["a"] = aNEWLINENEWLINE result = xr.Dataset({"a": a}, coords=coords)NEWLINENEWLINE assert_equal(expected, result)NEWLINENEWLINENEWLINEdef test_error_message_on_set_supplied():NEWLINE with pytest.raises(TypeError, match="has invalid type "):NEWLINE xr.Dataset(dict(date=[1, 2, 3], sec={4}))NEWLINENEWLINENEWLINE@pytest.mark.parametrize("unaligned_coords", ({"y": ("b", np.asarray([2, 1, 0]))},))NEWLINEdef test_constructor_raises_with_invalid_coords(unaligned_coords):NEWLINENEWLINE with pytest.raises(ValueError, match="not a subset of the DataArray dimensions"):NEWLINE xr.DataArray([1, 2, 3], dims=["x"], coords=unaligned_coords)NEWLINENEWLINENEWLINEdef test_dir_expected_attrs(data_set):NEWLINENEWLINE some_expected_attrs = {"pipe", "mean", "isnull", "var1", "dim2", "numbers"}NEWLINE result = dir(data_set)NEWLINE assert set(result) >= some_expected_attrsNEWLINENEWLINENEWLINEdef test_dir_non_string(data_set):NEWLINE # add a numbered key to ensure this doesn't break dirNEWLINE data_set[5] = "foo"NEWLINE result = dir(data_set)NEWLINE assert 5 not in resultNEWLINENEWLINE # GH2172NEWLINE sample_data = np.random.uniform(size=[2, 2000, 10000])NEWLINE x = xr.Dataset({"sample_data": (sample_data.shape, sample_data)})NEWLINE x2 = x["sample_data"]NEWLINE dir(x2)NEWLINENEWLINENEWLINEdef test_dir_unicode(data_set):NEWLINE data_set["unicode"] = "uni"NEWLINE result = dir(data_set)NEWLINE assert "unicode" in resultNEWLINENEWLINENEWLINE@pytest.fixture(params=[1])NEWLINEdef ds(request):NEWLINE if request.param == 1:NEWLINE return Dataset(NEWLINE {NEWLINE "z1": (["y", "x"], np.random.randn(2, 8)),NEWLINE "z2": (["time", "y"], np.random.randn(10, 2)),NEWLINE },NEWLINE {NEWLINE "x": ("x", np.linspace(0, 1.0, 8)),NEWLINE "time": ("time", np.linspace(0, 1.0, 10)),NEWLINE "c": ("y", ["a", "b"]),NEWLINE "y": range(2),NEWLINE },NEWLINE )NEWLINENEWLINE if request.param == 2:NEWLINE return Dataset(NEWLINE {NEWLINE "z1": (["time", "y"], np.random.randn(10, 2)),NEWLINE "z2": (["time"], np.random.randn(10)),NEWLINE "z3": (["x", "time"], np.random.randn(8, 10)),NEWLINE },NEWLINE {NEWLINE "x": ("x", np.linspace(0, 1.0, 8)),NEWLINE "time": ("time", np.linspace(0, 1.0, 10)),NEWLINE "c": ("y", ["a", "b"]),NEWLINE "y": range(2),NEWLINE },NEWLINE )NEWLINENEWLINENEWLINE@pytest.mark.parametrize("dask", [True, False])NEWLINE@pytest.mark.parametrize(("boundary", "side"), [("trim", "left"), ("pad", "right")])NEWLINEdef test_coarsen(ds, dask, boundary, side):NEWLINE if dask and has_dask:NEWLINE ds = ds.chunk({"x": 4})NEWLINENEWLINE actual = ds.coarsen(time=2, x=3, boundary=boundary, side=side).max()NEWLINE assert_equal(NEWLINE actual["z1"], ds["z1"].coarsen(time=2, x=3, boundary=boundary, side=side).max()NEWLINE )NEWLINE # coordinate should be mean by defaultNEWLINE assert_equal(NEWLINE actual["time"],NEWLINE ds["time"].coarsen(time=2, x=3, boundary=boundary, side=side).mean(),NEWLINE )NEWLINENEWLINENEWLINE@pytest.mark.parametrize("dask", [True, False])NEWLINEdef test_coarsen_coords(ds, dask):NEWLINE if dask and has_dask:NEWLINE ds = ds.chunk({"x": 4})NEWLINENEWLINE # check if coord_func worksNEWLINE actual = ds.coarsen(time=2, x=3, boundary="trim", coord_func={"time": "max"}).max()NEWLINE assert_equal(actual["z1"], ds["z1"].coarsen(time=2, x=3, boundary="trim").max())NEWLINE assert_equal(actual["time"], ds["time"].coarsen(time=2, x=3, boundary="trim").max())NEWLINENEWLINE # raise if exactNEWLINE with pytest.raises(ValueError):NEWLINE ds.coarsen(x=3).mean()NEWLINE # should be no errorNEWLINE ds.isel(x=slice(0, 3 * (len(ds["x"]) // 3))).coarsen(x=3).mean()NEWLINENEWLINE # working test with pd.timeNEWLINE da = xr.DataArray(NEWLINE np.linspace(0, 365, num=364),NEWLINE dims="time",NEWLINE coords={"time": pd.date_range("15/12/1999", periods=364)},NEWLINE )NEWLINE actual = da.coarsen(time=2).mean()NEWLINENEWLINENEWLINE@requires_cftimeNEWLINEdef test_coarsen_coords_cftime():NEWLINE times = xr.cftime_range("2000", periods=6)NEWLINE da = xr.DataArray(range(6), [("time", times)])NEWLINE actual = da.coarsen(time=3).mean()NEWLINE expected_times = xr.cftime_range("2000-01-02", freq="3D", periods=2)NEWLINE np.testing.assert_array_equal(actual.time, expected_times)NEWLINENEWLINENEWLINEdef test_rolling_properties(ds):NEWLINE # catching invalid argsNEWLINE with pytest.raises(ValueError, match="exactly one dim/window should"):NEWLINE ds.rolling(time=7, x=2)NEWLINE with pytest.raises(ValueError, match="window must be > 0"):NEWLINE ds.rolling(time=-2)NEWLINE with pytest.raises(ValueError, match="min_periods must be greater than zero"):NEWLINE ds.rolling(time=2, min_periods=0)NEWLINE with pytest.raises(KeyError, match="time2"):NEWLINE ds.rolling(time2=2)NEWLINENEWLINENEWLINE@pytest.mark.parametrize("name", ("sum", "mean", "std", "var", "min", "max", "median"))NEWLINE@pytest.mark.parametrize("center", (True, False, None))NEWLINE@pytest.mark.parametrize("min_periods", (1, None))NEWLINE@pytest.mark.parametrize("key", ("z1", "z2"))NEWLINEdef test_rolling_wrapped_bottleneck(ds, name, center, min_periods, key):NEWLINE bn = pytest.importorskip("bottleneck", minversion="1.1")NEWLINENEWLINE # Test all bottleneck functionsNEWLINE rolling_obj = ds.rolling(time=7, min_periods=min_periods)NEWLINENEWLINE func_name = f"move_{name}"NEWLINE actual = getattr(rolling_obj, name)()NEWLINE if key == "z1": # z1 does not depend on 'Time' axis. Stored as it is.NEWLINE expected = ds[key]NEWLINE elif key == "z2":NEWLINE expected = getattr(bn, func_name)(NEWLINE ds[key].values, window=7, axis=0, min_count=min_periodsNEWLINE )NEWLINE assert_array_equal(actual[key].values, expected)NEWLINENEWLINE # Test centerNEWLINE rolling_obj = ds.rolling(time=7, center=center)NEWLINE actual = getattr(rolling_obj, name)()["time"]NEWLINE assert_equal(actual, ds["time"])NEWLINENEWLINENEWLINE@requires_numbaggNEWLINEdef test_rolling_exp(ds):NEWLINENEWLINE result = ds.rolling_exp(time=10, window_type="span").mean()NEWLINE assert isinstance(result, Dataset)NEWLINENEWLINENEWLINE@pytest.mark.parametrize("center", (True, False))NEWLINE@pytest.mark.parametrize("min_periods", (None, 1, 2, 3))NEWLINE@pytest.mark.parametrize("window", (1, 2, 3, 4))NEWLINEdef test_rolling_pandas_compat(center, window, min_periods):NEWLINE df = pd.DataFrame(NEWLINE {NEWLINE "x": np.random.randn(20),NEWLINE "y": np.random.randn(20),NEWLINE "time": np.linspace(0, 1, 20),NEWLINE }NEWLINE )NEWLINE ds = Dataset.from_dataframe(df)NEWLINENEWLINE if min_periods is not None and window < min_periods:NEWLINE min_periods = windowNEWLINENEWLINE df_rolling = df.rolling(window, center=center, min_periods=min_periods).mean()NEWLINE ds_rolling = ds.rolling(index=window, center=center, min_periods=min_periods).mean()NEWLINENEWLINE np.testing.assert_allclose(df_rolling["x"].values, ds_rolling["x"].values)NEWLINE np.testing.assert_allclose(df_rolling.index, ds_rolling["index"])NEWLINENEWLINENEWLINE@pytest.mark.parametrize("center", (True, False))NEWLINE@pytest.mark.parametrize("window", (1, 2, 3, 4))NEWLINEdef test_rolling_construct(center, window):NEWLINE df = pd.DataFrame(NEWLINE {NEWLINE "x": np.random.randn(20),NEWLINE "y": np.random.randn(20),NEWLINE "time": np.linspace(0, 1, 20),NEWLINE }NEWLINE )NEWLINENEWLINE ds = Dataset.from_dataframe(df)NEWLINE df_rolling = df.rolling(window, center=center, min_periods=1).mean()NEWLINE ds_rolling = ds.rolling(index=window, center=center)NEWLINENEWLINE ds_rolling_mean = ds_rolling.construct("window").mean("window")NEWLINE np.testing.assert_allclose(df_rolling["x"].values, ds_rolling_mean["x"].values)NEWLINE np.testing.assert_allclose(df_rolling.index, ds_rolling_mean["index"])NEWLINENEWLINE # with strideNEWLINE ds_rolling_mean = ds_rolling.construct("window", stride=2).mean("window")NEWLINE np.testing.assert_allclose(df_rolling["x"][::2].values, ds_rolling_mean["x"].values)NEWLINE np.testing.assert_allclose(df_rolling.index[::2], ds_rolling_mean["index"])NEWLINE # with fill_valueNEWLINE ds_rolling_mean = ds_rolling.construct("window", stride=2, fill_value=0.0).mean(NEWLINE "window"NEWLINE )NEWLINE assert (ds_rolling_mean.isnull().sum() == 0).to_array(dim="vars").all()NEWLINE assert (ds_rolling_mean["x"] == 0.0).sum() >= 0NEWLINENEWLINENEWLINE@pytest.mark.slowNEWLINE@pytest.mark.parametrize("ds", (1, 2), indirect=True)NEWLINE@pytest.mark.parametrize("center", (True, False))NEWLINE@pytest.mark.parametrize("min_periods", (None, 1, 2, 3))NEWLINE@pytest.mark.parametrize("window", (1, 2, 3, 4))NEWLINE@pytest.mark.parametrize("name", ("sum", "mean", "std", "var", "min", "max", "median"))NEWLINEdef test_rolling_reduce(ds, center, min_periods, window, name):NEWLINENEWLINE if min_periods is not None and window < min_periods:NEWLINE min_periods = windowNEWLINENEWLINE if name == "std" and window == 1:NEWLINE pytest.skip("std with window == 1 is unstable in bottleneck")NEWLINENEWLINE rolling_obj = ds.rolling(time=window, center=center, min_periods=min_periods)NEWLINENEWLINE # add nan prefix to numpy methods to get similar behavior as bottleneckNEWLINE actual = rolling_obj.reduce(getattr(np, "nan%s" % name))NEWLINE expected = getattr(rolling_obj, name)()NEWLINE assert_allclose(actual, expected)NEWLINE assert ds.dims == actual.dimsNEWLINE # make sure the order of data_var are not changed.NEWLINE assert list(ds.data_vars.keys()) == list(actual.data_vars.keys())NEWLINENEWLINE # Make sure the dimension order is restoredNEWLINE for key, src_var in ds.data_vars.items():NEWLINE assert src_var.dims == actual[key].dimsNEWLINENEWLINENEWLINEdef test_raise_no_warning_for_nan_in_binary_ops():NEWLINE with pytest.warns(None) as record:NEWLINE Dataset(data_vars={"x": ("y", [1, 2, np.NaN])}) > 0NEWLINE assert len(record) == 0NEWLINENEWLINENEWLINE@pytest.mark.parametrize("dask", [True, False])NEWLINE@pytest.mark.parametrize("edge_order", [1, 2])NEWLINEdef test_differentiate(dask, edge_order):NEWLINE rs = np.random.RandomState(42)NEWLINE coord = [0.2, 0.35, 0.4, 0.6, 0.7, 0.75, 0.76, 0.8]NEWLINENEWLINE da = xr.DataArray(NEWLINE rs.randn(8, 6),NEWLINE dims=["x", "y"],NEWLINE coords={"x": coord, "z": 3, "x2d": (("x", "y"), rs.randn(8, 6))},NEWLINE )NEWLINE if dask and has_dask:NEWLINE da = da.chunk({"x": 4})NEWLINENEWLINE ds = xr.Dataset({"var": da})NEWLINENEWLINE # along xNEWLINE actual = da.differentiate("x", edge_order)NEWLINE expected_x = xr.DataArray(NEWLINE np.gradient(da, da["x"], axis=0, edge_order=edge_order),NEWLINE dims=da.dims,NEWLINE coords=da.coords,NEWLINE )NEWLINE assert_equal(expected_x, actual)NEWLINE assert_equal(NEWLINE ds["var"].differentiate("x", edge_order=edge_order),NEWLINE ds.differentiate("x", edge_order=edge_order)["var"],NEWLINE )NEWLINE # coordinate should not changeNEWLINE assert_equal(da["x"], actual["x"])NEWLINENEWLINE # along yNEWLINE actual = da.differentiate("y", edge_order)NEWLINE expected_y = xr.DataArray(NEWLINE np.gradient(da, da["y"], axis=1, edge_order=edge_order),NEWLINE dims=da.dims,NEWLINE coords=da.coords,NEWLINE )NEWLINE assert_equal(expected_y, actual)NEWLINE assert_equal(actual, ds.differentiate("y", edge_order=edge_order)["var"])NEWLINE assert_equal(NEWLINE ds["var"].differentiate("y", edge_order=edge_order),NEWLINE ds.differentiate("y", edge_order=edge_order)["var"],NEWLINE )NEWLINENEWLINE with pytest.raises(ValueError):NEWLINE da.differentiate("x2d")NEWLINENEWLINENEWLINE@pytest.mark.parametrize("dask", [True, False])NEWLINEdef test_differentiate_datetime(dask):NEWLINE rs = np.random.RandomState(42)NEWLINE coord = np.array(NEWLINE [NEWLINE "2004-07-13",NEWLINE "2006-01-13",NEWLINE "2010-08-13",NEWLINE "2010-09-13",NEWLINE "2010-10-11",NEWLINE "2010-12-13",NEWLINE "2011-02-13",NEWLINE "2012-08-13",NEWLINE ],NEWLINE dtype="datetime64",NEWLINE )NEWLINENEWLINE da = xr.DataArray(NEWLINE rs.randn(8, 6),NEWLINE dims=["x", "y"],NEWLINE coords={"x": coord, "z": 3, "x2d": (("x", "y"), rs.randn(8, 6))},NEWLINE )NEWLINE if dask and has_dask:NEWLINE da = da.chunk({"x": 4})NEWLINENEWLINE # along xNEWLINE actual = da.differentiate("x", edge_order=1, datetime_unit="D")NEWLINE expected_x = xr.DataArray(NEWLINE np.gradient(NEWLINE da, da["x"].variable._to_numeric(datetime_unit="D"), axis=0, edge_order=1NEWLINE ),NEWLINE dims=da.dims,NEWLINE coords=da.coords,NEWLINE )NEWLINE assert_equal(expected_x, actual)NEWLINENEWLINE actual2 = da.differentiate("x", edge_order=1, datetime_unit="h")NEWLINE assert np.allclose(actual, actual2 * 24)NEWLINENEWLINE # for datetime variableNEWLINE actual = da["x"].differentiate("x", edge_order=1, datetime_unit="D")NEWLINE assert np.allclose(actual, 1.0)NEWLINENEWLINE # with different date unitNEWLINE da = xr.DataArray(coord.astype("datetime64[ms]"), dims=["x"], coords={"x": coord})NEWLINE actual = da.differentiate("x", edge_order=1)NEWLINE assert np.allclose(actual, 1.0)NEWLINENEWLINENEWLINE@pytest.mark.skipif(not has_cftime, reason="Test requires cftime.")NEWLINE@pytest.mark.parametrize("dask", [True, False])NEWLINEdef test_differentiate_cftime(dask):NEWLINE rs = np.random.RandomState(42)NEWLINE coord = xr.cftime_range("2000", periods=8, freq="2M")NEWLINENEWLINE da = xr.DataArray(NEWLINE rs.randn(8, 6),NEWLINE coords={"time": coord, "z": 3, "t2d": (("time", "y"), rs.randn(8, 6))},NEWLINE dims=["time", "y"],NEWLINE )NEWLINENEWLINE if dask and has_dask:NEWLINE da = da.chunk({"time": 4})NEWLINENEWLINE actual = da.differentiate("time", edge_order=1, datetime_unit="D")NEWLINE expected_data = np.gradient(NEWLINE da, da["time"].variable._to_numeric(datetime_unit="D"), axis=0, edge_order=1NEWLINE )NEWLINE expected = xr.DataArray(expected_data, coords=da.coords, dims=da.dims)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE actual2 = da.differentiate("time", edge_order=1, datetime_unit="h")NEWLINE assert_allclose(actual, actual2 * 24)NEWLINENEWLINE # Test the differentiation of datetimes themselvesNEWLINE actual = da["time"].differentiate("time", edge_order=1, datetime_unit="D")NEWLINE assert_allclose(actual, xr.ones_like(da["time"]).astype(float))NEWLINENEWLINENEWLINE@pytest.mark.parametrize("dask", [True, False])NEWLINEdef test_integrate(dask):NEWLINE rs = np.random.RandomState(42)NEWLINE coord = [0.2, 0.35, 0.4, 0.6, 0.7, 0.75, 0.76, 0.8]NEWLINENEWLINE da = xr.DataArray(NEWLINE rs.randn(8, 6),NEWLINE dims=["x", "y"],NEWLINE coords={NEWLINE "x": coord,NEWLINE "x2": (("x",), rs.randn(8)),NEWLINE "z": 3,NEWLINE "x2d": (("x", "y"), rs.randn(8, 6)),NEWLINE },NEWLINE )NEWLINE if dask and has_dask:NEWLINE da = da.chunk({"x": 4})NEWLINENEWLINE ds = xr.Dataset({"var": da})NEWLINENEWLINE # along xNEWLINE actual = da.integrate("x")NEWLINE # coordinate that contains x should be dropped.NEWLINE expected_x = xr.DataArray(NEWLINE np.trapz(da, da["x"], axis=0),NEWLINE dims=["y"],NEWLINE coords={k: v for k, v in da.coords.items() if "x" not in v.dims},NEWLINE )NEWLINE assert_allclose(expected_x, actual.compute())NEWLINE assert_equal(ds["var"].integrate("x"), ds.integrate("x")["var"])NEWLINENEWLINE # make sure result is also a dask array (if the source is dask array)NEWLINE assert isinstance(actual.data, type(da.data))NEWLINENEWLINE # along yNEWLINE actual = da.integrate("y")NEWLINE expected_y = xr.DataArray(NEWLINE np.trapz(da, da["y"], axis=1),NEWLINE dims=["x"],NEWLINE coords={k: v for k, v in da.coords.items() if "y" not in v.dims},NEWLINE )NEWLINE assert_allclose(expected_y, actual.compute())NEWLINE assert_equal(actual, ds.integrate("y")["var"])NEWLINE assert_equal(ds["var"].integrate("y"), ds.integrate("y")["var"])NEWLINENEWLINE # along x and yNEWLINE actual = da.integrate(("y", "x"))NEWLINE assert actual.ndim == 0NEWLINENEWLINE with pytest.raises(ValueError):NEWLINE da.integrate("x2d")NEWLINENEWLINENEWLINE@pytest.mark.parametrize("dask", [True, False])NEWLINE@pytest.mark.parametrize("which_datetime", ["np", "cftime"])NEWLINEdef test_trapz_datetime(dask, which_datetime):NEWLINE rs = np.random.RandomState(42)NEWLINE if which_datetime == "np":NEWLINE coord = np.array(NEWLINE [NEWLINE "2004-07-13",NEWLINE "2006-01-13",NEWLINE "2010-08-13",NEWLINE "2010-09-13",NEWLINE "2010-10-11",NEWLINE "2010-12-13",NEWLINE "2011-02-13",NEWLINE "2012-08-13",NEWLINE ],NEWLINE dtype="datetime64",NEWLINE )NEWLINE else:NEWLINE if not has_cftime:NEWLINE pytest.skip("Test requires cftime.")NEWLINE coord = xr.cftime_range("2000", periods=8, freq="2D")NEWLINENEWLINE da = xr.DataArray(NEWLINE rs.randn(8, 6),NEWLINE coords={"time": coord, "z": 3, "t2d": (("time", "y"), rs.randn(8, 6))},NEWLINE dims=["time", "y"],NEWLINE )NEWLINENEWLINE if dask and has_dask:NEWLINE da = da.chunk({"time": 4})NEWLINENEWLINE actual = da.integrate("time", datetime_unit="D")NEWLINE expected_data = np.trapz(NEWLINE da, duck_array_ops.datetime_to_numeric(da["time"], datetime_unit="D"), axis=0NEWLINE )NEWLINE expected = xr.DataArray(NEWLINE expected_data,NEWLINE dims=["y"],NEWLINE coords={k: v for k, v in da.coords.items() if "time" not in v.dims},NEWLINE )NEWLINE assert_allclose(expected, actual.compute())NEWLINENEWLINE # make sure result is also a dask array (if the source is dask array)NEWLINE assert isinstance(actual.data, type(da.data))NEWLINENEWLINE actual2 = da.integrate("time", datetime_unit="h")NEWLINE assert_allclose(actual, actual2 / 24.0)NEWLINENEWLINENEWLINEdef test_no_dict():NEWLINE d = Dataset()NEWLINE with pytest.raises(AttributeError):NEWLINE d.__dict__NEWLINENEWLINENEWLINEdef test_subclass_slots():NEWLINE """Test that Dataset subclasses must explicitly define ``__slots__``.NEWLINENEWLINE .. note::NEWLINE As of 0.13.0, this is actually mitigated into a FutureWarning for any classNEWLINE defined outside of the xarray package.NEWLINE """NEWLINE with pytest.raises(AttributeError) as e:NEWLINENEWLINE class MyDS(Dataset):NEWLINE passNEWLINENEWLINE assert str(e.value) == "MyDS must explicitly define __slots__"NEWLINENEWLINENEWLINEdef test_weakref():NEWLINE """Classes with __slots__ are incompatible with the weakref module unless theyNEWLINE explicitly state __weakref__ among their slotsNEWLINE """NEWLINE from weakref import refNEWLINENEWLINE ds = Dataset()NEWLINE r = ref(ds)NEWLINE assert r() is dsNEWLINE import osNEWLINEimport reNEWLINEimport timeNEWLINENEWLINEimport pytestNEWLINEfrom helpers.cluster import ClickHouseClusterNEWLINEfrom helpers.test_tools import assert_eq_with_retry, TSVNEWLINENEWLINEcluster = ClickHouseCluster(__file__)NEWLINEnode = cluster.add_instance('node', main_configs=["configs/config.d/remote_servers.xml"],NEWLINE user_configs=["configs/users.d/row_policy.xml", "configs/users.d/another_user.xml",NEWLINE "configs/users.d/any_join_distinct_right_table_keys.xml"],NEWLINE with_zookeeper=True)NEWLINEnode2 = cluster.add_instance('node2', main_configs=["configs/config.d/remote_servers.xml"],NEWLINE user_configs=["configs/users.d/row_policy.xml", "configs/users.d/another_user.xml",NEWLINE "configs/users.d/any_join_distinct_right_table_keys.xml"],NEWLINE with_zookeeper=True)NEWLINEnodes = [node, node2]NEWLINENEWLINENEWLINEdef copy_policy_xml(local_file_name, reload_immediately=True):NEWLINE script_dir = os.path.dirname(os.path.realpath(__file__))NEWLINE for current_node in nodes:NEWLINE current_node.copy_file_to_container(os.path.join(script_dir, local_file_name),NEWLINE '/etc/clickhouse-server/users.d/row_policy.xml')NEWLINE if reload_immediately:NEWLINE current_node.query("SYSTEM RELOAD CONFIG")NEWLINENEWLINENEWLINE@pytest.fixture(scope="module", autouse=True)NEWLINEdef started_cluster():NEWLINE try:NEWLINE cluster.start()NEWLINENEWLINE for current_node in nodes:NEWLINE current_node.query('''NEWLINE CREATE DATABASE mydb;NEWLINENEWLINE CREATE TABLE mydb.filtered_table1 (a UInt8, b UInt8) ENGINE MergeTree ORDER BY a;NEWLINE INSERT INTO mydb.filtered_table1 values (0, 0), (0, 1), (1, 0), (1, 1);NEWLINENEWLINE CREATE TABLE mydb.table (a UInt8, b UInt8) ENGINE MergeTree ORDER BY a;NEWLINE INSERT INTO mydb.table values (0, 0), (0, 1), (1, 0), (1, 1);NEWLINENEWLINE CREATE TABLE mydb.filtered_table2 (a UInt8, b UInt8, c UInt8, d UInt8) ENGINE MergeTree ORDER BY a;NEWLINE INSERT INTO mydb.filtered_table2 values (0, 0, 0, 0), (1, 2, 3, 4), (4, 3, 2, 1), (0, 0, 6, 0);NEWLINENEWLINE CREATE TABLE mydb.filtered_table3 (a UInt8, b UInt8, c UInt16 ALIAS a + b) ENGINE MergeTree ORDER BY a;NEWLINE INSERT INTO mydb.filtered_table3 values (0, 0), (0, 1), (1, 0), (1, 1);NEWLINENEWLINE CREATE TABLE mydb.`.filtered_table4` (a UInt8, b UInt8, c UInt16 ALIAS a + b) ENGINE MergeTree ORDER BY a;NEWLINE INSERT INTO mydb.`.filtered_table4` values (0, 0), (0, 1), (1, 0), (1, 1);NEWLINENEWLINE CREATE TABLE mydb.local (a UInt8, b UInt8) ENGINE MergeTree ORDER BY a;NEWLINE ''')NEWLINENEWLINE node.query("INSERT INTO mydb.local values (2, 0), (2, 1), (1, 0), (1, 1)")NEWLINE node2.query("INSERT INTO mydb.local values (3, 0), (3, 1), (1, 0), (1, 1)")NEWLINENEWLINE yield clusterNEWLINENEWLINE finally:NEWLINE cluster.shutdown()NEWLINENEWLINENEWLINE@pytest.fixture(autouse=True)NEWLINEdef reset_policies():NEWLINE try:NEWLINE yieldNEWLINE finally:NEWLINE copy_policy_xml('normal_filters.xml')NEWLINE for current_node in nodes:NEWLINE current_node.query("DROP POLICY IF EXISTS pA, pB ON mydb.filtered_table1")NEWLINENEWLINENEWLINEdef test_smoke():NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[0, 0, 0, 0], [0, 0, 6, 0]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 1], [1, 0]])NEWLINENEWLINE assert node.query("SELECT a FROM mydb.filtered_table1") == TSV([[1], [1]])NEWLINE assert node.query("SELECT b FROM mydb.filtered_table1") == TSV([[0], [1]])NEWLINE assert node.query("SELECT a FROM mydb.filtered_table1 WHERE a = 1") == TSV([[1], [1]])NEWLINE assert node.query("SELECT a FROM mydb.filtered_table1 WHERE a IN (1)") == TSV([[1], [1]])NEWLINE assert node.query("SELECT a = 1 FROM mydb.filtered_table1") == TSV([[1], [1]])NEWLINENEWLINE assert node.query("SELECT a FROM mydb.filtered_table3") == TSV([[0], [1]])NEWLINE assert node.query("SELECT b FROM mydb.filtered_table3") == TSV([[1], [0]])NEWLINE assert node.query("SELECT c FROM mydb.filtered_table3") == TSV([[1], [1]])NEWLINE assert node.query("SELECT a + b FROM mydb.filtered_table3") == TSV([[1], [1]])NEWLINE assert node.query("SELECT a FROM mydb.filtered_table3 WHERE c = 1") == TSV([[0], [1]])NEWLINE assert node.query("SELECT c = 1 FROM mydb.filtered_table3") == TSV([[1], [1]])NEWLINE assert node.query("SELECT a + b = 1 FROM mydb.filtered_table3") == TSV([[1], [1]])NEWLINENEWLINENEWLINEdef test_join():NEWLINE assert node.query(NEWLINE "SELECT * FROM mydb.filtered_table1 as t1 ANY LEFT JOIN mydb.filtered_table1 as t2 ON t1.a = t2.b") == TSV(NEWLINE [[1, 0, 1, 1], [1, 1, 1, 1]])NEWLINE assert node.query(NEWLINE "SELECT * FROM mydb.filtered_table1 as t2 ANY RIGHT JOIN mydb.filtered_table1 as t1 ON t2.b = t1.a") == TSV(NEWLINE [[1, 1, 1, 0]])NEWLINENEWLINENEWLINEdef test_cannot_trick_row_policy_with_keyword_with():NEWLINE assert node.query("WITH 0 AS a SELECT a FROM mydb.filtered_table1") == TSV([[0], [0]])NEWLINE assert node.query("WITH 0 AS a SELECT b FROM mydb.filtered_table1") == TSV([[0], [1]])NEWLINENEWLINE assert node.query("WITH 0 AS a SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT * FROM mydb.filtered_table1 WHERE a >= 0 AND b >= 0 SETTINGS optimize_move_to_prewhere = 0") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT * FROM mydb.filtered_table1 PREWHERE a >= 0 AND b >= 0") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT * FROM mydb.filtered_table1 PREWHERE a >= 0 WHERE b >= 0") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT * FROM mydb.filtered_table1 PREWHERE b >= 0 WHERE a >= 0") == TSV([[1, 0], [1, 1]])NEWLINENEWLINE assert node.query("WITH 0 AS a SELECT a, b FROM mydb.filtered_table1") == TSV([[0, 0], [0, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT a, b FROM mydb.filtered_table1 WHERE a >= 0 AND b >= 0 SETTINGS optimize_move_to_prewhere = 0") == TSV([[0, 0], [0, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT a, b FROM mydb.filtered_table1 PREWHERE a >= 0 AND b >= 0") == TSV([[0, 0], [0, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT a, b FROM mydb.filtered_table1 PREWHERE a >= 0 WHERE b >= 0") == TSV([[0, 0], [0, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT a, b FROM mydb.filtered_table1 PREWHERE b >= 0 WHERE a >= 0") == TSV([[0, 0], [0, 1]])NEWLINENEWLINE assert node.query("WITH 0 AS c SELECT * FROM mydb.filtered_table3") == TSV([[0, 1], [1, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT * FROM mydb.filtered_table3 WHERE c >= 0 AND a >= 0 SETTINGS optimize_move_to_prewhere = 0") == TSV([[0, 1], [1, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT * FROM mydb.filtered_table3 PREWHERE c >= 0 AND a >= 0") == TSV([[0, 1], [1, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT * FROM mydb.filtered_table3 PREWHERE c >= 0 WHERE a >= 0") == TSV([[0, 1], [1, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT * FROM mydb.filtered_table3 PREWHERE a >= 0 WHERE c >= 0") == TSV([[0, 1], [1, 0]])NEWLINENEWLINE assert node.query("WITH 0 AS c SELECT a, b, c FROM mydb.filtered_table3") == TSV([[0, 1, 0], [1, 0, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT a, b, c FROM mydb.filtered_table3 WHERE c >= 0 AND a >= 0 SETTINGS optimize_move_to_prewhere = 0") == TSV([[0, 1, 0], [1, 0, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT a, b, c FROM mydb.filtered_table3 PREWHERE c >= 0 AND a >= 0") == TSV([[0, 1, 0], [1, 0, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT a, b, c FROM mydb.filtered_table3 PREWHERE c >= 0 WHERE a >= 0") == TSV([[0, 1, 0], [1, 0, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT a, b, c FROM mydb.filtered_table3 PREWHERE a >= 0 WHERE c >= 0") == TSV([[0, 1, 0], [1, 0, 0]])NEWLINENEWLINENEWLINEdef test_policy_from_users_xml_affects_only_user_assigned():NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1", user="another") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINENEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[0, 0, 0, 0], [0, 0, 6, 0]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2", user="another") == TSV(NEWLINE [[0, 0, 0, 0], [0, 0, 6, 0], [1, 2, 3, 4], [4, 3, 2, 1]])NEWLINENEWLINE assert node.query("SELECT * FROM mydb.local") == TSV([[1, 0], [1, 1], [2, 0], [2, 1]])NEWLINE assert node.query("SELECT * FROM mydb.local", user="another") == TSV([[1, 0], [1, 1]])NEWLINENEWLINENEWLINEdef test_with_prewhere():NEWLINE copy_policy_xml('normal_filter2_table2.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2 WHERE a > 1 SETTINGS optimize_move_to_prewhere = 0") == TSV([[4, 3, 2, 1]])NEWLINE assert node.query("SELECT a FROM mydb.filtered_table2 WHERE a > 1 SETTINGS optimize_move_to_prewhere = 0") == TSV([[4]])NEWLINE assert node.query("SELECT a, b FROM mydb.filtered_table2 WHERE a > 1 SETTINGS optimize_move_to_prewhere = 0") == TSV([[4, 3]])NEWLINE assert node.query("SELECT b, c FROM mydb.filtered_table2 WHERE a > 1 SETTINGS optimize_move_to_prewhere = 0") == TSV([[3, 2]])NEWLINE assert node.query("SELECT d FROM mydb.filtered_table2 WHERE a > 1 SETTINGS optimize_move_to_prewhere = 0") == TSV([[1]])NEWLINENEWLINE assert node.query("SELECT * FROM mydb.filtered_table2 PREWHERE a > 1") == TSV([[4, 3, 2, 1]])NEWLINE assert node.query("SELECT a FROM mydb.filtered_table2 PREWHERE a > 1") == TSV([[4]])NEWLINE assert node.query("SELECT a, b FROM mydb.filtered_table2 PREWHERE a > 1") == TSV([[4, 3]])NEWLINE assert node.query("SELECT b, c FROM mydb.filtered_table2 PREWHERE a > 1") == TSV([[3, 2]])NEWLINE assert node.query("SELECT d FROM mydb.filtered_table2 PREWHERE a > 1") == TSV([[1]])NEWLINENEWLINE assert node.query("SELECT * FROM mydb.filtered_table2 PREWHERE a < 4 WHERE b < 10") == TSV([[1, 2, 3, 4]])NEWLINE assert node.query("SELECT a FROM mydb.filtered_table2 PREWHERE a < 4 WHERE b < 10") == TSV([[1]])NEWLINE assert node.query("SELECT b FROM mydb.filtered_table2 PREWHERE a < 4 WHERE b < 10") == TSV([[2]])NEWLINE assert node.query("SELECT a, b FROM mydb.filtered_table2 PREWHERE a < 4 WHERE b < 10") == TSV([[1, 2]])NEWLINE assert node.query("SELECT a, c FROM mydb.filtered_table2 PREWHERE a < 4 WHERE b < 10") == TSV([[1, 3]])NEWLINE assert node.query("SELECT b, d FROM mydb.filtered_table2 PREWHERE a < 4 WHERE b < 10") == TSV([[2, 4]])NEWLINE assert node.query("SELECT c, d FROM mydb.filtered_table2 PREWHERE a < 4 WHERE b < 10") == TSV([[3, 4]])NEWLINENEWLINENEWLINEdef test_throwif_error_in_where_with_same_condition_as_filter():NEWLINE copy_policy_xml('normal_filter2_table2.xml')NEWLINE assert 'expected' in node.query_and_get_error("SELECT * FROM mydb.filtered_table2 WHERE throwIf(a > 0, 'expected') = 0 SETTINGS optimize_move_to_prewhere = 0")NEWLINENEWLINENEWLINEdef test_throwif_error_in_prewhere_with_same_condition_as_filter():NEWLINE copy_policy_xml('normal_filter2_table2.xml')NEWLINE assert 'expected' in node.query_and_get_error("SELECT * FROM mydb.filtered_table2 PREWHERE throwIf(a > 0, 'expected') = 0")NEWLINENEWLINENEWLINEdef test_throwif_in_where_doesnt_expose_restricted_data():NEWLINE copy_policy_xml('no_filters.xml')NEWLINE assert 'expected' in node.query_and_get_error("SELECT * FROM mydb.filtered_table2 WHERE throwIf(a = 0, 'expected') = 0 SETTINGS optimize_move_to_prewhere = 0")NEWLINENEWLINE copy_policy_xml('normal_filter2_table2.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2 WHERE throwIf(a = 0, 'pwned') = 0 SETTINGS optimize_move_to_prewhere = 0") == TSV([NEWLINE [1, 2, 3, 4], [4, 3, 2, 1]])NEWLINENEWLINENEWLINEdef test_throwif_in_prewhere_doesnt_expose_restricted_data():NEWLINE copy_policy_xml('no_filters.xml')NEWLINE assert 'expected' in node.query_and_get_error("SELECT * FROM mydb.filtered_table2 PREWHERE throwIf(a = 0, 'expected') = 0")NEWLINENEWLINE copy_policy_xml('normal_filter2_table2.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2 PREWHERE throwIf(a = 0, 'pwned') = 0") == TSV([NEWLINE [1, 2, 3, 4], [4, 3, 2, 1]])NEWLINENEWLINENEWLINEdef test_change_of_users_xml_changes_row_policies():NEWLINE copy_policy_xml('normal_filters.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[0, 0, 0, 0], [0, 0, 6, 0]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 1], [1, 0]])NEWLINENEWLINE copy_policy_xml('all_rows.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV(NEWLINE [[0, 0, 0, 0], [0, 0, 6, 0], [1, 2, 3, 4], [4, 3, 2, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINENEWLINE copy_policy_xml('no_rows.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == ""NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == ""NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == ""NEWLINENEWLINE copy_policy_xml('normal_filters.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[0, 0, 0, 0], [0, 0, 6, 0]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 1], [1, 0]])NEWLINENEWLINE copy_policy_xml('normal_filter2_table2.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[1, 2, 3, 4], [4, 3, 2, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINENEWLINE copy_policy_xml('no_filters.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV(NEWLINE [[0, 0, 0, 0], [0, 0, 6, 0], [1, 2, 3, 4], [4, 3, 2, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINENEWLINE copy_policy_xml('normal_filters.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[0, 0, 0, 0], [0, 0, 6, 0]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 1], [1, 0]])NEWLINENEWLINENEWLINEdef test_reload_users_xml_by_timer():NEWLINE copy_policy_xml('normal_filters.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[0, 0, 0, 0], [0, 0, 6, 0]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 1], [1, 0]])NEWLINENEWLINE time.sleep(1) # The modification time of the 'row_policy.xml' file should be different.NEWLINE copy_policy_xml('all_rows.xml', False)NEWLINE assert_eq_with_retry(node, "SELECT * FROM mydb.filtered_table1", [[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINE assert_eq_with_retry(node, "SELECT * FROM mydb.filtered_table2",NEWLINE [[0, 0, 0, 0], [0, 0, 6, 0], [1, 2, 3, 4], [4, 3, 2, 1]])NEWLINE assert_eq_with_retry(node, "SELECT * FROM mydb.filtered_table3", [[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINENEWLINE time.sleep(1) # The modification time of the 'row_policy.xml' file should be different.NEWLINE copy_policy_xml('normal_filters.xml', False)NEWLINE assert_eq_with_retry(node, "SELECT * FROM mydb.filtered_table1", [[1, 0], [1, 1]])NEWLINE assert_eq_with_retry(node, "SELECT * FROM mydb.filtered_table2", [[0, 0, 0, 0], [0, 0, 6, 0]])NEWLINE assert_eq_with_retry(node, "SELECT * FROM mydb.filtered_table3", [[0, 1], [1, 0]])NEWLINENEWLINENEWLINEdef test_introspection():NEWLINE policies = [NEWLINE ["another ON mydb.filtered_table1", "another", "mydb", "filtered_table1",NEWLINE "6068883a-0e9d-f802-7e22-0144f8e66d3c", "users.xml", "1", "permissive", 0, "['another']", "[]"],NEWLINE ["another ON mydb.filtered_table2", "another", "mydb", "filtered_table2",NEWLINE "c019e957-c60b-d54e-cc52-7c90dac5fb01", "users.xml", "1", "permissive", 0, "['another']", "[]"],NEWLINE ["another ON mydb.filtered_table3", "another", "mydb", "filtered_table3",NEWLINE "4cb080d0-44e8-dbef-6026-346655143628", "users.xml", "1", "permissive", 0, "['another']", "[]"],NEWLINE ["another ON mydb.local", "another", "mydb", "local", "5b23c389-7e18-06bf-a6bc-dd1afbbc0a97", "users.xml",NEWLINE "a = 1", "permissive", 0, "['another']", "[]"],NEWLINE ["default ON mydb.filtered_table1", "default", "mydb", "filtered_table1",NEWLINE "9e8a8f62-4965-2b5e-8599-57c7b99b3549", "users.xml", "a = 1", "permissive", 0, "['default']", "[]"],NEWLINE ["default ON mydb.filtered_table2", "default", "mydb", "filtered_table2",NEWLINE "cffae79d-b9bf-a2ef-b798-019c18470b25", "users.xml", "a + b < 1 or c - d > 5", "permissive", 0, "['default']", "[]"],NEWLINE ["default ON mydb.filtered_table3", "default", "mydb", "filtered_table3",NEWLINE "12fc5cef-e3da-3940-ec79-d8be3911f42b", "users.xml", "c = 1", "permissive", 0, "['default']", "[]"],NEWLINE ["default ON mydb.local", "default", "mydb", "local", "cdacaeb5-1d97-f99d-2bb0-4574f290629c", "users.xml", "1",NEWLINE "permissive", 0, "['default']", "[]"]NEWLINE ]NEWLINE assert node.query("SELECT * from system.row_policies ORDER BY short_name, database, table") == TSV(policies)NEWLINENEWLINENEWLINEdef test_dcl_introspection():NEWLINE assert node.query("SHOW POLICIES") == TSV(NEWLINE ["another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3",NEWLINE "another ON mydb.local", "default ON mydb.filtered_table1", "default ON mydb.filtered_table2",NEWLINE "default ON mydb.filtered_table3", "default ON mydb.local"])NEWLINENEWLINE assert node.query("SHOW POLICIES ON mydb.filtered_table1") == TSV(["another", "default"])NEWLINE assert node.query("SHOW POLICIES ON mydb.local") == TSV(["another", "default"])NEWLINE assert node.query("SHOW POLICIES ON mydb.*") == TSV(NEWLINE ["another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3",NEWLINE "another ON mydb.local", "default ON mydb.filtered_table1", "default ON mydb.filtered_table2",NEWLINE "default ON mydb.filtered_table3", "default ON mydb.local"])NEWLINE assert node.query("SHOW POLICIES default") == TSV(NEWLINE ["default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3",NEWLINE "default ON mydb.local"])NEWLINENEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table1") == "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 AS permissive TO default\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table2") == "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) AS permissive TO default\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table3") == "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 AS permissive TO default\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.local") == "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 AS permissive TO default\n"NEWLINENEWLINE assert node.query("SHOW CREATE POLICY default") == TSV(NEWLINE ["CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 AS permissive TO default"])NEWLINE assert node.query("SHOW CREATE POLICIES ON mydb.filtered_table1") == TSV(NEWLINE ["CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 AS permissive TO default"])NEWLINE assert node.query("SHOW CREATE POLICIES ON mydb.*") == TSV(NEWLINE ["CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY another ON mydb.filtered_table2 FOR SELECT USING 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY another ON mydb.filtered_table3 FOR SELECT USING 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY another ON mydb.local FOR SELECT USING a = 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 AS permissive TO default"])NEWLINE assert node.query("SHOW CREATE POLICIES") == TSV(NEWLINE ["CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY another ON mydb.filtered_table2 FOR SELECT USING 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY another ON mydb.filtered_table3 FOR SELECT USING 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY another ON mydb.local FOR SELECT USING a = 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 AS permissive TO default"])NEWLINENEWLINE expected_access = "CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 AS permissive TO another\n" \NEWLINE "CREATE ROW POLICY another ON mydb.filtered_table2 FOR SELECT USING 1 AS permissive TO another\n" \NEWLINE "CREATE ROW POLICY another ON mydb.filtered_table3 FOR SELECT USING 1 AS permissive TO another\n" \NEWLINE "CREATE ROW POLICY another ON mydb.local FOR SELECT USING a = 1 AS permissive TO another\n" \NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 AS permissive TO default\n" \NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) AS permissive TO default\n" \NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 AS permissive TO default\n" \NEWLINE "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 AS permissive TO default\n"NEWLINE assert expected_access in node.query("SHOW ACCESS")NEWLINENEWLINE copy_policy_xml('all_rows.xml')NEWLINE assert node.query("SHOW POLICIES") == TSV(NEWLINE ["another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3",NEWLINE "default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3"])NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table1") == "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING 1 AS permissive TO default\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table2") == "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING 1 AS permissive TO default\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table3") == "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING 1 AS permissive TO default\n"NEWLINENEWLINE copy_policy_xml('no_rows.xml')NEWLINE assert node.query("SHOW POLICIES") == TSV(NEWLINE ["another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3",NEWLINE "default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3"])NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table1") == "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING NULL AS permissive TO default\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table2") == "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING NULL AS permissive TO default\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table3") == "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING NULL AS permissive TO default\n"NEWLINENEWLINE copy_policy_xml('no_filters.xml')NEWLINE assert node.query("SHOW POLICIES") == ""NEWLINENEWLINENEWLINEdef test_dcl_management():NEWLINE copy_policy_xml('no_filters.xml')NEWLINE assert node.query("SHOW POLICIES") == ""NEWLINENEWLINE node.query("CREATE POLICY pA ON mydb.filtered_table1 FOR SELECT USING ab")NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0]])NEWLINENEWLINE node.query("ALTER POLICY pA ON mydb.filtered_table1 RENAME TO pB")NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0]])NEWLINE assert node.query("SHOW POLICIES ON mydb.filtered_table1") == "pB\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY pB ON mydb.filtered_table1") == "CREATE ROW POLICY pB ON mydb.filtered_table1 FOR SELECT USING a > b AS permissive TO default\n"NEWLINENEWLINE node.query("DROP POLICY pB ON mydb.filtered_table1")NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINE assert node.query("SHOW POLICIES") == ""NEWLINENEWLINENEWLINEdef test_grant_create_row_policy():NEWLINE copy_policy_xml('no_filters.xml')NEWLINE assert node.query("SHOW POLICIES") == ""NEWLINE node.query("CREATE USER X")NEWLINENEWLINE expected_error = "necessary to have grant CREATE ROW POLICY ON mydb.filtered_table1"NEWLINE assert expected_error in node.query_and_get_error("CREATE POLICY pA ON mydb.filtered_table1 FOR SELECT USING a (d + 5) AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 0 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.table FOR SELECT USING a = 0 AS permissive TO default"])NEWLINENEWLINENEWLINEdef test_miscellaneous_engines():NEWLINE node.query("CREATE ROW POLICY OR REPLACE pC ON mydb.other_table FOR SELECT USING a = 1 TO default")NEWLINE assert node.query("SHOW ROW POLICIES ON mydb.other_table") == "pC\n"NEWLINENEWLINE # ReplicatedMergeTreeNEWLINE node.query("DROP TABLE IF EXISTS mydb.other_table")NEWLINE node.query("CREATE TABLE mydb.other_table (a UInt8, b UInt8) ENGINE ReplicatedMergeTree('/clickhouse/tables/00-00/filtered_table1', 'replica1') ORDER BY a")NEWLINE node.query("INSERT INTO mydb.other_table values (0, 0), (0, 1), (1, 0), (1, 1)")NEWLINE assert node.query("SELECT * FROM mydb.other_table") == TSV([[1, 0], [1, 1]])NEWLINENEWLINE # CollapsingMergeTreeNEWLINE node.query("DROP TABLE mydb.other_table")NEWLINE node.query("CREATE TABLE mydb.other_table (a UInt8, b Int8) ENGINE CollapsingMergeTree(b) ORDER BY a")NEWLINE node.query("INSERT INTO mydb.other_table values (0, 1), (0, 1), (1, 1), (1, 1)")NEWLINE assert node.query("SELECT * FROM mydb.other_table") == TSV([[1, 1], [1, 1]])NEWLINENEWLINE # ReplicatedCollapsingMergeTreeNEWLINE node.query("DROP TABLE mydb.other_table")NEWLINE node.query("CREATE TABLE mydb.other_table (a UInt8, b Int8) ENGINE ReplicatedCollapsingMergeTree('/clickhouse/tables/00-01/filtered_table1', 'replica1', b) ORDER BY a")NEWLINE node.query("INSERT INTO mydb.other_table values (0, 1), (0, 1), (1, 1), (1, 1)")NEWLINE assert node.query("SELECT * FROM mydb.other_table") == TSV([[1, 1], [1, 1]])NEWLINENEWLINE node.query("DROP ROW POLICY pC ON mydb.other_table")NEWLINENEWLINE # DistributedMergeTreeNEWLINE node.query("DROP TABLE IF EXISTS mydb.other_table")NEWLINE node.query("CREATE TABLE mydb.other_table (a UInt8, b UInt8) ENGINE Distributed('test_local_cluster', mydb, local)")NEWLINE assert node.query("SELECT * FROM mydb.other_table", user="another") == TSV([[1, 0], [1, 1], [1, 0], [1, 1]])NEWLINE assert node.query("SELECT sum(a), b FROM mydb.other_table GROUP BY b ORDER BY b", user="another") == TSV([[2, 0], [2, 1]])NEWLINENEWLINENEWLINEdef test_policy_on_distributed_table_via_role():NEWLINE node.query("DROP TABLE IF EXISTS local_tbl")NEWLINE node.query("DROP TABLE IF EXISTS dist_tbl")NEWLINENEWLINE node.query("CREATE TABLE local_tbl engine=MergeTree ORDER BY tuple() as select * FROM numbers(10)")NEWLINE node.query("CREATE TABLE dist_tbl ENGINE=Distributed( 'test_cluster_two_shards_localhost', default, local_tbl) AS local_tbl")NEWLINENEWLINE node.query("CREATE ROLE OR REPLACE 'role1'")NEWLINE node.query("CREATE USER OR REPLACE 'user1' DEFAULT ROLE 'role1'")NEWLINENEWLINE node.query("GRANT SELECT ON dist_tbl TO 'role1'")NEWLINE node.query("GRANT SELECT ON local_tbl TO 'role1'")NEWLINENEWLINE node.query("CREATE ROW POLICY OR REPLACE 'all_data' ON dist_tbl, local_tbl USING 1 TO ALL EXCEPT 'role1'")NEWLINE node.query("CREATE ROW POLICY OR REPLACE 'role1_data' ON dist_tbl, local_tbl USING number % 2 = 0 TO 'role1'")NEWLINENEWLINE assert node.query("SELECT * FROM local_tbl SETTINGS prefer_localhost_replica=0", user="user1") == TSV([[0], [2], [4], [6], [8]])NEWLINE assert node.query("SELECT * FROM dist_tbl SETTINGS prefer_localhost_replica=0", user="user1") == TSV([[0], [2], [4], [6], [8], [0], [2], [4], [6], [8]])NEWLINE NEWLINEimport osNEWLINEimport timeNEWLINEimport signalNEWLINEimport socketNEWLINEimport loggingNEWLINEimport unittestNEWLINEimport BaseHTTPServerNEWLINENEWLINEimport redisNEWLINEimport requestsNEWLINENEWLINENEWLINElogger = logging.getLogger(__name__)NEWLINElogging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',NEWLINE level=logging.DEBUG)NEWLINENEWLINENEWLINEclass HTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):NEWLINENEWLINE def __init__(self, *args, **kwargs):NEWLINE BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, *args, **kwargs)NEWLINENEWLINE def do_GET(self):NEWLINE self.send_response(self.server._code)NEWLINE body = self.server._body if self.server._body else 'This is a body'NEWLINE self.send_header('Content-Length', len(body))NEWLINE if self.server._headers:NEWLINE for header in self.server._headers:NEWLINE self.send_header(*header)NEWLINE self.send_header('Connection', 'close')NEWLINE self.end_headers()NEWLINE self.wfile.write(body)NEWLINE self.wfile.flush()NEWLINENEWLINE def do_HEAD(self):NEWLINE return self.do_GET()NEWLINENEWLINENEWLINEclass TestCase(unittest.TestCase):NEWLINENEWLINE def __init__(self, *args, **kwargs):NEWLINE unittest.TestCase.__init__(self, *args, **kwargs)NEWLINE self.redis = redis.StrictRedis(os.getenv('REDIS_ADDRESS', 'localhost'), os.getenv('REDIS_PORT', 6379))NEWLINE self.check_ready()NEWLINE self._httpd_pids = []NEWLINE self._frontends = []NEWLINE self.addCleanup(self.stop_all_httpd)NEWLINE self.addCleanup(self.unregister_all_frontends)NEWLINENEWLINE def check_ready(self):NEWLINE """ Makes sure the activechecker is running """NEWLINE r = NoneNEWLINE try:NEWLINE r = requests.get('http://localhost:1080', headers={'Host': '__ping__'})NEWLINE except Exception:NEWLINE passNEWLINE if r is None or r.status_code != 200:NEWLINE self.fail('Hipache should run on port 1080: \n'NEWLINE '$ hipache -c config/config_test.json')NEWLINENEWLINE def stop_all_httpd(self):NEWLINE if not self._httpd_pids:NEWLINE returnNEWLINE for pid in self._httpd_pids:NEWLINE os.kill(pid, signal.SIGKILL)NEWLINE logger.info('httpd killed. PID: {0}'.format(pid))NEWLINE os.wait()NEWLINENEWLINE def spawn_httpd(self, port, code=200, headers=None, body=None):NEWLINE pid = os.fork()NEWLINE if pid > 0:NEWLINE # In the father, wait for the child to be availableNEWLINE while True:NEWLINE r = self.http_request('localhost', port=port)NEWLINE if r > 0:NEWLINE self._httpd_pids.append(pid)NEWLINE logger.info('httpd spawned on port {0}. PID: {1}'.format(port, pid))NEWLINE return pidNEWLINE time.sleep(0.5)NEWLINE # In the child, spawn the httpdNEWLINE httpd = BaseHTTPServer.HTTPServer(('localhost', port), HTTPHandler)NEWLINE httpd._code = codeNEWLINE httpd._headers = headersNEWLINE httpd._body = bodyNEWLINE httpd.serve_forever()NEWLINENEWLINE def stop_httpd(self, pid):NEWLINE os.kill(pid, signal.SIGKILL)NEWLINE logger.info('httpd stopped. PID: {0}'.format(pid))NEWLINE os.wait()NEWLINE if pid in self._httpd_pids:NEWLINE self._httpd_pids.remove(pid)NEWLINENEWLINE def register_frontend(self, frontend, backends_url):NEWLINE self.redis.rpush('frontend:{0}'.format(frontend), frontend, *backends_url)NEWLINE self._frontends.append(frontend)NEWLINENEWLINE def unregister_frontend(self, frontend):NEWLINE self.redis.delete('frontend:{0}'.format(frontend))NEWLINE self.redis.delete('dead:{0}'.format(frontend))NEWLINE if frontend in self._frontends:NEWLINE self._frontends.remove(frontend)NEWLINENEWLINE def unregister_all_frontends(self):NEWLINE # Copy the list of frontend since we modify the list inside the loopNEWLINE for frontend in list(self._frontends):NEWLINE self.unregister_frontend(frontend)NEWLINENEWLINE def http_request(self, host, port=1080):NEWLINE try:NEWLINE headers = {'Host': host, 'X-Debug': 'true'}NEWLINE r = requests.get('http://localhost:{0}/'.format(port),NEWLINE headers=headers,NEWLINE timeout=1.0)NEWLINE logger.debug('Frontend: {0}; Headers: {1}; Payload: "{2}"'.format(NEWLINE host, r.headers, r.text))NEWLINE return r.status_codeNEWLINE except (requests.ConnectionError, requests.Timeout, socket.timeout):NEWLINE return -1NEWLINE from __future__ import print_functionNEWLINE# Copyright (c) 2012 Google Inc. All rights reserved.NEWLINE# Use of this source code is governed by a BSD-style license that can beNEWLINE# found in the LICENSE file.NEWLINENEWLINEimport filecmpNEWLINEimport gyp.commonNEWLINEimport gyp.xcodeproj_fileNEWLINEimport gyp.xcode_ninjaNEWLINEimport errnoNEWLINEimport osNEWLINEimport sysNEWLINEimport posixpathNEWLINEimport reNEWLINEimport shutilNEWLINEimport subprocessNEWLINEimport tempfileNEWLINENEWLINENEWLINE# Project files generated by this module will use _intermediate_var as aNEWLINE# custom Xcode setting whose value is a DerivedSources-like directory that'sNEWLINE# project-specific and configuration-specific. The normal choice,NEWLINE# DERIVED_FILE_DIR, is target-specific, which is thought to be too restrictiveNEWLINE# as it is likely that multiple targets within a single project file will wantNEWLINE# to access the same set of generated files. The other option,NEWLINE# PROJECT_DERIVED_FILE_DIR, is unsuitable because while it is project-specific,NEWLINE# it is not configuration-specific. INTERMEDIATE_DIR is defined asNEWLINE# $(PROJECT_DERIVED_FILE_DIR)/$(CONFIGURATION).NEWLINE_intermediate_var = 'INTERMEDIATE_DIR'NEWLINENEWLINE# SHARED_INTERMEDIATE_DIR is the same, except that it is shared among allNEWLINE# targets that share the same BUILT_PRODUCTS_DIR.NEWLINE_shared_intermediate_var = 'SHARED_INTERMEDIATE_DIR'NEWLINENEWLINE_library_search_paths_var = 'LIBRARY_SEARCH_PATHS'NEWLINENEWLINEgenerator_default_variables = {NEWLINE 'EXECUTABLE_PREFIX': '',NEWLINE 'EXECUTABLE_SUFFIX': '',NEWLINE 'STATIC_LIB_PREFIX': 'lib',NEWLINE 'SHARED_LIB_PREFIX': 'lib',NEWLINE 'STATIC_LIB_SUFFIX': '.a',NEWLINE 'SHARED_LIB_SUFFIX': '.dylib',NEWLINE # INTERMEDIATE_DIR is a place for targets to build up intermediate products.NEWLINE # It is specific to each build environment. It is only guaranteed to existNEWLINE # and be constant within the context of a project, corresponding to a singleNEWLINE # input file. Some build environments may allow their intermediate directoryNEWLINE # to be shared on a wider scale, but this is not guaranteed.NEWLINE 'INTERMEDIATE_DIR': '$(%s)' % _intermediate_var,NEWLINE 'OS': 'mac',NEWLINE 'PRODUCT_DIR': '$(BUILT_PRODUCTS_DIR)',NEWLINE 'LIB_DIR': '$(BUILT_PRODUCTS_DIR)',NEWLINE 'RULE_INPUT_ROOT': '$(INPUT_FILE_BASE)',NEWLINE 'RULE_INPUT_EXT': '$(INPUT_FILE_SUFFIX)',NEWLINE 'RULE_INPUT_NAME': '$(INPUT_FILE_NAME)',NEWLINE 'RULE_INPUT_PATH': '$(INPUT_FILE_PATH)',NEWLINE 'RULE_INPUT_DIRNAME': '$(INPUT_FILE_DIRNAME)',NEWLINE 'SHARED_INTERMEDIATE_DIR': '$(%s)' % _shared_intermediate_var,NEWLINE 'CONFIGURATION_NAME': '$(CONFIGURATION)',NEWLINE}NEWLINENEWLINE# The Xcode-specific sections that hold paths.NEWLINEgenerator_additional_path_sections = [NEWLINE 'mac_bundle_resources',NEWLINE 'mac_framework_headers',NEWLINE 'mac_framework_private_headers',NEWLINE # 'mac_framework_dirs', input already handles _dirs endings.NEWLINE]NEWLINENEWLINE# The Xcode-specific keys that exist on targets and aren't moved down toNEWLINE# configurations.NEWLINEgenerator_additional_non_configuration_keys = [NEWLINE 'ios_app_extension',NEWLINE 'ios_watch_app',NEWLINE 'ios_watchkit_extension',NEWLINE 'mac_bundle',NEWLINE 'mac_bundle_resources',NEWLINE 'mac_framework_headers',NEWLINE 'mac_framework_private_headers',NEWLINE 'mac_xctest_bundle',NEWLINE 'xcode_create_dependents_test_runner',NEWLINE]NEWLINENEWLINE# We want to let any rules apply to files that are resources also.NEWLINEgenerator_extra_sources_for_rules = [NEWLINE 'mac_bundle_resources',NEWLINE 'mac_framework_headers',NEWLINE 'mac_framework_private_headers',NEWLINE]NEWLINENEWLINEgenerator_filelist_paths = NoneNEWLINENEWLINE# Xcode's standard set of library directories, which don't need to be duplicatedNEWLINE# in LIBRARY_SEARCH_PATHS. This list is not exhaustive, but that's okay.NEWLINExcode_standard_library_dirs = frozenset([NEWLINE '$(SDKROOT)/usr/lib',NEWLINE '$(SDKROOT)/usr/local/lib',NEWLINE])NEWLINENEWLINEdef CreateXCConfigurationList(configuration_names):NEWLINE xccl = gyp.xcodeproj_file.XCConfigurationList({'buildConfigurations': []})NEWLINE if len(configuration_names) == 0:NEWLINE configuration_names = ['Default']NEWLINE for configuration_name in configuration_names:NEWLINE xcbc = gyp.xcodeproj_file.XCBuildConfiguration({NEWLINE 'name': configuration_name})NEWLINE xccl.AppendProperty('buildConfigurations', xcbc)NEWLINE xccl.SetProperty('defaultConfigurationName', configuration_names[0])NEWLINE return xcclNEWLINENEWLINENEWLINEclass XcodeProject(object):NEWLINE def __init__(self, gyp_path, path, build_file_dict):NEWLINE self.gyp_path = gyp_pathNEWLINE self.path = pathNEWLINE self.project = gyp.xcodeproj_file.PBXProject(path=path)NEWLINE projectDirPath = gyp.common.RelativePath(NEWLINE os.path.dirname(os.path.abspath(self.gyp_path)),NEWLINE os.path.dirname(path) or '.')NEWLINE self.project.SetProperty('projectDirPath', projectDirPath)NEWLINE self.project_file = \NEWLINE gyp.xcodeproj_file.XCProjectFile({'rootObject': self.project})NEWLINE self.build_file_dict = build_file_dictNEWLINENEWLINE # TODO(mark): add destructor that cleans up self.path if created_dir isNEWLINE # True and things didn't complete successfully. Or do something evenNEWLINE # better with "try"?NEWLINE self.created_dir = FalseNEWLINE try:NEWLINE os.makedirs(self.path)NEWLINE self.created_dir = TrueNEWLINE except OSError as e:NEWLINE if e.errno != errno.EEXIST:NEWLINE raiseNEWLINENEWLINE def Finalize1(self, xcode_targets, serialize_all_tests):NEWLINE # Collect a list of all of the build configuration names used by theNEWLINE # various targets in the file. It is very heavily advised to keep eachNEWLINE # target in an entire project (even across multiple project files) usingNEWLINE # the same set of configuration names.NEWLINE configurations = []NEWLINE for xct in self.project.GetProperty('targets'):NEWLINE xccl = xct.GetProperty('buildConfigurationList')NEWLINE xcbcs = xccl.GetProperty('buildConfigurations')NEWLINE for xcbc in xcbcs:NEWLINE name = xcbc.GetProperty('name')NEWLINE if name not in configurations:NEWLINE configurations.append(name)NEWLINENEWLINE # Replace the XCConfigurationList attached to the PBXProject object withNEWLINE # a new one specifying all of the configuration names used by the variousNEWLINE # targets.NEWLINE try:NEWLINE xccl = CreateXCConfigurationList(configurations)NEWLINE self.project.SetProperty('buildConfigurationList', xccl)NEWLINE except:NEWLINE sys.stderr.write("Problem with gyp file %s\n" % self.gyp_path)NEWLINE raiseNEWLINENEWLINE # The need for this setting is explained above where _intermediate_var isNEWLINE # defined. The comments below about wanting to avoid project-wide buildNEWLINE # settings apply here too, but this needs to be set on a project-wide basisNEWLINE # so that files relative to the _intermediate_var setting can be displayedNEWLINE # properly in the Xcode UI.NEWLINE #NEWLINE # Note that for configuration-relative files such as anything relative toNEWLINE # _intermediate_var, for the purposes of UI tree view display, Xcode willNEWLINE # only resolve the configuration name once, when the project file isNEWLINE # opened. If the active build configuration is changed, the project fileNEWLINE # must be closed and reopened if it is desired for the tree view to update.NEWLINE # This is filed as Apple radar 6588391.NEWLINE xccl.SetBuildSetting(_intermediate_var,NEWLINE '$(PROJECT_DERIVED_FILE_DIR)/$(CONFIGURATION)')NEWLINE xccl.SetBuildSetting(_shared_intermediate_var,NEWLINE '$(SYMROOT)/DerivedSources/$(CONFIGURATION)')NEWLINENEWLINE # Set user-specified project-wide build settings and config files. ThisNEWLINE # is intended to be used very sparingly. Really, almost everything shouldNEWLINE # go into target-specific build settings sections. The project-wideNEWLINE # settings are only intended to be used in cases where Xcode attempts toNEWLINE # resolve variable references in a project context as opposed to a targetNEWLINE # context, such as when resolving sourceTree references while building upNEWLINE # the tree tree view for UI display.NEWLINE # Any values set globally are applied to all configurations, then anyNEWLINE # per-configuration values are applied.NEWLINE for xck, xcv in self.build_file_dict.get('xcode_settings', {}).items():NEWLINE xccl.SetBuildSetting(xck, xcv)NEWLINE if 'xcode_config_file' in self.build_file_dict:NEWLINE config_ref = self.project.AddOrGetFileInRootGroup(NEWLINE self.build_file_dict['xcode_config_file'])NEWLINE xccl.SetBaseConfiguration(config_ref)NEWLINE build_file_configurations = self.build_file_dict.get('configurations', {})NEWLINE if build_file_configurations:NEWLINE for config_name in configurations:NEWLINE build_file_configuration_named = \NEWLINE build_file_configurations.get(config_name, {})NEWLINE if build_file_configuration_named:NEWLINE xcc = xccl.ConfigurationNamed(config_name)NEWLINE for xck, xcv in build_file_configuration_named.get('xcode_settings',NEWLINE {}).items():NEWLINE xcc.SetBuildSetting(xck, xcv)NEWLINE if 'xcode_config_file' in build_file_configuration_named:NEWLINE config_ref = self.project.AddOrGetFileInRootGroup(NEWLINE build_file_configurations[config_name]['xcode_config_file'])NEWLINE xcc.SetBaseConfiguration(config_ref)NEWLINENEWLINE # Sort the targets based on how they appeared in the input.NEWLINE # TODO(mark): Like a lot of other things here, this assumes internalNEWLINE # knowledge of PBXProject - in this case, of its "targets" property.NEWLINENEWLINE # ordinary_targets are ordinary targets that are already in the projectNEWLINE # file. run_test_targets are the targets that run unittests and should beNEWLINE # used for the Run All Tests target. support_targets are the action/ruleNEWLINE # targets used by GYP file targets, just kept for the assert check.NEWLINE ordinary_targets = []NEWLINE run_test_targets = []NEWLINE support_targets = []NEWLINENEWLINE # targets is full list of targets in the project.NEWLINE targets = []NEWLINENEWLINE # does the it define it's own "all"?NEWLINE has_custom_all = FalseNEWLINENEWLINE # targets_for_all is the list of ordinary_targets that should be listedNEWLINE # in this project's "All" target. It includes each non_runtest_targetNEWLINE # that does not have suppress_wildcard set.NEWLINE targets_for_all = []NEWLINENEWLINE for target in self.build_file_dict['targets']:NEWLINE target_name = target['target_name']NEWLINE toolset = target['toolset']NEWLINE qualified_target = gyp.common.QualifiedTarget(self.gyp_path, target_name,NEWLINE toolset)NEWLINE xcode_target = xcode_targets[qualified_target]NEWLINE # Make sure that the target being added to the sorted list is already inNEWLINE # the unsorted list.NEWLINE assert xcode_target in self.project._properties['targets']NEWLINE targets.append(xcode_target)NEWLINE ordinary_targets.append(xcode_target)NEWLINE if xcode_target.support_target:NEWLINE support_targets.append(xcode_target.support_target)NEWLINE targets.append(xcode_target.support_target)NEWLINENEWLINE if not int(target.get('suppress_wildcard', False)):NEWLINE targets_for_all.append(xcode_target)NEWLINENEWLINE if target_name.lower() == 'all':NEWLINE has_custom_all = TrueNEWLINENEWLINE # If this target has a 'run_as' attribute, add its target to theNEWLINE # targets, and add it to the test targets.NEWLINE if target.get('run_as'):NEWLINE # Make a target to run something. It should have oneNEWLINE # dependency, the parent xcode target.NEWLINE xccl = CreateXCConfigurationList(configurations)NEWLINE run_target = gyp.xcodeproj_file.PBXAggregateTarget({NEWLINE 'name': 'Run ' + target_name,NEWLINE 'productName': xcode_target.GetProperty('productName'),NEWLINE 'buildConfigurationList': xccl,NEWLINE },NEWLINE parent=self.project)NEWLINE run_target.AddDependency(xcode_target)NEWLINENEWLINE command = target['run_as']NEWLINE script = ''NEWLINE if command.get('working_directory'):NEWLINE script = script + 'cd "%s"\n' % \NEWLINE gyp.xcodeproj_file.ConvertVariablesToShellSyntax(NEWLINE command.get('working_directory'))NEWLINENEWLINE if command.get('environment'):NEWLINE script = script + "\n".join(NEWLINE ['export %s="%s"' %NEWLINE (key, gyp.xcodeproj_file.ConvertVariablesToShellSyntax(val))NEWLINE for (key, val) in command.get('environment').items()]) + "\n"NEWLINENEWLINE # Some test end up using sockets, files on disk, etc. and can getNEWLINE # confused if more then one test runs at a time. The generatorNEWLINE # flag 'xcode_serialize_all_test_runs' controls the forcing of allNEWLINE # tests serially. It defaults to True. To get serial runs thisNEWLINE # little bit of python does the same as the linux flock utility toNEWLINE # make sure only one runs at a time.NEWLINE command_prefix = ''NEWLINE if serialize_all_tests:NEWLINE command_prefix = \NEWLINE"""python -c "import fcntl, subprocess, sysNEWLINEfile = open('$TMPDIR/GYP_serialize_test_runs', 'a')NEWLINEfcntl.flock(file.fileno(), fcntl.LOCK_EX)NEWLINEsys.exit(subprocess.call(sys.argv[1:]))" """NEWLINENEWLINE # If we were unable to exec for some reason, we want to exitNEWLINE # with an error, and fixup variable references to be shellNEWLINE # syntax instead of xcode syntax.NEWLINE script = script + 'exec ' + command_prefix + '%s\nexit 1\n' % \NEWLINE gyp.xcodeproj_file.ConvertVariablesToShellSyntax(NEWLINE gyp.common.EncodePOSIXShellList(command.get('action')))NEWLINENEWLINE ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({NEWLINE 'shellScript': script,NEWLINE 'showEnvVarsInLog': 0,NEWLINE })NEWLINE run_target.AppendProperty('buildPhases', ssbp)NEWLINENEWLINE # Add the run target to the project file.NEWLINE targets.append(run_target)NEWLINE run_test_targets.append(run_target)NEWLINE xcode_target.test_runner = run_targetNEWLINENEWLINENEWLINE # Make sure that the list of targets being replaced is the same length asNEWLINE # the one replacing it, but allow for the added test runner targets.NEWLINE assert len(self.project._properties['targets']) == \NEWLINE len(ordinary_targets) + len(support_targets)NEWLINENEWLINE self.project._properties['targets'] = targetsNEWLINENEWLINE # Get rid of unnecessary levels of depth in groups like the Source group.NEWLINE self.project.RootGroupsTakeOverOnlyChildren(True)NEWLINENEWLINE # Sort the groups nicely. Do this after sorting the targets, because theNEWLINE # Products group is sorted based on the order of the targets.NEWLINE self.project.SortGroups()NEWLINENEWLINE # Create an "All" target if there's more than one target in this projectNEWLINE # file and the project didn't define its own "All" target. Put a generatedNEWLINE # "All" target first so that people opening up the project for the firstNEWLINE # time will build everything by default.NEWLINE if len(targets_for_all) > 1 and not has_custom_all:NEWLINE xccl = CreateXCConfigurationList(configurations)NEWLINE all_target = gyp.xcodeproj_file.PBXAggregateTarget(NEWLINE {NEWLINE 'buildConfigurationList': xccl,NEWLINE 'name': 'All',NEWLINE },NEWLINE parent=self.project)NEWLINENEWLINE for target in targets_for_all:NEWLINE all_target.AddDependency(target)NEWLINENEWLINE # TODO(mark): This is evil because it relies on internal knowledge ofNEWLINE # PBXProject._properties. It's important to get the "All" target first,NEWLINE # though.NEWLINE self.project._properties['targets'].insert(0, all_target)NEWLINENEWLINE # The same, but for run_test_targets.NEWLINE if len(run_test_targets) > 1:NEWLINE xccl = CreateXCConfigurationList(configurations)NEWLINE run_all_tests_target = gyp.xcodeproj_file.PBXAggregateTarget(NEWLINE {NEWLINE 'buildConfigurationList': xccl,NEWLINE 'name': 'Run All Tests',NEWLINE },NEWLINE parent=self.project)NEWLINE for run_test_target in run_test_targets:NEWLINE run_all_tests_target.AddDependency(run_test_target)NEWLINENEWLINE # Insert after the "All" target, which must exist if there is more thanNEWLINE # one run_test_target.NEWLINE self.project._properties['targets'].insert(1, run_all_tests_target)NEWLINENEWLINE def Finalize2(self, xcode_targets, xcode_target_to_target_dict):NEWLINE # Finalize2 needs to happen in a separate step because the process ofNEWLINE # updating references to other projects depends on the ordering of targetsNEWLINE # within remote project files. Finalize1 is responsible for sorting duty,NEWLINE # and once all project files are sorted, Finalize2 can come in and updateNEWLINE # these references.NEWLINENEWLINE # To support making a "test runner" target that will run all the testsNEWLINE # that are direct dependents of any given target, we look forNEWLINE # xcode_create_dependents_test_runner being set on an Aggregate target,NEWLINE # and generate a second target that will run the tests runners found underNEWLINE # the marked target.NEWLINE for bf_tgt in self.build_file_dict['targets']:NEWLINE if int(bf_tgt.get('xcode_create_dependents_test_runner', 0)):NEWLINE tgt_name = bf_tgt['target_name']NEWLINE toolset = bf_tgt['toolset']NEWLINE qualified_target = gyp.common.QualifiedTarget(self.gyp_path,NEWLINE tgt_name, toolset)NEWLINE xcode_target = xcode_targets[qualified_target]NEWLINE if isinstance(xcode_target, gyp.xcodeproj_file.PBXAggregateTarget):NEWLINE # Collect all the run test targets.NEWLINE all_run_tests = []NEWLINE pbxtds = xcode_target.GetProperty('dependencies')NEWLINE for pbxtd in pbxtds:NEWLINE pbxcip = pbxtd.GetProperty('targetProxy')NEWLINE dependency_xct = pbxcip.GetProperty('remoteGlobalIDString')NEWLINE if hasattr(dependency_xct, 'test_runner'):NEWLINE all_run_tests.append(dependency_xct.test_runner)NEWLINENEWLINE # Directly depend on all the runners as they depend on the targetNEWLINE # that builds them.NEWLINE if len(all_run_tests) > 0:NEWLINE run_all_target = gyp.xcodeproj_file.PBXAggregateTarget({NEWLINE 'name': 'Run %s Tests' % tgt_name,NEWLINE 'productName': tgt_name,NEWLINE },NEWLINE parent=self.project)NEWLINE for run_test_target in all_run_tests:NEWLINE run_all_target.AddDependency(run_test_target)NEWLINENEWLINE # Insert the test runner after the related target.NEWLINE idx = self.project._properties['targets'].index(xcode_target)NEWLINE self.project._properties['targets'].insert(idx + 1, run_all_target)NEWLINENEWLINE # Update all references to other projects, to make sure that the lists ofNEWLINE # remote products are complete. Otherwise, Xcode will fill them in whenNEWLINE # it opens the project file, which will result in unnecessary diffs.NEWLINE # TODO(mark): This is evil because it relies on internal knowledge ofNEWLINE # PBXProject._other_pbxprojects.NEWLINE for other_pbxproject in self.project._other_pbxprojects.keys():NEWLINE self.project.AddOrGetProjectReference(other_pbxproject)NEWLINENEWLINE self.project.SortRemoteProductReferences()NEWLINENEWLINE # Give everything an ID.NEWLINE self.project_file.ComputeIDs()NEWLINENEWLINE # Make sure that no two objects in the project file have the same ID. IfNEWLINE # multiple objects wind up with the same ID, upon loading the file, XcodeNEWLINE # will only recognize one object (the last one in the file?) and theNEWLINE # results are unpredictable.NEWLINE self.project_file.EnsureNoIDCollisions()NEWLINENEWLINE def Write(self):NEWLINE # Write the project file to a temporary location first. Xcode watches forNEWLINE # changes to the project file and presents a UI sheet offering to reloadNEWLINE # the project when it does change. However, in some cases, especially whenNEWLINE # multiple projects are open or when Xcode is busy, things don't work soNEWLINE # seamlessly. Sometimes, Xcode is able to detect that a project file hasNEWLINE # changed but can't unload it because something else is referencing it.NEWLINE # To mitigate this problem, and to avoid even having Xcode present the UINEWLINE # sheet when an open project is rewritten for inconsequential changes, theNEWLINE # project file is written to a temporary file in the xcodeproj directoryNEWLINE # first. The new temporary file is then compared to the existing projectNEWLINE # file, if any. If they differ, the new file replaces the old; otherwise,NEWLINE # the new project file is simply deleted. Xcode properly detects a fileNEWLINE # being renamed over an open project file as a change and so it remainsNEWLINE # able to present the "project file changed" sheet under this system.NEWLINE # Writing to a temporary file first also avoids the possible problem ofNEWLINE # Xcode rereading an incomplete project file.NEWLINE (output_fd, new_pbxproj_path) = \NEWLINE tempfile.mkstemp(suffix='.tmp', prefix='project.pbxproj.gyp.',NEWLINE dir=self.path)NEWLINENEWLINE try:NEWLINE output_file = os.fdopen(output_fd, 'wb')NEWLINENEWLINE self.project_file.Print(output_file)NEWLINE output_file.close()NEWLINENEWLINE pbxproj_path = os.path.join(self.path, 'project.pbxproj')NEWLINENEWLINE same = FalseNEWLINE try:NEWLINE same = filecmp.cmp(pbxproj_path, new_pbxproj_path, False)NEWLINE except OSError as e:NEWLINE if e.errno != errno.ENOENT:NEWLINE raiseNEWLINENEWLINE if same:NEWLINE # The new file is identical to the old one, just get rid of the newNEWLINE # one.NEWLINE os.unlink(new_pbxproj_path)NEWLINE else:NEWLINE # The new file is different from the old one, or there is no old one.NEWLINE # Rename the new file to the permanent name.NEWLINE #NEWLINE # tempfile.mkstemp uses an overly restrictive mode, resulting in aNEWLINE # file that can only be read by the owner, regardless of the umask.NEWLINE # There's no reason to not respect the umask here, which means thatNEWLINE # an extra hoop is required to fetch it and reset the new file's mode.NEWLINE #NEWLINE # No way to get the umask without setting a new one? Set a safe oneNEWLINE # and then set it back to the old value.NEWLINE umask = os.umask(0o77)NEWLINE os.umask(umask)NEWLINENEWLINE os.chmod(new_pbxproj_path, 0o666 & ~umask)NEWLINE os.rename(new_pbxproj_path, pbxproj_path)NEWLINENEWLINE except Exception:NEWLINE # Don't leave turds behind. In fact, if this code was responsible forNEWLINE # creating the xcodeproj directory, get rid of that too.NEWLINE os.unlink(new_pbxproj_path)NEWLINE if self.created_dir:NEWLINE shutil.rmtree(self.path, True)NEWLINE raiseNEWLINENEWLINENEWLINEdef AddSourceToTarget(source, type, pbxp, xct):NEWLINE # TODO(mark): Perhaps source_extensions and library_extensions can be made aNEWLINE # little bit fancier.NEWLINE source_extensions = ['c', 'cc', 'cpp', 'cxx', 'm', 'mm', 's', 'swift']NEWLINENEWLINE # .o is conceptually more of a "source" than a "library," but Xcode thinksNEWLINE # of "sources" as things to compile and "libraries" (or "frameworks") asNEWLINE # things to link with. Adding an object file to an Xcode target's frameworksNEWLINE # phase works properly.NEWLINE library_extensions = ['a', 'dylib', 'framework', 'o']NEWLINENEWLINE basename = posixpath.basename(source)NEWLINE (root, ext) = posixpath.splitext(basename)NEWLINE if ext:NEWLINE ext = ext[1:].lower()NEWLINENEWLINE if ext in source_extensions and type != 'none':NEWLINE xct.SourcesPhase().AddFile(source)NEWLINE elif ext in library_extensions and type != 'none':NEWLINE xct.FrameworksPhase().AddFile(source)NEWLINE else:NEWLINE # Files that aren't added to a sources or frameworks build phase can stillNEWLINE # go into the project file, just not as part of a build phase.NEWLINE pbxp.AddOrGetFileInRootGroup(source)NEWLINENEWLINENEWLINEdef AddResourceToTarget(resource, pbxp, xct):NEWLINE # TODO(mark): Combine with AddSourceToTarget above? Or just inline this callNEWLINE # where it's used.NEWLINE xct.ResourcesPhase().AddFile(resource)NEWLINENEWLINENEWLINEdef AddHeaderToTarget(header, pbxp, xct, is_public):NEWLINE # TODO(mark): Combine with AddSourceToTarget above? Or just inline this callNEWLINE # where it's used.NEWLINE settings = '{ATTRIBUTES = (%s, ); }' % ('Private', 'Public')[is_public]NEWLINE xct.HeadersPhase().AddFile(header, settings)NEWLINENEWLINENEWLINE_xcode_variable_re = re.compile(r'(\$\((.*?)\))')NEWLINEdef ExpandXcodeVariables(string, expansions):NEWLINE """Expands Xcode-style $(VARIABLES) in string per the expansions dict.NEWLINENEWLINE In some rare cases, it is appropriate to expand Xcode variables when aNEWLINE project file is generated. For any substring $(VAR) in string, if VAR is aNEWLINE key in the expansions dict, $(VAR) will be replaced with expansions[VAR].NEWLINE Any $(VAR) substring in string for which VAR is not a key in the expansionsNEWLINE dict will remain in the returned string.NEWLINE """NEWLINENEWLINE matches = _xcode_variable_re.findall(string)NEWLINE if matches is None:NEWLINE return stringNEWLINENEWLINE matches.reverse()NEWLINE for match in matches:NEWLINE (to_replace, variable) = matchNEWLINE if not variable in expansions:NEWLINE continueNEWLINENEWLINE replacement = expansions[variable]NEWLINE string = re.sub(re.escape(to_replace), replacement, string)NEWLINENEWLINE return stringNEWLINENEWLINENEWLINE_xcode_define_re = re.compile(r'([\\\"\' ])')NEWLINEdef EscapeXcodeDefine(s):NEWLINE """We must escape the defines that we give to XCode so that it knows not toNEWLINE split on spaces and to respect backslash and quote literals. However, weNEWLINE must not quote the define, or Xcode will incorrectly intepret variablesNEWLINE especially $(inherited)."""NEWLINE return re.sub(_xcode_define_re, r'\\\1', s)NEWLINENEWLINENEWLINEdef PerformBuild(data, configurations, params):NEWLINE options = params['options']NEWLINENEWLINE for build_file, build_file_dict in data.items():NEWLINE (build_file_root, build_file_ext) = os.path.splitext(build_file)NEWLINE if build_file_ext != '.gyp':NEWLINE continueNEWLINE xcodeproj_path = build_file_root + options.suffix + '.xcodeproj'NEWLINE if options.generator_output:NEWLINE xcodeproj_path = os.path.join(options.generator_output, xcodeproj_path)NEWLINENEWLINE for config in configurations:NEWLINE arguments = ['xcodebuild', '-project', xcodeproj_path]NEWLINE arguments += ['-configuration', config]NEWLINE print("Building [%s]: %s" % (config, arguments))NEWLINE subprocess.check_call(arguments)NEWLINENEWLINENEWLINEdef CalculateGeneratorInputInfo(params):NEWLINE toplevel = params['options'].toplevel_dirNEWLINE if params.get('flavor') == 'ninja':NEWLINE generator_dir = os.path.relpath(params['options'].generator_output or '.')NEWLINE output_dir = params.get('generator_flags', {}).get('output_dir', 'out')NEWLINE output_dir = os.path.normpath(os.path.join(generator_dir, output_dir))NEWLINE qualified_out_dir = os.path.normpath(os.path.join(NEWLINE toplevel, output_dir, 'gypfiles-xcode-ninja'))NEWLINE else:NEWLINE output_dir = os.path.normpath(os.path.join(toplevel, 'xcodebuild'))NEWLINE qualified_out_dir = os.path.normpath(os.path.join(NEWLINE toplevel, output_dir, 'gypfiles'))NEWLINENEWLINE global generator_filelist_pathsNEWLINE generator_filelist_paths = {NEWLINE 'toplevel': toplevel,NEWLINE 'qualified_out_dir': qualified_out_dir,NEWLINE }NEWLINENEWLINENEWLINEdef GenerateOutput(target_list, target_dicts, data, params):NEWLINE # Optionally configure each spec to use ninja as the external builder.NEWLINE ninja_wrapper = params.get('flavor') == 'ninja'NEWLINE if ninja_wrapper:NEWLINE (target_list, target_dicts, data) = \NEWLINE gyp.xcode_ninja.CreateWrapper(target_list, target_dicts, data, params)NEWLINENEWLINE options = params['options']NEWLINE generator_flags = params.get('generator_flags', {})NEWLINE parallel_builds = generator_flags.get('xcode_parallel_builds', True)NEWLINE serialize_all_tests = \NEWLINE generator_flags.get('xcode_serialize_all_test_runs', True)NEWLINE upgrade_check_project_version = \NEWLINE generator_flags.get('xcode_upgrade_check_project_version', None)NEWLINENEWLINE # Format upgrade_check_project_version with leading zeros as needed.NEWLINE if upgrade_check_project_version:NEWLINE upgrade_check_project_version = str(upgrade_check_project_version)NEWLINE while len(upgrade_check_project_version) < 4:NEWLINE upgrade_check_project_version = '0' + upgrade_check_project_versionNEWLINENEWLINE skip_excluded_files = \NEWLINE not generator_flags.get('xcode_list_excluded_files', True)NEWLINE xcode_projects = {}NEWLINE for build_file, build_file_dict in data.items():NEWLINE (build_file_root, build_file_ext) = os.path.splitext(build_file)NEWLINE if build_file_ext != '.gyp':NEWLINE continueNEWLINE xcodeproj_path = build_file_root + options.suffix + '.xcodeproj'NEWLINE if options.generator_output:NEWLINE xcodeproj_path = os.path.join(options.generator_output, xcodeproj_path)NEWLINE xcp = XcodeProject(build_file, xcodeproj_path, build_file_dict)NEWLINE xcode_projects[build_file] = xcpNEWLINE pbxp = xcp.projectNEWLINENEWLINE # Set project-level attributes from multiple optionsNEWLINE project_attributes = {}NEWLINE if parallel_builds:NEWLINE project_attributes['BuildIndependentTargetsInParallel'] = 'YES'NEWLINE if upgrade_check_project_version:NEWLINE project_attributes['LastUpgradeCheck'] = upgrade_check_project_versionNEWLINE project_attributes['LastTestingUpgradeCheck'] = \NEWLINE upgrade_check_project_versionNEWLINE project_attributes['LastSwiftUpdateCheck'] = \NEWLINE upgrade_check_project_versionNEWLINE pbxp.SetProperty('attributes', project_attributes)NEWLINENEWLINE # Add gyp/gypi files to projectNEWLINE if not generator_flags.get('standalone'):NEWLINE main_group = pbxp.GetProperty('mainGroup')NEWLINE build_group = gyp.xcodeproj_file.PBXGroup({'name': 'Build'})NEWLINE main_group.AppendChild(build_group)NEWLINE for included_file in build_file_dict['included_files']:NEWLINE build_group.AddOrGetFileByPath(included_file, False)NEWLINENEWLINE xcode_targets = {}NEWLINE xcode_target_to_target_dict = {}NEWLINE for qualified_target in target_list:NEWLINE [build_file, target_name, toolset] = \NEWLINE gyp.common.ParseQualifiedTarget(qualified_target)NEWLINENEWLINE spec = target_dicts[qualified_target]NEWLINE if spec['toolset'] != 'target':NEWLINE raise Exception(NEWLINE 'Multiple toolsets not supported in xcode build (target %s)' %NEWLINE qualified_target)NEWLINE configuration_names = [spec['default_configuration']]NEWLINE for configuration_name in sorted(spec['configurations'].keys()):NEWLINE if configuration_name not in configuration_names:NEWLINE configuration_names.append(configuration_name)NEWLINE xcp = xcode_projects[build_file]NEWLINE pbxp = xcp.projectNEWLINENEWLINE # Set up the configurations for the target according to the list of namesNEWLINE # supplied.NEWLINE xccl = CreateXCConfigurationList(configuration_names)NEWLINENEWLINE # Create an XCTarget subclass object for the target. The type withNEWLINE # "+bundle" appended will be used if the target has "mac_bundle" set.NEWLINE # loadable_modules not in a mac_bundle are mapped toNEWLINE # com.googlecode.gyp.xcode.bundle, a pseudo-type that xcode.py interpretsNEWLINE # to create a single-file mh_bundle.NEWLINE _types = {NEWLINE 'executable': 'com.apple.product-type.tool',NEWLINE 'loadable_module': 'com.googlecode.gyp.xcode.bundle',NEWLINE 'shared_library': 'com.apple.product-type.library.dynamic',NEWLINE 'static_library': 'com.apple.product-type.library.static',NEWLINE 'mac_kernel_extension': 'com.apple.product-type.kernel-extension',NEWLINE 'executable+bundle': 'com.apple.product-type.application',NEWLINE 'loadable_module+bundle': 'com.apple.product-type.bundle',NEWLINE 'loadable_module+xctest': 'com.apple.product-type.bundle.unit-test',NEWLINE 'shared_library+bundle': 'com.apple.product-type.framework',NEWLINE 'executable+extension+bundle': 'com.apple.product-type.app-extension',NEWLINE 'executable+watch+extension+bundle':NEWLINE 'com.apple.product-type.watchkit-extension',NEWLINE 'executable+watch+bundle':NEWLINE 'com.apple.product-type.application.watchapp',NEWLINE 'mac_kernel_extension+bundle': 'com.apple.product-type.kernel-extension',NEWLINE }NEWLINENEWLINE target_properties = {NEWLINE 'buildConfigurationList': xccl,NEWLINE 'name': target_name,NEWLINE }NEWLINENEWLINE type = spec['type']NEWLINE is_xctest = int(spec.get('mac_xctest_bundle', 0))NEWLINE is_bundle = int(spec.get('mac_bundle', 0)) or is_xctestNEWLINE is_app_extension = int(spec.get('ios_app_extension', 0))NEWLINE is_watchkit_extension = int(spec.get('ios_watchkit_extension', 0))NEWLINE is_watch_app = int(spec.get('ios_watch_app', 0))NEWLINE if type != 'none':NEWLINE type_bundle_key = typeNEWLINE if is_xctest:NEWLINE type_bundle_key += '+xctest'NEWLINE assert type == 'loadable_module', (NEWLINE 'mac_xctest_bundle targets must have type loadable_module 'NEWLINE '(target %s)' % target_name)NEWLINE elif is_app_extension:NEWLINE assert is_bundle, ('ios_app_extension flag requires mac_bundle 'NEWLINE '(target %s)' % target_name)NEWLINE type_bundle_key += '+extension+bundle'NEWLINE elif is_watchkit_extension:NEWLINE assert is_bundle, ('ios_watchkit_extension flag requires mac_bundle 'NEWLINE '(target %s)' % target_name)NEWLINE type_bundle_key += '+watch+extension+bundle'NEWLINE elif is_watch_app:NEWLINE assert is_bundle, ('ios_watch_app flag requires mac_bundle 'NEWLINE '(target %s)' % target_name)NEWLINE type_bundle_key += '+watch+bundle'NEWLINE elif is_bundle:NEWLINE type_bundle_key += '+bundle'NEWLINENEWLINE xctarget_type = gyp.xcodeproj_file.PBXNativeTargetNEWLINE try:NEWLINE target_properties['productType'] = _types[type_bundle_key]NEWLINE except KeyError as e:NEWLINE gyp.common.ExceptionAppend(e, "-- unknown product type while "NEWLINE "writing target %s" % target_name)NEWLINE raiseNEWLINE else:NEWLINE xctarget_type = gyp.xcodeproj_file.PBXAggregateTargetNEWLINE assert not is_bundle, (NEWLINE 'mac_bundle targets cannot have type none (target "%s")' %NEWLINE target_name)NEWLINE assert not is_xctest, (NEWLINE 'mac_xctest_bundle targets cannot have type none (target "%s")' %NEWLINE target_name)NEWLINENEWLINE target_product_name = spec.get('product_name')NEWLINE if target_product_name is not None:NEWLINE target_properties['productName'] = target_product_nameNEWLINENEWLINE xct = xctarget_type(target_properties, parent=pbxp,NEWLINE force_outdir=spec.get('product_dir'),NEWLINE force_prefix=spec.get('product_prefix'),NEWLINE force_extension=spec.get('product_extension'))NEWLINE pbxp.AppendProperty('targets', xct)NEWLINE xcode_targets[qualified_target] = xctNEWLINE xcode_target_to_target_dict[xct] = specNEWLINENEWLINE spec_actions = spec.get('actions', [])NEWLINE spec_rules = spec.get('rules', [])NEWLINENEWLINE # Xcode has some "issues" with checking dependencies for the "CompileNEWLINE # sources" step with any source files/headers generated by actions/rules.NEWLINE # To work around this, if a target is building anything directly (notNEWLINE # type "none"), then a second target is used to run the GYP actions/rulesNEWLINE # and is made a dependency of this target. This way the work is doneNEWLINE # before the dependency checks for what should be recompiled.NEWLINE support_xct = NoneNEWLINE # The Xcode "issues" don't affect xcode-ninja builds, since the dependencyNEWLINE # logic all happens in ninja. Don't bother creating the extra targets inNEWLINE # that case.NEWLINE if type != 'none' and (spec_actions or spec_rules) and not ninja_wrapper:NEWLINE support_xccl = CreateXCConfigurationList(configuration_names)NEWLINE support_target_suffix = generator_flags.get(NEWLINE 'support_target_suffix', ' Support')NEWLINE support_target_properties = {NEWLINE 'buildConfigurationList': support_xccl,NEWLINE 'name': target_name + support_target_suffix,NEWLINE }NEWLINE if target_product_name:NEWLINE support_target_properties['productName'] = \NEWLINE target_product_name + ' Support'NEWLINE support_xct = \NEWLINE gyp.xcodeproj_file.PBXAggregateTarget(support_target_properties,NEWLINE parent=pbxp)NEWLINE pbxp.AppendProperty('targets', support_xct)NEWLINE xct.AddDependency(support_xct)NEWLINE # Hang the support target off the main target so it can be tested/foundNEWLINE # by the generator during Finalize.NEWLINE xct.support_target = support_xctNEWLINENEWLINE prebuild_index = 0NEWLINENEWLINE # Add custom shell script phases for "actions" sections.NEWLINE for action in spec_actions:NEWLINE # There's no need to write anything into the script to ensure that theNEWLINE # output directories already exist, because Xcode will look at theNEWLINE # declared outputs and automatically ensure that they exist for us.NEWLINENEWLINE # Do we have a message to print when this action runs?NEWLINE message = action.get('message')NEWLINE if message:NEWLINE message = 'echo note: ' + gyp.common.EncodePOSIXShellArgument(message)NEWLINE else:NEWLINE message = ''NEWLINENEWLINE # Turn the list into a string that can be passed to a shell.NEWLINE action_string = gyp.common.EncodePOSIXShellList(action['action'])NEWLINENEWLINE # Convert Xcode-type variable references to sh-compatible environmentNEWLINE # variable references.NEWLINE message_sh = gyp.xcodeproj_file.ConvertVariablesToShellSyntax(message)NEWLINE action_string_sh = gyp.xcodeproj_file.ConvertVariablesToShellSyntax(NEWLINE action_string)NEWLINENEWLINE script = ''NEWLINE # Include the optional messageNEWLINE if message_sh:NEWLINE script += message_sh + '\n'NEWLINE # Be sure the script runs in exec, and that if exec fails, the scriptNEWLINE # exits signalling an error.NEWLINE script += 'exec ' + action_string_sh + '\nexit 1\n'NEWLINE ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({NEWLINE 'inputPaths': action['inputs'],NEWLINE 'name': 'Action "' + action['action_name'] + '"',NEWLINE 'outputPaths': action['outputs'],NEWLINE 'shellScript': script,NEWLINE 'showEnvVarsInLog': 0,NEWLINE })NEWLINENEWLINE if support_xct:NEWLINE support_xct.AppendProperty('buildPhases', ssbp)NEWLINE else:NEWLINE # TODO(mark): this assumes too much knowledge of the internals ofNEWLINE # xcodeproj_file; some of these smarts should move into xcodeproj_fileNEWLINE # itself.NEWLINE xct._properties['buildPhases'].insert(prebuild_index, ssbp)NEWLINE prebuild_index = prebuild_index + 1NEWLINENEWLINE # TODO(mark): Should verify that at most one of these is specified.NEWLINE if int(action.get('process_outputs_as_sources', False)):NEWLINE for output in action['outputs']:NEWLINE AddSourceToTarget(output, type, pbxp, xct)NEWLINENEWLINE if int(action.get('process_outputs_as_mac_bundle_resources', False)):NEWLINE for output in action['outputs']:NEWLINE AddResourceToTarget(output, pbxp, xct)NEWLINENEWLINE # tgt_mac_bundle_resources holds the list of bundle resources soNEWLINE # the rule processing can check against it.NEWLINE if is_bundle:NEWLINE tgt_mac_bundle_resources = spec.get('mac_bundle_resources', [])NEWLINE else:NEWLINE tgt_mac_bundle_resources = []NEWLINENEWLINE # Add custom shell script phases driving "make" for "rules" sections.NEWLINE #NEWLINE # Xcode's built-in rule support is almost powerful enough to use directly,NEWLINE # but there are a few significant deficiencies that render them unusable.NEWLINE # There are workarounds for some of its inadequacies, but in aggregate,NEWLINE # the workarounds added complexity to the generator, and some workaroundsNEWLINE # actually require input files to be crafted more carefully than I'd like.NEWLINE # Consequently, until Xcode rules are made more capable, "rules" inputNEWLINE # sections will be handled in Xcode output by shell script build phasesNEWLINE # performed prior to the compilation phase.NEWLINE #NEWLINE # The following problems with Xcode rules were found. The numbers areNEWLINE # Apple radar IDs. I hope that these shortcomings are addressed, I reallyNEWLINE # liked having the rules handled directly in Xcode during the period thatNEWLINE # I was prototyping this.NEWLINE #NEWLINE # 6588600 Xcode compiles custom script rule outputs too soon, compilationNEWLINE # fails. This occurs when rule outputs from distinct inputs areNEWLINE # interdependent. The only workaround is to put rules and theirNEWLINE # inputs in a separate target from the one that compiles the ruleNEWLINE # outputs. This requires input file cooperation and it means thatNEWLINE # process_outputs_as_sources is unusable.NEWLINE # 6584932 Need to declare that custom rule outputs should be excluded fromNEWLINE # compilation. A possible workaround is to lie to Xcode about aNEWLINE # rule's output, giving it a dummy file it doesn't know how toNEWLINE # compile. The rule action script would need to touch the dummy.NEWLINE # 6584839 I need a way to declare additional inputs to a custom rule.NEWLINE # A possible workaround is a shell script phase prior toNEWLINE # compilation that touches a rule's primary input files if anyNEWLINE # would-be additional inputs are newer than the output. ModifyingNEWLINE # the source tree - even just modification times - feels dirty.NEWLINE # 6564240 Xcode "custom script" build rules always dump all environmentNEWLINE # variables. This is a low-prioroty problem and is not aNEWLINE # show-stopper.NEWLINE rules_by_ext = {}NEWLINE for rule in spec_rules:NEWLINE rules_by_ext[rule['extension']] = ruleNEWLINENEWLINE # First, some definitions:NEWLINE #NEWLINE # A "rule source" is a file that was listed in a target's "sources"NEWLINE # list and will have a rule applied to it on the basis of matching theNEWLINE # rule's "extensions" attribute. Rule sources are direct inputs toNEWLINE # rules.NEWLINE #NEWLINE # Rule definitions may specify additional inputs in their "inputs"NEWLINE # attribute. These additional inputs are used for dependency trackingNEWLINE # purposes.NEWLINE #NEWLINE # A "concrete output" is a rule output with input-dependent variablesNEWLINE # resolved. For example, given a rule with:NEWLINE # 'extension': 'ext', 'outputs': ['$(INPUT_FILE_BASE).cc'],NEWLINE # if the target's "sources" list contained "one.ext" and "two.ext",NEWLINE # the "concrete output" for rule input "two.ext" would be "two.cc". IfNEWLINE # a rule specifies multiple outputs, each input file that the rule isNEWLINE # applied to will have the same number of concrete outputs.NEWLINE #NEWLINE # If any concrete outputs are outdated or missing relative to theirNEWLINE # corresponding rule_source or to any specified additional input, theNEWLINE # rule action must be performed to generate the concrete outputs.NEWLINENEWLINE # concrete_outputs_by_rule_source will have an item at the same indexNEWLINE # as the rule['rule_sources'] that it corresponds to. Each item is aNEWLINE # list of all of the concrete outputs for the rule_source.NEWLINE concrete_outputs_by_rule_source = []NEWLINENEWLINE # concrete_outputs_all is a flat list of all concrete outputs that thisNEWLINE # rule is able to produce, given the known set of input filesNEWLINE # (rule_sources) that apply to it.NEWLINE concrete_outputs_all = []NEWLINENEWLINE # messages & actions are keyed by the same indices as rule['rule_sources']NEWLINE # and concrete_outputs_by_rule_source. They contain the message andNEWLINE # action to perform after resolving input-dependent variables. TheNEWLINE # message is optional, in which case None is stored for each rule source.NEWLINE messages = []NEWLINE actions = []NEWLINENEWLINE for rule_source in rule.get('rule_sources', []):NEWLINE rule_source_dirname, rule_source_basename = \NEWLINE posixpath.split(rule_source)NEWLINE (rule_source_root, rule_source_ext) = \NEWLINE posixpath.splitext(rule_source_basename)NEWLINENEWLINE # These are the same variable names that Xcode uses for its own nativeNEWLINE # rule support. Because Xcode's rule engine is not being used, theyNEWLINE # need to be expanded as they are written to the makefile.NEWLINE rule_input_dict = {NEWLINE 'INPUT_FILE_BASE': rule_source_root,NEWLINE 'INPUT_FILE_SUFFIX': rule_source_ext,NEWLINE 'INPUT_FILE_NAME': rule_source_basename,NEWLINE 'INPUT_FILE_PATH': rule_source,NEWLINE 'INPUT_FILE_DIRNAME': rule_source_dirname,NEWLINE }NEWLINENEWLINE concrete_outputs_for_this_rule_source = []NEWLINE for output in rule.get('outputs', []):NEWLINE # Fortunately, Xcode and make both use $(VAR) format for theirNEWLINE # variables, so the expansion is the only transformation necessary.NEWLINE # Any remaning $(VAR)-type variables in the string can be givenNEWLINE # directly to make, which will pick up the correct settings fromNEWLINE # what Xcode puts into the environment.NEWLINE concrete_output = ExpandXcodeVariables(output, rule_input_dict)NEWLINE concrete_outputs_for_this_rule_source.append(concrete_output)NEWLINENEWLINE # Add all concrete outputs to the project.NEWLINE pbxp.AddOrGetFileInRootGroup(concrete_output)NEWLINENEWLINE concrete_outputs_by_rule_source.append( \NEWLINE concrete_outputs_for_this_rule_source)NEWLINE concrete_outputs_all.extend(concrete_outputs_for_this_rule_source)NEWLINENEWLINE # TODO(mark): Should verify that at most one of these is specified.NEWLINE if int(rule.get('process_outputs_as_sources', False)):NEWLINE for output in concrete_outputs_for_this_rule_source:NEWLINE AddSourceToTarget(output, type, pbxp, xct)NEWLINENEWLINE # If the file came from the mac_bundle_resources list or if the ruleNEWLINE # is marked to process outputs as bundle resource, do so.NEWLINE was_mac_bundle_resource = rule_source in tgt_mac_bundle_resourcesNEWLINE if was_mac_bundle_resource or \NEWLINE int(rule.get('process_outputs_as_mac_bundle_resources', False)):NEWLINE for output in concrete_outputs_for_this_rule_source:NEWLINE AddResourceToTarget(output, pbxp, xct)NEWLINENEWLINE # Do we have a message to print when this rule runs?NEWLINE message = rule.get('message')NEWLINE if message:NEWLINE message = gyp.common.EncodePOSIXShellArgument(message)NEWLINE message = ExpandXcodeVariables(message, rule_input_dict)NEWLINE messages.append(message)NEWLINENEWLINE # Turn the list into a string that can be passed to a shell.NEWLINE action_string = gyp.common.EncodePOSIXShellList(rule['action'])NEWLINENEWLINE action = ExpandXcodeVariables(action_string, rule_input_dict)NEWLINE actions.append(action)NEWLINENEWLINE if len(concrete_outputs_all) > 0:NEWLINE # TODO(mark): There's a possibility for collision here. ConsiderNEWLINE # target "t" rule "A_r" and target "t_A" rule "r".NEWLINE makefile_name = '%s.make' % re.sub(NEWLINE '[^a-zA-Z0-9_]', '_' , '%s_%s' % (target_name, rule['rule_name']))NEWLINE makefile_path = os.path.join(xcode_projects[build_file].path,NEWLINE makefile_name)NEWLINE # TODO(mark): try/close? Write to a temporary file and swap it onlyNEWLINE # if it's got changes?NEWLINE makefile = open(makefile_path, 'wb')NEWLINENEWLINE # make will build the first target in the makefile by default. ByNEWLINE # convention, it's called "all". List all (or at least one)NEWLINE # concrete output for each rule source as a prerequisite of the "all"NEWLINE # target.NEWLINE makefile.write('all: \\\n')NEWLINE for concrete_output_index in \NEWLINE range(0, len(concrete_outputs_by_rule_source)):NEWLINE # Only list the first (index [0]) concrete output of each inputNEWLINE # in the "all" target. Otherwise, a parallel make (-j > 1) wouldNEWLINE # attempt to process each input multiple times simultaneously.NEWLINE # Otherwise, "all" could just contain the entire list ofNEWLINE # concrete_outputs_all.NEWLINE concrete_output = \NEWLINE concrete_outputs_by_rule_source[concrete_output_index][0]NEWLINE if concrete_output_index == len(concrete_outputs_by_rule_source) - 1:NEWLINE eol = ''NEWLINE else:NEWLINE eol = ' \\'NEWLINE makefile.write(' %s%s\n' % (concrete_output, eol))NEWLINENEWLINE for (rule_source, concrete_outputs, message, action) in \NEWLINE zip(rule['rule_sources'], concrete_outputs_by_rule_source,NEWLINE messages, actions):NEWLINE makefile.write('\n')NEWLINENEWLINE # Add a rule that declares it can build each concrete output of aNEWLINE # rule source. Collect the names of the directories that areNEWLINE # required.NEWLINE concrete_output_dirs = []NEWLINE for concrete_output_index in range(0, len(concrete_outputs)):NEWLINE concrete_output = concrete_outputs[concrete_output_index]NEWLINE if concrete_output_index == 0:NEWLINE bol = ''NEWLINE else:NEWLINE bol = ' 'NEWLINE makefile.write('%s%s \\\n' % (bol, concrete_output))NEWLINENEWLINE concrete_output_dir = posixpath.dirname(concrete_output)NEWLINE if (concrete_output_dir andNEWLINE concrete_output_dir not in concrete_output_dirs):NEWLINE concrete_output_dirs.append(concrete_output_dir)NEWLINENEWLINE makefile.write(' : \\\n')NEWLINENEWLINE # The prerequisites for this rule are the rule source itself andNEWLINE # the set of additional rule inputs, if any.NEWLINE prerequisites = [rule_source]NEWLINE prerequisites.extend(rule.get('inputs', []))NEWLINE for prerequisite_index in range(0, len(prerequisites)):NEWLINE prerequisite = prerequisites[prerequisite_index]NEWLINE if prerequisite_index == len(prerequisites) - 1:NEWLINE eol = ''NEWLINE else:NEWLINE eol = ' \\'NEWLINE makefile.write(' %s%s\n' % (prerequisite, eol))NEWLINENEWLINE # Make sure that output directories exist before executing the ruleNEWLINE # action.NEWLINE if len(concrete_output_dirs) > 0:NEWLINE makefile.write('\t@mkdir -p "%s"\n' %NEWLINE '" "'.join(concrete_output_dirs))NEWLINENEWLINE # The rule message and action have already had the necessary variableNEWLINE # substitutions performed.NEWLINE if message:NEWLINE # Mark it with note: so Xcode picks it up in build output.NEWLINE makefile.write('\t@echo note: %s\n' % message)NEWLINE makefile.write('\t%s\n' % action)NEWLINENEWLINE makefile.close()NEWLINENEWLINE # It might be nice to ensure that needed output directories existNEWLINE # here rather than in each target in the Makefile, but that wouldn'tNEWLINE # work if there ever was a concrete output that had an input-dependentNEWLINE # variable anywhere other than in the leaf position.NEWLINENEWLINE # Don't declare any inputPaths or outputPaths. If they're present,NEWLINE # Xcode will provide a slight optimization by only running the scriptNEWLINE # phase if any output is missing or outdated relative to any input.NEWLINE # Unfortunately, it will also assume that all outputs are touched byNEWLINE # the script, and if the outputs serve as files in a compilationNEWLINE # phase, they will be unconditionally rebuilt. Since make might notNEWLINE # rebuild everything that could be declared here as an output, thisNEWLINE # extra compilation activity is unnecessary. With inputPaths andNEWLINE # outputPaths not supplied, make will always be called, but it knowsNEWLINE # enough to not do anything when everything is up-to-date.NEWLINENEWLINE # To help speed things up, pass -j COUNT to make so it does some workNEWLINE # in parallel. Don't use ncpus because Xcode will build ncpus targetsNEWLINE # in parallel and if each target happens to have a rules step, thereNEWLINE # would be ncpus^2 things going. With a machine that has 2 quad-coreNEWLINE # Xeons, a build can quickly run out of processes based onNEWLINE # scheduling/other tasks, and randomly failing builds are no good.NEWLINE script = \NEWLINE"""JOB_COUNT="$(/usr/sbin/sysctl -n hw.ncpu)"NEWLINEif [ "${JOB_COUNT}" -gt 4 ]; thenNEWLINE JOB_COUNT=4NEWLINEfiNEWLINEexec xcrun make -f "${PROJECT_FILE_PATH}/%s" -j "${JOB_COUNT}"NEWLINEexit 1NEWLINE""" % makefile_nameNEWLINE ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({NEWLINE 'name': 'Rule "' + rule['rule_name'] + '"',NEWLINE 'shellScript': script,NEWLINE 'showEnvVarsInLog': 0,NEWLINE })NEWLINENEWLINE if support_xct:NEWLINE support_xct.AppendProperty('buildPhases', ssbp)NEWLINE else:NEWLINE # TODO(mark): this assumes too much knowledge of the internals ofNEWLINE # xcodeproj_file; some of these smarts should move into xcodeproj_fileNEWLINE # itself.NEWLINE xct._properties['buildPhases'].insert(prebuild_index, ssbp)NEWLINE prebuild_index = prebuild_index + 1NEWLINENEWLINE # Extra rule inputs also go into the project file. Concrete outputs wereNEWLINE # already added when they were computed.NEWLINE groups = ['inputs', 'inputs_excluded']NEWLINE if skip_excluded_files:NEWLINE groups = [x for x in groups if not x.endswith('_excluded')]NEWLINE for group in groups:NEWLINE for item in rule.get(group, []):NEWLINE pbxp.AddOrGetFileInRootGroup(item)NEWLINENEWLINE # Add "sources".NEWLINE for source in spec.get('sources', []):NEWLINE (source_root, source_extension) = posixpath.splitext(source)NEWLINE if source_extension[1:] not in rules_by_ext:NEWLINE # AddSourceToTarget will add the file to a root group if it's notNEWLINE # already there.NEWLINE AddSourceToTarget(source, type, pbxp, xct)NEWLINE else:NEWLINE pbxp.AddOrGetFileInRootGroup(source)NEWLINENEWLINE # Add "mac_bundle_resources" and "mac_framework_private_headers" ifNEWLINE # it's a bundle of any type.NEWLINE if is_bundle:NEWLINE for resource in tgt_mac_bundle_resources:NEWLINE (resource_root, resource_extension) = posixpath.splitext(resource)NEWLINE if resource_extension[1:] not in rules_by_ext:NEWLINE AddResourceToTarget(resource, pbxp, xct)NEWLINE else:NEWLINE pbxp.AddOrGetFileInRootGroup(resource)NEWLINENEWLINE for header in spec.get('mac_framework_private_headers', []):NEWLINE AddHeaderToTarget(header, pbxp, xct, False)NEWLINENEWLINE # Add "mac_framework_headers". These can be valid for both frameworksNEWLINE # and static libraries.NEWLINE if is_bundle or type == 'static_library':NEWLINE for header in spec.get('mac_framework_headers', []):NEWLINE AddHeaderToTarget(header, pbxp, xct, True)NEWLINENEWLINE # Add "copies".NEWLINE pbxcp_dict = {}NEWLINE for copy_group in spec.get('copies', []):NEWLINE dest = copy_group['destination']NEWLINE if dest[0] not in ('/', '$'):NEWLINE # Relative paths are relative to $(SRCROOT).NEWLINE dest = '$(SRCROOT)/' + destNEWLINENEWLINE code_sign = int(copy_group.get('xcode_code_sign', 0))NEWLINE settings = (None, '{ATTRIBUTES = (CodeSignOnCopy, ); }')[code_sign]NEWLINENEWLINE # Coalesce multiple "copies" sections in the same target with the sameNEWLINE # "destination" property into the same PBXCopyFilesBuildPhase, otherwiseNEWLINE # they'll wind up with ID collisions.NEWLINE pbxcp = pbxcp_dict.get(dest, None)NEWLINE if pbxcp is None:NEWLINE pbxcp = gyp.xcodeproj_file.PBXCopyFilesBuildPhase({NEWLINE 'name': 'Copy to ' + copy_group['destination']NEWLINE },NEWLINE parent=xct)NEWLINE pbxcp.SetDestination(dest)NEWLINENEWLINE # TODO(mark): The usual comment about this knowing too much aboutNEWLINE # gyp.xcodeproj_file internals applies.NEWLINE xct._properties['buildPhases'].insert(prebuild_index, pbxcp)NEWLINENEWLINE pbxcp_dict[dest] = pbxcpNEWLINENEWLINE for file in copy_group['files']:NEWLINE pbxcp.AddFile(file, settings)NEWLINENEWLINE # Excluded files can also go into the project file.NEWLINE if not skip_excluded_files:NEWLINE for key in ['sources', 'mac_bundle_resources', 'mac_framework_headers',NEWLINE 'mac_framework_private_headers']:NEWLINE excluded_key = key + '_excluded'NEWLINE for item in spec.get(excluded_key, []):NEWLINE pbxp.AddOrGetFileInRootGroup(item)NEWLINENEWLINE # So can "inputs" and "outputs" sections of "actions" groups.NEWLINE groups = ['inputs', 'inputs_excluded', 'outputs', 'outputs_excluded']NEWLINE if skip_excluded_files:NEWLINE groups = [x for x in groups if not x.endswith('_excluded')]NEWLINE for action in spec.get('actions', []):NEWLINE for group in groups:NEWLINE for item in action.get(group, []):NEWLINE # Exclude anything in BUILT_PRODUCTS_DIR. They're products, notNEWLINE # sources.NEWLINE if not item.startswith('$(BUILT_PRODUCTS_DIR)/'):NEWLINE pbxp.AddOrGetFileInRootGroup(item)NEWLINENEWLINE for postbuild in spec.get('postbuilds', []):NEWLINE action_string_sh = gyp.common.EncodePOSIXShellList(postbuild['action'])NEWLINE script = 'exec ' + action_string_sh + '\nexit 1\n'NEWLINENEWLINE # Make the postbuild step depend on the output of ld or ar from thisNEWLINE # target. Apparently putting the script step after the link step isn'tNEWLINE # sufficient to ensure proper ordering in all cases. With an inputNEWLINE # declared but no outputs, the script step should run every time, asNEWLINE # desired.NEWLINE ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({NEWLINE 'inputPaths': ['$(BUILT_PRODUCTS_DIR)/$(EXECUTABLE_PATH)'],NEWLINE 'name': 'Postbuild "' + postbuild['postbuild_name'] + '"',NEWLINE 'shellScript': script,NEWLINE 'showEnvVarsInLog': 0,NEWLINE })NEWLINE xct.AppendProperty('buildPhases', ssbp)NEWLINENEWLINE # Add dependencies before libraries, because adding a dependency may implyNEWLINE # adding a library. It's preferable to keep dependencies listed firstNEWLINE # during a link phase so that they can override symbols that wouldNEWLINE # otherwise be provided by libraries, which will usually include systemNEWLINE # libraries. On some systems, ld is finicky and even requires theNEWLINE # libraries to be ordered in such a way that unresolved symbols inNEWLINE # earlier-listed libraries may only be resolved by later-listed libraries.NEWLINE # The Mac linker doesn't work that way, but other platforms do, and soNEWLINE # their linker invocations need to be constructed in this way. There'sNEWLINE # no compelling reason for Xcode's linker invocations to differ.NEWLINENEWLINE if 'dependencies' in spec:NEWLINE for dependency in spec['dependencies']:NEWLINE xct.AddDependency(xcode_targets[dependency])NEWLINE # The support project also gets the dependencies (in case they areNEWLINE # needed for the actions/rules to work).NEWLINE if support_xct:NEWLINE support_xct.AddDependency(xcode_targets[dependency])NEWLINENEWLINE if 'libraries' in spec:NEWLINE for library in spec['libraries']:NEWLINE xct.FrameworksPhase().AddFile(library)NEWLINE # Add the library's directory to LIBRARY_SEARCH_PATHS if necessary.NEWLINE # I wish Xcode handled this automatically.NEWLINE library_dir = posixpath.dirname(library)NEWLINE if library_dir not in xcode_standard_library_dirs and (NEWLINE not xct.HasBuildSetting(_library_search_paths_var) orNEWLINE library_dir not in xct.GetBuildSetting(_library_search_paths_var)):NEWLINE xct.AppendBuildSetting(_library_search_paths_var, library_dir)NEWLINENEWLINE for configuration_name in configuration_names:NEWLINE configuration = spec['configurations'][configuration_name]NEWLINE xcbc = xct.ConfigurationNamed(configuration_name)NEWLINE for include_dir in configuration.get('mac_framework_dirs', []):NEWLINE xcbc.AppendBuildSetting('FRAMEWORK_SEARCH_PATHS', include_dir)NEWLINE for include_dir in configuration.get('include_dirs', []):NEWLINE xcbc.AppendBuildSetting('HEADER_SEARCH_PATHS', include_dir)NEWLINE for library_dir in configuration.get('library_dirs', []):NEWLINE if library_dir not in xcode_standard_library_dirs and (NEWLINE not xcbc.HasBuildSetting(_library_search_paths_var) orNEWLINE library_dir not in xcbc.GetBuildSetting(_library_search_paths_var)):NEWLINE xcbc.AppendBuildSetting(_library_search_paths_var, library_dir)NEWLINENEWLINE if 'defines' in configuration:NEWLINE for define in configuration['defines']:NEWLINE set_define = EscapeXcodeDefine(define)NEWLINE xcbc.AppendBuildSetting('GCC_PREPROCESSOR_DEFINITIONS', set_define)NEWLINE if 'xcode_settings' in configuration:NEWLINE for xck, xcv in configuration['xcode_settings'].items():NEWLINE xcbc.SetBuildSetting(xck, xcv)NEWLINE if 'xcode_config_file' in configuration:NEWLINE config_ref = pbxp.AddOrGetFileInRootGroup(NEWLINE configuration['xcode_config_file'])NEWLINE xcbc.SetBaseConfiguration(config_ref)NEWLINENEWLINE build_files = []NEWLINE for build_file, build_file_dict in data.items():NEWLINE if build_file.endswith('.gyp'):NEWLINE build_files.append(build_file)NEWLINENEWLINE for build_file in build_files:NEWLINE xcode_projects[build_file].Finalize1(xcode_targets, serialize_all_tests)NEWLINENEWLINE for build_file in build_files:NEWLINE xcode_projects[build_file].Finalize2(xcode_targets,NEWLINE xcode_target_to_target_dict)NEWLINENEWLINE for build_file in build_files:NEWLINE xcode_projects[build_file].Write()NEWLINE import sysNEWLINEimport osNEWLINEimport filecmpNEWLINEimport importlibNEWLINEimport datetimeNEWLINEimport commonNEWLINENEWLINEpath = os.path.abspath('.')NEWLINEsys.path.append(path)NEWLINENEWLINEdomain = 'maaseuduntulevaisuus'NEWLINEurl = 'http://www.maaseuduntulevaisuus.fi/maatalous/eu-s%C3%A4%C3%A4st%C3%A4%C3%A4-suorista-tuista-1-37-prosenttia-kriisien-varalle-1.161757'NEWLINENEWLINEout = 'test/parser_out.txt'NEWLINEmodule = importlib.import_module( 'sites.' + domain )NEWLINEd = module.parse(url)NEWLINENEWLINEclass TestParser:NEWLINENEWLINE @classmethodNEWLINE def setup_class(cls):NEWLINE common.initialise_file( out, d )NEWLINENEWLINE def test_file_exists(self):NEWLINE common.file_exists(out)NEWLINENEWLINE def test_file_not_empty(self):NEWLINE common.file_not_empty(out)NEWLINENEWLINE def test_file_contents_match(self):NEWLINE common.file_contents_match(domain, out)NEWLINENEWLINE def test_dictionary_created(self):NEWLINE common.dictionary_created(d)NEWLINENEWLINE def test_dictionary_contains_right_keys(self):NEWLINE common.dictionary_contains_right_keys(d)NEWLINENEWLINE def test_dictionary_values_correct_type(self):NEWLINE common.dictionary_values_correct_type(d)NEWLINE # PyYAML libraryNEWLINE__license__ = 'MIT'NEWLINE__author__ = 'Kirill Simonov'NEWLINE__copyright__ = """NEWLINE Copyright (c) 2017-2020 Ingy döt NetNEWLINE Copyright (c) 2006-2016 Kirill SimonovNEWLINE """NEWLINENEWLINE# For changes regarding this port for Ignition usage, please contact:NEWLINE__maintainer__ = 'Andrew Geiger'NEWLINE__email__ = 'andrew.geiger@corsosystems.com'NEWLINENEWLINENEWLINE__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError']NEWLINENEWLINEclass Mark(object):NEWLINENEWLINE def __init__(self, name, index, line, column, buffer, pointer):NEWLINE self.name = nameNEWLINE self.index = indexNEWLINE self.line = lineNEWLINE self.column = columnNEWLINE self.buffer = bufferNEWLINE self.pointer = pointerNEWLINENEWLINE def get_snippet(self, indent=4, max_length=75):NEWLINE if self.buffer is None:NEWLINE return NoneNEWLINE head = ''NEWLINE start = self.pointerNEWLINE while start > 0 and self.buffer[start-1] not in u'\0\r\n\x85\u2028\u2029':NEWLINE start -= 1NEWLINE if self.pointer-start > max_length/2-1:NEWLINE head = ' ... 'NEWLINE start += 5NEWLINE breakNEWLINE tail = ''NEWLINE end = self.pointerNEWLINE while end < len(self.buffer) and self.buffer[end] not in u'\0\r\n\x85\u2028\u2029':NEWLINE end += 1NEWLINE if end-self.pointer > max_length/2-1:NEWLINE tail = ' ... 'NEWLINE end -= 5NEWLINE breakNEWLINE snippet = self.buffer[start:end].encode('utf-8')NEWLINE return ' '*indent + head + snippet + tail + '\n' \NEWLINE + ' '*(indent+self.pointer-start+len(head)) + '^'NEWLINENEWLINE def __str__(self):NEWLINE snippet = self.get_snippet()NEWLINE where = " in \"%s\", line %d, column %d" \NEWLINE % (self.name, self.line+1, self.column+1)NEWLINE if snippet is not None:NEWLINE where += ":\n"+snippetNEWLINE return whereNEWLINENEWLINEclass YAMLError(Exception):NEWLINE passNEWLINENEWLINEclass MarkedYAMLError(YAMLError):NEWLINENEWLINE def __init__(self, context=None, context_mark=None,NEWLINE problem=None, problem_mark=None, note=None):NEWLINE self.context = contextNEWLINE self.context_mark = context_markNEWLINE self.problem = problemNEWLINE self.problem_mark = problem_markNEWLINE self.note = noteNEWLINENEWLINE def __str__(self):NEWLINE lines = []NEWLINE if self.context is not None:NEWLINE lines.append(self.context)NEWLINE if self.context_mark is not None \NEWLINE and (self.problem is None or self.problem_mark is NoneNEWLINE or self.context_mark.name != self.problem_mark.nameNEWLINE or self.context_mark.line != self.problem_mark.lineNEWLINE or self.context_mark.column != self.problem_mark.column):NEWLINE lines.append(str(self.context_mark))NEWLINE if self.problem is not None:NEWLINE lines.append(self.problem)NEWLINE if self.problem_mark is not None:NEWLINE lines.append(str(self.problem_mark))NEWLINE if self.note is not None:NEWLINE lines.append(self.note)NEWLINE return '\n'.join(lines)NEWLINE import requestsNEWLINENEWLINE#sresponse = requests.get() from selenium.webdriver.common.keys import KeysNEWLINEimport timeNEWLINEimport randomNEWLINENEWLINEfrom selenium_ui.base_page import BasePageNEWLINEfrom selenium_ui.jira.pages.selectors import UrlManager, LoginPageLocators, DashboardLocators, PopupLocators, \NEWLINE IssueLocators, ProjectLocators, SearchLocators, BoardsListLocators, BoardLocators, LogoutLocatorsNEWLINENEWLINENEWLINEclass PopupManager(BasePage):NEWLINENEWLINE def dismiss_default_popup(self):NEWLINE return self.dismiss_popup(PopupLocators.default_popup, PopupLocators.popup_1, PopupLocators.popup_2)NEWLINENEWLINENEWLINEclass Login(BasePage):NEWLINE page_url = LoginPageLocators.login_urlNEWLINE page_loaded_selector = LoginPageLocators.system_dashboardNEWLINENEWLINE def is_first_login(self):NEWLINE return True if self.get_elements(LoginPageLocators.continue_button) else FalseNEWLINENEWLINE def first_login_setup(self):NEWLINE self.wait_until_visible(LoginPageLocators.continue_button).send_keys(Keys.ESCAPE)NEWLINE self.get_element(LoginPageLocators.continue_button).click()NEWLINE self.wait_until_visible(LoginPageLocators.avatar_page_next_button).click()NEWLINE self.wait_until_visible(LoginPageLocators.explore_current_projects).click()NEWLINE self.go_to_url(DashboardLocators.dashboard_url)NEWLINE self.wait_until_visible(DashboardLocators.dashboard_window)NEWLINENEWLINE def set_credentials(self, username, password):NEWLINE self.get_element(LoginPageLocators.login_field).send_keys(username)NEWLINE self.get_element(LoginPageLocators.password_field).send_keys(password)NEWLINE self.get_element(LoginPageLocators.login_submit_button).click()NEWLINENEWLINENEWLINEclass Logout(BasePage):NEWLINE page_url = LogoutLocators.logout_urlNEWLINENEWLINE def click_logout(self):NEWLINE self.get_element(LogoutLocators.logout_submit_button).click()NEWLINENEWLINE def wait_for_page_loaded(self):NEWLINE self.wait_until_present(LogoutLocators.login_button_link)NEWLINENEWLINENEWLINEclass Dashboard(BasePage):NEWLINE page_url = DashboardLocators.dashboard_urlNEWLINENEWLINE def wait_dashboard_presented(self):NEWLINE self.wait_until_present(DashboardLocators.dashboard_window)NEWLINENEWLINENEWLINEclass Issue(BasePage):NEWLINE page_loaded_selector = IssueLocators.issue_titleNEWLINENEWLINE def __init__(self, driver, issue_key=None, issue_id=None):NEWLINE BasePage.__init__(self, driver)NEWLINE url_manager_modal = UrlManager(issue_key=issue_key)NEWLINE url_manager_edit_page = UrlManager(issue_id=issue_id)NEWLINE self.page_url = url_manager_modal.issue_url()NEWLINE self.page_url_edit_issue = url_manager_edit_page.edit_issue_url()NEWLINE self.page_url_edit_comment = url_manager_edit_page.edit_comments_url()NEWLINENEWLINE def wait_for_issue_title(self):NEWLINE self.wait_until_visible(IssueLocators.issue_title)NEWLINENEWLINE def go_to_edit_issue(self):NEWLINE self.go_to_url(self.page_url_edit_issue)NEWLINE self.wait_until_visible(IssueLocators.edit_issue_page)NEWLINENEWLINE def go_to_edit_comment(self):NEWLINE self.go_to_url(self.page_url_edit_comment)NEWLINE self.wait_until_visible(IssueLocators.edit_comment_add_comment_button)NEWLINENEWLINE def fill_summary_edit(self):NEWLINE text_summary = f"Edit summary form selenium - {self.generate_random_string(10)}"NEWLINE self.get_element(IssueLocators.issue_summary_field).send_keys(text_summary)NEWLINENEWLINE def __fill_rich_editor_textfield(self, text, selector):NEWLINE self.wait_until_available_to_switch(selector)NEWLINE self.get_element(IssueLocators.tinymce_description_field).send_keys(text)NEWLINE self.return_to_parent_frame()NEWLINENEWLINE def edit_issue_submit(self):NEWLINE self.get_element(IssueLocators.edit_issue_submit).click()NEWLINENEWLINE def fill_description_edit(self):NEWLINE text_description = f"Edit description form selenium - {self.generate_random_string(30)}"NEWLINE self.__fill_rich_editor_textfield(text_description, selector=IssueLocators.issue_description_field)NEWLINENEWLINE def open_create_issue_modal(self):NEWLINE self.wait_until_clickable(IssueLocators.create_issue_button).click()NEWLINE self.wait_until_visible(IssueLocators.issue_modal)NEWLINENEWLINE def fill_description_create(self):NEWLINE text_description = f'Description: {self.generate_random_string(100)}'NEWLINE self.__fill_rich_editor_textfield(text_description, selector=IssueLocators.issue_description_field)NEWLINENEWLINE def fill_summary_create(self):NEWLINE summary = f"Issue created date {time.time()}"NEWLINE self.wait_until_clickable(IssueLocators.issue_summary_field).send_keys(summary)NEWLINENEWLINE def assign_to_me(self):NEWLINE assign_to_me_links = self.get_elements(IssueLocators.issue_assign_to_me_link)NEWLINE for link in assign_to_me_links:NEWLINE link.click()NEWLINENEWLINE def set_resolution(self):NEWLINE resolution_field = self.get_elements(IssueLocators.issue_resolution_field)NEWLINE if resolution_field:NEWLINE drop_down_length = len(self.select(resolution_field[0]).options)NEWLINE random_resolution_id = random.randint(1, drop_down_length - 1)NEWLINE self.select(resolution_field[0]).select_by_index(random_resolution_id)NEWLINENEWLINE def set_issue_type(self):NEWLINE def __filer_epic(element):NEWLINE return "epic" not in element.get_attribute("class").lower()NEWLINENEWLINE self.get_element(IssueLocators.issue_type_field).click()NEWLINE issue_dropdown_elements = self.get_elements(IssueLocators.issue_type_dropdown_elements)NEWLINE if issue_dropdown_elements:NEWLINE filtered_issue_elements = list(filter(__filer_epic, issue_dropdown_elements))NEWLINE rnd_issue_type_el = random.choice(filtered_issue_elements)NEWLINE self.action_chains().move_to_element(rnd_issue_type_el).click(rnd_issue_type_el).perform()NEWLINE self.wait_until_invisible(IssueLocators.issue_ready_to_save_spinner)NEWLINENEWLINE def submit_issue(self):NEWLINE self.wait_until_clickable(IssueLocators.issue_submit_button).click()NEWLINE self.wait_until_invisible(IssueLocators.issue_modal)NEWLINENEWLINE def fill_comment_edit(self):NEWLINE text = 'Comment from selenium'NEWLINE self.__fill_rich_editor_textfield(text, selector=IssueLocators.edit_comment_text_field)NEWLINENEWLINE def edit_comment_submit(self):NEWLINE self.get_element(IssueLocators.edit_comment_add_comment_button).click()NEWLINE self.wait_until_visible(IssueLocators.issue_title)NEWLINENEWLINENEWLINEclass Project(BasePage):NEWLINE page_loaded_selector = ProjectLocators.project_summary_property_columnNEWLINENEWLINE def __init__(self, driver, project_key):NEWLINE BasePage.__init__(self, driver)NEWLINE url_manager = UrlManager(project_key=project_key)NEWLINE self.page_url = url_manager.project_summary_url()NEWLINENEWLINENEWLINEclass ProjectsList(BasePage):NEWLINENEWLINE def __init__(self, driver, projects_list_pages):NEWLINE BasePage.__init__(self, driver)NEWLINE self.projects_list_page = random.randint(1, projects_list_pages)NEWLINE url_manager = UrlManager(projects_list_page=self.projects_list_page)NEWLINE self.page_url = url_manager.projects_list_page_url()NEWLINENEWLINE def wait_for_page_loaded(self):NEWLINE self.wait_until_any_ec_presented(NEWLINE selector_names=[ProjectLocators.projects_list, ProjectLocators.projects_not_found])NEWLINENEWLINENEWLINEclass BoardsList(BasePage):NEWLINE page_url = BoardsListLocators.boards_list_urlNEWLINE page_loaded_selector = BoardsListLocators.boards_listNEWLINENEWLINENEWLINEclass Search(BasePage):NEWLINENEWLINE def __init__(self, driver, jql):NEWLINE BasePage.__init__(self, driver)NEWLINE url_manager = UrlManager(jql=jql)NEWLINE self.page_url = url_manager.jql_search_url()NEWLINENEWLINE def wait_for_page_loaded(self):NEWLINE self.wait_until_any_ec_presented(selector_names=[SearchLocators.search_issue_table,NEWLINE SearchLocators.search_issue_content,NEWLINE SearchLocators.search_no_issue_found])NEWLINENEWLINENEWLINEclass Board(BasePage):NEWLINE page_loaded_selector = BoardLocators.board_columnsNEWLINENEWLINE def __init__(self, driver, board_id):NEWLINE BasePage.__init__(self, driver)NEWLINE url_manager = UrlManager(board_id=board_id)NEWLINE self.page_url = url_manager.scrum_board_url()NEWLINE self.backlog_url = url_manager.scrum_board_backlog_url()NEWLINENEWLINE def go_to_backlog(self):NEWLINE self.go_to_url(self.backlog_url)NEWLINENEWLINE def wait_for_scrum_board_backlog(self):NEWLINE self.wait_until_present(BoardLocators.scrum_board_backlog_content)NEWLINE """NEWLINETests for navtagsNEWLINE"""NEWLINENEWLINEimport pytestNEWLINEassert pytestNEWLINENEWLINEfrom django.http import HttpRequestNEWLINENEWLINEfrom hm_web.templatetags import navtagsNEWLINENEWLINENEWLINEdef build_request(path):NEWLINE """NEWLINE Build an HttpRequest object with the given pathNEWLINE """NEWLINE request = HttpRequest()NEWLINE request.path = pathNEWLINE return requestNEWLINENEWLINENEWLINEdef test_home_active():NEWLINE assert navtags.active(build_request('/'), '/') == 'active'NEWLINE assert navtags.active(build_request('/login'), '/') == ''NEWLINENEWLINENEWLINEdef test_login_active():NEWLINE assert navtags.active(build_request('/'), '/login') == ''NEWLINE assert navtags.active(build_request('/login'), '/login') == 'active'NEWLINE from IPython import get_ipythonNEWLINEfrom IPython.core.magic import (magics_class, line_magic)NEWLINEfrom IPython.core.magics.osm import OSMagicsNEWLINEfrom johnstarich.ipython.shell import find_varNEWLINEimport keywordNEWLINEimport shutilNEWLINENEWLINENEWLINE@magics_classNEWLINEclass Bashisms(OSMagics):NEWLINE @propertyNEWLINE def _exit_code(self) -> int:NEWLINE return self.shell.user_ns['_exit_code']NEWLINENEWLINE @_exit_code.setterNEWLINE def _exit_code(self, value: int):NEWLINE self.shell.user_ns['_exit_code'] = valueNEWLINENEWLINE @line_magicNEWLINE def echo(self, line: str):NEWLINE "Simply print out its received arguments."NEWLINE print(line.format(**vars(), **globals()))NEWLINE self._exit_code = 0NEWLINE returnNEWLINENEWLINE @line_magicNEWLINE def cd(self, parameter_s=''):NEWLINE super(Bashisms, self).cd('-q ' + parameter_s)NEWLINENEWLINE @line_magicNEWLINE def which(self, line):NEWLINE var_location = find_var(self.shell, line)NEWLINE if var_location is not None:NEWLINE print(var_location.get(line))NEWLINE self._exit_code = 0NEWLINE returnNEWLINENEWLINE if keyword.iskeyword(line):NEWLINE help(line)NEWLINE self._exit_code = 0NEWLINE returnNEWLINENEWLINE ex = shutil.which(line)NEWLINE if ex is not None:NEWLINE print(ex)NEWLINE self._exit_code = 0NEWLINE returnNEWLINE else:NEWLINE print('"{}" could not be found on $PATH'NEWLINE .format(line))NEWLINE self._exit_code = 1NEWLINE returnNEWLINENEWLINEip = get_ipython()NEWLINEip.register_magics(Bashisms)NEWLINEdel ipNEWLINE import numpy as npNEWLINEfrom wacky_rl import layersNEWLINEfrom collections import dequeNEWLINENEWLINEclass AgentCore:NEWLINENEWLINE def __init__(self, obs_seq_lenght = 6):NEWLINE self.approx_contin = FalseNEWLINE self.obs_seq_lenght = obs_seq_lenghtNEWLINE self.obs_mem = deque(maxlen=obs_seq_lenght)NEWLINENEWLINE if not hasattr(self, 'logger'):NEWLINE self.logger = NoneNEWLINENEWLINE if not hasattr(self, 'approx_contin'):NEWLINE self.approx_contin = FalseNEWLINENEWLINE if not hasattr(self, 'env'):NEWLINE self.env = NoneNEWLINENEWLINE def __call__(self, *args, **kwargs):NEWLINE return self.act( *args, **kwargs)NEWLINENEWLINE def act(self, inputs, act_argmax=False):NEWLINE raise NotImplementedError('When subclassing the `AgentCore` class, you should 'NEWLINE 'implement a `act` method.')NEWLINENEWLINE def learn(self, *args, **kwargs):NEWLINE raise NotImplementedError('When subclassing the `AgentCore` class, you should 'NEWLINE 'implement a `train` method.')NEWLINENEWLINE def decode_space(self, gym_space):NEWLINENEWLINE from gym import spacesNEWLINENEWLINE if isinstance(gym_space, spaces.Box):NEWLINE import numpy as npNEWLINE return int(np.squeeze(gym_space.shape))NEWLINENEWLINE elif isinstance(gym_space, spaces.Discrete):NEWLINE return int(gym_space.n)NEWLINENEWLINE else:NEWLINE raise AttributeError('gym_space not understood: {}, use space.Box or space.Discrete'.format(gym_space))NEWLINENEWLINE def space_is_contin(self, gym_space):NEWLINE from gym import spacesNEWLINE return isinstance(gym_space, spaces.Box)NEWLINENEWLINE def space_is_discrete(self, gym_space):NEWLINE from gym import spacesNEWLINE return isinstance(gym_space, spaces.Discrete)NEWLINENEWLINE def make_action_layer(self, env, num_bins=21, num_actions=None, approx_contin=False, *args, **kwargs):NEWLINENEWLINE if num_actions is None:NEWLINE num_actions = int(self.decode_space(env.action_space))NEWLINENEWLINE if self.space_is_discrete(env.action_space):NEWLINE self.out_format = intNEWLINE return layers.DiscreteActionLayer(num_bins=num_actions, *args, **kwargs)NEWLINE elif approx_contin:NEWLINE self.out_format = floatNEWLINE self.approx_contin = TrueNEWLINE return layers.DiscreteActionLayer(num_bins=num_bins, num_actions=num_actions, *args, **kwargs)NEWLINE else:NEWLINE self.out_format = floatNEWLINE return layers.ContinActionLayer(num_actions=num_actions, *args, **kwargs)NEWLINENEWLINE def compare_with_old_policy(self, test_reward):NEWLINE passNEWLINENEWLINE def transform_actions(self, dist, actions, lows=None, highs=None, scale=1.0):NEWLINENEWLINE if self.approx_contin:NEWLINE actions = dist.discrete_to_contin(actions)NEWLINENEWLINE actions = np.squeeze(actions.numpy()) * scaleNEWLINENEWLINE if not lows is None or not highs is None:NEWLINE actions = np.clip(actions, a_min=lows, a_max=highs)NEWLINENEWLINE return actions.astype(self.out_format)NEWLINENEWLINE def take_step(self, obs, save_memories=True, render_env=False, act_argmax=False):NEWLINENEWLINE self.obs_mem.append(obs)NEWLINE # print(np.squeeze(np.array(self.obs_mem)))NEWLINE action = self.act(np.squeeze(np.array(self.obs_mem)), act_argmax=act_argmax, save_memories=save_memories)NEWLINE # action = self.agent.act(np.ravel(np.squeeze(np.array(self.obs_mem))), act_argmax=act_argmax, save_memories=save_memories)NEWLINE new_obs, r, done, _ = self.env.step(np.squeeze(action))NEWLINENEWLINE if save_memories:NEWLINE self.memory({NEWLINE 'obs': np.squeeze(np.array(self.obs_mem))NEWLINE # 'obs': np.ravel(np.squeeze(np.array(self.obs_mem)))NEWLINE }NEWLINE )NEWLINE self.obs_mem.append(new_obs)NEWLINE self.memory({NEWLINE # 'obs': np.array(self.obs_mem),NEWLINE 'new_obs': np.squeeze(np.array(self.obs_mem)),NEWLINE # 'new_obs': np.ravel(np.squeeze(np.array(self.obs_mem))),NEWLINE 'rewards': r,NEWLINE 'dones': float(1 - int(done)),NEWLINE }NEWLINE )NEWLINENEWLINE if render_env:NEWLINE self.env.render()NEWLINENEWLINE return done, new_obs, rNEWLINENEWLINE def sample_warmup(self, num_episodes, render_env=False):NEWLINE for e in range(num_episodes):NEWLINENEWLINE done = FalseNEWLINE obs = self.env.reset()NEWLINENEWLINE while not done:NEWLINE done, obs, _ = self.take_step(obs, save_memories=True, render_env=render_env)NEWLINE self.env.close()NEWLINENEWLINE def episode_train(self, num_episodes, render_env=False):NEWLINE for e in range(num_episodes):NEWLINENEWLINE done = FalseNEWLINE obs = self.env.reset()NEWLINE reward_list = []NEWLINE for i in range(self.obs_seq_lenght):NEWLINE self.obs_mem.append(np.zeros(np.shape(obs)))NEWLINENEWLINE while not done:NEWLINE done, obs, r = self.take_step(obs, save_memories=True, render_env=render_env)NEWLINE # self.env.render()NEWLINE reward_list.append(r)NEWLINENEWLINE if done:NEWLINE a_loss, c_loss = self.learn()NEWLINE if self.logger is None:NEWLINE print()NEWLINE print('# Episode', e)NEWLINE print('# Sum R:', np.round(np.sum(reward_list), 1))NEWLINE print('# Loss A:', np.round(np.mean(a_loss), 4))NEWLINE print('# Loss C:', np.round(np.mean(c_loss), 4))NEWLINE else:NEWLINE self.logger.log_mean('reward', np.round(np.sum(reward_list)))NEWLINE self.logger.print_status(e)NEWLINENEWLINE self.env.close()NEWLINENEWLINE def n_step_train(NEWLINE self,NEWLINE num_steps,NEWLINE n_steps=2048,NEWLINE render_env=False,NEWLINE train_on_test=True,NEWLINE render_test=True,NEWLINE ):NEWLINENEWLINE train_after = n_stepsNEWLINE episode_reward_list = []NEWLINE s = 0NEWLINE while s < num_steps:NEWLINENEWLINE obs = self.env.reset()NEWLINE done = FalseNEWLINE reward_list = []NEWLINE for i in range(self.obs_seq_lenght):NEWLINE self.obs_mem.append(np.zeros(np.shape(obs)))NEWLINENEWLINE while not done:NEWLINE done, obs, r = self.take_step(obs, save_memories=True, render_env=render_env)NEWLINE reward_list.append(r)NEWLINE s += 1NEWLINENEWLINE if done:NEWLINE obs = self.env.reset()NEWLINE episode_reward_list.append(np.sum(reward_list))NEWLINE reward_list = []NEWLINENEWLINE if s >= train_after:NEWLINE train_after += n_stepsNEWLINE a_loss, c_loss = self.learn()NEWLINE if self.logger is None:NEWLINE print()NEWLINE print('# steps', s)NEWLINE print('# Sum R:', np.round(np.sum(episode_reward_list), 1))NEWLINE print('# Loss A:', np.round(np.mean(a_loss), 4))NEWLINE print('# Loss C:', np.round(np.mean(c_loss), 4))NEWLINE else:NEWLINE self.logger.log_mean('sum reward', np.round(np.mean(episode_reward_list)))NEWLINE # print('sum reward:', np.round(np.sum(episode_reward_list), 1))NEWLINE self.logger.print_status(s)NEWLINE episode_reward_list = []NEWLINENEWLINE # Test:NEWLINE if train_on_test or render_test:NEWLINE done = FalseNEWLINE while not done:NEWLINE done, obs, r = self.take_step(obs, save_memories=True, render_env=render_test, act_argmax=True)NEWLINE reward_list.append(r)NEWLINENEWLINE if done:NEWLINE print('test reward:', np.round(sum(reward_list), 1))NEWLINE obs = self.env.reset()NEWLINE reward_list = []NEWLINENEWLINE self.env.close()NEWLINE """NEWLINEModule related to the argument parsingNEWLINENEWLINEThere is a fallback to the deprecated optparse if argparse is not foundNEWLINE"""NEWLINEfrom pathlib import PathNEWLINEfrom argparse import ArgumentParser, SUPPRESSNEWLINENEWLINENEWLINEdef parse_args(CONFIG_PATH: Path):NEWLINE """NEWLINE Parse the arguments from the command lineNEWLINE """NEWLINE parser = ArgumentParser('poezio')NEWLINE parser.add_argument(NEWLINE "-c",NEWLINE "--check-config",NEWLINE dest="check_config",NEWLINE action='store_true',NEWLINE help='Check the config file')NEWLINE parser.add_argument(NEWLINE "-d",NEWLINE "--debug",NEWLINE dest="debug",NEWLINE help="The file where debug will be written",NEWLINE metavar="DEBUG_FILE")NEWLINE parser.add_argument(NEWLINE "-f",NEWLINE "--file",NEWLINE dest="filename",NEWLINE default=CONFIG_PATH / 'poezio.cfg',NEWLINE type=Path,NEWLINE help="The config file you want to use",NEWLINE metavar="CONFIG_FILE")NEWLINE parser.add_argument(NEWLINE "-v",NEWLINE "--version",NEWLINE dest="version",NEWLINE help=SUPPRESS,NEWLINE metavar="VERSION",NEWLINE default="0.13-dev")NEWLINE options = parser.parse_args()NEWLINE return optionsNEWLINE #-----------------------------------------------------------------------------NEWLINE# Copyright (c) 2005-2016, PyInstaller Development Team.NEWLINE#NEWLINE# Distributed under the terms of the GNU General Public License with exceptionNEWLINE# for distributing bootloader.NEWLINE#NEWLINE# The full license is in the file COPYING.txt, distributed with this software.NEWLINE#-----------------------------------------------------------------------------NEWLINENEWLINENEWLINE"""NEWLINEUtilities to create data structures for embedding Python modules and additionalNEWLINEfiles into the executable.NEWLINE"""NEWLINENEWLINE# While an Archive is really an abstraction for any "filesystemNEWLINE# within a file", it is tuned for use with imputil.FuncImporter.NEWLINE# This assumes it contains python code objects, indexed by theNEWLINE# the internal name (ie, no '.py').NEWLINE#NEWLINE# See pyi_carchive.py for a more general archive (contains anything)NEWLINE# that can be understood by a C program.NEWLINENEWLINEimport osNEWLINEimport sysNEWLINEimport structNEWLINEfrom types import CodeTypeNEWLINEimport marshalNEWLINEimport zlibNEWLINENEWLINEfrom PyInstaller.building.utils import get_code_object, strip_paths_in_codeNEWLINEfrom .readers import PYZ_TYPE_MODULE, PYZ_TYPE_PKG, PYZ_TYPE_DATANEWLINEfrom ..compat import BYTECODE_MAGIC, is_py2NEWLINENEWLINENEWLINEclass ArchiveWriter(object):NEWLINE """NEWLINE A base class for a repository of python code objects.NEWLINE The extract method is used by imputil.ArchiveImporterNEWLINE to get code objects by name (fully qualified name), soNEWLINE an enduser "import a.b" would becomeNEWLINE extract('a.__init__')NEWLINE extract('a.b')NEWLINE """NEWLINE MAGIC = b'PYL\0'NEWLINE HDRLEN = 12 # default is MAGIC followed by python's magic, int pos of tocNEWLINE TOCPOS = 8NEWLINENEWLINE def __init__(self, archive_path, logical_toc):NEWLINE """NEWLINE Create an archive file of name 'archive_path'.NEWLINE logical_toc is a 'logical TOC' - a list of (name, path, ...)NEWLINE where name is the internal name, eg 'a'NEWLINE and path is a file to get the object from, eg './a.pyc'.NEWLINE """NEWLINE self.start = 0NEWLINENEWLINE self._start_add_entries(archive_path)NEWLINE self._add_from_table_of_contents(logical_toc)NEWLINE self._finalize()NEWLINENEWLINE def _start_add_entries(self, archive_path):NEWLINE """NEWLINE Open an empty archive for addition of entries.NEWLINE """NEWLINE self.lib = open(archive_path, 'wb')NEWLINE # Reserve space for the header.NEWLINE if self.HDRLEN:NEWLINE self.lib.write(b'\0' * self.HDRLEN)NEWLINE # Create an empty table of contents.NEWLINE # Use a list to support reproducible buildsNEWLINE self.toc = []NEWLINENEWLINE def _add_from_table_of_contents(self, toc):NEWLINE """NEWLINE Add entries from a logical TOC (without absolute positioning info).NEWLINE An entry is an entry in a logical TOC is a tuple,NEWLINE entry[0] is name (under which it will be saved).NEWLINE entry[1] is fullpathname of the file.NEWLINE entry[2] is a flag for it's storage format (True or 1 if compressed)NEWLINE entry[3] is the entry's type code.NEWLINE """NEWLINE for toc_entry in toc:NEWLINE self.add(toc_entry) # The guts of the archive.NEWLINENEWLINE def _finalize(self):NEWLINE """NEWLINE Finalize an archive which has been opened using _start_add_entries(),NEWLINE writing any needed padding and the table of contents.NEWLINE """NEWLINE toc_pos = self.lib.tell()NEWLINE self.save_trailer(toc_pos)NEWLINE if self.HDRLEN:NEWLINE self.update_headers(toc_pos)NEWLINE self.lib.close()NEWLINENEWLINENEWLINE ####### manages keeping the internal TOC and the guts in sync #######NEWLINE def add(self, entry):NEWLINE """NEWLINE Override this to influence the mechanics of the Archive.NEWLINE Assumes entry is a seq beginning with (nm, pth, ...) whereNEWLINE nm is the key by which we'll be asked for the object.NEWLINE pth is the name of where we find the object. Overrides ofNEWLINE get_obj_from can make use of further elements in entry.NEWLINE """NEWLINE nm = entry[0]NEWLINE pth = entry[1]NEWLINE pynm, ext = os.path.splitext(os.path.basename(pth))NEWLINE ispkg = pynm == '__init__'NEWLINE assert ext in ('.pyc', '.pyo')NEWLINE self.toc.append((nm, (ispkg, self.lib.tell())))NEWLINE f = open(entry[1], 'rb')NEWLINE f.seek(8) # skip magic and timestampNEWLINE self.lib.write(f.read())NEWLINENEWLINE def save_trailer(self, tocpos):NEWLINE """NEWLINE Default - toc is a dictNEWLINE Gets marshaled to self.libNEWLINE """NEWLINE try:NEWLINE self.lib.write(marshal.dumps(self.toc))NEWLINE # If the TOC to be marshalled contains an unmarshallable object, PythonNEWLINE # raises a cryptic exception providing no details on why such object isNEWLINE # unmarshallable. Correct this by iteratively inspecting the TOC forNEWLINE # unmarshallable objects.NEWLINE except ValueError as exception:NEWLINE if str(exception) == 'unmarshallable object':NEWLINENEWLINE # List of all marshallable types.NEWLINE MARSHALLABLE_TYPES = set((NEWLINE bool, int, float, complex, str, bytes, bytearray,NEWLINE tuple, list, set, frozenset, dict, CodeType))NEWLINE if sys.version_info[0] == 2:NEWLINE MARSHALLABLE_TYPES.add(long)NEWLINENEWLINE for module_name, module_tuple in self.toc.items():NEWLINE if type(module_name) not in MARSHALLABLE_TYPES:NEWLINE print('Module name "%s" (%s) unmarshallable.' % (module_name, type(module_name)))NEWLINE if type(module_tuple) not in MARSHALLABLE_TYPES:NEWLINE print('Module "%s" tuple "%s" (%s) unmarshallable.' % (module_name, module_tuple, type(module_tuple)))NEWLINE elif type(module_tuple) == tuple:NEWLINE for i in range(len(module_tuple)):NEWLINE if type(module_tuple[i]) not in MARSHALLABLE_TYPES:NEWLINE print('Module "%s" tuple index %s item "%s" (%s) unmarshallable.' % (module_name, i, module_tuple[i], type(module_tuple[i])))NEWLINENEWLINE raiseNEWLINENEWLINE def update_headers(self, tocpos):NEWLINE """NEWLINE Default - MAGIC + Python's magic + tocposNEWLINE """NEWLINE self.lib.seek(self.start)NEWLINE self.lib.write(self.MAGIC)NEWLINE self.lib.write(BYTECODE_MAGIC)NEWLINE self.lib.write(struct.pack('!i', tocpos))NEWLINENEWLINENEWLINEclass ZlibArchiveWriter(ArchiveWriter):NEWLINE """NEWLINE ZlibArchive - an archive with compressed entries. Archive is readNEWLINE from the executable created by PyInstaller.NEWLINENEWLINE This archive is used for bundling python modules inside the executable.NEWLINENEWLINE NOTE: The whole ZlibArchive (PYZ) is compressed so it is not necessaryNEWLINE to compress single modules with zlib.NEWLINE """NEWLINE MAGIC = b'PYZ\0'NEWLINE TOCPOS = 8NEWLINE HDRLEN = ArchiveWriter.HDRLEN + 5NEWLINE COMPRESSION_LEVEL = 6 # Default level of the 'zlib' module from Python.NEWLINENEWLINE def __init__(self, archive_path, logical_toc, code_dict=None, cipher=None):NEWLINE """NEWLINE code_dict dict containing module code objects from ModuleGraph.NEWLINE """NEWLINE # Keep references to module code objects constructed by ModuleGraphNEWLINE # to avoid writting .pyc/pyo files to hdd.NEWLINE self.code_dict = code_dict or {}NEWLINE self.cipher = cipher or NoneNEWLINENEWLINE super(ZlibArchiveWriter, self).__init__(archive_path, logical_toc)NEWLINENEWLINENEWLINE def add(self, entry):NEWLINE name, path, typ = entryNEWLINE if typ == 'PYMODULE':NEWLINE typ = PYZ_TYPE_MODULENEWLINE if path in ('-', None):NEWLINE # This is a NamespacePackage, modulegraph marks themNEWLINE # by using the filename '-'. (But wants to use None,NEWLINE # so check for None, too, to be forward-compatible.)NEWLINE typ = PYZ_TYPE_PKGNEWLINE else:NEWLINE base, ext = os.path.splitext(os.path.basename(path))NEWLINE if base == '__init__':NEWLINE typ = PYZ_TYPE_PKGNEWLINE data = marshal.dumps(self.code_dict[name])NEWLINE else:NEWLINE # Any data files, that might be required by pkg_resources.NEWLINE typ = PYZ_TYPE_DATANEWLINE with open(path, 'rb') as fh:NEWLINE data = fh.read()NEWLINE # No need to use forward slash as path-separator here sinceNEWLINE # pkg_resources on Windows back slash as path-separator.NEWLINENEWLINE obj = zlib.compress(data, self.COMPRESSION_LEVEL)NEWLINENEWLINE # First compress then encrypt.NEWLINE if self.cipher:NEWLINE obj = self.cipher.encrypt(obj)NEWLINENEWLINE self.toc.append((name, (typ, self.lib.tell(), len(obj))))NEWLINE self.lib.write(obj)NEWLINENEWLINE def update_headers(self, tocpos):NEWLINE """NEWLINE add levelNEWLINE """NEWLINE ArchiveWriter.update_headers(self, tocpos)NEWLINE self.lib.write(struct.pack('!B', self.cipher is not None))NEWLINENEWLINENEWLINENEWLINEclass CTOC(object):NEWLINE """NEWLINE A class encapsulating the table of contents of a CArchive.NEWLINENEWLINE When written to disk, it is easily read from C.NEWLINE """NEWLINE ENTRYSTRUCT = '!iiiiBB' # (structlen, dpos, dlen, ulen, flag, typcd) followed by nameNEWLINE ENTRYLEN = struct.calcsize(ENTRYSTRUCT)NEWLINENEWLINE def __init__(self):NEWLINE self.data = []NEWLINENEWLINE def tobinary(self):NEWLINE """NEWLINE Return self as a binary string.NEWLINE """NEWLINE rslt = []NEWLINE for (dpos, dlen, ulen, flag, typcd, nm) in self.data:NEWLINE # Encode all names using UTF-8. This should be save asNEWLINE # standard python modules only contain ascii-charactersNEWLINE # (and standard shared libraries should have the same) andNEWLINE # thus the C-code still can handle this correctly.NEWLINE if is_py2 and isinstance(nm, str):NEWLINE nm = nm.decode(sys.getfilesystemencoding())NEWLINENEWLINE nm = nm.encode('utf-8')NEWLINE nmlen = len(nm) + 1 # add 1 for a '\0'NEWLINE # align to 16 byte boundary so xplatform C can readNEWLINE toclen = nmlen + self.ENTRYLENNEWLINE if toclen % 16 == 0:NEWLINE pad = b'\0'NEWLINE else:NEWLINE padlen = 16 - (toclen % 16)NEWLINE pad = b'\0' * padlenNEWLINE nmlen = nmlen + padlenNEWLINE rslt.append(struct.pack(self.ENTRYSTRUCT + '%is' % nmlen,NEWLINE nmlen + self.ENTRYLEN, dpos, dlen, ulen,NEWLINE flag, ord(typcd), nm + pad))NEWLINENEWLINE return b''.join(rslt)NEWLINENEWLINE def add(self, dpos, dlen, ulen, flag, typcd, nm):NEWLINE """NEWLINE Add an entry to the table of contents.NEWLINENEWLINE DPOS is data position.NEWLINE DLEN is data length.NEWLINE ULEN is the uncompressed data len.NEWLINE FLAG says if the data is compressed.NEWLINE TYPCD is the "type" of the entry (used by the C code)NEWLINE NM is the entry's name.NEWLINENEWLINE This function is used only while creating an executable.NEWLINE """NEWLINE # Ensure forward slashes in paths are on Windows converted to backNEWLINE # slashes '\\' since on Windows the bootloader works only with backNEWLINE # slashes.NEWLINE nm = os.path.normpath(nm)NEWLINE self.data.append((dpos, dlen, ulen, flag, typcd, nm))NEWLINENEWLINENEWLINEclass CArchiveWriter(ArchiveWriter):NEWLINE """NEWLINE An Archive subclass that can hold arbitrary data.NEWLINENEWLINE This class encapsulates all files that are bundled within an executable.NEWLINE It can contain ZlibArchive (Python .pyc files), dlls, Python C extensionsNEWLINE and all other data files that are bundled in --onefile mode.NEWLINENEWLINE Easily handled from C or from Python.NEWLINE """NEWLINE # MAGIC is usefull to verify that conversion of Python data typesNEWLINE # to C structure and back works properly.NEWLINE MAGIC = b'MEI\014\013\012\013\016'NEWLINE HDRLEN = 0NEWLINE LEVEL = 9NEWLINENEWLINE # Cookie - holds some information for the bootloader. C struct formatNEWLINE # definition. '!' at the beginning means network byte order.NEWLINE # C struct looks like:NEWLINE #NEWLINE # typedef struct _cookie {NEWLINE # char magic[8]; /* 'MEI\014\013\012\013\016' */NEWLINE # int len; /* len of entire package */NEWLINE # int TOC; /* pos (rel to start) of TableOfContents */NEWLINE # int TOClen; /* length of TableOfContents */NEWLINE # int pyvers; /* new in v4 */NEWLINE # char pylibname[64]; /* Filename of Python dynamic library. */NEWLINE # } COOKIE;NEWLINE #NEWLINE _cookie_format = '!8siiii64s'NEWLINE _cookie_size = struct.calcsize(_cookie_format)NEWLINENEWLINE def __init__(self, archive_path, logical_toc, pylib_name):NEWLINE """NEWLINE Constructor.NEWLINENEWLINE archive_path path name of file (create empty CArchive if path is None).NEWLINE start is the seekposition within PATH.NEWLINE len is the length of the CArchive (if 0, then read till EOF).NEWLINE pylib_name name of Python DLL which bootloader will use.NEWLINE """NEWLINE self._pylib_name = pylib_nameNEWLINENEWLINE # A CArchive created from scratch starts at 0, no leading bootloader.NEWLINE super(CArchiveWriter, self).__init__(archive_path, logical_toc)NEWLINENEWLINE def _start_add_entries(self, path):NEWLINE """NEWLINE Open an empty archive for addition of entries.NEWLINE """NEWLINE super(CArchiveWriter, self)._start_add_entries(path)NEWLINE # Override parents' toc {} with a class.NEWLINE self.toc = CTOC()NEWLINENEWLINE def add(self, entry):NEWLINE """NEWLINE Add an ENTRY to the CArchive.NEWLINENEWLINE ENTRY must have:NEWLINE entry[0] is name (under which it will be saved).NEWLINE entry[1] is fullpathname of the file.NEWLINE entry[2] is a flag for it's storage format (0==uncompressed,NEWLINE 1==compressed)NEWLINE entry[3] is the entry's type code.NEWLINE Version 5:NEWLINE If the type code is 'o':NEWLINE entry[0] is the runtime optionNEWLINE eg: v (meaning verbose imports)NEWLINE u (menaing unbuffered)NEWLINE W arg (warning option arg)NEWLINE s (meaning do site.py processing.NEWLINE """NEWLINE (nm, pathnm, flag, typcd) = entry[:4]NEWLINE # FIXME Could we make the version 5 the default one?NEWLINE # Version 5 - allow type 'o' = runtime option.NEWLINE code_data = NoneNEWLINE fh = NoneNEWLINE try:NEWLINE if typcd in ('o', 'd'):NEWLINE ulen = 0NEWLINE flag = 0NEWLINE elif typcd == 's':NEWLINE # If it's a source code file, compile it to a code object and marshallNEWLINE # the object so it can be unmarshalled by the bootloader.NEWLINENEWLINE code = get_code_object(nm, pathnm)NEWLINE code = strip_paths_in_code(code)NEWLINENEWLINE code_data = marshal.dumps(code)NEWLINE ulen = len(code_data)NEWLINE else:NEWLINE fh = open(pathnm, 'rb')NEWLINE ulen = os.fstat(fh.fileno()).st_sizeNEWLINE except IOError:NEWLINE print("Cannot find ('%s', '%s', %s, '%s')" % (nm, pathnm, flag, typcd))NEWLINE raiseNEWLINENEWLINE where = self.lib.tell()NEWLINE assert flag in range(3)NEWLINE if not fh and not code_data:NEWLINE # no need to write anythingNEWLINE passNEWLINE elif flag == 1:NEWLINE comprobj = zlib.compressobj(self.LEVEL)NEWLINE if code_data is not None:NEWLINE self.lib.write(comprobj.compress(code_data))NEWLINE else:NEWLINE assert fhNEWLINE while 1:NEWLINE buf = fh.read(16*1024)NEWLINE if not buf:NEWLINE breakNEWLINE self.lib.write(comprobj.compress(buf))NEWLINE self.lib.write(comprobj.flush())NEWLINENEWLINE else:NEWLINE if code_data is not None:NEWLINE self.lib.write(code_data)NEWLINE else:NEWLINE assert fhNEWLINE while 1:NEWLINE buf = fh.read(16*1024)NEWLINE if not buf:NEWLINE breakNEWLINE self.lib.write(buf)NEWLINENEWLINE dlen = self.lib.tell() - whereNEWLINE if typcd == 'm':NEWLINE if pathnm.find('.__init__.py') > -1:NEWLINE typcd = 'M'NEWLINENEWLINE # Record the entry in the CTOCNEWLINE self.toc.add(where, dlen, ulen, flag, typcd, nm)NEWLINENEWLINENEWLINE def save_trailer(self, tocpos):NEWLINE """NEWLINE Save the table of contents and the cookie for the bootlader toNEWLINE disk.NEWLINENEWLINE CArchives can be opened from the end - the cookie pointsNEWLINE back to the start.NEWLINE """NEWLINE tocstr = self.toc.tobinary()NEWLINE self.lib.write(tocstr)NEWLINE toclen = len(tocstr)NEWLINENEWLINE # now save teh cookieNEWLINE total_len = tocpos + toclen + self._cookie_sizeNEWLINE pyvers = sys.version_info[0] * 10 + sys.version_info[1]NEWLINE # Before saving cookie we need to convert it to correspondingNEWLINE # C representation.NEWLINE cookie = struct.pack(self._cookie_format, self.MAGIC, total_len,NEWLINE tocpos, toclen, pyvers,NEWLINE self._pylib_name.encode('ascii'))NEWLINE self.lib.write(cookie)NEWLINE """Given an algorithm object, run the algorithm."""NEWLINEfrom __future__ import division, print_functionNEWLINENEWLINEimport signalNEWLINEimport sysNEWLINEimport multiprocessing as mpNEWLINEimport osNEWLINEimport textwrapNEWLINEimport jsonNEWLINENEWLINEimport requestsNEWLINEimport sixNEWLINEimport codejailNEWLINEfrom codejail.safe_exec import not_safe_execNEWLINEfrom codejail.limits import set_limitNEWLINENEWLINENEWLINE__all__ = ["AlgorithmRunner"]NEWLINENEWLINENEWLINEclass GracefulExit(Exception):NEWLINE """Graceful exit exception class."""NEWLINENEWLINENEWLINEdef sigint_handler(signum, thread):NEWLINE """Handle interrupt signal."""NEWLINE raise GracefulExit()NEWLINENEWLINENEWLINEdef check_environ():NEWLINE """Check that all environment variable exists.NEWLINENEWLINE Note:NEWLINE - Required environment variables are `OPALALGO_SANDBOX_VENV` andNEWLINE `OPALALGO_SANDBOX_USER`.NEWLINENEWLINE """NEWLINE req_environ_vars = ['OPALALGO_SANDBOX_VENV', 'OPALALGO_SANDBOX_USER']NEWLINE for environ_var in req_environ_vars:NEWLINE if environ_var not in os.environ:NEWLINE raise RuntimeError(NEWLINE 'Environment variable {} not set'.format(environ_var))NEWLINENEWLINENEWLINEdef get_jail(python_version=sys.version_info[0]):NEWLINE """Return codejail object.NEWLINENEWLINE Note:NEWLINE - Please set environmental variables `OPALALGO_SANDBOX_VENV`NEWLINE and `OPALALGO_SANDBOX_USER` before calling this function.NEWLINE - `OPALALGO_SANDBOX_VENV` must be set to the path of the sandboxNEWLINE virtual environment.NEWLINE - `OPALALGO_SANDBOX_USER` must be set to the user running theNEWLINE sandboxed algorithms.NEWLINENEWLINE """NEWLINE sandbox_env = os.environ.get('OPALALGO_SANDBOX_VENV')NEWLINE sandbox_user = os.environ.get('OPALALGO_SANDBOX_USER')NEWLINE set_limit("REALTIME", None)NEWLINE set_limit("CPU", 15)NEWLINE codejail.configure(NEWLINE 'python',NEWLINE os.path.join(sandbox_env, 'bin', 'python'),NEWLINE user=sandbox_user)NEWLINE codejail.configure(NEWLINE 'python3',NEWLINE os.path.join(sandbox_env, 'bin', 'python'),NEWLINE user=sandbox_user)NEWLINE if python_version < 3:NEWLINE jail = codejail.get_codejail('python')NEWLINE else:NEWLINE jail = codejail.get_codejail('python3')NEWLINE return jailNEWLINENEWLINENEWLINEdef process_user_csv(params, user_csv_file, algorithm, dev_mode, sandboxing,NEWLINE jail):NEWLINE """Process a single user csv file.NEWLINENEWLINE Args:NEWLINE params (dict): Parameters for the request.NEWLINE user_csv_file (string): Path to user csv file.NEWLINE algorithm (dict): Dictionary with keys `code` and `className`NEWLINE specifying algorithm code and className.NEWLINE dev_mode (bool): Should the algorithm run in development mode orNEWLINE production mode.NEWLINE sandboxing (bool): Should sandboxing be used or not.NEWLINE jail (codejail.Jail): Jail object.NEWLINENEWLINE Returns:NEWLINE Result of the execution.NEWLINENEWLINE Raises:NEWLINE SafeExecException: If the execution wasn't successful.NEWLINENEWLINE """NEWLINE username = os.path.splitext(os.path.basename(user_csv_file))[0]NEWLINE globals_dict = {NEWLINE 'params': params,NEWLINE }NEWLINE user_specific_code = textwrap.dedent(NEWLINE """NEWLINE def run_code():NEWLINE import bandicootNEWLINENEWLINE algorithmobj = {}()NEWLINE bandicoot_user = bandicoot.read_csv(NEWLINE '{}', '', describe={}, warnings={})NEWLINE return algorithmobj.map(params, bandicoot_user)NEWLINE result = run_code()NEWLINE """.format(NEWLINE algorithm['className'], username,NEWLINE str(dev_mode), str(dev_mode)))NEWLINE code = "{}\n{}".format(algorithm['code'], user_specific_code)NEWLINE if sandboxing:NEWLINE jail.safe_exec(NEWLINE code, globals_dict, files=[user_csv_file])NEWLINE else:NEWLINE not_safe_exec(NEWLINE code, globals_dict, files=[user_csv_file])NEWLINE result = globals_dict['result']NEWLINE return resultNEWLINENEWLINENEWLINEdef mapper(writing_queue, params, file_queue, algorithm,NEWLINE dev_mode=False, sandboxing=True, python_version=2):NEWLINE """Call the map function and insert result into the queue if valid.NEWLINENEWLINE Args:NEWLINE writing_queue (mp.manager.Queue): Queue for inserting results.NEWLINE params (dict): Parameters to be used by each map of the algorithm.NEWLINE users_csv_files (list): List of paths of csv files of users.NEWLINE algorithm (dict): Dictionary with keys `code` and `className`NEWLINE specifying algorithm code and className.NEWLINE dev_mode (bool): Should the algorithm run in development mode orNEWLINE production mode.NEWLINE sandboxing (bool): Should sandboxing be used or not.NEWLINE python_version (int): Python version being used for sandboxing.NEWLINENEWLINE """NEWLINE jail = get_jail(python_version)NEWLINE while not file_queue.empty():NEWLINE filepath = NoneNEWLINE scaler = NoneNEWLINE try:NEWLINE result = file_queue.get(timeout=1)NEWLINE filepath, scaler = resultNEWLINE except Exception as exc:NEWLINE print(exc)NEWLINE breakNEWLINE result = process_user_csv(NEWLINE params, filepath, algorithm, dev_mode,NEWLINE sandboxing, jail)NEWLINE if result and is_valid_result(result):NEWLINE writing_queue.put((result, scaler))NEWLINE elif result and dev_mode:NEWLINE print("Error in result {}".format(result))NEWLINENEWLINENEWLINEdef scale_result(result, scaler):NEWLINE """Return scaled result.NEWLINENEWLINE Args:NEWLINE result (dict): Result.NEWLINE scaler (number): Factor by which results need to be scaled.NEWLINENEWLINE Returns:NEWLINE dict: Scaled result.NEWLINENEWLINE """NEWLINE scaled_result = {}NEWLINE for key, val in six.iteritems(result):NEWLINE scaled_result[key] = scaler * valNEWLINE return scaled_resultNEWLINENEWLINENEWLINEdef collector(writing_queue, params, dev_mode=False):NEWLINE """Collect the results in writing queue and post to aggregator.NEWLINENEWLINE Args:NEWLINE writing_queue (mp.manager.Queue): Queue from which collect results.NEWLINE results_csv_path (str): CSV where we have to save results.NEWLINE dev_mode (bool): Whether to run algorithm in development mode.NEWLINENEWLINE Returns:NEWLINE bool: True on successful exit if `dev_mode` is set to False.NEWLINENEWLINE Note:NEWLINE If `dev_mode` is set to true, then collector will just return all theNEWLINE results in a list format.NEWLINENEWLINE """NEWLINE result_processor = ResultProcessor(params, dev_mode)NEWLINE while True:NEWLINE # wait for result to appear in the queueNEWLINE processed_result = writing_queue.get()NEWLINE # if got signal 'kill' exit the loopNEWLINE if processed_result == 'kill':NEWLINE breakNEWLINE result, scaler = processed_resultNEWLINE result_processor(result, scaler=scaler)NEWLINE return result_processor.get_result()NEWLINENEWLINENEWLINEdef is_valid_result(result):NEWLINE """Check if result is valid.NEWLINENEWLINE Args:NEWLINE result: Output of the algorithm.NEWLINENEWLINE Note:NEWLINE Result is valid if it is a dict. All keys of the dict must beNEWLINE be a string. All values must be numbers. These results are sent toNEWLINE reducer which will sum, count, mean, median, mode of the valuesNEWLINE belonging to same key.NEWLINENEWLINE Example:NEWLINE - {"alpha1": 1, "ant199": 1, ..}NEWLINENEWLINE Returns:NEWLINE bool: Specifying if the result is valid or not.NEWLINENEWLINE Todo:NEWLINE * Define what is valid with privacy and other concernsNEWLINENEWLINE """NEWLINE # check result must be a dictNEWLINE if not isinstance(result, dict):NEWLINE return FalseNEWLINE # check each value must be an integer or floatNEWLINE if not (all([isinstance(x, six.integer_types) or isinstance(x, float)NEWLINE for x in six.itervalues(result)])):NEWLINE return FalseNEWLINE # check each key must be a string.NEWLINE if not (all([isinstance(x, six.string_types)NEWLINE for x in six.iterkeys(result)])):NEWLINE return FalseNEWLINE return TrueNEWLINENEWLINENEWLINEclass ResultProcessor(object):NEWLINE """Process results.NEWLINENEWLINE Args:NEWLINE params (dict): Dictionary of parameters.NEWLINE dev_mode (bool): Specify if dev_mode is on.NEWLINENEWLINE """NEWLINENEWLINE def __init__(self, params, dev_mode):NEWLINE """Initialize result processor."""NEWLINE self.params = paramsNEWLINE self.dev_mode = dev_modeNEWLINE self.result_list = []NEWLINENEWLINE def __call__(self, result, scaler=1):NEWLINE """Process the result.NEWLINENEWLINE If dev_mode is set to true, it appends the result to a list.NEWLINE Else it send the post request to `aggregationServiceUrl`.NEWLINENEWLINE Args:NEWLINE result (dict): Result of the processed algorithm.NEWLINE scaler (int): Scale results by what value.NEWLINENEWLINE """NEWLINE result = scale_result(result, scaler)NEWLINE if self.dev_mode:NEWLINE self.result_list.append(result)NEWLINE else:NEWLINE self._send_request(result)NEWLINENEWLINE def _send_request(self, result):NEWLINE """Send request to aggregationServiceUrl.NEWLINENEWLINE Args:NEWLINE result (dict): Result to be sent as an update.NEWLINENEWLINE """NEWLINE response = requests.post(NEWLINE self.params['aggregationServiceUrl'], json={'update': result})NEWLINE if response.status_code != 200:NEWLINE raise RuntimeError(NEWLINE 'Aggregation service returned {}'.format(NEWLINE response.status_code))NEWLINENEWLINE def get_result(self):NEWLINE """Return the result after processing.NEWLINENEWLINE Returns:NEWLINE dict: if dev_mode is set to true else returns `True`NEWLINENEWLINE """NEWLINE if self.dev_mode:NEWLINE return self.result_listNEWLINE return TrueNEWLINENEWLINENEWLINEclass AlgorithmRunner(object):NEWLINE """Algorithm runner.NEWLINENEWLINE Args:NEWLINE algorithm (dict): Dictionary containing `code` and `className`.NEWLINE dev_mode (bool): Development mode switchNEWLINE multiprocess (bool): Use multiprocessing or single process forNEWLINE complete execution.NEWLINE sandboxing (bool): Use sandboxing for execution or execute in unsafeNEWLINE environment.NEWLINENEWLINE """NEWLINENEWLINE def __init__(self, algorithm, dev_mode=False, multiprocess=True,NEWLINE sandboxing=True):NEWLINE """Initialize class."""NEWLINE self.algorithm = algorithmNEWLINE self.dev_mode = dev_modeNEWLINE self.multiprocess = multiprocessNEWLINE self.sandboxing = sandboxingNEWLINENEWLINE def __call__(self, params, data_dir, num_threads, weights_file=None):NEWLINE """Run algorithm.NEWLINENEWLINE Selects the csv files from the data directory. Divides the csv filesNEWLINE into chunks of equal size across the `num_threads` threads. Each threadNEWLINE performs calls map function of the csv file and processes the result.NEWLINE The collector thread, waits for results before posting it to aggregatorNEWLINE service.NEWLINENEWLINE Args:NEWLINE params (dict): Dictionary containing all the parameters for theNEWLINE algorithmNEWLINE data_dir (str): Data directory with csv files.NEWLINE num_threads (int): Number of threadsNEWLINE weights_file (str): Path to the json file containing weights.NEWLINENEWLINE Returns:NEWLINE int: Amount of time required for computation in microseconds.NEWLINENEWLINE """NEWLINE check_environ()NEWLINE csv_files = [os.path.join(NEWLINE os.path.abspath(data_dir), f) for f in os.listdir(data_dir)NEWLINE if f.endswith('.csv')]NEWLINE csv2weights = self._get_weights(csv_files, weights_file)NEWLINE if self.multiprocess:NEWLINE return self._multiprocess(NEWLINE params, num_threads, csv_files, csv2weights)NEWLINE return self._singleprocess(params, csv_files, csv2weights)NEWLINENEWLINE def _get_weights(self, csv_files, weights_file):NEWLINE """Return weights for each user if available, else return 1."""NEWLINE weights = NoneNEWLINE if weights_file:NEWLINE with open(weights_file) as file_path:NEWLINE weights = json.load(file_path)NEWLINE csv2weights = {}NEWLINE for file_path in csv_files:NEWLINE csv_weight = 1 # default weightNEWLINE user = os.path.splitext(os.path.basename(file_path))[0]NEWLINE if weights and user in weights:NEWLINE csv_weight = weights[user]NEWLINE csv2weights[file_path] = csv_weightNEWLINE return csv2weightsNEWLINENEWLINE def _multiprocess(self, params, num_threads, csv_files, csv2weights):NEWLINE # set up parallel processingNEWLINE manager = mp.Manager()NEWLINE writing_queue = manager.Queue()NEWLINE file_queue = manager.Queue()NEWLINE for fpath in csv_files:NEWLINE file_queue.put((fpath, csv2weights[fpath]))NEWLINE jobs = []NEWLINENEWLINE # additional 1 process for writerNEWLINE signal.signal(signal.SIGINT, signal.SIG_IGN)NEWLINE pool = mp.Pool(processes=num_threads + 1)NEWLINE signal.signal(signal.SIGINT, sigint_handler)NEWLINE try:NEWLINE collector_job = pool.apply_async(NEWLINE collector, (writing_queue, params, self.dev_mode))NEWLINENEWLINE # Compute the densityNEWLINE for _ in range(num_threads):NEWLINE jobs.append(pool.apply_async(mapper, (NEWLINE writing_queue, params, file_queue, self.algorithm,NEWLINE self.dev_mode, self.sandboxing)))NEWLINENEWLINE # Clean up parallel processing (close pool, wait for processes toNEWLINE # finish, kill writing_queue, wait for queue to be killed)NEWLINE pool.close()NEWLINE for job in jobs:NEWLINE job.get()NEWLINE writing_queue.put('kill') # stop collectionNEWLINE result = collector_job.get()NEWLINE pool.join()NEWLINE return resultNEWLINE except GracefulExit:NEWLINE pool.terminate()NEWLINE print("Exiting")NEWLINE pool.join()NEWLINE raise RuntimeError("Received interrupt signal, exiting. Bye.")NEWLINENEWLINE def _singleprocess(self, params, csv_files, csv2weights):NEWLINE result_processor = ResultProcessor(params, self.dev_mode)NEWLINE jail = get_jail(python_version=2)NEWLINE for fpath in csv_files:NEWLINE scaler = csv2weights[fpath]NEWLINE result = process_user_csv(NEWLINE params, fpath, self.algorithm, self.dev_mode, self.sandboxing, jail)NEWLINE result_processor(result, scaler=scaler)NEWLINE return result_processor.get_result()NEWLINE import jsonNEWLINEfrom controller.client import ClientNEWLINENEWLINENEWLINEdef offerview(user, offer, taking):NEWLINE isvalid = _offer(user, offer, taking)NEWLINE if isvalid:NEWLINE print('A troca foi anunciada')NEWLINE return isvalidNEWLINE else:NEWLINE print('Lamentamos, mas não alguma coisa não está correta (quantidade insuficente ou ID incorreto)')NEWLINE return NoneNEWLINENEWLINENEWLINEdef _offer(user, offer, taking):NEWLINE client = Client()NEWLINE response = client.createTrade(idUser=user.idUser, offer=offer, taking=taking)NEWLINE isvalid = response.responseNEWLINENEWLINE return isvalidNEWLINE """Resnet v1 model variants.NEWLINECode branched out from slim/nets/resnet_v1.py, and please refer to it forNEWLINEmore details.NEWLINEThe original version ResNets-v1 were proposed by:NEWLINE[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian SunNEWLINE Deep Residual Learning for Image Recognition. arXiv:1512.03385NEWLINE"""NEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import print_functionNEWLINENEWLINEimport functoolsNEWLINEimport tensorflow as tfNEWLINENEWLINEfrom models import resnet_utilsNEWLINEfrom utils.metrics import *NEWLINEfrom utils.loss import *NEWLINEimport warningsNEWLINEwarnings.filterwarnings('ignore')NEWLINEfrom tensorflow.contrib import layersNEWLINEfrom tensorflow.contrib.framework.python.ops import add_arg_scopeNEWLINEfrom tensorflow.contrib.framework.python.ops import arg_scopeNEWLINEfrom tensorflow.contrib.layers.python.layers import utilsNEWLINEfrom tensorflow.contrib.layers.python.layers import regularizersNEWLINENEWLINE_DEFAULT_MULTI_GRID = [1, 1, 1]NEWLINENEWLINEdef update_argparser(parser):NEWLINE parser.set_defaults(NEWLINE train_steps=40000,NEWLINE learning_rate=((20000,30000), (0.0001, 0.00001,0.000001)),NEWLINE save_checkpoints_steps=200,NEWLINE )NEWLINENEWLINENEWLINE@add_arg_scopeNEWLINEdef bottleneck(inputs,NEWLINE depth,NEWLINE depth_bottleneck,NEWLINE stride,NEWLINE unit_rate=1,NEWLINE rate=1,NEWLINE outputs_collections=None,NEWLINE scope=None):NEWLINE """Bottleneck residual unit variant with BN after convolutions.NEWLINE This is the original residual unit proposed in [1]. See Fig. 1(a) of [2] forNEWLINE its definition. Note that we use here the bottleneck variant which has anNEWLINE extra bottleneck layer.NEWLINE When putting together two consecutive ResNet blocks that use this unit, oneNEWLINE should use stride = 2 in the last unit of the first block.NEWLINE Args:NEWLINE inputs: A tensor of size [batch, height, width, channels].NEWLINE depth: The depth of the ResNet unit output.NEWLINE depth_bottleneck: The depth of the bottleneck layers.NEWLINE stride: The ResNet unit's stride. Determines the amount of downsampling ofNEWLINE the units output compared to its input.NEWLINE unit_rate: An integer, unit rate for atrous convolution.NEWLINE rate: An integer, rate for atrous convolution.NEWLINE outputs_collections: Collection to add the ResNet unit output.NEWLINE scope: Optional variable_scope.NEWLINE Returns:NEWLINE The ResNet unit's output.NEWLINE """NEWLINE with tf.variable_scope(scope, 'bottleneck_v1', [inputs]) as sc:NEWLINE depth_in = utils.last_dimension(inputs.get_shape(), min_rank=4)NEWLINE if depth == depth_in:NEWLINE shortcut = resnet_utils.subsample(inputs, stride, 'shortcut')NEWLINE else:NEWLINE shortcut = layers.conv2d(NEWLINE inputs,NEWLINE depth,NEWLINE [1, 1],NEWLINE stride=stride,NEWLINE activation_fn=None,NEWLINE scope='shortcut')NEWLINENEWLINE residual = layers.conv2d(inputs, depth_bottleneck, [1, 1], stride=1,NEWLINE scope='conv1')NEWLINE residual = resnet_utils.conv2d_same(residual, depth_bottleneck, 3, stride,NEWLINE rate=rate*unit_rate, scope='conv2')NEWLINE residual = layers.conv2d(residual, depth, [1, 1], stride=1,NEWLINE activation_fn=None, scope='conv3')NEWLINE output = tf.nn.relu(shortcut + residual)NEWLINENEWLINE return utils.collect_named_outputs(outputs_collections,NEWLINE sc.name,NEWLINE output)NEWLINENEWLINENEWLINEdef root_block_fn_for_beta_variant(net):NEWLINE """Gets root_block_fn for beta variant.NEWLINE ResNet-v1 beta variant modifies the first original 7x7 convolution to threeNEWLINE 3x3 convolutions.NEWLINE Args:NEWLINE net: A tensor of size [batch, height, width, channels], input to the model.NEWLINE Returns:NEWLINE A tensor after three 3x3 convolutions.NEWLINE """NEWLINE net = resnet_utils.conv2d_same(net, 64, 3, stride=2, scope='conv1_1')NEWLINE net = resnet_utils.conv2d_same(net, 64, 3, stride=1, scope='conv1_2')NEWLINE net = resnet_utils.conv2d_same(net, 128, 3, stride=1, scope='conv1_3')NEWLINENEWLINE return netNEWLINENEWLINENEWLINEdef resnet_v1_beta(inputs,NEWLINE blocks,NEWLINE num_classes=None,NEWLINE is_training=None,NEWLINE global_pool=True,NEWLINE output_stride=None,NEWLINE root_block_fn=None,NEWLINE scope=None):NEWLINE """Generator for v1 ResNet models (beta variant).NEWLINE This function generates a family of modified ResNet v1 models. In particular,NEWLINE the first original 7x7 convolution is replaced with three 3x3 convolutions.NEWLINE See the resnet_v1_*() methods for specific model instantiations, obtained byNEWLINE selecting different block instantiations that produce ResNets of variousNEWLINE depths.NEWLINE The code is modified from slim/nets/resnet_v1.py, and please refer to it forNEWLINE more details.NEWLINE Args:NEWLINE inputs: A tensor of size [batch, height_in, width_in, channels].NEWLINE blocks: A list of length equal to the number of ResNet blocks. Each elementNEWLINE is a resnet_utils.Block object describing the units in the block.NEWLINE num_classes: Number of predicted classes for classification tasks. If NoneNEWLINE we return the features before the logit layer.NEWLINE is_training: Enable/disable is_training for batch normalization.NEWLINE global_pool: If True, we perform global average pooling before computing theNEWLINE logits. Set to True for image classification, False for dense prediction.NEWLINE output_stride: If None, then the output will be computed at the nominalNEWLINE network stride. If output_stride is not None, it specifies the requestedNEWLINE ratio of input to output spatial resolution.NEWLINE root_block_fn: The function consisting of convolution operations applied toNEWLINE the root input. If root_block_fn is None, use the original setting ofNEWLINE RseNet-v1, which is simply one convolution with 7x7 kernel and stride=2.NEWLINE reuse: whether or not the network and its variables should be reused. To beNEWLINE able to reuse 'scope' must be given.NEWLINE scope: Optional variable_scope.NEWLINE Returns:NEWLINE net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].NEWLINE If global_pool is False, then height_out and width_out are reduced by aNEWLINE factor of output_stride compared to the respective height_in and width_in,NEWLINE else both height_out and width_out equal one. If num_classes is None, thenNEWLINE net is the output of the last ResNet block, potentially after globalNEWLINE average pooling. If num_classes is not None, net contains the pre-softmaxNEWLINE activations.NEWLINE end_points: A dictionary from components of the network to the correspondingNEWLINE activation.NEWLINE Raises:NEWLINE ValueError: If the target output_stride is not valid.NEWLINE """NEWLINE if root_block_fn is None:NEWLINE root_block_fn = functools.partial(resnet_utils.conv2d_same,NEWLINE num_outputs=64,NEWLINE kernel_size=7,NEWLINE stride=2,NEWLINE scope='conv1')NEWLINE with tf.variable_scope(scope, 'resnet_v1', [inputs]) as sc:NEWLINE end_points_collection = sc.original_name_scope + '_end_points'NEWLINE with arg_scope([layers.conv2d, bottleneck,NEWLINE resnet_utils.stack_blocks_dense],NEWLINE outputs_collections=end_points_collection):NEWLINE if is_training is not None:NEWLINE arg_sc = arg_scope([layers.batch_norm], is_training=is_training)NEWLINE else:NEWLINE arg_sc = arg_scope([])NEWLINE with arg_sc:NEWLINE net = inputsNEWLINE if output_stride is not None:NEWLINE if output_stride % 4 != 0:NEWLINE raise ValueError('The output_stride needs to be a multiple of 4.')NEWLINE output_stride /= 4NEWLINE print(str(output_stride) + 'Before resnet blocks')NEWLINE net = root_block_fn(net)NEWLINE net = layers.max_pool2d(net, 3, stride=2, padding='SAME', scope='pool1')NEWLINE net = resnet_utils.stack_blocks_dense(net, blocks, output_stride)NEWLINENEWLINE if global_pool:NEWLINE # Global average pooling.NEWLINE net = tf.reduce_mean(net, [1, 2], name='pool5', keepdims=True)NEWLINE if num_classes is not None:NEWLINE net = layers.conv2d(net, num_classes, [1, 1], activation_fn=None,NEWLINE normalizer_fn=None, scope='logit')NEWLINE # Convert end_points_collection into a dictionary of end_points.NEWLINE end_points = utils.convert_collection_to_dict(end_points_collection)NEWLINE if num_classes is not None:NEWLINE end_points['predictions'] = layers.softmax(net, scope='predictions')NEWLINE return net, end_pointsNEWLINENEWLINENEWLINEdef resnet_v1_beta_block(scope, base_depth, num_units, stride):NEWLINE """Helper function for creating a resnet_v1 beta variant bottleneck block.NEWLINE Args:NEWLINE scope: The scope of the block.NEWLINE base_depth: The depth of the bottleneck layer for each unit.NEWLINE num_units: The number of units in the block.NEWLINE stride: The stride of the block, implemented as a stride in the last unit.NEWLINE All other units have stride=1.NEWLINE Returns:NEWLINE A resnet_v1 bottleneck block.NEWLINE """NEWLINE return resnet_utils.Block(scope, bottleneck, [{NEWLINE 'depth': base_depth * 4,NEWLINE 'depth_bottleneck': base_depth,NEWLINE 'stride': 1,NEWLINE 'unit_rate': 1NEWLINE }] * (num_units - 1) + [{NEWLINE 'depth': base_depth * 4,NEWLINE 'depth_bottleneck': base_depth,NEWLINE 'stride': stride,NEWLINE 'unit_rate': 1NEWLINE }])NEWLINENEWLINEdef resnet_v1_101_beta(inputs,NEWLINE num_classes=None,NEWLINE is_training=None,NEWLINE global_pool=False,NEWLINE output_stride=None,NEWLINE multi_grid=None,NEWLINE scope='resnet_v1_101'):NEWLINE """Resnet v1 101 beta variant.NEWLINE This variant modifies the first convolution layer of ResNet-v1-101. InNEWLINE particular, it changes the original one 7x7 convolution to three 3x3NEWLINE convolutions.NEWLINE Args:NEWLINE inputs: A tensor of size [batch, height_in, width_in, channels].NEWLINE num_classes: Number of predicted classes for classification tasks. If NoneNEWLINE we return the features before the logit layer.NEWLINE is_training: Enable/disable is_training for batch normalization.NEWLINE global_pool: If True, we perform global average pooling before computing theNEWLINE logits. Set to True for image classification, False for dense prediction.NEWLINE output_stride: If None, then the output will be computed at the nominalNEWLINE network stride. If output_stride is not None, it specifies the requestedNEWLINE ratio of input to output spatial resolution.NEWLINE multi_grid: Employ a hierarchy of different atrous rates within network.NEWLINE reuse: whether or not the network and its variables should be reused. To beNEWLINE able to reuse 'scope' must be given.NEWLINE scope: Optional variable_scope.NEWLINE Returns:NEWLINE net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].NEWLINE If global_pool is False, then height_out and width_out are reduced by aNEWLINE factor of output_stride compared to the respective height_in and width_in,NEWLINE else both height_out and width_out equal one. If num_classes is None, thenNEWLINE net is the output of the last ResNet block, potentially after globalNEWLINE average pooling. If num_classes is not None, net contains the pre-softmaxNEWLINE activations.NEWLINE end_points: A dictionary from components of the network to the correspondingNEWLINE activation.NEWLINE Raises:NEWLINE ValueError: if multi_grid is not None and does not have length = 3.NEWLINE """NEWLINE if multi_grid is None:NEWLINE multi_grid = _DEFAULT_MULTI_GRIDNEWLINE else:NEWLINE if len(multi_grid) != 3:NEWLINE raise ValueError('Expect multi_grid to have length 3.')NEWLINENEWLINE blocks = [NEWLINE resnet_v1_beta_block(NEWLINE 'block1', base_depth=64, num_units=3, stride=2),NEWLINE resnet_v1_beta_block(NEWLINE 'block2', base_depth=128, num_units=4, stride=2),NEWLINE resnet_v1_beta_block(NEWLINE 'block3', base_depth=256, num_units=23, stride=2),NEWLINE resnet_utils.Block('block4', bottleneck, [NEWLINE {'depth': 2048,NEWLINE 'depth_bottleneck': 512,NEWLINE 'stride': 1,NEWLINE 'unit_rate': rate} for rate in multi_grid]),NEWLINE ]NEWLINE return resnet_v1_beta(NEWLINE inputs,NEWLINE blocks=blocks,NEWLINE num_classes=num_classes,NEWLINE is_training=is_training,NEWLINE global_pool=global_pool,NEWLINE output_stride=output_stride,NEWLINE root_block_fn=functools.partial(root_block_fn_for_beta_variant),NEWLINE scope=scope)NEWLINENEWLINEdef atrous_spatial_pyramid_pooling(net, scope, output_stride, is_training, weight_decay, depth=256):NEWLINE """NEWLINE ASPP consists of (a) one 1×1 convolution and three 3×3 convolutions with rates = (6, 12, 18) when output stride = 16NEWLINE when output stride = 8, rates are doubledNEWLINE (all with 256 filters and batch normalization), and (b) the image-level features as described in https://arxiv.org/abs/1706.05587NEWLINE :param net: tensor of shape [BATCH_SIZE, WIDTH, HEIGHT, DEPTH]NEWLINE :param scope: scope name of the aspp layerNEWLINE :return: network layer with aspp applyed to it.NEWLINE """NEWLINE if output_stride == 16:NEWLINE rates = [6,12,18]NEWLINE elif output_stride == 8:NEWLINE rates = [12,24,36]NEWLINENEWLINE with tf.variable_scope(scope):NEWLINE batch_norm_params = {NEWLINE 'is_training': is_training,NEWLINE 'decay': 0.9997,NEWLINE 'epsilon': 1e-5,NEWLINE 'scale': True,NEWLINE }NEWLINENEWLINE with arg_scope(NEWLINE [layers.conv2d],NEWLINE # comment next line of code if multiple gpus are usedNEWLINE weights_regularizer=regularizers.l2_regularizer(weight_decay),NEWLINE activation_fn=tf.nn.relu,NEWLINE normalizer_fn=layers.batch_norm,NEWLINE normalizer_params=batch_norm_params):NEWLINE NEWLINE with arg_scope([layers.batch_norm], **batch_norm_params):NEWLINENEWLINE feature_map_size = tf.shape(net)NEWLINE # apply global average poolingNEWLINE image_level_features = tf.reduce_mean(net, [1, 2], name='image_level_global_pool', keepdims=True)NEWLINE image_level_features = layers.conv2d(image_level_features, depth, [1, 1], scope="image_level_conv_1x1",NEWLINE activation_fn=None)NEWLINE image_level_features = tf.image.resize_bilinear(image_level_features, (feature_map_size[1], feature_map_size[2]))NEWLINENEWLINE at_pool1x1 = layers.conv2d(net, depth, [1, 1], scope="conv_1x1_0", activation_fn=None)NEWLINENEWLINE at_pool3x3_1 = layers.conv2d(net, depth, [3, 3], scope="conv_3x3_1", rate=rates[0], activation_fn=None)NEWLINENEWLINE at_pool3x3_2 = layers.conv2d(net, depth, [3, 3], scope="conv_3x3_2", rate=rates[1], activation_fn=None)NEWLINENEWLINE at_pool3x3_3 = layers.conv2d(net, depth, [3, 3], scope="conv_3x3_3", rate=rates[2], activation_fn=None)NEWLINENEWLINE net = tf.concat((image_level_features, at_pool1x1, at_pool3x3_1, at_pool3x3_2, at_pool3x3_3), axis=3,NEWLINE name="concat")NEWLINE net = layers.conv2d(net, depth, [1, 1], scope="conv_1x1_output", activation_fn=None)NEWLINE net = layers.dropout(net, keep_prob=0.9, is_training=is_training, scope="dropout")NEWLINE return netNEWLINENEWLINE#用@add_arg_scope修饰目标函数NEWLINE#用with arg_scope(...) 设置默认参数.NEWLINEdef deeplab_v3(inputs, args, is_training, output_stride):NEWLINENEWLINE # inputs has shape - Original: [batch, 513, 513, 3]NEWLINE with arg_scope(resnet_utils.resnet_arg_scope(args.l2_regularizer, is_training)):NEWLINE _, end_points = resnet_v1_101_beta(inputs,NEWLINE args.num_classes,NEWLINE is_training=is_training,NEWLINE global_pool=False,NEWLINE output_stride=output_stride,NEWLINE multi_grid=args.multi_grid)NEWLINENEWLINE with tf.variable_scope("DeepLab_v3"):NEWLINENEWLINE # get block 4 feature outputsNEWLINE net = end_points[args.resnet_model + '/block4']NEWLINENEWLINE net = atrous_spatial_pyramid_pooling(net, "ASPP_layer", output_stride, is_training, args.l2_regularizer, depth=256)NEWLINENEWLINE net = layers.conv2d(net, args.num_classes, [1, 1], activation_fn=None,NEWLINE normalizer_fn=None, scope='logits')NEWLINENEWLINE size = tf.shape(inputs)[1:3]NEWLINE # resize the output logits to match the labels dimensionsNEWLINE net = tf.image.resize_bilinear(net, size)NEWLINE return netNEWLINENEWLINEdef model_fn(features, labels, mode, params):NEWLINE ''' Model function'''NEWLINENEWLINE output_stride = NoneNEWLINENEWLINE if mode == tf.estimator.ModeKeys.TRAIN:NEWLINE train = TrueNEWLINE output_stride = params.train_output_strideNEWLINE else:NEWLINE train = FalseNEWLINE output_stride = params.eval_output_strideNEWLINE NEWLINE img_input = tf.reshape(features, [-1, params.crop_size, params.crop_size, 3])NEWLINENEWLINE # Create networkNEWLINE raw_output = deeplab_v3(img_input, params, train, output_stride)NEWLINENEWLINE predictions = tf.argmax(raw_output, axis=-1)NEWLINENEWLINE # Setup the estimator according to the phase (Train, eval)NEWLINE reduced_loss = NoneNEWLINE train_op = NoneNEWLINE eval_metric_ops = {}NEWLINENEWLINE # compute loss(train and eval)NEWLINE loss = softmax_sparse_crossentropy_ignoring_last_label(labels,raw_output)NEWLINENEWLINE # L2 regularizationNEWLINE l2_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)NEWLINENEWLINE # Trainable VariablesNEWLINE #all_trainable = tf.trainable_variables()NEWLINE # L2 regularizationNEWLINE #l2_losses = [params.l2_regularizer * tf.nn.l2_loss(v) for v in all_trainable if 'weights' in v.name]NEWLINENEWLINE # Loss functionNEWLINE reduced_loss = tf.reduce_mean(loss) + tf.add_n(l2_losses)NEWLINENEWLINENEWLINE # evaluation metricNEWLINE miou, update_op = mIOU(raw_output,labels,params.num_classes,img_input)NEWLINENEWLINENEWLINE # configure trainingNEWLINE if mode == tf.estimator.ModeKeys.TRAIN:NEWLINE # piecewise learning rate schedulerNEWLINE global_step = tf.train.get_or_create_global_step()NEWLINE learning_rate = tf.train.piecewise_constant(global_step, params.learning_rate[0], params.learning_rate[1])NEWLINENEWLINE '''NEWLINE # learning rate schedulerNEWLINE global_step = tf.train.get_or_create_global_step()NEWLINE starter_learning_rate = 0.0001NEWLINE end_learning_rate = 0NEWLINE decay_steps = params.train_stepsNEWLINE learning_rate = tf.train.polynomial_decay(starter_learning_rate, global_step,NEWLINE decay_steps, end_learning_rate,NEWLINE power=0.9)NEWLINE '''NEWLINE NEWLINE # SGD + momentum optimizerNEWLINE optimizer = tf.train.MomentumOptimizer(learning_rate,momentum = 0.9)NEWLINE # comment out next two lines if batch norm is frozenNEWLINE # NOTE still need this because aspp needs batch normNEWLINE update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)NEWLINE with tf.control_dependencies(update_ops):NEWLINE train_op = optimizer.minimize(reduced_loss, global_step=tf.train.get_or_create_global_step())NEWLINENEWLINE if mode == tf.estimator.ModeKeys.EVAL:NEWLINE eval_metric_ops = {NEWLINE 'miou': (miou, update_op)NEWLINE }NEWLINENEWLINE return tf.estimator.EstimatorSpec(NEWLINE mode=mode,NEWLINE predictions=predictions,NEWLINE loss=reduced_loss,NEWLINE train_op=train_op,NEWLINE eval_metric_ops=eval_metric_ops,NEWLINE export_outputs=None,NEWLINE )NEWLINE import jsonNEWLINEimport osNEWLINENEWLINEimport requestsNEWLINENEWLINENEWLINEclass _SdcCommon(object):NEWLINE '''Interact with the Sysdig Monitor/Secure API.NEWLINENEWLINE **Arguments**NEWLINE - **token**: A Sysdig Monitor/Secure API token from the *Sysdig Cloud API* section of the Settings page for `monitor `_ or .`secure `_.NEWLINE - **sdc_url**: URL for contacting the Sysdig API server. Set this in `On-Premises installs `__.NEWLINE - **ssl_verify**: Whether to verify certificate. Set to False if using a self-signed certificate in an `On-Premises install `__.NEWLINE - **custom_headers**: [dict] Pass in custom headers. Useful for authentication and will override the default headers.NEWLINENEWLINE **Returns**NEWLINE An object for further interactions with the Sysdig Monitor/Secure API. See methods below.NEWLINE '''NEWLINE lasterr = NoneNEWLINENEWLINE def __init__(self, token="", sdc_url='https://app.sysdigcloud.com', ssl_verify=True, custom_headers=None):NEWLINE self.token = os.environ.get("SDC_TOKEN", token)NEWLINE self.hdrs = self.__get_headers(custom_headers)NEWLINE self.url = os.environ.get("SDC_URL", sdc_url).rstrip('/')NEWLINE self.ssl_verify = os.environ.get("SDC_SSL_VERIFY", None)NEWLINE if self.ssl_verify == None:NEWLINE self.ssl_verify = ssl_verifyNEWLINE else:NEWLINE if self.ssl_verify.lower() in ['true', 'false']:NEWLINE self.ssl_verify = self.ssl_verify.lower() == 'true'NEWLINENEWLINE def __get_headers(self, custom_headers):NEWLINE headers = {NEWLINE 'Content-Type': 'application/json',NEWLINE 'Authorization': 'Bearer ' + self.tokenNEWLINE }NEWLINE if custom_headers:NEWLINE headers.update(custom_headers)NEWLINE return headersNEWLINENEWLINE def _checkResponse(self, res):NEWLINE if res.status_code >= 300: # FIXME: Should it be >=400? 301 = Moved Permanently, 302 = Found, 303 = See OtherNEWLINE errorcode = res.status_codeNEWLINE self.lasterr = NoneNEWLINENEWLINE try:NEWLINE j = res.json()NEWLINE except Exception:NEWLINE self.lasterr = 'status code ' + str(errorcode)NEWLINE return FalseNEWLINENEWLINE if 'errors' in j:NEWLINE error_msgs = []NEWLINE for error in j['errors']:NEWLINE error_msg = []NEWLINE if 'message' in error:NEWLINE error_msg.append(error['message'])NEWLINENEWLINE if 'reason' in error:NEWLINE error_msg.append(error['reason'])NEWLINENEWLINE error_msgs.append(': '.join(error_msg))NEWLINENEWLINE self.lasterr = '\n'.join(error_msgs)NEWLINE elif 'message' in j:NEWLINE self.lasterr = j['message']NEWLINE else:NEWLINE self.lasterr = 'status code ' + str(errorcode)NEWLINE return FalseNEWLINE return TrueNEWLINENEWLINE def get_user_info(self):NEWLINE '''**Description**NEWLINE Get details about the current user.NEWLINENEWLINE **Success Return Value**NEWLINE A dictionary containing information about the user, for example its email and the maximum number of agents it can install.NEWLINENEWLINE **Example**NEWLINE `examples/print_user_info.py `_NEWLINE '''NEWLINE res = requests.get(self.url + '/api/user/me', headers=self.hdrs, verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def get_user_token(self):NEWLINE '''**Description**NEWLINE Return the API token of the current user.NEWLINENEWLINE **Success Return Value**NEWLINE A string containing the user token.NEWLINE '''NEWLINE res = requests.get(self.url + '/api/token', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE tkinfo = res.json()NEWLINENEWLINE return [True, tkinfo['token']['key']]NEWLINENEWLINE def get_connected_agents(self):NEWLINE '''**Description**NEWLINE Return the agents currently connected to Sysdig Monitor for the current user.NEWLINENEWLINE **Success Return Value**NEWLINE A list of the agents with all their attributes.NEWLINE '''NEWLINE res = requests.get(self.url + '/api/agents/connected', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE data = res.json()NEWLINE return [True, data['agents']]NEWLINENEWLINE def get_n_connected_agents(self):NEWLINE '''**Description**NEWLINE Return the number of agents currently connected to Sysdig Monitor for the current user.NEWLINENEWLINE **Success Return Value**NEWLINE An integer number.NEWLINE '''NEWLINE res = requests.get(self.url + '/api/agents/connected', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE data = res.json()NEWLINE return [True, data['total']]NEWLINENEWLINE def list_notification_channels(self):NEWLINE '''**Description**NEWLINE List all configured Notification ChannelsNEWLINENEWLINE **Arguments**NEWLINE noneNEWLINENEWLINE **Success Return Value**NEWLINE A JSON representation of all the notification channelsNEWLINE '''NEWLINE res = requests.get(self.url + '/api/notificationChannels', headers=self.hdrs, verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def get_notification_ids(self, channels=None):NEWLINE '''**Description**NEWLINE Get an array of all configured Notification Channel IDs, or a filtered subset of them.NEWLINENEWLINE **Arguments**NEWLINE - **channels**: an optional array of dictionaries to limit the set of Notification Channel IDs returned. If not specified, IDs for all configured Notification Channels are returned. Each dictionary contains a ``type`` field that can be one of the available types of Notification Channel (``EMAIL``, ``SNS``, ``PAGER_DUTY``, ``SLACK``, ``OPSGENIE``, ``VICTOROPS``, ``WEBHOOK``) as well as additional elements specific to each channel type.NEWLINENEWLINE **Success Return Value**NEWLINE An array of Notification Channel IDs (integers).NEWLINENEWLINE **Examples**NEWLINE - `examples/create_alert.py `_NEWLINE - `examples/restore_alerts.py `_NEWLINE '''NEWLINENEWLINE res = requests.get(self.url + '/api/notificationChannels', headers=self.hdrs, verify=self.ssl_verify)NEWLINENEWLINE if not self._checkResponse(res):NEWLINE return False, self.lasterrNEWLINENEWLINE ids = []NEWLINENEWLINE # If no array of channel types/names was provided to filter by,NEWLINE # just return them all.NEWLINE if channels is None:NEWLINE for ch in res.json()["notificationChannels"]:NEWLINE ids.append(ch['id'])NEWLINE return [True, ids]NEWLINENEWLINE # Return the filtered set of channels based on the provided types/names array.NEWLINE # Should try and improve this M * N lookupNEWLINE for c in channels:NEWLINE found = FalseNEWLINE for ch in res.json()["notificationChannels"]:NEWLINE if c['type'] == ch['type']:NEWLINE if c['type'] == 'SNS':NEWLINE opt = ch['options']NEWLINE if set(opt['snsTopicARNs']) == set(c['snsTopicARNs']):NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE elif c['type'] == 'EMAIL':NEWLINE opt = ch['options']NEWLINE if 'emailRecipients' in c:NEWLINE if set(c['emailRecipients']) == set(opt['emailRecipients']):NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE elif 'name' in c:NEWLINE if c['name'] == ch.get('name'):NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE elif c['type'] == 'PAGER_DUTY':NEWLINE opt = ch['options']NEWLINE if opt['account'] == c['account'] and opt['serviceName'] == c['serviceName']:NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE elif c['type'] == 'SLACK':NEWLINE if 'name' in c:NEWLINE if c['name'] == ch.get('name'):NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE elif c['type'] == 'OPSGENIE':NEWLINE if 'name' in c:NEWLINE if c['name'] == ch.get('name'):NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE elif c['type'] == 'VICTOROPS':NEWLINE if 'name' in c:NEWLINE if c['name'] == ch.get('name'):NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE elif c['type'] == 'WEBHOOK':NEWLINE if 'name' in c:NEWLINE if c['name'] == ch.get('name'):NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE if not found:NEWLINE return False, "Channel not found: " + str(c)NEWLINENEWLINE return True, idsNEWLINENEWLINE def create_email_notification_channel(self, channel_name, email_recipients):NEWLINE channel_json = {NEWLINE 'notificationChannel': {NEWLINE 'type': 'EMAIL',NEWLINE 'name': channel_name,NEWLINE 'enabled': True,NEWLINE 'options': {NEWLINE 'emailRecipients': email_recipientsNEWLINE }NEWLINE }NEWLINE }NEWLINENEWLINE res = requests.post(self.url + '/api/notificationChannels', headers=self.hdrs, data=json.dumps(channel_json),NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def create_notification_channel(self, channel):NEWLINE channel["id"] = NoneNEWLINE channel["version"] = NoneNEWLINE channel["createdOn"] = NoneNEWLINE channel["modifiedOn"] = NoneNEWLINE channel_json = {NEWLINE 'notificationChannel': channelNEWLINE }NEWLINENEWLINE res = requests.post(self.url + '/api/notificationChannels', headers=self.hdrs, data=json.dumps(channel_json),NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def get_notification_channel(self, id):NEWLINENEWLINE res = requests.get(self.url + '/api/notificationChannels/' + str(id), headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return False, self.lasterrNEWLINENEWLINE return True, res.json()['notificationChannel']NEWLINENEWLINE def update_notification_channel(self, channel):NEWLINE if 'id' not in channel:NEWLINE return [False, "Invalid channel format"]NEWLINENEWLINE res = requests.put(self.url + '/api/notificationChannels/' + str(channel['id']), headers=self.hdrs,NEWLINE data=json.dumps({"notificationChannel": channel}), verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def delete_notification_channel(self, channel):NEWLINE if 'id' not in channel:NEWLINE return [False, "Invalid channel format"]NEWLINENEWLINE res = requests.delete(self.url + '/api/notificationChannels/' + str(channel['id']), headers=self.hdrs,NEWLINE verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return False, self.lasterrNEWLINE return True, NoneNEWLINENEWLINE def get_data_retention_info(self):NEWLINE '''**Description**NEWLINE Return the list of data retention intervals, with beginning and end UTC time for each of them. Sysdig Monitor performs rollups of the data it stores. This means that data is stored at different time granularities depending on how far back in time it is. This call can be used to know what precision you can expect before you make a call to :func:`~SdcClient.get_data`.NEWLINENEWLINE **Success Return Value**NEWLINE A dictionary containing the list of available sampling intervals.NEWLINENEWLINE **Example**NEWLINE `examples/print_data_retention_info.py `_NEWLINE '''NEWLINE res = requests.get(self.url + '/api/history/timelines/', headers=self.hdrs, verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def get_topology_map(self, grouping_hierarchy, time_window_s, sampling_time_s):NEWLINE #NEWLINE # Craft the time interval sectionNEWLINE #NEWLINE tlines = self.get_data_retention_info()NEWLINENEWLINE for tline in tlines[1]['agents']:NEWLINE if tline['sampling'] == sampling_time_s * 1000000:NEWLINE timeinfo = tlineNEWLINENEWLINE if timeinfo is None:NEWLINE return [False, "sampling time " + str(sampling_time_s) + " not supported"]NEWLINENEWLINE timeinfo['from'] = timeinfo['to'] - timeinfo['sampling']NEWLINENEWLINE #NEWLINE # Create the grouping hierarchyNEWLINE #NEWLINE gby = [{'metric': g} for g in grouping_hierarchy]NEWLINENEWLINE #NEWLINE # Prepare the jsonNEWLINE #NEWLINE req_json = {NEWLINE 'format': {NEWLINE 'type': 'map',NEWLINE 'exportProcess': TrueNEWLINE },NEWLINE 'time': timeinfo,NEWLINE # 'filter': {NEWLINE # 'filters': [NEWLINE # {NEWLINE # 'metric': 'agent.tag.Tag',NEWLINE # 'op': '=',NEWLINE # 'value': 'production-maintenance',NEWLINE # 'filters': NoneNEWLINE # }NEWLINE # ],NEWLINE # 'logic': 'and'NEWLINE # },NEWLINE 'limit': {NEWLINE 'hostGroups': 20,NEWLINE 'hosts': 20,NEWLINE 'containers': 20,NEWLINE 'processes': 10NEWLINE },NEWLINE 'group': {NEWLINE 'configuration': {NEWLINE 'groups': [NEWLINE {NEWLINE 'filters': [],NEWLINE 'groupBy': gbyNEWLINE }NEWLINE ]NEWLINE }NEWLINE },NEWLINE 'nodeMetrics': [NEWLINE {NEWLINE 'id': 'cpu.used.percent',NEWLINE 'aggregation': 'timeAvg',NEWLINE 'groupAggregation': 'avg'NEWLINE }NEWLINE ],NEWLINE 'linkMetrics': [NEWLINE {NEWLINE 'id': 'net.bytes.total',NEWLINE 'aggregation': 'timeAvg',NEWLINE 'groupAggregation': 'sum'NEWLINE }NEWLINE ]NEWLINE }NEWLINENEWLINE #NEWLINE # Fire the requestNEWLINE #NEWLINE res = requests.post(self.url + '/api/data?format=map', headers=self.hdrs,NEWLINE data=json.dumps(req_json), verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def get_data(self, metrics, start_ts, end_ts=0, sampling_s=0,NEWLINE filter='', datasource_type='host', paging=None):NEWLINE '''**Description**NEWLINE Export metric data (both time-series and table-based).NEWLINENEWLINE **Arguments**NEWLINE - **metrics**: a list of dictionaries, specifying the metrics and grouping keys that the query will return. A metric is any of the entries that can be found in the *Metrics* section of the Explore page in Sysdig Monitor. Metric entries require an *aggregations* section specifying how to aggregate the metric across time and containers/hosts. A grouping key is any of the entries that can be found in the *Show* or *Segment By* sections of the Explore page in Sysdig Monitor. These entries are used to apply single or hierarchical segmentation to the returned data and don't require the aggregations section. Refer to the Example link below for ready-to-use code snippets.NEWLINE - **start_ts**: the UTC time (in seconds) of the beginning of the data window. A negative value can be optionally used to indicate a relative time in the past from now. For example, -3600 means "one hour ago".NEWLINE - **end_ts**: the UTC time (in seconds) of the end of the data window, or 0 to indicate "now". A negative value can also be optionally used to indicate a relative time in the past from now. For example, -3600 means "one hour ago".NEWLINE - **sampling_s**: the duration of the samples that will be returned. 0 means that the whole data will be returned as a single sample.NEWLINE - **filter**: a boolean expression combining Sysdig Monitor segmentation criteria that defines what the query will be applied to. For example: *kubernetes.namespace.name='production' and container.image='nginx'*.NEWLINE - **datasource_type**: specify the metric source for the request, can be ``container`` or ``host``. Most metrics, for example ``cpu.used.percent`` or ``memory.bytes.used``, are reported by both hosts and containers. By default, host metrics are used, but if the request contains a container-specific grouping key in the metric list/filter (e.g. ``container.name``), then the container source is used. In cases where grouping keys are missing or apply to both hosts and containers (e.g. ``tag.Name``), *datasource_type* can be explicitly set to avoid any ambiguity and allow the user to select precisely what kind of data should be used for the request. `examples/get_data_datasource.py `_ contains a few examples that should clarify the use of this argument.NEWLINE - **paging**: if segmentation of the query generates values for several different entities (e.g. containers/hosts), this parameter specifies which to include in the returned result. It's specified as a dictionary of inclusive values for ``from`` and ``to`` with the default being ``{ "from": 0, "to": 9 }``, which will return values for the "top 10" entities. The meaning of "top" is query-dependent, based on points having been sorted via the specified group aggregation, with the results sorted in ascending order if the group aggregation is ``min`` or ``none``, and descending order otherwise.NEWLINENEWLINE **Success Return Value**NEWLINE A dictionary with the requested data. Data is organized in a list of time samples, each of which includes a UTC timestamp and a list of values, whose content and order reflect what was specified in the *metrics* argument.NEWLINENEWLINE **Examples**NEWLINE - `examples/get_data_simple.py `_NEWLINE - `examples/get_data_advanced.py `_NEWLINE - `examples/list_hosts.py `_NEWLINE - `examples/get_data_datasource.py `_NEWLINE '''NEWLINE reqbody = {NEWLINE 'metrics': metrics,NEWLINE 'dataSourceType': datasource_type,NEWLINE }NEWLINENEWLINE if start_ts < 0:NEWLINE reqbody['last'] = -start_tsNEWLINE elif start_ts == 0:NEWLINE return [False, "start_ts cannot be 0"]NEWLINE else:NEWLINE reqbody['start'] = start_tsNEWLINE reqbody['end'] = end_tsNEWLINENEWLINE if filter != '':NEWLINE reqbody['filter'] = filterNEWLINENEWLINE if paging is not None:NEWLINE reqbody['paging'] = pagingNEWLINENEWLINE if sampling_s != 0:NEWLINE reqbody['sampling'] = sampling_sNEWLINENEWLINE res = requests.post(self.url + '/api/data/', headers=self.hdrs, data=json.dumps(reqbody),NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def get_sysdig_captures(self, from_sec=None, to_sec=None, scope_filter=None):NEWLINE '''**Description**NEWLINE Returns the list of sysdig captures for the user.NEWLINENEWLINE **Arguments**NEWLINE - from_sec: the start of the timerange for which to get the capturesNEWLINE - end_sec: the end of the timerange for which to get the capturesNEWLINE - scope_filter: this is a SysdigMonitor-like filter (e.g 'container.image=ubuntu'). When provided, events are filtered by their scope, so only a subset will be returned (e.g. 'container.image=ubuntu' will provide only events that have happened on an ubuntu container).NEWLINENEWLINE **Success Return Value**NEWLINE A dictionary containing the list of captures.NEWLINENEWLINE **Example**NEWLINE `examples/list_sysdig_captures.py `_NEWLINE '''NEWLINE url = '{url}/api/sysdig?source={source}{frm}{to}{scopeFilter}'.format(NEWLINE url=self.url,NEWLINE source=self.product,NEWLINE frm="&from=%d" % (from_sec * 10 ** 6) if from_sec else "",NEWLINE to="&to=%d" % (to_sec * 10 ** 6) if to_sec else "",NEWLINE scopeFilter="&scopeFilter=%s" % scope_filter if scope_filter else "")NEWLINE res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def poll_sysdig_capture(self, capture):NEWLINE '''**Description**NEWLINE Fetch the updated state of a sysdig capture. Can be used to poll the status of a capture that has been previously created and started with :func:`~SdcClient.create_sysdig_capture`.NEWLINENEWLINE **Arguments**NEWLINE - **capture**: the capture object as returned by :func:`~SdcClient.get_sysdig_captures` or :func:`~SdcClient.create_sysdig_capture`.NEWLINENEWLINE **Success Return Value**NEWLINE A dictionary showing the updated details of the capture. Use the ``status`` field to check the progress of a capture.NEWLINENEWLINE **Example**NEWLINE `examples/create_sysdig_capture.py `_NEWLINE '''NEWLINE if 'id' not in capture:NEWLINE return [False, 'Invalid capture format']NEWLINENEWLINE url = '{url}/api/sysdig/{id}?source={source}'.format(NEWLINE url=self.url, id=capture['id'], source=self.product)NEWLINE res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def create_sysdig_capture(self, hostname, capture_name, duration, capture_filter='', folder='/'):NEWLINE '''**Description**NEWLINE Create a new sysdig capture. The capture will be immediately started.NEWLINENEWLINE **Arguments**NEWLINE - **hostname**: the hostname of the instrumented host where the capture will be taken.NEWLINE - **capture_name**: the name of the capture.NEWLINE - **duration**: the duration of the capture, in seconds.NEWLINE - **capture_filter**: a sysdig filter expression.NEWLINE - **folder**: directory in the S3 bucket where the capture will be saved.NEWLINENEWLINE **Success Return Value**NEWLINE A dictionary showing the details of the new capture.NEWLINENEWLINE **Example**NEWLINE `examples/create_sysdig_capture.py `_NEWLINE '''NEWLINE res = self.get_connected_agents()NEWLINE if not res[0]:NEWLINE return resNEWLINENEWLINE capture_agent = NoneNEWLINENEWLINE for agent in res[1]:NEWLINE if hostname == agent['hostName']:NEWLINE capture_agent = agentNEWLINE breakNEWLINENEWLINE if capture_agent is None:NEWLINE return [False, hostname + ' not found']NEWLINENEWLINE data = {NEWLINE 'agent': capture_agent,NEWLINE 'name': capture_name,NEWLINE 'duration': duration,NEWLINE 'folder': folder,NEWLINE 'filters': capture_filter,NEWLINE 'bucketName': '',NEWLINE 'source': self.productNEWLINE }NEWLINENEWLINE res = requests.post(self.url + '/api/sysdig', headers=self.hdrs, data=json.dumps(data), verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def download_sysdig_capture(self, capture_id):NEWLINE '''**Description**NEWLINE Download a sysdig capture by id.NEWLINENEWLINE **Arguments**NEWLINE - **capture_id**: the capture id to download.NEWLINENEWLINE **Success Return Value**NEWLINE The bytes of the scapNEWLINE '''NEWLINE url = '{url}/api/sysdig/{id}/download?_product={product}'.format(NEWLINE url=self.url, id=capture_id, product=self.product)NEWLINE res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return False, self.lasterrNEWLINENEWLINE return True, res.contentNEWLINENEWLINE def create_user_invite(self, user_email, first_name=None, last_name=None, system_role=None):NEWLINE '''**Description**NEWLINE Invites a new user to use Sysdig Monitor. This should result in an email notification to the specified address.NEWLINENEWLINE **Arguments**NEWLINE - **user_email**: the email address of the user that will be invited to use Sysdig MonitorNEWLINE - **first_name**: the first name of the user being invitedNEWLINE - **last_name**: the last name of the user being invitedNEWLINE - **system_role**: system-wide privilege level for this user regardless of team. specify 'ROLE_CUSTOMER' to create an Admin. if not specified, default is a non-Admin ('ROLE_USER').NEWLINENEWLINE **Success Return Value**NEWLINE The newly created user.NEWLINENEWLINE **Examples**NEWLINE - `examples/user_team_mgmt.py `_NEWLINE - `examples/user_team_mgmt_extended.py `_NEWLINENEWLINE '''NEWLINE # Look up the list of users to see if this exists, do not create if one existsNEWLINE res = requests.get(self.url + '/api/users', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE data = res.json()NEWLINE for user in data['users']:NEWLINE if user['username'] == user_email:NEWLINE return [False, 'user ' + user_email + ' already exists']NEWLINENEWLINE # Create the userNEWLINE options = {'username': user_email,NEWLINE 'firstName': first_name,NEWLINE 'lastName': last_name,NEWLINE 'systemRole': system_role}NEWLINE user_json = {k: v for k, v in options.items() if v is not None}NEWLINENEWLINE res = requests.post(self.url + '/api/users', headers=self.hdrs, data=json.dumps(user_json),NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def delete_user(self, user_email):NEWLINE '''**Description**NEWLINE Deletes a user from Sysdig Monitor.NEWLINENEWLINE **Arguments**NEWLINE - **user_email**: the email address of the user that will be deleted from Sysdig MonitorNEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt.py `_NEWLINE '''NEWLINE res = self.get_user_ids([user_email])NEWLINE if res[0] == False:NEWLINE return resNEWLINE userid = res[1][0]NEWLINE res = requests.delete(self.url + '/api/users/' + str(userid), headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE return [True, None]NEWLINENEWLINE def get_user(self, user_email):NEWLINE res = requests.get(self.url + '/api/users', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE for u in res.json()['users']:NEWLINE if u['username'] == user_email:NEWLINE return [True, u]NEWLINE return [False, 'User not found']NEWLINENEWLINE def get_users(self):NEWLINE '''**Description**NEWLINE Return a list containing details about all users in the Sysdig Monitor environment. The API token must have Admin rights for this to succeed.NEWLINENEWLINE **Success Return Value**NEWLINE A list user objectsNEWLINE '''NEWLINE res = requests.get(self.url + '/api/users', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE return [True, res.json()['users']]NEWLINENEWLINE def edit_user(self, user_email, firstName=None, lastName=None, systemRole=None):NEWLINE res = self.get_user(user_email)NEWLINE if res[0] == False:NEWLINE return resNEWLINE user = res[1]NEWLINE reqbody = {NEWLINE 'systemRole': systemRole if systemRole else user['systemRole'],NEWLINE 'username': user_email,NEWLINE 'enabled': user.get('enabled', False),NEWLINE 'version': user['version']NEWLINE }NEWLINENEWLINE if firstName == None:NEWLINE reqbody['firstName'] = user['firstName'] if 'firstName' in list(user.keys()) else ''NEWLINE else:NEWLINE reqbody['firstName'] = firstNameNEWLINENEWLINE if lastName == None:NEWLINE reqbody['lastName'] = user['lastName'] if 'lastName' in list(user.keys()) else ''NEWLINE else:NEWLINE reqbody['lastName'] = lastNameNEWLINENEWLINE res = requests.put(self.url + '/api/users/' + str(user['id']), headers=self.hdrs, data=json.dumps(reqbody),NEWLINE verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE return [True, 'Successfully edited user']NEWLINENEWLINE def get_teams(self, team_filter=''):NEWLINE '''**Description**NEWLINE Return the set of teams that match the filter specified. The *team_filter* should be a substring of the names of the teams to be returned.NEWLINENEWLINE **Arguments**NEWLINE - **team_filter**: the team filter to match when returning the list of teamsNEWLINENEWLINE **Success Return Value**NEWLINE The teams that match the filter.NEWLINE '''NEWLINE res = requests.get(self.url + '/api/teams', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE ret = [t for t in res.json()['teams'] if team_filter in t['name']]NEWLINE return [True, ret]NEWLINENEWLINE def get_team(self, name):NEWLINE '''**Description**NEWLINE Return the team with the specified team name, if it is present.NEWLINENEWLINE **Arguments**NEWLINE - **name**: the name of the team to returnNEWLINENEWLINE **Success Return Value**NEWLINE The requested team.NEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt.py `_NEWLINE '''NEWLINE res = self.get_teams(name)NEWLINE if res[0] == False:NEWLINE return resNEWLINE for t in res[1]:NEWLINE if t['name'] == name:NEWLINE return [True, t]NEWLINE return [False, 'Could not find team']NEWLINENEWLINE def get_team_ids(self, teams):NEWLINE res = requests.get(self.url + '/api/teams', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE u = [x for x in res.json()['teams'] if x['name'] in teams]NEWLINE return [True, [x['id'] for x in u]]NEWLINENEWLINE def _get_user_id_dict(self, users):NEWLINE res = requests.get(self.url + '/api/users', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE u = [x for x in res.json()['users'] if x['username'] in users]NEWLINE return [True, dict((user['username'], user['id']) for user in u)]NEWLINENEWLINE def _get_id_user_dict(self, user_ids):NEWLINE res = requests.get(self.url + '/api/users', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE u = [x for x in res.json()['users'] if x['id'] in user_ids]NEWLINE return [True, dict((user['id'], user['username']) for user in u)]NEWLINENEWLINE def get_user_ids(self, users):NEWLINE res = self._get_user_id_dict(users)NEWLINE if res[0] == False:NEWLINE return resNEWLINE else:NEWLINE return [True, list(res[1].values())]NEWLINENEWLINE def create_team(self, name, memberships=None, filter='', description='', show='host', theme='#7BB0B2',NEWLINE perm_capture=False, perm_custom_events=False, perm_aws_data=False):NEWLINE '''NEWLINE **Description**NEWLINE Creates a new teamNEWLINENEWLINE **Arguments**NEWLINE - **name**: the name of the team to create.NEWLINE - **memberships**: dictionary of (user-name, team-role) pairs that should describe new memberships of the team.NEWLINE - **filter**: the scope that this team is able to access within Sysdig Monitor.NEWLINE - **description**: describes the team that will be created.NEWLINE - **show**: possible values are *host*, *container*.NEWLINE - **theme**: the color theme that Sysdig Monitor will use when displaying the team.NEWLINE - **perm_capture**: if True, this team will be allowed to take sysdig captures.NEWLINE - **perm_custom_events**: if True, this team will be allowed to view all custom events from every user and agent.NEWLINE - **perm_aws_data**: if True, this team will have access to all AWS metrics and tags, regardless of the team's scope.NEWLINENEWLINE **Success Return Value**NEWLINE The newly created team.NEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt.py `_NEWLINE '''NEWLINE reqbody = {NEWLINE 'name': name,NEWLINE 'description': description,NEWLINE 'theme': theme,NEWLINE 'show': show,NEWLINE 'canUseSysdigCapture': perm_capture,NEWLINE 'canUseCustomEvents': perm_custom_events,NEWLINE 'canUseAwsMetrics': perm_aws_data,NEWLINE }NEWLINENEWLINE # Map user-names to IDsNEWLINE if memberships != None and len(memberships) != 0:NEWLINE res = self._get_user_id_dict(list(memberships.keys()))NEWLINE if res[0] == False:NEWLINE return [False, 'Could not fetch IDs for user names']NEWLINE reqbody['userRoles'] = [NEWLINE {NEWLINE 'userId': user_id,NEWLINE 'role': memberships[user_name]NEWLINE }NEWLINE for (user_name, user_id) in res[1].items()NEWLINE ]NEWLINE else:NEWLINE reqbody['users'] = []NEWLINENEWLINE if filter != '':NEWLINE reqbody['filter'] = filterNEWLINENEWLINE res = requests.post(self.url + '/api/teams', headers=self.hdrs, data=json.dumps(reqbody),NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def edit_team(self, name, memberships=None, filter=None, description=None, show=None, theme=None,NEWLINE perm_capture=None, perm_custom_events=None, perm_aws_data=None):NEWLINE '''NEWLINE **Description**NEWLINE Edits an existing team. All arguments are optional. Team settings for any arguments unspecified will remain at their current settings.NEWLINENEWLINE **Arguments**NEWLINE - **name**: the name of the team to edit.NEWLINE - **memberships**: dictionary of (user-name, team-role) pairs that should describe new memberships of the team.NEWLINE - **filter**: the scope that this team is able to access within Sysdig Monitor.NEWLINE - **description**: describes the team that will be created.NEWLINE - **show**: possible values are *host*, *container*.NEWLINE - **theme**: the color theme that Sysdig Monitor will use when displaying the team.NEWLINE - **perm_capture**: if True, this team will be allowed to take sysdig captures.NEWLINE - **perm_custom_events**: if True, this team will be allowed to view all custom events from every user and agent.NEWLINE - **perm_aws_data**: if True, this team will have access to all AWS metrics and tags, regardless of the team's scope.NEWLINENEWLINE **Success Return Value**NEWLINE The edited team.NEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt.py `_NEWLINE '''NEWLINE res = self.get_team(name)NEWLINE if res[0] == False:NEWLINE return resNEWLINENEWLINE t = res[1]NEWLINE reqbody = {NEWLINE 'name': name,NEWLINE 'theme': theme if theme else t['theme'],NEWLINE 'show': show if show else t['show'],NEWLINE 'canUseSysdigCapture': perm_capture if perm_capture else t['canUseSysdigCapture'],NEWLINE 'canUseCustomEvents': perm_custom_events if perm_custom_events else t['canUseCustomEvents'],NEWLINE 'canUseAwsMetrics': perm_aws_data if perm_aws_data else t['canUseAwsMetrics'],NEWLINE 'id': t['id'],NEWLINE 'version': t['version']NEWLINE }NEWLINENEWLINE # Handling team descriptionNEWLINE if description is not None:NEWLINE reqbody['description'] = descriptionNEWLINE elif 'description' in list(t.keys()):NEWLINE reqbody['description'] = t['description']NEWLINENEWLINE # Handling for users to map (user-name, team-role) pairs to membershipsNEWLINE if memberships != None:NEWLINE res = self._get_user_id_dict(list(memberships.keys()))NEWLINE if res[0] == False:NEWLINE return [False, 'Could not convert user names to IDs']NEWLINE reqbody['userRoles'] = [NEWLINE {NEWLINE 'userId': user_id,NEWLINE 'role': memberships[user_name]NEWLINE }NEWLINE for (user_name, user_id) in res[1].items()NEWLINE ]NEWLINE elif 'userRoles' in list(t.keys()):NEWLINE reqbody['userRoles'] = t['userRoles']NEWLINE else:NEWLINE reqbody['userRoles'] = []NEWLINENEWLINE # Special handling for filters since we don't support blank filtersNEWLINE if filter != None:NEWLINE reqbody['filter'] = filterNEWLINE elif 'filter' in list(t.keys()):NEWLINE reqbody['filter'] = t['filter']NEWLINENEWLINE res = requests.put(self.url + '/api/teams/' + str(t['id']), headers=self.hdrs, data=json.dumps(reqbody),NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def delete_team(self, name):NEWLINE '''**Description**NEWLINE Deletes a team from Sysdig Monitor.NEWLINENEWLINE **Arguments**NEWLINE - **name**: the name of the team that will be deleted from Sysdig MonitorNEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt.py `_NEWLINE '''NEWLINE res = self.get_team(name)NEWLINE if res[0] == False:NEWLINE return resNEWLINENEWLINE t = res[1]NEWLINE res = requests.delete(self.url + '/api/teams/' + str(t['id']), headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE return [True, None]NEWLINENEWLINE def list_memberships(self, team):NEWLINE '''NEWLINE **Description**NEWLINE List all memberships for specified team.NEWLINENEWLINE **Arguments**NEWLINE - **team**: the name of the team for which we want to see membershipsNEWLINENEWLINE **Result**NEWLINE Dictionary of (user-name, team-role) pairs that should describe memberships of the team.NEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt_extended.py `_NEWLINE '''NEWLINE res = self.get_team(team)NEWLINE if res[0] == False:NEWLINE return resNEWLINENEWLINE raw_memberships = res[1]['userRoles']NEWLINE user_ids = [m['userId'] for m in raw_memberships]NEWLINENEWLINE res = self._get_id_user_dict(user_ids)NEWLINE if res[0] == False:NEWLINE return [False, 'Could not fetch IDs for user names']NEWLINE else:NEWLINE id_user_dict = res[1]NEWLINENEWLINE return [True, dict([(id_user_dict[m['userId']], m['role']) for m in raw_memberships])]NEWLINENEWLINE def save_memberships(self, team, memberships):NEWLINE '''NEWLINE **Description**NEWLINE Create new user team memberships or update existing ones.NEWLINENEWLINE **Arguments**NEWLINE - **team**: the name of the team for which we are creating new membershipsNEWLINE - **memberships**: dictionary of (user-name, team-role) pairs that should describe new membershipsNEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt_extended.py `_NEWLINE '''NEWLINENEWLINE res = self.list_memberships(team)NEWLINENEWLINE if res[0] is False:NEWLINE return resNEWLINENEWLINE full_memberships = res[1]NEWLINE full_memberships.update(memberships)NEWLINENEWLINE res = self.edit_team(team, full_memberships)NEWLINENEWLINE if res[0] is False:NEWLINE return resNEWLINE else:NEWLINE return [True, None]NEWLINENEWLINE def remove_memberships(self, team, users):NEWLINE '''NEWLINE **Description**NEWLINE Remove user memberships from specified team.NEWLINENEWLINE **Arguments**NEWLINE - **team**: the name of the team from which user memberships are removedNEWLINE - **users**: list of usernames which should be removed from teamNEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt_extended.py `_NEWLINE '''NEWLINENEWLINE res = self.list_memberships(team)NEWLINENEWLINE if res[0] is False:NEWLINE return resNEWLINENEWLINE old_memberships = res[1]NEWLINE new_memberships = {k: v for k, v in old_memberships.items() if k not in users}NEWLINENEWLINE res = self.edit_team(team, new_memberships)NEWLINENEWLINE if res[0] is False:NEWLINE return resNEWLINE else:NEWLINE return [True, None]NEWLINENEWLINE def list_access_keys(self):NEWLINE '''NEWLINE **Description**NEWLINE List all the access keys enabled and disabled for this instance of Sysdig Monitor/SecureNEWLINENEWLINE **Reslut**NEWLINE A list of access keys objectsNEWLINENEWLINE **Example**NEWLINE `examples/list_access_keys.py `_NEWLINE '''NEWLINE res = requests.get(self.url + '/api/customer/accessKeys', headers=self.hdrs, verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def create_access_key(self):NEWLINE '''NEWLINE **Description**NEWLINE Create a new access key for Sysdig Monitor/SecureNEWLINENEWLINE **Reslut**NEWLINE The access keys objectNEWLINE '''NEWLINE res = requests.post(self.url + '/api/customer/accessKeys', headers=self.hdrs, verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def disable_access_key(self, access_key):NEWLINE '''NEWLINE **Description**NEWLINE Disable an existing access keyNEWLINENEWLINE **Arguments**NEWLINE - **access_key**: the access key to be disabledNEWLINENEWLINE **Reslut**NEWLINE The access keys objectNEWLINE '''NEWLINE res = requests.post(self.url + '/api/customer/accessKeys/' + access_key + "/disable/", headers=self.hdrs,NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def enable_access_key(self, access_key):NEWLINE '''NEWLINE **Description**NEWLINE Enable an existing access keyNEWLINENEWLINE **Arguments**NEWLINE - **access_key**: the access key to be enabledNEWLINENEWLINE **Reslut**NEWLINE The access keys objectNEWLINE '''NEWLINE res = requests.post(self.url + '/api/customer/accessKeys/' + access_key + "/enable/", headers=self.hdrs,NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def get_agents_config(self):NEWLINE res = requests.get(self.url + '/api/agents/config', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE data = res.json()NEWLINE return [True, data]NEWLINENEWLINE def set_agents_config(self, config):NEWLINE res = requests.put(self.url + '/api/agents/config', headers=self.hdrs, data=json.dumps(config),NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def clear_agents_config(self):NEWLINE data = {'files': []}NEWLINE return self.set_agents_config(data)NEWLINENEWLINE def get_user_api_token(self, username, teamname):NEWLINE res = self.get_team(teamname)NEWLINE if res[0] == False:NEWLINE return resNEWLINENEWLINE t = res[1]NEWLINENEWLINE res = requests.get(self.url + '/api/token/%s/%d' % (username, t['id']), headers=self.hdrs,NEWLINE verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE data = res.json()NEWLINE return [True, data['token']['key']]NEWLINENEWLINE def _request_result(self, res):NEWLINE if not self._checkResponse(res):NEWLINE return False, self.lasterrNEWLINENEWLINE return True, res.json()NEWLINE # Generated by Django 3.2.4 on 2021-06-06 05:11NEWLINENEWLINEfrom django.conf import settingsNEWLINEfrom django.db import migrations, modelsNEWLINEimport django.db.models.deletionNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE initial = TrueNEWLINENEWLINE dependencies = [NEWLINE ("farm", "0001_initial"),NEWLINE migrations.swappable_dependency(settings.AUTH_USER_MODEL),NEWLINE ("geometry", "0001_initial"),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.CreateModel(NEWLINE name="Plot",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.AutoField(NEWLINE auto_created=True,NEWLINE primary_key=True,NEWLINE serialize=False,NEWLINE verbose_name="ID",NEWLINE ),NEWLINE ),NEWLINE (NEWLINE "name",NEWLINE models.CharField(NEWLINE blank=True, default="Unnamed Plot", max_length=128NEWLINE ),NEWLINE ),NEWLINE (NEWLINE "description",NEWLINE models.CharField(blank=True, default="", max_length=1024),NEWLINE ),NEWLINE (NEWLINE "type",NEWLINE models.CharField(NEWLINE blank=True,NEWLINE choices=[NEWLINE ("F", "field"),NEWLINE ("W", "forest"),NEWLINE ("G", "garden"),NEWLINE ("O", "orchard"),NEWLINE ("P", "pasture"),NEWLINE ("S", "silvopasture"),NEWLINE ],NEWLINE default=None,NEWLINE max_length=1,NEWLINE null=True,NEWLINE ),NEWLINE ),NEWLINE (NEWLINE "farm",NEWLINE models.ForeignKey(NEWLINE on_delete=django.db.models.deletion.CASCADE, to="farm.farm"NEWLINE ),NEWLINE ),NEWLINE (NEWLINE "farmer",NEWLINE models.ForeignKey(NEWLINE on_delete=django.db.models.deletion.CASCADE,NEWLINE to=settings.AUTH_USER_MODEL,NEWLINE ),NEWLINE ),NEWLINE (NEWLINE "parent",NEWLINE models.ForeignKey(NEWLINE blank=True,NEWLINE null=True,NEWLINE on_delete=django.db.models.deletion.CASCADE,NEWLINE to="plot.plot",NEWLINE ),NEWLINE ),NEWLINE (NEWLINE "shape",NEWLINE models.ForeignKey(NEWLINE default=None,NEWLINE null=True,NEWLINE on_delete=django.db.models.deletion.CASCADE,NEWLINE to="geometry.shape",NEWLINE ),NEWLINE ),NEWLINE ],NEWLINE options={NEWLINE "db_table": "plot",NEWLINE },NEWLINE ),NEWLINE ]NEWLINE # iterator objects implement __iter__ and __next__ methodsNEWLINENEWLINEl = [3, 54,32, 'name']NEWLINEl_iterator = iter(l)NEWLINENEWLINE#print(l_iterator)NEWLINE#print(next(l_iterator))NEWLINE#print(next(l_iterator))NEWLINE#print(next(l_iterator))NEWLINE#print(next(l_iterator))NEWLINE#print(next(l_iterator))NEWLINENEWLINEstring = 'this is a string'NEWLINEs_iterator = iter(string)NEWLINENEWLINEfor a in s_iterator:NEWLINE print(a)NEWLINENEWLINEnumber = 3940NEWLINEnumber_iterator = iter(3940) '''NEWLINEFile name: common_utils.pyNEWLINEProgrammed by: Mike BernardNEWLINEDate: 2019-11-08NEWLINENEWLINECommon helper functions used in multiple scripts.NEWLINE'''NEWLINENEWLINEfrom nav.utils.constants import PASSNEWLINENEWLINENEWLINEdef weighted_avg(values, weights):NEWLINE '''NEWLINE Takes a list of values and a list of weights associatedNEWLINE with those values (index-to-index) and returns a weightedNEWLINE averaged of those values as a float.NEWLINENEWLINE :param values: `list` of values to be averagedNEWLINE :param weights: `list` of weights for each value (index-to-index)NEWLINENEWLINE :return: `float` The weighted average of the valuesNEWLINE '''NEWLINE denom = sum([1 / w ** 2 for w in weights])NEWLINE num = sum([1 / w ** 2 * v for v, w in zip(values, weights)])NEWLINENEWLINE return num / denomNEWLINENEWLINENEWLINEdef unit_test(module_name, tests):NEWLINE '''NEWLINE Run a set of test functions and print out the results.NEWLINE See test directory for examples of how to structure these testsNEWLINE and how to set up calling this function.NEWLINE NEWLINE :param module_name: `str` the name of the module being testedNEWLINE :param tests: `list` of functions to test as objectsNEWLINE '''NEWLINE passed = 0NEWLINE failed = 0NEWLINE fail_messages = []NEWLINENEWLINE for test in tests:NEWLINE status, description = test()NEWLINE if status == PASS:NEWLINE passed += 1NEWLINE else:NEWLINE failed += 1NEWLINE fail_messages.append(description)NEWLINENEWLINE print(module_name, 'unit test results: ', end='')NEWLINE print('{} out of {} tests passed.'.format(passed, len(tests)))NEWLINE if len(fail_messages) > 0:NEWLINE print('Failed tests:')NEWLINE for msg in fail_messages:NEWLINE print('\t' + msg)NEWLINE #!/usr/bin/env pythonNEWLINENEWLINE"""NEWLINEFill the "Player" table with info from this and past seasonss FPLNEWLINE"""NEWLINEimport osNEWLINENEWLINEimport jsonNEWLINENEWLINEfrom airsenal.framework.mappings import positionsNEWLINEfrom airsenal.framework.schema import PlayerAttributes, session_scope, sessionNEWLINENEWLINEfrom airsenal.framework.utils import (NEWLINE get_next_gameweek,NEWLINE get_player,NEWLINE get_player_from_api_id,NEWLINE get_team_name,NEWLINE get_past_seasons,NEWLINE CURRENT_SEASON,NEWLINE get_player_attributes,NEWLINE get_player_team_from_fixture,NEWLINE get_return_gameweek_from_news,NEWLINE)NEWLINENEWLINEfrom airsenal.framework.data_fetcher import FPLDataFetcherNEWLINENEWLINENEWLINEdef fill_attributes_table_from_file(detail_data, season, dbsession=session):NEWLINE """Fill player attributes table for previous season using data fromNEWLINE player detail JSON files.NEWLINE """NEWLINENEWLINE for player_name in detail_data.keys():NEWLINE # find the player id in the player table. If they're notNEWLINE # there, then we don't care (probably not a current player).NEWLINE player = get_player(player_name, dbsession=dbsession)NEWLINE if not player:NEWLINE print("Couldn't find player {}".format(player_name))NEWLINE continueNEWLINENEWLINE print("ATTRIBUTES {} {}".format(season, player))NEWLINE # now loop through all the fixtures that player played inNEWLINE #  Only one attributes row per gameweek - create list of gameweeksNEWLINE # encountered so can ignore duplicates (e.g. from double gameweeks).NEWLINE previous_gameweeks = []NEWLINE for fixture_data in detail_data[player_name]:NEWLINE gameweek = int(fixture_data["gameweek"])NEWLINE if gameweek in previous_gameweeks:NEWLINE # already done this gameweekNEWLINE continueNEWLINE else:NEWLINE previous_gameweeks.append(gameweek)NEWLINENEWLINE pa = PlayerAttributes()NEWLINE pa.player = playerNEWLINE pa.player_id = player.player_idNEWLINE pa.season = seasonNEWLINE pa.gameweek = gameweekNEWLINE pa.price = int(fixture_data["value"])NEWLINE pa.team = fixture_data["played_for"]NEWLINE pa.position = fixture_data["position"]NEWLINE pa.transfers_balance = int(fixture_data["transfers_balance"])NEWLINE pa.selected = int(fixture_data["selected"])NEWLINE pa.transfers_in = int(fixture_data["transfers_in"])NEWLINE pa.transfers_out = int(fixture_data["transfers_out"])NEWLINE dbsession.add(pa)NEWLINENEWLINENEWLINEdef fill_attributes_table_from_api(season, gw_start=1, dbsession=session):NEWLINE """NEWLINE use the FPL API to get player attributes info for the current seasonNEWLINE """NEWLINE fetcher = FPLDataFetcher()NEWLINE next_gw = get_next_gameweek(season=season, dbsession=dbsession)NEWLINENEWLINE # needed for selected by calculation from percentage belowNEWLINE n_players = fetcher.get_current_summary_data()["total_players"]NEWLINENEWLINE input_data = fetcher.get_player_summary_data()NEWLINENEWLINE for player_api_id in input_data.keys():NEWLINE # find the player in the player tableNEWLINE player = get_player_from_api_id(player_api_id, dbsession=dbsession)NEWLINE if not player:NEWLINE print(NEWLINE "ATTRIBUTES {} No player found with id {}".format(season, player_api_id)NEWLINE )NEWLINE continueNEWLINENEWLINE print("ATTRIBUTES {} {}".format(season, player.name))NEWLINENEWLINE # First update the current gameweek using the summary dataNEWLINE p_summary = input_data[player_api_id]NEWLINE position = positions[p_summary["element_type"]]NEWLINENEWLINE pa = get_player_attributes(NEWLINE player.player_id, season=season, gameweek=next_gw, dbsession=dbsessionNEWLINE )NEWLINE if pa:NEWLINE # found pre-existing attributes for this gameweekNEWLINE update = TrueNEWLINE else:NEWLINE # no attributes for this gameweek for this player yetNEWLINE pa = PlayerAttributes()NEWLINE update = FalseNEWLINENEWLINE pa.player = playerNEWLINE pa.player_id = player.player_idNEWLINE pa.season = seasonNEWLINE pa.gameweek = next_gwNEWLINE pa.price = int(p_summary["now_cost"])NEWLINE pa.team = get_team_name(p_summary["team"], season=season, dbsession=dbsession)NEWLINE pa.position = positions[p_summary["element_type"]]NEWLINE pa.selected = int(float(p_summary["selected_by_percent"]) * n_players / 100)NEWLINE pa.transfers_in = int(p_summary["transfers_in_event"])NEWLINE pa.transfers_out = int(p_summary["transfers_out_event"])NEWLINE pa.transfers_balance = pa.transfers_in - pa.transfers_outNEWLINE pa.chance_of_playing_next_round = p_summary["chance_of_playing_next_round"]NEWLINE pa.news = p_summary["news"]NEWLINE if (NEWLINE pa.chance_of_playing_next_round is not NoneNEWLINE and pa.chance_of_playing_next_round <= 50NEWLINE ):NEWLINE pa.return_gameweek = get_return_gameweek_from_news(NEWLINE p_summary["news"],NEWLINE season=season,NEWLINE dbsession=dbsession,NEWLINE )NEWLINENEWLINE if not update:NEWLINE # only need to add to the dbsession for new entries, if we're doingNEWLINE #  an update the final dbsession.commit() is enoughNEWLINE dbsession.add(pa)NEWLINENEWLINE # now get data for previous gameweeksNEWLINE player_data = fetcher.get_gameweek_data_for_player(player_api_id)NEWLINE if not player_data:NEWLINE print("Failed to get data for", player.name)NEWLINE continueNEWLINE for gameweek, data in player_data.items():NEWLINE if gameweek < gw_start:NEWLINE continueNEWLINENEWLINE for result in data:NEWLINE # check whether there are pre-existing attributes to updateNEWLINE pa = get_player_attributes(NEWLINE player.player_id,NEWLINE season=season,NEWLINE gameweek=gameweek,NEWLINE dbsession=dbsession,NEWLINE )NEWLINE if pa:NEWLINE update = TrueNEWLINE else:NEWLINE pa = PlayerAttributes()NEWLINE update = FalseNEWLINENEWLINE # determine the team the player played for in this fixtureNEWLINE opponent_id = result["opponent_team"]NEWLINE was_home = result["was_home"]NEWLINE kickoff_time = result["kickoff_time"]NEWLINE team = get_player_team_from_fixture(NEWLINE gameweek,NEWLINE opponent_id,NEWLINE was_home,NEWLINE kickoff_time,NEWLINE season=season,NEWLINE dbsession=dbsession,NEWLINE )NEWLINENEWLINE pa.player = playerNEWLINE pa.player_id = player.player_idNEWLINE pa.season = seasonNEWLINE pa.gameweek = gameweekNEWLINE pa.price = int(result["value"])NEWLINE pa.team = teamNEWLINE pa.position = position # does not change during seasonNEWLINE pa.transfers_balance = int(result["transfers_balance"])NEWLINE pa.selected = int(result["selected"])NEWLINE pa.transfers_in = int(result["transfers_in"])NEWLINE pa.transfers_out = int(result["transfers_out"])NEWLINENEWLINE if not update:NEWLINE # don't need to add to dbsession if updating pre-existing rowNEWLINE dbsession.add(pa)NEWLINENEWLINE break # done this gameweek nowNEWLINENEWLINENEWLINEdef make_attributes_table(seasons=[], dbsession=session):NEWLINE """Create the player attributes table using the previous 3 seasons (fromNEWLINE player details JSON files) and the current season (from API)NEWLINE """NEWLINE if not seasons:NEWLINE seasons = get_past_seasons(3)NEWLINE seasons.append(CURRENT_SEASON)NEWLINENEWLINE for season in seasons:NEWLINE if season == CURRENT_SEASON:NEWLINE continueNEWLINE input_path = os.path.join(NEWLINE os.path.dirname(__file__), "../data/player_details_{}.json".format(season)NEWLINE )NEWLINE with open(input_path, "r") as f:NEWLINE input_data = json.load(f)NEWLINENEWLINE fill_attributes_table_from_file(NEWLINE detail_data=input_data, season=season, dbsession=dbsessionNEWLINE )NEWLINENEWLINE # this season's data from the APINEWLINE if CURRENT_SEASON in seasons:NEWLINE fill_attributes_table_from_api(season=CURRENT_SEASON, dbsession=dbsession)NEWLINENEWLINE dbsession.commit()NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE with session_scope() as dbsession:NEWLINE make_attributes_table(dbsession=dbsession)NEWLINE # -*- coding: utf-8 -*-NEWLINENEWLINEimport pymysqlNEWLINEimport structNEWLINENEWLINEfrom pymysql.constants.COMMAND import COM_BINLOG_DUMP, COM_REGISTER_SLAVENEWLINEfrom pymysql.cursors import DictCursorNEWLINEfrom pymysql.util import int2byteNEWLINENEWLINEfrom .packet import BinLogPacketWrapperNEWLINEfrom .constants.BINLOG import TABLE_MAP_EVENT, ROTATE_EVENTNEWLINEfrom .gtid import GtidSetNEWLINEfrom .event import (NEWLINE QueryEvent, RotateEvent, FormatDescriptionEvent,NEWLINE XidEvent, GtidEvent, StopEvent,NEWLINE BeginLoadQueryEvent, ExecuteLoadQueryEvent,NEWLINE HeartbeatLogEvent, NotImplementedEvent)NEWLINEfrom .exceptions import BinLogNotEnabledNEWLINEfrom .row_event import (NEWLINE UpdateRowsEvent, WriteRowsEvent, DeleteRowsEvent, TableMapEvent)NEWLINENEWLINEtry:NEWLINE from pymysql.constants.COMMAND import COM_BINLOG_DUMP_GTIDNEWLINEexcept ImportError:NEWLINE # Handle old pymysql versionsNEWLINE # See: https://github.com/PyMySQL/PyMySQL/pull/261NEWLINE COM_BINLOG_DUMP_GTID = 0x1eNEWLINENEWLINE# 2013 Connection LostNEWLINE# 2006 MySQL server has gone awayNEWLINEMYSQL_EXPECTED_ERROR_CODES = [2013, 2006]NEWLINENEWLINENEWLINEclass ReportSlave(object):NEWLINENEWLINE """Represent the values that you may report when connecting as a slaveNEWLINE to a master. SHOW SLAVE HOSTS related"""NEWLINENEWLINE hostname = ''NEWLINE username = ''NEWLINE password = ''NEWLINE port = 0NEWLINENEWLINE def __init__(self, value):NEWLINE """NEWLINE Attributes:NEWLINE value: string or tupleNEWLINE if string, then it will be used hostnameNEWLINE if tuple it will be used as (hostname, user, password, port)NEWLINE """NEWLINENEWLINE if isinstance(value, (tuple, list)):NEWLINE try:NEWLINE self.hostname = value[0]NEWLINE self.username = value[1]NEWLINE self.password = value[2]NEWLINE self.port = int(value[3])NEWLINE except IndexError:NEWLINE passNEWLINE elif isinstance(value, dict):NEWLINE for key in ['hostname', 'username', 'password', 'port']:NEWLINE try:NEWLINE setattr(self, key, value[key])NEWLINE except KeyError:NEWLINE passNEWLINE else:NEWLINE self.hostname = valueNEWLINENEWLINE def __repr__(self):NEWLINE return '' %\NEWLINE (self.hostname, self.username, self.password, self.port)NEWLINENEWLINE def encoded(self, server_id, master_id=0):NEWLINE """NEWLINE server_id: the slave server-idNEWLINE master_id: usually 0. Appears as "master id" in SHOW SLAVE HOSTSNEWLINE on the master. Unknown what else it impacts.NEWLINE """NEWLINENEWLINE # 1 [15] COM_REGISTER_SLAVENEWLINE # 4 server-idNEWLINE # 1 slaves hostname lengthNEWLINE # string[$len] slaves hostnameNEWLINE # 1 slaves user lenNEWLINE # string[$len] slaves userNEWLINE # 1 slaves password lenNEWLINE # string[$len] slaves passwordNEWLINE # 2 slaves mysql-portNEWLINE # 4 replication rankNEWLINE # 4 master-idNEWLINENEWLINE lhostname = len(self.hostname.encode())NEWLINE lusername = len(self.username.encode())NEWLINE lpassword = len(self.password.encode())NEWLINENEWLINE packet_len = (1 + # commandNEWLINE 4 + # server-idNEWLINE 1 + # hostname lengthNEWLINE lhostname +NEWLINE 1 + # username lengthNEWLINE lusername +NEWLINE 1 + # password lengthNEWLINE lpassword +NEWLINE 2 + # slave mysql portNEWLINE 4 + # replication rankNEWLINE 4) # master-idNEWLINENEWLINE MAX_STRING_LEN = 257 # one byte for length + 256 charsNEWLINENEWLINE return (struct.pack(' 5.6"""NEWLINE cur = self._stream_connection.cursor()NEWLINE cur.execute("SHOW GLOBAL VARIABLES LIKE 'BINLOG_CHECKSUM'")NEWLINE result = cur.fetchone()NEWLINE cur.close()NEWLINENEWLINE if result is None:NEWLINE return FalseNEWLINE var, value = result[:2]NEWLINE if value == 'NONE':NEWLINE return FalseNEWLINE return TrueNEWLINENEWLINE def _register_slave(self):NEWLINE if not self.report_slave:NEWLINE returnNEWLINENEWLINE packet = self.report_slave.encoded(self.__server_id)NEWLINENEWLINE if pymysql.__version__ < "0.6":NEWLINE self._stream_connection.wfile.write(packet)NEWLINE self._stream_connection.wfile.flush()NEWLINE self._stream_connection.read_packet()NEWLINE else:NEWLINE self._stream_connection._write_bytes(packet)NEWLINE self._stream_connection._next_seq_id = 1NEWLINE self._stream_connection._read_packet()NEWLINENEWLINE def __connect_to_stream(self):NEWLINE # log_pos (4) -- position in the binlog-file to start the stream withNEWLINE # flags (2) BINLOG_DUMP_NON_BLOCK (0 or 1)NEWLINE # server_id (4) -- server id of this slaveNEWLINE # log_file (string.EOF) -- filename of the binlog on the masterNEWLINE self._stream_connection = self.pymysql_wrapper(**self.__connection_settings)NEWLINENEWLINE self.__use_checksum = self.__checksum_enabled()NEWLINENEWLINE # If checksum is enabled we need to inform the server about the thatNEWLINE # we support itNEWLINE if self.__use_checksum:NEWLINE cur = self._stream_connection.cursor()NEWLINE cur.execute("set @master_binlog_checksum= @@global.binlog_checksum")NEWLINE cur.close()NEWLINENEWLINE if self.slave_uuid:NEWLINE cur = self._stream_connection.cursor()NEWLINE cur.execute("set @slave_uuid= '%s'" % self.slave_uuid)NEWLINE cur.close()NEWLINENEWLINE if self.slave_heartbeat:NEWLINE # 4294967 is documented as the max value for heartbeatsNEWLINE net_timeout = float(self.__connection_settings.get('read_timeout',NEWLINE 4294967))NEWLINE # If heartbeat is too low, the connection will disconnect before,NEWLINE # this is also the behavior in mysqlNEWLINE heartbeat = float(min(net_timeout/2., self.slave_heartbeat))NEWLINE if heartbeat > 4294967:NEWLINE heartbeat = 4294967NEWLINENEWLINE # master_heartbeat_period is nanosecondsNEWLINE heartbeat = int(heartbeat * 1000000000)NEWLINE cur = self._stream_connection.cursor()NEWLINE cur.execute("set @master_heartbeat_period= %d" % heartbeat)NEWLINE cur.close()NEWLINENEWLINE self._register_slave()NEWLINENEWLINE if not self.auto_position:NEWLINE # only when log_file and log_pos both provided, the position info isNEWLINE # valid, if not, get the current position from masterNEWLINE if self.log_file is None or self.log_pos is None:NEWLINE cur = self._stream_connection.cursor()NEWLINE cur.execute("SHOW MASTER STATUS")NEWLINE master_status = cur.fetchone()NEWLINE if master_status is None:NEWLINE raise BinLogNotEnabled()NEWLINE self.log_file, self.log_pos = master_status[:2]NEWLINE cur.close()NEWLINENEWLINE prelude = struct.pack('=2.24.0) you can choose a profileNEWLINEusing the --boto-profile command line argument (e.g. ec2.py --boto-profile prod) or usingNEWLINEthe AWS_PROFILE variable:NEWLINENEWLINE AWS_PROFILE=prod ansible-playbook -i ec2.py myplaybook.ymlNEWLINENEWLINEFor more details, see: http://docs.pythonboto.org/en/latest/boto_config_tut.htmlNEWLINENEWLINEWhen run against a specific host, this script returns the following variables:NEWLINE - ec2_ami_launch_indexNEWLINE - ec2_architectureNEWLINE - ec2_associationNEWLINE - ec2_attachTimeNEWLINE - ec2_attachmentNEWLINE - ec2_attachmentIdNEWLINE - ec2_block_devicesNEWLINE - ec2_client_tokenNEWLINE - ec2_deleteOnTerminationNEWLINE - ec2_descriptionNEWLINE - ec2_deviceIndexNEWLINE - ec2_dns_nameNEWLINE - ec2_eventsSetNEWLINE - ec2_group_nameNEWLINE - ec2_hypervisorNEWLINE - ec2_idNEWLINE - ec2_image_idNEWLINE - ec2_instanceStateNEWLINE - ec2_instance_typeNEWLINE - ec2_ipOwnerIdNEWLINE - ec2_ip_addressNEWLINE - ec2_itemNEWLINE - ec2_kernelNEWLINE - ec2_key_nameNEWLINE - ec2_launch_timeNEWLINE - ec2_monitoredNEWLINE - ec2_monitoringNEWLINE - ec2_networkInterfaceIdNEWLINE - ec2_ownerIdNEWLINE - ec2_persistentNEWLINE - ec2_placementNEWLINE - ec2_platformNEWLINE - ec2_previous_stateNEWLINE - ec2_private_dns_nameNEWLINE - ec2_private_ip_addressNEWLINE - ec2_publicIpNEWLINE - ec2_public_dns_nameNEWLINE - ec2_ramdiskNEWLINE - ec2_reasonNEWLINE - ec2_regionNEWLINE - ec2_requester_idNEWLINE - ec2_root_device_nameNEWLINE - ec2_root_device_typeNEWLINE - ec2_security_group_idsNEWLINE - ec2_security_group_namesNEWLINE - ec2_shutdown_stateNEWLINE - ec2_sourceDestCheckNEWLINE - ec2_spot_instance_request_idNEWLINE - ec2_stateNEWLINE - ec2_state_codeNEWLINE - ec2_state_reasonNEWLINE - ec2_statusNEWLINE - ec2_subnet_idNEWLINE - ec2_tenancyNEWLINE - ec2_virtualization_typeNEWLINE - ec2_vpc_idNEWLINENEWLINEThese variables are pulled out of a boto.ec2.instance object. There is a lack ofNEWLINEconsistency with variable spellings (camelCase and underscores) since thisNEWLINEjust loops through all variables the object exposes. It is preferred to use theNEWLINEones with underscores when multiple exist.NEWLINENEWLINEIn addition, if an instance has AWS Tags associated with it, each tag is a newNEWLINEvariable named:NEWLINE - ec2_tag_[Key] = [Value]NEWLINENEWLINESecurity groups are comma-separated in 'ec2_security_group_ids' andNEWLINE'ec2_security_group_names'.NEWLINE'''NEWLINENEWLINE# (c) 2012, Peter SankauskasNEWLINE#NEWLINE# This file is part of Ansible,NEWLINE#NEWLINE# Ansible is free software: you can redistribute it and/or modifyNEWLINE# it under the terms of the GNU General Public License as published byNEWLINE# the Free Software Foundation, either version 3 of the License, orNEWLINE# (at your option) any later version.NEWLINE#NEWLINE# Ansible is distributed in the hope that it will be useful,NEWLINE# but WITHOUT ANY WARRANTY; without even the implied warranty ofNEWLINE# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theNEWLINE# GNU General Public License for more details.NEWLINE#NEWLINE# You should have received a copy of the GNU General Public LicenseNEWLINE# along with Ansible. If not, see .NEWLINENEWLINE######################################################################NEWLINENEWLINEimport sysNEWLINEimport osNEWLINEimport argparseNEWLINEimport reNEWLINEfrom time import timeNEWLINEimport botoNEWLINEfrom boto import ec2NEWLINEfrom boto import rdsNEWLINEfrom boto import elasticacheNEWLINEfrom boto import route53NEWLINEfrom boto import stsNEWLINEimport sixNEWLINENEWLINEfrom ansible.module_utils import ec2 as ec2_utilsNEWLINENEWLINEHAS_BOTO3 = FalseNEWLINEtry:NEWLINE import boto3NEWLINE HAS_BOTO3 = TrueNEWLINEexcept ImportError:NEWLINE passNEWLINENEWLINEfrom six.moves import configparserNEWLINEfrom collections import defaultdictNEWLINENEWLINEtry:NEWLINE import jsonNEWLINEexcept ImportError:NEWLINE import simplejson as jsonNEWLINENEWLINENEWLINEclass Ec2Inventory(object):NEWLINENEWLINE def _empty_inventory(self):NEWLINE return {"_meta": {"hostvars": {}}}NEWLINENEWLINE def __init__(self):NEWLINE ''' Main execution path '''NEWLINENEWLINE # Inventory grouped by instance IDs, tags, security groups, regions,NEWLINE # and availability zonesNEWLINE self.inventory = self._empty_inventory()NEWLINENEWLINE self.aws_account_id = NoneNEWLINENEWLINE # Index of hostname (address) to instance IDNEWLINE self.index = {}NEWLINENEWLINE # Boto profile to use (if any)NEWLINE self.boto_profile = NoneNEWLINENEWLINE # AWS credentials.NEWLINE self.credentials = {}NEWLINENEWLINE # Read settings and parse CLI argumentsNEWLINE self.parse_cli_args()NEWLINE self.read_settings()NEWLINENEWLINE # Make sure that profile_name is not passed at all if not setNEWLINE # as pre 2.24 boto will fall over otherwiseNEWLINE if self.boto_profile:NEWLINE if not hasattr(boto.ec2.EC2Connection, 'profile_name'):NEWLINE self.fail_with_error("boto version must be >= 2.24 to use profile")NEWLINENEWLINE # CacheNEWLINE if self.args.refresh_cache:NEWLINE self.do_api_calls_update_cache()NEWLINE elif not self.is_cache_valid():NEWLINE self.do_api_calls_update_cache()NEWLINENEWLINE # Data to printNEWLINE if self.args.host:NEWLINE data_to_print = self.get_host_info()NEWLINENEWLINE elif self.args.list:NEWLINE # Display list of instances for inventoryNEWLINE if self.inventory == self._empty_inventory():NEWLINE data_to_print = self.get_inventory_from_cache()NEWLINE else:NEWLINE data_to_print = self.json_format_dict(self.inventory, True)NEWLINENEWLINE print(data_to_print)NEWLINENEWLINE def is_cache_valid(self):NEWLINE ''' Determines if the cache files have expired, or if it is still valid '''NEWLINENEWLINE if os.path.isfile(self.cache_path_cache):NEWLINE mod_time = os.path.getmtime(self.cache_path_cache)NEWLINE current_time = time()NEWLINE if (mod_time + self.cache_max_age) > current_time:NEWLINE if os.path.isfile(self.cache_path_index):NEWLINE return TrueNEWLINENEWLINE return FalseNEWLINENEWLINE def read_settings(self):NEWLINE ''' Reads the settings from the ec2.ini file '''NEWLINENEWLINE scriptbasename = __file__NEWLINE scriptbasename = os.path.basename(scriptbasename)NEWLINE scriptbasename = scriptbasename.replace('.py', '')NEWLINENEWLINE defaults = {NEWLINE 'ec2': {NEWLINE 'ini_fallback': os.path.join(os.path.dirname(__file__), 'ec2.ini'),NEWLINE 'ini_path': os.path.join(os.path.dirname(__file__), '%s.ini' % scriptbasename)NEWLINE }NEWLINE }NEWLINENEWLINE if six.PY3:NEWLINE config = configparser.ConfigParser()NEWLINE else:NEWLINE config = configparser.SafeConfigParser()NEWLINE ec2_ini_path = os.environ.get('EC2_INI_PATH', defaults['ec2']['ini_path'])NEWLINE ec2_ini_path = os.path.expanduser(os.path.expandvars(ec2_ini_path))NEWLINENEWLINE if not os.path.isfile(ec2_ini_path):NEWLINE ec2_ini_path = os.path.expanduser(defaults['ec2']['ini_fallback'])NEWLINENEWLINE config.read(ec2_ini_path)NEWLINENEWLINE # is eucalyptus?NEWLINE self.eucalyptus_host = NoneNEWLINE self.eucalyptus = FalseNEWLINE if config.has_option('ec2', 'eucalyptus'):NEWLINE self.eucalyptus = config.getboolean('ec2', 'eucalyptus')NEWLINE if self.eucalyptus and config.has_option('ec2', 'eucalyptus_host'):NEWLINE self.eucalyptus_host = config.get('ec2', 'eucalyptus_host')NEWLINENEWLINE # RegionsNEWLINE self.regions = []NEWLINE configRegions = config.get('ec2', 'regions')NEWLINE if (configRegions == 'all'):NEWLINE if self.eucalyptus_host:NEWLINE self.regions.append(boto.connect_euca(host=self.eucalyptus_host).region.name, **self.credentials)NEWLINE else:NEWLINE configRegions_exclude = config.get('ec2', 'regions_exclude')NEWLINE for regionInfo in ec2.regions():NEWLINE if regionInfo.name not in configRegions_exclude:NEWLINE self.regions.append(regionInfo.name)NEWLINE else:NEWLINE self.regions = configRegions.split(",")NEWLINE if 'auto' in self.regions:NEWLINE env_region = os.environ.get('AWS_REGION')NEWLINE if env_region is None:NEWLINE env_region = os.environ.get('AWS_DEFAULT_REGION')NEWLINE self.regions = [env_region]NEWLINENEWLINE # Destination addressesNEWLINE self.destination_variable = config.get('ec2', 'destination_variable')NEWLINE self.vpc_destination_variable = config.get('ec2', 'vpc_destination_variable')NEWLINENEWLINE if config.has_option('ec2', 'hostname_variable'):NEWLINE self.hostname_variable = config.get('ec2', 'hostname_variable')NEWLINE else:NEWLINE self.hostname_variable = NoneNEWLINENEWLINE if config.has_option('ec2', 'destination_format') and \NEWLINE config.has_option('ec2', 'destination_format_tags'):NEWLINE self.destination_format = config.get('ec2', 'destination_format')NEWLINE self.destination_format_tags = config.get('ec2', 'destination_format_tags').split(',')NEWLINE else:NEWLINE self.destination_format = NoneNEWLINE self.destination_format_tags = NoneNEWLINENEWLINE # Route53NEWLINE self.route53_enabled = config.getboolean('ec2', 'route53')NEWLINE if config.has_option('ec2', 'route53_hostnames'):NEWLINE self.route53_hostnames = config.get('ec2', 'route53_hostnames')NEWLINE else:NEWLINE self.route53_hostnames = NoneNEWLINE self.route53_excluded_zones = []NEWLINE if config.has_option('ec2', 'route53_excluded_zones'):NEWLINE self.route53_excluded_zones.extend(NEWLINE config.get('ec2', 'route53_excluded_zones', '').split(','))NEWLINENEWLINE # Include RDS instances?NEWLINE self.rds_enabled = TrueNEWLINE if config.has_option('ec2', 'rds'):NEWLINE self.rds_enabled = config.getboolean('ec2', 'rds')NEWLINENEWLINE # Include RDS cluster instances?NEWLINE if config.has_option('ec2', 'include_rds_clusters'):NEWLINE self.include_rds_clusters = config.getboolean('ec2', 'include_rds_clusters')NEWLINE else:NEWLINE self.include_rds_clusters = FalseNEWLINENEWLINE # Include ElastiCache instances?NEWLINE self.elasticache_enabled = TrueNEWLINE if config.has_option('ec2', 'elasticache'):NEWLINE self.elasticache_enabled = config.getboolean('ec2', 'elasticache')NEWLINENEWLINE # Return all EC2 instances?NEWLINE if config.has_option('ec2', 'all_instances'):NEWLINE self.all_instances = config.getboolean('ec2', 'all_instances')NEWLINE else:NEWLINE self.all_instances = FalseNEWLINENEWLINE # Instance states to be gathered in inventory. Default is 'running'.NEWLINE # Setting 'all_instances' to 'yes' overrides this option.NEWLINE ec2_valid_instance_states = [NEWLINE 'pending',NEWLINE 'running',NEWLINE 'shutting-down',NEWLINE 'terminated',NEWLINE 'stopping',NEWLINE 'stopped'NEWLINE ]NEWLINE self.ec2_instance_states = []NEWLINE if self.all_instances:NEWLINE self.ec2_instance_states = ec2_valid_instance_statesNEWLINE elif config.has_option('ec2', 'instance_states'):NEWLINE for instance_state in config.get('ec2', 'instance_states').split(','):NEWLINE instance_state = instance_state.strip()NEWLINE if instance_state not in ec2_valid_instance_states:NEWLINE continueNEWLINE self.ec2_instance_states.append(instance_state)NEWLINE else:NEWLINE self.ec2_instance_states = ['running']NEWLINENEWLINE # Return all RDS instances? (if RDS is enabled)NEWLINE if config.has_option('ec2', 'all_rds_instances') and self.rds_enabled:NEWLINE self.all_rds_instances = config.getboolean('ec2', 'all_rds_instances')NEWLINE else:NEWLINE self.all_rds_instances = FalseNEWLINENEWLINE # Return all ElastiCache replication groups? (if ElastiCache is enabled)NEWLINE if config.has_option('ec2', 'all_elasticache_replication_groups') and self.elasticache_enabled:NEWLINE self.all_elasticache_replication_groups = config.getboolean('ec2', 'all_elasticache_replication_groups')NEWLINE else:NEWLINE self.all_elasticache_replication_groups = FalseNEWLINENEWLINE # Return all ElastiCache clusters? (if ElastiCache is enabled)NEWLINE if config.has_option('ec2', 'all_elasticache_clusters') and self.elasticache_enabled:NEWLINE self.all_elasticache_clusters = config.getboolean('ec2', 'all_elasticache_clusters')NEWLINE else:NEWLINE self.all_elasticache_clusters = FalseNEWLINENEWLINE # Return all ElastiCache nodes? (if ElastiCache is enabled)NEWLINE if config.has_option('ec2', 'all_elasticache_nodes') and self.elasticache_enabled:NEWLINE self.all_elasticache_nodes = config.getboolean('ec2', 'all_elasticache_nodes')NEWLINE else:NEWLINE self.all_elasticache_nodes = FalseNEWLINENEWLINE # boto configuration profile (prefer CLI argument then environment variables then config file)NEWLINE self.boto_profile = self.args.boto_profile or os.environ.get('AWS_PROFILE')NEWLINE if config.has_option('ec2', 'boto_profile') and not self.boto_profile:NEWLINE self.boto_profile = config.get('ec2', 'boto_profile')NEWLINENEWLINE # AWS credentials (prefer environment variables)NEWLINE if not (self.boto_profile or os.environ.get('AWS_ACCESS_KEY_ID') orNEWLINE os.environ.get('AWS_PROFILE')):NEWLINE if config.has_option('credentials', 'aws_access_key_id'):NEWLINE aws_access_key_id = config.get('credentials', 'aws_access_key_id')NEWLINE else:NEWLINE aws_access_key_id = NoneNEWLINE if config.has_option('credentials', 'aws_secret_access_key'):NEWLINE aws_secret_access_key = config.get('credentials', 'aws_secret_access_key')NEWLINE else:NEWLINE aws_secret_access_key = NoneNEWLINE if config.has_option('credentials', 'aws_security_token'):NEWLINE aws_security_token = config.get('credentials', 'aws_security_token')NEWLINE else:NEWLINE aws_security_token = NoneNEWLINE if aws_access_key_id:NEWLINE self.credentials = {NEWLINE 'aws_access_key_id': aws_access_key_id,NEWLINE 'aws_secret_access_key': aws_secret_access_keyNEWLINE }NEWLINE if aws_security_token:NEWLINE self.credentials['security_token'] = aws_security_tokenNEWLINENEWLINE # Cache relatedNEWLINE cache_dir = os.path.expanduser(config.get('ec2', 'cache_path'))NEWLINE if self.boto_profile:NEWLINE cache_dir = os.path.join(cache_dir, 'profile_' + self.boto_profile)NEWLINE if not os.path.exists(cache_dir):NEWLINE os.makedirs(cache_dir)NEWLINENEWLINE cache_name = 'ansible-ec2'NEWLINE cache_id = self.boto_profile or os.environ.get('AWS_ACCESS_KEY_ID', self.credentials.get('aws_access_key_id'))NEWLINE if cache_id:NEWLINE cache_name = '%s-%s' % (cache_name, cache_id)NEWLINE self.cache_path_cache = os.path.join(cache_dir, "%s.cache" % cache_name)NEWLINE self.cache_path_index = os.path.join(cache_dir, "%s.index" % cache_name)NEWLINE self.cache_max_age = config.getint('ec2', 'cache_max_age')NEWLINENEWLINE if config.has_option('ec2', 'expand_csv_tags'):NEWLINE self.expand_csv_tags = config.getboolean('ec2', 'expand_csv_tags')NEWLINE else:NEWLINE self.expand_csv_tags = FalseNEWLINENEWLINE # Configure nested groups instead of flat namespace.NEWLINE if config.has_option('ec2', 'nested_groups'):NEWLINE self.nested_groups = config.getboolean('ec2', 'nested_groups')NEWLINE else:NEWLINE self.nested_groups = FalseNEWLINENEWLINE # Replace dash or not in group namesNEWLINE if config.has_option('ec2', 'replace_dash_in_groups'):NEWLINE self.replace_dash_in_groups = config.getboolean('ec2', 'replace_dash_in_groups')NEWLINE else:NEWLINE self.replace_dash_in_groups = TrueNEWLINENEWLINE # IAM role to assume for connectionNEWLINE if config.has_option('ec2', 'iam_role'):NEWLINE self.iam_role = config.get('ec2', 'iam_role')NEWLINE else:NEWLINE self.iam_role = NoneNEWLINENEWLINE # Configure which groups should be created.NEWLINE group_by_options = [NEWLINE 'group_by_instance_id',NEWLINE 'group_by_region',NEWLINE 'group_by_availability_zone',NEWLINE 'group_by_ami_id',NEWLINE 'group_by_instance_type',NEWLINE 'group_by_instance_state',NEWLINE 'group_by_key_pair',NEWLINE 'group_by_vpc_id',NEWLINE 'group_by_security_group',NEWLINE 'group_by_tag_keys',NEWLINE 'group_by_tag_none',NEWLINE 'group_by_route53_names',NEWLINE 'group_by_rds_engine',NEWLINE 'group_by_rds_parameter_group',NEWLINE 'group_by_elasticache_engine',NEWLINE 'group_by_elasticache_cluster',NEWLINE 'group_by_elasticache_parameter_group',NEWLINE 'group_by_elasticache_replication_group',NEWLINE 'group_by_aws_account',NEWLINE ]NEWLINE for option in group_by_options:NEWLINE if config.has_option('ec2', option):NEWLINE setattr(self, option, config.getboolean('ec2', option))NEWLINE else:NEWLINE setattr(self, option, True)NEWLINENEWLINE # Do we need to just include hosts that match a pattern?NEWLINE try:NEWLINE pattern_include = config.get('ec2', 'pattern_include')NEWLINE if pattern_include and len(pattern_include) > 0:NEWLINE self.pattern_include = re.compile(pattern_include)NEWLINE else:NEWLINE self.pattern_include = NoneNEWLINE except configparser.NoOptionError:NEWLINE self.pattern_include = NoneNEWLINENEWLINE # Do we need to exclude hosts that match a pattern?NEWLINE try:NEWLINE pattern_exclude = config.get('ec2', 'pattern_exclude')NEWLINE if pattern_exclude and len(pattern_exclude) > 0:NEWLINE self.pattern_exclude = re.compile(pattern_exclude)NEWLINE else:NEWLINE self.pattern_exclude = NoneNEWLINE except configparser.NoOptionError:NEWLINE self.pattern_exclude = NoneNEWLINENEWLINE # Do we want to stack multiple filters?NEWLINE if config.has_option('ec2', 'stack_filters'):NEWLINE self.stack_filters = config.getboolean('ec2', 'stack_filters')NEWLINE else:NEWLINE self.stack_filters = FalseNEWLINENEWLINE # Instance filters (see boto and EC2 API docs). Ignore invalid filters.NEWLINE self.ec2_instance_filters = defaultdict(list)NEWLINE if config.has_option('ec2', 'instance_filters'):NEWLINENEWLINE filters = [f for f in config.get('ec2', 'instance_filters').split(',') if f]NEWLINENEWLINE for instance_filter in filters:NEWLINE instance_filter = instance_filter.strip()NEWLINE if not instance_filter or '=' not in instance_filter:NEWLINE continueNEWLINE filter_key, filter_value = [x.strip() for x in instance_filter.split('=', 1)]NEWLINE if not filter_key:NEWLINE continueNEWLINE self.ec2_instance_filters[filter_key].append(filter_value)NEWLINENEWLINE def parse_cli_args(self):NEWLINE ''' Command line argument processing '''NEWLINENEWLINE parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on EC2')NEWLINE parser.add_argument('--list', action='store_true', default=True,NEWLINE help='List instances (default: True)')NEWLINE parser.add_argument('--host', action='store',NEWLINE help='Get all the variables about a specific instance')NEWLINE parser.add_argument('--refresh-cache', action='store_true', default=False,NEWLINE help='Force refresh of cache by making API requests to EC2 (default: False - use cache files)')NEWLINE parser.add_argument('--profile', '--boto-profile', action='store', dest='boto_profile',NEWLINE help='Use boto profile for connections to EC2')NEWLINE self.args = parser.parse_args()NEWLINENEWLINE def do_api_calls_update_cache(self):NEWLINE ''' Do API calls to each region, and save data in cache files '''NEWLINENEWLINE if self.route53_enabled:NEWLINE self.get_route53_records()NEWLINENEWLINE for region in self.regions:NEWLINE self.get_instances_by_region(region)NEWLINE if self.rds_enabled:NEWLINE self.get_rds_instances_by_region(region)NEWLINE if self.elasticache_enabled:NEWLINE self.get_elasticache_clusters_by_region(region)NEWLINE self.get_elasticache_replication_groups_by_region(region)NEWLINE if self.include_rds_clusters:NEWLINE self.include_rds_clusters_by_region(region)NEWLINENEWLINE self.write_to_cache(self.inventory, self.cache_path_cache)NEWLINE self.write_to_cache(self.index, self.cache_path_index)NEWLINENEWLINE def connect(self, region):NEWLINE ''' create connection to api server'''NEWLINE if self.eucalyptus:NEWLINE conn = boto.connect_euca(host=self.eucalyptus_host, **self.credentials)NEWLINE conn.APIVersion = '2010-08-31'NEWLINE else:NEWLINE conn = self.connect_to_aws(ec2, region)NEWLINE return connNEWLINENEWLINE def boto_fix_security_token_in_profile(self, connect_args):NEWLINE ''' monkey patch for boto issue boto/boto#2100 '''NEWLINE profile = 'profile ' + self.boto_profileNEWLINE if boto.config.has_option(profile, 'aws_security_token'):NEWLINE connect_args['security_token'] = boto.config.get(profile, 'aws_security_token')NEWLINE return connect_argsNEWLINENEWLINE def connect_to_aws(self, module, region):NEWLINE connect_args = self.credentialsNEWLINENEWLINE # only pass the profile name if it's set (as it is not supported by older boto versions)NEWLINE if self.boto_profile:NEWLINE connect_args['profile_name'] = self.boto_profileNEWLINE self.boto_fix_security_token_in_profile(connect_args)NEWLINENEWLINE if self.iam_role:NEWLINE sts_conn = sts.connect_to_region(region, **connect_args)NEWLINE role = sts_conn.assume_role(self.iam_role, 'ansible_dynamic_inventory')NEWLINE connect_args['aws_access_key_id'] = role.credentials.access_keyNEWLINE connect_args['aws_secret_access_key'] = role.credentials.secret_keyNEWLINE connect_args['security_token'] = role.credentials.session_tokenNEWLINENEWLINE conn = module.connect_to_region(region, **connect_args)NEWLINE # connect_to_region will fail "silently" by returning None if the region name is wrong or not supportedNEWLINE if conn is None:NEWLINE self.fail_with_error("region name: %s likely not supported, or AWS is down. connection to region failed." % region)NEWLINE return connNEWLINENEWLINE def get_instances_by_region(self, region):NEWLINE ''' Makes an AWS EC2 API call to the list of instances in a particularNEWLINE region '''NEWLINENEWLINE try:NEWLINE conn = self.connect(region)NEWLINE reservations = []NEWLINE if self.ec2_instance_filters:NEWLINE if self.stack_filters:NEWLINE filters_dict = {}NEWLINE for filter_key, filter_values in self.ec2_instance_filters.items():NEWLINE filters_dict[filter_key] = filter_valuesNEWLINE reservations.extend(conn.get_all_instances(filters=filters_dict))NEWLINE else:NEWLINE for filter_key, filter_values in self.ec2_instance_filters.items():NEWLINE reservations.extend(conn.get_all_instances(filters={filter_key: filter_values}))NEWLINE else:NEWLINE reservations = conn.get_all_instances()NEWLINENEWLINE # Pull the tags back in a second stepNEWLINE # AWS are on record as saying that the tags fetched in the first `get_all_instances` request are notNEWLINE # reliable and may be missing, and the only way to guarantee they are there is by calling `get_all_tags`NEWLINE instance_ids = []NEWLINE for reservation in reservations:NEWLINE instance_ids.extend([instance.id for instance in reservation.instances])NEWLINENEWLINE max_filter_value = 199NEWLINE tags = []NEWLINE for i in range(0, len(instance_ids), max_filter_value):NEWLINE tags.extend(conn.get_all_tags(filters={'resource-type': 'instance', 'resource-id': instance_ids[i:i + max_filter_value]}))NEWLINENEWLINE tags_by_instance_id = defaultdict(dict)NEWLINE for tag in tags:NEWLINE tags_by_instance_id[tag.res_id][tag.name] = tag.valueNEWLINENEWLINE if (not self.aws_account_id) and reservations:NEWLINE self.aws_account_id = reservations[0].owner_idNEWLINENEWLINE for reservation in reservations:NEWLINE for instance in reservation.instances:NEWLINE instance.tags = tags_by_instance_id[instance.id]NEWLINE self.add_instance(instance, region)NEWLINENEWLINE except boto.exception.BotoServerError as e:NEWLINE if e.error_code == 'AuthFailure':NEWLINE error = self.get_auth_error_message()NEWLINE else:NEWLINE backend = 'Eucalyptus' if self.eucalyptus else 'AWS'NEWLINE error = "Error connecting to %s backend.\n%s" % (backend, e.message)NEWLINE self.fail_with_error(error, 'getting EC2 instances')NEWLINENEWLINE def get_rds_instances_by_region(self, region):NEWLINE ''' Makes an AWS API call to the list of RDS instances in a particularNEWLINE region '''NEWLINENEWLINE if not HAS_BOTO3:NEWLINE self.fail_with_error("Working with RDS instances requires boto3 - please install boto3 and try again",NEWLINE "getting RDS instances")NEWLINENEWLINE client = ec2_utils.boto3_inventory_conn('client', 'rds', region, **self.credentials)NEWLINE db_instances = client.describe_db_instances()NEWLINENEWLINE try:NEWLINE conn = self.connect_to_aws(rds, region)NEWLINE if conn:NEWLINE marker = NoneNEWLINE while True:NEWLINE instances = conn.get_all_dbinstances(marker=marker)NEWLINE marker = instances.markerNEWLINE for index, instance in enumerate(instances):NEWLINE # Add tags to instances.NEWLINE instance.arn = db_instances['DBInstances'][index]['DBInstanceArn']NEWLINE tags = client.list_tags_for_resource(ResourceName=instance.arn)['TagList']NEWLINE instance.tags = {}NEWLINE for tag in tags:NEWLINE instance.tags[tag['Key']] = tag['Value']NEWLINENEWLINE self.add_rds_instance(instance, region)NEWLINE if not marker:NEWLINE breakNEWLINE except boto.exception.BotoServerError as e:NEWLINE error = e.reasonNEWLINENEWLINE if e.error_code == 'AuthFailure':NEWLINE error = self.get_auth_error_message()NEWLINE elif e.error_code == "OptInRequired":NEWLINE error = "RDS hasn't been enabled for this account yet. " \NEWLINE "You must either log in to the RDS service through the AWS console to enable it, " \NEWLINE "or set 'rds = False' in ec2.ini"NEWLINE elif not e.reason == "Forbidden":NEWLINE error = "Looks like AWS RDS is down:\n%s" % e.messageNEWLINE self.fail_with_error(error, 'getting RDS instances')NEWLINENEWLINE def include_rds_clusters_by_region(self, region):NEWLINE if not HAS_BOTO3:NEWLINE self.fail_with_error("Working with RDS clusters requires boto3 - please install boto3 and try again",NEWLINE "getting RDS clusters")NEWLINENEWLINE client = ec2_utils.boto3_inventory_conn('client', 'rds', region, **self.credentials)NEWLINENEWLINE marker, clusters = '', []NEWLINE while marker is not None:NEWLINE resp = client.describe_db_clusters(Marker=marker)NEWLINE clusters.extend(resp["DBClusters"])NEWLINE marker = resp.get('Marker', None)NEWLINENEWLINE account_id = boto.connect_iam().get_user().arn.split(':')[4]NEWLINE c_dict = {}NEWLINE for c in clusters:NEWLINE # remove these datetime objects as there is no serialisation to jsonNEWLINE # currently in place and we don't need the data yetNEWLINE if 'EarliestRestorableTime' in c:NEWLINE del c['EarliestRestorableTime']NEWLINE if 'LatestRestorableTime' in c:NEWLINE del c['LatestRestorableTime']NEWLINENEWLINE if self.ec2_instance_filters == {}:NEWLINE matches_filter = TrueNEWLINE else:NEWLINE matches_filter = FalseNEWLINENEWLINE try:NEWLINE # arn:aws:rds::::NEWLINE tags = client.list_tags_for_resource(NEWLINE ResourceName='arn:aws:rds:' + region + ':' + account_id + ':cluster:' + c['DBClusterIdentifier'])NEWLINE c['Tags'] = tags['TagList']NEWLINENEWLINE if self.ec2_instance_filters:NEWLINE for filter_key, filter_values in self.ec2_instance_filters.items():NEWLINE # get AWS tag key e.g. tag:env will be 'env'NEWLINE tag_name = filter_key.split(":", 1)[1]NEWLINE # Filter values is a list (if you put multiple values for the same tag name)NEWLINE matches_filter = any(d['Key'] == tag_name and d['Value'] in filter_values for d in c['Tags'])NEWLINENEWLINE if matches_filter:NEWLINE # it matches a filter, so stop looking for further matchesNEWLINE breakNEWLINENEWLINE except Exception as e:NEWLINE if e.message.find('DBInstanceNotFound') >= 0:NEWLINE # AWS RDS bug (2016-01-06) means deletion does not fully complete and leave an 'empty' cluster.NEWLINE # Ignore errors when trying to find tags for theseNEWLINE passNEWLINENEWLINE # ignore empty clusters caused by AWS bugNEWLINE if len(c['DBClusterMembers']) == 0:NEWLINE continueNEWLINE elif matches_filter:NEWLINE c_dict[c['DBClusterIdentifier']] = cNEWLINENEWLINE self.inventory['db_clusters'] = c_dictNEWLINENEWLINE def get_elasticache_clusters_by_region(self, region):NEWLINE ''' Makes an AWS API call to the list of ElastiCache clusters (withNEWLINE nodes' info) in a particular region.'''NEWLINENEWLINE # ElastiCache boto module doesn't provide a get_all_instances method,NEWLINE # that's why we need to call describe directly (it would be called byNEWLINE # the shorthand method anyway...)NEWLINE try:NEWLINE conn = self.connect_to_aws(elasticache, region)NEWLINE if conn:NEWLINE # show_cache_node_info = TrueNEWLINE # because we also want nodes' informationNEWLINE response = conn.describe_cache_clusters(None, None, None, True)NEWLINENEWLINE except boto.exception.BotoServerError as e:NEWLINE error = e.reasonNEWLINENEWLINE if e.error_code == 'AuthFailure':NEWLINE error = self.get_auth_error_message()NEWLINE elif e.error_code == "OptInRequired":NEWLINE error = "ElastiCache hasn't been enabled for this account yet. " \NEWLINE "You must either log in to the ElastiCache service through the AWS console to enable it, " \NEWLINE "or set 'elasticache = False' in ec2.ini"NEWLINE elif not e.reason == "Forbidden":NEWLINE error = "Looks like AWS ElastiCache is down:\n%s" % e.messageNEWLINE self.fail_with_error(error, 'getting ElastiCache clusters')NEWLINENEWLINE try:NEWLINE # Boto also doesn't provide wrapper classes to CacheClusters orNEWLINE # CacheNodes. Because of that we can't make use of the get_listNEWLINE # method in the AWSQueryConnection. Let's do the work manuallyNEWLINE clusters = response['DescribeCacheClustersResponse']['DescribeCacheClustersResult']['CacheClusters']NEWLINENEWLINE except KeyError as e:NEWLINE error = "ElastiCache query to AWS failed (unexpected format)."NEWLINE self.fail_with_error(error, 'getting ElastiCache clusters')NEWLINENEWLINE for cluster in clusters:NEWLINE self.add_elasticache_cluster(cluster, region)NEWLINENEWLINE def get_elasticache_replication_groups_by_region(self, region):NEWLINE ''' Makes an AWS API call to the list of ElastiCache replication groupsNEWLINE in a particular region.'''NEWLINENEWLINE # ElastiCache boto module doesn't provide a get_all_instances method,NEWLINE # that's why we need to call describe directly (it would be called byNEWLINE # the shorthand method anyway...)NEWLINE try:NEWLINE conn = self.connect_to_aws(elasticache, region)NEWLINE if conn:NEWLINE response = conn.describe_replication_groups()NEWLINENEWLINE except boto.exception.BotoServerError as e:NEWLINE error = e.reasonNEWLINENEWLINE if e.error_code == 'AuthFailure':NEWLINE error = self.get_auth_error_message()NEWLINE if not e.reason == "Forbidden":NEWLINE error = "Looks like AWS ElastiCache [Replication Groups] is down:\n%s" % e.messageNEWLINE self.fail_with_error(error, 'getting ElastiCache clusters')NEWLINENEWLINE try:NEWLINE # Boto also doesn't provide wrapper classes to ReplicationGroupsNEWLINE # Because of that we can't make use of the get_list method in theNEWLINE # AWSQueryConnection. Let's do the work manuallyNEWLINE replication_groups = response['DescribeReplicationGroupsResponse']['DescribeReplicationGroupsResult']['ReplicationGroups']NEWLINENEWLINE except KeyError as e:NEWLINE error = "ElastiCache [Replication Groups] query to AWS failed (unexpected format)."NEWLINE self.fail_with_error(error, 'getting ElastiCache clusters')NEWLINENEWLINE for replication_group in replication_groups:NEWLINE self.add_elasticache_replication_group(replication_group, region)NEWLINENEWLINE def get_auth_error_message(self):NEWLINE ''' create an informative error message if there is an issue authenticating'''NEWLINE errors = ["Authentication error retrieving ec2 inventory."]NEWLINE if None in [os.environ.get('AWS_ACCESS_KEY_ID'), os.environ.get('AWS_SECRET_ACCESS_KEY')]:NEWLINE errors.append(' - No AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY environment vars found')NEWLINE else:NEWLINE errors.append(' - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment vars found but may not be correct')NEWLINENEWLINE boto_paths = ['/etc/boto.cfg', '~/.boto', '~/.aws/credentials']NEWLINE boto_config_found = list(p for p in boto_paths if os.path.isfile(os.path.expanduser(p)))NEWLINE if len(boto_config_found) > 0:NEWLINE errors.append(" - Boto configs found at '%s', but the credentials contained may not be correct" % ', '.join(boto_config_found))NEWLINE else:NEWLINE errors.append(" - No Boto config found at any expected location '%s'" % ', '.join(boto_paths))NEWLINENEWLINE return '\n'.join(errors)NEWLINENEWLINE def fail_with_error(self, err_msg, err_operation=None):NEWLINE '''log an error to std err for ansible-playbook to consume and exit'''NEWLINE if err_operation:NEWLINE err_msg = 'ERROR: "{err_msg}", while: {err_operation}'.format(NEWLINE err_msg=err_msg, err_operation=err_operation)NEWLINE sys.stderr.write(err_msg)NEWLINE sys.exit(1)NEWLINENEWLINE def get_instance(self, region, instance_id):NEWLINE conn = self.connect(region)NEWLINENEWLINE reservations = conn.get_all_instances([instance_id])NEWLINE for reservation in reservations:NEWLINE for instance in reservation.instances:NEWLINE return instanceNEWLINENEWLINE def add_instance(self, instance, region):NEWLINE ''' Adds an instance to the inventory and index, as long as it isNEWLINE addressable '''NEWLINENEWLINE # Only return instances with desired instance statesNEWLINE if instance.state not in self.ec2_instance_states:NEWLINE returnNEWLINENEWLINE # Select the best destination addressNEWLINE if self.destination_format and self.destination_format_tags:NEWLINE dest = self.destination_format.format(*[getattr(instance, 'tags').get(tag, '') for tag in self.destination_format_tags])NEWLINE elif instance.subnet_id:NEWLINE dest = getattr(instance, self.vpc_destination_variable, None)NEWLINE if dest is None:NEWLINE dest = getattr(instance, 'tags').get(self.vpc_destination_variable, None)NEWLINE else:NEWLINE dest = getattr(instance, self.destination_variable, None)NEWLINE if dest is None:NEWLINE dest = getattr(instance, 'tags').get(self.destination_variable, None)NEWLINENEWLINE if not dest:NEWLINE # Skip instances we cannot address (e.g. private VPC subnet)NEWLINE returnNEWLINENEWLINE # Set the inventory nameNEWLINE hostname = NoneNEWLINE if self.hostname_variable:NEWLINE if self.hostname_variable.startswith('tag_'):NEWLINE hostname = instance.tags.get(self.hostname_variable[4:], None)NEWLINE else:NEWLINE hostname = getattr(instance, self.hostname_variable)NEWLINENEWLINE # set the hostname from route53NEWLINE if self.route53_enabled and self.route53_hostnames:NEWLINE route53_names = self.get_instance_route53_names(instance)NEWLINE for name in route53_names:NEWLINE if name.endswith(self.route53_hostnames):NEWLINE hostname = nameNEWLINENEWLINE # If we can't get a nice hostname, use the destination addressNEWLINE if not hostname:NEWLINE hostname = destNEWLINE # to_safe strips hostname characters like dots, so don't strip route53 hostnamesNEWLINE elif self.route53_enabled and self.route53_hostnames and hostname.endswith(self.route53_hostnames):NEWLINE hostname = hostname.lower()NEWLINE else:NEWLINE hostname = self.to_safe(hostname).lower()NEWLINENEWLINE # if we only want to include hosts that match a pattern, skip those that don'tNEWLINE if self.pattern_include and not self.pattern_include.match(hostname):NEWLINE returnNEWLINENEWLINE # if we need to exclude hosts that match a pattern, skip thoseNEWLINE if self.pattern_exclude and self.pattern_exclude.match(hostname):NEWLINE returnNEWLINENEWLINE # Add to indexNEWLINE self.index[hostname] = [region, instance.id]NEWLINENEWLINE # Inventory: Group by instance ID (always a group of 1)NEWLINE if self.group_by_instance_id:NEWLINE self.inventory[instance.id] = [hostname]NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'instances', instance.id)NEWLINENEWLINE # Inventory: Group by regionNEWLINE if self.group_by_region:NEWLINE self.push(self.inventory, region, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'regions', region)NEWLINENEWLINE # Inventory: Group by availability zoneNEWLINE if self.group_by_availability_zone:NEWLINE self.push(self.inventory, instance.placement, hostname)NEWLINE if self.nested_groups:NEWLINE if self.group_by_region:NEWLINE self.push_group(self.inventory, region, instance.placement)NEWLINE self.push_group(self.inventory, 'zones', instance.placement)NEWLINENEWLINE # Inventory: Group by Amazon Machine Image (AMI) IDNEWLINE if self.group_by_ami_id:NEWLINE ami_id = self.to_safe(instance.image_id)NEWLINE self.push(self.inventory, ami_id, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'images', ami_id)NEWLINENEWLINE # Inventory: Group by instance typeNEWLINE if self.group_by_instance_type:NEWLINE type_name = self.to_safe('type_' + instance.instance_type)NEWLINE self.push(self.inventory, type_name, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'types', type_name)NEWLINENEWLINE # Inventory: Group by instance stateNEWLINE if self.group_by_instance_state:NEWLINE state_name = self.to_safe('instance_state_' + instance.state)NEWLINE self.push(self.inventory, state_name, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'instance_states', state_name)NEWLINENEWLINE # Inventory: Group by key pairNEWLINE if self.group_by_key_pair and instance.key_name:NEWLINE key_name = self.to_safe('key_' + instance.key_name)NEWLINE self.push(self.inventory, key_name, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'keys', key_name)NEWLINENEWLINE # Inventory: Group by VPCNEWLINE if self.group_by_vpc_id and instance.vpc_id:NEWLINE vpc_id_name = self.to_safe('vpc_id_' + instance.vpc_id)NEWLINE self.push(self.inventory, vpc_id_name, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'vpcs', vpc_id_name)NEWLINENEWLINE # Inventory: Group by security groupNEWLINE if self.group_by_security_group:NEWLINE try:NEWLINE for group in instance.groups:NEWLINE key = self.to_safe("security_group_" + group.name)NEWLINE self.push(self.inventory, key, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'security_groups', key)NEWLINE except AttributeError:NEWLINE self.fail_with_error('\n'.join(['Package boto seems a bit older.',NEWLINE 'Please upgrade boto >= 2.3.0.']))NEWLINENEWLINE # Inventory: Group by AWS account IDNEWLINE if self.group_by_aws_account:NEWLINE self.push(self.inventory, self.aws_account_id, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'accounts', self.aws_account_id)NEWLINENEWLINE # Inventory: Group by tag keysNEWLINE if self.group_by_tag_keys:NEWLINE for k, v in instance.tags.items():NEWLINE if self.expand_csv_tags and v and ',' in v:NEWLINE values = map(lambda x: x.strip(), v.split(','))NEWLINE else:NEWLINE values = [v]NEWLINENEWLINE for v in values:NEWLINE if v:NEWLINE key = self.to_safe("tag_" + k + "=" + v)NEWLINE else:NEWLINE key = self.to_safe("tag_" + k)NEWLINE self.push(self.inventory, key, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'tags', self.to_safe("tag_" + k))NEWLINE if v:NEWLINE self.push_group(self.inventory, self.to_safe("tag_" + k), key)NEWLINENEWLINE # Inventory: Group by Route53 domain names if enabledNEWLINE if self.route53_enabled and self.group_by_route53_names:NEWLINE route53_names = self.get_instance_route53_names(instance)NEWLINE for name in route53_names:NEWLINE self.push(self.inventory, name, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'route53', name)NEWLINENEWLINE # Global Tag: instances without tagsNEWLINE if self.group_by_tag_none and len(instance.tags) == 0:NEWLINE self.push(self.inventory, 'tag_none', hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'tags', 'tag_none')NEWLINENEWLINE # Global Tag: tag all EC2 instancesNEWLINE self.push(self.inventory, 'ec2', hostname)NEWLINENEWLINE self.inventory["_meta"]["hostvars"][hostname] = self.get_host_info_dict_from_instance(instance)NEWLINE self.inventory["_meta"]["hostvars"][hostname]['ansible_host'] = destNEWLINENEWLINE def add_rds_instance(self, instance, region):NEWLINE ''' Adds an RDS instance to the inventory and index, as long as it isNEWLINE addressable '''NEWLINENEWLINE # Only want available instances unless all_rds_instances is TrueNEWLINE if not self.all_rds_instances and instance.status != 'available':NEWLINE returnNEWLINENEWLINE # Select the best destination addressNEWLINE dest = instance.endpoint[0]NEWLINENEWLINE if not dest:NEWLINE # Skip instances we cannot address (e.g. private VPC subnet)NEWLINE returnNEWLINENEWLINE # Set the inventory nameNEWLINE hostname = NoneNEWLINE if self.hostname_variable:NEWLINE if self.hostname_variable.startswith('tag_'):NEWLINE hostname = instance.tags.get(self.hostname_variable[4:], None)NEWLINE else:NEWLINE hostname = getattr(instance, self.hostname_variable)NEWLINENEWLINE # If we can't get a nice hostname, use the destination addressNEWLINE if not hostname:NEWLINE hostname = destNEWLINENEWLINE hostname = self.to_safe(hostname).lower()NEWLINENEWLINE # Add to indexNEWLINE self.index[hostname] = [region, instance.id]NEWLINENEWLINE # Inventory: Group by instance ID (always a group of 1)NEWLINE if self.group_by_instance_id:NEWLINE self.inventory[instance.id] = [hostname]NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'instances', instance.id)NEWLINENEWLINE # Inventory: Group by regionNEWLINE if self.group_by_region:NEWLINE self.push(self.inventory, region, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'regions', region)NEWLINENEWLINE # Inventory: Group by availability zoneNEWLINE if self.group_by_availability_zone:NEWLINE self.push(self.inventory, instance.availability_zone, hostname)NEWLINE if self.nested_groups:NEWLINE if self.group_by_region:NEWLINE self.push_group(self.inventory, region, instance.availability_zone)NEWLINE self.push_group(self.inventory, 'zones', instance.availability_zone)NEWLINENEWLINE # Inventory: Group by instance typeNEWLINE if self.group_by_instance_type:NEWLINE type_name = self.to_safe('type_' + instance.instance_class)NEWLINE self.push(self.inventory, type_name, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'types', type_name)NEWLINENEWLINE # Inventory: Group by VPCNEWLINE if self.group_by_vpc_id and instance.subnet_group and instance.subnet_group.vpc_id:NEWLINE vpc_id_name = self.to_safe('vpc_id_' + instance.subnet_group.vpc_id)NEWLINE self.push(self.inventory, vpc_id_name, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'vpcs', vpc_id_name)NEWLINENEWLINE # Inventory: Group by security groupNEWLINE if self.group_by_security_group:NEWLINE try:NEWLINE if instance.security_group:NEWLINE key = self.to_safe("security_group_" + instance.security_group.name)NEWLINE self.push(self.inventory, key, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'security_groups', key)NEWLINENEWLINE except AttributeError:NEWLINE self.fail_with_error('\n'.join(['Package boto seems a bit older.',NEWLINE 'Please upgrade boto >= 2.3.0.']))NEWLINENEWLINE # Inventory: Group by engineNEWLINE if self.group_by_rds_engine:NEWLINE self.push(self.inventory, self.to_safe("rds_" + instance.engine), hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'rds_engines', self.to_safe("rds_" + instance.engine))NEWLINENEWLINE # Inventory: Group by parameter groupNEWLINE if self.group_by_rds_parameter_group:NEWLINE self.push(self.inventory, self.to_safe("rds_parameter_group_" + instance.parameter_group.name), hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'rds_parameter_groups', self.to_safe("rds_parameter_group_" + instance.parameter_group.name))NEWLINENEWLINE # Global Tag: all RDS instancesNEWLINE self.push(self.inventory, 'rds', hostname)NEWLINENEWLINE self.inventory["_meta"]["hostvars"][hostname] = self.get_host_info_dict_from_instance(instance)NEWLINE self.inventory["_meta"]["hostvars"][hostname]['ansible_host'] = destNEWLINENEWLINE def add_elasticache_cluster(self, cluster, region):NEWLINE ''' Adds an ElastiCache cluster to the inventory and index, as long asNEWLINE it's nodes are addressable '''NEWLINENEWLINE # Only want available clusters unless all_elasticache_clusters is TrueNEWLINE if not self.all_elasticache_clusters and cluster['CacheClusterStatus'] != 'available':NEWLINE returnNEWLINENEWLINE # Select the best destination addressNEWLINE if 'ConfigurationEndpoint' in cluster and cluster['ConfigurationEndpoint']:NEWLINE # Memcached clusterNEWLINE dest = cluster['ConfigurationEndpoint']['Address']NEWLINE is_redis = FalseNEWLINE else:NEWLINE # Redis sigle node clusterNEWLINE # Because all Redis clusters are single nodes, we'll merge theNEWLINE # info from the cluster with info about the nodeNEWLINE dest = cluster['CacheNodes'][0]['Endpoint']['Address']NEWLINE is_redis = TrueNEWLINENEWLINE if not dest:NEWLINE # Skip clusters we cannot address (e.g. private VPC subnet)NEWLINE returnNEWLINENEWLINE # Add to indexNEWLINE self.index[dest] = [region, cluster['CacheClusterId']]NEWLINENEWLINE # Inventory: Group by instance ID (always a group of 1)NEWLINE if self.group_by_instance_id:NEWLINE self.inventory[cluster['CacheClusterId']] = [dest]NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'instances', cluster['CacheClusterId'])NEWLINENEWLINE # Inventory: Group by regionNEWLINE if self.group_by_region and not is_redis:NEWLINE self.push(self.inventory, region, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'regions', region)NEWLINENEWLINE # Inventory: Group by availability zoneNEWLINE if self.group_by_availability_zone and not is_redis:NEWLINE self.push(self.inventory, cluster['PreferredAvailabilityZone'], dest)NEWLINE if self.nested_groups:NEWLINE if self.group_by_region:NEWLINE self.push_group(self.inventory, region, cluster['PreferredAvailabilityZone'])NEWLINE self.push_group(self.inventory, 'zones', cluster['PreferredAvailabilityZone'])NEWLINENEWLINE # Inventory: Group by node typeNEWLINE if self.group_by_instance_type and not is_redis:NEWLINE type_name = self.to_safe('type_' + cluster['CacheNodeType'])NEWLINE self.push(self.inventory, type_name, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'types', type_name)NEWLINENEWLINE # Inventory: Group by VPC (information not available in the currentNEWLINE # AWS API version for ElastiCache)NEWLINENEWLINE # Inventory: Group by security groupNEWLINE if self.group_by_security_group and not is_redis:NEWLINENEWLINE # Check for the existence of the 'SecurityGroups' key and also ifNEWLINE # this key has some value. When the cluster is not placed in a SGNEWLINE # the query can return None here and cause an error.NEWLINE if 'SecurityGroups' in cluster and cluster['SecurityGroups'] is not None:NEWLINE for security_group in cluster['SecurityGroups']:NEWLINE key = self.to_safe("security_group_" + security_group['SecurityGroupId'])NEWLINE self.push(self.inventory, key, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'security_groups', key)NEWLINENEWLINE # Inventory: Group by engineNEWLINE if self.group_by_elasticache_engine and not is_redis:NEWLINE self.push(self.inventory, self.to_safe("elasticache_" + cluster['Engine']), dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'elasticache_engines', self.to_safe(cluster['Engine']))NEWLINENEWLINE # Inventory: Group by parameter groupNEWLINE if self.group_by_elasticache_parameter_group:NEWLINE self.push(self.inventory, self.to_safe("elasticache_parameter_group_" + cluster['CacheParameterGroup']['CacheParameterGroupName']), dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'elasticache_parameter_groups', self.to_safe(cluster['CacheParameterGroup']['CacheParameterGroupName']))NEWLINENEWLINE # Inventory: Group by replication groupNEWLINE if self.group_by_elasticache_replication_group and 'ReplicationGroupId' in cluster and cluster['ReplicationGroupId']:NEWLINE self.push(self.inventory, self.to_safe("elasticache_replication_group_" + cluster['ReplicationGroupId']), dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'elasticache_replication_groups', self.to_safe(cluster['ReplicationGroupId']))NEWLINENEWLINE # Global Tag: all ElastiCache clustersNEWLINE self.push(self.inventory, 'elasticache_clusters', cluster['CacheClusterId'])NEWLINENEWLINE host_info = self.get_host_info_dict_from_describe_dict(cluster)NEWLINENEWLINE self.inventory["_meta"]["hostvars"][dest] = host_infoNEWLINENEWLINE # Add the nodesNEWLINE for node in cluster['CacheNodes']:NEWLINE self.add_elasticache_node(node, cluster, region)NEWLINENEWLINE def add_elasticache_node(self, node, cluster, region):NEWLINE ''' Adds an ElastiCache node to the inventory and index, as long asNEWLINE it is addressable '''NEWLINENEWLINE # Only want available nodes unless all_elasticache_nodes is TrueNEWLINE if not self.all_elasticache_nodes and node['CacheNodeStatus'] != 'available':NEWLINE returnNEWLINENEWLINE # Select the best destination addressNEWLINE dest = node['Endpoint']['Address']NEWLINENEWLINE if not dest:NEWLINE # Skip nodes we cannot address (e.g. private VPC subnet)NEWLINE returnNEWLINENEWLINE node_id = self.to_safe(cluster['CacheClusterId'] + '_' + node['CacheNodeId'])NEWLINENEWLINE # Add to indexNEWLINE self.index[dest] = [region, node_id]NEWLINENEWLINE # Inventory: Group by node ID (always a group of 1)NEWLINE if self.group_by_instance_id:NEWLINE self.inventory[node_id] = [dest]NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'instances', node_id)NEWLINENEWLINE # Inventory: Group by regionNEWLINE if self.group_by_region:NEWLINE self.push(self.inventory, region, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'regions', region)NEWLINENEWLINE # Inventory: Group by availability zoneNEWLINE if self.group_by_availability_zone:NEWLINE self.push(self.inventory, cluster['PreferredAvailabilityZone'], dest)NEWLINE if self.nested_groups:NEWLINE if self.group_by_region:NEWLINE self.push_group(self.inventory, region, cluster['PreferredAvailabilityZone'])NEWLINE self.push_group(self.inventory, 'zones', cluster['PreferredAvailabilityZone'])NEWLINENEWLINE # Inventory: Group by node typeNEWLINE if self.group_by_instance_type:NEWLINE type_name = self.to_safe('type_' + cluster['CacheNodeType'])NEWLINE self.push(self.inventory, type_name, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'types', type_name)NEWLINENEWLINE # Inventory: Group by VPC (information not available in the currentNEWLINE # AWS API version for ElastiCache)NEWLINENEWLINE # Inventory: Group by security groupNEWLINE if self.group_by_security_group:NEWLINENEWLINE # Check for the existence of the 'SecurityGroups' key and also ifNEWLINE # this key has some value. When the cluster is not placed in a SGNEWLINE # the query can return None here and cause an error.NEWLINE if 'SecurityGroups' in cluster and cluster['SecurityGroups'] is not None:NEWLINE for security_group in cluster['SecurityGroups']:NEWLINE key = self.to_safe("security_group_" + security_group['SecurityGroupId'])NEWLINE self.push(self.inventory, key, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'security_groups', key)NEWLINENEWLINE # Inventory: Group by engineNEWLINE if self.group_by_elasticache_engine:NEWLINE self.push(self.inventory, self.to_safe("elasticache_" + cluster['Engine']), dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'elasticache_engines', self.to_safe("elasticache_" + cluster['Engine']))NEWLINENEWLINE # Inventory: Group by parameter group (done at cluster level)NEWLINENEWLINE # Inventory: Group by replication group (done at cluster level)NEWLINENEWLINE # Inventory: Group by ElastiCache ClusterNEWLINE if self.group_by_elasticache_cluster:NEWLINE self.push(self.inventory, self.to_safe("elasticache_cluster_" + cluster['CacheClusterId']), dest)NEWLINENEWLINE # Global Tag: all ElastiCache nodesNEWLINE self.push(self.inventory, 'elasticache_nodes', dest)NEWLINENEWLINE host_info = self.get_host_info_dict_from_describe_dict(node)NEWLINENEWLINE if dest in self.inventory["_meta"]["hostvars"]:NEWLINE self.inventory["_meta"]["hostvars"][dest].update(host_info)NEWLINE else:NEWLINE self.inventory["_meta"]["hostvars"][dest] = host_infoNEWLINENEWLINE def add_elasticache_replication_group(self, replication_group, region):NEWLINE ''' Adds an ElastiCache replication group to the inventory and index '''NEWLINENEWLINE # Only want available clusters unless all_elasticache_replication_groups is TrueNEWLINE if not self.all_elasticache_replication_groups and replication_group['Status'] != 'available':NEWLINE returnNEWLINENEWLINE # Skip clusters we cannot address (e.g. private VPC subnet or clustered redis)NEWLINE if replication_group['NodeGroups'][0]['PrimaryEndpoint'] is None or \NEWLINE replication_group['NodeGroups'][0]['PrimaryEndpoint']['Address'] is None:NEWLINE returnNEWLINENEWLINE # Select the best destination address (PrimaryEndpoint)NEWLINE dest = replication_group['NodeGroups'][0]['PrimaryEndpoint']['Address']NEWLINENEWLINE # Add to indexNEWLINE self.index[dest] = [region, replication_group['ReplicationGroupId']]NEWLINENEWLINE # Inventory: Group by ID (always a group of 1)NEWLINE if self.group_by_instance_id:NEWLINE self.inventory[replication_group['ReplicationGroupId']] = [dest]NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'instances', replication_group['ReplicationGroupId'])NEWLINENEWLINE # Inventory: Group by regionNEWLINE if self.group_by_region:NEWLINE self.push(self.inventory, region, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'regions', region)NEWLINENEWLINE # Inventory: Group by availability zone (doesn't apply to replication groups)NEWLINENEWLINE # Inventory: Group by node type (doesn't apply to replication groups)NEWLINENEWLINE # Inventory: Group by VPC (information not available in the currentNEWLINE # AWS API version for replication groupsNEWLINENEWLINE # Inventory: Group by security group (doesn't apply to replication groups)NEWLINE # Check this value in cluster levelNEWLINENEWLINE # Inventory: Group by engine (replication groups are always Redis)NEWLINE if self.group_by_elasticache_engine:NEWLINE self.push(self.inventory, 'elasticache_redis', dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'elasticache_engines', 'redis')NEWLINENEWLINE # Global Tag: all ElastiCache clustersNEWLINE self.push(self.inventory, 'elasticache_replication_groups', replication_group['ReplicationGroupId'])NEWLINENEWLINE host_info = self.get_host_info_dict_from_describe_dict(replication_group)NEWLINENEWLINE self.inventory["_meta"]["hostvars"][dest] = host_infoNEWLINENEWLINE def get_route53_records(self):NEWLINE ''' Get and store the map of resource records to domain names thatNEWLINE point to them. '''NEWLINENEWLINE if self.boto_profile:NEWLINE r53_conn = route53.Route53Connection(profile_name=self.boto_profile)NEWLINE else:NEWLINE r53_conn = route53.Route53Connection()NEWLINE all_zones = r53_conn.get_zones()NEWLINENEWLINE route53_zones = [zone for zone in all_zones if zone.name[:-1] not in self.route53_excluded_zones]NEWLINENEWLINE self.route53_records = {}NEWLINENEWLINE for zone in route53_zones:NEWLINE rrsets = r53_conn.get_all_rrsets(zone.id)NEWLINENEWLINE for record_set in rrsets:NEWLINE record_name = record_set.nameNEWLINENEWLINE if record_name.endswith('.'):NEWLINE record_name = record_name[:-1]NEWLINENEWLINE for resource in record_set.resource_records:NEWLINE self.route53_records.setdefault(resource, set())NEWLINE self.route53_records[resource].add(record_name)NEWLINENEWLINE def get_instance_route53_names(self, instance):NEWLINE ''' Check if an instance is referenced in the records we have fromNEWLINE Route53. If it is, return the list of domain names pointing to saidNEWLINE instance. If nothing points to it, return an empty list. '''NEWLINENEWLINE instance_attributes = ['public_dns_name', 'private_dns_name',NEWLINE 'ip_address', 'private_ip_address']NEWLINENEWLINE name_list = set()NEWLINENEWLINE for attrib in instance_attributes:NEWLINE try:NEWLINE value = getattr(instance, attrib)NEWLINE except AttributeError:NEWLINE continueNEWLINENEWLINE if value in self.route53_records:NEWLINE name_list.update(self.route53_records[value])NEWLINENEWLINE return list(name_list)NEWLINENEWLINE def get_host_info_dict_from_instance(self, instance):NEWLINE instance_vars = {}NEWLINE for key in vars(instance):NEWLINE value = getattr(instance, key)NEWLINE key = self.to_safe('ec2_' + key)NEWLINENEWLINE # Handle complex typesNEWLINE # state/previous_state changed to properties in boto in https://github.com/boto/boto/commit/a23c379837f698212252720d2af8dec0325c9518NEWLINE if key == 'ec2__state':NEWLINE instance_vars['ec2_state'] = instance.state or ''NEWLINE instance_vars['ec2_state_code'] = instance.state_codeNEWLINE elif key == 'ec2__previous_state':NEWLINE instance_vars['ec2_previous_state'] = instance.previous_state or ''NEWLINE instance_vars['ec2_previous_state_code'] = instance.previous_state_codeNEWLINE elif isinstance(value, (int, bool)):NEWLINE instance_vars[key] = valueNEWLINE elif isinstance(value, six.string_types):NEWLINE instance_vars[key] = value.strip()NEWLINE elif value is None:NEWLINE instance_vars[key] = ''NEWLINE elif key == 'ec2_region':NEWLINE instance_vars[key] = value.nameNEWLINE elif key == 'ec2__placement':NEWLINE instance_vars['ec2_placement'] = value.zoneNEWLINE elif key == 'ec2_tags':NEWLINE for k, v in value.items():NEWLINE if self.expand_csv_tags and ',' in v:NEWLINE v = list(map(lambda x: x.strip(), v.split(',')))NEWLINE key = self.to_safe('ec2_tag_' + k)NEWLINE instance_vars[key] = vNEWLINE elif key == 'ec2_groups':NEWLINE group_ids = []NEWLINE group_names = []NEWLINE for group in value:NEWLINE group_ids.append(group.id)NEWLINE group_names.append(group.name)NEWLINE instance_vars["ec2_security_group_ids"] = ','.join([str(i) for i in group_ids])NEWLINE instance_vars["ec2_security_group_names"] = ','.join([str(i) for i in group_names])NEWLINE elif key == 'ec2_block_device_mapping':NEWLINE instance_vars["ec2_block_devices"] = {}NEWLINE for k, v in value.items():NEWLINE instance_vars["ec2_block_devices"][os.path.basename(k)] = v.volume_idNEWLINE else:NEWLINE passNEWLINE # TODO Product codes if someone finds them usefulNEWLINE # print keyNEWLINE # print type(value)NEWLINE # print valueNEWLINENEWLINE instance_vars[self.to_safe('ec2_account_id')] = self.aws_account_idNEWLINENEWLINE return instance_varsNEWLINENEWLINE def get_host_info_dict_from_describe_dict(self, describe_dict):NEWLINE ''' Parses the dictionary returned by the API call into a flat listNEWLINE of parameters. This method should be used only when 'describe' isNEWLINE used directly because Boto doesn't provide specific classes. '''NEWLINENEWLINE # I really don't agree with prefixing everything with 'ec2'NEWLINE # because EC2, RDS and ElastiCache are different services.NEWLINE # I'm just following the pattern used until now to not break anyNEWLINE # compatibility.NEWLINENEWLINE host_info = {}NEWLINE for key in describe_dict:NEWLINE value = describe_dict[key]NEWLINE key = self.to_safe('ec2_' + self.uncammelize(key))NEWLINENEWLINE # Handle complex typesNEWLINENEWLINE # Target: Memcached Cache ClustersNEWLINE if key == 'ec2_configuration_endpoint' and value:NEWLINE host_info['ec2_configuration_endpoint_address'] = value['Address']NEWLINE host_info['ec2_configuration_endpoint_port'] = value['Port']NEWLINENEWLINE # Target: Cache Nodes and Redis Cache Clusters (single node)NEWLINE if key == 'ec2_endpoint' and value:NEWLINE host_info['ec2_endpoint_address'] = value['Address']NEWLINE host_info['ec2_endpoint_port'] = value['Port']NEWLINENEWLINE # Target: Redis Replication GroupsNEWLINE if key == 'ec2_node_groups' and value:NEWLINE host_info['ec2_endpoint_address'] = value[0]['PrimaryEndpoint']['Address']NEWLINE host_info['ec2_endpoint_port'] = value[0]['PrimaryEndpoint']['Port']NEWLINE replica_count = 0NEWLINE for node in value[0]['NodeGroupMembers']:NEWLINE if node['CurrentRole'] == 'primary':NEWLINE host_info['ec2_primary_cluster_address'] = node['ReadEndpoint']['Address']NEWLINE host_info['ec2_primary_cluster_port'] = node['ReadEndpoint']['Port']NEWLINE host_info['ec2_primary_cluster_id'] = node['CacheClusterId']NEWLINE elif node['CurrentRole'] == 'replica':NEWLINE host_info['ec2_replica_cluster_address_' + str(replica_count)] = node['ReadEndpoint']['Address']NEWLINE host_info['ec2_replica_cluster_port_' + str(replica_count)] = node['ReadEndpoint']['Port']NEWLINE host_info['ec2_replica_cluster_id_' + str(replica_count)] = node['CacheClusterId']NEWLINE replica_count += 1NEWLINENEWLINE # Target: Redis Replication GroupsNEWLINE if key == 'ec2_member_clusters' and value:NEWLINE host_info['ec2_member_clusters'] = ','.join([str(i) for i in value])NEWLINENEWLINE # Target: All Cache ClustersNEWLINE elif key == 'ec2_cache_parameter_group':NEWLINE host_info["ec2_cache_node_ids_to_reboot"] = ','.join([str(i) for i in value['CacheNodeIdsToReboot']])NEWLINE host_info['ec2_cache_parameter_group_name'] = value['CacheParameterGroupName']NEWLINE host_info['ec2_cache_parameter_apply_status'] = value['ParameterApplyStatus']NEWLINENEWLINE # Target: Almost everythingNEWLINE elif key == 'ec2_security_groups':NEWLINENEWLINE # Skip if SecurityGroups is NoneNEWLINE # (it is possible to have the key defined but no value in it).NEWLINE if value is not None:NEWLINE sg_ids = []NEWLINE for sg in value:NEWLINE sg_ids.append(sg['SecurityGroupId'])NEWLINE host_info["ec2_security_group_ids"] = ','.join([str(i) for i in sg_ids])NEWLINENEWLINE # Target: EverythingNEWLINE # Preserve booleans and integersNEWLINE elif isinstance(value, (int, bool)):NEWLINE host_info[key] = valueNEWLINENEWLINE # Target: EverythingNEWLINE # Sanitize string valuesNEWLINE elif isinstance(value, six.string_types):NEWLINE host_info[key] = value.strip()NEWLINENEWLINE # Target: EverythingNEWLINE # Replace None by an empty stringNEWLINE elif value is None:NEWLINE host_info[key] = ''NEWLINENEWLINE else:NEWLINE # Remove non-processed complex typesNEWLINE passNEWLINENEWLINE return host_infoNEWLINENEWLINE def get_host_info(self):NEWLINE ''' Get variables about a specific host '''NEWLINENEWLINE if len(self.index) == 0:NEWLINE # Need to load index from cacheNEWLINE self.load_index_from_cache()NEWLINENEWLINE if self.args.host not in self.index:NEWLINE # try updating the cacheNEWLINE self.do_api_calls_update_cache()NEWLINE if self.args.host not in self.index:NEWLINE # host might not exist anymoreNEWLINE return self.json_format_dict({}, True)NEWLINENEWLINE (region, instance_id) = self.index[self.args.host]NEWLINENEWLINE instance = self.get_instance(region, instance_id)NEWLINE return self.json_format_dict(self.get_host_info_dict_from_instance(instance), True)NEWLINENEWLINE def push(self, my_dict, key, element):NEWLINE ''' Push an element onto an array that may not have been defined inNEWLINE the dict '''NEWLINE group_info = my_dict.setdefault(key, [])NEWLINE if isinstance(group_info, dict):NEWLINE host_list = group_info.setdefault('hosts', [])NEWLINE host_list.append(element)NEWLINE else:NEWLINE group_info.append(element)NEWLINENEWLINE def push_group(self, my_dict, key, element):NEWLINE ''' Push a group as a child of another group. '''NEWLINE parent_group = my_dict.setdefault(key, {})NEWLINE if not isinstance(parent_group, dict):NEWLINE parent_group = my_dict[key] = {'hosts': parent_group}NEWLINE child_groups = parent_group.setdefault('children', [])NEWLINE if element not in child_groups:NEWLINE child_groups.append(element)NEWLINENEWLINE def get_inventory_from_cache(self):NEWLINE ''' Reads the inventory from the cache file and returns it as a JSONNEWLINE object '''NEWLINENEWLINE with open(self.cache_path_cache, 'r') as f:NEWLINE json_inventory = f.read()NEWLINE return json_inventoryNEWLINENEWLINE def load_index_from_cache(self):NEWLINE ''' Reads the index from the cache file sets self.index '''NEWLINENEWLINE with open(self.cache_path_index, 'rb') as f:NEWLINE self.index = json.load(f)NEWLINENEWLINE def write_to_cache(self, data, filename):NEWLINE ''' Writes data in JSON format to a file '''NEWLINENEWLINE json_data = self.json_format_dict(data, True)NEWLINE with open(filename, 'w') as f:NEWLINE f.write(json_data)NEWLINENEWLINE def uncammelize(self, key):NEWLINE temp = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', key)NEWLINE return re.sub('([a-z0-9])([A-Z])', r'\1_\2', temp).lower()NEWLINENEWLINE def to_safe(self, word):NEWLINE ''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups '''NEWLINE regex = "[^A-Za-z0-9\_"NEWLINE if not self.replace_dash_in_groups:NEWLINE regex += "\-"NEWLINE return re.sub(regex + "]", "_", word)NEWLINENEWLINE def json_format_dict(self, data, pretty=False):NEWLINE ''' Converts a dict to a JSON object and dumps it as a formattedNEWLINE string '''NEWLINENEWLINE if pretty:NEWLINE return json.dumps(data, sort_keys=True, indent=2)NEWLINE else:NEWLINE return json.dumps(data)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE # Run the scriptNEWLINE Ec2Inventory()NEWLINE #NEWLINE# Copyright (c) 2016-2021 JEP AUTHORS.NEWLINE#NEWLINE# This file is licensed under the the zlib/libpng License.NEWLINE#NEWLINE# This software is provided 'as-is', without any express or impliedNEWLINE# warranty. In no event will the authors be held liable for anyNEWLINE# damages arising from the use of this software.NEWLINE# NEWLINE# Permission is granted to anyone to use this software for anyNEWLINE# purpose, including commercial applications, and to alter it andNEWLINE# redistribute it freely, subject to the following restrictions:NEWLINE# NEWLINE# 1. The origin of this software must not be misrepresented; youNEWLINE# must not claim that you wrote the original software. If you useNEWLINE# this software in a product, an acknowledgment in the productNEWLINE# documentation would be appreciated but is not required.NEWLINE# NEWLINE# 2. Altered source versions must be plainly marked as such, andNEWLINE# must not be misrepresented as being the original software.NEWLINE# NEWLINE# 3. This notice may not be removed or altered from any sourceNEWLINE# distribution.NEWLINE#NEWLINENEWLINEimport sysNEWLINENEWLINEclass StreamRedirect(object):NEWLINE "Redirects a Python output stream to a Java OutputStream"NEWLINENEWLINE def __init__(self, javaOutputStream):NEWLINE from java.io import PrintStreamNEWLINE self.printstream = PrintStream(javaOutputStream)NEWLINE self.printmethod = getattr(self.printstream, 'print')NEWLINE self.flushmethod = getattr(self.printstream, 'flush')NEWLINENEWLINE def write(self, msg):NEWLINE self.printmethod(msg)NEWLINENEWLINE def flush(self):NEWLINE self.flushmethod()NEWLINENEWLINEdef redirectStdout(javaOutputStream):NEWLINE sys.stdout = StreamRedirect(javaOutputStream)NEWLINENEWLINEdef redirectStderr(javaOutputStream):NEWLINE sys.stderr = StreamRedirect(javaOutputStream)NEWLINE #!/usr/bin/env pythonNEWLINE#NEWLINE# Copyright 2015-2016 Rafael Ferreira da SilvaNEWLINE# http://www.rafaelsilva.com/toolsNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing,NEWLINE# software distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE#NEWLINE__author__ = "Rafael Ferreira da Silva"NEWLINENEWLINEimport unicodedataNEWLINEfrom tools.utils import *NEWLINENEWLINElog = logging.getLogger(__name__)NEWLINENEWLINENEWLINEclass EntryType:NEWLINE ARTICLE = "article"NEWLINE BOOK = "book"NEWLINE INCOLLECTION = "incollection"NEWLINE INPROCEEDINGS = "inproceedings"NEWLINE MASTERTHESIS = "mastersthesis"NEWLINE PHDTHESIS = "phdthesis"NEWLINE MISC = "misc"NEWLINE PROCEEDINGS = "proceedings"NEWLINE TECHREPORT = "techreport"NEWLINENEWLINENEWLINEclass Entry:NEWLINE def __init__(self, entry_type=None, cite_key=None, address=None, annote=None, authors=None, booktitle=None,NEWLINE chapter=None, crossref=None, edition=None, editor=None, howpublished=None, institution=None,NEWLINE journal=None, key=None, month=None, note=None, number=None, organization=None, pages=None,NEWLINE publisher=None, school=None, series=None, title=None, type=None, url=None, volume=None,NEWLINE year=None, doi=None):NEWLINE """NEWLINE Create a bib entry.NEWLINE :param entry_type: type of the entry (e.g., article, inproceedings, etc.)NEWLINE :param cite_key: cite key used in latex files to reference the entryNEWLINE :param address:NEWLINE :param annote:NEWLINE :param authors: list of authors (separated by 'and')NEWLINE :param booktitle: title of the conference bookNEWLINE :param chapter:NEWLINE :param crossref:NEWLINE :param edition:NEWLINE :param editors: list of editors (separated by 'and')NEWLINE :param howpublished:NEWLINE :param institution:NEWLINE :param journal: title of the journalNEWLINE :param key: publication key (usually required for 'misc' entry types)NEWLINE :param month:NEWLINE :param note:NEWLINE :param number: journal issue numberNEWLINE :param organization:NEWLINE :param pages: page numbers (separated by dashes)NEWLINE :param publisher:NEWLINE :param school:NEWLINE :param series:NEWLINE :param title: publication titleNEWLINE :param type:NEWLINE :param url: publication urlNEWLINE :param volume: journal volumeNEWLINE :param year: publication yearNEWLINE :param doi: document object identifierNEWLINE """NEWLINE self.entry_type = entry_typeNEWLINE self.cite_key = cite_keyNEWLINE self.address = addressNEWLINE self.annote = annoteNEWLINE self.authors = Authors(authors_list=authors)NEWLINE self.booktitle = _parse_booktitle(booktitle)NEWLINE self.chapter = chapterNEWLINE self.crossref = crossrefNEWLINE self.edition = editionNEWLINE self.editors = Authors(authors_list=editor)NEWLINE self.howpublished = howpublishedNEWLINE self.institution = institutionNEWLINE self.journal = journalNEWLINE self.key = keyNEWLINE self.month = monthNEWLINE self.note = noteNEWLINE self.number = numberNEWLINE self.organization = organizationNEWLINE self.pages = _parse_pages(pages)NEWLINE self.publisher = publisherNEWLINE self.school = schoolNEWLINE self.series = seriesNEWLINE self.title = titleNEWLINE self.type = typeNEWLINE self.url = urlNEWLINE self.volume = volumeNEWLINE self.year = yearNEWLINE self.doi = doiNEWLINE # Entry internal propertiesNEWLINE self.online_processed = FalseNEWLINE self.compressed = FalseNEWLINENEWLINE def merge(self, entry):NEWLINE """NEWLINE Merge two entries.NEWLINE :param entry: entry to be mergedNEWLINE """NEWLINE self.entry_type = _merge_entry_type(self.entry_type, entry.entry_type)NEWLINE self.address = _merge_field(self.address, entry.address)NEWLINE self.annote = _merge_field(self.annote, entry.annote)NEWLINE self.booktitle = _merge_field(self.booktitle, entry.booktitle)NEWLINE self.chapter = _merge_field(self.chapter, entry.chapter)NEWLINE self.crossref = _merge_field(self.crossref, entry.crossref)NEWLINE self.edition = _merge_field(self.edition, entry.edition)NEWLINE self.howpublished = _merge_field(self.howpublished, entry.howpublished)NEWLINE self.institution = _merge_field(self.institution, entry.institution)NEWLINE self.journal = _merge_field(self.journal, entry.journal)NEWLINE self.key = _merge_field(self.key, entry.key)NEWLINE self.month = _merge_field(self.month, entry.month)NEWLINE self.note = _merge_field(self.note, entry.note)NEWLINE self.number = _merge_field(self.number, entry.number, is_int=True)NEWLINE self.organization = _merge_field(self.organization, entry.organization)NEWLINE self.pages = _merge_field(self.pages, entry.pages)NEWLINE self.publisher = _merge_field(self.publisher, entry.publisher)NEWLINE self.school = _merge_field(self.school, entry.school)NEWLINE self.series = _merge_field(self.series, entry.series)NEWLINE self.title = _merge_field(self.title, entry.title)NEWLINE self.type = _merge_field(self.type, entry.type)NEWLINE self.url = _merge_field(self.url, entry.url)NEWLINE self.volume = _merge_field(self.volume, entry.volume)NEWLINE self.year = _merge_field(self.year, entry.year, is_int=True)NEWLINE self.doi = _merge_field(self.doi, entry.doi)NEWLINE self.editors.merge(entry.editors.authors)NEWLINE self.authors.merge(entry.authors.authors)NEWLINENEWLINE def __str__(self):NEWLINE entry_str = "@%s{%s,\n" % (self.entry_type, self.cite_key)NEWLINE entry_str += _print_field("author", self.authors)NEWLINE entry_str += _print_field("booktitle", self.booktitle, capitals=True)NEWLINE entry_str += _print_field("journal", self.journal, capitals=True)NEWLINE entry_str += _print_field("number", self.number)NEWLINE entry_str += _print_field("title", self.title)NEWLINE entry_str += _print_field("volume", self.volume)NEWLINE entry_str += _print_field("year", self.year)NEWLINENEWLINE if not self.compressed:NEWLINE entry_str += _print_field("address", self.address)NEWLINE entry_str += _print_field("annote", self.annote)NEWLINE entry_str += _print_field("chapter", self.chapter)NEWLINE entry_str += _print_field("crossref", self.crossref)NEWLINE entry_str += _print_field("edition", self.edition)NEWLINE entry_str += _print_field("editor", self.editors)NEWLINE entry_str += _print_field("howpublished", self.howpublished)NEWLINE entry_str += _print_field("institution", self.institution)NEWLINE entry_str += _print_field("key", self.key)NEWLINE entry_str += _print_field("month", self.month)NEWLINE entry_str += _print_field("note", self.note)NEWLINE entry_str += _print_field("organization", self.organization)NEWLINE entry_str += _print_field("pages", self.pages)NEWLINE entry_str += _print_field("publisher", self.publisher)NEWLINE entry_str += _print_field("school", self.school)NEWLINE entry_str += _print_field("series", self.series)NEWLINE entry_str += _print_field("type", self.type)NEWLINE entry_str += _print_field("url", self.url)NEWLINE entry_str += _print_field("doi", self.doi)NEWLINENEWLINE entry_str += "}\n\n"NEWLINE return entry_strNEWLINENEWLINE def __repr__(self):NEWLINE return self.__str__NEWLINENEWLINENEWLINEclass Authors:NEWLINE def __init__(self, authors_list=None):NEWLINE """NEWLINENEWLINE :param authors_list: list of authors namesNEWLINE """NEWLINE self.authors = []NEWLINE if authors_list:NEWLINE authors_list = authors_list.replace(" AND ", " and ")NEWLINE for author in authors_list.split(" and "):NEWLINE self.authors.append(Author(author.strip()))NEWLINENEWLINE def merge(self, merge_authors):NEWLINE max_len = min(len(merge_authors), len(self.authors))NEWLINE for i in range(0, max_len):NEWLINE self.authors[i].merge(merge_authors[i])NEWLINE if len(merge_authors) > len(self.authors):NEWLINE for i in range(max_len, len(merge_authors)):NEWLINE self.authors.append(merge_authors[i])NEWLINENEWLINE def __str__(self):NEWLINE authors = ""NEWLINE for author in self.authors:NEWLINE if len(authors) > 0:NEWLINE authors += " and "NEWLINE authors += author.__str__()NEWLINE return authorsNEWLINENEWLINE def __repr__(self):NEWLINE return self.__str__NEWLINENEWLINE def __len__(self):NEWLINE return len(self.authors)NEWLINENEWLINENEWLINEclass Author:NEWLINE def __init__(self, author_name):NEWLINE """NEWLINE Create an author object with first and last names.NEWLINE :param author_name: name of a single authorNEWLINE """NEWLINE self.first_name = ""NEWLINE self.last_name = ""NEWLINENEWLINE if "," in author_name:NEWLINE s = author_name.split(",")NEWLINE self.first_name = s[1].strip()NEWLINE self.last_name = s[0].strip()NEWLINE else:NEWLINE s = author_name.split(" ")NEWLINE if len(s) == 2:NEWLINE self.first_name = s[0].strip()NEWLINE self.last_name = s[1].strip()NEWLINE elif len(s) > 2:NEWLINE index = len(s) - 1NEWLINE value = s[len(s) - 2]NEWLINE if len(value) <= 2 and not value.endswith('.'):NEWLINE self.last_name = value + " " + s[len(s) - 1]NEWLINE index -= 1NEWLINE else:NEWLINE self.last_name = s[len(s) - 1]NEWLINE for i in range(0, index):NEWLINE if len(self.first_name) > 0:NEWLINE self.first_name += " "NEWLINE self.first_name += s[i]NEWLINE else:NEWLINE self.first_name = author_nameNEWLINE self.last_name = NoneNEWLINE if not author_name.lower() == "others":NEWLINE log.warning("Unable to find last name: %s" % author_name)NEWLINENEWLINE if self.first_name and self.last_name:NEWLINE self._remove_duplicated_names()NEWLINENEWLINE def merge(self, author_merge):NEWLINE """NEWLINE Merge author's first and last names with another similar entry.NEWLINE :param author_merge: author names to be mergedNEWLINE """NEWLINE if not self.last_name and author_merge.last_name:NEWLINE self.last_name = author_merge.last_nameNEWLINE if self.first_name.lower() == "others":NEWLINE self.first_name = author_merge.first_nameNEWLINENEWLINE elif author_merge.last_name and is_similar(self.last_name, author_merge.last_name, threshold=0.5):NEWLINE if len(author_merge.last_name) > len(self.last_name):NEWLINE self.last_name = author_merge.last_nameNEWLINE if len(author_merge.first_name) > len(self.first_name):NEWLINE self.first_name = author_merge.first_nameNEWLINENEWLINE self._remove_duplicated_names()NEWLINENEWLINE def _remove_duplicated_names(self):NEWLINE """NEWLINE Look for duplicated names in authors and remove them (Bug #13).NEWLINE """NEWLINE given_names = self.first_name.split(" ")NEWLINE last_names = self.last_name.split(" ")NEWLINE change = FalseNEWLINENEWLINE if len(given_names) > 0 and len(last_names) > 1:NEWLINE for name in given_names[1:]:NEWLINE if "." not in name and name in self.last_name:NEWLINE self.first_name = self.first_name.replace(name, "")NEWLINENEWLINE if len(last_names) > 0 and len(given_names) == 1:NEWLINE if given_names[0] in last_names:NEWLINE change = TrueNEWLINE self.last_name = self.last_name.replace(given_names[0], "")NEWLINENEWLINE def __str__(self):NEWLINE if self.last_name:NEWLINE return self.last_name + ", " + self.first_nameNEWLINE else:NEWLINE return self.first_nameNEWLINENEWLINE def __repr__(self):NEWLINE return self.__str__NEWLINENEWLINENEWLINEdef _parse_pages(pages):NEWLINE """NEWLINE Parse the page number to a 2-dashes format (e.g. 100--120).NEWLINE :param pages: entry page numbersNEWLINE :return:NEWLINE """NEWLINE if pages:NEWLINE if "-" in pages:NEWLINE if not pages.count("-") == 2:NEWLINE pages = re.sub("-+", "--", pages)NEWLINE return pagesNEWLINE return NoneNEWLINENEWLINENEWLINEdef _parse_booktitle(booktitle):NEWLINE """NEWLINENEWLINE :param booktitle: entry book titleNEWLINE """NEWLINE if booktitle:NEWLINE if "," in booktitle:NEWLINE bt = booktitle.split(",")NEWLINE booktitle = bt[1].strip() + " " + bt[0].strip()NEWLINE return booktitleNEWLINE return NoneNEWLINENEWLINENEWLINEdef _print_field(field_name, field_value, capitals=False):NEWLINE """NEWLINE Print a field in bib format if value is not none.NEWLINE :param field_name: name of the fieldNEWLINE :param field_value: value of the fieldNEWLINE :param capitals: whether to addNEWLINE :return: field in bib format or blank if field is NoneNEWLINE """NEWLINE if field_value:NEWLINE field_value = str(field_value).replace("_", "\_")NEWLINE field_value = str(field_value).replace("\\\\_", "\_")NEWLINE field_value = str(field_value).replace("#", "\#")NEWLINE field_value = str(field_value).replace("\\\\#", "\#")NEWLINE field_value = str(field_value).replace("$", "")NEWLINE if capitals:NEWLINE return "\t%s = {{%s}},\n" % (field_name, field_value)NEWLINE else:NEWLINE return "\t%s = {%s},\n" % (field_name, field_value)NEWLINE return ""NEWLINENEWLINENEWLINEdef _merge_field(f1, f2, is_int=False):NEWLINE """NEWLINE Merge field contents from two entries.NEWLINE :param f1: first fieldNEWLINE :param f2: second fieldNEWLINE :param is_int: whether the field is an integerNEWLINE :return: merged field contentsNEWLINE """NEWLINE if not f1 and not f2:NEWLINE return NoneNEWLINE if not f2 and f1 is not None:NEWLINE return f1NEWLINE if not f1 and f2 is not None:NEWLINE return f2NEWLINE if is_int:NEWLINE try:NEWLINE if int(f1) >= int(f2):NEWLINE return f1NEWLINE else:NEWLINE return f2NEWLINE except ValueError:NEWLINE passNEWLINE if len(f1) >= len(f2):NEWLINE return f1NEWLINE else:NEWLINE return f2NEWLINE return f1NEWLINENEWLINENEWLINEdef _merge_entry_type(t1, t2):NEWLINE """NEWLINE Merge entry type field from two entries according to entry type level.NEWLINE :param t1: first entry typeNEWLINE :param t2: second entry typeNEWLINE :return: merged entry typeNEWLINE """NEWLINE if t1 == EntryType.ARTICLE or t2 == EntryType.ARTICLE:NEWLINE return EntryType.ARTICLENEWLINE if t1 == EntryType.INPROCEEDINGS or t2 == EntryType.INPROCEEDINGS:NEWLINE return EntryType.INPROCEEDINGSNEWLINE if t1 == EntryType.INCOLLECTION or t2 == EntryType.INCOLLECTION:NEWLINE return EntryType.INCOLLECTIONNEWLINE if t1 == EntryType.PROCEEDINGS or t2 == EntryType.PROCEEDINGS:NEWLINE return EntryType.PROCEEDINGSNEWLINE if t1 == EntryType.BOOK or t2 == EntryType.BOOK:NEWLINE return EntryType.BOOKNEWLINE if t1 == EntryType.PHDTHESIS or t2 == EntryType.PHDTHESIS:NEWLINE return EntryType.PHDTHESISNEWLINE if t1 == EntryType.MASTERTHESIS or t2 == EntryType.MASTERTHESIS:NEWLINE return EntryType.MASTERTHESISNEWLINE if t1 == EntryType.TECHREPORT or t2 == EntryType.TECHREPORT:NEWLINE return EntryType.TECHREPORTNEWLINE return EntryType.MISCNEWLINE """NEWLINE OpenVINO DL WorkbenchNEWLINE Script to check internet connectionNEWLINENEWLINE Copyright (c) 2020 Intel CorporationNEWLINENEWLINE Licensed under the Apache License, Version 2.0 (the "License");NEWLINE you may not use this file except in compliance with the License.NEWLINE You may obtain a copy of the License atNEWLINE http://www.apache.org/licenses/LICENSE-2.0NEWLINE Unless required by applicable law or agreed to in writing, softwareNEWLINE distributed under the License is distributed on an "AS IS" BASIS,NEWLINE WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE See the License for the specific language governing permissions andNEWLINE limitations under the License.NEWLINE"""NEWLINEfrom cpuinfo import get_cpu_infoNEWLINEfrom psutil import cpu_count, cpu_freqNEWLINENEWLINEif __name__ == '__main__':NEWLINE FULL_CPU_NAME = get_cpu_info()['brand_raw']NEWLINE print(f'Full CPU name is {FULL_CPU_NAME}')NEWLINE print(f'CPU cores number: {cpu_count(logical=False)}')NEWLINE CPU_FREQUENCY_RANGE = cpu_freq(percpu=False)NEWLINE CPU_FREQUENCY_UNITS = 'GHz'NEWLINE MHZ_IN_GHZ = 1000NEWLINE if CPU_FREQUENCY_RANGE.min == CPU_FREQUENCY_RANGE.max:NEWLINE CPU_FREQUENCY = '{:.1f} {units}'.format(CPU_FREQUENCY_RANGE.min / MHZ_IN_GHZ, units=CPU_FREQUENCY_UNITS)NEWLINE else:NEWLINE CPU_FREQUENCY = '{:.1f}-{:.1f} {units}'.format(CPU_FREQUENCY_RANGE.min / MHZ_IN_GHZ,NEWLINE CPU_FREQUENCY_RANGE.max / MHZ_IN_GHZ, units=CPU_FREQUENCY_UNITS)NEWLINE print(f'CPU frequency range: {CPU_FREQUENCY}')NEWLINE import pandas as pdNEWLINEfrom sklearn.metrics import mean_squared_errorNEWLINEfrom sklearn.model_selection import train_test_splitNEWLINEfrom sklearn.preprocessing import LabelEncoderNEWLINENEWLINEfrom deepctr.models import DeepFMNEWLINEfrom deepctr.feature_column import SparseFeat,get_feature_namesNEWLINENEWLINEif __name__ == "__main__":NEWLINENEWLINE data = pd.read_csv("./movielens_sample.txt")NEWLINE sparse_features = ["movie_id", "user_id",NEWLINE "gender", "age", "occupation", "zip"]NEWLINE target = ['rating']NEWLINENEWLINE # 1.Label Encoding for sparse features,and do simple Transformation for dense featuresNEWLINE for feat in sparse_features:NEWLINE lbe = LabelEncoder()NEWLINE data[feat] = lbe.fit_transform(data[feat])NEWLINE # 2.count #unique features for each sparse fieldNEWLINE fixlen_feature_columns = [SparseFeat(feat, data[feat].nunique(),embedding_dim=4)NEWLINE for feat in sparse_features]NEWLINE linear_feature_columns = fixlen_feature_columnsNEWLINE dnn_feature_columns = fixlen_feature_columnsNEWLINE feature_names = get_feature_names(linear_feature_columns + dnn_feature_columns)NEWLINENEWLINE # 3.generate input data for modelNEWLINE train, test = train_test_split(data, test_size=0.2)NEWLINE train_model_input = {name:train[name].values for name in feature_names}NEWLINE test_model_input = {name:test[name].values for name in feature_names}NEWLINENEWLINE # 4.Define Model,train,predict and evaluateNEWLINE model = DeepFM(linear_feature_columns, dnn_feature_columns, task='regression')NEWLINE model.compile("adam", "mse", metrics=['mse'], )NEWLINENEWLINE history = model.fit(train_model_input, train[target].values,NEWLINE batch_size=256, epochs=10, verbose=2, validation_split=0.2, )NEWLINE pred_ans = model.predict(test_model_input, batch_size=256)NEWLINE print("test MSE", round(mean_squared_error(NEWLINE test[target].values, pred_ans), 4))NEWLINE """NEWLINENEWLINE208. Implement Trie (Prefix Tree)NEWLINEMediumNEWLINENEWLINE5115NEWLINENEWLINE77NEWLINENEWLINEAdd to ListNEWLINENEWLINEShareNEWLINEA trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.NEWLINENEWLINEImplement the Trie class:NEWLINENEWLINETrie() Initializes the trie object.NEWLINEvoid insert(String word) Inserts the string word into the trie.NEWLINEboolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.NEWLINEboolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.NEWLINE NEWLINENEWLINEExample 1:NEWLINENEWLINEInputNEWLINE["Trie", "insert", "search", "search", "startsWith", "insert", "search"]NEWLINE[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]NEWLINEOutputNEWLINE[null, null, true, false, true, null, true]NEWLINENEWLINEExplanationNEWLINETrie trie = new Trie();NEWLINEtrie.insert("apple");NEWLINEtrie.search("apple"); // return TrueNEWLINEtrie.search("app"); // return FalseNEWLINEtrie.startsWith("app"); // return TrueNEWLINEtrie.insert("app");NEWLINEtrie.search("app"); // return TrueNEWLINE NEWLINENEWLINEConstraints:NEWLINENEWLINE1 <= word.length, prefix.length <= 2000NEWLINEword and prefix consist only of lowercase English letters.NEWLINEAt most 3 * 104 calls in total will be made to insert, search, and startsWith.NEWLINENEWLINE"""NEWLINENEWLINE# V0NEWLINE# IDEA : USE dict AS data structure (# TrieNode: is dict, or hashmap)NEWLINEclass Trie(object): NEWLINE def __init__(self):NEWLINE self.root = {} # TrieNode: is dict, or hashmap NEWLINE NEWLINE def insert(self, word):NEWLINE p = self.rootNEWLINE for c in word: NEWLINE if c not in p: NEWLINE p[c] = {}NEWLINE ### NOTE THISNEWLINE p = p[c]NEWLINE ### NOTE HERENEWLINE p['#'] = True # ‘#’ is a key indicating word boundayNEWLINE NEWLINE def search(self, word):NEWLINE node = self.find(word)NEWLINE return node is not None and '#' in node # NOTE NEWLINE NEWLINE def startsWith(self, prefix):NEWLINE return self.find(prefix) is not None # NOTE NEWLINE NEWLINE ### NOTE : remember to implement this help fuuncNEWLINE def find(self, prefix):NEWLINE p = self.rootNEWLINE for c in prefix: NEWLINE if c not in p: NEWLINE return NoneNEWLINE # for validating if "search to the end" (check '#' in the node or not) NEWLINE p = p[c]NEWLINE return pNEWLINENEWLINE# V1NEWLINE# IDEA : USE dict AS data structure (# TrieNode: is dict, or hashmap)NEWLINE# https://leetcode.com/problems/implement-trie-prefix-tree/discuss/633007/25-lines-python-use-50-less-code-than-c%2B%2B-should-I-change-to-pythonNEWLINEclass Trie(object): NEWLINE def __init__(self):NEWLINE self.root = {} # TrieNode: is dict, or hashmap NEWLINE NEWLINE def insert(self, word):NEWLINE p = self.rootNEWLINE for c in word: NEWLINE if c not in p: NEWLINE p[c] = {}NEWLINE p = p[c]NEWLINE ### NOTE HERENEWLINE p['#'] = True # ‘#’ is a key indicating word boundayNEWLINE NEWLINE def search(self, word):NEWLINE node = self.find(word)NEWLINE return node is not None and '#' in node # NOTE NEWLINE NEWLINE def startsWith(self, prefix):NEWLINE return self.find(prefix) is not None # NOTE NEWLINE NEWLINE def find(self, prefix):NEWLINE p = self.rootNEWLINE for c in prefix: NEWLINE if c not in p: NEWLINE return NoneNEWLINE p = p[c]NEWLINE return pNEWLINENEWLINE# V1 NEWLINE# https://blog.csdn.net/fuxuemingzhu/article/details/79388432NEWLINEclass Node(object):NEWLINE def __init__(self):NEWLINE self.children = collections.defaultdict(Node)NEWLINE self.isword = FalseNEWLINE NEWLINEclass Trie(object):NEWLINENEWLINE def __init__(self):NEWLINE """NEWLINE Initialize your data structure here.NEWLINE """NEWLINE self.root = Node()NEWLINENEWLINE def insert(self, word):NEWLINE """NEWLINE Inserts a word into the trie.NEWLINE :type word: strNEWLINE :rtype: voidNEWLINE """NEWLINE current = self.rootNEWLINE for w in word:NEWLINE current = current.children[w]NEWLINE current.isword = TrueNEWLINENEWLINE def search(self, word):NEWLINE """NEWLINE Returns if the word is in the trie.NEWLINE :type word: strNEWLINE :rtype: boolNEWLINE """NEWLINE current = self.rootNEWLINE for w in word:NEWLINE current = current.children.get(w)NEWLINE if current == None:NEWLINE return FalseNEWLINE return current.iswordNEWLINENEWLINE def startsWith(self, prefix):NEWLINE """NEWLINE Returns if there is any word in the trie that starts with the given prefix.NEWLINE :type prefix: strNEWLINE :rtype: boolNEWLINE """NEWLINE current = self.rootNEWLINE for w in prefix:NEWLINE current = current.children.get(w)NEWLINE if current == None:NEWLINE return FalseNEWLINE return True NEWLINENEWLINENEWLINE# Your Trie object will be instantiated and called as such:NEWLINE# obj = Trie()NEWLINE# obj.insert(word)NEWLINE# param_2 = obj.search(word)NEWLINE# param_3 = obj.startsWith(prefix)NEWLINENEWLINE# V1'NEWLINE# https://www.jiuzhang.com/solution/implement-trie-prefix-tree/#tag-highlight-lang-pythonNEWLINEclass TrieNode:NEWLINE NEWLINE def __init__(self):NEWLINE self.children = {}NEWLINE self.is_word = FalseNEWLINE NEWLINE NEWLINEclass Trie:NEWLINE NEWLINE def __init__(self):NEWLINE self.root = TrieNode()NEWLINENEWLINE """NEWLINE @param: word: a wordNEWLINE @return: nothingNEWLINE """NEWLINE def insert(self, word):NEWLINE node = self.rootNEWLINE for c in word:NEWLINE if c not in node.children:NEWLINE node.children[c] = TrieNode()NEWLINE node = node.children[c]NEWLINE NEWLINE node.is_word = TrueNEWLINENEWLINE """NEWLINE return the node in the trie if exists NEWLINE """NEWLINE def find(self, word):NEWLINE node = self.rootNEWLINE for c in word:NEWLINE node = node.children.get(c)NEWLINE if node is None:NEWLINE return NoneNEWLINE return nodeNEWLINE NEWLINE """NEWLINE @param: word: A stringNEWLINE @return: if the word is in the trie.NEWLINE """NEWLINE def search(self, word):NEWLINE node = self.find(word)NEWLINE return node is not None and node.is_wordNEWLINENEWLINE """NEWLINE @param: prefix: A stringNEWLINE @return: if there is any word in the trie that starts with the given prefix.NEWLINE """NEWLINE def startsWith(self, prefix):NEWLINE return self.find(prefix) is not NoneNEWLINENEWLINE# V1''NEWLINE# https://www.jiuzhang.com/solution/implement-trie-prefix-tree/#tag-highlight-lang-pythonNEWLINEclass TrieNode:NEWLINE NEWLINE def __init__(self):NEWLINE self.children = {}NEWLINE self.is_word = FalseNEWLINE NEWLINE NEWLINEclass Trie:NEWLINE NEWLINE def __init__(self):NEWLINE self.root = TrieNode()NEWLINENEWLINE """NEWLINE @param: word: a wordNEWLINE @return: nothingNEWLINE """NEWLINE def insert(self, word):NEWLINE node = self.rootNEWLINE for c in word:NEWLINE if c not in node.children:NEWLINE node.children[c] = TrieNode()NEWLINE node = node.children[c]NEWLINE NEWLINE node.is_word = TrueNEWLINENEWLINE """NEWLINE return the node in the trie if exists NEWLINE """NEWLINE def find(self, word):NEWLINE node = self.rootNEWLINE for c in word:NEWLINE node = node.children.get(c)NEWLINE if node is None:NEWLINE return NoneNEWLINE return nodeNEWLINE NEWLINE """NEWLINE @param: word: A stringNEWLINE @return: if the word is in the trie.NEWLINE """NEWLINE def search(self, word):NEWLINE node = self.find(word)NEWLINE return node is not None and node.is_wordNEWLINENEWLINE """NEWLINE @param: prefix: A stringNEWLINE @return: if there is any word in the trie that starts with the given prefix.NEWLINE """NEWLINE def startsWith(self, prefix):NEWLINE return self.find(prefix) is not NoneNEWLINENEWLINE# V2 NEWLINE# Time: O(n), per operationNEWLINE# Space: O(1)NEWLINEclass TrieNode(object):NEWLINE # Initialize your data structure here.NEWLINE def __init__(self):NEWLINE self.is_string = FalseNEWLINE self.leaves = {}NEWLINENEWLINEclass Trie(object):NEWLINENEWLINE def __init__(self):NEWLINE self.root = TrieNode()NEWLINENEWLINE # @param {string} wordNEWLINE # @return {void}NEWLINE # Inserts a word into the trie.NEWLINE def insert(self, word):NEWLINE cur = self.rootNEWLINE for c in word:NEWLINE if not c in cur.leaves:NEWLINE cur.leaves[c] = TrieNode()NEWLINE cur = cur.leaves[c]NEWLINE cur.is_string = TrueNEWLINENEWLINE # @param {string} wordNEWLINE # @return {boolean}NEWLINE # Returns if the word is in the trie.NEWLINE def search(self, word):NEWLINE node = self.childSearch(word)NEWLINE if node:NEWLINE return node.is_stringNEWLINE return FalseNEWLINENEWLINE # @param {string} prefixNEWLINE # @return {boolean}NEWLINE # Returns if there is any word in the trieNEWLINE # that starts with the given prefix.NEWLINE def startsWith(self, prefix):NEWLINE return self.childSearch(prefix) is not NoneNEWLINENEWLINE def childSearch(self, word):NEWLINE cur = self.rootNEWLINE for c in word:NEWLINE if c in cur.leaves:NEWLINE cur = cur.leaves[c]NEWLINE else:NEWLINE return NoneNEWLINE return cur # NEED THIS INIT FOR PYTEST --COV TO GENERATE A PROPER REPORTNEWLINENEWLINENEWLINE# Found the answer:NEWLINE#NEWLINE# DO NOT put a __init__.py file in a folder containing TESTS ifNEWLINE# you plan on using pytest. I had one such file, deleting itNEWLINE# solved the problem.NEWLINE#NEWLINE# This was actually buried in the comments to the secondNEWLINE# answer of PATH issue with pytestNEWLINE# 'ImportError: No module named YadaYadaYada' so I didNEWLINE# not see it, hope it gets more visibility here.NEWLINENEWLINE#https://stackoverflow.com/questions/41748464/pytest-cannot-import-module-while-python-canNEWLINE import numpy as npNEWLINEimport torchNEWLINEimport torch.nn as nnNEWLINENEWLINEfrom mmcv.cnn import constant_init, normal_initNEWLINEfrom mmdet.models.anchor_heads.ssd_head import SSDHeadNEWLINEfrom mmdet.models.registry import HEADSNEWLINENEWLINEfrom .operations import conv_dw_headNEWLINENEWLINENEWLINE@HEADS.register_moduleNEWLINEclass SSDLightHead(SSDHead):NEWLINENEWLINE def __init__(self,NEWLINE input_size=300,NEWLINE num_classes=81,NEWLINE in_channels=(512, 1024, 512, 256, 256, 256),NEWLINE anchor_strides=(8, 16, 32, 64, 100, 300),NEWLINE basesize_ratio_range=(0.1, 0.9),NEWLINE anchor_ratios=([2], [2, 3], [2, 3], [2, 3], [2], [2]),NEWLINE target_means=(.0, .0, .0, .0),NEWLINE target_stds=(1.0, 1.0, 1.0, 1.0),NEWLINE search=False):NEWLINE super(SSDLightHead, self).__init__(input_size, num_classes, in_channels, NEWLINE anchor_strides, basesize_ratio_range, anchor_ratios,NEWLINE target_means, target_stds)NEWLINE self.search = searchNEWLINE num_anchors = [len(ratios) * 2 + 2 for ratios in anchor_ratios]NEWLINE reg_convs = []NEWLINE cls_convs = []NEWLINE for i in range(len(in_channels)):NEWLINE reg_convs.append(NEWLINE conv_dw_head(in_channels[i], num_anchors[i] * 4)NEWLINE )NEWLINE cls_convs.append(NEWLINE conv_dw_head(in_channels[i], num_anchors[i] * num_classes)NEWLINE )NEWLINE self.reg_convs = nn.ModuleList(reg_convs)NEWLINE self.cls_convs = nn.ModuleList(cls_convs)NEWLINENEWLINE def init_weights(self):NEWLINE for m in self.modules():NEWLINE if isinstance(m, nn.Conv2d):NEWLINE normal_init(m, std=0.03)NEWLINE elif isinstance(m, nn.BatchNorm2d):NEWLINE constant_init(m, 1)NEWLINENEWLINE def forward(self, feats):NEWLINE if self.search:NEWLINE feats, net_sub_obj = featsNEWLINE cls_scores = []NEWLINE bbox_preds = []NEWLINE for feat, reg_conv, cls_conv in zip(feats, self.reg_convs,NEWLINE self.cls_convs):NEWLINE cls_scores.append(cls_conv(feat))NEWLINE bbox_preds.append(reg_conv(feat))NEWLINE if self.search:NEWLINE return (cls_scores, bbox_preds), net_sub_obj NEWLINE else:NEWLINE return cls_scores, bbox_preds # coding: utf-8NEWLINE# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) DepartmentNEWLINE# Distributed under the terms of "New BSD License", see the LICENSE file.NEWLINENEWLINEfrom __future__ import print_function, unicode_literalsNEWLINEimport numpy as npNEWLINEimport osNEWLINEfrom pyiron_base import stateNEWLINEimport mendeleevNEWLINEimport pandasNEWLINEfrom functools import lru_cacheNEWLINENEWLINE__author__ = "Joerg Neugebauer, Sudarsan Surendralal, Martin Boeckmann"NEWLINE__copyright__ = (NEWLINE "Copyright 2021, Max-Planck-Institut für Eisenforschung GmbH - "NEWLINE "Computational Materials Design (CM) Department"NEWLINE)NEWLINE__version__ = "1.0"NEWLINE__maintainer__ = "Sudarsan Surendralal"NEWLINE__email__ = "surendralal@mpie.de"NEWLINE__status__ = "production"NEWLINE__date__ = "Sep 1, 2017"NEWLINENEWLINEpandas.options.mode.chained_assignment = NoneNEWLINENEWLINENEWLINE@lru_cache(maxsize=118)NEWLINEdef element(*args):NEWLINE return mendeleev.element(*args)NEWLINENEWLINENEWLINEclass ChemicalElement(object):NEWLINE """NEWLINE An Object which contains the element specific parametersNEWLINE """NEWLINENEWLINE def __init__(self, sub):NEWLINE """NEWLINE Constructor: assign PSE dictionary to objectNEWLINE """NEWLINE self._dataset = NoneNEWLINE self.sub = subNEWLINE self._mendeleev_element = NoneNEWLINE self._mendeleev_property_lst = NoneNEWLINE stringtypes = strNEWLINE if isinstance(self.sub, stringtypes):NEWLINE self._init_mendeleev(self.sub)NEWLINE elif "Parent" in self.sub.index and isinstance(self.sub.Parent, stringtypes):NEWLINE self._init_mendeleev(self.sub.Parent)NEWLINE elif len(self.sub) > 0:NEWLINE self._init_mendeleev(self.sub.Abbreviation)NEWLINENEWLINE self._mendeleev_translation_dict = {NEWLINE "AtomicNumber": "atomic_number",NEWLINE "AtomicRadius": "covalent_radius_cordero",NEWLINE "AtomicMass": "mass",NEWLINE "Color": "cpk_color",NEWLINE "CovalentRadius": "covalent_radius",NEWLINE "CrystalStructure": "lattice_structure",NEWLINE "Density": "density",NEWLINE "DiscoveryYear": "discovery_year",NEWLINE "ElectronAffinity": "electron_affinity",NEWLINE "Electronegativity": "electronegativity",NEWLINE "Group": "group_id",NEWLINE "Name": "name",NEWLINE "Period": "period",NEWLINE "StandardName": "name",NEWLINE "VanDerWaalsRadius": "vdw_radius",NEWLINE "MeltingPoint": "melting_point",NEWLINE }NEWLINE self.el = NoneNEWLINENEWLINE def _init_mendeleev(self, element_str):NEWLINE self._mendeleev_element = element(str(element_str))NEWLINE self._mendeleev_property_lst = [NEWLINE s for s in dir(self._mendeleev_element) if not s.startswith("_")NEWLINE ]NEWLINENEWLINE def __getattr__(self, item):NEWLINE if item in ["__array_struct__", "__array_interface__", "__array__"]:NEWLINE raise AttributeErrorNEWLINE return self[item]NEWLINENEWLINE def __getitem__(self, item):NEWLINE if item in self._mendeleev_translation_dict.keys():NEWLINE item = self._mendeleev_translation_dict[item]NEWLINE if item in self._mendeleev_property_lst:NEWLINE return getattr(self._mendeleev_element, item)NEWLINE if item in self.sub.index:NEWLINE return self.sub[item]NEWLINENEWLINE def __eq__(self, other):NEWLINE if isinstance(other, self.__class__):NEWLINE conditions = list()NEWLINE conditions.append(self.sub.to_dict() == other.sub.to_dict())NEWLINE return all(conditions)NEWLINE elif isinstance(other, (np.ndarray, list)):NEWLINE conditions = list()NEWLINE for sp in other:NEWLINE conditions.append(self.sub.to_dict() == sp.sub.to_dict())NEWLINE return any(conditions)NEWLINENEWLINE def __ne__(self, other):NEWLINE return not self.__eq__(other)NEWLINENEWLINE def __gt__(self, other):NEWLINE if self != other:NEWLINE if self["AtomicNumber"] != other["AtomicNumber"]:NEWLINE return self["AtomicNumber"] > other["AtomicNumber"]NEWLINE else:NEWLINE return self["Abbreviation"] > other["Abbreviation"]NEWLINE else:NEWLINE return FalseNEWLINENEWLINE def __ge__(self, other):NEWLINE if self != other:NEWLINE return self > otherNEWLINE else:NEWLINE return TrueNEWLINENEWLINE def __hash__(self):NEWLINE return hash(repr(self))NEWLINENEWLINE @propertyNEWLINE def tags(self):NEWLINE if "tags" not in self.sub.keys() or self.sub["tags"] is None:NEWLINE return dict()NEWLINE return self.sub["tags"]NEWLINENEWLINE def __dir__(self):NEWLINE return list(self.sub.index) + super(ChemicalElement, self).__dir__()NEWLINENEWLINE def __str__(self):NEWLINE return str([self._dataset, self.sub])NEWLINENEWLINE def add_tags(self, tag_dic):NEWLINE """NEWLINE Add tags to an existing element inside its specific panda series without overwriting the old tagsNEWLINENEWLINE Args:NEWLINE tag_dic (dict): dictionary containing e.g. key = "spin" value = "up",NEWLINE more than one tag can be added at onceNEWLINENEWLINE """NEWLINE (self.sub["tags"]).update(tag_dic)NEWLINENEWLINE def to_hdf(self, hdf):NEWLINE """NEWLINE saves the element with his parameters into his hdf5 job fileNEWLINE Args:NEWLINE hdf (Hdfio): Hdfio object which will be usedNEWLINE """NEWLINE with hdf.open(self.Abbreviation) as hdf_el: # "Symbol of the chemical element"NEWLINE # TODO: save all parameters that are different from the parent (e.g. modified mass)NEWLINE if self.Parent is not None:NEWLINE self._dataset = {"Parameter": ["Parent"], "Value": [self.Parent]}NEWLINE hdf_el["elementData"] = self._datasetNEWLINE with hdf_el.open(NEWLINE "tagData"NEWLINE ) as hdf_tag: # "Dictionary of element tag static"NEWLINE for key in self.tags.keys():NEWLINE hdf_tag[key] = self.tags[key]NEWLINENEWLINE def from_hdf(self, hdf):NEWLINE """NEWLINE loads an element with his parameters from the hdf5 job file and store it into its specific pandas seriesNEWLINE Args:NEWLINE hdf (Hdfio): Hdfio object which will be used to read a hdf5 fileNEWLINE """NEWLINE pse = PeriodicTable()NEWLINE elname = self.sub.nameNEWLINE with hdf.open(elname) as hdf_el:NEWLINE if "elementData" in hdf_el.list_nodes():NEWLINE element_data = hdf_el["elementData"]NEWLINE for key, val in zip(element_data["Parameter"], element_data["Value"]):NEWLINE if key in "Parent":NEWLINE self.sub = pse.dataframe.loc[val]NEWLINE self.sub["Parent"] = valNEWLINE self._init_mendeleev(val)NEWLINE else:NEWLINE self.sub["Parent"] = NoneNEWLINE self._init_mendeleev(elname)NEWLINE self.sub.name = elnameNEWLINE if "tagData" in hdf_el.list_groups():NEWLINE with hdf_el.open(NEWLINE "tagData"NEWLINE ) as hdf_tag: # "Dictionary of element tag static"NEWLINE tag_dic = {}NEWLINE for key in hdf_tag.list_nodes():NEWLINE tag_dic[key] = hdf_tag[key]NEWLINE self.sub["tags"] = tag_dicNEWLINENEWLINENEWLINEclass PeriodicTable(object):NEWLINE """NEWLINE An Object which stores an elementary table which can be modified for the current sessionNEWLINE """NEWLINENEWLINE def __init__(self, file_name=None): # PSE_dat_file = None):NEWLINE """NEWLINENEWLINE Args:NEWLINE file_name (str): Possibility to choose an source hdf5 fileNEWLINE """NEWLINE self.dataframe = self._get_periodic_table_df(file_name)NEWLINE if "Abbreviation" not in self.dataframe.columns.values:NEWLINE self.dataframe["Abbreviation"] = NoneNEWLINE if not all(self.dataframe["Abbreviation"].values):NEWLINE for item in self.dataframe.index.values:NEWLINE if self.dataframe["Abbreviation"][item] is None:NEWLINE self.dataframe["Abbreviation"][item] = itemNEWLINE self._parent_element = NoneNEWLINE self.el = NoneNEWLINENEWLINE def __getattr__(self, item):NEWLINE return self[item]NEWLINENEWLINE def __getitem__(self, item):NEWLINE if item in self.dataframe.columns.values:NEWLINE return self.dataframe[item]NEWLINE if item in self.dataframe.index.values:NEWLINE return self.dataframe.loc[item]NEWLINENEWLINE def from_hdf(self, hdf):NEWLINE """NEWLINE loads an element with his parameters from the hdf5 job file by creating an Object of the ChemicalElement type.NEWLINE The new element will be stored in the current periodic table.NEWLINE Changes in the tags will also be modified inside the periodic table.NEWLINENEWLINE Args:NEWLINE hdf (Hdfio): Hdfio object which will be used to read the data from a hdf5 fileNEWLINENEWLINE Returns:NEWLINENEWLINE """NEWLINE elements = hdf.list_groups() # ["elements"]NEWLINE for el in elements:NEWLINE sub = pandas.Series(dtype=object)NEWLINE new_element = ChemicalElement(sub)NEWLINE new_element.sub.name = elNEWLINE new_element.from_hdf(hdf)NEWLINE new_element.sub["Abbreviation"] = elNEWLINENEWLINE if "sub_tags" in new_element.tags:NEWLINE if not new_element.tags["sub_tags"]:NEWLINE del new_element.tags["sub_tags"]NEWLINENEWLINE if new_element.Parent is None:NEWLINE if not (el in self.dataframe.index.values):NEWLINE raise AssertionError()NEWLINE if len(new_element.sub["tags"]) > 0:NEWLINE raise ValueError("Element cannot get tag-assignment twice")NEWLINE if "tags" not in self.dataframe.keys():NEWLINE self.dataframe["tags"] = NoneNEWLINE self.dataframe["tags"][el] = new_element.tagsNEWLINE else:NEWLINE self.dataframe = pandas.concat(NEWLINE [self.dataframe, new_element.sub.to_frame().T]NEWLINE )NEWLINE self.dataframe["tags"] = self.dataframe["tags"].apply(NEWLINE lambda x: None if pandas.isnull(x) else xNEWLINE )NEWLINE self.dataframe["Parent"] = self.dataframe["Parent"].apply(NEWLINE lambda x: None if pandas.isnull(x) else xNEWLINE )NEWLINENEWLINE def element(self, arg, **qwargs):NEWLINE """NEWLINE The method searches through the periodic table. If the table contains the element,NEWLINE it will return an Object of the type ChemicalElement containing all parameters from the periodic table.NEWLINE The option **qwargs allows a direct modification of the tag-values during the creation processNEWLINE Args:NEWLINE arg (str, ChemicalElement): sort of elementNEWLINE **qwargs: e.g. a dictionary of tagsNEWLINENEWLINE Returns element (ChemicalElement): a element with all its properties (Abbreviation, AtomicMass, Weight, ...)NEWLINENEWLINE """NEWLINE stringtypes = strNEWLINE if isinstance(arg, stringtypes):NEWLINE if arg in self.dataframe.index.values:NEWLINE self.el = argNEWLINE else:NEWLINE raise KeyError(arg)NEWLINE elif isinstance(arg, int):NEWLINENEWLINE if arg in list(self.dataframe["AtomicNumber"]):NEWLINE index = list(self.dataframe["AtomicNumber"]).index(arg)NEWLINE self.el = self.dataframe.iloc[index].nameNEWLINE else:NEWLINE raise ValueError("type not defined: " + str(type(arg)))NEWLINE if len(qwargs.values()) > 0:NEWLINE if "tags" not in self.dataframe.columns.values:NEWLINE self.dataframe["tags"] = NoneNEWLINE self.dataframe["tags"][self.el] = qwargsNEWLINE element = self.dataframe.loc[self.el]NEWLINE # element['CovalentRadius'] /= 100NEWLINE return ChemicalElement(element)NEWLINENEWLINE def is_element(self, symbol):NEWLINE """NEWLINE Compares the Symbol with the Abbreviations of elements inside the periodic tableNEWLINE Args:NEWLINE symbol (str): name of element, strNEWLINENEWLINE Returns boolean: true for the same element, false otherwiseNEWLINENEWLINE """NEWLINE return symbol in self.dataframe["Abbreviation"]NEWLINENEWLINE def atomic_number_to_abbreviation(self, atom_no):NEWLINE """NEWLINENEWLINE Args:NEWLINE atom_no:NEWLINENEWLINE Returns:NEWLINENEWLINE """NEWLINE if not isinstance(atom_no, int):NEWLINE raise ValueError("type not defined: " + str(type(atom_no)))NEWLINENEWLINE return self.Abbreviation[NEWLINE np.nonzero(self.AtomicNumber.to_numpy() == atom_no)[0][0]NEWLINE ]NEWLINENEWLINE def add_element(NEWLINE self, parent_element, new_element, use_parent_potential=False, **qwargsNEWLINE ):NEWLINE """NEWLINE Add "additional" chemical elements to the Periodic Table. These can be used to distinguish between the variousNEWLINE potentials which may exist for a given species or to introduce artificial elements such as pseudohydrogen. ForNEWLINE this case set use_parent_potential = False and add in the directory containing the potential files a new fileNEWLINE which is derived from the name new element.NEWLINENEWLINE This function may be also used to provide additional information for the identical chemical element, e.g., toNEWLINE define a Fe_up and Fe_down to perform the correct symmetry search as well as initialization.NEWLINENEWLINE Args:NEWLINE parent_element (str): name of parent elementNEWLINE new_element (str): name of new elementNEWLINE use_parent_potential: True: use the potential from the parent speciesNEWLINE **qwargs: define tags and their values, e.g. spin = "up", relax = [True, True, True]NEWLINENEWLINE Returns: new element (ChemicalElement)NEWLINENEWLINE """NEWLINENEWLINE pandas.options.mode.chained_assignment = NoneNEWLINE parent_element_data_series = self.dataframe.loc[parent_element]NEWLINE parent_element_data_series["Abbreviation"] = new_elementNEWLINE parent_element_data_series["Parent"] = parent_elementNEWLINE parent_element_data_series.name = new_elementNEWLINE if new_element not in self.dataframe.T.columns:NEWLINE self.dataframe = pandas.concat(NEWLINE [self.dataframe, parent_element_data_series.to_frame().T],NEWLINE )NEWLINE else:NEWLINE self.dataframe.loc[new_element] = parent_element_data_seriesNEWLINE if use_parent_potential:NEWLINE self._parent_element = parent_elementNEWLINE return self.element(new_element, **qwargs)NEWLINENEWLINE @staticmethodNEWLINE @lru_cache(maxsize=1)NEWLINE def _get_periodic_table_df(file_name):NEWLINE """NEWLINENEWLINE Args:NEWLINE file_name:NEWLINENEWLINE Returns:NEWLINENEWLINE """NEWLINE if not file_name:NEWLINE for resource_path in state.settings.resource_paths:NEWLINE if os.path.exists(os.path.join(resource_path, "atomistics")):NEWLINE resource_path = os.path.join(resource_path, "atomistics")NEWLINE for path, folder_lst, file_lst in os.walk(resource_path):NEWLINE for periodic_table_file_name in {"periodic_table.csv"}:NEWLINE if (NEWLINE periodic_table_file_name in file_lstNEWLINE and periodic_table_file_name.endswith(".csv")NEWLINE ):NEWLINE return pandas.read_csv(NEWLINE os.path.join(path, periodic_table_file_name),NEWLINE index_col=0,NEWLINE )NEWLINE elif (NEWLINE periodic_table_file_name in file_lstNEWLINE and periodic_table_file_name.endswith(".h5")NEWLINE ):NEWLINE return pandas.read_hdf(NEWLINE os.path.join(path, periodic_table_file_name), mode="r"NEWLINE )NEWLINE raise ValueError("Was not able to locate a periodic table. ")NEWLINE else:NEWLINE if file_name.endswith(".h5"):NEWLINE return pandas.read_hdf(file_name, mode="r")NEWLINE elif file_name.endswith(".csv"):NEWLINE return pandas.read_csv(file_name, index_col=0)NEWLINE raise TypeError(NEWLINE "PeriodicTable file format not recognised: "NEWLINE + file_nameNEWLINE + " supported file formats are csv, h5."NEWLINE )NEWLINE import osNEWLINEimport shlexNEWLINEimport subprocessNEWLINEimport reNEWLINEfrom typing import Dict, NoReturnNEWLINENEWLINEdef run_shell_command(command: str): -> NoReturnNEWLINE subprocess.run(shlex.split(command))NEWLINENEWLINENEWLINEdef get_git_info(git_repo_address: str) -> Dict:NEWLINE """Returns the various parts of the git_repo_address as a dictionary.NEWLINENEWLINE Example:NEWLINENEWLINE get_git_info(git_repo_address="https://github.com/sugatoray/colab_git_ssh")NEWLINE """NEWLINE gitpatterns = {NEWLINE "ssh": "(git)@(.*):(.*)/(.*).git", NEWLINE "https": "(https)://(.*)/(.*)/(.*)"NEWLINE }NEWLINE if git_repo_address.startswith("git@"):NEWLINE git_protocol = "ssh"NEWLINE elif git_repo_address.startswith("https://"):NEWLINE git_protocol = "https"NEWLINE if git_protocol in ["ssh", "https"]:NEWLINE parts = re.findall(gitpatterns[git_protocol], git_repo_address)[0]NEWLINE git_info = dict(NEWLINE host = parts[1],NEWLINE owner = parts[2],NEWLINE repo = parts[3],NEWLINE protocol = git_protocol,NEWLINE address = git_repo_addressNEWLINE )NEWLINE return git_infoNEWLINE else:NEWLINE raise ValueError("Non standard git_repo_address provided.")NEWLINENEWLINENEWLINEdef git_clone_repo(git_repo_address: str=None, verbose=True) -> Dict:NEWLINE """Clones a repo by the given git_repo_address. Returns the git_info as a dict.NEWLINE Supports both SSH and HTTPS protocols.NEWLINE NEWLINE Example:NEWLINENEWLINE git_clone_repo(git_repo_address="https://github.com/sugatoray/colab_git_ssh")NEWLINE """NEWLINE if git_repo_address is None:NEWLINE git_repo_address = "https://github.com/sugatoray/colab_git_ssh"NEWLINE git_info = get_git_info(git_repo_address)NEWLINE if os.path.isdir(git_info["repo"]):NEWLINE #! rm -r test_privateNEWLINE command = f'rm -r {git_info["repo"]}'NEWLINE run_shell_command(command)NEWLINE # git_repo_address examples:NEWLINE # git@github.org:/.gitNEWLINE # git@gitlab.org:/.gitNEWLINE # git@bitbucket.org:/.gitNEWLINE # ! git clone $git_repo_addressNEWLINE run_shell_command(command=f'git clone {git_repo_address}')NEWLINE NEWLINE if verbose:NEWLINE # print(f"Cloned repo: {git_repo_address} " + emoji.emojize(":fire:") * 3)NEWLINE print(f"Cloned repo: {git_repo_address} " + "🔥🔥🔥")NEWLINE return git_infoNEWLINENEWLINENEWLINEdef get_githost(host: str="github.com") -> str:NEWLINE """Returns the git host for GitHub, GitLab, BitBucket.NEWLINENEWLINE Parameters:NEWLINENEWLINE host (str): {("gh", "github", "github.com"), NEWLINE ("gl", "gitlab", "gitlab.com"), NEWLINE ("bb", "bitbucket", "bitbucket.org")}.NEWLINENEWLINE (default: "github.com")NEWLINENEWLINE Example:NEWLINENEWLINE The folloing three will return: "github.com"NEWLINE get_githost(host="gh")NEWLINE get_githost(host="github")NEWLINE get_githost(host="github.com")NEWLINENEWLINE The folloing three will return: "gitlab.com"NEWLINE get_githost(host="gl")NEWLINE get_githost(host="gitlab")NEWLINE get_githost(host="gitlab.com")NEWLINENEWLINE The folloing three will return: "bitbucket.org"NEWLINE get_githost(host="bb")NEWLINE get_githost(host="bitbucket")NEWLINE get_githost(host="bitbucket.org")NEWLINENEWLINE """NEWLINE host = host.lower() NEWLINE if any(x in host for x in ["gh", "github", "github.com"]):NEWLINE host = "github.com"NEWLINE elif any(x in host for x in ["gl", "gitlab", "gitlab.com"]):NEWLINE host = "gitlab.com"NEWLINE elif any(x in host for x in ["bb", "bitbucket", "bitbucket.org"]):NEWLINE host = "bitbucket.org" NEWLINE NEWLINE return hostNEWLINENEWLINENEWLINEdef make_git_address(repo: str="repo", owner: str="owner", host: str="github.com", protocol: str="ssh") -> str:NEWLINE """Constructs git repo address from given components.NEWLINENEWLINE Parameters:NEWLINENEWLINE repo (str): git repository name. (default: "repo")NEWLINE owner (str): git repository owner-name. (default: "owner") NEWLINE host (str): git cloud host domain. (default: "github.com")NEWLINE protocol (str): {ssh, https}. (default: "ssh")NEWLINENEWLINE Example:NEWLINENEWLINE For this repository: https://github.com/sugatoray/colab_git_sshNEWLINENEWLINE repo = "colab_git_ssh"NEWLINE owner = "sugatoray"NEWLINE host = "github.com"NEWLINE protocol = "https"NEWLINENEWLINE For this repository: git@github.com:sugatoray/colab_git_ssh.gitNEWLINENEWLINE repo = "colab_git_ssh"NEWLINE owner = "sugatoray"NEWLINE host = "github.com"NEWLINE protocol = "ssh"NEWLINENEWLINE """NEWLINE host = get_githost(host) NEWLINE if protocol=="ssh":NEWLINE address = f"git@{host}:{owner}/{repo}.git"NEWLINE else:NEWLINE # protocol=="https"NEWLINE address = f"https://{host}/{owner}/{repo}"NEWLINE return addressNEWLINE from player import PlayerNEWLINEfrom Card import CardNEWLINEimport timeNEWLINEimport uuid,randomNEWLINEclass Game:NEWLINE id = 0NEWLINE last_action_time = 0NEWLINE turn = 0NEWLINE cards = []NEWLINE players = []NEWLINE action = ""NEWLINE reaction_card = ""NEWLINE reacting_player = ""NEWLINE challenging_player = ""NEWLINE state = "" #Challenging, Over, Acting, Revealing, StartingNEWLINE target_player = ""NEWLINE exchanging_cards = []NEWLINE NEWLINE def __init__(self,player_list,start_time):NEWLINE self.id = uuid.uuid4().time_lowNEWLINE self.last_action_time = start_timeNEWLINE self.state = "Starting"NEWLINE self.target_player = ""NEWLINE self.reaction = ""NEWLINE self.challenging_player = ""NEWLINE self.exchanging_cards = []NEWLINE for p in player_list:NEWLINE self.players.append(Player(p))NEWLINE for i in range(3):NEWLINE self.cards.append(Card('Duke', ['TAX','BLOCK_FOREIGN_AID']))NEWLINE self.cards.append(Card('Captain', ['STEAL','BLOCK_STEAL'])) #Block stealNEWLINE self.cards.append(Card('Ambassador', ['EXCHANGE','BLOCK_STEAL'])) #Block stealNEWLINE self.cards.append(Card('Assassin', ['ASSASINATE']))NEWLINE self.cards.append(Card('Contessa', ['BLOCK_ASSASIANTE'])) #Block assassinationiNEWLINENEWLINE def get_cards_for_exchange(self):NEWLINE cards = [ card for card in self.players[self.get_turn()].get_cards() if card.get_state() == "active" ] + self.get_two_random_card()NEWLINE self.exchanging_cards = cardsNEWLINENEWLINE self.players[self.get_turn()].clean_cards()NEWLINENEWLINE return cardsNEWLINE NEWLINE NEWLINE def get_challenging_player(self):NEWLINE return self.challenging_playerNEWLINE def get_exchanging_cards(self):NEWLINE return self.exchanging_cardsNEWLINENEWLINENEWLINE def get_two_random_card(self):NEWLINE random.shuffle(self.cards)NEWLINE random_cards = [NEWLINE self.cards.pop(),self.cards.pop()NEWLINE ]NEWLINE return random_cardsNEWLINENEWLINENEWLINE def check_action_is_exchange(self):NEWLINE if(self.action == "EXCHANGE"):NEWLINE return TrueNEWLINE return FalseNEWLINE NEWLINE def get_target_player(self):NEWLINE return self.target_playerNEWLINE NEWLINE def perform(self):NEWLINE if(self.action == "TAX"):NEWLINE self.players[self.get_turn()].tax()NEWLINE return None , FalseNEWLINE if(self.action == "STEAL"):NEWLINE profit = self.target_player.get_rubbed()NEWLINE self.players[self.get_turn()].set_coins(self.players[self.get_turn()].get_coins() + profit )NEWLINE return None , FalseNEWLINE if(self.action == "COUP"):NEWLINE card , is_dead = self.target_player.kill_one_card()NEWLINE return card , is_deadNEWLINE if(self.action == "ASSASINATE"):NEWLINE card , is_dead = self.target_player.kill_one_card()NEWLINE return card , is_deadNEWLINE if(self.action == "INCOME"):NEWLINE self.players[self.get_turn()].income()NEWLINE return None , FalseNEWLINENEWLINE return None , FalseNEWLINE NEWLINENEWLINE def get_reaction_card(self):NEWLINE return self.reaction_cardNEWLINENEWLINE NEWLINE def set_reaction_card(self , reaction_card):NEWLINE self.reaction_card = reaction_cardNEWLINENEWLINENEWLINE def get_turn_counter(self):NEWLINE return self.turnNEWLINENEWLINENEWLINE def set_target_player(self,target_player_chat_id):NEWLINE NEWLINE for player in self.players:NEWLINE if(player.get_id().message.chat_id == target_player_chat_id):NEWLINE self.target_player = playerNEWLINE return TrueNEWLINE return FalseNEWLINENEWLINE NEWLINE def check_target_player_need(self):NEWLINE if(self.action in ["ASSASINATE","STEAL","COUP"]):NEWLINE return TrueNEWLINE else:NEWLINE return FalseNEWLINE def check_react_challenge(self):NEWLINE if(self.get_target_player().has_card(self.reaction_card)):NEWLINE card , is_dead = self.get_players()[self.get_turn()].kill_one_card()NEWLINE return False , card , is_deadNEWLINE else:NEWLINE card , is_dead = self.get_target_player().kill_one_card()NEWLINE return True , card , is_deadNEWLINENEWLINENEWLINE def check_challenge(self,player_chat_id):NEWLINE playing_player_index = self.get_turn()NEWLINE challenging_player_chat_id = player_chat_idNEWLINENEWLINE for player in self.players:NEWLINE c = player.get_id().message.chat_idNEWLINE if( c == challenging_player_chat_id):NEWLINE challenging_player = playerNEWLINE self.challenging_player = playerNEWLINE is_bluffing = self.players[playing_player_index].is_bluffing(self.action)NEWLINENEWLINE if(is_bluffing):NEWLINE card , is_dead = self.players[playing_player_index].kill_one_card()NEWLINE NEWLINE return True , card , is_dead NEWLINE else:NEWLINE card , is_dead = challenging_player.kill_one_card()NEWLINE return False , card , is_dead NEWLINENEWLINE def check_challenge_possibility(self):NEWLINE if(self.action in ['COUP','INCOME']):NEWLINE return FalseNEWLINE else:NEWLINE self.get_last_action_time = time.time()NEWLINE return TrueNEWLINENEWLINE def get_action(self):NEWLINE return self.actionNEWLINE NEWLINE def set_action(self,new_action):NEWLINE self.action = new_actionNEWLINE return 1NEWLINE NEWLINE def get_turn(self):NEWLINE return self.turn % len(self.players)NEWLINE NEWLINE def next_turn(self):NEWLINE self.target_player = ""NEWLINE self.action = ""NEWLINE self.reaction_card = ""NEWLINE self.reacting_player = ""NEWLINE self.state = "" #Challenging, Over, Acting, Revealing, StartingNEWLINE for i in range(self.turn+1,5000):NEWLINE if(self.players[i % len(self.players)].get_state()!= "DEAD"):NEWLINE self.turn = i NEWLINE breakNEWLINE return TrueNEWLINENEWLINE def start(self):NEWLINE random.shuffle(self.cards)NEWLINE for player in self.players:NEWLINE player.add_card(self.cards.pop())NEWLINE player.add_card(self.cards.pop())NEWLINE player.coins = 2NEWLINE turn = 0NEWLINE self.state = "Acting" NEWLINENEWLINE def get_living_players(self):NEWLINE NEWLINE return [player for player in self.players if player.state != "Dead" ]NEWLINE def get_players(self):NEWLINE return self.playersNEWLINE def get_last_action_time(self): NEWLINE return self.last_action_timeNEWLINE NEWLINE def get_state(self):NEWLINE return self.stateNEWLINENEWLINE def set_state(self,state):NEWLINE self.state = stateNEWLINE NEWLINE def set_last_action_time(self,time):NEWLINE self.last_action_time = time NEWLINE return 1NEWLINE NEWLINE def get_id(self):NEWLINE return self.idNEWLINE # Copyright 2018 Open Source Robotics Foundation, Inc.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINEimport unittestNEWLINENEWLINEfrom rclpy.clock import ClockTypeNEWLINEfrom rclpy.duration import DurationNEWLINEfrom rclpy.time import TimeNEWLINENEWLINEfrom test_msgs.msg import BuiltinsNEWLINENEWLINENEWLINEclass TestTime(unittest.TestCase):NEWLINENEWLINE def test_time_construction(self):NEWLINE time = Time()NEWLINE assert time.nanoseconds == 0NEWLINENEWLINE time = Time(seconds=1, nanoseconds=5e8, clock_type=ClockType.SYSTEM_TIME)NEWLINE assert time.nanoseconds == 1500000000NEWLINE assert time.clock_type == ClockType.SYSTEM_TIMENEWLINENEWLINE with self.assertRaises(OverflowError):NEWLINE time = Time(nanoseconds=2**63)NEWLINE time = Time(nanoseconds=2**63 - 1)NEWLINE assert time.nanoseconds == 2**63 - 1NEWLINENEWLINE with self.assertRaises(ValueError):NEWLINE time = Time(seconds=-1)NEWLINE with self.assertRaises(ValueError):NEWLINE time = Time(nanoseconds=-1)NEWLINE with self.assertRaises(TypeError):NEWLINE time = Time(clock_type='SYSTEM_TIME')NEWLINENEWLINE def test_duration_construction(self):NEWLINE duration = Duration()NEWLINE assert duration.nanoseconds == 0NEWLINENEWLINE duration = Duration(seconds=1, nanoseconds=5e8)NEWLINE assert duration.nanoseconds == 1500000000NEWLINENEWLINE with self.assertRaises(OverflowError):NEWLINE duration = Duration(nanoseconds=2**63)NEWLINE duration = Duration(nanoseconds=2**63 - 1)NEWLINE assert duration.nanoseconds == 2**63 - 1NEWLINENEWLINE assert Duration(seconds=-1).nanoseconds == -1 * 1000 * 1000 * 1000NEWLINE assert Duration(nanoseconds=-1).nanoseconds == -1NEWLINENEWLINE assert Duration(seconds=-2**63 / 1e9).nanoseconds == -2**63NEWLINE with self.assertRaises(OverflowError):NEWLINE # Much smaller number because float to integer conversion of seconds is impreciseNEWLINE duration = Duration(seconds=-2**63 / 1e9 - 1)NEWLINENEWLINE assert Duration(nanoseconds=-2**63).nanoseconds == -2**63NEWLINE with self.assertRaises(OverflowError):NEWLINE Duration(nanoseconds=-2**63 - 1)NEWLINENEWLINE def test_time_operators(self):NEWLINE time1 = Time(nanoseconds=1, clock_type=ClockType.STEADY_TIME)NEWLINENEWLINE # Addition/subtraction of time and durationNEWLINE duration = Duration(nanoseconds=1)NEWLINE time2 = time1 + durationNEWLINE assert isinstance(time2, Time)NEWLINE assert time2.nanoseconds == 2NEWLINE assert time2.clock_type == ClockType.STEADY_TIMENEWLINENEWLINE time2 = duration + time1NEWLINE assert isinstance(time2, Time)NEWLINE assert time2.nanoseconds == 2NEWLINE assert time2.clock_type == ClockType.STEADY_TIMENEWLINENEWLINE time2 = time1 - durationNEWLINE assert isinstance(time2, Time)NEWLINE assert time2.nanoseconds == 0NEWLINE assert time2.clock_type == ClockType.STEADY_TIMENEWLINENEWLINE with self.assertRaises(OverflowError):NEWLINE Duration(nanoseconds=1) + Time(nanoseconds=2**63 - 1)NEWLINENEWLINE with self.assertRaises(ValueError):NEWLINE Time(nanoseconds=1) - Duration(nanoseconds=2)NEWLINENEWLINE # Subtraction of times with the same clock typeNEWLINE diff = time1 - time2NEWLINE assert isinstance(diff, Duration)NEWLINE assert diff.nanoseconds == 1NEWLINENEWLINE # Subtraction resulting in a negative durationNEWLINE assert (Time(nanoseconds=1) - Time(nanoseconds=2)).nanoseconds == -1NEWLINENEWLINE # Subtraction of times with different clock typesNEWLINE with self.assertRaises(TypeError):NEWLINE Time(nanoseconds=2, clock_type=ClockType.SYSTEM_TIME) - \NEWLINE Time(nanoseconds=1, clock_type=ClockType.STEADY_TIME)NEWLINENEWLINE # Invalid arithmetic combinationsNEWLINE with self.assertRaises(TypeError):NEWLINE time1 + time2NEWLINE with self.assertRaises(TypeError):NEWLINE duration - time1NEWLINENEWLINE def test_time_comparators(self):NEWLINE # Times with the same clock typeNEWLINE time1 = Time(nanoseconds=1)NEWLINE time2 = Time(nanoseconds=2)NEWLINE self.assertFalse(time1 == time2)NEWLINE self.assertTrue(time1 != time2)NEWLINE self.assertFalse(time1 > time2)NEWLINE self.assertFalse(time1 >= time2)NEWLINE self.assertTrue(time1 < time2)NEWLINE self.assertTrue(time1 <= time2)NEWLINENEWLINE time1 = Time(nanoseconds=5e9)NEWLINE time2 = Time(seconds=5)NEWLINE self.assertTrue(time1 == time2)NEWLINENEWLINE # Times with different clock typesNEWLINE time1 = Time(nanoseconds=1, clock_type=ClockType.SYSTEM_TIME)NEWLINE time2 = Time(nanoseconds=2, clock_type=ClockType.STEADY_TIME)NEWLINE with self.assertRaises(TypeError):NEWLINE time1 == time2NEWLINE with self.assertRaises(TypeError):NEWLINE time1 != time2NEWLINE with self.assertRaises(TypeError):NEWLINE time1 > time2NEWLINE with self.assertRaises(TypeError):NEWLINE time1 >= time2NEWLINE with self.assertRaises(TypeError):NEWLINE time1 < time2NEWLINE with self.assertRaises(TypeError):NEWLINE time1 <= time2NEWLINENEWLINE # Invalid combinationsNEWLINE time1 = Time(nanoseconds=1)NEWLINE with self.assertRaises(TypeError):NEWLINE time1 == 1NEWLINE duration = Duration()NEWLINE with self.assertRaises(TypeError):NEWLINE time1 == durationNEWLINE with self.assertRaises(TypeError):NEWLINE time1 != durationNEWLINE with self.assertRaises(TypeError):NEWLINE time1 > durationNEWLINE with self.assertRaises(TypeError):NEWLINE time1 >= durationNEWLINE with self.assertRaises(TypeError):NEWLINE time1 < durationNEWLINE with self.assertRaises(TypeError):NEWLINE time1 <= durationNEWLINENEWLINE def test_duration_comparators(self):NEWLINE duration1 = Duration(nanoseconds=1)NEWLINE duration2 = Duration(nanoseconds=2)NEWLINE self.assertFalse(duration1 == duration2)NEWLINE self.assertTrue(duration1 != duration2)NEWLINE self.assertFalse(duration1 > duration2)NEWLINE self.assertFalse(duration1 >= duration2)NEWLINE self.assertTrue(duration1 < duration2)NEWLINE self.assertTrue(duration1 <= duration2)NEWLINENEWLINE duration1 = Duration(nanoseconds=5e9)NEWLINE duration2 = Duration(seconds=5)NEWLINE self.assertTrue(duration1 == duration2)NEWLINENEWLINE # Invalid combinationsNEWLINE duration1 = Duration(nanoseconds=1)NEWLINE with self.assertRaises(TypeError):NEWLINE duration1 == 1NEWLINE time = Time()NEWLINE with self.assertRaises(TypeError):NEWLINE duration1 == timeNEWLINE with self.assertRaises(TypeError):NEWLINE duration1 != timeNEWLINE with self.assertRaises(TypeError):NEWLINE duration1 > timeNEWLINE with self.assertRaises(TypeError):NEWLINE duration1 >= timeNEWLINE with self.assertRaises(TypeError):NEWLINE duration1 < timeNEWLINE with self.assertRaises(TypeError):NEWLINE duration1 <= timeNEWLINENEWLINE def test_time_message_conversions(self):NEWLINE time1 = Time(nanoseconds=1, clock_type=ClockType.ROS_TIME)NEWLINE builtins_msg = Builtins()NEWLINE builtins_msg.time_value = time1.to_msg()NEWLINENEWLINE # Default clock type resulting from from_msg will be ROS timeNEWLINE time2 = Time.from_msg(builtins_msg.time_value)NEWLINE assert isinstance(time2, Time)NEWLINE assert time1 == time2NEWLINE # Clock type can be specified if appropriateNEWLINE time3 = Time.from_msg(builtins_msg.time_value, clock_type=ClockType.SYSTEM_TIME)NEWLINE assert time3.clock_type == ClockType.SYSTEM_TIMENEWLINENEWLINE def test_time_message_conversions_big_nanoseconds(self):NEWLINE time1 = Time(nanoseconds=1553575413247045598, clock_type=ClockType.ROS_TIME)NEWLINE builtins_msg = Builtins()NEWLINE builtins_msg.time_value = time1.to_msg()NEWLINENEWLINE # Default clock type resulting from from_msg will be ROS timeNEWLINE time2 = Time.from_msg(builtins_msg.time_value)NEWLINE assert isinstance(time2, Time)NEWLINE assert time1 == time2NEWLINENEWLINE def test_duration_message_conversions(self):NEWLINE duration = Duration(nanoseconds=1)NEWLINE builtins_msg = Builtins()NEWLINE builtins_msg.duration_value = duration.to_msg()NEWLINE duration2 = Duration.from_msg(builtins_msg.duration_value)NEWLINE assert isinstance(duration2, Duration)NEWLINE assert duration2.nanoseconds == 1NEWLINENEWLINE def test_seconds_nanoseconds(self):NEWLINE assert (1, int(5e8)) == Time(seconds=1, nanoseconds=5e8).seconds_nanoseconds()NEWLINE assert (1, int(5e8)) == Time(seconds=0, nanoseconds=15e8).seconds_nanoseconds()NEWLINE assert (0, 0) == Time().seconds_nanoseconds()NEWLINE from django.db import modelsNEWLINENEWLINE# Create your models here.NEWLINEclass Grade(models.Model):NEWLINE gno=models.CharField(max_length=20,primary_key=True)NEWLINE gname=models.CharField(max_length=20,unique=True)NEWLINE class Meta():NEWLINE db_table = 'grade'NEWLINENEWLINEclass Course(models.Model):NEWLINE cno=models.CharField(max_length=20,primary_key=True)NEWLINE cname=models.CharField(max_length=100)NEWLINE textBook=models.CharField(max_length=50)NEWLINE gradeCourses=models.ManyToManyField("Grade",through="TeachPlan")NEWLINE class Meta():NEWLINE db_table = 'course'NEWLINENEWLINEclass TeachPlan(models.Model):NEWLINE course = models.ForeignKey("Course", on_delete=models.CASCADE)NEWLINE grade = models.ForeignKey("Grade", on_delete=models.CASCADE)NEWLINE credit=models.FloatField()NEWLINE teach_date = models.DateField()NEWLINE checkType = models.CharField(max_length=50)NEWLINE class Meta():NEWLINE db_table = 'teachplan'NEWLINENEWLINEclass Teacher(models.Model):NEWLINE tno=models.CharField(max_length=20,primary_key=True)NEWLINE tname=models.CharField(max_length=50)NEWLINE gender=models.CharField(max_length=10)NEWLINE jobTitle=models.CharField(max_length=10)NEWLINE teachCourse=models.ManyToManyField("Course")NEWLINE class Meta():NEWLINE db_table = 'teacher'NEWLINENEWLINEclass Student(models.Model):NEWLINE sno=models.CharField(max_length=50,primary_key=True)NEWLINE sname=models.CharField(max_length=50)NEWLINE gender=models.CharField(max_length=10)NEWLINE studentCourse=models.ManyToManyField("Course",through="Achievement")NEWLINE class Meta():NEWLINE db_table = 'student'NEWLINENEWLINEclass Achievement(models.Model):NEWLINE course = models.ForeignKey("Course", on_delete=models.CASCADE)NEWLINE student = models.ForeignKey("Student", on_delete=models.CASCADE)NEWLINE score = models.FloatField()NEWLINE gain_date = models.DateField()NEWLINE class Meta():NEWLINE db_table = 'achievement'NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE import lossesNEWLINEimport torchNEWLINENEWLINENEWLINEdef build_loss(cfg):NEWLINE args = cfg.copy()NEWLINE name = args.pop('type')NEWLINE if hasattr(torch.nn, name):NEWLINE criterion = getattr(torch.nn, name)(**args)NEWLINE else:NEWLINE criterion = losses.__dict__[name](**args)NEWLINE return criterionNEWLINE """NEWLINEPyTorch policy class used for SAC.NEWLINE"""NEWLINENEWLINEimport gymNEWLINEfrom gym.spaces import DiscreteNEWLINEimport loggingNEWLINEfrom typing import Dict, List, Optional, Tuple, Type, UnionNEWLINENEWLINEimport rayNEWLINEimport ray.experimental.tf_utilsNEWLINEfrom ray.rllib.agents.sac.sac_tf_policy import build_sac_model, \NEWLINE postprocess_trajectory, validate_spacesNEWLINEfrom ray.rllib.agents.dqn.dqn_tf_policy import PRIO_WEIGHTSNEWLINEfrom ray.rllib.models.modelv2 import ModelV2NEWLINEfrom ray.rllib.models.torch.torch_action_dist import \NEWLINE TorchDistributionWrapper, TorchDirichletNEWLINEfrom ray.rllib.policy.policy import PolicyNEWLINEfrom ray.rllib.policy.policy_template import build_policy_classNEWLINEfrom ray.rllib.policy.sample_batch import SampleBatchNEWLINEfrom ray.rllib.models.torch.torch_action_dist import (NEWLINE TorchCategorical, TorchSquashedGaussian, TorchDiagGaussian, TorchBeta)NEWLINEfrom ray.rllib.utils.framework import try_import_torchNEWLINEfrom ray.rllib.utils.spaces.simplex import SimplexNEWLINEfrom ray.rllib.utils.torch_ops import apply_grad_clipping, huber_lossNEWLINEfrom ray.rllib.utils.typing import LocalOptimizer, TensorType, \NEWLINE TrainerConfigDictNEWLINENEWLINEtorch, nn = try_import_torch()NEWLINEF = nn.functionalNEWLINENEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINENEWLINEdef build_sac_model_and_action_dist(NEWLINE policy: Policy,NEWLINE obs_space: gym.spaces.Space,NEWLINE action_space: gym.spaces.Space,NEWLINE config: TrainerConfigDict) -> \NEWLINE Tuple[ModelV2, Type[TorchDistributionWrapper]]:NEWLINE """Constructs the necessary ModelV2 and action dist class for the Policy.NEWLINENEWLINE Args:NEWLINE policy (Policy): The TFPolicy that will use the models.NEWLINE obs_space (gym.spaces.Space): The observation space.NEWLINE action_space (gym.spaces.Space): The action space.NEWLINE config (TrainerConfigDict): The SAC trainer's config dict.NEWLINENEWLINE Returns:NEWLINE ModelV2: The ModelV2 to be used by the Policy. Note: An additionalNEWLINE target model will be created in this function and assigned toNEWLINE `policy.target_model`.NEWLINE """NEWLINE model = build_sac_model(policy, obs_space, action_space, config)NEWLINE action_dist_class = _get_dist_class(config, action_space)NEWLINE return model, action_dist_classNEWLINENEWLINENEWLINEdef _get_dist_class(config: TrainerConfigDict, action_space: gym.spaces.SpaceNEWLINE ) -> Type[TorchDistributionWrapper]:NEWLINE """Helper function to return a dist class based on config and action space.NEWLINENEWLINE Args:NEWLINE config (TrainerConfigDict): The Trainer's config dict.NEWLINE action_space (gym.spaces.Space): The action space used.NEWLINENEWLINE Returns:NEWLINE Type[TFActionDistribution]: A TF distribution class.NEWLINE """NEWLINE if isinstance(action_space, Discrete):NEWLINE return TorchCategoricalNEWLINE elif isinstance(action_space, Simplex):NEWLINE return TorchDirichletNEWLINE else:NEWLINE if config["normalize_actions"]:NEWLINE return TorchSquashedGaussian if \NEWLINE not config["_use_beta_distribution"] else TorchBetaNEWLINE else:NEWLINE return TorchDiagGaussianNEWLINENEWLINENEWLINEdef action_distribution_fn(NEWLINE policy: Policy,NEWLINE model: ModelV2,NEWLINE obs_batch: TensorType,NEWLINE *,NEWLINE state_batches: Optional[List[TensorType]] = None,NEWLINE seq_lens: Optional[TensorType] = None,NEWLINE prev_action_batch: Optional[TensorType] = None,NEWLINE prev_reward_batch=None,NEWLINE explore: Optional[bool] = None,NEWLINE timestep: Optional[int] = None,NEWLINE is_training: Optional[bool] = None) -> \NEWLINE Tuple[TensorType, Type[TorchDistributionWrapper], List[TensorType]]:NEWLINE """The action distribution function to be used the algorithm.NEWLINENEWLINE An action distribution function is used to customize the choice of actionNEWLINE distribution class and the resulting action distribution inputs (toNEWLINE parameterize the distribution object).NEWLINE After parameterizing the distribution, a `sample()` callNEWLINE will be made on it to generate actions.NEWLINENEWLINE Args:NEWLINE policy (Policy): The Policy being queried for actions and calling thisNEWLINE function.NEWLINE model (TorchModelV2): The SAC specific Model to use to generate theNEWLINE distribution inputs (see sac_tf|torch_model.py). Must support theNEWLINE `get_policy_output` method.NEWLINE obs_batch (TensorType): The observations to be used as inputs to theNEWLINE model.NEWLINE state_batches (Optional[List[TensorType]]): The list of internal stateNEWLINE tensor batches.NEWLINE seq_lens (Optional[TensorType]): The tensor of sequence lengths usedNEWLINE in RNNs.NEWLINE prev_action_batch (Optional[TensorType]): Optional batch of prevNEWLINE actions used by the model.NEWLINE prev_reward_batch (Optional[TensorType]): Optional batch of prevNEWLINE rewards used by the model.NEWLINE explore (Optional[bool]): Whether to activate exploration or not. IfNEWLINE None, use value of `config.explore`.NEWLINE timestep (Optional[int]): An optional timestep.NEWLINE is_training (Optional[bool]): An optional is-training flag.NEWLINENEWLINE Returns:NEWLINE Tuple[TensorType, Type[TorchDistributionWrapper], List[TensorType]]:NEWLINE The dist inputs, dist class, and a list of internal state outputsNEWLINE (in the RNN case).NEWLINE """NEWLINE # Get base-model output (w/o the SAC specific parts of the network).NEWLINE model_out, _ = model({NEWLINE "obs": obs_batch,NEWLINE "is_training": is_training,NEWLINE }, [], None)NEWLINE # Use the base output to get the policy outputs from the SAC model'sNEWLINE # policy components.NEWLINE distribution_inputs = model.get_policy_output(model_out)NEWLINE # Get a distribution class to be used with the just calculated dist-inputs.NEWLINE action_dist_class = _get_dist_class(policy.config, policy.action_space)NEWLINENEWLINE return distribution_inputs, action_dist_class, []NEWLINENEWLINENEWLINEdef actor_critic_loss(NEWLINE policy: Policy, model: ModelV2,NEWLINE dist_class: Type[TorchDistributionWrapper],NEWLINE train_batch: SampleBatch) -> Union[TensorType, List[TensorType]]:NEWLINE """Constructs the loss for the Soft Actor Critic.NEWLINENEWLINE Args:NEWLINE policy (Policy): The Policy to calculate the loss for.NEWLINE model (ModelV2): The Model to calculate the loss for.NEWLINE dist_class (Type[TorchDistributionWrapper]: The action distr. class.NEWLINE train_batch (SampleBatch): The training data.NEWLINENEWLINE Returns:NEWLINE Union[TensorType, List[TensorType]]: A single loss tensor or a listNEWLINE of loss tensors.NEWLINE """NEWLINE # Should be True only for debugging purposes (e.g. test cases)!NEWLINE deterministic = policy.config["_deterministic_loss"]NEWLINENEWLINE model_out_t, _ = model({NEWLINE "obs": train_batch[SampleBatch.CUR_OBS],NEWLINE "is_training": True,NEWLINE }, [], None)NEWLINENEWLINE model_out_tp1, _ = model({NEWLINE "obs": train_batch[SampleBatch.NEXT_OBS],NEWLINE "is_training": True,NEWLINE }, [], None)NEWLINENEWLINE target_model_out_tp1, _ = policy.target_model({NEWLINE "obs": train_batch[SampleBatch.NEXT_OBS],NEWLINE "is_training": True,NEWLINE }, [], None)NEWLINENEWLINE alpha = torch.exp(model.log_alpha)NEWLINENEWLINE # Discrete case.NEWLINE if model.discrete:NEWLINE # Get all action probs directly from pi and form their logp.NEWLINE log_pis_t = F.log_softmax(model.get_policy_output(model_out_t), dim=-1)NEWLINE policy_t = torch.exp(log_pis_t)NEWLINE log_pis_tp1 = F.log_softmax(model.get_policy_output(model_out_tp1), -1)NEWLINE policy_tp1 = torch.exp(log_pis_tp1)NEWLINE # Q-values.NEWLINE q_t = model.get_q_values(model_out_t)NEWLINE # Target Q-values.NEWLINE q_tp1 = policy.target_model.get_q_values(target_model_out_tp1)NEWLINE if policy.config["twin_q"]:NEWLINE twin_q_t = model.get_twin_q_values(model_out_t)NEWLINE twin_q_tp1 = policy.target_model.get_twin_q_values(NEWLINE target_model_out_tp1)NEWLINE q_tp1 = torch.min(q_tp1, twin_q_tp1)NEWLINE q_tp1 -= alpha * log_pis_tp1NEWLINENEWLINE # Actually selected Q-values (from the actions batch).NEWLINE one_hot = F.one_hot(NEWLINE train_batch[SampleBatch.ACTIONS].long(),NEWLINE num_classes=q_t.size()[-1])NEWLINE q_t_selected = torch.sum(q_t * one_hot, dim=-1)NEWLINE if policy.config["twin_q"]:NEWLINE twin_q_t_selected = torch.sum(twin_q_t * one_hot, dim=-1)NEWLINE # Discrete case: "Best" means weighted by the policy (prob) outputs.NEWLINE q_tp1_best = torch.sum(torch.mul(policy_tp1, q_tp1), dim=-1)NEWLINE q_tp1_best_masked = \NEWLINE (1.0 - train_batch[SampleBatch.DONES].float()) * \NEWLINE q_tp1_bestNEWLINE # Continuous actions case.NEWLINE else:NEWLINE # Sample single actions from distribution.NEWLINE action_dist_class = _get_dist_class(policy.config, policy.action_space)NEWLINE action_dist_t = action_dist_class(NEWLINE model.get_policy_output(model_out_t), policy.model)NEWLINE policy_t = action_dist_t.sample() if not deterministic else \NEWLINE action_dist_t.deterministic_sample()NEWLINE log_pis_t = torch.unsqueeze(action_dist_t.logp(policy_t), -1)NEWLINE action_dist_tp1 = action_dist_class(NEWLINE model.get_policy_output(model_out_tp1), policy.model)NEWLINE policy_tp1 = action_dist_tp1.sample() if not deterministic else \NEWLINE action_dist_tp1.deterministic_sample()NEWLINE log_pis_tp1 = torch.unsqueeze(action_dist_tp1.logp(policy_tp1), -1)NEWLINENEWLINE # Q-values for the actually selected actions.NEWLINE q_t = model.get_q_values(model_out_t, train_batch[SampleBatch.ACTIONS])NEWLINE if policy.config["twin_q"]:NEWLINE twin_q_t = model.get_twin_q_values(NEWLINE model_out_t, train_batch[SampleBatch.ACTIONS])NEWLINENEWLINE # Q-values for current policy in given current state.NEWLINE q_t_det_policy = model.get_q_values(model_out_t, policy_t)NEWLINE if policy.config["twin_q"]:NEWLINE twin_q_t_det_policy = model.get_twin_q_values(NEWLINE model_out_t, policy_t)NEWLINE q_t_det_policy = torch.min(q_t_det_policy, twin_q_t_det_policy)NEWLINENEWLINE # Target q network evaluation.NEWLINE q_tp1 = policy.target_model.get_q_values(target_model_out_tp1,NEWLINE policy_tp1)NEWLINE if policy.config["twin_q"]:NEWLINE twin_q_tp1 = policy.target_model.get_twin_q_values(NEWLINE target_model_out_tp1, policy_tp1)NEWLINE # Take min over both twin-NNs.NEWLINE q_tp1 = torch.min(q_tp1, twin_q_tp1)NEWLINENEWLINE q_t_selected = torch.squeeze(q_t, dim=-1)NEWLINE if policy.config["twin_q"]:NEWLINE twin_q_t_selected = torch.squeeze(twin_q_t, dim=-1)NEWLINE q_tp1 -= alpha * log_pis_tp1NEWLINENEWLINE q_tp1_best = torch.squeeze(input=q_tp1, dim=-1)NEWLINE q_tp1_best_masked = (1.0 - train_batch[SampleBatch.DONES].float()) * \NEWLINE q_tp1_bestNEWLINENEWLINE # compute RHS of bellman equationNEWLINE q_t_selected_target = (NEWLINE train_batch[SampleBatch.REWARDS] +NEWLINE (policy.config["gamma"]**policy.config["n_step"]) * q_tp1_best_maskedNEWLINE ).detach()NEWLINENEWLINE # Compute the TD-error (potentially clipped).NEWLINE base_td_error = torch.abs(q_t_selected - q_t_selected_target)NEWLINE if policy.config["twin_q"]:NEWLINE twin_td_error = torch.abs(twin_q_t_selected - q_t_selected_target)NEWLINE td_error = 0.5 * (base_td_error + twin_td_error)NEWLINE else:NEWLINE td_error = base_td_errorNEWLINENEWLINE critic_loss = [NEWLINE torch.mean(train_batch[PRIO_WEIGHTS] * huber_loss(base_td_error))NEWLINE ]NEWLINE if policy.config["twin_q"]:NEWLINE critic_loss.append(NEWLINE torch.mean(train_batch[PRIO_WEIGHTS] * huber_loss(twin_td_error)))NEWLINENEWLINE # Alpha- and actor losses.NEWLINE # Note: In the papers, alpha is used directly, here we take the log.NEWLINE # Discrete case: Multiply the action probs as weights with the originalNEWLINE # loss terms (no expectations needed).NEWLINE if model.discrete:NEWLINE weighted_log_alpha_loss = policy_t.detach() * (NEWLINE -model.log_alpha * (log_pis_t + model.target_entropy).detach())NEWLINE # Sum up weighted terms and mean over all batch items.NEWLINE alpha_loss = torch.mean(torch.sum(weighted_log_alpha_loss, dim=-1))NEWLINE # Actor loss.NEWLINE actor_loss = torch.mean(NEWLINE torch.sum(NEWLINE torch.mul(NEWLINE # NOTE: No stop_grad around policy output hereNEWLINE # (compare with q_t_det_policy for continuous case).NEWLINE policy_t,NEWLINE alpha.detach() * log_pis_t - q_t.detach()),NEWLINE dim=-1))NEWLINE else:NEWLINE alpha_loss = -torch.mean(model.log_alpha *NEWLINE (log_pis_t + model.target_entropy).detach())NEWLINE # Note: Do not detach q_t_det_policy here b/c is depends partlyNEWLINE # on the policy vars (policy sample pushed through Q-net).NEWLINE # However, we must make sure `actor_loss` is not used to updateNEWLINE # the Q-net(s)' variables.NEWLINE actor_loss = torch.mean(alpha.detach() * log_pis_t - q_t_det_policy)NEWLINENEWLINE # Save for stats function.NEWLINE policy.q_t = q_tNEWLINE policy.policy_t = policy_tNEWLINE policy.log_pis_t = log_pis_tNEWLINE policy.td_error = td_errorNEWLINE policy.actor_loss = actor_lossNEWLINE policy.critic_loss = critic_lossNEWLINE policy.alpha_loss = alpha_lossNEWLINE policy.log_alpha_value = model.log_alphaNEWLINE policy.alpha_value = alphaNEWLINE policy.target_entropy = model.target_entropyNEWLINENEWLINE # Return all loss terms corresponding to our optimizers.NEWLINE return tuple([policy.actor_loss] + policy.critic_loss +NEWLINE [policy.alpha_loss])NEWLINENEWLINENEWLINEdef stats(policy: Policy, train_batch: SampleBatch) -> Dict[str, TensorType]:NEWLINE """Stats function for SAC. Returns a dict with important loss stats.NEWLINENEWLINE Args:NEWLINE policy (Policy): The Policy to generate stats for.NEWLINE train_batch (SampleBatch): The SampleBatch (already) used for training.NEWLINENEWLINE Returns:NEWLINE Dict[str, TensorType]: The stats dict.NEWLINE """NEWLINE return {NEWLINE "td_error": policy.td_error,NEWLINE "mean_td_error": torch.mean(policy.td_error),NEWLINE "actor_loss": torch.mean(policy.actor_loss),NEWLINE "critic_loss": torch.mean(torch.stack(policy.critic_loss)),NEWLINE "alpha_loss": torch.mean(policy.alpha_loss),NEWLINE "alpha_value": torch.mean(policy.alpha_value),NEWLINE "log_alpha_value": torch.mean(policy.log_alpha_value),NEWLINE "target_entropy": policy.target_entropy,NEWLINE "policy_t": torch.mean(policy.policy_t),NEWLINE "mean_q": torch.mean(policy.q_t),NEWLINE "max_q": torch.max(policy.q_t),NEWLINE "min_q": torch.min(policy.q_t),NEWLINE }NEWLINENEWLINENEWLINEdef optimizer_fn(policy: Policy, config: TrainerConfigDict) -> \NEWLINE Tuple[LocalOptimizer]:NEWLINE """Creates all necessary optimizers for SAC learning.NEWLINENEWLINE The 3 or 4 (twin_q=True) optimizers returned here correspond to theNEWLINE number of loss terms returned by the loss function.NEWLINENEWLINE Args:NEWLINE policy (Policy): The policy object to be trained.NEWLINE config (TrainerConfigDict): The Trainer's config dict.NEWLINENEWLINE Returns:NEWLINE Tuple[LocalOptimizer]: The local optimizers to use for policy training.NEWLINE """NEWLINE policy.actor_optim = torch.optim.Adam(NEWLINE params=policy.model.policy_variables(),NEWLINE lr=config["optimization"]["actor_learning_rate"],NEWLINE eps=1e-7, # to match tf.keras.optimizers.Adam's epsilon defaultNEWLINE )NEWLINENEWLINE critic_split = len(policy.model.q_variables())NEWLINE if config["twin_q"]:NEWLINE critic_split //= 2NEWLINENEWLINE policy.critic_optims = [NEWLINE torch.optim.Adam(NEWLINE params=policy.model.q_variables()[:critic_split],NEWLINE lr=config["optimization"]["critic_learning_rate"],NEWLINE eps=1e-7, # to match tf.keras.optimizers.Adam's epsilon defaultNEWLINE )NEWLINE ]NEWLINE if config["twin_q"]:NEWLINE policy.critic_optims.append(NEWLINE torch.optim.Adam(NEWLINE params=policy.model.q_variables()[critic_split:],NEWLINE lr=config["optimization"]["critic_learning_rate"],NEWLINE eps=1e-7, # to match tf.keras.optimizers.Adam's eps defaultNEWLINE ))NEWLINE policy.alpha_optim = torch.optim.Adam(NEWLINE params=[policy.model.log_alpha],NEWLINE lr=config["optimization"]["entropy_learning_rate"],NEWLINE eps=1e-7, # to match tf.keras.optimizers.Adam's epsilon defaultNEWLINE )NEWLINENEWLINE return tuple([policy.actor_optim] + policy.critic_optims +NEWLINE [policy.alpha_optim])NEWLINENEWLINENEWLINEclass ComputeTDErrorMixin:NEWLINE """Mixin class calculating TD-error (part of critic loss) per batch item.NEWLINENEWLINE - Adds `policy.compute_td_error()` method for TD-error calculation from aNEWLINE batch of observations/actions/rewards/etc..NEWLINE """NEWLINENEWLINE def __init__(self):NEWLINE def compute_td_error(obs_t, act_t, rew_t, obs_tp1, done_mask,NEWLINE importance_weights):NEWLINE input_dict = self._lazy_tensor_dict({NEWLINE SampleBatch.CUR_OBS: obs_t,NEWLINE SampleBatch.ACTIONS: act_t,NEWLINE SampleBatch.REWARDS: rew_t,NEWLINE SampleBatch.NEXT_OBS: obs_tp1,NEWLINE SampleBatch.DONES: done_mask,NEWLINE PRIO_WEIGHTS: importance_weights,NEWLINE })NEWLINE # Do forward pass on loss to update td errors attributeNEWLINE # (one TD-error value per item in batch to update PR weights).NEWLINE actor_critic_loss(self, self.model, None, input_dict)NEWLINENEWLINE # `self.td_error` is set within actor_critic_loss call. ReturnNEWLINE # its updated value here.NEWLINE return self.td_errorNEWLINENEWLINE # Assign the method to policy (self) for later usage.NEWLINE self.compute_td_error = compute_td_errorNEWLINENEWLINENEWLINEclass TargetNetworkMixin:NEWLINE """Mixin class adding a method for (soft) target net(s) synchronizations.NEWLINENEWLINE - Adds the `update_target` method to the policy.NEWLINE Calling `update_target` updates all target Q-networks' weights from theirNEWLINE respective "main" Q-metworks, based on tau (smooth, partial updating).NEWLINE """NEWLINENEWLINE def __init__(self):NEWLINE # Hard initial update from Q-net(s) to target Q-net(s).NEWLINE self.update_target(tau=1.0)NEWLINENEWLINE def update_target(self, tau=None):NEWLINE # Update_target_fn will be called periodically to copy Q network toNEWLINE # target Q network, using (soft) tau-synching.NEWLINE tau = tau or self.config.get("tau")NEWLINE model_state_dict = self.model.state_dict()NEWLINE # Support partial (soft) synching.NEWLINE # If tau == 1.0: Full sync from Q-model to target Q-model.NEWLINE target_state_dict = self.target_model.state_dict()NEWLINE model_state_dict = {NEWLINE k: tau * model_state_dict[k] + (1 - tau) * vNEWLINE for k, v in target_state_dict.items()NEWLINE }NEWLINENEWLINE self.target_model.load_state_dict(model_state_dict)NEWLINENEWLINENEWLINEdef setup_late_mixins(policy: Policy, obs_space: gym.spaces.Space,NEWLINE action_space: gym.spaces.Space,NEWLINE config: TrainerConfigDict) -> None:NEWLINE """Call mixin classes' constructors after Policy initialization.NEWLINENEWLINE - Moves the target model(s) to the GPU, if necessary.NEWLINE - Adds the `compute_td_error` method to the given policy.NEWLINE Calling `compute_td_error` with batch data will re-calculate the lossNEWLINE on that batch AND return the per-batch-item TD-error for prioritizedNEWLINE replay buffer record weight updating (in case a prioritized replay bufferNEWLINE is used).NEWLINE - Also adds the `update_target` method to the given policy.NEWLINE Calling `update_target` updates all target Q-networks' weights from theirNEWLINE respective "main" Q-metworks, based on tau (smooth, partial updating).NEWLINENEWLINE Args:NEWLINE policy (Policy): The Policy object.NEWLINE obs_space (gym.spaces.Space): The Policy's observation space.NEWLINE action_space (gym.spaces.Space): The Policy's action space.NEWLINE config (TrainerConfigDict): The Policy's config.NEWLINE """NEWLINE policy.target_model = policy.target_model.to(policy.device)NEWLINE policy.model.log_alpha = policy.model.log_alpha.to(policy.device)NEWLINE policy.model.target_entropy = policy.model.target_entropy.to(policy.device)NEWLINE ComputeTDErrorMixin.__init__(policy)NEWLINE TargetNetworkMixin.__init__(policy)NEWLINENEWLINENEWLINE# Build a child class of `TorchPolicy`, given the custom functions definedNEWLINE# above.NEWLINESACTorchPolicy = build_policy_class(NEWLINE name="SACTorchPolicy",NEWLINE framework="torch",NEWLINE loss_fn=actor_critic_loss,NEWLINE get_default_config=lambda: ray.rllib.agents.sac.sac.DEFAULT_CONFIG,NEWLINE stats_fn=stats,NEWLINE postprocess_fn=postprocess_trajectory,NEWLINE extra_grad_process_fn=apply_grad_clipping,NEWLINE optimizer_fn=optimizer_fn,NEWLINE validate_spaces=validate_spaces,NEWLINE before_loss_init=setup_late_mixins,NEWLINE make_model_and_action_dist=build_sac_model_and_action_dist,NEWLINE mixins=[TargetNetworkMixin, ComputeTDErrorMixin],NEWLINE action_distribution_fn=action_distribution_fn,NEWLINE)NEWLINE # Generated by Django 3.2.5 on 2021-07-18 23:06NEWLINENEWLINEfrom django.db import migrations, modelsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ('login', '0001_initial'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.AlterField(NEWLINE model_name='config',NEWLINE name='level',NEWLINE field=models.SmallIntegerField(),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name='user',NEWLINE name='age',NEWLINE field=models.PositiveSmallIntegerField(blank=True),NEWLINE ),NEWLINE ]NEWLINE #!/usr/bin/env pythonNEWLINENEWLINE# Copyright (c) 2015 Google Inc. All rights reserved.NEWLINE# Use of this source code is governed by a BSD-style license that can beNEWLINE# found in the LICENSE file.NEWLINENEWLINE"""NEWLINEMake sure that we cause downstream modules to get built when we depend on theNEWLINEparent targets.NEWLINE"""NEWLINENEWLINEimport TestGypNEWLINENEWLINEtest = TestGyp.TestGyp()NEWLINENEWLINECHDIR = 'module-dep'NEWLINEtest.run_gyp('indirect-module-dependency.gyp', chdir=CHDIR)NEWLINEtest.build('indirect-module-dependency.gyp', 'an_exe', chdir=CHDIR)NEWLINEtest.built_file_must_exist(NEWLINE test.built_file_basename('a_module', test.LOADABLE_MODULE), chdir=CHDIR)NEWLINENEWLINEtest.pass_test()NEWLINE from django.db import modelsNEWLINENEWLINE# Create your models here.NEWLINEclass Grade(models.Model):NEWLINE gno=models.CharField(max_length=20,primary_key=True)NEWLINE gname=models.CharField(max_length=20,unique=True)NEWLINE class Meta():NEWLINE db_table = 'grade'NEWLINENEWLINEclass Course(models.Model):NEWLINE cno=models.CharField(max_length=20,primary_key=True)NEWLINE cname=models.CharField(max_length=100)NEWLINE textBook=models.CharField(max_length=50)NEWLINE gradeCourses=models.ManyToManyField("Grade",through="TeachPlan")NEWLINE class Meta():NEWLINE db_table = 'course'NEWLINENEWLINEclass TeachPlan(models.Model):NEWLINE course = models.ForeignKey("Course", on_delete=models.CASCADE)NEWLINE grade = models.ForeignKey("Grade", on_delete=models.CASCADE)NEWLINE credit=models.FloatField()NEWLINE teach_date = models.DateField()NEWLINE checkType = models.CharField(max_length=50)NEWLINE class Meta():NEWLINE db_table = 'teachplan'NEWLINENEWLINEclass Teacher(models.Model):NEWLINE tno=models.CharField(max_length=20,primary_key=True)NEWLINE tname=models.CharField(max_length=50)NEWLINE gender=models.CharField(max_length=10)NEWLINE jobTitle=models.CharField(max_length=10)NEWLINE teachCourse=models.ManyToManyField("Course")NEWLINE class Meta():NEWLINE db_table = 'teacher'NEWLINENEWLINEclass Student(models.Model):NEWLINE sno=models.CharField(max_length=50,primary_key=True)NEWLINE sname=models.CharField(max_length=50)NEWLINE gender=models.CharField(max_length=10)NEWLINE studentCourse=models.ManyToManyField("Course",through="Achievement")NEWLINE class Meta():NEWLINE db_table = 'student'NEWLINENEWLINEclass Achievement(models.Model):NEWLINE course = models.ForeignKey("Course", on_delete=models.CASCADE)NEWLINE student = models.ForeignKey("Student", on_delete=models.CASCADE)NEWLINE score = models.FloatField()NEWLINE gain_date = models.DateField()NEWLINE class Meta():NEWLINE db_table = 'achievement'NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE from app.business.blog.views import blog # noqaNEWLINE from time import timeNEWLINEfrom base64 import b16encodeNEWLINEfrom functools import partialNEWLINEfrom operator import __eq__, __ne__, __lt__, __le__, __gt__, __ge__NEWLINENEWLINEfrom six import (NEWLINE integer_types as _integer_types,NEWLINE text_type as _text_type)NEWLINENEWLINEfrom OpenSSL._util import (NEWLINE ffi as _ffi,NEWLINE lib as _lib,NEWLINE exception_from_error_queue as _exception_from_error_queue,NEWLINE byte_string as _byte_string,NEWLINE native as _native)NEWLINENEWLINEFILETYPE_PEM = _lib.SSL_FILETYPE_PEMNEWLINEFILETYPE_ASN1 = _lib.SSL_FILETYPE_ASN1NEWLINENEWLINE# TODO This was an API mistake. OpenSSL has no such constant.NEWLINEFILETYPE_TEXT = 2 ** 16 - 1NEWLINENEWLINETYPE_RSA = _lib.EVP_PKEY_RSANEWLINETYPE_DSA = _lib.EVP_PKEY_DSANEWLINENEWLINENEWLINEclass Error(Exception):NEWLINE """NEWLINE An error occurred in an `OpenSSL.crypto` API.NEWLINE """NEWLINENEWLINENEWLINE_raise_current_error = partial(_exception_from_error_queue, Error)NEWLINENEWLINEdef _untested_error(where):NEWLINE """NEWLINE An OpenSSL API failed somehow. Additionally, the failure which wasNEWLINE encountered isn't one that's exercised by the test suite so future behaviorNEWLINE of pyOpenSSL is now somewhat less predictable.NEWLINE """NEWLINE raise RuntimeError("Unknown %s failure" % (where,))NEWLINENEWLINENEWLINENEWLINEdef _new_mem_buf(buffer=None):NEWLINE """NEWLINE Allocate a new OpenSSL memory BIO.NEWLINENEWLINE Arrange for the garbage collector to clean it up automatically.NEWLINENEWLINE :param buffer: None or some bytes to use to put into the BIO so that theyNEWLINE can be read out.NEWLINE """NEWLINE if buffer is None:NEWLINE bio = _lib.BIO_new(_lib.BIO_s_mem())NEWLINE free = _lib.BIO_freeNEWLINE else:NEWLINE data = _ffi.new("char[]", buffer)NEWLINE bio = _lib.BIO_new_mem_buf(data, len(buffer))NEWLINE # Keep the memory alive as long as the bio is alive!NEWLINE def free(bio, ref=data):NEWLINE return _lib.BIO_free(bio)NEWLINENEWLINE if bio == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE bio = _ffi.gc(bio, free)NEWLINE return bioNEWLINENEWLINENEWLINENEWLINEdef _bio_to_string(bio):NEWLINE """NEWLINE Copy the contents of an OpenSSL BIO object into a Python byte string.NEWLINE """NEWLINE result_buffer = _ffi.new('char**')NEWLINE buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)NEWLINE return _ffi.buffer(result_buffer[0], buffer_length)[:]NEWLINENEWLINENEWLINENEWLINEdef _set_asn1_time(boundary, when):NEWLINE """NEWLINE The the time value of an ASN1 time object.NEWLINENEWLINE @param boundary: An ASN1_GENERALIZEDTIME pointer (or an object safelyNEWLINE castable to that type) which will have its value set.NEWLINE @param when: A string representation of the desired time value.NEWLINENEWLINE @raise TypeError: If C{when} is not a L{bytes} string.NEWLINE @raise ValueError: If C{when} does not represent a time in the requiredNEWLINE format.NEWLINE @raise RuntimeError: If the time value cannot be set for some otherNEWLINE (unspecified) reason.NEWLINE """NEWLINE if not isinstance(when, bytes):NEWLINE raise TypeError("when must be a byte string")NEWLINENEWLINE set_result = _lib.ASN1_GENERALIZEDTIME_set_string(NEWLINE _ffi.cast('ASN1_GENERALIZEDTIME*', boundary), when)NEWLINE if set_result == 0:NEWLINE dummy = _ffi.gc(_lib.ASN1_STRING_new(), _lib.ASN1_STRING_free)NEWLINE _lib.ASN1_STRING_set(dummy, when, len(when))NEWLINE check_result = _lib.ASN1_GENERALIZEDTIME_check(NEWLINE _ffi.cast('ASN1_GENERALIZEDTIME*', dummy))NEWLINE if not check_result:NEWLINE raise ValueError("Invalid string")NEWLINE else:NEWLINE _untested_error()NEWLINENEWLINENEWLINENEWLINEdef _get_asn1_time(timestamp):NEWLINE """NEWLINE Retrieve the time value of an ASN1 time object.NEWLINENEWLINE @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable toNEWLINE that type) from which the time value will be retrieved.NEWLINENEWLINE @return: The time value from C{timestamp} as a L{bytes} string in a certainNEWLINE format. Or C{None} if the object contains no time value.NEWLINE """NEWLINE string_timestamp = _ffi.cast('ASN1_STRING*', timestamp)NEWLINE if _lib.ASN1_STRING_length(string_timestamp) == 0:NEWLINE return NoneNEWLINE elif _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME:NEWLINE return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))NEWLINE else:NEWLINE generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")NEWLINE _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)NEWLINE if generalized_timestamp[0] == _ffi.NULL:NEWLINE # This may happen:NEWLINE # - if timestamp was not an ASN1_TIMENEWLINE # - if allocating memory for the ASN1_GENERALIZEDTIME failedNEWLINE # - if a copy of the time data from timestamp cannot be made forNEWLINE # the newly allocated ASN1_GENERALIZEDTIMENEWLINE #NEWLINE # These are difficult to test. cffi enforces the ASN1_TIME type.NEWLINE # Memory allocation failures are a pain to triggerNEWLINE # deterministically.NEWLINE _untested_error("ASN1_TIME_to_generalizedtime")NEWLINE else:NEWLINE string_timestamp = _ffi.cast(NEWLINE "ASN1_STRING*", generalized_timestamp[0])NEWLINE string_data = _lib.ASN1_STRING_data(string_timestamp)NEWLINE string_result = _ffi.string(string_data)NEWLINE _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])NEWLINE return string_resultNEWLINENEWLINENEWLINENEWLINEclass PKey(object):NEWLINE _only_public = FalseNEWLINE _initialized = TrueNEWLINENEWLINE def __init__(self):NEWLINE pkey = _lib.EVP_PKEY_new()NEWLINE self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)NEWLINE self._initialized = FalseNEWLINENEWLINENEWLINE def generate_key(self, type, bits):NEWLINE """NEWLINE Generate a key of a given type, with a given number of a bitsNEWLINENEWLINE :param type: The key type (TYPE_RSA or TYPE_DSA)NEWLINE :param bits: The number of bitsNEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(type, int):NEWLINE raise TypeError("type must be an integer")NEWLINENEWLINE if not isinstance(bits, int):NEWLINE raise TypeError("bits must be an integer")NEWLINENEWLINE # TODO Check error returnNEWLINE exponent = _lib.BN_new()NEWLINE exponent = _ffi.gc(exponent, _lib.BN_free)NEWLINE _lib.BN_set_word(exponent, _lib.RSA_F4)NEWLINENEWLINE if type == TYPE_RSA:NEWLINE if bits <= 0:NEWLINE raise ValueError("Invalid number of bits")NEWLINENEWLINE rsa = _lib.RSA_new()NEWLINENEWLINE result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)NEWLINE if result == 0:NEWLINE # TODO: The test for this case is commented out. DifferentNEWLINE # builds of OpenSSL appear to have different failure modes thatNEWLINE # make it hard to test. Visual inspection of the OpenSSLNEWLINE # source reveals that a return value of 0 signals an error.NEWLINE # Manual testing on a particular build of OpenSSL suggests thatNEWLINE # this is probably the appropriate way to handle those errors.NEWLINE _raise_current_error()NEWLINENEWLINE result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)NEWLINE if not result:NEWLINE # TODO: It appears as though this can fail if an engine is inNEWLINE # use which does not support RSA.NEWLINE _raise_current_error()NEWLINENEWLINE elif type == TYPE_DSA:NEWLINE dsa = _lib.DSA_generate_parameters(NEWLINE bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE if dsa == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE if not _lib.DSA_generate_key(dsa):NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE if not _lib.EVP_PKEY_assign_DSA(self._pkey, dsa):NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE else:NEWLINE raise Error("No such key type")NEWLINENEWLINE self._initialized = TrueNEWLINENEWLINENEWLINE def check(self):NEWLINE """NEWLINE Check the consistency of an RSA private key.NEWLINENEWLINE :return: True if key is consistent.NEWLINE :raise Error: if the key is inconsistent.NEWLINE :raise TypeError: if the key is of a type which cannot be checked.NEWLINE Only RSA keys can currently be checked.NEWLINE """NEWLINE if self._only_public:NEWLINE raise TypeError("public key only")NEWLINENEWLINE if _lib.EVP_PKEY_type(self._pkey.type) != _lib.EVP_PKEY_RSA:NEWLINE raise TypeError("key type unsupported")NEWLINENEWLINE rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)NEWLINE rsa = _ffi.gc(rsa, _lib.RSA_free)NEWLINE result = _lib.RSA_check_key(rsa)NEWLINE if result:NEWLINE return TrueNEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def type(self):NEWLINE """NEWLINE Returns the type of the keyNEWLINENEWLINE :return: The type of the key.NEWLINE """NEWLINE return self._pkey.typeNEWLINENEWLINENEWLINE def bits(self):NEWLINE """NEWLINE Returns the number of bits of the keyNEWLINENEWLINE :return: The number of bits of the key.NEWLINE """NEWLINE return _lib.EVP_PKEY_bits(self._pkey)NEWLINEPKeyType = PKeyNEWLINENEWLINENEWLINENEWLINEclass X509Name(object):NEWLINE def __init__(self, name):NEWLINE """NEWLINE Create a new X509Name, copying the given X509Name instance.NEWLINENEWLINE :param name: An X509Name object to copyNEWLINE """NEWLINE name = _lib.X509_NAME_dup(name._name)NEWLINE self._name = _ffi.gc(name, _lib.X509_NAME_free)NEWLINENEWLINENEWLINE def __setattr__(self, name, value):NEWLINE if name.startswith('_'):NEWLINE return super(X509Name, self).__setattr__(name, value)NEWLINENEWLINE # Note: we really do not want str subclasses here, so we do not useNEWLINE # isinstance.NEWLINE if type(name) is not str:NEWLINE raise TypeError("attribute name must be string, not '%.200s'" % (NEWLINE type(value).__name__,))NEWLINENEWLINE nid = _lib.OBJ_txt2nid(_byte_string(name))NEWLINE if nid == _lib.NID_undef:NEWLINE try:NEWLINE _raise_current_error()NEWLINE except Error:NEWLINE passNEWLINE raise AttributeError("No such attribute")NEWLINENEWLINE # If there's an old entry for this NID, remove itNEWLINE for i in range(_lib.X509_NAME_entry_count(self._name)):NEWLINE ent = _lib.X509_NAME_get_entry(self._name, i)NEWLINE ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)NEWLINE ent_nid = _lib.OBJ_obj2nid(ent_obj)NEWLINE if nid == ent_nid:NEWLINE ent = _lib.X509_NAME_delete_entry(self._name, i)NEWLINE _lib.X509_NAME_ENTRY_free(ent)NEWLINE breakNEWLINENEWLINE if isinstance(value, _text_type):NEWLINE value = value.encode('utf-8')NEWLINENEWLINE add_result = _lib.X509_NAME_add_entry_by_NID(NEWLINE self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0)NEWLINE if not add_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def __getattr__(self, name):NEWLINE """NEWLINE Find attribute. An X509Name object has the following attributes:NEWLINE countryName (alias C), stateOrProvince (alias ST), locality (alias L),NEWLINE organization (alias O), organizationalUnit (alias OU), commonName (aliasNEWLINE CN) and more...NEWLINE """NEWLINE nid = _lib.OBJ_txt2nid(_byte_string(name))NEWLINE if nid == _lib.NID_undef:NEWLINE # This is a bit weird. OBJ_txt2nid indicated failure, but it seemsNEWLINE # a lower level function, a2d_ASN1_OBJECT, also feels the need toNEWLINE # push something onto the error queue. If we don't clean that upNEWLINE # now, someone else will bump into it later and be quite confused.NEWLINE # See lp#314814.NEWLINE try:NEWLINE _raise_current_error()NEWLINE except Error:NEWLINE passNEWLINE return super(X509Name, self).__getattr__(name)NEWLINENEWLINE entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)NEWLINE if entry_index == -1:NEWLINE return NoneNEWLINENEWLINE entry = _lib.X509_NAME_get_entry(self._name, entry_index)NEWLINE data = _lib.X509_NAME_ENTRY_get_data(entry)NEWLINENEWLINE result_buffer = _ffi.new("unsigned char**")NEWLINE data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)NEWLINE if data_length < 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE try:NEWLINE result = _ffi.buffer(result_buffer[0], data_length)[:].decode('utf-8')NEWLINE finally:NEWLINE # XXX untestedNEWLINE _lib.OPENSSL_free(result_buffer[0])NEWLINE return resultNEWLINENEWLINENEWLINE def _cmp(op):NEWLINE def f(self, other):NEWLINE if not isinstance(other, X509Name):NEWLINE return NotImplementedNEWLINE result = _lib.X509_NAME_cmp(self._name, other._name)NEWLINE return op(result, 0)NEWLINE return fNEWLINENEWLINE __eq__ = _cmp(__eq__)NEWLINE __ne__ = _cmp(__ne__)NEWLINENEWLINE __lt__ = _cmp(__lt__)NEWLINE __le__ = _cmp(__le__)NEWLINENEWLINE __gt__ = _cmp(__gt__)NEWLINE __ge__ = _cmp(__ge__)NEWLINENEWLINE def __repr__(self):NEWLINE """NEWLINE String representation of an X509NameNEWLINE """NEWLINE result_buffer = _ffi.new("char[]", 512);NEWLINE format_result = _lib.X509_NAME_oneline(NEWLINE self._name, result_buffer, len(result_buffer))NEWLINENEWLINE if format_result == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return "" % (NEWLINE _native(_ffi.string(result_buffer)),)NEWLINENEWLINENEWLINE def hash(self):NEWLINE """NEWLINE Return the hash value of this nameNEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return _lib.X509_NAME_hash(self._name)NEWLINENEWLINENEWLINE def der(self):NEWLINE """NEWLINE Return the DER encoding of this nameNEWLINENEWLINE :return: A :py:class:`bytes` instance giving the DER encoded form ofNEWLINE this name.NEWLINE """NEWLINE result_buffer = _ffi.new('unsigned char**')NEWLINE encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)NEWLINE if encode_result < 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE string_result = _ffi.buffer(result_buffer[0], encode_result)[:]NEWLINE _lib.OPENSSL_free(result_buffer[0])NEWLINE return string_resultNEWLINENEWLINENEWLINE def get_components(self):NEWLINE """NEWLINE Returns the split-up components of this name.NEWLINENEWLINE :return: List of tuples (name, value).NEWLINE """NEWLINE result = []NEWLINE for i in range(_lib.X509_NAME_entry_count(self._name)):NEWLINE ent = _lib.X509_NAME_get_entry(self._name, i)NEWLINENEWLINE fname = _lib.X509_NAME_ENTRY_get_object(ent)NEWLINE fval = _lib.X509_NAME_ENTRY_get_data(ent)NEWLINENEWLINE nid = _lib.OBJ_obj2nid(fname)NEWLINE name = _lib.OBJ_nid2sn(nid)NEWLINENEWLINE result.append((NEWLINE _ffi.string(name),NEWLINE _ffi.string(NEWLINE _lib.ASN1_STRING_data(fval),NEWLINE _lib.ASN1_STRING_length(fval))))NEWLINENEWLINE return resultNEWLINEX509NameType = X509NameNEWLINENEWLINENEWLINEclass X509Extension(object):NEWLINE def __init__(self, type_name, critical, value, subject=None, issuer=None):NEWLINE """NEWLINE :param typename: The name of the extension to create.NEWLINE :type typename: :py:data:`str`NEWLINENEWLINE :param critical: A flag indicating whether this is a critical extension.NEWLINENEWLINE :param value: The value of the extension.NEWLINE :type value: :py:data:`str`NEWLINENEWLINE :param subject: Optional X509 cert to use as subject.NEWLINE :type subject: :py:class:`X509`NEWLINENEWLINE :param issuer: Optional X509 cert to use as issuer.NEWLINE :type issuer: :py:class:`X509`NEWLINENEWLINE :return: The X509Extension objectNEWLINE """NEWLINE ctx = _ffi.new("X509V3_CTX*")NEWLINENEWLINE # A context is necessary for any extension which uses the r2i conversionNEWLINE # method. That is, X509V3_EXT_nconf may segfault if passed a NULL ctx.NEWLINE # Start off by initializing most of the fields to NULL.NEWLINE _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)NEWLINENEWLINE # We have no configuration database - but perhaps we should (someNEWLINE # extensions may require it).NEWLINE _lib.X509V3_set_ctx_nodb(ctx)NEWLINENEWLINE # Initialize the subject and issuer, if appropriate. ctx is a local,NEWLINE # and as far as I can tell none of the X509V3_* APIs invoked here stealNEWLINE # any references, so no need to mess with reference counts or duplicates.NEWLINE if issuer is not None:NEWLINE if not isinstance(issuer, X509):NEWLINE raise TypeError("issuer must be an X509 instance")NEWLINE ctx.issuer_cert = issuer._x509NEWLINE if subject is not None:NEWLINE if not isinstance(subject, X509):NEWLINE raise TypeError("subject must be an X509 instance")NEWLINE ctx.subject_cert = subject._x509NEWLINENEWLINE if critical:NEWLINE # There are other OpenSSL APIs which would let us pass in criticalNEWLINE # separately, but they're harder to use, and since value is alreadyNEWLINE # a pile of crappy junk smuggling a ton of utterly importantNEWLINE # structured data, what's the point of trying to avoid nasty stuffNEWLINE # with strings? (However, X509V3_EXT_i2d in particular seems like itNEWLINE # would be a better API to invoke. I do not know where to get theNEWLINE # ext_struc it desires for its last parameter, though.)NEWLINE value = b"critical," + valueNEWLINENEWLINE extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)NEWLINE if extension == _ffi.NULL:NEWLINE _raise_current_error()NEWLINE self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)NEWLINENEWLINENEWLINE @propertyNEWLINE def _nid(self):NEWLINE return _lib.OBJ_obj2nid(self._extension.object)NEWLINENEWLINE _prefixes = {NEWLINE _lib.GEN_EMAIL: "email",NEWLINE _lib.GEN_DNS: "DNS",NEWLINE _lib.GEN_URI: "URI",NEWLINE }NEWLINENEWLINE def _subjectAltNameString(self):NEWLINE method = _lib.X509V3_EXT_get(self._extension)NEWLINE if method == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE payload = self._extension.value.dataNEWLINE length = self._extension.value.lengthNEWLINENEWLINE payloadptr = _ffi.new("unsigned char**")NEWLINE payloadptr[0] = payloadNEWLINENEWLINE if method.it != _ffi.NULL:NEWLINE ptr = _lib.ASN1_ITEM_ptr(method.it)NEWLINE data = _lib.ASN1_item_d2i(_ffi.NULL, payloadptr, length, ptr)NEWLINE names = _ffi.cast("GENERAL_NAMES*", data)NEWLINE else:NEWLINE names = _ffi.cast(NEWLINE "GENERAL_NAMES*",NEWLINE method.d2i(_ffi.NULL, payloadptr, length))NEWLINENEWLINE parts = []NEWLINE for i in range(_lib.sk_GENERAL_NAME_num(names)):NEWLINE name = _lib.sk_GENERAL_NAME_value(names, i)NEWLINE try:NEWLINE label = self._prefixes[name.type]NEWLINE except KeyError:NEWLINE bio = _new_mem_buf()NEWLINE _lib.GENERAL_NAME_print(bio, name)NEWLINE parts.append(_native(_bio_to_string(bio)))NEWLINE else:NEWLINE value = _native(NEWLINE _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[:])NEWLINE parts.append(label + ":" + value)NEWLINE return ", ".join(parts)NEWLINENEWLINENEWLINE def __str__(self):NEWLINE """NEWLINE :return: a nice text representation of the extensionNEWLINE """NEWLINE if _lib.NID_subject_alt_name == self._nid:NEWLINE return self._subjectAltNameString()NEWLINENEWLINE bio = _new_mem_buf()NEWLINE print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)NEWLINE if not print_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _native(_bio_to_string(bio))NEWLINENEWLINENEWLINE def get_critical(self):NEWLINE """NEWLINE Returns the critical field of the X509ExtensionNEWLINENEWLINE :return: The critical field.NEWLINE """NEWLINE return _lib.X509_EXTENSION_get_critical(self._extension)NEWLINENEWLINENEWLINE def get_short_name(self):NEWLINE """NEWLINE Returns the short version of the type name of the X509ExtensionNEWLINENEWLINE :return: The short type name.NEWLINE """NEWLINE obj = _lib.X509_EXTENSION_get_object(self._extension)NEWLINE nid = _lib.OBJ_obj2nid(obj)NEWLINE return _ffi.string(_lib.OBJ_nid2sn(nid))NEWLINENEWLINENEWLINE def get_data(self):NEWLINE """NEWLINE Returns the data of the X509ExtensionNEWLINENEWLINE :return: A :py:data:`str` giving the X509Extension's ASN.1 encoded data.NEWLINE """NEWLINE octet_result = _lib.X509_EXTENSION_get_data(self._extension)NEWLINE string_result = _ffi.cast('ASN1_STRING*', octet_result)NEWLINE char_result = _lib.ASN1_STRING_data(string_result)NEWLINE result_length = _lib.ASN1_STRING_length(string_result)NEWLINE return _ffi.buffer(char_result, result_length)[:]NEWLINENEWLINEX509ExtensionType = X509ExtensionNEWLINENEWLINENEWLINEclass X509Req(object):NEWLINE def __init__(self):NEWLINE req = _lib.X509_REQ_new()NEWLINE self._req = _ffi.gc(req, _lib.X509_REQ_free)NEWLINENEWLINENEWLINE def set_pubkey(self, pkey):NEWLINE """NEWLINE Set the public key of the certificate requestNEWLINENEWLINE :param pkey: The public key to useNEWLINE :return: NoneNEWLINE """NEWLINE set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)NEWLINE if not set_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_pubkey(self):NEWLINE """NEWLINE Get the public key from the certificate requestNEWLINENEWLINE :return: The public keyNEWLINE """NEWLINE pkey = PKey.__new__(PKey)NEWLINE pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)NEWLINE if pkey._pkey == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)NEWLINE pkey._only_public = TrueNEWLINE return pkeyNEWLINENEWLINENEWLINE def set_version(self, version):NEWLINE """NEWLINE Set the version subfield (RFC 2459, section 4.1.2.1) of the certificateNEWLINE request.NEWLINENEWLINE :param version: The version numberNEWLINE :return: NoneNEWLINE """NEWLINE set_result = _lib.X509_REQ_set_version(self._req, version)NEWLINE if not set_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_version(self):NEWLINE """NEWLINE Get the version subfield (RFC 2459, section 4.1.2.1) of the certificateNEWLINE request.NEWLINENEWLINE :return: an integer giving the value of the version subfieldNEWLINE """NEWLINE return _lib.X509_REQ_get_version(self._req)NEWLINENEWLINENEWLINE def get_subject(self):NEWLINE """NEWLINE Create an X509Name object for the subject of the certificate requestNEWLINENEWLINE :return: An X509Name objectNEWLINE """NEWLINE name = X509Name.__new__(X509Name)NEWLINE name._name = _lib.X509_REQ_get_subject_name(self._req)NEWLINE if name._name == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE # The name is owned by the X509Req structure. As long as the X509NameNEWLINE # Python object is alive, keep the X509Req Python object alive.NEWLINE name._owner = selfNEWLINENEWLINE return nameNEWLINENEWLINENEWLINE def add_extensions(self, extensions):NEWLINE """NEWLINE Add extensions to the request.NEWLINENEWLINE :param extensions: a sequence of X509Extension objectsNEWLINE :return: NoneNEWLINE """NEWLINE stack = _lib.sk_X509_EXTENSION_new_null()NEWLINE if stack == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)NEWLINENEWLINE for ext in extensions:NEWLINE if not isinstance(ext, X509Extension):NEWLINE raise ValueError("One of the elements is not an X509Extension")NEWLINENEWLINE # TODO push can fail (here and elsewhere)NEWLINE _lib.sk_X509_EXTENSION_push(stack, ext._extension)NEWLINENEWLINE add_result = _lib.X509_REQ_add_extensions(self._req, stack)NEWLINE if not add_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def sign(self, pkey, digest):NEWLINE """NEWLINE Sign the certificate request using the supplied key and digestNEWLINENEWLINE :param pkey: The key to sign withNEWLINE :param digest: The message digest to useNEWLINE :return: NoneNEWLINE """NEWLINE if pkey._only_public:NEWLINE raise ValueError("Key has only public part")NEWLINENEWLINE if not pkey._initialized:NEWLINE raise ValueError("Key is uninitialized")NEWLINENEWLINE digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if digest_obj == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)NEWLINE if not sign_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def verify(self, pkey):NEWLINE """NEWLINE Verifies a certificate request using the supplied public keyNEWLINENEWLINE :param key: a public keyNEWLINE :return: True if the signature is correct.NEWLINENEWLINE :raise OpenSSL.crypto.Error: If the signature is invalid or there is aNEWLINE problem verifying the signature.NEWLINE """NEWLINE if not isinstance(pkey, PKey):NEWLINE raise TypeError("pkey must be a PKey instance")NEWLINENEWLINE result = _lib.X509_REQ_verify(self._req, pkey._pkey)NEWLINE if result <= 0:NEWLINE _raise_current_error()NEWLINENEWLINE return resultNEWLINENEWLINENEWLINEX509ReqType = X509ReqNEWLINENEWLINENEWLINENEWLINEclass X509(object):NEWLINE def __init__(self):NEWLINE # TODO Allocation failure? And why not __new__ instead of __init__?NEWLINE x509 = _lib.X509_new()NEWLINE self._x509 = _ffi.gc(x509, _lib.X509_free)NEWLINENEWLINENEWLINE def set_version(self, version):NEWLINE """NEWLINE Set version number of the certificateNEWLINENEWLINE :param version: The version numberNEWLINE :type version: :py:class:`int`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(version, int):NEWLINE raise TypeError("version must be an integer")NEWLINENEWLINE _lib.X509_set_version(self._x509, version)NEWLINENEWLINENEWLINE def get_version(self):NEWLINE """NEWLINE Return version number of the certificateNEWLINENEWLINE :return: Version number as a Python integerNEWLINE """NEWLINE return _lib.X509_get_version(self._x509)NEWLINENEWLINENEWLINE def get_pubkey(self):NEWLINE """NEWLINE Get the public key of the certificateNEWLINENEWLINE :return: The public keyNEWLINE """NEWLINE pkey = PKey.__new__(PKey)NEWLINE pkey._pkey = _lib.X509_get_pubkey(self._x509)NEWLINE if pkey._pkey == _ffi.NULL:NEWLINE _raise_current_error()NEWLINE pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)NEWLINE pkey._only_public = TrueNEWLINE return pkeyNEWLINENEWLINENEWLINE def set_pubkey(self, pkey):NEWLINE """NEWLINE Set the public key of the certificateNEWLINENEWLINE :param pkey: The public keyNEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(pkey, PKey):NEWLINE raise TypeError("pkey must be a PKey instance")NEWLINENEWLINE set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)NEWLINE if not set_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def sign(self, pkey, digest):NEWLINE """NEWLINE Sign the certificate using the supplied key and digestNEWLINENEWLINE :param pkey: The key to sign withNEWLINE :param digest: The message digest to useNEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(pkey, PKey):NEWLINE raise TypeError("pkey must be a PKey instance")NEWLINENEWLINE if pkey._only_public:NEWLINE raise ValueError("Key only has public part")NEWLINENEWLINE if not pkey._initialized:NEWLINE raise ValueError("Key is uninitialized")NEWLINENEWLINE evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if evp_md == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)NEWLINE if not sign_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_signature_algorithm(self):NEWLINE """NEWLINE Retrieve the signature algorithm used in the certificateNEWLINENEWLINE :return: A byte string giving the name of the signature algorithm used inNEWLINE the certificate.NEWLINE :raise ValueError: If the signature algorithm is undefined.NEWLINE """NEWLINE alg = self._x509.cert_info.signature.algorithmNEWLINE nid = _lib.OBJ_obj2nid(alg)NEWLINE if nid == _lib.NID_undef:NEWLINE raise ValueError("Undefined signature algorithm")NEWLINE return _ffi.string(_lib.OBJ_nid2ln(nid))NEWLINENEWLINENEWLINE def digest(self, digest_name):NEWLINE """NEWLINE Return the digest of the X509 object.NEWLINENEWLINE :param digest_name: The name of the digest algorithm to use.NEWLINE :type digest_name: :py:class:`bytes`NEWLINENEWLINE :return: The digest of the objectNEWLINE """NEWLINE digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))NEWLINE if digest == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE result_buffer = _ffi.new("char[]", _lib.EVP_MAX_MD_SIZE)NEWLINE result_length = _ffi.new("unsigned int[]", 1)NEWLINE result_length[0] = len(result_buffer)NEWLINENEWLINE digest_result = _lib.X509_digest(NEWLINE self._x509, digest, result_buffer, result_length)NEWLINENEWLINE if not digest_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return b":".join([NEWLINE b16encode(ch).upper() for chNEWLINE in _ffi.buffer(result_buffer, result_length[0])])NEWLINENEWLINENEWLINE def subject_name_hash(self):NEWLINE """NEWLINE Return the hash of the X509 subject.NEWLINENEWLINE :return: The hash of the subject.NEWLINE """NEWLINE return _lib.X509_subject_name_hash(self._x509)NEWLINENEWLINENEWLINE def set_serial_number(self, serial):NEWLINE """NEWLINE Set serial number of the certificateNEWLINENEWLINE :param serial: The serial numberNEWLINE :type serial: :py:class:`int`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(serial, _integer_types):NEWLINE raise TypeError("serial must be an integer")NEWLINENEWLINE hex_serial = hex(serial)[2:]NEWLINE if not isinstance(hex_serial, bytes):NEWLINE hex_serial = hex_serial.encode('ascii')NEWLINENEWLINE bignum_serial = _ffi.new("BIGNUM**")NEWLINENEWLINE # BN_hex2bn stores the result in &bignum. Unless it doesn't feel likeNEWLINE # it. If bignum is still NULL after this call, then the return value isNEWLINE # actually the result. I hope. -exarkunNEWLINE small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)NEWLINENEWLINE if bignum_serial[0] == _ffi.NULL:NEWLINE set_result = _lib.ASN1_INTEGER_set(NEWLINE _lib.X509_get_serialNumber(self._x509), small_serial)NEWLINE if set_result:NEWLINE # TODO Not testedNEWLINE _raise_current_error()NEWLINE else:NEWLINE asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)NEWLINE _lib.BN_free(bignum_serial[0])NEWLINE if asn1_serial == _ffi.NULL:NEWLINE # TODO Not testedNEWLINE _raise_current_error()NEWLINE asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)NEWLINE set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)NEWLINE if not set_result:NEWLINE # TODO Not testedNEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_serial_number(self):NEWLINE """NEWLINE Return serial number of the certificateNEWLINENEWLINE :return: Serial number as a Python integerNEWLINE """NEWLINE asn1_serial = _lib.X509_get_serialNumber(self._x509)NEWLINE bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)NEWLINE try:NEWLINE hex_serial = _lib.BN_bn2hex(bignum_serial)NEWLINE try:NEWLINE hexstring_serial = _ffi.string(hex_serial)NEWLINE serial = int(hexstring_serial, 16)NEWLINE return serialNEWLINE finally:NEWLINE _lib.OPENSSL_free(hex_serial)NEWLINE finally:NEWLINE _lib.BN_free(bignum_serial)NEWLINENEWLINENEWLINE def gmtime_adj_notAfter(self, amount):NEWLINE """NEWLINE Adjust the time stamp for when the certificate stops being validNEWLINENEWLINE :param amount: The number of seconds by which to adjust the endingNEWLINE validity time.NEWLINE :type amount: :py:class:`int`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(amount, int):NEWLINE raise TypeError("amount must be an integer")NEWLINENEWLINE notAfter = _lib.X509_get_notAfter(self._x509)NEWLINE _lib.X509_gmtime_adj(notAfter, amount)NEWLINENEWLINENEWLINE def gmtime_adj_notBefore(self, amount):NEWLINE """NEWLINE Change the timestamp for when the certificate starts being valid to the currentNEWLINE time plus an offset.NEWLINENEWLINE :param amount: The number of seconds by which to adjust the starting validityNEWLINE time.NEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(amount, int):NEWLINE raise TypeError("amount must be an integer")NEWLINENEWLINE notBefore = _lib.X509_get_notBefore(self._x509)NEWLINE _lib.X509_gmtime_adj(notBefore, amount)NEWLINENEWLINENEWLINE def has_expired(self):NEWLINE """NEWLINE Check whether the certificate has expired.NEWLINENEWLINE :return: True if the certificate has expired, false otherwiseNEWLINE """NEWLINE now = int(time())NEWLINE notAfter = _lib.X509_get_notAfter(self._x509)NEWLINE return _lib.ASN1_UTCTIME_cmp_time_t(NEWLINE _ffi.cast('ASN1_UTCTIME*', notAfter), now) < 0NEWLINENEWLINENEWLINE def _get_boundary_time(self, which):NEWLINE return _get_asn1_time(which(self._x509))NEWLINENEWLINENEWLINE def get_notBefore(self):NEWLINE """NEWLINE Retrieve the time stamp for when the certificate starts being validNEWLINENEWLINE :return: A string giving the timestamp, in the format::NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINENEWLINE or None if there is no value set.NEWLINE """NEWLINE return self._get_boundary_time(_lib.X509_get_notBefore)NEWLINENEWLINENEWLINE def _set_boundary_time(self, which, when):NEWLINE return _set_asn1_time(which(self._x509), when)NEWLINENEWLINENEWLINE def set_notBefore(self, when):NEWLINE """NEWLINE Set the time stamp for when the certificate starts being validNEWLINENEWLINE :param when: A string giving the timestamp, in the format:NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINE :type when: :py:class:`bytes`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return self._set_boundary_time(_lib.X509_get_notBefore, when)NEWLINENEWLINENEWLINE def get_notAfter(self):NEWLINE """NEWLINE Retrieve the time stamp for when the certificate stops being validNEWLINENEWLINE :return: A string giving the timestamp, in the format::NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINENEWLINE or None if there is no value set.NEWLINE """NEWLINE return self._get_boundary_time(_lib.X509_get_notAfter)NEWLINENEWLINENEWLINE def set_notAfter(self, when):NEWLINE """NEWLINE Set the time stamp for when the certificate stops being validNEWLINENEWLINE :param when: A string giving the timestamp, in the format:NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINE :type when: :py:class:`bytes`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return self._set_boundary_time(_lib.X509_get_notAfter, when)NEWLINENEWLINENEWLINE def _get_name(self, which):NEWLINE name = X509Name.__new__(X509Name)NEWLINE name._name = which(self._x509)NEWLINE if name._name == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE # The name is owned by the X509 structure. As long as the X509NameNEWLINE # Python object is alive, keep the X509 Python object alive.NEWLINE name._owner = selfNEWLINENEWLINE return nameNEWLINENEWLINENEWLINE def _set_name(self, which, name):NEWLINE if not isinstance(name, X509Name):NEWLINE raise TypeError("name must be an X509Name")NEWLINE set_result = which(self._x509, name._name)NEWLINE if not set_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_issuer(self):NEWLINE """NEWLINE Create an X509Name object for the issuer of the certificateNEWLINENEWLINE :return: An X509Name objectNEWLINE """NEWLINE return self._get_name(_lib.X509_get_issuer_name)NEWLINENEWLINENEWLINE def set_issuer(self, issuer):NEWLINE """NEWLINE Set the issuer of the certificateNEWLINENEWLINE :param issuer: The issuer nameNEWLINE :type issuer: :py:class:`X509Name`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return self._set_name(_lib.X509_set_issuer_name, issuer)NEWLINENEWLINENEWLINE def get_subject(self):NEWLINE """NEWLINE Create an X509Name object for the subject of the certificateNEWLINENEWLINE :return: An X509Name objectNEWLINE """NEWLINE return self._get_name(_lib.X509_get_subject_name)NEWLINENEWLINENEWLINE def set_subject(self, subject):NEWLINE """NEWLINE Set the subject of the certificateNEWLINENEWLINE :param subject: The subject nameNEWLINE :type subject: :py:class:`X509Name`NEWLINE :return: NoneNEWLINE """NEWLINE return self._set_name(_lib.X509_set_subject_name, subject)NEWLINENEWLINENEWLINE def get_extension_count(self):NEWLINE """NEWLINE Get the number of extensions on the certificate.NEWLINENEWLINE :return: The number of extensions as an integer.NEWLINE """NEWLINE return _lib.X509_get_ext_count(self._x509)NEWLINENEWLINENEWLINE def add_extensions(self, extensions):NEWLINE """NEWLINE Add extensions to the certificate.NEWLINENEWLINE :param extensions: a sequence of X509Extension objectsNEWLINE :return: NoneNEWLINE """NEWLINE for ext in extensions:NEWLINE if not isinstance(ext, X509Extension):NEWLINE raise ValueError("One of the elements is not an X509Extension")NEWLINENEWLINE add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)NEWLINE if not add_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_extension(self, index):NEWLINE """NEWLINE Get a specific extension of the certificate by index.NEWLINENEWLINE :param index: The index of the extension to retrieve.NEWLINE :return: The X509Extension object at the specified index.NEWLINE """NEWLINE ext = X509Extension.__new__(X509Extension)NEWLINE ext._extension = _lib.X509_get_ext(self._x509, index)NEWLINE if ext._extension == _ffi.NULL:NEWLINE raise IndexError("extension index out of bounds")NEWLINENEWLINE extension = _lib.X509_EXTENSION_dup(ext._extension)NEWLINE ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)NEWLINE return extNEWLINENEWLINEX509Type = X509NEWLINENEWLINENEWLINENEWLINEclass X509Store(object):NEWLINE def __init__(self):NEWLINE store = _lib.X509_STORE_new()NEWLINE self._store = _ffi.gc(store, _lib.X509_STORE_free)NEWLINENEWLINENEWLINE def add_cert(self, cert):NEWLINE if not isinstance(cert, X509):NEWLINE raise TypeError()NEWLINENEWLINE result = _lib.X509_STORE_add_cert(self._store, cert._x509)NEWLINE if not result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINEX509StoreType = X509StoreNEWLINENEWLINENEWLINENEWLINEdef load_certificate(type, buffer):NEWLINE """NEWLINE Load a certificate from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINENEWLINE :param buffer: The buffer the certificate is stored inNEWLINE :type buffer: :py:class:`bytes`NEWLINENEWLINE :return: The X509 objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE elif type == FILETYPE_ASN1:NEWLINE x509 = _lib.d2i_X509_bio(bio, _ffi.NULL);NEWLINE else:NEWLINE raise ValueError(NEWLINE "type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if x509 == _ffi.NULL:NEWLINE _raise_current_error()NEWLINENEWLINE cert = X509.__new__(X509)NEWLINE cert._x509 = _ffi.gc(x509, _lib.X509_free)NEWLINE return certNEWLINENEWLINENEWLINEdef dump_certificate(type, cert):NEWLINE """NEWLINE Dump a certificate to a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, orNEWLINE FILETYPE_TEXT)NEWLINE :param cert: The certificate to dumpNEWLINE :return: The buffer with the dumped certificate inNEWLINE """NEWLINE bio = _new_mem_buf()NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE result_code = _lib.PEM_write_bio_X509(bio, cert._x509)NEWLINE elif type == FILETYPE_ASN1:NEWLINE result_code = _lib.i2d_X509_bio(bio, cert._x509)NEWLINE elif type == FILETYPE_TEXT:NEWLINE result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)NEWLINE else:NEWLINE raise ValueError(NEWLINE "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "NEWLINE "FILETYPE_TEXT")NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINENEWLINEdef dump_privatekey(type, pkey, cipher=None, passphrase=None):NEWLINE """NEWLINE Dump a private key to a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, orNEWLINE FILETYPE_TEXT)NEWLINE :param pkey: The PKey to dumpNEWLINE :param cipher: (optional) if encrypted PEM format, the cipher toNEWLINE useNEWLINE :param passphrase: (optional) if encrypted PEM format, this can be eitherNEWLINE the passphrase to use, or a callback for providing theNEWLINE passphrase.NEWLINE :return: The buffer with the dumped key inNEWLINE :rtype: :py:data:`str`NEWLINE """NEWLINE bio = _new_mem_buf()NEWLINENEWLINE if cipher is not None:NEWLINE if passphrase is None:NEWLINE raise TypeError(NEWLINE "if a value is given for cipher "NEWLINE "one must also be given for passphrase")NEWLINE cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))NEWLINE if cipher_obj == _ffi.NULL:NEWLINE raise ValueError("Invalid cipher name")NEWLINE else:NEWLINE cipher_obj = _ffi.NULLNEWLINENEWLINE helper = _PassphraseHelper(type, passphrase)NEWLINE if type == FILETYPE_PEM:NEWLINE result_code = _lib.PEM_write_bio_PrivateKey(NEWLINE bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,NEWLINE helper.callback, helper.callback_args)NEWLINE helper.raise_if_problem()NEWLINE elif type == FILETYPE_ASN1:NEWLINE result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)NEWLINE elif type == FILETYPE_TEXT:NEWLINE rsa = _lib.EVP_PKEY_get1_RSA(pkey._pkey)NEWLINE result_code = _lib.RSA_print(bio, rsa, 0)NEWLINE # TODO RSA_free(rsa)?NEWLINE else:NEWLINE raise ValueError(NEWLINE "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "NEWLINE "FILETYPE_TEXT")NEWLINENEWLINE if result_code == 0:NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINENEWLINEdef _X509_REVOKED_dup(original):NEWLINE copy = _lib.X509_REVOKED_new()NEWLINE if copy == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE if original.serialNumber != _ffi.NULL:NEWLINE copy.serialNumber = _lib.ASN1_INTEGER_dup(original.serialNumber)NEWLINENEWLINE if original.revocationDate != _ffi.NULL:NEWLINE copy.revocationDate = _lib.M_ASN1_TIME_dup(original.revocationDate)NEWLINENEWLINE if original.extensions != _ffi.NULL:NEWLINE extension_stack = _lib.sk_X509_EXTENSION_new_null()NEWLINE for i in range(_lib.sk_X509_EXTENSION_num(original.extensions)):NEWLINE original_ext = _lib.sk_X509_EXTENSION_value(original.extensions, i)NEWLINE copy_ext = _lib.X509_EXTENSION_dup(original_ext)NEWLINE _lib.sk_X509_EXTENSION_push(extension_stack, copy_ext)NEWLINE copy.extensions = extension_stackNEWLINENEWLINE copy.sequence = original.sequenceNEWLINE return copyNEWLINENEWLINENEWLINENEWLINEclass Revoked(object):NEWLINE # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_NEWLINE # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matchesNEWLINE # OCSP_crl_reason_str. We use the latter, just like the command lineNEWLINE # program.NEWLINE _crl_reasons = [NEWLINE b"unspecified",NEWLINE b"keyCompromise",NEWLINE b"CACompromise",NEWLINE b"affiliationChanged",NEWLINE b"superseded",NEWLINE b"cessationOfOperation",NEWLINE b"certificateHold",NEWLINE # b"removeFromCRL",NEWLINE ]NEWLINENEWLINE def __init__(self):NEWLINE revoked = _lib.X509_REVOKED_new()NEWLINE self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)NEWLINENEWLINENEWLINE def set_serial(self, hex_str):NEWLINE """NEWLINE Set the serial number of a revoked Revoked structureNEWLINENEWLINE :param hex_str: The new serial number.NEWLINE :type hex_str: :py:data:`str`NEWLINE :return: NoneNEWLINE """NEWLINE bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)NEWLINE bignum_ptr = _ffi.new("BIGNUM**")NEWLINE bignum_ptr[0] = bignum_serialNEWLINE bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)NEWLINE if not bn_result:NEWLINE raise ValueError("bad hex string")NEWLINENEWLINE asn1_serial = _ffi.gc(NEWLINE _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),NEWLINE _lib.ASN1_INTEGER_free)NEWLINE _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)NEWLINENEWLINENEWLINE def get_serial(self):NEWLINE """NEWLINE Return the serial number of a Revoked structureNEWLINENEWLINE :return: The serial number as a stringNEWLINE """NEWLINE bio = _new_mem_buf()NEWLINENEWLINE result = _lib.i2a_ASN1_INTEGER(bio, self._revoked.serialNumber)NEWLINE if result < 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINE def _delete_reason(self):NEWLINE stack = self._revoked.extensionsNEWLINE for i in range(_lib.sk_X509_EXTENSION_num(stack)):NEWLINE ext = _lib.sk_X509_EXTENSION_value(stack, i)NEWLINE if _lib.OBJ_obj2nid(ext.object) == _lib.NID_crl_reason:NEWLINE _lib.X509_EXTENSION_free(ext)NEWLINE _lib.sk_X509_EXTENSION_delete(stack, i)NEWLINE breakNEWLINENEWLINENEWLINE def set_reason(self, reason):NEWLINE """NEWLINE Set the reason of a Revoked object.NEWLINENEWLINE If :py:data:`reason` is :py:data:`None`, delete the reason instead.NEWLINENEWLINE :param reason: The reason string.NEWLINE :type reason: :py:class:`str` or :py:class:`NoneType`NEWLINE :return: NoneNEWLINE """NEWLINE if reason is None:NEWLINE self._delete_reason()NEWLINE elif not isinstance(reason, bytes):NEWLINE raise TypeError("reason must be None or a byte string")NEWLINE else:NEWLINE reason = reason.lower().replace(b' ', b'')NEWLINE reason_code = [r.lower() for r in self._crl_reasons].index(reason)NEWLINENEWLINE new_reason_ext = _lib.ASN1_ENUMERATED_new()NEWLINE if new_reason_ext == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)NEWLINENEWLINE set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)NEWLINE if set_result == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE self._delete_reason()NEWLINE add_result = _lib.X509_REVOKED_add1_ext_i2d(NEWLINE self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)NEWLINENEWLINE if not add_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_reason(self):NEWLINE """NEWLINE Return the reason of a Revoked object.NEWLINENEWLINE :return: The reason as a stringNEWLINE """NEWLINE extensions = self._revoked.extensionsNEWLINE for i in range(_lib.sk_X509_EXTENSION_num(extensions)):NEWLINE ext = _lib.sk_X509_EXTENSION_value(extensions, i)NEWLINE if _lib.OBJ_obj2nid(ext.object) == _lib.NID_crl_reason:NEWLINE bio = _new_mem_buf()NEWLINENEWLINE print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)NEWLINE if not print_result:NEWLINE print_result = _lib.M_ASN1_OCTET_STRING_print(bio, ext.value)NEWLINE if print_result == 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINE def all_reasons(self):NEWLINE """NEWLINE Return a list of all the supported reason strings.NEWLINENEWLINE :return: A list of reason strings.NEWLINE """NEWLINE return self._crl_reasons[:]NEWLINENEWLINENEWLINE def set_rev_date(self, when):NEWLINE """NEWLINE Set the revocation timestampNEWLINENEWLINE :param when: A string giving the timestamp, in the format:NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return _set_asn1_time(self._revoked.revocationDate, when)NEWLINENEWLINENEWLINE def get_rev_date(self):NEWLINE """NEWLINE Retrieve the revocation dateNEWLINENEWLINE :return: A string giving the timestamp, in the format:NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINE """NEWLINE return _get_asn1_time(self._revoked.revocationDate)NEWLINENEWLINENEWLINENEWLINEclass CRL(object):NEWLINE def __init__(self):NEWLINE """NEWLINE Create a new empty CRL object.NEWLINE """NEWLINE crl = _lib.X509_CRL_new()NEWLINE self._crl = _ffi.gc(crl, _lib.X509_CRL_free)NEWLINENEWLINENEWLINE def get_revoked(self):NEWLINE """NEWLINE Return revoked portion of the CRL structure (by value not reference).NEWLINENEWLINE :return: A tuple of Revoked objects.NEWLINE """NEWLINE results = []NEWLINE revoked_stack = self._crl.crl.revokedNEWLINE for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):NEWLINE revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)NEWLINE revoked_copy = _X509_REVOKED_dup(revoked)NEWLINE pyrev = Revoked.__new__(Revoked)NEWLINE pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)NEWLINE results.append(pyrev)NEWLINE if results:NEWLINE return tuple(results)NEWLINENEWLINENEWLINE def add_revoked(self, revoked):NEWLINE """NEWLINE Add a revoked (by value not reference) to the CRL structureNEWLINENEWLINE :param revoked: The new revoked.NEWLINE :type revoked: :class:`X509`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE copy = _X509_REVOKED_dup(revoked._revoked)NEWLINE if copy == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)NEWLINE if add_result == 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def export(self, cert, key, type=FILETYPE_PEM, days=100):NEWLINE """NEWLINE export a CRL as a stringNEWLINENEWLINE :param cert: Used to sign CRL.NEWLINE :type cert: :class:`X509`NEWLINENEWLINE :param key: Used to sign CRL.NEWLINE :type key: :class:`PKey`NEWLINENEWLINE :param type: The export format, either :py:data:`FILETYPE_PEM`, :py:data:`FILETYPE_ASN1`, or :py:data:`FILETYPE_TEXT`.NEWLINENEWLINE :param days: The number of days until the next update of this CRL.NEWLINE :type days: :py:data:`int`NEWLINENEWLINE :return: :py:data:`str`NEWLINE """NEWLINE if not isinstance(cert, X509):NEWLINE raise TypeError("cert must be an X509 instance")NEWLINE if not isinstance(key, PKey):NEWLINE raise TypeError("key must be a PKey instance")NEWLINE if not isinstance(type, int):NEWLINE raise TypeError("type must be an integer")NEWLINENEWLINE bio = _lib.BIO_new(_lib.BIO_s_mem())NEWLINE if bio == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE # A scratch time object to give different values to different CRL fieldsNEWLINE sometime = _lib.ASN1_TIME_new()NEWLINE if sometime == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE _lib.X509_gmtime_adj(sometime, 0)NEWLINE _lib.X509_CRL_set_lastUpdate(self._crl, sometime)NEWLINENEWLINE _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)NEWLINE _lib.X509_CRL_set_nextUpdate(self._crl, sometime)NEWLINENEWLINE _lib.X509_CRL_set_issuer_name(self._crl, _lib.X509_get_subject_name(cert._x509))NEWLINENEWLINE sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, _lib.EVP_md5())NEWLINE if not sign_result:NEWLINE _raise_current_error()NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE ret = _lib.PEM_write_bio_X509_CRL(bio, self._crl)NEWLINE elif type == FILETYPE_ASN1:NEWLINE ret = _lib.i2d_X509_CRL_bio(bio, self._crl)NEWLINE elif type == FILETYPE_TEXT:NEWLINE ret = _lib.X509_CRL_print(bio, self._crl)NEWLINE else:NEWLINE raise ValueError(NEWLINE "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT")NEWLINENEWLINE if not ret:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINECRLType = CRLNEWLINENEWLINENEWLINENEWLINEclass PKCS7(object):NEWLINE def type_is_signed(self):NEWLINE """NEWLINE Check if this NID_pkcs7_signed objectNEWLINENEWLINE :return: True if the PKCS7 is of type signedNEWLINE """NEWLINE if _lib.PKCS7_type_is_signed(self._pkcs7):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE def type_is_enveloped(self):NEWLINE """NEWLINE Check if this NID_pkcs7_enveloped objectNEWLINENEWLINE :returns: True if the PKCS7 is of type envelopedNEWLINE """NEWLINE if _lib.PKCS7_type_is_enveloped(self._pkcs7):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE def type_is_signedAndEnveloped(self):NEWLINE """NEWLINE Check if this NID_pkcs7_signedAndEnveloped objectNEWLINENEWLINE :returns: True if the PKCS7 is of type signedAndEnvelopedNEWLINE """NEWLINE if _lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE def type_is_data(self):NEWLINE """NEWLINE Check if this NID_pkcs7_data objectNEWLINENEWLINE :return: True if the PKCS7 is of type dataNEWLINE """NEWLINE if _lib.PKCS7_type_is_data(self._pkcs7):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE def get_type_name(self):NEWLINE """NEWLINE Returns the type name of the PKCS7 structureNEWLINENEWLINE :return: A string with the typenameNEWLINE """NEWLINE nid = _lib.OBJ_obj2nid(self._pkcs7.type)NEWLINE string_type = _lib.OBJ_nid2sn(nid)NEWLINE return _ffi.string(string_type)NEWLINENEWLINEPKCS7Type = PKCS7NEWLINENEWLINENEWLINENEWLINEclass PKCS12(object):NEWLINE def __init__(self):NEWLINE self._pkey = NoneNEWLINE self._cert = NoneNEWLINE self._cacerts = NoneNEWLINE self._friendlyname = NoneNEWLINENEWLINENEWLINE def get_certificate(self):NEWLINE """NEWLINE Return certificate portion of the PKCS12 structureNEWLINENEWLINE :return: X509 object containing the certificateNEWLINE """NEWLINE return self._certNEWLINENEWLINENEWLINE def set_certificate(self, cert):NEWLINE """NEWLINE Replace the certificate portion of the PKCS12 structureNEWLINENEWLINE :param cert: The new certificate.NEWLINE :type cert: :py:class:`X509` or :py:data:`None`NEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(cert, X509):NEWLINE raise TypeError("cert must be an X509 instance")NEWLINE self._cert = certNEWLINENEWLINENEWLINE def get_privatekey(self):NEWLINE """NEWLINE Return private key portion of the PKCS12 structureNEWLINENEWLINE :returns: PKey object containing the private keyNEWLINE """NEWLINE return self._pkeyNEWLINENEWLINENEWLINE def set_privatekey(self, pkey):NEWLINE """NEWLINE Replace or set the certificate portion of the PKCS12 structureNEWLINENEWLINE :param pkey: The new private key.NEWLINE :type pkey: :py:class:`PKey`NEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(pkey, PKey):NEWLINE raise TypeError("pkey must be a PKey instance")NEWLINE self._pkey = pkeyNEWLINENEWLINENEWLINE def get_ca_certificates(self):NEWLINE """NEWLINE Return CA certificates within of the PKCS12 objectNEWLINENEWLINE :return: A newly created tuple containing the CA certificates in the chain,NEWLINE if any are present, or None if no CA certificates are present.NEWLINE """NEWLINE if self._cacerts is not None:NEWLINE return tuple(self._cacerts)NEWLINENEWLINENEWLINE def set_ca_certificates(self, cacerts):NEWLINE """NEWLINE Replace or set the CA certificates withing the PKCS12 object.NEWLINENEWLINE :param cacerts: The new CA certificates.NEWLINE :type cacerts: :py:data:`None` or an iterable of :py:class:`X509`NEWLINE :return: NoneNEWLINE """NEWLINE if cacerts is None:NEWLINE self._cacerts = NoneNEWLINE else:NEWLINE cacerts = list(cacerts)NEWLINE for cert in cacerts:NEWLINE if not isinstance(cert, X509):NEWLINE raise TypeError("iterable must only contain X509 instances")NEWLINE self._cacerts = cacertsNEWLINENEWLINENEWLINE def set_friendlyname(self, name):NEWLINE """NEWLINE Replace or set the certificate portion of the PKCS12 structureNEWLINENEWLINE :param name: The new friendly name.NEWLINE :type name: :py:class:`bytes`NEWLINE :return: NoneNEWLINE """NEWLINE if name is None:NEWLINE self._friendlyname = NoneNEWLINE elif not isinstance(name, bytes):NEWLINE raise TypeError("name must be a byte string or None (not %r)" % (name,))NEWLINE self._friendlyname = nameNEWLINENEWLINENEWLINE def get_friendlyname(self):NEWLINE """NEWLINE Return friendly name portion of the PKCS12 structureNEWLINENEWLINE :returns: String containing the friendlynameNEWLINE """NEWLINE return self._friendlynameNEWLINENEWLINENEWLINE def export(self, passphrase=None, iter=2048, maciter=1):NEWLINE """NEWLINE Dump a PKCS12 object as a string. See also "man PKCS12_create".NEWLINENEWLINE :param passphrase: used to encrypt the PKCS12NEWLINE :type passphrase: :py:data:`bytes`NEWLINENEWLINE :param iter: How many times to repeat the encryptionNEWLINE :type iter: :py:data:`int`NEWLINENEWLINE :param maciter: How many times to repeat the MACNEWLINE :type maciter: :py:data:`int`NEWLINENEWLINE :return: The string containing the PKCS12NEWLINE """NEWLINE if self._cacerts is None:NEWLINE cacerts = _ffi.NULLNEWLINE else:NEWLINE cacerts = _lib.sk_X509_new_null()NEWLINE cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)NEWLINE for cert in self._cacerts:NEWLINE _lib.sk_X509_push(cacerts, cert._x509)NEWLINENEWLINE if passphrase is None:NEWLINE passphrase = _ffi.NULLNEWLINENEWLINE friendlyname = self._friendlynameNEWLINE if friendlyname is None:NEWLINE friendlyname = _ffi.NULLNEWLINENEWLINE if self._pkey is None:NEWLINE pkey = _ffi.NULLNEWLINE else:NEWLINE pkey = self._pkey._pkeyNEWLINENEWLINE if self._cert is None:NEWLINE cert = _ffi.NULLNEWLINE else:NEWLINE cert = self._cert._x509NEWLINENEWLINE pkcs12 = _lib.PKCS12_create(NEWLINE passphrase, friendlyname, pkey, cert, cacerts,NEWLINE _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,NEWLINE _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,NEWLINE iter, maciter, 0)NEWLINE if pkcs12 == _ffi.NULL:NEWLINE _raise_current_error()NEWLINE pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)NEWLINENEWLINE bio = _new_mem_buf()NEWLINE _lib.i2d_PKCS12_bio(bio, pkcs12)NEWLINE return _bio_to_string(bio)NEWLINENEWLINEPKCS12Type = PKCS12NEWLINENEWLINENEWLINENEWLINEclass NetscapeSPKI(object):NEWLINE def __init__(self):NEWLINE spki = _lib.NETSCAPE_SPKI_new()NEWLINE self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)NEWLINENEWLINENEWLINE def sign(self, pkey, digest):NEWLINE """NEWLINE Sign the certificate request using the supplied key and digestNEWLINENEWLINE :param pkey: The key to sign withNEWLINE :param digest: The message digest to useNEWLINE :return: NoneNEWLINE """NEWLINE if pkey._only_public:NEWLINE raise ValueError("Key has only public part")NEWLINENEWLINE if not pkey._initialized:NEWLINE raise ValueError("Key is uninitialized")NEWLINENEWLINE digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if digest_obj == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE sign_result = _lib.NETSCAPE_SPKI_sign(self._spki, pkey._pkey, digest_obj)NEWLINE if not sign_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def verify(self, key):NEWLINE """NEWLINE Verifies a certificate request using the supplied public keyNEWLINENEWLINE :param key: a public keyNEWLINE :return: True if the signature is correct.NEWLINE :raise OpenSSL.crypto.Error: If the signature is invalid or there is aNEWLINE problem verifying the signature.NEWLINE """NEWLINE answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)NEWLINE if answer <= 0:NEWLINE _raise_current_error()NEWLINE return TrueNEWLINENEWLINENEWLINE def b64_encode(self):NEWLINE """NEWLINE Generate a base64 encoded string from an SPKINEWLINENEWLINE :return: The base64 encoded stringNEWLINE """NEWLINE encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)NEWLINE result = _ffi.string(encoded)NEWLINE _lib.CRYPTO_free(encoded)NEWLINE return resultNEWLINENEWLINENEWLINE def get_pubkey(self):NEWLINE """NEWLINE Get the public key of the certificateNEWLINENEWLINE :return: The public keyNEWLINE """NEWLINE pkey = PKey.__new__(PKey)NEWLINE pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)NEWLINE if pkey._pkey == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)NEWLINE pkey._only_public = TrueNEWLINE return pkeyNEWLINENEWLINENEWLINE def set_pubkey(self, pkey):NEWLINE """NEWLINE Set the public key of the certificateNEWLINENEWLINE :param pkey: The public keyNEWLINE :return: NoneNEWLINE """NEWLINE set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)NEWLINE if not set_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENetscapeSPKIType = NetscapeSPKINEWLINENEWLINENEWLINEclass _PassphraseHelper(object):NEWLINE def __init__(self, type, passphrase, more_args=False, truncate=False):NEWLINE if type != FILETYPE_PEM and passphrase is not None:NEWLINE raise ValueError("only FILETYPE_PEM key format supports encryption")NEWLINE self._passphrase = passphraseNEWLINE self._more_args = more_argsNEWLINE self._truncate = truncateNEWLINE self._problems = []NEWLINENEWLINENEWLINE @propertyNEWLINE def callback(self):NEWLINE if self._passphrase is None:NEWLINE return _ffi.NULLNEWLINE elif isinstance(self._passphrase, bytes):NEWLINE return _ffi.NULLNEWLINE elif callable(self._passphrase):NEWLINE return _ffi.callback("pem_password_cb", self._read_passphrase)NEWLINE else:NEWLINE raise TypeError("Last argument must be string or callable")NEWLINENEWLINENEWLINE @propertyNEWLINE def callback_args(self):NEWLINE if self._passphrase is None:NEWLINE return _ffi.NULLNEWLINE elif isinstance(self._passphrase, bytes):NEWLINE return self._passphraseNEWLINE elif callable(self._passphrase):NEWLINE return _ffi.NULLNEWLINE else:NEWLINE raise TypeError("Last argument must be string or callable")NEWLINENEWLINENEWLINE def raise_if_problem(self, exceptionType=Error):NEWLINE try:NEWLINE _exception_from_error_queue(exceptionType)NEWLINE except exceptionType as e:NEWLINE from_queue = eNEWLINE if self._problems:NEWLINE raise self._problems[0]NEWLINE return from_queueNEWLINENEWLINENEWLINE def _read_passphrase(self, buf, size, rwflag, userdata):NEWLINE try:NEWLINE if self._more_args:NEWLINE result = self._passphrase(size, rwflag, userdata)NEWLINE else:NEWLINE result = self._passphrase(rwflag)NEWLINE if not isinstance(result, bytes):NEWLINE raise ValueError("String expected")NEWLINE if len(result) > size:NEWLINE if self._truncate:NEWLINE result = result[:size]NEWLINE else:NEWLINE raise ValueError("passphrase returned by callback is too long")NEWLINE for i in range(len(result)):NEWLINE buf[i] = result[i:i + 1]NEWLINE return len(result)NEWLINE except Exception as e:NEWLINE self._problems.append(e)NEWLINE return 0NEWLINENEWLINENEWLINENEWLINEdef load_privatekey(type, buffer, passphrase=None):NEWLINE """NEWLINE Load a private key from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINE :param buffer: The buffer the key is stored inNEWLINE :param passphrase: (optional) if encrypted PEM format, this can beNEWLINE either the passphrase to use, or a callback forNEWLINE providing the passphrase.NEWLINENEWLINE :return: The PKey objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE helper = _PassphraseHelper(type, passphrase)NEWLINE if type == FILETYPE_PEM:NEWLINE evp_pkey = _lib.PEM_read_bio_PrivateKey(NEWLINE bio, _ffi.NULL, helper.callback, helper.callback_args)NEWLINE helper.raise_if_problem()NEWLINE elif type == FILETYPE_ASN1:NEWLINE evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)NEWLINE else:NEWLINE raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if evp_pkey == _ffi.NULL:NEWLINE _raise_current_error()NEWLINENEWLINE pkey = PKey.__new__(PKey)NEWLINE pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)NEWLINE return pkeyNEWLINENEWLINENEWLINENEWLINEdef dump_certificate_request(type, req):NEWLINE """NEWLINE Dump a certificate request to a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINE :param req: The certificate request to dumpNEWLINE :return: The buffer with the dumped certificate request inNEWLINE """NEWLINE bio = _new_mem_buf()NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)NEWLINE elif type == FILETYPE_ASN1:NEWLINE result_code = _lib.i2d_X509_REQ_bio(bio, req._req)NEWLINE elif type == FILETYPE_TEXT:NEWLINE result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)NEWLINE else:NEWLINE raise ValueError("type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT")NEWLINENEWLINE if result_code == 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINENEWLINEdef load_certificate_request(type, buffer):NEWLINE """NEWLINE Load a certificate request from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINE :param buffer: The buffer the certificate request is stored inNEWLINE :return: The X509Req objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE elif type == FILETYPE_ASN1:NEWLINE req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)NEWLINE else:NEWLINE raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if req == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE x509req = X509Req.__new__(X509Req)NEWLINE x509req._req = _ffi.gc(req, _lib.X509_REQ_free)NEWLINE return x509reqNEWLINENEWLINENEWLINENEWLINEdef sign(pkey, data, digest):NEWLINE """NEWLINE Sign data with a digestNEWLINENEWLINE :param pkey: Pkey to sign withNEWLINE :param data: data to be signedNEWLINE :param digest: message digest to useNEWLINE :return: signatureNEWLINE """NEWLINE digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if digest_obj == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE md_ctx = _ffi.new("EVP_MD_CTX*")NEWLINE md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup)NEWLINENEWLINE _lib.EVP_SignInit(md_ctx, digest_obj)NEWLINE _lib.EVP_SignUpdate(md_ctx, data, len(data))NEWLINENEWLINE signature_buffer = _ffi.new("unsigned char[]", 512)NEWLINE signature_length = _ffi.new("unsigned int*")NEWLINE signature_length[0] = len(signature_buffer)NEWLINE final_result = _lib.EVP_SignFinal(NEWLINE md_ctx, signature_buffer, signature_length, pkey._pkey)NEWLINENEWLINE if final_result != 1:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _ffi.buffer(signature_buffer, signature_length[0])[:]NEWLINENEWLINENEWLINENEWLINEdef verify(cert, signature, data, digest):NEWLINE """NEWLINE Verify a signatureNEWLINENEWLINE :param cert: signing certificate (X509 object)NEWLINE :param signature: signature returned by sign functionNEWLINE :param data: data to be verifiedNEWLINE :param digest: message digest to useNEWLINE :return: None if the signature is correct, raise exception otherwiseNEWLINE """NEWLINE digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if digest_obj == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE pkey = _lib.X509_get_pubkey(cert._x509)NEWLINE if pkey == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)NEWLINENEWLINE md_ctx = _ffi.new("EVP_MD_CTX*")NEWLINE md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup)NEWLINENEWLINE _lib.EVP_VerifyInit(md_ctx, digest_obj)NEWLINE _lib.EVP_VerifyUpdate(md_ctx, data, len(data))NEWLINE verify_result = _lib.EVP_VerifyFinal(md_ctx, signature, len(signature), pkey)NEWLINENEWLINE if verify_result != 1:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINENEWLINEdef load_crl(type, buffer):NEWLINE """NEWLINE Load a certificate revocation list from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINE :param buffer: The buffer the CRL is stored inNEWLINENEWLINE :return: The PKey objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE elif type == FILETYPE_ASN1:NEWLINE crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)NEWLINE else:NEWLINE raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if crl == _ffi.NULL:NEWLINE _raise_current_error()NEWLINENEWLINE result = CRL.__new__(CRL)NEWLINE result._crl = crlNEWLINE return resultNEWLINENEWLINENEWLINENEWLINEdef load_pkcs7_data(type, buffer):NEWLINE """NEWLINE Load pkcs7 data from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)NEWLINE :param buffer: The buffer with the pkcs7 data.NEWLINE :return: The PKCS7 objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE elif type == FILETYPE_ASN1:NEWLINE passNEWLINE else:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if pkcs7 == _ffi.NULL:NEWLINE _raise_current_error()NEWLINENEWLINE pypkcs7 = PKCS7.__new__(PKCS7)NEWLINE pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)NEWLINE return pypkcs7NEWLINENEWLINENEWLINENEWLINEdef load_pkcs12(buffer, passphrase):NEWLINE """NEWLINE Load a PKCS12 object from a bufferNEWLINENEWLINE :param buffer: The buffer the certificate is stored inNEWLINE :param passphrase: (Optional) The password to decrypt the PKCS12 lumpNEWLINE :returns: The PKCS12 objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)NEWLINE if p12 == _ffi.NULL:NEWLINE _raise_current_error()NEWLINE p12 = _ffi.gc(p12, _lib.PKCS12_free)NEWLINENEWLINE pkey = _ffi.new("EVP_PKEY**")NEWLINE cert = _ffi.new("X509**")NEWLINE cacerts = _ffi.new("Cryptography_STACK_OF_X509**")NEWLINENEWLINE parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)NEWLINE if not parse_result:NEWLINE _raise_current_error()NEWLINENEWLINE cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)NEWLINENEWLINE # openssl 1.0.0 sometimes leaves an X509_check_private_key error in theNEWLINE # queue for no particular reason. This error isn't interesting to anyoneNEWLINE # outside this function. It's not even interesting to us. Get rid of it.NEWLINE try:NEWLINE _raise_current_error()NEWLINE except Error:NEWLINE passNEWLINENEWLINE if pkey[0] == _ffi.NULL:NEWLINE pykey = NoneNEWLINE else:NEWLINE pykey = PKey.__new__(PKey)NEWLINE pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)NEWLINENEWLINE if cert[0] == _ffi.NULL:NEWLINE pycert = NoneNEWLINE friendlyname = NoneNEWLINE else:NEWLINE pycert = X509.__new__(X509)NEWLINE pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)NEWLINENEWLINE friendlyname_length = _ffi.new("int*")NEWLINE friendlyname_buffer = _lib.X509_alias_get0(cert[0], friendlyname_length)NEWLINE friendlyname = _ffi.buffer(friendlyname_buffer, friendlyname_length[0])[:]NEWLINE if friendlyname_buffer == _ffi.NULL:NEWLINE friendlyname = NoneNEWLINENEWLINE pycacerts = []NEWLINE for i in range(_lib.sk_X509_num(cacerts)):NEWLINE pycacert = X509.__new__(X509)NEWLINE pycacert._x509 = _lib.sk_X509_value(cacerts, i)NEWLINE pycacerts.append(pycacert)NEWLINE if not pycacerts:NEWLINE pycacerts = NoneNEWLINENEWLINE pkcs12 = PKCS12.__new__(PKCS12)NEWLINE pkcs12._pkey = pykeyNEWLINE pkcs12._cert = pycertNEWLINE pkcs12._cacerts = pycacertsNEWLINE pkcs12._friendlyname = friendlynameNEWLINE return pkcs12NEWLINENEWLINENEWLINEdef _initialize_openssl_threads(get_ident, Lock):NEWLINE import _sslNEWLINE returnNEWLINENEWLINE locks = list(Lock() for n in range(_lib.CRYPTO_num_locks()))NEWLINENEWLINE def locking_function(mode, index, filename, line):NEWLINE if mode & _lib.CRYPTO_LOCK:NEWLINE locks[index].acquire()NEWLINE else:NEWLINE locks[index].release()NEWLINENEWLINE _lib.CRYPTO_set_id_callback(NEWLINE _ffi.callback("unsigned long (*)(void)", get_ident))NEWLINENEWLINE _lib.CRYPTO_set_locking_callback(NEWLINE _ffi.callback(NEWLINE "void (*)(int, int, const char*, int)", locking_function))NEWLINENEWLINENEWLINEtry:NEWLINE from thread import get_identNEWLINE from threading import LockNEWLINEexcept ImportError:NEWLINE passNEWLINEelse:NEWLINE _initialize_openssl_threads(get_ident, Lock)NEWLINE del get_ident, LockNEWLINENEWLINE# There are no direct unit tests for this initialization. It is testedNEWLINE# indirectly since it is necessary for functions like dump_privatekey whenNEWLINE# using encryption.NEWLINE#NEWLINE# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphraseNEWLINE# and some other similar tests may fail without this (though they may not ifNEWLINE# the Python runtime has already done some initialization of the underlyingNEWLINE# OpenSSL library (and is linked against the same one that cryptography isNEWLINE# using)).NEWLINE_lib.OpenSSL_add_all_algorithms()NEWLINENEWLINE# This is similar but exercised mainly by exception_from_error_queue. It callsNEWLINE# both ERR_load_crypto_strings() and ERR_load_SSL_strings().NEWLINE_lib.SSL_load_error_strings()NEWLINE from game.combat.effects.moveeffect.basemoveeffect import BaseMoveEffectNEWLINEfrom game.combat.effects.partialeffect.applystatuseffect import ApplyStatusNEWLINEfrom game.combat.effects import statuseffectNEWLINENEWLINENEWLINEclass Confusion(BaseMoveEffect):NEWLINE def after_action(self):NEWLINE if self.scene.board.random_roll(self.move.chance):NEWLINE ApplyStatus(self.scene, statuseffect.CONFUSION, self.move.user, self.move.target).apply()NEWLINE return True, False, FalseNEWLINE NEWLINE# This file helps to compute a version number in source trees obtained fromNEWLINE# git-archive tarball (such as those provided by githubs download-from-tagNEWLINE# feature). Distribution tarballs (built by setup.py sdist) and buildNEWLINE# directories (produced by setup.py build) will contain a much shorter fileNEWLINE# that just contains the computed version number.NEWLINENEWLINE# This file is released into the public domain. Generated byNEWLINE# versioneer-0.18 (https://github.com/warner/python-versioneer)NEWLINENEWLINE"""Git implementation of _version.py."""NEWLINENEWLINEimport errnoNEWLINEimport osNEWLINEimport reNEWLINEimport subprocessNEWLINEimport sysNEWLINENEWLINENEWLINEdef get_keywords():NEWLINE """Get the keywords needed to look up the version information."""NEWLINE # these strings will be replaced by git during git-archive.NEWLINE # setup.py/versioneer.py will grep for the variable names, so they mustNEWLINE # each be defined on a line of their own. _version.py will just callNEWLINE # get_keywords().NEWLINE git_refnames = "$Format:%d$"NEWLINE git_full = "$Format:%H$"NEWLINE git_date = "$Format:%ci$"NEWLINE keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}NEWLINE return keywordsNEWLINENEWLINENEWLINEclass VersioneerConfig:NEWLINE """Container for Versioneer configuration parameters."""NEWLINENEWLINENEWLINEdef get_config():NEWLINE """Create, populate and return the VersioneerConfig() object."""NEWLINE # these strings are filled in when 'setup.py versioneer' createsNEWLINE # _version.pyNEWLINE cfg = VersioneerConfig()NEWLINE cfg.VCS = "git"NEWLINE cfg.style = ""NEWLINE cfg.tag_prefix = ""NEWLINE cfg.parentdir_prefix = "magic-wormhole-mailbox-server"NEWLINE cfg.versionfile_source = "src/wormhole_mailbox_server/_version.py"NEWLINE cfg.verbose = FalseNEWLINE return cfgNEWLINENEWLINENEWLINEclass NotThisMethod(Exception):NEWLINE """Exception raised if a method is not valid for the current scenario."""NEWLINENEWLINENEWLINELONG_VERSION_PY = {}NEWLINEHANDLERS = {}NEWLINENEWLINENEWLINEdef register_vcs_handler(vcs, method): # decoratorNEWLINE """Decorator to mark a method as the handler for a particular VCS."""NEWLINE def decorate(f):NEWLINE """Store f in HANDLERS[vcs][method]."""NEWLINE if vcs not in HANDLERS:NEWLINE HANDLERS[vcs] = {}NEWLINE HANDLERS[vcs][method] = fNEWLINE return fNEWLINE return decorateNEWLINENEWLINENEWLINEdef run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,NEWLINE env=None):NEWLINE """Call the given command(s)."""NEWLINE assert isinstance(commands, list)NEWLINE p = NoneNEWLINE for c in commands:NEWLINE try:NEWLINE dispcmd = str([c] + args)NEWLINE # remember shell=False, so use git.cmd on windows, not just gitNEWLINE p = subprocess.Popen([c] + args, cwd=cwd, env=env,NEWLINE stdout=subprocess.PIPE,NEWLINE stderr=(subprocess.PIPE if hide_stderrNEWLINE else None))NEWLINE breakNEWLINE except EnvironmentError:NEWLINE e = sys.exc_info()[1]NEWLINE if e.errno == errno.ENOENT:NEWLINE continueNEWLINE if verbose:NEWLINE print("unable to run %s" % dispcmd)NEWLINE print(e)NEWLINE return None, NoneNEWLINE else:NEWLINE if verbose:NEWLINE print("unable to find command, tried %s" % (commands,))NEWLINE return None, NoneNEWLINE stdout = p.communicate()[0].strip()NEWLINE if sys.version_info[0] >= 3:NEWLINE stdout = stdout.decode()NEWLINE if p.returncode != 0:NEWLINE if verbose:NEWLINE print("unable to run %s (error)" % dispcmd)NEWLINE print("stdout was %s" % stdout)NEWLINE return None, p.returncodeNEWLINE return stdout, p.returncodeNEWLINENEWLINENEWLINEdef versions_from_parentdir(parentdir_prefix, root, verbose):NEWLINE """Try to determine the version from the parent directory name.NEWLINENEWLINE Source tarballs conventionally unpack into a directory that includes bothNEWLINE the project name and a version string. We will also support searching upNEWLINE two directory levels for an appropriately named parent directoryNEWLINE """NEWLINE rootdirs = []NEWLINENEWLINE for i in range(3):NEWLINE dirname = os.path.basename(root)NEWLINE if dirname.startswith(parentdir_prefix):NEWLINE return {"version": dirname[len(parentdir_prefix):],NEWLINE "full-revisionid": None,NEWLINE "dirty": False, "error": None, "date": None}NEWLINE else:NEWLINE rootdirs.append(root)NEWLINE root = os.path.dirname(root) # up a levelNEWLINENEWLINE if verbose:NEWLINE print("Tried directories %s but none started with prefix %s" %NEWLINE (str(rootdirs), parentdir_prefix))NEWLINE raise NotThisMethod("rootdir doesn't start with parentdir_prefix")NEWLINENEWLINENEWLINE@register_vcs_handler("git", "get_keywords")NEWLINEdef git_get_keywords(versionfile_abs):NEWLINE """Extract version information from the given file."""NEWLINE # the code embedded in _version.py can just fetch the value of theseNEWLINE # keywords. When used from setup.py, we don't want to import _version.py,NEWLINE # so we do it with a regexp instead. This function is not used fromNEWLINE # _version.py.NEWLINE keywords = {}NEWLINE try:NEWLINE f = open(versionfile_abs, "r")NEWLINE for line in f.readlines():NEWLINE if line.strip().startswith("git_refnames ="):NEWLINE mo = re.search(r'=\s*"(.*)"', line)NEWLINE if mo:NEWLINE keywords["refnames"] = mo.group(1)NEWLINE if line.strip().startswith("git_full ="):NEWLINE mo = re.search(r'=\s*"(.*)"', line)NEWLINE if mo:NEWLINE keywords["full"] = mo.group(1)NEWLINE if line.strip().startswith("git_date ="):NEWLINE mo = re.search(r'=\s*"(.*)"', line)NEWLINE if mo:NEWLINE keywords["date"] = mo.group(1)NEWLINE f.close()NEWLINE except EnvironmentError:NEWLINE passNEWLINE return keywordsNEWLINENEWLINENEWLINE@register_vcs_handler("git", "keywords")NEWLINEdef git_versions_from_keywords(keywords, tag_prefix, verbose):NEWLINE """Get version information from git keywords."""NEWLINE if not keywords:NEWLINE raise NotThisMethod("no keywords at all, weird")NEWLINE date = keywords.get("date")NEWLINE if date is not None:NEWLINE # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliantNEWLINE # datestamp. However we prefer "%ci" (which expands to an "ISO-8601NEWLINE # -like" string, which we must then edit to make compliant), becauseNEWLINE # it's been around since git-1.5.3, and it's too difficult toNEWLINE # discover which version we're using, or to work around using anNEWLINE # older one.NEWLINE date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)NEWLINE refnames = keywords["refnames"].strip()NEWLINE if refnames.startswith("$Format"):NEWLINE if verbose:NEWLINE print("keywords are unexpanded, not using")NEWLINE raise NotThisMethod("unexpanded keywords, not a git-archive tarball")NEWLINE refs = set([r.strip() for r in refnames.strip("()").split(",")])NEWLINE # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead ofNEWLINE # just "foo-1.0". If we see a "tag: " prefix, prefer those.NEWLINE TAG = "tag: "NEWLINE tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])NEWLINE if not tags:NEWLINE # Either we're using git < 1.8.3, or there really are no tags. We useNEWLINE # a heuristic: assume all version tags have a digit. The old git %dNEWLINE # expansion behaves like git log --decorate=short and strips out theNEWLINE # refs/heads/ and refs/tags/ prefixes that would let us distinguishNEWLINE # between branches and tags. By ignoring refnames without digits, weNEWLINE # filter out many common branch names like "release" andNEWLINE # "stabilization", as well as "HEAD" and "master".NEWLINE tags = set([r for r in refs if re.search(r'\d', r)])NEWLINE if verbose:NEWLINE print("discarding '%s', no digits" % ",".join(refs - tags))NEWLINE if verbose:NEWLINE print("likely tags: %s" % ",".join(sorted(tags)))NEWLINE for ref in sorted(tags):NEWLINE # sorting will prefer e.g. "2.0" over "2.0rc1"NEWLINE if ref.startswith(tag_prefix):NEWLINE r = ref[len(tag_prefix):]NEWLINE if verbose:NEWLINE print("picking %s" % r)NEWLINE return {"version": r,NEWLINE "full-revisionid": keywords["full"].strip(),NEWLINE "dirty": False, "error": None,NEWLINE "date": date}NEWLINE # no suitable tags, so version is "0+unknown", but full hex is still thereNEWLINE if verbose:NEWLINE print("no suitable tags, using unknown + full revision id")NEWLINE return {"version": "0+unknown",NEWLINE "full-revisionid": keywords["full"].strip(),NEWLINE "dirty": False, "error": "no suitable tags", "date": None}NEWLINENEWLINENEWLINE@register_vcs_handler("git", "pieces_from_vcs")NEWLINEdef git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):NEWLINE """Get version from 'git describe' in the root of the source tree.NEWLINENEWLINE This only gets called if the git-archive 'subst' keywords were *not*NEWLINE expanded, and _version.py hasn't already been rewritten with a shortNEWLINE version string, meaning we're inside a checked out source tree.NEWLINE """NEWLINE GITS = ["git"]NEWLINE if sys.platform == "win32":NEWLINE GITS = ["git.cmd", "git.exe"]NEWLINENEWLINE out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root,NEWLINE hide_stderr=True)NEWLINE if rc != 0:NEWLINE if verbose:NEWLINE print("Directory %s not under git control" % root)NEWLINE raise NotThisMethod("'git rev-parse --git-dir' returned error")NEWLINENEWLINE # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]NEWLINE # if there isn't one, this yields HEX[-dirty] (no NUM)NEWLINE describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",NEWLINE "--always", "--long",NEWLINE "--match", "%s*" % tag_prefix],NEWLINE cwd=root)NEWLINE # --long was added in git-1.5.5NEWLINE if describe_out is None:NEWLINE raise NotThisMethod("'git describe' failed")NEWLINE describe_out = describe_out.strip()NEWLINE full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)NEWLINE if full_out is None:NEWLINE raise NotThisMethod("'git rev-parse' failed")NEWLINE full_out = full_out.strip()NEWLINENEWLINE pieces = {}NEWLINE pieces["long"] = full_outNEWLINE pieces["short"] = full_out[:7] # maybe improved laterNEWLINE pieces["error"] = NoneNEWLINENEWLINE # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]NEWLINE # TAG might have hyphens.NEWLINE git_describe = describe_outNEWLINENEWLINE # look for -dirty suffixNEWLINE dirty = git_describe.endswith("-dirty")NEWLINE pieces["dirty"] = dirtyNEWLINE if dirty:NEWLINE git_describe = git_describe[:git_describe.rindex("-dirty")]NEWLINENEWLINE # now we have TAG-NUM-gHEX or HEXNEWLINENEWLINE if "-" in git_describe:NEWLINE # TAG-NUM-gHEXNEWLINE mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)NEWLINE if not mo:NEWLINE # unparseable. Maybe git-describe is misbehaving?NEWLINE pieces["error"] = ("unable to parse git-describe output: '%s'"NEWLINE % describe_out)NEWLINE return piecesNEWLINENEWLINE # tagNEWLINE full_tag = mo.group(1)NEWLINE if not full_tag.startswith(tag_prefix):NEWLINE if verbose:NEWLINE fmt = "tag '%s' doesn't start with prefix '%s'"NEWLINE print(fmt % (full_tag, tag_prefix))NEWLINE pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"NEWLINE % (full_tag, tag_prefix))NEWLINE return piecesNEWLINE pieces["closest-tag"] = full_tag[len(tag_prefix):]NEWLINENEWLINE # distance: number of commits since tagNEWLINE pieces["distance"] = int(mo.group(2))NEWLINENEWLINE # commit: short hex revision IDNEWLINE pieces["short"] = mo.group(3)NEWLINENEWLINE else:NEWLINE # HEX: no tagsNEWLINE pieces["closest-tag"] = NoneNEWLINE count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"],NEWLINE cwd=root)NEWLINE pieces["distance"] = int(count_out) # total number of commitsNEWLINENEWLINE # commit date: see ISO-8601 comment in git_versions_from_keywords()NEWLINE date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"],NEWLINE cwd=root)[0].strip()NEWLINE pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)NEWLINENEWLINE return piecesNEWLINENEWLINENEWLINEdef plus_or_dot(pieces):NEWLINE """Return a + if we don't already have one, else return a ."""NEWLINE if "+" in pieces.get("closest-tag", ""):NEWLINE return "."NEWLINE return "+"NEWLINENEWLINENEWLINEdef render_pep440(pieces):NEWLINE """Build up version string, with post-release "local version identifier".NEWLINENEWLINE Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if youNEWLINE get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirtyNEWLINENEWLINE Exceptions:NEWLINE 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"] or pieces["dirty"]:NEWLINE rendered += plus_or_dot(pieces)NEWLINE rendered += "%d.g%s" % (pieces["distance"], pieces["short"])NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dirty"NEWLINE else:NEWLINE # exception #1NEWLINE rendered = "0+untagged.%d.g%s" % (pieces["distance"],NEWLINE pieces["short"])NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dirty"NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_pep440_pre(pieces):NEWLINE """TAG[.post.devDISTANCE] -- No -dirty.NEWLINENEWLINE Exceptions:NEWLINE 1: no tags. 0.post.devDISTANCENEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"]:NEWLINE rendered += ".post.dev%d" % pieces["distance"]NEWLINE else:NEWLINE # exception #1NEWLINE rendered = "0.post.dev%d" % pieces["distance"]NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_pep440_post(pieces):NEWLINE """TAG[.postDISTANCE[.dev0]+gHEX] .NEWLINENEWLINE The ".dev0" means dirty. Note that .dev0 sorts backwardsNEWLINE (a dirty tree will appear "older" than the corresponding clean one),NEWLINE but you shouldn't be releasing software with -dirty anyways.NEWLINENEWLINE Exceptions:NEWLINE 1: no tags. 0.postDISTANCE[.dev0]NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"] or pieces["dirty"]:NEWLINE rendered += ".post%d" % pieces["distance"]NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dev0"NEWLINE rendered += plus_or_dot(pieces)NEWLINE rendered += "g%s" % pieces["short"]NEWLINE else:NEWLINE # exception #1NEWLINE rendered = "0.post%d" % pieces["distance"]NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dev0"NEWLINE rendered += "+g%s" % pieces["short"]NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_pep440_old(pieces):NEWLINE """TAG[.postDISTANCE[.dev0]] .NEWLINENEWLINE The ".dev0" means dirty.NEWLINENEWLINE Eexceptions:NEWLINE 1: no tags. 0.postDISTANCE[.dev0]NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"] or pieces["dirty"]:NEWLINE rendered += ".post%d" % pieces["distance"]NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dev0"NEWLINE else:NEWLINE # exception #1NEWLINE rendered = "0.post%d" % pieces["distance"]NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dev0"NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_git_describe(pieces):NEWLINE """TAG[-DISTANCE-gHEX][-dirty].NEWLINENEWLINE Like 'git describe --tags --dirty --always'.NEWLINENEWLINE Exceptions:NEWLINE 1: no tags. HEX[-dirty] (note: no 'g' prefix)NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"]:NEWLINE rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])NEWLINE else:NEWLINE # exception #1NEWLINE rendered = pieces["short"]NEWLINE if pieces["dirty"]:NEWLINE rendered += "-dirty"NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_git_describe_long(pieces):NEWLINE """TAG-DISTANCE-gHEX[-dirty].NEWLINENEWLINE Like 'git describe --tags --dirty --always -long'.NEWLINE The distance/hash is unconditional.NEWLINENEWLINE Exceptions:NEWLINE 1: no tags. HEX[-dirty] (note: no 'g' prefix)NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])NEWLINE else:NEWLINE # exception #1NEWLINE rendered = pieces["short"]NEWLINE if pieces["dirty"]:NEWLINE rendered += "-dirty"NEWLINE return renderedNEWLINENEWLINENEWLINEdef render(pieces, style):NEWLINE """Render the given version pieces into the requested style."""NEWLINE if pieces["error"]:NEWLINE return {"version": "unknown",NEWLINE "full-revisionid": pieces.get("long"),NEWLINE "dirty": None,NEWLINE "error": pieces["error"],NEWLINE "date": None}NEWLINENEWLINE if not style or style == "default":NEWLINE style = "pep440" # the defaultNEWLINENEWLINE if style == "pep440":NEWLINE rendered = render_pep440(pieces)NEWLINE elif style == "pep440-pre":NEWLINE rendered = render_pep440_pre(pieces)NEWLINE elif style == "pep440-post":NEWLINE rendered = render_pep440_post(pieces)NEWLINE elif style == "pep440-old":NEWLINE rendered = render_pep440_old(pieces)NEWLINE elif style == "git-describe":NEWLINE rendered = render_git_describe(pieces)NEWLINE elif style == "git-describe-long":NEWLINE rendered = render_git_describe_long(pieces)NEWLINE else:NEWLINE raise ValueError("unknown style '%s'" % style)NEWLINENEWLINE return {"version": rendered, "full-revisionid": pieces["long"],NEWLINE "dirty": pieces["dirty"], "error": None,NEWLINE "date": pieces.get("date")}NEWLINENEWLINENEWLINEdef get_versions():NEWLINE """Get version information or return default if unable to do so."""NEWLINE # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we haveNEWLINE # __file__, we can work backwards from there to the root. SomeNEWLINE # py2exe/bbfreeze/non-CPython implementations don't do __file__, in whichNEWLINE # case we can only use expanded keywords.NEWLINENEWLINE cfg = get_config()NEWLINE verbose = cfg.verboseNEWLINENEWLINE try:NEWLINE return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,NEWLINE verbose)NEWLINE except NotThisMethod:NEWLINE passNEWLINENEWLINE try:NEWLINE root = os.path.realpath(__file__)NEWLINE # versionfile_source is the relative path from the top of the sourceNEWLINE # tree (where the .git directory might live) to this file. InvertNEWLINE # this to find the root from __file__.NEWLINE for i in cfg.versionfile_source.split('/'):NEWLINE root = os.path.dirname(root)NEWLINE except NameError:NEWLINE return {"version": "0+unknown", "full-revisionid": None,NEWLINE "dirty": None,NEWLINE "error": "unable to find root of source tree",NEWLINE "date": None}NEWLINENEWLINE try:NEWLINE pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)NEWLINE return render(pieces, cfg.style)NEWLINE except NotThisMethod:NEWLINE passNEWLINENEWLINE try:NEWLINE if cfg.parentdir_prefix:NEWLINE return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)NEWLINE except NotThisMethod:NEWLINE passNEWLINENEWLINE return {"version": "0+unknown", "full-revisionid": None,NEWLINE "dirty": None,NEWLINE "error": "unable to compute version", "date": None}NEWLINE # coding=utf-8NEWLINE# --------------------------------------------------------------------------NEWLINE# Copyright (c) Microsoft Corporation. All rights reserved.NEWLINE# Licensed under the MIT License. See License.txt in the project root forNEWLINE# license information.NEWLINE#NEWLINE# Code generated by Microsoft (R) AutoRest Code Generator.NEWLINE# Changes may cause incorrect behavior and will be lost if the code isNEWLINE# regenerated.NEWLINE# --------------------------------------------------------------------------NEWLINENEWLINEfrom msrest.paging import PagedNEWLINENEWLINENEWLINEclass UserPaged(Paged):NEWLINE """NEWLINE A paging container for iterating over a list of :class:`User ` objectNEWLINE """NEWLINENEWLINE _attribute_map = {NEWLINE 'next_link': {'key': 'odata\\.nextLink', 'type': 'str'},NEWLINE 'current_page': {'key': 'value', 'type': '[User]'}NEWLINE }NEWLINENEWLINE def __init__(self, *args, **kwargs):NEWLINENEWLINE super(UserPaged, self).__init__(*args, **kwargs)NEWLINE import torchNEWLINENEWLINE#from tinydfa import DFA, DFALayer, FeedbackPointsHandlingNEWLINEfrom tinydfa.light_dfa import DFA, DFALayerNEWLINENEWLINENEWLINEclass VeryTinyNeRFModel(torch.nn.Module):NEWLINE r"""Define a "very tiny" NeRF model comprising three fully connected layers.NEWLINE """NEWLINENEWLINE def __init__(self, filter_size=128, num_encoding_functions=6, use_viewdirs=True):NEWLINE super(VeryTinyNeRFModel, self).__init__()NEWLINE self.num_encoding_functions = num_encoding_functionsNEWLINE self.xyz_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINE if use_viewdirs is True:NEWLINE self.viewdir_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINE else:NEWLINE self.viewdir_encoding_dims = 0NEWLINE # Input layer (default: 65 -> 128)NEWLINE self.layer1 = torch.nn.Linear(NEWLINE self.xyz_encoding_dims + self.viewdir_encoding_dims, filter_sizeNEWLINE )NEWLINE # Layer 2 (default: 128 -> 128)NEWLINE self.layer2 = torch.nn.Linear(filter_size, filter_size)NEWLINE # Layer 3 (default: 128 -> 4)NEWLINE self.layer3 = torch.nn.Linear(filter_size, 4)NEWLINE # Short hand for torch.nn.functional.reluNEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE x = self.relu(self.layer1(x))NEWLINE x = self.relu(self.layer2(x))NEWLINE x = self.layer3(x)NEWLINE return xNEWLINENEWLINENEWLINEclass MultiHeadNeRFModel(torch.nn.Module):NEWLINE r"""Define a "multi-head" NeRF model (radiance and RGB colors are predicted byNEWLINE separate heads).NEWLINE """NEWLINENEWLINE def __init__(self, hidden_size=128, num_encoding_functions=6, use_viewdirs=True):NEWLINE super(MultiHeadNeRFModel, self).__init__()NEWLINE self.num_encoding_functions = num_encoding_functionsNEWLINE self.xyz_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINE if use_viewdirs is True:NEWLINE self.viewdir_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINE else:NEWLINE self.viewdir_encoding_dims = 0NEWLINE # Input layer (default: 39 -> 128)NEWLINE self.layer1 = torch.nn.Linear(self.xyz_encoding_dims, hidden_size)NEWLINE # Layer 2 (default: 128 -> 128)NEWLINE self.layer2 = torch.nn.Linear(hidden_size, hidden_size)NEWLINE # Layer 3_1 (default: 128 -> 1): Predicts radiance ("sigma")NEWLINE self.layer3_1 = torch.nn.Linear(hidden_size, 1)NEWLINE # Layer 3_2 (default: 128 -> 1): Predicts a feature vector (used for color)NEWLINE self.layer3_2 = torch.nn.Linear(hidden_size, hidden_size)NEWLINENEWLINE # Layer 4 (default: 39 + 128 -> 128)NEWLINE self.layer4 = torch.nn.Linear(NEWLINE self.viewdir_encoding_dims + hidden_size, hidden_sizeNEWLINE )NEWLINE # Layer 5 (default: 128 -> 128)NEWLINE self.layer5 = torch.nn.Linear(hidden_size, hidden_size)NEWLINE # Layer 6 (default: 128 -> 3): Predicts RGB colorNEWLINE self.layer6 = torch.nn.Linear(hidden_size, 3)NEWLINENEWLINE # Short hand for torch.nn.functional.reluNEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE x, view = x[..., : self.xyz_encoding_dims], x[..., self.xyz_encoding_dims :]NEWLINE x = self.relu(self.layer1(x))NEWLINE x = self.relu(self.layer2(x))NEWLINE sigma = self.layer3_1(x)NEWLINE feat = self.relu(self.layer3_2(x))NEWLINE x = torch.cat((feat, view), dim=-1)NEWLINE x = self.relu(self.layer4(x))NEWLINE x = self.relu(self.layer5(x))NEWLINE x = self.layer6(x)NEWLINE return torch.cat((x, sigma), dim=-1)NEWLINENEWLINENEWLINEclass ReplicateNeRFModel(torch.nn.Module):NEWLINE r"""NeRF model that follows the figure (from the supp. material of NeRF) toNEWLINE every last detail. (ofc, with some flexibility)NEWLINE """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE hidden_size=256,NEWLINE num_layers=4,NEWLINE num_encoding_fn_xyz=6,NEWLINE num_encoding_fn_dir=4,NEWLINE include_input_xyz=True,NEWLINE include_input_dir=True,NEWLINE ):NEWLINE super(ReplicateNeRFModel, self).__init__()NEWLINE # xyz_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINENEWLINE self.dim_xyz = (3 if include_input_xyz else 0) + 2 * 3 * num_encoding_fn_xyzNEWLINE self.dim_dir = (3 if include_input_dir else 0) + 2 * 3 * num_encoding_fn_dirNEWLINENEWLINE self.layer1 = torch.nn.Linear(self.dim_xyz, hidden_size)NEWLINE self.layer2 = torch.nn.Linear(hidden_size, hidden_size)NEWLINE self.layer3 = torch.nn.Linear(hidden_size, hidden_size)NEWLINE self.fc_alpha = torch.nn.Linear(hidden_size, 1)NEWLINENEWLINE self.layer4 = torch.nn.Linear(hidden_size + self.dim_dir, hidden_size // 2)NEWLINE self.layer5 = torch.nn.Linear(hidden_size // 2, hidden_size // 2)NEWLINE self.fc_rgb = torch.nn.Linear(hidden_size // 2, 3)NEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE xyz, direction = x[..., : self.dim_xyz], x[..., self.dim_xyz :]NEWLINE x_ = self.relu(self.layer1(xyz))NEWLINE x_ = self.relu(self.layer2(x_))NEWLINE feat = self.layer3(x_)NEWLINE alpha = self.fc_alpha(x_)NEWLINE y_ = self.relu(self.layer4(torch.cat((feat, direction), dim=-1)))NEWLINE y_ = self.relu(self.layer5(y_))NEWLINE rgb = self.fc_rgb(y_)NEWLINE return torch.cat((rgb, alpha), dim=-1)NEWLINENEWLINENEWLINEclass PaperNeRFModel(torch.nn.Module):NEWLINE r"""Implements the NeRF model as described in Fig. 7 (appendix) of theNEWLINE arXiv submission (v0). """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE num_layers=8,NEWLINE hidden_size=256,NEWLINE skip_connect_every=4,NEWLINE num_encoding_fn_xyz=6,NEWLINE num_encoding_fn_dir=4,NEWLINE include_input_xyz=True,NEWLINE include_input_dir=True,NEWLINE use_viewdirs=True,NEWLINE ):NEWLINE super(PaperNeRFModel, self).__init__()NEWLINENEWLINE include_input_xyz = 3 if include_input_xyz else 0NEWLINE include_input_dir = 3 if include_input_dir else 0NEWLINE self.dim_xyz = include_input_xyz + 2 * 3 * num_encoding_fn_xyzNEWLINE self.dim_dir = include_input_dir + 2 * 3 * num_encoding_fn_dirNEWLINENEWLINE self.layers_xyz = torch.nn.ModuleList()NEWLINE self.use_viewdirs = use_viewdirsNEWLINE self.layers_xyz.append(torch.nn.Linear(self.dim_xyz, 256))NEWLINE for i in range(1, 8):NEWLINE if i == 4:NEWLINE self.layers_xyz.append(torch.nn.Linear(self.dim_xyz + 256, 256))NEWLINE else:NEWLINE self.layers_xyz.append(torch.nn.Linear(256, 256))NEWLINE self.fc_feat = torch.nn.Linear(256, 256)NEWLINE self.fc_alpha = torch.nn.Linear(256, 1)NEWLINENEWLINE self.layers_dir = torch.nn.ModuleList()NEWLINE self.layers_dir.append(torch.nn.Linear(256 + self.dim_dir, 128))NEWLINE for i in range(3):NEWLINE self.layers_dir.append(torch.nn.Linear(128, 128))NEWLINE self.fc_rgb = torch.nn.Linear(128, 3)NEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE xyz, dirs = x[..., : self.dim_xyz], x[..., self.dim_xyz :]NEWLINE for i in range(8):NEWLINE if i == 4:NEWLINE x = self.layers_xyz[i](torch.cat((xyz, x), -1))NEWLINE else:NEWLINE x = self.layers_xyz[i](x)NEWLINE x = self.relu(x)NEWLINE feat = self.fc_feat(x)NEWLINE alpha = self.fc_alpha(feat)NEWLINE if self.use_viewdirs:NEWLINE x = self.layers_dir[0](torch.cat((feat, dirs), -1))NEWLINE else:NEWLINE x = self.layers_dir[0](feat)NEWLINE x = self.relu(x)NEWLINE for i in range(1, 3):NEWLINE x = self.layers_dir[i](x)NEWLINE x = self.relu(x)NEWLINE rgb = self.fc_rgb(x)NEWLINE return torch.cat((rgb, alpha), dim=-1)NEWLINENEWLINENEWLINEclass FlexibleNeRFModel(torch.nn.Module):NEWLINE def __init__(NEWLINE self,NEWLINE num_layers=4,NEWLINE hidden_size=128,NEWLINE skip_connect_every=4,NEWLINE num_encoding_fn_xyz=6,NEWLINE num_encoding_fn_dir=4,NEWLINE include_input_xyz=True,NEWLINE include_input_dir=True,NEWLINE use_viewdirs=True,NEWLINE ):NEWLINE super(FlexibleNeRFModel, self).__init__()NEWLINENEWLINE include_input_xyz = 3 if include_input_xyz else 0NEWLINE include_input_dir = 3 if include_input_dir else 0NEWLINE self.dim_xyz = include_input_xyz + 2 * 3 * num_encoding_fn_xyzNEWLINE self.dim_dir = include_input_dir + 2 * 3 * num_encoding_fn_dirNEWLINE self.skip_connect_every = skip_connect_everyNEWLINE if not use_viewdirs:NEWLINE self.dim_dir = 0NEWLINENEWLINE self.layer1 = torch.nn.Linear(self.dim_xyz, hidden_size)NEWLINE self.layers_xyz = torch.nn.ModuleList()NEWLINE for i in range(num_layers - 1):NEWLINE if i % self.skip_connect_every == 0 and i > 0 and i != num_layers - 1:NEWLINE self.layers_xyz.append(NEWLINE torch.nn.Linear(self.dim_xyz + hidden_size, hidden_size)NEWLINE )NEWLINE else:NEWLINE self.layers_xyz.append(torch.nn.Linear(hidden_size, hidden_size))NEWLINENEWLINE self.use_viewdirs = use_viewdirsNEWLINE if self.use_viewdirs:NEWLINE self.layers_dir = torch.nn.ModuleList()NEWLINE # This deviates from the original paper, and follows the code release instead.NEWLINE self.layers_dir.append(NEWLINE torch.nn.Linear(self.dim_dir + hidden_size, hidden_size // 2)NEWLINE )NEWLINENEWLINE self.fc_alpha = torch.nn.Linear(hidden_size, 1)NEWLINE self.fc_rgb = torch.nn.Linear(hidden_size // 2, 3)NEWLINE self.fc_feat = torch.nn.Linear(hidden_size, hidden_size)NEWLINE else:NEWLINE self.fc_out = torch.nn.Linear(hidden_size, 4)NEWLINENEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE if self.use_viewdirs:NEWLINE xyz, view = x[..., : self.dim_xyz], x[..., self.dim_xyz :]NEWLINE else:NEWLINE xyz = x[..., : self.dim_xyz]NEWLINE x = self.layer1(xyz) # Missing a ReLU (?)NEWLINE for i in range(len(self.layers_xyz)):NEWLINE if (NEWLINE i % self.skip_connect_every == 0NEWLINE and i > 0NEWLINE and i != len(self.linear_layers) - 1NEWLINE ):NEWLINE x = torch.cat((x, xyz), dim=-1)NEWLINE x = self.relu(self.layers_xyz[i](x))NEWLINE if self.use_viewdirs:NEWLINE feat = self.relu(self.fc_feat(x))NEWLINE alpha = self.fc_alpha(x)NEWLINE x = torch.cat((feat, view), dim=-1)NEWLINE for l in self.layers_dir:NEWLINE x = self.relu(l(x))NEWLINE rgb = self.fc_rgb(x)NEWLINE return torch.cat((rgb, alpha), dim=-1)NEWLINE else:NEWLINE return self.fc_out(x)NEWLINENEWLINENEWLINEclass DFAFlexibleNeRFModel(torch.nn.Module):NEWLINE def __init__(self, num_layers=4, hidden_size=128, skip_connect_every=4, num_encoding_fn_xyz=6,NEWLINE num_encoding_fn_dir=4, include_input_xyz=True, include_input_dir=True, use_viewdirs=True,):NEWLINE super(DFAFlexibleNeRFModel, self).__init__()NEWLINENEWLINE # Determine the inputs:NEWLINE include_input_xyz = 3 if include_input_xyz else 0 # Add raw xyz coordinatesNEWLINE include_input_dir = 3 if include_input_dir else 0 # Add raw viewing angle (specularity)NEWLINE self.dim_xyz = include_input_xyz + 2 * 3 * num_encoding_fn_xyz # Total xyz input: raw? + embeddingNEWLINENEWLINE self.use_viewdirs = use_viewdirs # Are we using view direction? (specularity)NEWLINE if not self.use_viewdirs:NEWLINE self.dim_dir = 0NEWLINE else:NEWLINE self.dim_dir = include_input_dir + 2 * 3 * num_encoding_fn_dirNEWLINENEWLINE # Network layersNEWLINE self.layer1 = torch.nn.Linear(self.dim_xyz, hidden_size) # Input layerNEWLINE self.dfa1 = DFALayer(name='dfa1')NEWLINE # First stack of layers, using only xyz coordinates:NEWLINE self.layers_xyz = torch.nn.ModuleList()NEWLINE self.dfa_xyz = torch.nn.ModuleList()NEWLINE self.skip_connect_every = skip_connect_everyNEWLINE for i in range(num_layers - 1):NEWLINE if i % self.skip_connect_every == 0 and i > 0 and i != num_layers - 1:NEWLINE # Handle skip-connection.NEWLINE self.layers_xyz.append(torch.nn.Linear(self.dim_xyz + hidden_size, hidden_size))NEWLINE else:NEWLINE self.layers_xyz.append(torch.nn.Linear(hidden_size, hidden_size))NEWLINE self.dfa_xyz.append(DFALayer(name=f'dfa_xyz{i}'))NEWLINENEWLINENEWLINE if self.use_viewdirs:NEWLINE self.fc_alpha = torch.nn.Linear(hidden_size, 1) # Transparency output at top of xyz stackNEWLINENEWLINE self.fc_feat = torch.nn.Linear(hidden_size, hidden_size) # Link between angle stack and xyz stackNEWLINE self.dfa_feat = DFALayer(name='dfa_feat')NEWLINENEWLINE # Second stack of layers, using viewing angle:NEWLINE self.layers_dir = torch.nn.ModuleList()NEWLINE # This deviates from the original paper, and follows the code release instead.NEWLINE self.layers_dir.append(NEWLINE torch.nn.Linear(self.dim_dir + hidden_size, hidden_size // 2)NEWLINE )NEWLINE self.dfa_dir = DFALayer(name='dfa_dir')NEWLINENEWLINE self.fc_rgb = torch.nn.Linear(hidden_size // 2, 3) # RGB color output, at top of viewing angle stackNEWLINE else:NEWLINE # If not using viewing angle, go straight to (transparency, r, g, b) output:NEWLINE self.fc_out = torch.nn.Linear(hidden_size, 4)NEWLINENEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE self.dfa_layers = [self.dfa1, *self.dfa_xyz, self.dfa_feat, self.dfa_dir]NEWLINE self.dfa = DFA(self.dfa_layers) #feedback_points_handling=FeedbackPointsHandling.MINIBATCH)NEWLINENEWLINE def forward(self, x):NEWLINE # Separate the xyz and viewing angle embeddingsNEWLINE if self.use_viewdirs:NEWLINE xyz, view = x[..., :self.dim_xyz], x[..., self.dim_xyz:]NEWLINE else:NEWLINE xyz = x[..., :self.dim_xyz]NEWLINENEWLINE x = self.dfa1(self.relu(self.layer1(xyz))) # Go through first layerNEWLINE # Go through xyz stack:NEWLINE for i in range(len(self.layers_xyz)):NEWLINE if (i % self.skip_connect_every == 0 and i > 0 and i != len(self.linear_layers) - 1):NEWLINE # Handle skip connectionNEWLINE x = torch.cat((x, xyz), dim=-1)NEWLINE x = self.dfa_xyz[i](self.relu(self.layers_xyz[i](x))) # Go through layerNEWLINENEWLINE if self.use_viewdirs:NEWLINE alpha = self.fc_alpha(x) # Output alpha (transparency value)NEWLINE # Prepare for viewing angle stack:NEWLINE feat = self.dfa_feat(self.relu(self.fc_feat(x))) # Link between xyz/viewing angle stackNEWLINE x = torch.cat((feat, view), dim=-1) # Add viewing angle informationNEWLINE for l in self.layers_dir:NEWLINE # Go through viewing angle stack (proper):NEWLINE x = self.dfa_dir(self.relu(l(x)))NEWLINE rgb = self.fc_rgb(x) # Output rgb valueNEWLINE return self.dfa(torch.cat((rgb, alpha), dim=-1))NEWLINE else:NEWLINE return self.dfa(self.fc_out(x))NEWLINE # -*- coding: utf-8 -*-NEWLINEfrom hashlib import sha256NEWLINENEWLINEfrom .sha1 import SHA1NEWLINENEWLINENEWLINEdef hmac(key, message, hash_class):NEWLINE block_size = hash_class().block_sizeNEWLINENEWLINE if len(key) > block_size:NEWLINE key = hash_class(key).digest()NEWLINE key = key.ljust(block_size, b"\x00")NEWLINENEWLINE mac = message.encode() if isinstance(message, str) else messageNEWLINE for pad_byte in b"\x5c", b"\x36":NEWLINE prefix = bytes(kb ^ pb for kb, pb in zip(key, pad_byte * block_size))NEWLINE mac = hash_class(prefix + mac).digest()NEWLINENEWLINE return macNEWLINENEWLINENEWLINEdef hmac_sha1(key, message):NEWLINE return hmac(key, message, SHA1)NEWLINENEWLINENEWLINEdef hmac_sha256(key, message):NEWLINE return hmac(key, message, sha256)NEWLINE # Copyright 2019 The Vitess Authors.NEWLINE# NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE# NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE# NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINE"""Kubernetes environment."""NEWLINENEWLINEimport getpassNEWLINEimport jsonNEWLINEimport loggingNEWLINEimport osNEWLINEimport subprocessNEWLINEimport timeNEWLINENEWLINEfrom sandbox import kubernetes_componentsNEWLINEfrom vtproto import topodata_pb2NEWLINEfrom vtdb import vtgate_clientNEWLINEimport base_environmentNEWLINEimport protocols_flavorNEWLINEimport vtctl_helperNEWLINENEWLINENEWLINEclass K8sEnvironment(base_environment.BaseEnvironment):NEWLINE """Environment for kubernetes clusters on Google Compute Engine."""NEWLINENEWLINE def __init__(self):NEWLINE super(K8sEnvironment, self).__init__()NEWLINENEWLINE def use_named(self, instance_name):NEWLINE # Check to make sure kubectl existsNEWLINE try:NEWLINE subprocess.check_output(['kubectl'])NEWLINE except OSError:NEWLINE raise base_environment.VitessEnvironmentError(NEWLINE 'kubectl not found, please install by visiting kubernetes.io or 'NEWLINE 'running gcloud components update kubectl if using compute engine.')NEWLINENEWLINE vtctld_ip = kubernetes_components.get_forwarded_ip(NEWLINE 'vtctld', instance_name)NEWLINE self.vtctl_addr = '%s:15999' % vtctld_ipNEWLINENEWLINE self.vtctl_helper = vtctl_helper.VtctlHelper('grpc', self.vtctl_addr)NEWLINE self.cluster_name = instance_nameNEWLINENEWLINE keyspaces = self.vtctl_helper.execute_vtctl_command(['GetKeyspaces'])NEWLINE self.mobs = filter(None, keyspaces.split('\n'))NEWLINE self.keyspaces = self.mobsNEWLINENEWLINE if not self.keyspaces:NEWLINE raise base_environment.VitessEnvironmentError(NEWLINE 'Invalid environment, no keyspaces found')NEWLINENEWLINE self.num_shards = []NEWLINE self.shards = []NEWLINENEWLINE for keyspace in self.keyspaces:NEWLINE shards = json.loads(self.vtctl_helper.execute_vtctl_command(NEWLINE ['FindAllShardsInKeyspace', keyspace]))NEWLINE self.shards.append(shards)NEWLINE self.num_shards.append(len(shards))NEWLINENEWLINE # This assumes that all keyspaces use the same set of cellsNEWLINE self.cells = json.loads(self.vtctl_helper.execute_vtctl_command(NEWLINE ['GetShard', '%s/%s' % (self.keyspaces[0], self.shards[0].keys()[0])]NEWLINE ))['cells']NEWLINENEWLINE self.primary_cells = self.cellsNEWLINE self.replica_instances = []NEWLINE self.rdonly_instances = []NEWLINENEWLINE # This assumes that all cells are equivalent for k8s environments.NEWLINE all_tablets_in_a_cell = self.vtctl_helper.execute_vtctl_command(NEWLINE ['ListAllTablets', self.cells[0]])NEWLINE all_tablets_in_a_cell = [x.split(' ') for x inNEWLINE filter(None, all_tablets_in_a_cell.split('\n'))]NEWLINENEWLINE for index, keyspace in enumerate(self.keyspaces):NEWLINE keyspace_tablets_in_cell = [NEWLINE tablet for tablet in all_tablets_in_a_cell if tablet[1] == keyspace]NEWLINE replica_tablets_in_cell = [NEWLINE tablet for tablet in keyspace_tablets_in_cellNEWLINE if tablet[3] == 'master' or tablet[3] == 'replica']NEWLINE replica_instances = len(replica_tablets_in_cell) / self.num_shards[index]NEWLINE self.replica_instances.append(replica_instances)NEWLINE self.rdonly_instances.append(NEWLINE (len(keyspace_tablets_in_cell) / self.num_shards[index]) -NEWLINE replica_instances)NEWLINENEWLINE # Converts keyspace name and alias to number of instancesNEWLINE self.keyspace_alias_to_num_instances_dict = {}NEWLINE for index, keyspace in enumerate(self.keyspaces):NEWLINE self.keyspace_alias_to_num_instances_dict[keyspace] = {NEWLINE 'replica': int(self.replica_instances[index]),NEWLINE 'rdonly': int(self.rdonly_instances[index])NEWLINE }NEWLINENEWLINE self.vtgate_addrs = {}NEWLINE for cell in self.cells:NEWLINE vtgate_ip = kubernetes_components.get_forwarded_ip(NEWLINE 'vtgate-%s' % cell, instance_name)NEWLINE self.vtgate_addrs[cell] = '%s:15991' % vtgate_ipNEWLINE super(K8sEnvironment, self).use_named(instance_name)NEWLINENEWLINE def create(self, **kwargs):NEWLINE self.create_gke_cluster = (NEWLINE kwargs.get('create_gke_cluster', 'false').lower() != 'false')NEWLINE if self.create_gke_cluster and 'GKE_NUM_NODES' not in kwargs:NEWLINE raise base_environment.VitessEnvironmentError(NEWLINE 'Must specify GKE_NUM_NODES')NEWLINE if 'GKE_CLUSTER_NAME' not in kwargs:NEWLINE kwargs['GKE_CLUSTER_NAME'] = getpass.getuser()NEWLINE if 'VITESS_NAME' not in kwargs:NEWLINE kwargs['VITESS_NAME'] = getpass.getuser()NEWLINE kwargs['TEST_MODE'] = '1'NEWLINE self.script_dir = os.path.join(os.environ['VTROOT'], 'examples/kubernetes')NEWLINE try:NEWLINE subprocess.check_output(['gcloud', 'config', 'list'])NEWLINE except OSError:NEWLINE raise base_environment.VitessEnvironmentError(NEWLINE 'gcloud not found, please install by visiting cloud.google.com')NEWLINE if 'project' in kwargs:NEWLINE logging.info('Setting project to %s', kwargs['project'])NEWLINE subprocess.check_output(NEWLINE ['gcloud', 'config', 'set', 'project', kwargs['project']])NEWLINE project_name_json = json.loads(subprocess.check_output(NEWLINE ['gcloud', 'config', 'list', 'project', '--format', 'json']))NEWLINE project_name = project_name_json['core']['project']NEWLINE logging.info('Current project name: %s', project_name)NEWLINE for k, v in kwargs.iteritems():NEWLINE os.environ[k] = vNEWLINE if self.create_gke_cluster:NEWLINE cluster_up_txt = subprocess.check_output(NEWLINE [os.path.join(self.script_dir, 'cluster-up.sh')],NEWLINE cwd=self.script_dir, stderr=subprocess.STDOUT)NEWLINE logging.info(cluster_up_txt)NEWLINE vitess_up_output = subprocess.check_output(NEWLINE [os.path.join(self.script_dir, 'vitess-up.sh')],NEWLINE cwd=self.script_dir, stderr=subprocess.STDOUT)NEWLINE logging.info(vitess_up_output)NEWLINE self.use_named(kwargs['VITESS_NAME'])NEWLINENEWLINE def destroy(self):NEWLINE vitess_down_output = subprocess.check_output(NEWLINE [os.path.join(self.script_dir, 'vitess-down.sh')],NEWLINE cwd=self.script_dir, stderr=subprocess.STDOUT)NEWLINE logging.info(vitess_down_output)NEWLINE if self.create_gke_cluster:NEWLINE cluster_down_output = subprocess.check_output(NEWLINE [os.path.join(self.script_dir, 'cluster-down.sh')],NEWLINE cwd=self.script_dir, stderr=subprocess.STDOUT)NEWLINE logging.info(cluster_down_output)NEWLINENEWLINE def get_vtgate_conn(self, cell):NEWLINE return vtgate_client.connect(NEWLINE protocols_flavor.protocols_flavor().vtgate_python_protocol(),NEWLINE self.vtgate_addrs[cell], 60)NEWLINENEWLINE def restart_mysql_task(self, tablet_name, task_name, is_alloc=False):NEWLINE # Delete the whole pod, which deletes mysql + vttablet tasks.NEWLINE os.system('kubectl delete pod %s --namespace=%s' % (NEWLINE self.get_tablet_pod_name(tablet_name), self.cluster_name))NEWLINE return 0NEWLINENEWLINE def wait_for_good_failover_status(NEWLINE self, keyspace, shard_name, failover_completion_timeout_s=60):NEWLINE return 0NEWLINENEWLINE def poll_for_varz(self, tablet_name, varz, timeout=60.0,NEWLINE condition_fn=None, converter=str, condition_msg=None):NEWLINE """Polls for varz to exist, or match specific conditions, within a timeout.NEWLINENEWLINE Args:NEWLINE tablet_name: the name of the process that we're trying to poll vars from.NEWLINE varz: name of the vars to fetch from varzNEWLINE timeout: number of seconds that we should attempt to poll for.NEWLINE condition_fn: a function that takes the var as input, and returns a truthyNEWLINE value if it matches the success conditions.NEWLINE converter: function to convert varz valueNEWLINE condition_msg: string describing the conditions that we're polling for,NEWLINE used for error messaging.NEWLINENEWLINE Raises:NEWLINE VitessEnvironmentError: Raised if the varz conditions aren't met withinNEWLINE the given timeout.NEWLINENEWLINE Returns:NEWLINE dict of requested varz.NEWLINE """NEWLINE start_time = time.time()NEWLINE while True:NEWLINE if (time.time() - start_time) >= timeout:NEWLINE timeout_error_msg = 'Timed out polling for varz.'NEWLINE if condition_fn and condition_msg:NEWLINE timeout_error_msg += ' Condition "%s" not met.' % condition_msgNEWLINE raise base_environment.VitessEnvironmentError(timeout_error_msg)NEWLINE hostname = self.get_tablet_ip_port(tablet_name)NEWLINE host_varz = subprocess.check_output([NEWLINE 'kubectl', 'exec', '-ti', self.get_tablet_pod_name(tablet_name),NEWLINE '--namespace=%s' % self.cluster_name,NEWLINE 'curl', '%s/debug/vars' % hostname])NEWLINE if not host_varz:NEWLINE continueNEWLINE host_varz = json.loads(host_varz)NEWLINE if condition_fn is None or condition_fn(host_varz):NEWLINE return host_varzNEWLINENEWLINE def wait_for_healthy_tablets(self):NEWLINE return 0NEWLINENEWLINE def get_tablet_pod_name(self, tablet_name):NEWLINE tablet_info = json.loads(self.vtctl_helper.execute_vtctl_command(NEWLINE ['GetTablet', tablet_name]))NEWLINE # Hostname is .vttabletNEWLINE return tablet_info['hostname'].split('.')[0]NEWLINENEWLINE def get_tablet_task_number(self, tablet_name):NEWLINE # Tablet pod name under StatefulSet isNEWLINE # "----"NEWLINE # Example: test1-foo-0-replica-0.NEWLINE return int(self.get_tablet_pod_name(tablet_name).split('-')[-1])NEWLINENEWLINE def automatic_reparent_available(self):NEWLINE """Checks if the environment can automatically reparent."""NEWLINE p1 = subprocess.Popen(NEWLINE ['kubectl', 'get', 'pods', '--namespace=%s' % self.cluster_name],NEWLINE stdout=subprocess.PIPE)NEWLINE p2 = subprocess.Popen(NEWLINE ['grep', 'orchestrator'], stdin=p1.stdout, stdout=subprocess.PIPE)NEWLINE output = p2.communicate()[0]NEWLINE return bool(output)NEWLINENEWLINE def internal_reparent(self, keyspace, shard_name, new_master_uid,NEWLINE emergency=False):NEWLINE reparent_command = (NEWLINE 'EmergencyReparentShard' if emergency else 'PlannedReparentShard')NEWLINE self.vtctl_helper.execute_vtctl_command(NEWLINE [reparent_command, '-keyspace_shard', '%s/%s' % (keyspace, shard_name),NEWLINE '-new_master', new_master_uid])NEWLINE self.vtctl_helper.execute_vtctl_command(['RebuildKeyspaceGraph', keyspace])NEWLINE return 0, 'No output'NEWLINENEWLINE def backup(self, tablet_name):NEWLINE logging.info('Backing up tablet %s', tablet_name)NEWLINE self.vtctl_helper.execute_vtctl_command(['Backup', tablet_name])NEWLINENEWLINE def drain_tablet(self, tablet_name, duration_s=600):NEWLINE self.vtctl_helper.execute_vtctl_command(['StopSlave', tablet_name])NEWLINE self.vtctl_helper.execute_vtctl_command(NEWLINE ['ChangeSlaveType', tablet_name, 'drained'])NEWLINENEWLINE def is_tablet_drained(self, tablet_name):NEWLINE return self.get_tablet_type(tablet_name) == topodata_pb2.DRAINEDNEWLINENEWLINE def undrain_tablet(self, tablet_name):NEWLINE self.vtctl_helper.execute_vtctl_command(NEWLINE ['ChangeSlaveType', tablet_name, 'replica'])NEWLINE self.vtctl_helper.execute_vtctl_command(['StartSlave', tablet_name])NEWLINENEWLINE def is_tablet_undrained(self, tablet_name):NEWLINE return not self.is_tablet_drained(tablet_name)NEWLINENEWLINE def get_tablet_query_total_count(self, tablet_name):NEWLINE return self.poll_for_varz(NEWLINE tablet_name, ['Queries'])['Queries']['TotalCount']NEWLINENEWLINE # -*- coding: utf-8 -*-NEWLINENEWLINE# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:NEWLINE# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-codeNEWLINENEWLINEfrom ccxt.async_support.base.exchange import ExchangeNEWLINEimport base64NEWLINEfrom ccxt.base.errors import ExchangeErrorNEWLINEfrom ccxt.base.errors import ArgumentsRequiredNEWLINENEWLINENEWLINEclass luno (Exchange):NEWLINENEWLINE def describe(self):NEWLINE return self.deep_extend(super(luno, self).describe(), {NEWLINE 'id': 'luno',NEWLINE 'name': 'luno',NEWLINE 'countries': ['GB', 'SG', 'ZA'],NEWLINE 'rateLimit': 1000,NEWLINE 'version': '1',NEWLINE 'has': {NEWLINE 'CORS': False,NEWLINE 'fetchTickers': True,NEWLINE 'fetchOrder': True,NEWLINE 'fetchOrders': True,NEWLINE 'fetchOpenOrders': True,NEWLINE 'fetchClosedOrders': True,NEWLINE 'fetchMyTrades': True,NEWLINE 'fetchTradingFees': True,NEWLINE },NEWLINE 'urls': {NEWLINE 'logo': 'https://user-images.githubusercontent.com/1294454/27766607-8c1a69d8-5ede-11e7-930c-540b5eb9be24.jpg',NEWLINE 'api': 'https://api.mybitx.com/api',NEWLINE 'www': 'https://www.luno.com',NEWLINE 'doc': [NEWLINE 'https://www.luno.com/en/api',NEWLINE 'https://npmjs.org/package/bitx',NEWLINE 'https://github.com/bausmeier/node-bitx',NEWLINE ],NEWLINE },NEWLINE 'api': {NEWLINE 'public': {NEWLINE 'get': [NEWLINE 'orderbook',NEWLINE 'orderbook_top',NEWLINE 'ticker',NEWLINE 'tickers',NEWLINE 'trades',NEWLINE ],NEWLINE },NEWLINE 'private': {NEWLINE 'get': [NEWLINE 'accounts/{id}/pending',NEWLINE 'accounts/{id}/transactions',NEWLINE 'balance',NEWLINE 'fee_info',NEWLINE 'funding_address',NEWLINE 'listorders',NEWLINE 'listtrades',NEWLINE 'orders/{id}',NEWLINE 'quotes/{id}',NEWLINE 'withdrawals',NEWLINE 'withdrawals/{id}',NEWLINE ],NEWLINE 'post': [NEWLINE 'accounts',NEWLINE 'postorder',NEWLINE 'marketorder',NEWLINE 'stoporder',NEWLINE 'funding_address',NEWLINE 'withdrawals',NEWLINE 'send',NEWLINE 'quotes',NEWLINE 'oauth2/grant',NEWLINE ],NEWLINE 'put': [NEWLINE 'quotes/{id}',NEWLINE ],NEWLINE 'delete': [NEWLINE 'quotes/{id}',NEWLINE 'withdrawals/{id}',NEWLINE ],NEWLINE },NEWLINE },NEWLINE })NEWLINENEWLINE async def fetch_markets(self, params={}):NEWLINE markets = await self.publicGetTickers()NEWLINE result = []NEWLINE for p in range(0, len(markets['tickers'])):NEWLINE market = markets['tickers'][p]NEWLINE id = market['pair']NEWLINE base = id[0:3]NEWLINE quote = id[3:6]NEWLINE base = self.common_currency_code(base)NEWLINE quote = self.common_currency_code(quote)NEWLINE symbol = base + '/' + quoteNEWLINE result.append({NEWLINE 'id': id,NEWLINE 'symbol': symbol,NEWLINE 'base': base,NEWLINE 'quote': quote,NEWLINE 'info': market,NEWLINE })NEWLINE return resultNEWLINENEWLINE async def fetch_balance(self, params={}):NEWLINE await self.load_markets()NEWLINE response = await self.privateGetBalance()NEWLINE wallets = response['balance']NEWLINE result = {'info': response}NEWLINE for b in range(0, len(wallets)):NEWLINE wallet = wallets[b]NEWLINE currency = self.common_currency_code(wallet['asset'])NEWLINE reserved = float(wallet['reserved'])NEWLINE unconfirmed = float(wallet['unconfirmed'])NEWLINE balance = float(wallet['balance'])NEWLINE account = {NEWLINE 'free': 0.0,NEWLINE 'used': self.sum(reserved, unconfirmed),NEWLINE 'total': self.sum(balance, unconfirmed),NEWLINE }NEWLINE account['free'] = account['total'] - account['used']NEWLINE result[currency] = accountNEWLINE return self.parse_balance(result)NEWLINENEWLINE async def fetch_order_book(self, symbol, limit=None, params={}):NEWLINE await self.load_markets()NEWLINE method = 'publicGetOrderbook'NEWLINE if limit is not None:NEWLINE if limit <= 100:NEWLINE method += 'Top' # get just the top of the orderbook when limit is lowNEWLINE orderbook = await getattr(self, method)(self.extend({NEWLINE 'pair': self.market_id(symbol),NEWLINE }, params))NEWLINE timestamp = orderbook['timestamp']NEWLINE return self.parse_order_book(orderbook, timestamp, 'bids', 'asks', 'price', 'volume')NEWLINENEWLINE def parse_order(self, order, market=None):NEWLINE timestamp = order['creation_timestamp']NEWLINE status = 'open' if (order['state'] == 'PENDING') else 'closed'NEWLINE side = 'sell' if (order['type'] == 'ASK') else 'buy'NEWLINE if market is None:NEWLINE market = self.find_market(order['pair'])NEWLINE symbol = market['symbol']NEWLINE price = self.safe_float(order, 'limit_price')NEWLINE amount = self.safe_float(order, 'limit_volume')NEWLINE quoteFee = self.safe_float(order, 'fee_counter')NEWLINE baseFee = self.safe_float(order, 'fee_base')NEWLINE filled = self.safe_float(order, 'base')NEWLINE cost = self.safe_float(order, 'counter')NEWLINE remaining = NoneNEWLINE if amount is not None:NEWLINE if filled is not None:NEWLINE remaining = max(0, amount - filled)NEWLINE fee = {'currency': None}NEWLINE if quoteFee:NEWLINE fee['side'] = 'quote'NEWLINE fee['cost'] = quoteFeeNEWLINE else:NEWLINE fee['side'] = 'base'NEWLINE fee['cost'] = baseFeeNEWLINE return {NEWLINE 'id': order['order_id'],NEWLINE 'datetime': self.iso8601(timestamp),NEWLINE 'timestamp': timestamp,NEWLINE 'lastTradeTimestamp': None,NEWLINE 'status': status,NEWLINE 'symbol': symbol,NEWLINE 'type': None,NEWLINE 'side': side,NEWLINE 'price': price,NEWLINE 'amount': amount,NEWLINE 'filled': filled,NEWLINE 'cost': cost,NEWLINE 'remaining': remaining,NEWLINE 'trades': None,NEWLINE 'fee': fee,NEWLINE 'info': order,NEWLINE }NEWLINENEWLINE async def fetch_order(self, id, symbol=None, params={}):NEWLINE await self.load_markets()NEWLINE response = await self.privateGetOrdersId(self.extend({NEWLINE 'id': id,NEWLINE }, params))NEWLINE return self.parse_order(response)NEWLINENEWLINE async def fetch_orders_by_state(self, state=None, symbol=None, since=None, limit=None, params={}):NEWLINE await self.load_markets()NEWLINE request = {}NEWLINE market = NoneNEWLINE if state is not None:NEWLINE request['state'] = stateNEWLINE if symbol is not None:NEWLINE market = self.market(symbol)NEWLINE request['pair'] = market['id']NEWLINE response = await self.privateGetListorders(self.extend(request, params))NEWLINE orders = self.safe_value(response, 'orders', [])NEWLINE return self.parse_orders(orders, market, since, limit)NEWLINENEWLINE async def fetch_orders(self, symbol=None, since=None, limit=None, params={}):NEWLINE return await self.fetch_orders_by_state(None, symbol, since, limit, params)NEWLINENEWLINE async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):NEWLINE return await self.fetch_orders_by_state('PENDING', symbol, since, limit, params)NEWLINENEWLINE async def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):NEWLINE return await self.fetch_orders_by_state('COMPLETE', symbol, since, limit, params)NEWLINENEWLINE def parse_ticker(self, ticker, market=None):NEWLINE timestamp = ticker['timestamp']NEWLINE symbol = NoneNEWLINE if market:NEWLINE symbol = market['symbol']NEWLINE last = self.safe_float(ticker, 'last_trade')NEWLINE return {NEWLINE 'symbol': symbol,NEWLINE 'timestamp': timestamp,NEWLINE 'datetime': self.iso8601(timestamp),NEWLINE 'high': None,NEWLINE 'low': None,NEWLINE 'bid': self.safe_float(ticker, 'bid'),NEWLINE 'bidVolume': None,NEWLINE 'ask': self.safe_float(ticker, 'ask'),NEWLINE 'askVolume': None,NEWLINE 'vwap': None,NEWLINE 'open': None,NEWLINE 'close': last,NEWLINE 'last': last,NEWLINE 'previousClose': None,NEWLINE 'change': None,NEWLINE 'percentage': None,NEWLINE 'average': None,NEWLINE 'baseVolume': self.safe_float(ticker, 'rolling_24_hour_volume'),NEWLINE 'quoteVolume': None,NEWLINE 'info': ticker,NEWLINE }NEWLINENEWLINE async def fetch_tickers(self, symbols=None, params={}):NEWLINE await self.load_markets()NEWLINE response = await self.publicGetTickers(params)NEWLINE tickers = self.index_by(response['tickers'], 'pair')NEWLINE ids = list(tickers.keys())NEWLINE result = {}NEWLINE for i in range(0, len(ids)):NEWLINE id = ids[i]NEWLINE market = self.markets_by_id[id]NEWLINE symbol = market['symbol']NEWLINE ticker = tickers[id]NEWLINE result[symbol] = self.parse_ticker(ticker, market)NEWLINE return resultNEWLINENEWLINE async def fetch_ticker(self, symbol, params={}):NEWLINE await self.load_markets()NEWLINE market = self.market(symbol)NEWLINE ticker = await self.publicGetTicker(self.extend({NEWLINE 'pair': market['id'],NEWLINE }, params))NEWLINE return self.parse_ticker(ticker, market)NEWLINENEWLINE def parse_trade(self, trade, market):NEWLINE # For public trade data(is_buy is True) indicates 'buy' side but for private trade dataNEWLINE # is_buy indicates maker or taker. The value of "type"(ASK/BID) indicate sell/buy side.NEWLINE # Private trade data includes ID field which public trade data does not.NEWLINE order = self.safe_string(trade, 'order_id')NEWLINE takerOrMaker = NoneNEWLINE side = NoneNEWLINE if order is not None:NEWLINE side = 'sell' if (trade['type'] == 'ASK') else 'buy'NEWLINE if side == 'sell' and trade['is_buy']:NEWLINE takerOrMaker = 'maker'NEWLINE elif side == 'buy' and not trade['is_buy']:NEWLINE takerOrMaker = 'maker'NEWLINE else:NEWLINE takerOrMaker = 'taker'NEWLINE else:NEWLINE side = 'buy' if (trade['is_buy']) else 'sell'NEWLINE feeBase = self.safe_float(trade, 'fee_base')NEWLINE feeCounter = self.safe_float(trade, 'fee_counter')NEWLINE feeCurrency = NoneNEWLINE feeCost = NoneNEWLINE if feeBase is not None:NEWLINE if feeBase != 0.0:NEWLINE feeCurrency = market['base']NEWLINE feeCost = feeBaseNEWLINE elif feeCounter is not None:NEWLINE if feeCounter != 0.0:NEWLINE feeCurrency = market['quote']NEWLINE feeCost = feeCounterNEWLINE return {NEWLINE 'info': trade,NEWLINE 'id': None,NEWLINE 'timestamp': trade['timestamp'],NEWLINE 'datetime': self.iso8601(trade['timestamp']),NEWLINE 'symbol': market['symbol'],NEWLINE 'order': order,NEWLINE 'type': None,NEWLINE 'side': side,NEWLINE 'takerOrMaker': takerOrMaker,NEWLINE 'price': self.safe_float(trade, 'price'),NEWLINE 'amount': self.safe_float(trade, 'volume'),NEWLINE # Does not include potential fee costsNEWLINE 'cost': self.safe_float(trade, 'counter'),NEWLINE 'fee': {NEWLINE 'cost': feeCost,NEWLINE 'currency': feeCurrency,NEWLINE },NEWLINE }NEWLINENEWLINE async def fetch_trades(self, symbol, since=None, limit=None, params={}):NEWLINE await self.load_markets()NEWLINE market = self.market(symbol)NEWLINE request = {NEWLINE 'pair': market['id'],NEWLINE }NEWLINE if since is not None:NEWLINE request['since'] = sinceNEWLINE response = await self.publicGetTrades(self.extend(request, params))NEWLINE trades = self.safe_value(response, 'trades', [])NEWLINE return self.parse_trades(trades, market, since, limit)NEWLINENEWLINE async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):NEWLINE if symbol is None:NEWLINE raise ArgumentsRequired(self.id + ' fetchMyTrades requires a symbol argument')NEWLINE await self.load_markets()NEWLINE market = self.market(symbol)NEWLINE request = {NEWLINE 'pair': market['id'],NEWLINE }NEWLINE if since is not None:NEWLINE request['since'] = sinceNEWLINE if limit is not None:NEWLINE request['limit'] = limitNEWLINE response = await self.privateGetListtrades(self.extend(request, params))NEWLINE trades = self.safe_value(response, 'trades', [])NEWLINE return self.parse_trades(trades, market, since, limit)NEWLINENEWLINE async def fetch_trading_fees(self, params={}):NEWLINE await self.load_markets()NEWLINE response = await self.privateGetFeeInfo(params)NEWLINE return {NEWLINE 'info': response,NEWLINE 'maker': self.safe_float(response, 'maker_fee'),NEWLINE 'taker': self.safe_float(response, 'taker_fee'),NEWLINE }NEWLINENEWLINE async def create_order(self, symbol, type, side, amount, price=None, params={}):NEWLINE await self.load_markets()NEWLINE method = 'privatePost'NEWLINE order = {'pair': self.market_id(symbol)}NEWLINE if type == 'market':NEWLINE method += 'Marketorder'NEWLINE order['type'] = side.upper()NEWLINE if side == 'buy':NEWLINE order['counter_volume'] = amountNEWLINE else:NEWLINE order['base_volume'] = amountNEWLINE else:NEWLINE method += 'Postorder'NEWLINE order['volume'] = amountNEWLINE order['price'] = priceNEWLINE if side == 'buy':NEWLINE order['type'] = 'BID'NEWLINE else:NEWLINE order['type'] = 'ASK'NEWLINE response = await getattr(self, method)(self.extend(order, params))NEWLINE return {NEWLINE 'info': response,NEWLINE 'id': response['order_id'],NEWLINE }NEWLINENEWLINE async def cancel_order(self, id, symbol=None, params={}):NEWLINE await self.load_markets()NEWLINE return await self.privatePostStoporder({'order_id': id})NEWLINENEWLINE def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):NEWLINE url = self.urls['api'] + '/' + self.version + '/' + self.implode_params(path, params)NEWLINE query = self.omit(params, self.extract_params(path))NEWLINE if query:NEWLINE url += '?' + self.urlencode(query)NEWLINE if api == 'private':NEWLINE self.check_required_credentials()NEWLINE auth = self.encode(self.apiKey + ':' + self.secret)NEWLINE auth = base64.b64encode(auth)NEWLINE headers = {'Authorization': 'Basic ' + self.decode(auth)}NEWLINE return {'url': url, 'method': method, 'body': body, 'headers': headers}NEWLINENEWLINE async def request(self, path, api='public', method='GET', params={}, headers=None, body=None):NEWLINE response = await self.fetch2(path, api, method, params, headers, body)NEWLINE if 'error' in response:NEWLINE raise ExchangeError(self.id + ' ' + self.json(response))NEWLINE return responseNEWLINE #! /usr/bin/python3NEWLINENEWLINE"""Create and parse 'send'-type messages."""NEWLINENEWLINEimport structNEWLINEimport jsonNEWLINEimport loggingNEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINEfrom ... import (config, exceptions, util, message_type)NEWLINENEWLINEFORMAT = '>QQ'NEWLINELENGTH = 8 + 8NEWLINEID = 0NEWLINENEWLINEdef unpack(db, message, block_index):NEWLINE # Only used for `unpack` API call at the moment.NEWLINE try:NEWLINE asset_id, quantity = struct.unpack(FORMAT, message)NEWLINE asset = util.get_asset_name(db, asset_id, block_index)NEWLINENEWLINE except struct.error:NEWLINE raise exceptions.UnpackError('could not unpack')NEWLINENEWLINE except AssetNameError:NEWLINE raise exceptions.UnpackError('asset id invalid')NEWLINENEWLINE unpacked = {NEWLINE 'asset': asset,NEWLINE 'quantity': quantityNEWLINE }NEWLINE return unpackedNEWLINENEWLINEdef validate (db, source, destination, asset, quantity, block_index):NEWLINE problems = []NEWLINENEWLINE if asset == config.BTC: problems.append('cannot send bitcoins') # Only for parsing.NEWLINENEWLINE if not isinstance(quantity, int):NEWLINE problems.append('quantity must be in satoshis')NEWLINE return problemsNEWLINENEWLINE if quantity < 0:NEWLINE problems.append('negative quantity')NEWLINENEWLINE # For SQLite3NEWLINE if quantity > config.MAX_INT:NEWLINE problems.append('integer overflow')NEWLINENEWLINE if util.enabled('send_destination_required'): # Protocol change.NEWLINE if not destination:NEWLINE problems.append('destination is required')NEWLINENEWLINE if util.enabled('options_require_memo'):NEWLINE # Check destination address optionsNEWLINENEWLINE cursor = db.cursor()NEWLINE results = cursor.execute('SELECT options FROM addresses WHERE address=?', (destination,))NEWLINE if results:NEWLINE result = results.fetchone()NEWLINE if result and util.active_options(result['options'], config.ADDRESS_OPTION_REQUIRE_MEMO):NEWLINE problems.append('destination requires memo')NEWLINE cursor.close()NEWLINENEWLINE return problemsNEWLINENEWLINEdef compose (db, source, destination, asset, quantity):NEWLINE cursor = db.cursor()NEWLINENEWLINE # Just send BTC?NEWLINE if asset == config.BTC:NEWLINE return (source, [(destination, quantity)], None)NEWLINENEWLINE # resolve subassetsNEWLINE asset = util.resolve_subasset_longname(db, asset)NEWLINENEWLINE #quantity must be in int satoshi (not float, string, etc)NEWLINE if not isinstance(quantity, int):NEWLINE raise exceptions.ComposeError('quantity must be an int (in satoshi)')NEWLINENEWLINE # Only for outgoing (incoming will overburn).NEWLINE balances = list(cursor.execute('''SELECT * FROM balances WHERE (address = ? AND asset = ?)''', (source, asset)))NEWLINE if not balances or balances[0]['quantity'] < quantity:NEWLINE raise exceptions.ComposeError('insufficient funds')NEWLINENEWLINE block_index = util.CURRENT_BLOCK_INDEXNEWLINENEWLINE problems = validate(db, source, destination, asset, quantity, block_index)NEWLINE if problems: raise exceptions.ComposeError(problems)NEWLINENEWLINE asset_id = util.get_asset_id(db, asset, block_index)NEWLINE data = message_type.pack(ID)NEWLINE data += struct.pack(FORMAT, asset_id, quantity)NEWLINENEWLINE cursor.close()NEWLINE return (source, [(destination, None)], data)NEWLINENEWLINEdef parse (db, tx, message):NEWLINE cursor = db.cursor()NEWLINENEWLINE # Unpack message.NEWLINE try:NEWLINE if len(message) != LENGTH:NEWLINE raise exceptions.UnpackErrorNEWLINE asset_id, quantity = struct.unpack(FORMAT, message)NEWLINE asset = util.get_asset_name(db, asset_id, tx['block_index'])NEWLINE status = 'valid'NEWLINE except (exceptions.UnpackError, exceptions.AssetNameError, struct.error) as e:NEWLINE asset, quantity = None, NoneNEWLINE status = 'invalid: could not unpack'NEWLINENEWLINE if status == 'valid':NEWLINE # OversendNEWLINE cursor.execute('''SELECT * FROM balances \NEWLINE WHERE (address = ? AND asset = ?)''', (tx['source'], asset))NEWLINE balances = cursor.fetchall()NEWLINE if not balances:NEWLINE status = 'invalid: insufficient funds'NEWLINE elif balances[0]['quantity'] < quantity:NEWLINE quantity = min(balances[0]['quantity'], quantity)NEWLINENEWLINE # For SQLite3NEWLINE if quantity:NEWLINE quantity = min(quantity, config.MAX_INT)NEWLINENEWLINE if status == 'valid':NEWLINE problems = validate(db, tx['source'], tx['destination'], asset, quantity, tx['block_index'])NEWLINE if problems: status = 'invalid: ' + '; '.join(problems)NEWLINENEWLINE if status == 'valid':NEWLINE util.debit(db, tx['source'], asset, quantity, action='send', event=tx['tx_hash'])NEWLINE util.credit(db, tx['destination'], asset, quantity, action='send', event=tx['tx_hash'])NEWLINENEWLINE # Add parsed transaction to message-type–specific table.NEWLINE bindings = {NEWLINE 'tx_index': tx['tx_index'],NEWLINE 'tx_hash': tx['tx_hash'],NEWLINE 'block_index': tx['block_index'],NEWLINE 'source': tx['source'],NEWLINE 'destination': tx['destination'],NEWLINE 'asset': asset,NEWLINE 'quantity': quantity,NEWLINE 'status': status,NEWLINE }NEWLINE if "integer overflow" not in status and "quantity must be in satoshis" not in status:NEWLINE sql = 'insert into sends (tx_index, tx_hash, block_index, source, destination, asset, quantity, status, memo) values(:tx_index, :tx_hash, :block_index, :source, :destination, :asset, :quantity, :status, NULL)'NEWLINE cursor.execute(sql, bindings)NEWLINE else:NEWLINE logger.warn("Not storing [send] tx [%s]: %s" % (tx['tx_hash'], status))NEWLINE logger.debug("Bindings: %s" % (json.dumps(bindings), ))NEWLINENEWLINENEWLINE cursor.close()NEWLINENEWLINE# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4NEWLINE from neo.Prompt.Commands.Invoke import InvokeContract, InvokeWithTokenVerificationScriptNEWLINEfrom neo.Core.Fixed8 import Fixed8NEWLINEfrom neo.Core.UInt160 import UInt160NEWLINEfrom neo.Network.common import blocking_prompt as promptNEWLINEfrom decimal import DecimalNEWLINEfrom neo.Core.TX.TransactionAttribute import TransactionAttributeNEWLINEimport binasciiNEWLINEfrom neo.Prompt.CommandBase import CommandBase, CommandDesc, ParameterDescNEWLINEfrom neo.Prompt.PromptData import PromptDataNEWLINEfrom neo.Prompt import Utils as PromptUtilsNEWLINEfrom neo.Implementations.Wallets.peewee.Models import NEP5Token as ModelNEP5TokenNEWLINEfrom neo.Implementations.Notifications.NotificationDB import NotificationDBNEWLINEfrom neo.Core.TX.TransactionAttribute import TransactionAttributeUsageNEWLINEfrom neo.Core.Utils import isValidPublicAddressNEWLINEimport peeweeNEWLINEimport tracebackNEWLINEfrom neo.Prompt.PromptPrinter import prompt_print as printNEWLINEfrom neo.logging import log_managerNEWLINENEWLINElogger = log_manager.getLogger()NEWLINENEWLINENEWLINEclass CommandWalletToken(CommandBase):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINE self.register_sub_command(CommandTokenDelete())NEWLINE self.register_sub_command(CommandTokenSend())NEWLINE self.register_sub_command(CommandTokenSendFrom())NEWLINE self.register_sub_command(CommandTokenHistory())NEWLINE self.register_sub_command(CommandTokenApprove())NEWLINE self.register_sub_command(CommandTokenAllowance())NEWLINE self.register_sub_command(CommandTokenMint())NEWLINE self.register_sub_command(CommandTokenRegister())NEWLINENEWLINE def command_desc(self):NEWLINE return CommandDesc('token', 'various token operations')NEWLINENEWLINE def execute(self, arguments):NEWLINE item = PromptUtils.get_arg(arguments)NEWLINENEWLINE if not item:NEWLINE print(f"run `{self.command_desc().command} help` to see supported queries")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE return self.execute_sub_command(item, arguments[1:])NEWLINE except KeyError:NEWLINE print(f"{item} is an invalid parameter")NEWLINE return FalseNEWLINENEWLINENEWLINEclass CommandTokenDelete(CommandBase):NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) != 1:NEWLINE print("Please specify the required parameter")NEWLINE return FalseNEWLINENEWLINE hash_string = arguments[0]NEWLINE try:NEWLINE script_hash = UInt160.ParseString(hash_string)NEWLINE except Exception:NEWLINE # because UInt160 throws a generic exception. Should be fixed in the futureNEWLINE print("Invalid script hash")NEWLINE return FalseNEWLINENEWLINE # try to find token and collect some dataNEWLINE try:NEWLINE token = ModelNEP5Token.get(ContractHash=script_hash)NEWLINE except peewee.DoesNotExist:NEWLINE print(f"Could not find a token with script_hash {arguments[0]}")NEWLINE return FalseNEWLINENEWLINE success = wallet.DeleteNEP5Token(script_hash)NEWLINE if success:NEWLINE print(f"Token {token.Symbol} with script_hash {arguments[0]} deleted")NEWLINE else:NEWLINE # probably unreachable to due token check earlier. Better safe than sorrowNEWLINE print(f"Could not find a token with script_hash {arguments[0]}")NEWLINENEWLINE return successNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('contract', 'token contract hash (script hash)')NEWLINE return CommandDesc('delete', 'remove a token from the wallet', [p1])NEWLINENEWLINENEWLINEclass CommandTokenSend(CommandBase):NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 4:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE if len(arguments) > 6:NEWLINE # the 5th and 6th arguments are optionalNEWLINE print("Too many parameters supplied. Please check your command")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINE arguments, user_tx_attributes = PromptUtils.get_tx_attr_from_args(arguments)NEWLINENEWLINE token = arguments[0]NEWLINE from_addr = arguments[1]NEWLINE to_addr = arguments[2]NEWLINE try:NEWLINE amount = float(arguments[3])NEWLINE except ValueError:NEWLINE print(f"{arguments[3]} is not a valid amount")NEWLINE return FalseNEWLINENEWLINE fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE fee = priority_feeNEWLINE if fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE success = token_send(wallet, token, from_addr, to_addr, amount, fee=fee, user_tx_attributes=user_tx_attributes)NEWLINE except ValueError as e:NEWLINE # occurs if arguments are invalidNEWLINE print(str(e))NEWLINE success = FalseNEWLINENEWLINE return successNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('token', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('from_addr', 'address to send token from')NEWLINE p3 = ParameterDesc('to_addr', 'address to send token to')NEWLINE p4 = ParameterDesc('amount', 'number of tokens to send')NEWLINE p5 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINE p6 = ParameterDesc('--tx-attr', f"a list of transaction attributes to attach to the transaction\n\n"NEWLINE f"{' ':>17} See: http://docs.neo.org/en-us/network/network-protocol.html section 4 for a description of possible attributes\n\n" # noqa: E128 ignore indentationNEWLINE f"{' ':>17} Example:\n"NEWLINE f"{' ':>20} --tx-attr=[{{\"usage\": ,\"data\":\"\"}}, ...]\n"NEWLINE f"{' ':>20} --tx-attr=[{{\"usage\": 0x90,\"data\":\"my brief description\"}}]\n", optional=True)NEWLINENEWLINE return CommandDesc('send', 'send a token from the wallet', [p1, p2, p3, p4, p5, p6])NEWLINENEWLINENEWLINEclass CommandTokenSendFrom(CommandBase):NEWLINE """NEWLINE This command is for old style NEP-5 tokens before the proposal got amended to remove this optional command.NEWLINE """NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 4:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINENEWLINE token_str = arguments[0]NEWLINE from_addr = arguments[1]NEWLINE to_addr = arguments[2]NEWLINENEWLINE try:NEWLINE amount = float(arguments[3])NEWLINE except ValueError:NEWLINE print(f"{arguments[3]} is not a valid amount")NEWLINE return FalseNEWLINENEWLINE p_fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE p_fee = priority_feeNEWLINE if p_fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE token, tx, fee, results = test_token_send_from(wallet, token_str, from_addr, to_addr, amount)NEWLINE except ValueError as e:NEWLINE # invalid arguments or bad allowanceNEWLINE print(str(e))NEWLINE return FalseNEWLINE except Exception as e:NEWLINE # we act as the final capturing placeNEWLINE print("Something really unexpected happened")NEWLINE logger.error(traceback.format_exc())NEWLINE return FalseNEWLINENEWLINE if tx is not None and results is not None:NEWLINE vm_result = results[0].GetBigInteger()NEWLINE if vm_result == 1:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print("Transfer of %s %s from %s to %s" % (NEWLINE string_from_amount(token, amount), token.symbol, from_addr, to_addr))NEWLINE print("Transfer fee: %s " % (fee.value / Fixed8.D))NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Transfer Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Transaction cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeContract(wallet, tx, comb_fee)NEWLINENEWLINE print(f"Could not transfer tokens. Virtual machine returned: {vm_result}")NEWLINE return FalseNEWLINENEWLINE print(f"Could not transfer tokens. An unknown error occurred resulting in no Transaction object or VM output.")NEWLINE return FalseNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('token', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('from_addr', 'address to send token from')NEWLINE p3 = ParameterDesc('to_addr', 'address to send token to')NEWLINE p4 = ParameterDesc('amount', 'number of tokens to send')NEWLINE p5 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINENEWLINE return CommandDesc('sendfrom', 'send a token on behalf of another account (requires approval)', [p1, p2, p3, p4, p5])NEWLINENEWLINENEWLINEclass CommandTokenHistory(CommandBase):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) != 1:NEWLINE print("Please specify the required parameter")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE token, events = token_history(wallet, arguments[0])NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE if events:NEWLINE addresses = wallet.AddressesNEWLINE print("-----------------------------------------------------------")NEWLINE print("Recent transaction history (last = more recent):")NEWLINE for event in events:NEWLINE if event.Type != 'transfer':NEWLINE continueNEWLINE if event.AddressFrom in addresses:NEWLINE print(f"[{event.AddressFrom}]: Sent {string_from_amount(token, event.Amount)}"NEWLINE f" {token.symbol} to {event.AddressTo}")NEWLINE if event.AddressTo in addresses:NEWLINE print(f"[{event.AddressTo}]: Received {string_from_amount(token, event.Amount)}"NEWLINE f" {token.symbol} from {event.AddressFrom}")NEWLINE print("-----------------------------------------------------------")NEWLINE else:NEWLINE print("History contains no transactions")NEWLINE return TrueNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE return CommandDesc('history', 'show transaction history', [p1])NEWLINENEWLINENEWLINEclass CommandTokenApprove(CommandBase):NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 4:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINENEWLINE token_str = arguments[0]NEWLINE from_addr = arguments[1]NEWLINE to_addr = arguments[2]NEWLINENEWLINE try:NEWLINE amount = float(arguments[3])NEWLINE except ValueError:NEWLINE print(f"{arguments[3]} is not a valid amount")NEWLINE return FalseNEWLINENEWLINE p_fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE p_fee = priority_feeNEWLINE if p_fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE token = _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount)NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE decimal_amount = amount_from_string(token, amount)NEWLINENEWLINE tx, fee, results = token.Approve(wallet, from_addr, to_addr, decimal_amount)NEWLINENEWLINE if tx is not None and results is not None:NEWLINE if results[0].GetBigInteger() == 1:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print(f"Approve allowance of {amount} {token.symbol} from {from_addr} to {to_addr}")NEWLINE print(f"Invocation fee: {fee.value / Fixed8.D}")NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Invocation Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Allowance approval cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeContract(wallet, tx, comb_fee)NEWLINENEWLINE print("Failed to approve tokens. Make sure you are entitled for approving.")NEWLINE return FalseNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('from_addr', 'address to send token from')NEWLINE p3 = ParameterDesc('to_addr', 'address to send token to')NEWLINE p4 = ParameterDesc('amount', 'number of tokens to send')NEWLINE p5 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINENEWLINE return CommandDesc('approve', 'approve an allowance', [p1, p2, p3, p4, p5])NEWLINENEWLINE def handle_help(self, arguments):NEWLINE super().handle_help(arguments)NEWLINE print(NEWLINE "\nThis is an optional NEP-5 command (now legacy).\nFor more information see https://github.com/neo-project/proposals/blob/c357f5965afc2155615b6b96c7d15da688f81982/nep-5.mediawiki#approve_optional")NEWLINENEWLINENEWLINEclass CommandTokenAllowance(CommandBase):NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) != 3:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE token_str = arguments[0]NEWLINE from_addr = arguments[1]NEWLINE to_addr = arguments[2]NEWLINENEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE try:NEWLINE allowance = token_get_allowance(wallet, token_str, from_addr, to_addr)NEWLINE print(f"{token.symbol} allowance for {from_addr} from {to_addr} : {allowance} ")NEWLINE return TrueNEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('from_addr', 'address to send token from')NEWLINE p3 = ParameterDesc('to_addr', 'address to send token to')NEWLINENEWLINE return CommandDesc('allowance', 'get the amount an account can transfer from another acount', [p1, p2, p3])NEWLINENEWLINENEWLINEclass CommandTokenMint(CommandBase):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 2:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE if len(arguments) > 6:NEWLINE # the 3rd and 4th argument are for attaching neo/gas, 5th for attaching a fee, 6th for attaching attributesNEWLINE print("Too many parameters supplied. Please check your command")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINE arguments, invoke_attrs = PromptUtils.get_tx_attr_from_args(arguments)NEWLINENEWLINE token_str = arguments[0]NEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE to_addr = arguments[1]NEWLINE if not isValidPublicAddress(to_addr):NEWLINE print(f"{to_addr} is not a valid address")NEWLINE return FalseNEWLINENEWLINE remaining_args = arguments[2:]NEWLINE asset_attachments = []NEWLINE for optional in remaining_args:NEWLINE _, neo_to_attach, gas_to_attach = PromptUtils.get_asset_attachments([optional])NEWLINENEWLINE if "attach-neo" in optional:NEWLINE if not neo_to_attach:NEWLINE print(f"Could not parse value from --attach-neo. Value must be an integer")NEWLINE return FalseNEWLINE else:NEWLINE asset_attachments.append(optional)NEWLINENEWLINE if "attach-gas" in optional:NEWLINE if not gas_to_attach:NEWLINE print(f"Could not parse value from --attach-gas")NEWLINE return FalseNEWLINE else:NEWLINE asset_attachments.append(optional)NEWLINENEWLINE fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE fee = priority_feeNEWLINE if fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE return token_mint(token, wallet, to_addr, asset_attachments=asset_attachments, fee=fee, invoke_attrs=invoke_attrs)NEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('to_addr', 'address to mint tokens to')NEWLINE p3 = ParameterDesc('--attach-neo', 'amount of neo to attach to the transaction', optional=True)NEWLINE p4 = ParameterDesc('--attach-gas', 'amount of gas to attach to the transaction', optional=True)NEWLINE p5 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINE p6 = ParameterDesc('--tx-attr', f"a list of transaction attributes to attach to the transaction\n\n"NEWLINE f"{' ':>17} See: http://docs.neo.org/en-us/network/network-protocol.html section 4 for a description of possible attributes\n\n" # noqa: E128 ignore indentationNEWLINE f"{' ':>17} Example:\n"NEWLINE f"{' ':>20} --tx-attr=[{{\"usage\": ,\"data\":\"\"}}, ...]\n"NEWLINE f"{' ':>20} --tx-attr=[{{\"usage\": 0x90,\"data\":\"my brief description\"}}]\n", optional=True)NEWLINENEWLINE return CommandDesc('mint', 'mint tokens from a contract', [p1, p2, p3, p4, p5, p6])NEWLINENEWLINENEWLINEclass CommandTokenRegister(CommandBase):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 2:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINENEWLINE token_str = arguments[0]NEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE register_addr = arguments[1:]NEWLINE addr_list = []NEWLINE for addr in register_addr:NEWLINE if isValidPublicAddress(addr):NEWLINE addr_list.append(addr)NEWLINE else:NEWLINE print(f"{addr} is not a valid address")NEWLINE return FalseNEWLINENEWLINE p_fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE p_fee = priority_feeNEWLINE if p_fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE tx, fee, results = token.CrowdsaleRegister(wallet, addr_list)NEWLINENEWLINE if tx is not None and results is not None:NEWLINE if len(results) > 0 and results[0].GetBigInteger() > 0:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print("[%s] Will register addresses for crowdsale: %s " % (token.symbol, register_addr))NEWLINE print("Invocation Fee: %s " % (fee.value / Fixed8.D))NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Invocation Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Registration cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeContract(wallet, tx, comb_fee)NEWLINENEWLINE print("Could not register address(es)")NEWLINE return FalseNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('addresses', 'space separated list of NEO addresses')NEWLINE p3 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINE return CommandDesc('register', 'register for a crowd sale', [p1, p2, p3])NEWLINENEWLINENEWLINEdef _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount):NEWLINE """NEWLINE A helper function to validate common arguments used in NEP-5 functionsNEWLINENEWLINE Args:NEWLINE wallet (Wallet): a UserWallet instanceNEWLINE token_str (str): symbol name or script_hashNEWLINE from_addr (str): a wallet addressNEWLINE to_addr (str): a wallet addressNEWLINE amount (float): the number of tokens to sendNEWLINENEWLINE Raises:NEWLINE ValueError: for invalid argumentsNEWLINENEWLINE Returns:NEWLINE token (NEP5Token): instanceNEWLINE """NEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError:NEWLINE raiseNEWLINENEWLINE if not isValidPublicAddress(from_addr):NEWLINE raise ValueError("send_from is not a valid address")NEWLINENEWLINE if not isValidPublicAddress(to_addr):NEWLINE raise ValueError("send_to is not a valid address")NEWLINENEWLINE try:NEWLINE # internally this function uses the `Decimal` class which will parse the float amount to its required format.NEWLINE # the name is a bit misleading /shrugNEWLINE amount = amount_from_string(token, amount)NEWLINE except Exception:NEWLINE raise ValueError(f"{amount} is not a valid amount")NEWLINENEWLINE return tokenNEWLINENEWLINENEWLINEdef token_send(wallet, token_str, from_addr, to_addr, amount, fee=Fixed8.Zero(), user_tx_attributes=None):NEWLINE """NEWLINE Send `amount` of tokens from `from_addr` to `to_addr`NEWLINENEWLINE Args:NEWLINE wallet (Wallet): a UserWallet instanceNEWLINE token_str (str): symbol name or script_hashNEWLINE from_addr (str): a wallet addressNEWLINE to_addr (str): a wallet addressNEWLINE amount (float): the number of tokens to sendNEWLINE fee (Fixed8): (optional) a fee to give the transaction priority (> 0.001) NEWLINE user_tx_attributes (list): a list of ``TransactionAttribute``s.NEWLINENEWLINE Raises:NEWLINE ValueError: for invalid argumentsNEWLINENEWLINE Returns:NEWLINE a Transaction object if successful, False otherwise.NEWLINE """NEWLINE if not user_tx_attributes:NEWLINE user_tx_attributes = []NEWLINENEWLINE try:NEWLINE token = _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount)NEWLINE except ValueError:NEWLINE # just making it explicit for the readerNEWLINE raiseNEWLINENEWLINE for attr in user_tx_attributes:NEWLINE if not isinstance(attr, TransactionAttribute):NEWLINE raise ValueError(f"{attr} is not a valid transaction attribute")NEWLINENEWLINE decimal_amount = amount_from_string(token, amount)NEWLINENEWLINE return do_token_transfer(token, wallet, from_addr, to_addr, decimal_amount, fee=fee, tx_attributes=user_tx_attributes)NEWLINENEWLINENEWLINEdef test_token_send_from(wallet, token_str, from_addr, to_addr, amount):NEWLINE """NEWLINE Test sending funds from `addr_from` to `addr_to` without commiting to the network.NEWLINENEWLINE This does a local test to validate all supplied arguments and if the blockchain state allows for the transfer.NEWLINENEWLINE Args:NEWLINE wallet (Wallet): a UserWallet instanceNEWLINE token_str (str): symbol name or script_hashNEWLINE from_addr (str): a wallet addressNEWLINE to_addr (str): a wallet addressNEWLINE amount (float): the number of tokens to sendNEWLINENEWLINE Raises:NEWLINE ValueError: for invalid arguments or if allowance is insufficient.NEWLINENEWLINE Returns:NEWLINE tuple:NEWLINE token (NEP5Token): instanceNEWLINE InvocationTransaction: the transaction.NEWLINE int: the transaction fee.NEWLINE list: the neo VM evaluation stack results.NEWLINE """NEWLINE try:NEWLINE token = _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount)NEWLINE allowance = token_get_allowance(wallet, token_str, from_addr, to_addr, verbose=False)NEWLINENEWLINE if allowance < amount:NEWLINE raise ValueError(f"Insufficient allowance: {allowance}")NEWLINE except ValueError:NEWLINE # bad args or allowanceNEWLINE raiseNEWLINENEWLINE tx, fees, results = token.TransferFrom(wallet, from_addr, to_addr, amount)NEWLINE return token, tx, fees, resultsNEWLINENEWLINENEWLINEdef token_get_allowance(wallet, token_str, from_addr, to_addr, verbose=False):NEWLINE """NEWLINE Query the smart contract for the amount from_addr is allowed to send to to_addrNEWLINENEWLINE Requires amount to be `approved`.NEWLINENEWLINE Args:NEWLINE wallet (Wallet): a UserWallet instanceNEWLINE token_str (str): symbol name or script_hashNEWLINE from_addr (str): a wallet addressNEWLINE to_addr (str): a wallet addressNEWLINE verbose (bool): flag indicating whether to print VM resultsNEWLINENEWLINE Raises:NEWLINE ValueError: for invalid arguments or if allowance could not be queriedNEWLINENEWLINE Returns:NEWLINE int: allowanceNEWLINE """NEWLINE try:NEWLINE token = _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount=0)NEWLINE except ValueError:NEWLINE raiseNEWLINENEWLINE tx, fee, results = token.Allowance(wallet, from_addr, to_addr)NEWLINENEWLINE if tx is not None and results is not None:NEWLINE allowance = results[0].GetBigInteger()NEWLINE if verbose:NEWLINE print("%s allowance for %s from %s : %s " % (token.symbol, from_addr, to_addr, allowance))NEWLINENEWLINE return allowanceNEWLINE else:NEWLINE if verbose:NEWLINE print("Could not get allowance for token %s " % token.symbol)NEWLINE raise ValueError(f"Could not get allowance for token {token.symbol}")NEWLINENEWLINENEWLINEdef token_mint(token, wallet, to_addr, asset_attachments=[], fee=Fixed8.Zero(), invoke_attrs=None):NEWLINE if not invoke_attrs:NEWLINE invoke_attrs = []NEWLINENEWLINE p_fee = feeNEWLINENEWLINE tx, fee, results = token.Mint(wallet, to_addr, asset_attachments, invoke_attrs=invoke_attrs)NEWLINENEWLINE if tx is not None and results is not None:NEWLINE if len(results) > 0 and results[0] is not None:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print(f"[{token.symbol}] Will mint tokens to address: {to_addr}")NEWLINE print(f"Invocation Fee: {fee.value / Fixed8.D}")NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Invocation Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Token mint cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeWithTokenVerificationScript(wallet, tx, token, comb_fee, invoke_attrs=invoke_attrs)NEWLINENEWLINE print("Failed to mint tokens")NEWLINE return FalseNEWLINENEWLINENEWLINEdef do_token_transfer(token, wallet, from_address, to_address, amount, fee=Fixed8.Zero(), tx_attributes=None):NEWLINE if not tx_attributes:NEWLINE tx_attributes = []NEWLINENEWLINE p_fee = feeNEWLINENEWLINE # because we cannot differentiate between a normal and multisig from_addr, and because we want to makeNEWLINE # sending NEP5 tokens straight forward even when sending from multisig addresses, we include the script_hashNEWLINE # for verification by default to the transaction attributes. See PR/Issue: https://github.com/CityOfZion/neo-python/pull/491NEWLINE from_script_hash = binascii.unhexlify(bytes(wallet.ToScriptHash(from_address).ToString2(), 'utf-8'))NEWLINE tx_attributes.append(TransactionAttribute(usage=TransactionAttributeUsage.Script, data=from_script_hash))NEWLINENEWLINE tx, fee, results = token.Transfer(wallet, from_address, to_address, amount, tx_attributes=tx_attributes)NEWLINENEWLINE if tx is not None and results is not None and len(results) > 0:NEWLINENEWLINE if results[0].GetBigInteger() == 1:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print("Will transfer %s %s from %s to %s" % (string_from_amount(token, amount), token.symbol, from_address, to_address))NEWLINE print("Transfer fee: %s " % (fee.value / Fixed8.D))NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Transfer Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Transfer cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeContract(wallet, tx, comb_fee)NEWLINENEWLINE print("could not transfer tokens")NEWLINE return FalseNEWLINENEWLINENEWLINEdef token_history(wallet, token_str):NEWLINE notification_db = NotificationDB.instance()NEWLINENEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError:NEWLINE raiseNEWLINENEWLINE events = notification_db.get_by_contract(token.ScriptHash)NEWLINE return token, eventsNEWLINENEWLINENEWLINEdef amount_from_string(token, amount_str):NEWLINE precision_mult = pow(10, token.decimals)NEWLINE amount = Decimal(amount_str) * precision_multNEWLINENEWLINE return int(amount)NEWLINENEWLINENEWLINEdef string_from_amount(token, amount):NEWLINE precision_mult = pow(10, token.decimals)NEWLINE amount = Decimal(amount) / Decimal(precision_mult)NEWLINE formatter_str = '.%sf' % token.decimalsNEWLINE amount_str = format(amount, formatter_str)NEWLINENEWLINE return amount_strNEWLINE #!/usr/bin/env python3NEWLINE"""NEWLINEpixivNEWLINENEWLINEUsage:NEWLINE pixiv.pyNEWLINE pixiv.py ...NEWLINE pixiv.py -r [-d | --date=]NEWLINE pixiv.py -uNEWLINENEWLINEArguments:NEWLINE user_idsNEWLINENEWLINEOptions:NEWLINE -r Download by rankingNEWLINE -d --date Target dateNEWLINE -u Update exist folderNEWLINE -h --help Show this screenNEWLINE -v --version Show versionNEWLINENEWLINEExamples:NEWLINE pixiv.py 7210261 1980643NEWLINE pixiv.py -r -d 2016-09-24NEWLINE"""NEWLINEimport datetimeNEWLINEimport mathNEWLINEimport osNEWLINEimport queueNEWLINEimport reNEWLINEimport sysNEWLINEimport threadingNEWLINEimport timeNEWLINEimport tracebackNEWLINENEWLINEimport requestsNEWLINEfrom docopt import docoptNEWLINEfrom tqdm import tqdmNEWLINENEWLINEfrom api import PixivApiNEWLINEfrom i18n import i18n as _NEWLINEfrom model import PixivIllustModelNEWLINENEWLINE_THREADING_NUMBER = 10NEWLINE_finished_download = 0NEWLINE_CREATE_FOLDER_LOCK = threading.Lock()NEWLINE_PROGRESS_LOCK = threading.Lock()NEWLINE_SPEED_LOCK = threading.Lock()NEWLINE_Global_Download = 0NEWLINE_error_count = {}NEWLINE_ILLUST_PER_PAGE = 30NEWLINE_MAX_ERROR_COUNT = 5NEWLINENEWLINENEWLINEdef get_default_save_path():NEWLINE current_path = os.path.dirname(os.path.abspath(sys.argv[0]))NEWLINE filepath = os.path.join(current_path, 'illustrations')NEWLINE if not os.path.exists(filepath):NEWLINE with _CREATE_FOLDER_LOCK:NEWLINE if not os.path.exists(os.path.dirname(filepath)):NEWLINE os.makedirs(os.path.dirname(filepath))NEWLINE os.makedirs(filepath)NEWLINE return filepathNEWLINENEWLINENEWLINEdef get_speed(elapsed):NEWLINE """Get current download speed"""NEWLINE with _SPEED_LOCK:NEWLINE global _Global_DownloadNEWLINE down = _Global_DownloadNEWLINE _Global_Download = 0NEWLINE speed = down / elapsedNEWLINE if speed == 0:NEWLINE return '%8.2f /s' % 0NEWLINE units = [' B', 'KB', 'MB', 'GB', 'TB', 'PB']NEWLINE unit = math.floor(math.log(speed, 1024.0))NEWLINE speed /= math.pow(1024.0, unit)NEWLINE return '%6.2f %s/s' % (speed, units[unit])NEWLINENEWLINENEWLINEdef print_progress(max_size):NEWLINE global _finished_downloadNEWLINE pbar = tqdm(total=max_size)NEWLINENEWLINE last = 0NEWLINE while _finished_download != max_size:NEWLINE pbar.update(_finished_download - last)NEWLINE last = _finished_downloadNEWLINE time.sleep(0.5)NEWLINE pbar.update(_finished_download - last)NEWLINE pbar.close()NEWLINENEWLINENEWLINEdef download_file(url, filepath):NEWLINE headers = {'Referer': 'http://www.pixiv.net/'}NEWLINE r = requests.get(url, headers=headers, stream=True, timeout=PixivApi.timeout)NEWLINE if r.status_code == requests.codes.ok:NEWLINE total_length = r.headers.get('content-length')NEWLINE if total_length:NEWLINE data = []NEWLINE for chunk in r.iter_content(1024 * 16):NEWLINE data.append(chunk)NEWLINE with _SPEED_LOCK:NEWLINE global _Global_DownloadNEWLINE _Global_Download += len(chunk)NEWLINE with open(filepath, 'wb') as f:NEWLINE list(map(f.write, data))NEWLINE else:NEWLINE raise ConnectionError('\r', _('Connection error: %s') % r.status_code)NEWLINENEWLINENEWLINEdef download_threading(download_queue):NEWLINE global _finished_downloadNEWLINE while not download_queue.empty():NEWLINE illustration = download_queue.get()NEWLINE filepath = illustration['path']NEWLINE filename = illustration['file']NEWLINE url = illustration['url']NEWLINE count = _error_count.get(url, 0)NEWLINE if count < _MAX_ERROR_COUNT:NEWLINE if not os.path.exists(filepath):NEWLINE with _CREATE_FOLDER_LOCK:NEWLINE if not os.path.exists(os.path.dirname(filepath)):NEWLINE os.makedirs(os.path.dirname(filepath))NEWLINE try:NEWLINE download_file(url, filepath)NEWLINE with _PROGRESS_LOCK:NEWLINE _finished_download += 1NEWLINE except Exception as e:NEWLINE if count < _MAX_ERROR_COUNT:NEWLINE print(_('%s => %s download error, retry') % (e, filename))NEWLINE download_queue.put(illustration)NEWLINE _error_count[url] = count + 1NEWLINE else:NEWLINE print(url, 'reach max retries, canceled')NEWLINE with _PROGRESS_LOCK:NEWLINE _finished_download += 1NEWLINE download_queue.task_done()NEWLINENEWLINENEWLINEdef start_and_wait_download_threading(download_queue, count):NEWLINE """start download threading and wait till complete"""NEWLINE progress_t = threading.Thread(target=print_progress, args=(count,))NEWLINE progress_t.daemon = TrueNEWLINE progress_t.start()NEWLINE for i in range(_THREADING_NUMBER):NEWLINE download_t = threading.Thread(target=download_threading, args=(download_queue,))NEWLINE download_t.daemon = TrueNEWLINE download_t.start()NEWLINENEWLINE progress_t.join()NEWLINE download_queue.join()NEWLINENEWLINENEWLINEdef get_filepath(url, illustration, save_path='.', add_user_folder=False, add_rank=False):NEWLINE """return (filename,filepath)"""NEWLINENEWLINE if add_user_folder:NEWLINE user_id = illustration.user_idNEWLINE user_name = illustration.user_nameNEWLINE current_path = get_default_save_path()NEWLINE cur_dirs = list(filter(os.path.isdir, [os.path.join(current_path, i) for i in os.listdir(current_path)]))NEWLINE cur_user_ids = [os.path.basename(cur_dir).split()[0] for cur_dir in cur_dirs]NEWLINE if user_id not in cur_user_ids:NEWLINE dir_name = re.sub(r'[<>:"/\\|\?\*]', ' ', user_id + ' ' + user_name)NEWLINE else:NEWLINE dir_name = list(i for i in cur_dirs if os.path.basename(i).split()[0] == user_id)[0]NEWLINE save_path = os.path.join(save_path, dir_name)NEWLINENEWLINE filename = url.split('/')[-1]NEWLINE if add_rank:NEWLINE filename = f'{illustration.rank} - {filename}'NEWLINE filepath = os.path.join(save_path, filename)NEWLINE return filename, filepathNEWLINENEWLINENEWLINEdef check_files(illustrations, save_path='.', add_user_folder=False, add_rank=False):NEWLINE download_queue = queue.Queue()NEWLINE index_list = []NEWLINE count = 0NEWLINE if illustrations:NEWLINE last_i = -1NEWLINE for index, illustration in enumerate(illustrations):NEWLINE if not illustration.image_urls:NEWLINE continueNEWLINE else:NEWLINE for url in illustration.image_urls:NEWLINE filename, filepath = get_filepath(url, illustration, save_path, add_user_folder, add_rank)NEWLINE if os.path.exists(filepath):NEWLINE continueNEWLINE else:NEWLINE if last_i != index:NEWLINE last_i = indexNEWLINE index_list.append(index)NEWLINE download_queue.put({'url': url, 'file': filename, 'path': filepath})NEWLINE count += 1NEWLINE return download_queue, count, index_listNEWLINENEWLINENEWLINEdef count_illustrations(illustrations):NEWLINE return sum(len(i.image_urls) for i in illustrations)NEWLINENEWLINENEWLINEdef is_manga(illustrate):NEWLINE return True if illustrate.is_manga or illustrate.type == 'manga' else FalseNEWLINENEWLINENEWLINEdef download_illustrations(user, data_list, save_path='.', add_user_folder=False, add_rank=False, skip_manga=False):NEWLINE """Download illustratonsNEWLINENEWLINE Args:NEWLINE user: PixivApi()NEWLINE data_list: jsonNEWLINE save_path: str, download path of the illustrationsNEWLINE add_user_folder: bool, whether put the illustration into user folderNEWLINE add_rank: bool, add illustration rank at the beginning of filenameNEWLINE """NEWLINE illustrations = PixivIllustModel.from_data(data_list)NEWLINE if skip_manga:NEWLINE manga_number = sum([is_manga(i) for i in illustrations])NEWLINE if manga_number:NEWLINE print('skip', manga_number, 'manga')NEWLINE illustrations = list(filter(lambda x: not is_manga(x), illustrations))NEWLINE download_queue, count = check_files(illustrations, save_path, add_user_folder, add_rank)[0:2]NEWLINE if count > 0:NEWLINE print(_('Start download, total illustrations '), count)NEWLINE global _finished_download, _Global_DownloadNEWLINE _finished_download = 0NEWLINE _Global_Download = 0NEWLINE start_and_wait_download_threading(download_queue, count)NEWLINE print()NEWLINE else:NEWLINE print(_('There is no new illustration need to download'))NEWLINENEWLINENEWLINEdef download_by_user_id(user, user_ids=None):NEWLINE save_path = get_default_save_path()NEWLINE if not user_ids:NEWLINE user_ids = input(_('Input the artist\'s id:(separate with space)')).strip().split(' ')NEWLINE for user_id in user_ids:NEWLINE print(_('Artists %s') % user_id)NEWLINE data_list = user.get_all_user_illustrations(user_id)NEWLINE download_illustrations(user, data_list, save_path, add_user_folder=True)NEWLINENEWLINENEWLINEdef download_by_ranking(user):NEWLINE today = str(datetime.date.today())NEWLINE save_path = os.path.join(get_default_save_path(), today + ' ranking')NEWLINE data_list = user.get_ranking_illustrations()NEWLINE download_illustrations(user, data_list, save_path, add_rank=True)NEWLINENEWLINENEWLINEdef download_by_history_ranking(user, date=''):NEWLINE if not date:NEWLINE date = input(_('Input the date:(eg:2015-07-10)'))NEWLINE if not (re.search("^\d{4}-\d{2}-\d{2}", date)):NEWLINE print(_('[invalid date format]'))NEWLINE date = str(datetime.date.today() - datetime.timedelta(days=1))NEWLINE save_path = os.path.join(get_default_save_path(), date + ' ranking')NEWLINE data_list = user.get_ranking_illustrations(date=date)NEWLINE download_illustrations(user, data_list, save_path, add_rank=True)NEWLINENEWLINENEWLINEdef artist_folder_scanner(user, user_id_list, save_path, final_list, fast):NEWLINE while not user_id_list.empty():NEWLINE user_info = user_id_list.get()NEWLINE user_id = user_info['id']NEWLINE folder = user_info['folder']NEWLINE try:NEWLINE if fast:NEWLINE data_list = []NEWLINE offset = 0NEWLINE page_result = user.get_all_user_illustrations(user_id, offset, _ILLUST_PER_PAGE)NEWLINE if len(page_result) > 0:NEWLINE data_list.extend(page_result)NEWLINE file_path = os.path.join(save_path, folder, data_list[-1]['image_urls']['large'].split('/')[-1])NEWLINE while not os.path.exists(file_path) and len(page_result) == _ILLUST_PER_PAGE:NEWLINE offset += _ILLUST_PER_PAGENEWLINE page_result = user.get_all_user_illustrations(user_id, offset, _ILLUST_PER_PAGE)NEWLINE data_list.extend(page_result)NEWLINE file_path = os.path.join(save_path, folder, data_list[-1]['image_urls']['large'].split('/')[-1])NEWLINE # prevent rate limitNEWLINE time.sleep(1)NEWLINE else:NEWLINE data_list = user.get_all_user_illustrations(user_id)NEWLINE illustrations = PixivIllustModel.from_data(data_list)NEWLINE count, checked_list = check_files(illustrations, save_path, add_user_folder=True, add_rank=False)[1:3]NEWLINE if len(sys.argv) < 2 or count:NEWLINE try:NEWLINE print(_('Artists %s [%s]') % (folder, count))NEWLINE except UnicodeError:NEWLINE print(_('Artists %s ?? [%s]') % (user_id, count))NEWLINE with _PROGRESS_LOCK:NEWLINE for index in checked_list:NEWLINE final_list.append(data_list[index])NEWLINE except Exception:NEWLINE traceback.print_exc()NEWLINE user_id_list.task_done()NEWLINENEWLINENEWLINEdef update_exist(user, fast=True):NEWLINE current_path = get_default_save_path()NEWLINE final_list = []NEWLINE user_id_list = queue.Queue()NEWLINE for folder in os.listdir(current_path):NEWLINE if os.path.isdir(os.path.join(current_path, folder)):NEWLINE user_id = re.search('^(\d+) ', folder)NEWLINE if user_id:NEWLINE user_id = user_id.group(1)NEWLINE user_id_list.put({'id': user_id, 'folder': folder})NEWLINE for i in range(1):NEWLINE # use one thread to prevent Rate Limit in new App APINEWLINE scan_t = threading.Thread(target=artist_folder_scanner,NEWLINE args=(user, user_id_list, current_path, final_list, fast,))NEWLINE scan_t.daemon = TrueNEWLINE scan_t.start()NEWLINE user_id_list.join()NEWLINE download_illustrations(user, final_list, current_path, add_user_folder=True)NEWLINENEWLINENEWLINEdef remove_repeat(_):NEWLINE """Delete xxxxx.img if xxxxx_p0.img exist"""NEWLINE choice = input(_('Dangerous Action: continue?(y/n)'))NEWLINE if choice == 'y':NEWLINE illust_path = get_default_save_path()NEWLINE for folder in os.listdir(illust_path):NEWLINE if os.path.isdir(os.path.join(illust_path, folder)):NEWLINE if re.search('^(\d+) ', folder):NEWLINE path = os.path.join(illust_path, folder)NEWLINE for file_name in os.listdir(path):NEWLINE illustration_id = re.search('^\d+\.', file_name)NEWLINE if illustration_id:NEWLINE if os.path.isfile(os.path.join(pathNEWLINE , illustration_id.string.replace('.', '_p0.'))):NEWLINE os.remove(os.path.join(path, file_name))NEWLINE print('Delete', os.path.join(path, file_name))NEWLINENEWLINENEWLINEdef main():NEWLINE user = PixivApi()NEWLINE if len(sys.argv) > 1:NEWLINE print(datetime.datetime.now().strftime('%X %x'))NEWLINE ids = arguments['']NEWLINE is_rank = arguments['-r']NEWLINE date = arguments['--date']NEWLINE is_update = arguments['-u']NEWLINE if ids:NEWLINE download_by_user_id(user, ids)NEWLINE elif is_rank:NEWLINE if date:NEWLINE date = date[0]NEWLINE download_by_history_ranking(user, date)NEWLINE else:NEWLINE download_by_ranking(user)NEWLINE elif is_update:NEWLINE update_exist(user)NEWLINE print(datetime.datetime.now().strftime('%X %x'))NEWLINE else:NEWLINE print(_(' Pixiv Downloader 2.4 ').center(77, '#'))NEWLINE options = {NEWLINE '1': download_by_user_id,NEWLINE '2': download_by_ranking,NEWLINE '3': download_by_history_ranking,NEWLINE '4': update_exist,NEWLINE '5': remove_repeatNEWLINE }NEWLINE while True:NEWLINE print(_('Which do you want to:'))NEWLINE for i in sorted(options.keys()):NEWLINE print('\t %s %s' % (i, _(options[i].__name__).replace('_', ' ')))NEWLINE choose = input('\t e %s \n:' % _('exit'))NEWLINE if choose in [str(i) for i in range(1, len(options) + 1)]:NEWLINE print((' ' + _(options[choose].__name__).replace('_', ' ') + ' ').center(60, '#') + '\n')NEWLINE if choose == 4:NEWLINE options[choose](user, False)NEWLINE else:NEWLINE options[choose](user)NEWLINE print('\n' + (' ' + _(options[choose].__name__).replace('_', ' ') + _(' finished ')).center(60,NEWLINE '#') + '\n')NEWLINE elif choose == 'e':NEWLINE breakNEWLINE else:NEWLINE print(_('Wrong input!'))NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE arguments = docopt(__doc__, version='pixiv 3')NEWLINE sys.exit(main())NEWLINE import argparseNEWLINENEWLINEimport torchNEWLINEfrom torch_geometric.nn import Node2VecNEWLINEfrom torch_geometric.utils import to_undirectedNEWLINENEWLINEfrom ogb.nodeproppred import PygNodePropPredDatasetNEWLINENEWLINENEWLINEdef save_embedding(model):NEWLINE torch.save(model.embedding.weight.data.cpu(), 'embedding.pt')NEWLINENEWLINENEWLINEdef main():NEWLINE parser = argparse.ArgumentParser(description='OGBN-Arxiv (Node2Vec)')NEWLINE parser.add_argument('--device', type=int, default=0)NEWLINE parser.add_argument('--embedding_dim', type=int, default=128)NEWLINE parser.add_argument('--walk_length', type=int, default=80)NEWLINE parser.add_argument('--context_size', type=int, default=20)NEWLINE parser.add_argument('--walks_per_node', type=int, default=10)NEWLINE parser.add_argument('--batch_size', type=int, default=256)NEWLINE parser.add_argument('--lr', type=float, default=0.01)NEWLINE parser.add_argument('--epochs', type=int, default=5)NEWLINE parser.add_argument('--log_steps', type=int, default=1)NEWLINE args = parser.parse_args()NEWLINENEWLINE device = f'cuda:{args.device}' if torch.cuda.is_available() else 'cpu'NEWLINE device = torch.device(device)NEWLINENEWLINE dataset = PygNodePropPredDataset(name='ogbn-arxiv',NEWLINE root='/srv/scratch/ogb/datasets/nodeproppred')NEWLINE data = dataset[0]NEWLINE data.edge_index = to_undirected(data.edge_index, data.num_nodes)NEWLINENEWLINE model = Node2Vec(data.edge_index, args.embedding_dim, args.walk_length,NEWLINE args.context_size, args.walks_per_node,NEWLINE sparse=True).to(device)NEWLINENEWLINE loader = model.loader(batch_size=args.batch_size, shuffle=True,NEWLINE num_workers=4)NEWLINE optimizer = torch.optim.SparseAdam(list(model.parameters()), lr=args.lr)NEWLINENEWLINE model.train()NEWLINE for epoch in range(1, args.epochs + 1):NEWLINE for i, (pos_rw, neg_rw) in enumerate(loader):NEWLINE optimizer.zero_grad()NEWLINE loss = model.loss(pos_rw.to(device), neg_rw.to(device))NEWLINE loss.backward()NEWLINE optimizer.step()NEWLINENEWLINE if (i + 1) % args.log_steps == 0:NEWLINE print(f'Epoch: {epoch:02d}, Step: {i+1:03d}/{len(loader)}, 'NEWLINE f'Loss: {loss:.4f}')NEWLINENEWLINE if (i + 1) % 100 == 0: # Save model every 100 steps.NEWLINE save_embedding(model)NEWLINE save_embedding(model)NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE main()NEWLINE # coding=utf-8NEWLINE# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE"""The Large Spanish Corpus is a compilation of Spanish corpora spanning Wikipedia to European parliament notes."""NEWLINENEWLINEfrom __future__ import absolute_import, division, print_functionNEWLINENEWLINEimport osNEWLINENEWLINEimport datasetsNEWLINENEWLINENEWLINE_CITATION = """\NEWLINE@dataset{jose_canete_2019_3247731,NEWLINE author = {José Cañete},NEWLINE title = {Compilation of Large Spanish Unannotated Corpora},NEWLINE month = may,NEWLINE year = 2019,NEWLINE publisher = {Zenodo},NEWLINE doi = {10.5281/zenodo.3247731},NEWLINE url = {https://doi.org/10.5281/zenodo.3247731}NEWLINE}NEWLINE"""NEWLINENEWLINE_DESCRIPTION = """\NEWLINEThe Large Spanish Corpus is a compilation of 15 unlabelled Spanish corpora spanning Wikipedia to European parliament \NEWLINEnotes. Each config contains the data corresponding to a different corpus. For example, "all_wiki" only includes \NEWLINEexamples from Spanish Wikipedia. By default, the config is set to "combined" which loads all the corpora; with this \NEWLINEsetting you can also specify the number of samples to return per corpus by configuring the "split" argument.NEWLINE"""NEWLINENEWLINE_HOMEPAGE = "https://github.com/josecannete/spanish-corpora"NEWLINENEWLINE_LICENSE = "MIT"NEWLINENEWLINE_URL = "https://zenodo.org/record/3247731/files/raw.tar.bz2"NEWLINENEWLINE_CORPORA = [NEWLINE "JRC",NEWLINE "EMEA",NEWLINE "GlobalVoices",NEWLINE "ECB",NEWLINE "DOGC",NEWLINE "all_wikis",NEWLINE "TED",NEWLINE "multiUN",NEWLINE "Europarl",NEWLINE "NewsCommentary11",NEWLINE "UN",NEWLINE "EUBookShop",NEWLINE "ParaCrawl",NEWLINE "OpenSubtitles2018",NEWLINE "DGT",NEWLINE]NEWLINENEWLINE_CORPORA_FILEPATHS = {corpus: os.path.join("spanish-corpora", "raw", f"{corpus}.txt") for corpus in _CORPORA}NEWLINENEWLINE_VERSION = "1.1.0"NEWLINENEWLINE_COMBINED = "combined"NEWLINENEWLINENEWLINEclass LargeSpanishCorpusConfig(datasets.BuilderConfig):NEWLINE def __init__(self, corpora=None, **kwargs):NEWLINE super(LargeSpanishCorpusConfig, self).__init__(version=datasets.Version(_VERSION, ""), **kwargs)NEWLINE self.corpora = corporaNEWLINENEWLINE @propertyNEWLINE def filepaths(self):NEWLINE return [_CORPORA_FILEPATHS[corpus] for corpus in self.corpora]NEWLINENEWLINENEWLINEclass LargeSpanishCorpus(datasets.GeneratorBasedBuilder):NEWLINE """The Large Spanish Corpus."""NEWLINENEWLINE BUILDER_CONFIGS = [NEWLINE LargeSpanishCorpusConfig(name=corpus, corpora=[corpus], description=f"Spanish examples in corpus {corpus}.")NEWLINE for corpus in _CORPORANEWLINE ] + [NEWLINE LargeSpanishCorpusConfig(NEWLINE name=_COMBINED, corpora=_CORPORA, description=f"Complete Spanish dataset with all corpora."NEWLINE )NEWLINE ]NEWLINE BUILDER_CONFIG_CLASS = LargeSpanishCorpusConfigNEWLINE DEFAULT_CONFIG_NAME = _COMBINEDNEWLINENEWLINE def _info(self):NEWLINE return datasets.DatasetInfo(NEWLINE description=_DESCRIPTION,NEWLINE features=datasets.Features(NEWLINE {NEWLINE "text": datasets.Value("string"),NEWLINE }NEWLINE ),NEWLINE supervised_keys=None,NEWLINE homepage=_HOMEPAGE,NEWLINE license=_LICENSE,NEWLINE citation=_CITATION,NEWLINE )NEWLINENEWLINE def _split_generators(self, dl_manager):NEWLINE data_dir = dl_manager.download_and_extract(_URL)NEWLINE return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"data_dir": data_dir})]NEWLINENEWLINE def _generate_examples(self, data_dir):NEWLINE for filepath in self.config.filepaths:NEWLINE filepath = os.path.join(data_dir, filepath)NEWLINE _id = 0NEWLINE with open(filepath, mode="r", encoding="utf-8") as f:NEWLINE for line in f:NEWLINE yield _id, {"text": line.strip()},NEWLINE _id += 1NEWLINE NEWLINEfrom .client import NetworkTableClientNEWLINEfrom .server import NetworkTableServerNEWLINEfrom .socketstream import SocketStreamFactory, SocketServerStreamProviderNEWLINEfrom .type import BooleanArray, NumberArray, StringArray, DefaultEntryTypesNEWLINE # -*- coding: utf-8 -*-NEWLINENEWLINE'''NEWLINE**Wavelet Based in CUSUM control chart for filtering signals Project (module**NEWLINE``statsWaveletFilt.miscellaneous`` **):** A Miscellaneous of functions forNEWLINEwork with data and show wavelet coefficientsNEWLINENEWLINE*Created by Tiarles Guterres, 2018*NEWLINE'''NEWLINENEWLINEdef showWaveletCoeff(coefficients, filename='tmp', format='pdf',NEWLINE threshold_value=0, color='black', color_threshold='black',NEWLINE figsize=(7, 8), title=''):NEWLINE '''NEWLINE Show and save the wavelet and scale coefficients in a plot.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE coeff: list of numpy.array'sNEWLINE With in '0' position the scale coefficients. Equal to theNEWLINE ``pywt.wavedec()`` return.NEWLINE filename: stringNEWLINE Optional, is 'tmp' by default. This is the first part of theNEWLINE name of the figure.NEWLINE format: stringNEWLINE Optional, is 'pdf' by default. This is the last part of the name of theNEWLINE figure. Can be 'png', 'ps', 'eps' and 'svg' too.NEWLINENEWLINE threshold_value: int, float or list.NEWLINE Optional, is 0 by default, this means that bothing new happens.NEWLINE Otherwise, a line in threshold value will be plotted in all waveletNEWLINE coefficients plots. This value can be a list too, but they was to beNEWLINE the same size of wavelet coefficients (without the scale coefficient).NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE void:NEWLINE Nothing is returned, the plots is show and save.NEWLINENEWLINE See alsoNEWLINE --------NEWLINE pywt.wavedec: Function that decomposes the signal in wavelet andNEWLINE scale coefficientsNEWLINE pywt.waverec: Function that recomposes the signal from wavelet andNEWLINE scale coefficientsNEWLINENEWLINE filtration.filtration: Function that use this function to filter viaNEWLINE wavelet coefficientsNEWLINENEWLINE filtration.filtrationCusum: Function that use Cumulative Sum Control ChartNEWLINE and some variation for filter wavelet coefficients.NEWLINE '''NEWLINENEWLINE import numpy as npNEWLINE import matplotlib.pyplot as pltNEWLINENEWLINE if isinstance(threshold_value, (int, float, np.float64, np.int32,NEWLINE np.int64)):NEWLINE threshold_list = [threshold_value]*len(coefficients)NEWLINE else:NEWLINE threshold_list = [0] + list(threshold_value)NEWLINENEWLINE N = len(coefficients) - 1NEWLINENEWLINE fig, ax = plt.subplots(len(coefficients), 1, figsize=figsize)NEWLINENEWLINE ax[0].set_title(title)NEWLINENEWLINE # Scale CoefficientsNEWLINE ax[0].plot(coefficients[0], color=color, label='$c_0$ ($c_%d$)' % N)NEWLINE ax[0].legend(loc=1)NEWLINE ax[0].grid()NEWLINENEWLINE # Wavelet CoefficientsNEWLINENEWLINE for i in range(1, len(coefficients)):NEWLINE ax[i].plot(coefficients[i], color=color,NEWLINE label='$d_%d$ ($d_%d$)' % (i - 1, N - i + 1))NEWLINE if threshold_list[i] != 0:NEWLINE x_min, x_max = ax[i].get_xlim()NEWLINE ax[i].hlines(threshold_list[i], x_min, x_max,NEWLINE colors=color_threshold, linestyles='dashed')NEWLINENEWLINE ax[i].hlines(-threshold_list[i], x_min, x_max,NEWLINE colors=color_threshold, linestyles='dashed',NEWLINE label='$\\lambda$')NEWLINE ax[i].legend(loc=1)NEWLINE ax[i].grid()NEWLINENEWLINE plt.tight_layout()NEWLINE plt.savefig('%s' % filename+'.'+format)NEWLINE plt.show()NEWLINENEWLINE returnNEWLINENEWLINENEWLINEdef normalizeData(data, min=0, max=1):NEWLINE '''NEWLINE Its almost a map function. This function normalize the data between aNEWLINE min and max values.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINENEWLINE data: list or array-likeNEWLINE The values that desire normalize.NEWLINE min: int or floatNEWLINE Optional, is -1 by default. The min value correspond, in the end,NEWLINE of the min value of data.NEWLINE max: int or floatNEWLINE Optional, is 1 by default. The max value correspond, in the end,NEWLINE of the max value of data.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE numpy.array:NEWLINE The data normalized between min and max values.NEWLINENEWLINE '''NEWLINENEWLINE import numpy as npNEWLINENEWLINE data = np.array(data)NEWLINENEWLINE new_data = data.copy()NEWLINE max_value = data.max()NEWLINE min_value = data.min()NEWLINENEWLINE diff_pp = max_value - min_valueNEWLINE diff_new_pp = max - minNEWLINENEWLINE new_data = new_data - min_valueNEWLINE new_data = new_data / diff_ppNEWLINENEWLINE new_data = new_data * diff_new_ppNEWLINE new_data = new_data + minNEWLINENEWLINE return new_dataNEWLINENEWLINENEWLINEdef generateData(functions=['doppler', 'block', 'bump', 'heavsine'],NEWLINE varNoises=[0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007,NEWLINE 0.008, 0.009, 0.010],NEWLINE dim_signals=1024,NEWLINE n_samples_per_sig_per_noise=10000, folder='tmp'):NEWLINE '''NEWLINE If you like to generate your dataset before run your test you can useNEWLINE this function to generate the data. With the 1) type of signal andNEWLINE 2) quantity of noise (in variance). Saves in ``.npy``NEWLINE '''NEWLINENEWLINE from statsWaveletFilt.signals import bumpFunction, blockFunctionNEWLINE from statsWaveletFilt.signals import dopplerFunction, heavsineFunctionNEWLINE import numpy as npNEWLINE import osNEWLINENEWLINE try:NEWLINE os.mkdir(folder)NEWLINE print('try: ', folder)NEWLINE except FileExistsError:NEWLINE passNEWLINENEWLINE n_it = n_samples_per_sig_per_noiseNEWLINENEWLINE functions_dic = {'doppler': dopplerFunction,NEWLINE 'block': blockFunction,NEWLINE 'bump': bumpFunction,NEWLINE 'heavsine': heavsineFunction}NEWLINENEWLINE functions_dic_used = {function: functions_dic[function]NEWLINE for function in functions}NEWLINENEWLINE for name, function in functions_dic_used.items():NEWLINE x, y = function(dim_signals)NEWLINE print('|----', name)NEWLINE NEWLINE try:NEWLINE os.mkdir(folder+'/'+name)NEWLINE except FileExistsError:NEWLINE passNEWLINE NEWLINE for varNoise in varNoises:NEWLINE counter = 0NEWLINE print('|----|----', varNoise)NEWLINE while counter < n_it:NEWLINE np.random.seed(counter)NEWLINE noise = np.random.normal(0, np.sqrt(varNoise), dim_signals)NEWLINENEWLINE sinalNoisy = y + noiseNEWLINENEWLINE filename = './%s/%s/%f_%d.npy' % (folder, name, varNoise,NEWLINE counter)NEWLINE NEWLINE np.save(filename, sinalNoisy)NEWLINE counter += 1NEWLINE #!/usr/bin/env pythonNEWLINE# coding=utf-8NEWLINENEWLINEimport socketNEWLINENEWLINEfrom urllib.parse import urlparseNEWLINEfrom http.server import HTTPServer, BaseHTTPRequestHandlerNEWLINENEWLINENEWLINEclass ProxyHandler(BaseException):NEWLINE """NEWLINE 参考链接:NEWLINE https://zhuanlan.zhihu.com/p/28737960NEWLINE https://docs.python.org/3/library/http.server.htmlNEWLINE """NEWLINE def _recv_proxy_data(self, socket_client: socket.socket):NEWLINE data = b''NEWLINE while True:NEWLINE recv = socket_client.recv(1024)NEWLINE if recv:NEWLINE data += recvNEWLINE else:NEWLINE breakNEWLINE socket_client.close()NEWLINE return dataNEWLINENEWLINE def do_GET(self):NEWLINE uri = urlparse(self.path)NEWLINE scheme, host, path = uri.scheme, uri.netloc, uri.pathNEWLINE host_id = socket.gethostbyname(host)NEWLINE port = 443 if scheme == 'https' else 80NEWLINENEWLINE data = 'GET {} {}\r\n'.format(path, self.protocol_version)NEWLINE for k, v in self.headers.items():NEWLINE data += '{}: {}\r\n'.format(k, v)NEWLINE data += '\r\n'NEWLINENEWLINE with open('./res.txt', 'a') as fp:NEWLINE fp.write(data)NEWLINE socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)NEWLINE socket_client.connect((host, port))NEWLINE socket_client.sendall(data.encode('utf-8'))NEWLINE recv_res_data = self._recv_proxy_data(socket_client)NEWLINE self.wfile.write(recv_res_data)NEWLINENEWLINENEWLINEdef main():NEWLINE try:NEWLINE server = HTTPServer(('', 6789), ProxyHandler)NEWLINE server.serve_forever()NEWLINE except KeyboardInterrupt as e:NEWLINE server.socket.close()NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE main()NEWLINE #===============================================================================NEWLINE#NEWLINE# FILE: parse_log_3.pyNEWLINE#NEWLINE# USAGE:NEWLINE#NEWLINE# DESCRIPTION:NEWLINE#NEWLINE# OPTIONS: NEWLINE# REQUIREMENTS: NEWLINE# BUGS: NEWLINE# NOTES: NEWLINE# AUTHOR: Debjit PalNEWLINE# CONTACT: debjit.pal@cornell.eduNEWLINE# ORGANIZATION: ECE, Cornell UniversityNEWLINE# VERSION: NEWLINE# CREATED: 22-11-2019NEWLINE# REVISION: NEWLINE# LMODIFIED: Fri 22 Nov 2019 11:49:26 PM ESTNEWLINE#===============================================================================NEWLINENEWLINEimport os, sysNEWLINEfrom shutil import copyfile as cpfNEWLINENEWLINEgl_dir = os.environ.get('GRAPHLEARN')NEWLINESOURCE_PATH = gl_dir + '/data_app_source_bit'NEWLINEDEST_PATH = gl_dir + '/num_source'NEWLINENEWLINE#SOURCE_PATH = 'path..../source_data/data_app_source_bit'NEWLINE#DEST_PATH = 'path..../source_data/num_source'NEWLINENEWLINEfiles = [f for f in os.listdir(SOURCE_PATH) if f.endswith('.edgelist')]NEWLINEfiles_sorted = sorted(files)NEWLINEdel filesNEWLINENEWLINEcounter = 0NEWLINENEWLINEmh = open('nfile_efile_glearn.map', 'w')NEWLINEfor file_ in files_sorted:NEWLINE name = file_[:file_.find('.')]NEWLINE cpf_name = str(counter)NEWLINE cpf(SOURCE_PATH + '/' + name + '.edgelist', DEST_PATH + '/' + cpf_name + '.edgelist')NEWLINE cpf(SOURCE_PATH + '/' + name + '.nodelist', DEST_PATH + '/' + cpf_name + '.nodelist')NEWLINE mh.write(name + '\t' + cpf_name + '\n')NEWLINE counter = counter + 1NEWLINENEWLINEmh.close()NEWLINE NEWLINE#-*-coding:utf-8-*- 设置utf-8编码NEWLINEprint "Hello World!"NEWLINEprint "Hello Again"NEWLINEprint "I like typing this."NEWLINEprint "This is fun."NEWLINEprint "Yay! Printing."NEWLINEprint "I'd much rather you 'not "NEWLINEprint 'I "said" do not touch this.'NEWLINE#print "我爱你们!"NEWLINE# A comment , this is so you can read your program later.NEWLINE# Anything after the # is ignored by pythonNEWLINEprint "I could have code like this." # and the comment after is ignored NEWLINE# You can also use a comment to "disable" or comment out a piece of code;NEWLINENEWLINE# print "This won't run"NEWLINENEWLINEprint "This will run."NEWLINE from random import randintNEWLINEfrom tkinter import *NEWLINEfrom tkinter import ttkNEWLINENEWLINENEWLINEclass Node:NEWLINE def __init__(self, x, y, aValue):NEWLINE self.x = xNEWLINE self.y = yNEWLINE self.leftNode = 0NEWLINE self.bottomNode = 0NEWLINE self.rightNode = 0NEWLINE self.topNode = 0NEWLINE self.aValue = aValueNEWLINENEWLINENEWLINEclass AObject:NEWLINE def __init__(self, finder, start, pokemon, tablero):NEWLINE self.openQ = []NEWLINE self.closeQ = []NEWLINE self.rightWay = []NEWLINE self.steps = []NEWLINENEWLINE def insertStep(node):NEWLINE if not self.rightWay:NEWLINE print('primer paso')NEWLINE self.rightWay.append(node)NEWLINE # print(self.rightWay, node, self.rightWay[0].rightNode)NEWLINENEWLINE else:NEWLINE print('entre')NEWLINE for i in self.rightWay:NEWLINE print('right', node.x, i.rightNode.x, node.y, i.rightNode.y)NEWLINE print('left', node.x, i.leftNode.x, node.y, i.leftNode.y)NEWLINE print('top', node.x, i.topNode.x, node.y, i.topNode.y)NEWLINE print('bottom', node.x, i.bottomNode.x,NEWLINE node.y, i.bottomNode.y)NEWLINE if i.rightNode != 0:NEWLINE if (node.x == i.rightNode.x and node.y == i.rightNode.y):NEWLINE self.rightWay = self.rightWay[0: self.rightWay.index(NEWLINE i) + 1]NEWLINE breakNEWLINE if i.leftNode != 0:NEWLINE if (node.x == i.leftNode.x and node.y == i.leftNode.y):NEWLINE self.rightWay = self.rightWay[0: self.rightWay.index(NEWLINE i) + 1]NEWLINE breakNEWLINE if i.topNode != 0:NEWLINE if (node.x == i.topNode.x and node.y == i.topNode.y):NEWLINE self.rightWay = self.rightWay[0: self.rightWay.index(NEWLINE i) + 1]NEWLINE breakNEWLINE if i.bottomNode != 0:NEWLINE if (node.x == i.bottomNode.x and node.y == i.bottomNode.y):NEWLINE self.rightWay = self.rightWay[0: self.rightWay.index(NEWLINE i) + 1]NEWLINE breakNEWLINENEWLINE def insertClose(node):NEWLINE if self.openQ:NEWLINE for i in self.openQ:NEWLINE if node.x == i.x and node.y == i.y:NEWLINE self.openQ.remove(i)NEWLINE breakNEWLINE if self.closeQ:NEWLINE for i in self.closeQ:NEWLINE if node.aValue <= i.aValue:NEWLINE self.closeQ.insert(self.closeQ.index(i), node)NEWLINE breakNEWLINE if node.aValue > self.closeQ[-1].aValue:NEWLINE self.closeQ.append(node)NEWLINE else:NEWLINE self.closeQ.append(node)NEWLINENEWLINE def insertOpen(node):NEWLINE # print('Agregando nodo')NEWLINE if self.closeQ:NEWLINE for i in self.closeQ:NEWLINE if node.x == i.x and node.y == i.y:NEWLINE returnNEWLINE if self.openQ:NEWLINE for i in self.openQ:NEWLINE # print('buscando lugar para el nodo')NEWLINE if node.aValue <= i.aValue:NEWLINE self.openQ.insert(self.openQ.index(i), node)NEWLINE # print('nodo agregado')NEWLINE breakNEWLINE if node.aValue > self.openQ[-1].aValue:NEWLINE self.openQ.append(node)NEWLINE # print('nodo agregado')NEWLINE else:NEWLINE self.openQ.append(node)NEWLINE # print('primer nodo agregado')NEWLINENEWLINE def findWay(goal):NEWLINE self.rightWay = []NEWLINENEWLINE def wayWithoutObstacle(finder):NEWLINE obstacles = {}NEWLINE if finder.x > 0:NEWLINE if (tablero[finder.y][finder.x - 1].name != 'Rock') and (tablero[finder.y][finder.x - 1].name != 'Van'):NEWLINE obstacles['left'] = (True)NEWLINE else:NEWLINE obstacles['left'] = (False)NEWLINE else:NEWLINE obstacles['left'] = (False)NEWLINE if finder.x < 9:NEWLINE if (tablero[finder.y][finder.x + 1].name != 'Rock') and (tablero[finder.y][finder.x + 1].name != 'Van'):NEWLINE obstacles['right'] = (True)NEWLINE else:NEWLINE obstacles['right'] = (False)NEWLINE else:NEWLINE obstacles['right'] = (False)NEWLINE if finder.y > 0:NEWLINE if (tablero[finder.y - 1][finder.x].name != 'Rock') and (tablero[finder.y - 1][finder.x].name != 'Van'):NEWLINE obstacles['up'] = (True)NEWLINE else:NEWLINE obstacles['up'] = (False)NEWLINE else:NEWLINE obstacles['up'] = (False)NEWLINE if finder.y < 9:NEWLINE if (tablero[finder.y + 1][finder.x].name != 'Rock') and (tablero[finder.y + 1][finder.x].name != 'Van'):NEWLINE obstacles['down'] = (True)NEWLINE else:NEWLINE obstacles['down'] = (False)NEWLINE else:NEWLINE obstacles['down'] = (False)NEWLINE return obstaclesNEWLINENEWLINE def manhatan(startX, startY, goal):NEWLINE return abs(startX - goal.x) + abs(startY - goal.y)NEWLINE g_n_ = manhatan(finder.x, finder.y, start)NEWLINE h_n_ = manhatan(finder.x, finder.y, goal)NEWLINE currentTrainer = Trainer(finder.y, finder.x)NEWLINE while True:NEWLINE a = input()NEWLINE print('Pokemon', goal.x, goal.y)NEWLINE if self.openQ:NEWLINE currentTrainer = Trainer(self.openQ[0].y, self.openQ[0].x)NEWLINE g_n_ = manhatan(currentTrainer.x, currentTrainer.y, start)NEWLINE h_n_ = manhatan(currentTrainer.x, currentTrainer.y, goal)NEWLINENEWLINE print('Pokebola', currentTrainer.x, currentTrainer.y)NEWLINE currentNode = Node(NEWLINE currentTrainer.x, currentTrainer.y, g_n_ + h_n_)NEWLINE obstacles = wayWithoutObstacle(currentTrainer)NEWLINE print(obstacles)NEWLINE insertClose(currentNode)NEWLINE # for k in self.closeQ:NEWLINE # print('Cola cerrada', '[', k.x, k.y, k.aValue, ']')NEWLINENEWLINE if obstacles['left']:NEWLINE # print('izq')NEWLINE g_n_ = manhatan(currentTrainer.x - 1,NEWLINE currentTrainer.y, start)NEWLINE h_n_ = manhatan(currentTrainer.x - 1,NEWLINE currentTrainer.y, goal)NEWLINE insertOpen(Node(currentTrainer.x - 1,NEWLINE currentTrainer.y, g_n_ + h_n_))NEWLINE currentNode.leftNode = Node(NEWLINE currentTrainer.x - 1, currentTrainer.y, g_n_ + h_n_)NEWLINE if obstacles['right']:NEWLINE # print('der')NEWLINE g_n_ = manhatan(currentTrainer.x + 1,NEWLINE currentTrainer.y, start)NEWLINE h_n_ = manhatan(currentTrainer.x + 1,NEWLINE currentTrainer.y, goal)NEWLINE insertOpen(Node(currentTrainer.x + 1,NEWLINE currentTrainer.y, g_n_ + h_n_))NEWLINE currentNode.rightNode = Node(NEWLINE currentTrainer.x - 1, currentTrainer.y, g_n_ + h_n_)NEWLINE if obstacles['up']:NEWLINE # print('arriba')NEWLINE g_n_ = manhatan(currentTrainer.x,NEWLINE currentTrainer.y - 1, start)NEWLINE h_n_ = manhatan(currentTrainer.x,NEWLINE currentTrainer.y - 1, goal)NEWLINE insertOpen(NEWLINE Node(currentTrainer.x, currentTrainer.y - 1, g_n_ + h_n_))NEWLINE currentNode.topNode = Node(NEWLINE currentTrainer.x - 1, currentTrainer.y, g_n_ + h_n_)NEWLINE if obstacles['down']:NEWLINE # print('abajo')NEWLINE g_n_ = manhatan(currentTrainer.x,NEWLINE currentTrainer.y + 1, start)NEWLINE h_n_ = manhatan(currentTrainer.x,NEWLINE currentTrainer.y + 1, goal)NEWLINE insertOpen(NEWLINE Node(currentTrainer.x, currentTrainer.y + 1, g_n_ + h_n_))NEWLINE currentNode.bottomNode = Node(NEWLINE currentTrainer.x - 1, currentTrainer.y, g_n_ + h_n_)NEWLINENEWLINE insertStep(currentNode)NEWLINENEWLINE # for k in self.openQ:NEWLINE # print('Cola abierta', '[', k.x, k.y, k.aValue, ']')NEWLINENEWLINE if currentTrainer.x == goal.x and currentTrainer.y == goal.y:NEWLINE for k in self.rightWay:NEWLINE print('Paso', '[', k.x, k.y, ']')NEWLINE return self.rightWayNEWLINENEWLINE self.steps.append(findWay(pokemon[0]))NEWLINENEWLINENEWLINEclass Pokemon:NEWLINE def __init__(self, i, j, pokemonId, container):NEWLINE self.name = 'Pokemon'NEWLINE self.pokemonId = pokemonIdNEWLINE self.image = PhotoImage(file='images/' + str(pokemonId) + '.png')NEWLINE self.y = iNEWLINE self.x = jNEWLINE self.label = Label(NEWLINE container,NEWLINE height='64',NEWLINE width='64',NEWLINE borderwidth='2',NEWLINE image=self.imageNEWLINE )NEWLINENEWLINENEWLINEclass Grass:NEWLINE def __init__(self, i, j, container):NEWLINE self.name = 'Grass'NEWLINE self.image = PhotoImage(file='images/grass.png')NEWLINE self.y = iNEWLINE self.x = jNEWLINE self.label = Label(NEWLINE container,NEWLINE height='64',NEWLINE width='64',NEWLINE borderwidth='2',NEWLINE image=self.imageNEWLINE )NEWLINENEWLINENEWLINEclass Rock:NEWLINE def __init__(self, i, j, container):NEWLINE self.name = 'Rock'NEWLINE self.image = PhotoImage(file='images/rock.png')NEWLINE self.y = iNEWLINE self.x = jNEWLINE self.label = Label(NEWLINE container,NEWLINE height='64',NEWLINE width='64',NEWLINE borderwidth='2',NEWLINE image=self.imageNEWLINE )NEWLINENEWLINENEWLINEclass Bean:NEWLINE def __init__(self, i, j, container):NEWLINE self.name = 'Bean'NEWLINE self.image = PhotoImage(file='images/jelly-beans.png')NEWLINE self.y = iNEWLINE self.x = jNEWLINE self.label = Label(NEWLINE container,NEWLINE height='64',NEWLINE width='64',NEWLINE borderwidth='2',NEWLINE image=self.imageNEWLINE )NEWLINENEWLINENEWLINEclass Trainer:NEWLINE def __init__(self, i, j, container=False, pokeball=False):NEWLINE self.name = 'Trainer'NEWLINE self.y = iNEWLINE self.x = jNEWLINE self.back = FalseNEWLINE if container:NEWLINE self.image = PhotoImage(file='images/' + pokeball + '.png')NEWLINE self.label = Label(NEWLINE container,NEWLINE height='64',NEWLINE width='64',NEWLINE borderwidth='2',NEWLINE image=self.imageNEWLINE )NEWLINENEWLINENEWLINEclass Van:NEWLINE def __init__(self, i, j, container):NEWLINE self.name = 'Van'NEWLINE self.image = PhotoImage(file='images/van.png')NEWLINE self.y = iNEWLINE self.x = jNEWLINE self.label = Label(NEWLINE container,NEWLINE height='64',NEWLINE width='64',NEWLINE borderwidth='2',NEWLINE image=self.imageNEWLINE )NEWLINENEWLINENEWLINEclass Tablero:NEWLINE def __init__(self, size):NEWLINE self.window = Tk()NEWLINE self.window.title('Pokemon Finder')NEWLINE self.size = sizeNEWLINE self.tablero = []NEWLINE self.pokemonArray = []NEWLINE self.trainer = Trainer(randint(0, self.size), randint(NEWLINE 0, self.size), self.window, 'pokeball2')NEWLINENEWLINE for i in range(10):NEWLINE self.tablero.append([])NEWLINE for j in range(10):NEWLINE if ((j == self.trainer.x) & (i == self.trainer.y - 1)):NEWLINE self.van = Van(i, j, self.window)NEWLINE self.tablero[i].append(self.van)NEWLINE elif randint(0, 6) == 1:NEWLINE pokemon = Pokemon(i, j, randint(1, 19), self.window)NEWLINE self.pokemonArray.append(pokemon)NEWLINE self.tablero[i].append(pokemon)NEWLINE elif randint(0, 6) == 1:NEWLINE rock = Rock(i, j, self.window)NEWLINE self.tablero[i].append(rock)NEWLINE else:NEWLINE grass = Grass(i, j, self.window)NEWLINE self.tablero[i].append(grass)NEWLINENEWLINE for i in range(10):NEWLINE for j in range(10):NEWLINE self.tablero[i][j].label.grid(NEWLINE column=self.tablero[i][j].x, row=self.tablero[i][j].y)NEWLINENEWLINE self.window.after(500, self.findPokemon)NEWLINE self.window.mainloop()NEWLINENEWLINE def findPokemon(self):NEWLINENEWLINE def Move(trainer):NEWLINE def rightMove(leaveBean=False):NEWLINE if leaveBean:NEWLINE # self.tablero[trainer.y][trainer.x] = Bean(trainer.y, trainer.y, self.window)NEWLINE self.tablero[trainer.y][trainer.x + 1] = Trainer(NEWLINE trainer.y, trainer.x + 1, self.window, 'pokeball1')NEWLINE else:NEWLINE self.tablero[trainer.y][trainer.x + 1] = Trainer(NEWLINE trainer.y, trainer.x + 1, self.window, 'pokeball2')NEWLINENEWLINE self.tablero[trainer.y][trainer.x] = Grass(NEWLINE trainer.y, trainer.x, self.window)NEWLINE self.tablero[trainer.y][trainer.x].label.grid(NEWLINE column=trainer.x, row=trainer.y)NEWLINE self.tablero[trainer.y][trainer.x +NEWLINE 1].label.grid(column=trainer.x + 1, row=trainer.y)NEWLINE trainer.x += 1NEWLINENEWLINE def leftMove(leaveBean=False):NEWLINE if leaveBean:NEWLINE # self.tablero[trainer.y][trainer.x] = Bean(trainer.y, trainer.y, self.window)NEWLINE self.tablero[trainer.y][trainer.x - 1] = Trainer(NEWLINE trainer.y, trainer.x - 1, self.window, 'pokeball1')NEWLINE else:NEWLINE self.tablero[trainer.y][trainer.x - 1] = Trainer(NEWLINE trainer.y, trainer.x - 1, self.window, 'pokeball2')NEWLINENEWLINE self.tablero[trainer.y][trainer.x] = Grass(NEWLINE trainer.y, trainer.x, self.window)NEWLINE self.tablero[trainer.y][trainer.x].label.grid(NEWLINE column=trainer.x, row=trainer.y)NEWLINE self.tablero[trainer.y][trainer.x -NEWLINE 1].label.grid(column=trainer.x - 1, row=trainer.y)NEWLINE trainer.x -= 1NEWLINENEWLINE def downMove(leaveBean=False):NEWLINE if leaveBean:NEWLINE # self.tablero[trainer.y][trainer.x] = Bean(trainer.y, trainer.y, self.window)NEWLINE self.tablero[trainer.y + 1][trainer.x] = Trainer(NEWLINE trainer.y + 1, trainer.x, self.window, 'pokeball1')NEWLINE else:NEWLINE self.tablero[trainer.y + 1][trainer.x] = Trainer(NEWLINE trainer.y + 1, trainer.x, self.window, 'pokeball2')NEWLINENEWLINE self.tablero[trainer.y][trainer.x] = Grass(NEWLINE trainer.y, trainer.x, self.window)NEWLINE self.tablero[trainer.y][trainer.x].label.grid(NEWLINE column=trainer.x, row=trainer.y)NEWLINE self.tablero[trainer.y +NEWLINE 1][trainer.x].label.grid(column=trainer.x, row=trainer.y + 1)NEWLINE trainer.y += 1NEWLINENEWLINE def upMove(leaveBean=False):NEWLINE if leaveBean:NEWLINE # self.tablero[trainer.y][trainer.x] = Bean(trainer.y, trainer.y, self.window)NEWLINE self.tablero[trainer.y - 1][trainer.x] = Trainer(NEWLINE trainer.y - 1, trainer.x, self.window, 'pokeball1')NEWLINE else:NEWLINE self.tablero[trainer.y - 1][trainer.x] = Trainer(NEWLINE trainer.y - 1, trainer.x, self.window, 'pokeball2')NEWLINENEWLINE self.tablero[trainer.y][trainer.x] = Grass(NEWLINE trainer.y, trainer.x, self.window)NEWLINE self.tablero[trainer.y][trainer.x].label.grid(NEWLINE column=trainer.x, row=trainer.y)NEWLINE self.tablero[trainer.y -NEWLINE 1][trainer.x].label.grid(column=trainer.x, row=trainer.y - 1)NEWLINE trainer.y -= 1NEWLINENEWLINE def isPokemonClose():NEWLINE if trainer.x < self.size - 1 and self.tablero[trainer.y][trainer.x+1].name == 'Pokemon':NEWLINE return 'right'NEWLINE elif trainer.x > 0 and self.tablero[trainer.y][trainer.x-1].name == 'Pokemon':NEWLINE return 'left'NEWLINE elif trainer.y < self.size - 1 and self.tablero[trainer.y + 1][trainer.x].name == 'Pokemon':NEWLINE return 'down'NEWLINE elif trainer.y > 0 and self.tablero[trainer.y - 1][trainer.x].name == 'Pokemon':NEWLINE return 'up'NEWLINENEWLINE def wayWithoutObstacle():NEWLINE obstacles = {}NEWLINE if trainer.x > 0:NEWLINE if (self.tablero[trainer.y][trainer.x - 1].name != 'Rock') and (self.tablero[trainer.y][trainer.x - 1].name != 'Van'):NEWLINE obstacles['left'] = (True)NEWLINE else:NEWLINE obstacles['left'] = (False)NEWLINE else:NEWLINE obstacles['left'] = (False)NEWLINE if trainer.x < self.size - 1:NEWLINE if (self.tablero[trainer.y][trainer.x + 1].name != 'Rock') and (self.tablero[trainer.y][trainer.x + 1].name != 'Van'):NEWLINE obstacles['right'] = (True)NEWLINE else:NEWLINE obstacles['right'] = (False)NEWLINE else:NEWLINE obstacles['right'] = (False)NEWLINE if trainer.y > 0:NEWLINE if (self.tablero[trainer.y - 1][trainer.x].name != 'Rock') and (self.tablero[trainer.y - 1][trainer.x].name != 'Van'):NEWLINE obstacles['up'] = (True)NEWLINE else:NEWLINE obstacles['up'] = (False)NEWLINE else:NEWLINE obstacles['up'] = (False)NEWLINE if trainer.y < self.size - 1:NEWLINE if (self.tablero[trainer.y + 1][trainer.x].name != 'Rock') and (self.tablero[trainer.y + 1][trainer.x].name != 'Van'):NEWLINE obstacles['down'] = (True)NEWLINE else:NEWLINE obstacles['down'] = (False)NEWLINE else:NEWLINE obstacles['down'] = (False)NEWLINE return obstaclesNEWLINENEWLINE def chooseWay(obstacles):NEWLINE choose = randint(0, 3)NEWLINE if choose == 0 and obstacles['left']:NEWLINE return 'left'NEWLINE elif choose == 1 and obstacles['right']:NEWLINE return 'right'NEWLINE elif choose == 2 and obstacles['up']:NEWLINE return 'up'NEWLINE elif choose == 3 and obstacles['down']:NEWLINE return 'down'NEWLINE else:NEWLINE return chooseWay(obstacles)NEWLINENEWLINE def backToVan():NEWLINENEWLINE def chooseBackWay():NEWLINE min = abs(trainer.x + 1 - self.van.x) + \NEWLINE abs(trainer.y - self.van.y)NEWLINE if (abs(trainer.x - 1 - self.van.x) + abs(trainer.y - self.van.y) < min) and wayWithoutObstacle()['left'] and isPokemonClose() != 'left':NEWLINE return 'left'NEWLINE elif (abs(trainer.x - self.van.x) + abs(trainer.y + 1 - self.van.y) < min) and wayWithoutObstacle()['down'] and isPokemonClose() != 'down':NEWLINE return 'down'NEWLINE elif (abs(trainer.x - self.van.x) + abs(trainer.y - 1 - self.van.y) < min) and wayWithoutObstacle()['up'] and isPokemonClose() != 'up':NEWLINE return 'up'NEWLINE elif wayWithoutObstacle()['right'] and isPokemonClose() != 'right':NEWLINE return 'right'NEWLINE else:NEWLINE NoneNEWLINENEWLINE def isVanClose():NEWLINE if self.trainer.x < self.size - 1:NEWLINE if self.tablero[trainer.y][trainer.x+1].name == 'Van':NEWLINE return TrueNEWLINE if self.trainer.x > 0:NEWLINE if self.tablero[trainer.y][trainer.x-1].name == 'Van':NEWLINE return TrueNEWLINE if self.trainer.y < self.size - 1:NEWLINE if self.tablero[trainer.y+1][trainer.x].name == 'Van':NEWLINE return TrueNEWLINE if self.trainer.y > 0:NEWLINE if self.tablero[trainer.y-1][trainer.x].name == 'Van':NEWLINE return TrueNEWLINE else:NEWLINE return FalseNEWLINE pokemonGotcha(True)NEWLINE try:NEWLINE if isVanClose():NEWLINE pokemonGotcha(False)NEWLINE elif chooseBackWay() == 'right':NEWLINE rightMove(True)NEWLINE elif chooseBackWay() == 'left':NEWLINE leftMove(True)NEWLINE elif chooseBackWay() == 'down':NEWLINE downMove(True)NEWLINE elif chooseBackWay() == 'up':NEWLINE upMove(True)NEWLINE except Exception as error:NEWLINE print(error)NEWLINENEWLINE def pokemonGotcha(gotIt):NEWLINE self.trainer.back = gotItNEWLINE self.trainer.image = PhotoImage(file='images/pokeball1.png')NEWLINE self.trainer.label.config(image=self.trainer.image)NEWLINENEWLINE self.a = AObject(self.trainer, self.van,NEWLINE self.pokemonArray, self.tablero)NEWLINE # print(self.a.openQ, self.a.closeQ)NEWLINENEWLINE Move(self.trainer)NEWLINE self.window.after(500, self.findPokemon)NEWLINENEWLINENEWLINEdef main():NEWLINE tierra = Tablero(10)NEWLINENEWLINENEWLINE# x = j | y = iNEWLINEif __name__ == '__main__':NEWLINE main()NEWLINE # coding=utf-8NEWLINE# --------------------------------------------------------------------------NEWLINE# Copyright (c) Microsoft Corporation. All rights reserved.NEWLINE# Licensed under the MIT License. See License.txt in the project root for license information.NEWLINE# Code generated by Microsoft (R) AutoRest Code Generator.NEWLINE# Changes may cause incorrect behavior and will be lost if the code is regenerated.NEWLINE# --------------------------------------------------------------------------NEWLINEfrom typing import TYPE_CHECKINGNEWLINEimport warningsNEWLINENEWLINEfrom azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_errorNEWLINEfrom azure.core.paging import ItemPagedNEWLINEfrom azure.core.pipeline import PipelineResponseNEWLINEfrom azure.core.pipeline.transport import HttpRequest, HttpResponseNEWLINEfrom azure.core.polling import LROPoller, NoPolling, PollingMethodNEWLINEfrom azure.mgmt.core.exceptions import ARMErrorFormatNEWLINEfrom azure.mgmt.core.polling.arm_polling import ARMPollingNEWLINENEWLINEfrom .. import models as _modelsNEWLINENEWLINEif TYPE_CHECKING:NEWLINE # pylint: disable=unused-import,ungrouped-importsNEWLINE from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, UnionNEWLINENEWLINE T = TypeVar('T')NEWLINE ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]NEWLINENEWLINEclass InterfaceEndpointsOperations(object):NEWLINE """InterfaceEndpointsOperations operations.NEWLINENEWLINE You should not instantiate this class directly. Instead, you should create a Client instance thatNEWLINE instantiates it for you and attaches it as an attribute.NEWLINENEWLINE :ivar models: Alias to model classes used in this operation group.NEWLINE :type models: ~azure.mgmt.network.v2019_02_01.modelsNEWLINE :param client: Client for service requests.NEWLINE :param config: Configuration of service client.NEWLINE :param serializer: An object model serializer.NEWLINE :param deserializer: An object model deserializer.NEWLINE """NEWLINENEWLINE models = _modelsNEWLINENEWLINE def __init__(self, client, config, serializer, deserializer):NEWLINE self._client = clientNEWLINE self._serialize = serializerNEWLINE self._deserialize = deserializerNEWLINE self._config = configNEWLINENEWLINE def _delete_initial(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE interface_endpoint_name, # type: strNEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> NoneNEWLINE cls = kwargs.pop('cls', None) # type: ClsType[None]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2019-02-01"NEWLINENEWLINE # Construct URLNEWLINE url = self._delete_initial.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),NEWLINE 'interfaceEndpointName': self._serialize.url("interface_endpoint_name", interface_endpoint_name, 'str'),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINENEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINENEWLINE request = self._client.delete(url, query_parameters, header_parameters)NEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200, 202, 204]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, None, {})NEWLINENEWLINE _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/interfaceEndpoints/{interfaceEndpointName}'} # type: ignoreNEWLINENEWLINE def begin_delete(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE interface_endpoint_name, # type: strNEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> LROPoller[None]NEWLINE """Deletes the specified interface endpoint.NEWLINENEWLINE :param resource_group_name: The name of the resource group.NEWLINE :type resource_group_name: strNEWLINE :param interface_endpoint_name: The name of the interface endpoint.NEWLINE :type interface_endpoint_name: strNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :keyword str continuation_token: A continuation token to restart a poller from a saved state.NEWLINE :keyword polling: By default, your polling method will be ARMPolling.NEWLINE Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.NEWLINE :paramtype polling: bool or ~azure.core.polling.PollingMethodNEWLINE :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.NEWLINE :return: An instance of LROPoller that returns either None or the result of cls(response)NEWLINE :rtype: ~azure.core.polling.LROPoller[None]NEWLINE :raises ~azure.core.exceptions.HttpResponseError:NEWLINE """NEWLINE polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]NEWLINE cls = kwargs.pop('cls', None) # type: ClsType[None]NEWLINE lro_delay = kwargs.pop(NEWLINE 'polling_interval',NEWLINE self._config.polling_intervalNEWLINE )NEWLINE cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]NEWLINE if cont_token is None:NEWLINE raw_result = self._delete_initial(NEWLINE resource_group_name=resource_group_name,NEWLINE interface_endpoint_name=interface_endpoint_name,NEWLINE cls=lambda x,y,z: x,NEWLINE **kwargsNEWLINE )NEWLINENEWLINE kwargs.pop('error_map', None)NEWLINE kwargs.pop('content_type', None)NEWLINENEWLINE def get_long_running_output(pipeline_response):NEWLINE if cls:NEWLINE return cls(pipeline_response, None, {})NEWLINENEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),NEWLINE 'interfaceEndpointName': self._serialize.url("interface_endpoint_name", interface_endpoint_name, 'str'),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),NEWLINE }NEWLINENEWLINE if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)NEWLINE elif polling is False: polling_method = NoPolling()NEWLINE else: polling_method = pollingNEWLINE if cont_token:NEWLINE return LROPoller.from_continuation_token(NEWLINE polling_method=polling_method,NEWLINE continuation_token=cont_token,NEWLINE client=self._client,NEWLINE deserialization_callback=get_long_running_outputNEWLINE )NEWLINE else:NEWLINE return LROPoller(self._client, raw_result, get_long_running_output, polling_method)NEWLINE begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/interfaceEndpoints/{interfaceEndpointName}'} # type: ignoreNEWLINENEWLINE def get(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE interface_endpoint_name, # type: strNEWLINE expand=None, # type: Optional[str]NEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> "_models.InterfaceEndpoint"NEWLINE """Gets the specified interface endpoint by resource group.NEWLINENEWLINE :param resource_group_name: The name of the resource group.NEWLINE :type resource_group_name: strNEWLINE :param interface_endpoint_name: The name of the interface endpoint.NEWLINE :type interface_endpoint_name: strNEWLINE :param expand: Expands referenced resources.NEWLINE :type expand: strNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: InterfaceEndpoint, or the result of cls(response)NEWLINE :rtype: ~azure.mgmt.network.v2019_02_01.models.InterfaceEndpointNEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.InterfaceEndpoint"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2019-02-01"NEWLINE accept = "application/json"NEWLINENEWLINE # Construct URLNEWLINE url = self.get.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),NEWLINE 'interfaceEndpointName': self._serialize.url("interface_endpoint_name", interface_endpoint_name, 'str'),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINENEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINE if expand is not None:NEWLINE query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')NEWLINENEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINE header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')NEWLINENEWLINE request = self._client.get(url, query_parameters, header_parameters)NEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE deserialized = self._deserialize('InterfaceEndpoint', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINENEWLINE return deserializedNEWLINE get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/interfaceEndpoints/{interfaceEndpointName}'} # type: ignoreNEWLINENEWLINE def _create_or_update_initial(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE interface_endpoint_name, # type: strNEWLINE parameters, # type: "_models.InterfaceEndpoint"NEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> "_models.InterfaceEndpoint"NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.InterfaceEndpoint"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2019-02-01"NEWLINE content_type = kwargs.pop("content_type", "application/json")NEWLINE accept = "application/json"NEWLINENEWLINE # Construct URLNEWLINE url = self._create_or_update_initial.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),NEWLINE 'interfaceEndpointName': self._serialize.url("interface_endpoint_name", interface_endpoint_name, 'str'),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINENEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINE header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')NEWLINE header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')NEWLINENEWLINE body_content_kwargs = {} # type: Dict[str, Any]NEWLINE body_content = self._serialize.body(parameters, 'InterfaceEndpoint')NEWLINE body_content_kwargs['content'] = body_contentNEWLINE request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)NEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200, 201]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE if response.status_code == 200:NEWLINE deserialized = self._deserialize('InterfaceEndpoint', pipeline_response)NEWLINENEWLINE if response.status_code == 201:NEWLINE deserialized = self._deserialize('InterfaceEndpoint', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINENEWLINE return deserializedNEWLINE _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/interfaceEndpoints/{interfaceEndpointName}'} # type: ignoreNEWLINENEWLINE def begin_create_or_update(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE interface_endpoint_name, # type: strNEWLINE parameters, # type: "_models.InterfaceEndpoint"NEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> LROPoller["_models.InterfaceEndpoint"]NEWLINE """Creates or updates an interface endpoint in the specified resource group.NEWLINENEWLINE :param resource_group_name: The name of the resource group.NEWLINE :type resource_group_name: strNEWLINE :param interface_endpoint_name: The name of the interface endpoint.NEWLINE :type interface_endpoint_name: strNEWLINE :param parameters: Parameters supplied to the create or update interface endpoint operation.NEWLINE :type parameters: ~azure.mgmt.network.v2019_02_01.models.InterfaceEndpointNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :keyword str continuation_token: A continuation token to restart a poller from a saved state.NEWLINE :keyword polling: By default, your polling method will be ARMPolling.NEWLINE Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.NEWLINE :paramtype polling: bool or ~azure.core.polling.PollingMethodNEWLINE :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.NEWLINE :return: An instance of LROPoller that returns either InterfaceEndpoint or the result of cls(response)NEWLINE :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2019_02_01.models.InterfaceEndpoint]NEWLINE :raises ~azure.core.exceptions.HttpResponseError:NEWLINE """NEWLINE polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.InterfaceEndpoint"]NEWLINE lro_delay = kwargs.pop(NEWLINE 'polling_interval',NEWLINE self._config.polling_intervalNEWLINE )NEWLINE cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]NEWLINE if cont_token is None:NEWLINE raw_result = self._create_or_update_initial(NEWLINE resource_group_name=resource_group_name,NEWLINE interface_endpoint_name=interface_endpoint_name,NEWLINE parameters=parameters,NEWLINE cls=lambda x,y,z: x,NEWLINE **kwargsNEWLINE )NEWLINENEWLINE kwargs.pop('error_map', None)NEWLINE kwargs.pop('content_type', None)NEWLINENEWLINE def get_long_running_output(pipeline_response):NEWLINE deserialized = self._deserialize('InterfaceEndpoint', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINE return deserializedNEWLINENEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),NEWLINE 'interfaceEndpointName': self._serialize.url("interface_endpoint_name", interface_endpoint_name, 'str'),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),NEWLINE }NEWLINENEWLINE if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)NEWLINE elif polling is False: polling_method = NoPolling()NEWLINE else: polling_method = pollingNEWLINE if cont_token:NEWLINE return LROPoller.from_continuation_token(NEWLINE polling_method=polling_method,NEWLINE continuation_token=cont_token,NEWLINE client=self._client,NEWLINE deserialization_callback=get_long_running_outputNEWLINE )NEWLINE else:NEWLINE return LROPoller(self._client, raw_result, get_long_running_output, polling_method)NEWLINE begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/interfaceEndpoints/{interfaceEndpointName}'} # type: ignoreNEWLINENEWLINE def list(NEWLINE self,NEWLINE resource_group_name, # type: strNEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> Iterable["_models.InterfaceEndpointListResult"]NEWLINE """Gets all interface endpoints in a resource group.NEWLINENEWLINE :param resource_group_name: The name of the resource group.NEWLINE :type resource_group_name: strNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: An iterator like instance of either InterfaceEndpointListResult or the result of cls(response)NEWLINE :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2019_02_01.models.InterfaceEndpointListResult]NEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.InterfaceEndpointListResult"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2019-02-01"NEWLINE accept = "application/json"NEWLINENEWLINE def prepare_request(next_link=None):NEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINE header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')NEWLINENEWLINE if not next_link:NEWLINE # Construct URLNEWLINE url = self.list.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE request = self._client.get(url, query_parameters, header_parameters)NEWLINE else:NEWLINE url = next_linkNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE request = self._client.get(url, query_parameters, header_parameters)NEWLINE return requestNEWLINENEWLINE def extract_data(pipeline_response):NEWLINE deserialized = self._deserialize('InterfaceEndpointListResult', pipeline_response)NEWLINE list_of_elem = deserialized.valueNEWLINE if cls:NEWLINE list_of_elem = cls(list_of_elem)NEWLINE return deserialized.next_link or None, iter(list_of_elem)NEWLINENEWLINE def get_next(next_link=None):NEWLINE request = prepare_request(next_link)NEWLINENEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE return pipeline_responseNEWLINENEWLINE return ItemPaged(NEWLINE get_next, extract_dataNEWLINE )NEWLINE list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/interfaceEndpoints'} # type: ignoreNEWLINENEWLINE def list_by_subscription(NEWLINE self,NEWLINE **kwargs # type: AnyNEWLINE ):NEWLINE # type: (...) -> Iterable["_models.InterfaceEndpointListResult"]NEWLINE """Gets all interface endpoints in a subscription.NEWLINENEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: An iterator like instance of either InterfaceEndpointListResult or the result of cls(response)NEWLINE :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2019_02_01.models.InterfaceEndpointListResult]NEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.InterfaceEndpointListResult"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE api_version = "2019-02-01"NEWLINE accept = "application/json"NEWLINENEWLINE def prepare_request(next_link=None):NEWLINE # Construct headersNEWLINE header_parameters = {} # type: Dict[str, Any]NEWLINE header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')NEWLINENEWLINE if not next_link:NEWLINE # Construct URLNEWLINE url = self.list_by_subscription.metadata['url'] # type: ignoreNEWLINE path_format_arguments = {NEWLINE 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),NEWLINE }NEWLINE url = self._client.format_url(url, **path_format_arguments)NEWLINE # Construct parametersNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')NEWLINENEWLINE request = self._client.get(url, query_parameters, header_parameters)NEWLINE else:NEWLINE url = next_linkNEWLINE query_parameters = {} # type: Dict[str, Any]NEWLINE request = self._client.get(url, query_parameters, header_parameters)NEWLINE return requestNEWLINENEWLINE def extract_data(pipeline_response):NEWLINE deserialized = self._deserialize('InterfaceEndpointListResult', pipeline_response)NEWLINE list_of_elem = deserialized.valueNEWLINE if cls:NEWLINE list_of_elem = cls(list_of_elem)NEWLINE return deserialized.next_link or None, iter(list_of_elem)NEWLINENEWLINE def get_next(next_link=None):NEWLINE request = prepare_request(next_link)NEWLINENEWLINE pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE return pipeline_responseNEWLINENEWLINE return ItemPaged(NEWLINE get_next, extract_dataNEWLINE )NEWLINE list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/interfaceEndpoints'} # type: ignoreNEWLINE import sys, os, reNEWLINEimport timeNEWLINENEWLINEsys.path.append("lib")NEWLINEimport utilsNEWLINENEWLINEimport requestsNEWLINEfrom bs4 import BeautifulSoupNEWLINENEWLINEtail_number_records = utils.read_json_lines_file('data/tail_numbers.jsonl')NEWLINENEWLINEaircraft_records = []NEWLINE# Loop through the tail numbers, fetchingNEWLINEfor tail_number_record in tail_number_records:NEWLINE time.sleep(0.1) # essential to sleep FIRST in loop or you will flood sitesNEWLINE NEWLINE # Parameterize the URL with the tail numberNEWLINE BASE_URL = 'http://registry.faa.gov/aircraftinquiry/NNum_Results.aspx?NNumbertxt={}'NEWLINE tail_number = tail_number_record['TailNum']NEWLINE url = BASE_URL.format(tail_number)NEWLINENEWLINE # Fetch the page, parse the HTMLNEWLINE r = requests.get(url)NEWLINE NEWLINE html = r.textNEWLINE soup = BeautifulSoup(html)NEWLINE NEWLINE # The table structure is constant for all pages that contain dataNEWLINE try:NEWLINE aircraft_description = soup.find_all('table')[4]NEWLINE craft_tds = aircraft_description.find_all('td')NEWLINE serial_number = craft_tds[1].text.strip()NEWLINE manufacturer = craft_tds[5].text.strip()NEWLINE model = craft_tds[9].text.strip()NEWLINE mfr_year = craft_tds[25].text.strip()NEWLINENEWLINE registered_owner = soup.find_all('table')[5]NEWLINE reg_tds = registered_owner.find_all('td')NEWLINE owner = reg_tds[1].text.strip()NEWLINE owner_state = reg_tds[9].text.strip()NEWLINENEWLINE airworthiness = soup.find_all('table')[6]NEWLINE worthy_tds = airworthiness.find_all('td')NEWLINE engine_manufacturer = worthy_tds[1].text.strip()NEWLINE engine_model = worthy_tds[5].text.strip()NEWLINENEWLINE aircraft_record = {NEWLINE 'TailNum': tail_number,NEWLINE 'serial_number': serial_number,NEWLINE 'manufacturer': manufacturer,NEWLINE 'model': model,NEWLINE 'mfr_year': mfr_year,NEWLINE 'owner': owner,NEWLINE 'owner_state': owner_state,NEWLINE 'engine_manufacturer': engine_manufacturer,NEWLINE 'engine_model': engine_model,NEWLINE }NEWLINE aircraft_records.append(NEWLINE aircraft_recordNEWLINE )NEWLINE print(aircraft_record)NEWLINE NEWLINE except IndexError as e:NEWLINE print("Missing {} record: {}".format(tail_number, e))NEWLINENEWLINEutils.write_json_lines_file(NEWLINE aircraft_records, 'data/faa_tail_number_inquiry.jsonl'NEWLINE)NEWLINE # pylint: disable=too-many-linesNEWLINE# coding=utf-8NEWLINE# --------------------------------------------------------------------------NEWLINE# Copyright (c) Microsoft Corporation. All rights reserved.NEWLINE# Licensed under the MIT License. See License.txt in the project root for license information.NEWLINE# Code generated by Microsoft (R) AutoRest Code Generator.NEWLINE# Changes may cause incorrect behavior and will be lost if the code is regenerated.NEWLINE# --------------------------------------------------------------------------NEWLINEfrom typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, UnionNEWLINENEWLINEfrom azure.core.async_paging import AsyncItemPaged, AsyncListNEWLINEfrom azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_errorNEWLINEfrom azure.core.pipeline import PipelineResponseNEWLINEfrom azure.core.pipeline.transport import AsyncHttpResponseNEWLINEfrom azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethodNEWLINEfrom azure.core.rest import HttpRequestNEWLINEfrom azure.core.tracing.decorator import distributed_traceNEWLINEfrom azure.core.tracing.decorator_async import distributed_trace_asyncNEWLINEfrom azure.mgmt.core.exceptions import ARMErrorFormatNEWLINEfrom azure.mgmt.core.polling.async_arm_polling import AsyncARMPollingNEWLINENEWLINEfrom ... import models as _modelsNEWLINEfrom ..._vendor import _convert_requestNEWLINEfrom ...operations._scope_maps_operations import build_create_request_initial, build_delete_request_initial, build_get_request, build_list_request, build_update_request_initialNEWLINET = TypeVar('T')NEWLINEClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]NEWLINENEWLINEclass ScopeMapsOperations:NEWLINE """ScopeMapsOperations async operations.NEWLINENEWLINE You should not instantiate this class directly. Instead, you should create a Client instance thatNEWLINE instantiates it for you and attaches it as an attribute.NEWLINENEWLINE :ivar models: Alias to model classes used in this operation group.NEWLINE :type models: ~azure.mgmt.containerregistry.v2020_11_01_preview.modelsNEWLINE :param client: Client for service requests.NEWLINE :param config: Configuration of service client.NEWLINE :param serializer: An object model serializer.NEWLINE :param deserializer: An object model deserializer.NEWLINE """NEWLINENEWLINE models = _modelsNEWLINENEWLINE def __init__(self, client, config, serializer, deserializer) -> None:NEWLINE self._client = clientNEWLINE self._serialize = serializerNEWLINE self._deserialize = deserializerNEWLINE self._config = configNEWLINENEWLINE @distributed_trace_asyncNEWLINE async def get(NEWLINE self,NEWLINE resource_group_name: str,NEWLINE registry_name: str,NEWLINE scope_map_name: str,NEWLINE **kwargs: AnyNEWLINE ) -> "_models.ScopeMap":NEWLINE """Gets the properties of the specified scope map.NEWLINENEWLINE :param resource_group_name: The name of the resource group to which the container registryNEWLINE belongs.NEWLINE :type resource_group_name: strNEWLINE :param registry_name: The name of the container registry.NEWLINE :type registry_name: strNEWLINE :param scope_map_name: The name of the scope map.NEWLINE :type scope_map_name: strNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: ScopeMap, or the result of cls(response)NEWLINE :rtype: ~azure.mgmt.containerregistry.v2020_11_01_preview.models.ScopeMapNEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.ScopeMap"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINENEWLINE api_version = kwargs.pop('api_version', "2020-11-01-preview") # type: strNEWLINENEWLINE NEWLINE request = build_get_request(NEWLINE subscription_id=self._config.subscription_id,NEWLINE resource_group_name=resource_group_name,NEWLINE registry_name=registry_name,NEWLINE scope_map_name=scope_map_name,NEWLINE api_version=api_version,NEWLINE template_url=self.get.metadata['url'],NEWLINE )NEWLINE request = _convert_request(request)NEWLINE request.url = self._client.format_url(request.url)NEWLINENEWLINE pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-accessNEWLINE request,NEWLINE stream=False,NEWLINE **kwargsNEWLINE )NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE deserialized = self._deserialize('ScopeMap', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINENEWLINE return deserializedNEWLINENEWLINE get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}"} # type: ignoreNEWLINENEWLINENEWLINE async def _create_initial(NEWLINE self,NEWLINE resource_group_name: str,NEWLINE registry_name: str,NEWLINE scope_map_name: str,NEWLINE scope_map_create_parameters: "_models.ScopeMap",NEWLINE **kwargs: AnyNEWLINE ) -> "_models.ScopeMap":NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.ScopeMap"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINENEWLINE api_version = kwargs.pop('api_version', "2020-11-01-preview") # type: strNEWLINE content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]NEWLINENEWLINE _json = self._serialize.body(scope_map_create_parameters, 'ScopeMap')NEWLINENEWLINE request = build_create_request_initial(NEWLINE subscription_id=self._config.subscription_id,NEWLINE resource_group_name=resource_group_name,NEWLINE registry_name=registry_name,NEWLINE scope_map_name=scope_map_name,NEWLINE api_version=api_version,NEWLINE content_type=content_type,NEWLINE json=_json,NEWLINE template_url=self._create_initial.metadata['url'],NEWLINE )NEWLINE request = _convert_request(request)NEWLINE request.url = self._client.format_url(request.url)NEWLINENEWLINE pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-accessNEWLINE request,NEWLINE stream=False,NEWLINE **kwargsNEWLINE )NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200, 201]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE if response.status_code == 200:NEWLINE deserialized = self._deserialize('ScopeMap', pipeline_response)NEWLINENEWLINE if response.status_code == 201:NEWLINE deserialized = self._deserialize('ScopeMap', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINENEWLINE return deserializedNEWLINENEWLINE _create_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}"} # type: ignoreNEWLINENEWLINENEWLINE @distributed_trace_asyncNEWLINE async def begin_create(NEWLINE self,NEWLINE resource_group_name: str,NEWLINE registry_name: str,NEWLINE scope_map_name: str,NEWLINE scope_map_create_parameters: "_models.ScopeMap",NEWLINE **kwargs: AnyNEWLINE ) -> AsyncLROPoller["_models.ScopeMap"]:NEWLINE """Creates a scope map for a container registry with the specified parameters.NEWLINENEWLINE :param resource_group_name: The name of the resource group to which the container registryNEWLINE belongs.NEWLINE :type resource_group_name: strNEWLINE :param registry_name: The name of the container registry.NEWLINE :type registry_name: strNEWLINE :param scope_map_name: The name of the scope map.NEWLINE :type scope_map_name: strNEWLINE :param scope_map_create_parameters: The parameters for creating a scope map.NEWLINE :type scope_map_create_parameters:NEWLINE ~azure.mgmt.containerregistry.v2020_11_01_preview.models.ScopeMapNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :keyword str continuation_token: A continuation token to restart a poller from a saved state.NEWLINE :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False forNEWLINE this operation to not poll, or pass in your own initialized polling object for a personalNEWLINE polling strategy.NEWLINE :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethodNEWLINE :keyword int polling_interval: Default waiting time between two polls for LRO operations if noNEWLINE Retry-After header is present.NEWLINE :return: An instance of AsyncLROPoller that returns either ScopeMap or the result ofNEWLINE cls(response)NEWLINE :rtype:NEWLINE ~azure.core.polling.AsyncLROPoller[~azure.mgmt.containerregistry.v2020_11_01_preview.models.ScopeMap]NEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE api_version = kwargs.pop('api_version', "2020-11-01-preview") # type: strNEWLINE content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]NEWLINE polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.ScopeMap"]NEWLINE lro_delay = kwargs.pop(NEWLINE 'polling_interval',NEWLINE self._config.polling_intervalNEWLINE )NEWLINE cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]NEWLINE if cont_token is None:NEWLINE raw_result = await self._create_initial(NEWLINE resource_group_name=resource_group_name,NEWLINE registry_name=registry_name,NEWLINE scope_map_name=scope_map_name,NEWLINE scope_map_create_parameters=scope_map_create_parameters,NEWLINE api_version=api_version,NEWLINE content_type=content_type,NEWLINE cls=lambda x,y,z: x,NEWLINE **kwargsNEWLINE )NEWLINE kwargs.pop('error_map', None)NEWLINENEWLINE def get_long_running_output(pipeline_response):NEWLINE response = pipeline_response.http_responseNEWLINE deserialized = self._deserialize('ScopeMap', pipeline_response)NEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINE return deserializedNEWLINENEWLINENEWLINE if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs)NEWLINE elif polling is False: polling_method = AsyncNoPolling()NEWLINE else: polling_method = pollingNEWLINE if cont_token:NEWLINE return AsyncLROPoller.from_continuation_token(NEWLINE polling_method=polling_method,NEWLINE continuation_token=cont_token,NEWLINE client=self._client,NEWLINE deserialization_callback=get_long_running_outputNEWLINE )NEWLINE return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)NEWLINENEWLINE begin_create.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}"} # type: ignoreNEWLINENEWLINE async def _delete_initial( # pylint: disable=inconsistent-return-statementsNEWLINE self,NEWLINE resource_group_name: str,NEWLINE registry_name: str,NEWLINE scope_map_name: str,NEWLINE **kwargs: AnyNEWLINE ) -> None:NEWLINE cls = kwargs.pop('cls', None) # type: ClsType[None]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINENEWLINE api_version = kwargs.pop('api_version', "2020-11-01-preview") # type: strNEWLINENEWLINE NEWLINE request = build_delete_request_initial(NEWLINE subscription_id=self._config.subscription_id,NEWLINE resource_group_name=resource_group_name,NEWLINE registry_name=registry_name,NEWLINE scope_map_name=scope_map_name,NEWLINE api_version=api_version,NEWLINE template_url=self._delete_initial.metadata['url'],NEWLINE )NEWLINE request = _convert_request(request)NEWLINE request.url = self._client.format_url(request.url)NEWLINENEWLINE pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-accessNEWLINE request,NEWLINE stream=False,NEWLINE **kwargsNEWLINE )NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200, 202, 204]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, None, {})NEWLINENEWLINE _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}"} # type: ignoreNEWLINENEWLINENEWLINE @distributed_trace_asyncNEWLINE async def begin_delete( # pylint: disable=inconsistent-return-statementsNEWLINE self,NEWLINE resource_group_name: str,NEWLINE registry_name: str,NEWLINE scope_map_name: str,NEWLINE **kwargs: AnyNEWLINE ) -> AsyncLROPoller[None]:NEWLINE """Deletes a scope map from a container registry.NEWLINENEWLINE :param resource_group_name: The name of the resource group to which the container registryNEWLINE belongs.NEWLINE :type resource_group_name: strNEWLINE :param registry_name: The name of the container registry.NEWLINE :type registry_name: strNEWLINE :param scope_map_name: The name of the scope map.NEWLINE :type scope_map_name: strNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :keyword str continuation_token: A continuation token to restart a poller from a saved state.NEWLINE :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False forNEWLINE this operation to not poll, or pass in your own initialized polling object for a personalNEWLINE polling strategy.NEWLINE :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethodNEWLINE :keyword int polling_interval: Default waiting time between two polls for LRO operations if noNEWLINE Retry-After header is present.NEWLINE :return: An instance of AsyncLROPoller that returns either None or the result of cls(response)NEWLINE :rtype: ~azure.core.polling.AsyncLROPoller[None]NEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE api_version = kwargs.pop('api_version', "2020-11-01-preview") # type: strNEWLINE polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]NEWLINE cls = kwargs.pop('cls', None) # type: ClsType[None]NEWLINE lro_delay = kwargs.pop(NEWLINE 'polling_interval',NEWLINE self._config.polling_intervalNEWLINE )NEWLINE cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]NEWLINE if cont_token is None:NEWLINE raw_result = await self._delete_initial(NEWLINE resource_group_name=resource_group_name,NEWLINE registry_name=registry_name,NEWLINE scope_map_name=scope_map_name,NEWLINE api_version=api_version,NEWLINE cls=lambda x,y,z: x,NEWLINE **kwargsNEWLINE )NEWLINE kwargs.pop('error_map', None)NEWLINENEWLINE def get_long_running_output(pipeline_response):NEWLINE if cls:NEWLINE return cls(pipeline_response, None, {})NEWLINENEWLINENEWLINE if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs)NEWLINE elif polling is False: polling_method = AsyncNoPolling()NEWLINE else: polling_method = pollingNEWLINE if cont_token:NEWLINE return AsyncLROPoller.from_continuation_token(NEWLINE polling_method=polling_method,NEWLINE continuation_token=cont_token,NEWLINE client=self._client,NEWLINE deserialization_callback=get_long_running_outputNEWLINE )NEWLINE return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)NEWLINENEWLINE begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}"} # type: ignoreNEWLINENEWLINE async def _update_initial(NEWLINE self,NEWLINE resource_group_name: str,NEWLINE registry_name: str,NEWLINE scope_map_name: str,NEWLINE scope_map_update_parameters: "_models.ScopeMapUpdateParameters",NEWLINE **kwargs: AnyNEWLINE ) -> "_models.ScopeMap":NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.ScopeMap"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINENEWLINE api_version = kwargs.pop('api_version', "2020-11-01-preview") # type: strNEWLINE content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]NEWLINENEWLINE _json = self._serialize.body(scope_map_update_parameters, 'ScopeMapUpdateParameters')NEWLINENEWLINE request = build_update_request_initial(NEWLINE subscription_id=self._config.subscription_id,NEWLINE resource_group_name=resource_group_name,NEWLINE registry_name=registry_name,NEWLINE scope_map_name=scope_map_name,NEWLINE api_version=api_version,NEWLINE content_type=content_type,NEWLINE json=_json,NEWLINE template_url=self._update_initial.metadata['url'],NEWLINE )NEWLINE request = _convert_request(request)NEWLINE request.url = self._client.format_url(request.url)NEWLINENEWLINE pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-accessNEWLINE request,NEWLINE stream=False,NEWLINE **kwargsNEWLINE )NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200, 201]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE if response.status_code == 200:NEWLINE deserialized = self._deserialize('ScopeMap', pipeline_response)NEWLINENEWLINE if response.status_code == 201:NEWLINE deserialized = self._deserialize('ScopeMap', pipeline_response)NEWLINENEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINENEWLINE return deserializedNEWLINENEWLINE _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}"} # type: ignoreNEWLINENEWLINENEWLINE @distributed_trace_asyncNEWLINE async def begin_update(NEWLINE self,NEWLINE resource_group_name: str,NEWLINE registry_name: str,NEWLINE scope_map_name: str,NEWLINE scope_map_update_parameters: "_models.ScopeMapUpdateParameters",NEWLINE **kwargs: AnyNEWLINE ) -> AsyncLROPoller["_models.ScopeMap"]:NEWLINE """Updates a scope map with the specified parameters.NEWLINENEWLINE :param resource_group_name: The name of the resource group to which the container registryNEWLINE belongs.NEWLINE :type resource_group_name: strNEWLINE :param registry_name: The name of the container registry.NEWLINE :type registry_name: strNEWLINE :param scope_map_name: The name of the scope map.NEWLINE :type scope_map_name: strNEWLINE :param scope_map_update_parameters: The parameters for updating a scope map.NEWLINE :type scope_map_update_parameters:NEWLINE ~azure.mgmt.containerregistry.v2020_11_01_preview.models.ScopeMapUpdateParametersNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :keyword str continuation_token: A continuation token to restart a poller from a saved state.NEWLINE :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False forNEWLINE this operation to not poll, or pass in your own initialized polling object for a personalNEWLINE polling strategy.NEWLINE :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethodNEWLINE :keyword int polling_interval: Default waiting time between two polls for LRO operations if noNEWLINE Retry-After header is present.NEWLINE :return: An instance of AsyncLROPoller that returns either ScopeMap or the result ofNEWLINE cls(response)NEWLINE :rtype:NEWLINE ~azure.core.polling.AsyncLROPoller[~azure.mgmt.containerregistry.v2020_11_01_preview.models.ScopeMap]NEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE api_version = kwargs.pop('api_version', "2020-11-01-preview") # type: strNEWLINE content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]NEWLINE polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]NEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.ScopeMap"]NEWLINE lro_delay = kwargs.pop(NEWLINE 'polling_interval',NEWLINE self._config.polling_intervalNEWLINE )NEWLINE cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]NEWLINE if cont_token is None:NEWLINE raw_result = await self._update_initial(NEWLINE resource_group_name=resource_group_name,NEWLINE registry_name=registry_name,NEWLINE scope_map_name=scope_map_name,NEWLINE scope_map_update_parameters=scope_map_update_parameters,NEWLINE api_version=api_version,NEWLINE content_type=content_type,NEWLINE cls=lambda x,y,z: x,NEWLINE **kwargsNEWLINE )NEWLINE kwargs.pop('error_map', None)NEWLINENEWLINE def get_long_running_output(pipeline_response):NEWLINE response = pipeline_response.http_responseNEWLINE deserialized = self._deserialize('ScopeMap', pipeline_response)NEWLINE if cls:NEWLINE return cls(pipeline_response, deserialized, {})NEWLINE return deserializedNEWLINENEWLINENEWLINE if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs)NEWLINE elif polling is False: polling_method = AsyncNoPolling()NEWLINE else: polling_method = pollingNEWLINE if cont_token:NEWLINE return AsyncLROPoller.from_continuation_token(NEWLINE polling_method=polling_method,NEWLINE continuation_token=cont_token,NEWLINE client=self._client,NEWLINE deserialization_callback=get_long_running_outputNEWLINE )NEWLINE return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)NEWLINENEWLINE begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}"} # type: ignoreNEWLINENEWLINE @distributed_traceNEWLINE def list(NEWLINE self,NEWLINE resource_group_name: str,NEWLINE registry_name: str,NEWLINE **kwargs: AnyNEWLINE ) -> AsyncIterable["_models.ScopeMapListResult"]:NEWLINE """Lists all the scope maps for the specified container registry.NEWLINENEWLINE :param resource_group_name: The name of the resource group to which the container registryNEWLINE belongs.NEWLINE :type resource_group_name: strNEWLINE :param registry_name: The name of the container registry.NEWLINE :type registry_name: strNEWLINE :keyword callable cls: A custom type or function that will be passed the direct responseNEWLINE :return: An iterator like instance of either ScopeMapListResult or the result of cls(response)NEWLINE :rtype:NEWLINE ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.containerregistry.v2020_11_01_preview.models.ScopeMapListResult]NEWLINE :raises: ~azure.core.exceptions.HttpResponseErrorNEWLINE """NEWLINE api_version = kwargs.pop('api_version', "2020-11-01-preview") # type: strNEWLINENEWLINE cls = kwargs.pop('cls', None) # type: ClsType["_models.ScopeMapListResult"]NEWLINE error_map = {NEWLINE 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsErrorNEWLINE }NEWLINE error_map.update(kwargs.pop('error_map', {}))NEWLINE def prepare_request(next_link=None):NEWLINE if not next_link:NEWLINE NEWLINE request = build_list_request(NEWLINE subscription_id=self._config.subscription_id,NEWLINE resource_group_name=resource_group_name,NEWLINE registry_name=registry_name,NEWLINE api_version=api_version,NEWLINE template_url=self.list.metadata['url'],NEWLINE )NEWLINE request = _convert_request(request)NEWLINE request.url = self._client.format_url(request.url)NEWLINENEWLINE else:NEWLINE NEWLINE request = build_list_request(NEWLINE subscription_id=self._config.subscription_id,NEWLINE resource_group_name=resource_group_name,NEWLINE registry_name=registry_name,NEWLINE api_version=api_version,NEWLINE template_url=next_link,NEWLINE )NEWLINE request = _convert_request(request)NEWLINE request.url = self._client.format_url(request.url)NEWLINE request.method = "GET"NEWLINE return requestNEWLINENEWLINE async def extract_data(pipeline_response):NEWLINE deserialized = self._deserialize("ScopeMapListResult", pipeline_response)NEWLINE list_of_elem = deserialized.valueNEWLINE if cls:NEWLINE list_of_elem = cls(list_of_elem)NEWLINE return deserialized.next_link or None, AsyncList(list_of_elem)NEWLINENEWLINE async def get_next(next_link=None):NEWLINE request = prepare_request(next_link)NEWLINENEWLINE pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-accessNEWLINE request,NEWLINE stream=False,NEWLINE **kwargsNEWLINE )NEWLINE response = pipeline_response.http_responseNEWLINENEWLINE if response.status_code not in [200]:NEWLINE map_error(status_code=response.status_code, response=response, error_map=error_map)NEWLINE raise HttpResponseError(response=response, error_format=ARMErrorFormat)NEWLINENEWLINE return pipeline_responseNEWLINENEWLINENEWLINE return AsyncItemPaged(NEWLINE get_next, extract_dataNEWLINE )NEWLINE list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps"} # type: ignoreNEWLINE import osNEWLINENEWLINEBINARIES_PATHS = [NEWLINE '/home/ttz/git/opencv-4.3.0/build/lib'NEWLINE] + BINARIES_PATHSNEWLINE # Copyright 2017 Battelle Energy Alliance, LLCNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE"""NEWLINECreated on Feb. 16 2018NEWLINENEWLINE@author: wangcNEWLINE"""NEWLINE#for future compatibility with Python 3--------------------------------------------------------------NEWLINEfrom __future__ import division, print_function, unicode_literals, absolute_importNEWLINEimport warningsNEWLINEwarnings.simplefilter('default',DeprecationWarning)NEWLINE#End compatibility block for Python 3----------------------------------------------------------------NEWLINENEWLINE#External Modules------------------------------------------------------------------------------------NEWLINEimport mathNEWLINEimport scipyNEWLINEimport numpy as npNEWLINEimport astNEWLINEimport scipy.spatial.distance as spatialDistanceNEWLINE#External Modules End--------------------------------------------------------------------------------NEWLINENEWLINE#Internal Modules------------------------------------------------------------------------------------NEWLINEfrom .Metric import MetricNEWLINEfrom utils import utils, InputDataNEWLINE#Internal Modules End--------------------------------------------------------------------------------NEWLINENEWLINEclass ScipyMetric(Metric):NEWLINE """NEWLINE ScipyMetric metrics which can be employed for both pointSets and historySetsNEWLINE """NEWLINE availMetrics = {}NEWLINE # Distance functions between two numeric vectorsNEWLINE availMetrics['paired_distance'] = {}NEWLINE availMetrics['paired_distance']['braycurtis'] = spatialDistance.braycurtisNEWLINE availMetrics['paired_distance']['canberra'] = spatialDistance.canberraNEWLINE availMetrics['paired_distance']['correlation'] = spatialDistance.correlationNEWLINE availMetrics['paired_distance']['minkowski'] = spatialDistance.minkowskiNEWLINE # Distance functions between two boolean vectorsNEWLINE availMetrics['boolean'] = {}NEWLINE availMetrics['boolean']['rogerstanimoto'] = spatialDistance.rogerstanimotoNEWLINE availMetrics['boolean']['dice'] = spatialDistance.diceNEWLINE availMetrics['boolean']['hamming'] = spatialDistance.hammingNEWLINE availMetrics['boolean']['jaccard'] = spatialDistance.jaccardNEWLINE availMetrics['boolean']['kulsinski'] = spatialDistance.kulsinskiNEWLINE availMetrics['boolean']['russellrao'] = spatialDistance.russellraoNEWLINE availMetrics['boolean']['sokalmichener'] = spatialDistance.sokalmichenerNEWLINE availMetrics['boolean']['sokalsneath'] = spatialDistance.sokalsneathNEWLINE availMetrics['boolean']['yule'] = spatialDistance.yuleNEWLINENEWLINE @classmethodNEWLINE def getInputSpecification(cls):NEWLINE """NEWLINE Method to get a reference to a class that specifies the input data forNEWLINE class cls.NEWLINE @ In, cls, the class for which we are retrieving the specificationNEWLINE @ Out, inputSpecification, InputData.ParameterInput, class to use forNEWLINE specifying input of cls.NEWLINE """NEWLINE inputSpecification = super(ScipyMetric, cls).getInputSpecification()NEWLINE inputSpecification.addSub(InputData.parameterInputFactory("metricType",contentType=InputData.StringType),quantity=InputData.Quantity.one)NEWLINE inputSpecification.addSub(InputData.parameterInputFactory("w",contentType=InputData.FloatListType),quantity=InputData.Quantity.zero_to_one)NEWLINE inputSpecification.addSub(InputData.parameterInputFactory("p",contentType=InputData.FloatType),quantity=InputData.Quantity.zero_to_one)NEWLINENEWLINE return inputSpecificationNEWLINENEWLINE def __init__(self):NEWLINE """NEWLINE ConstructorNEWLINE @ In, NoneNEWLINE @ Out, NoneNEWLINE """NEWLINE Metric.__init__(self)NEWLINE # The type of given metric, None or List of two elements, first element should be in availMetrics.keys()NEWLINE # and sencond element should be in availMetrics.values()[firstElement].keys()NEWLINE self.metricType = NoneNEWLINENEWLINE def _localReadMoreXML(self,xmlNode):NEWLINE """NEWLINE Method that reads the portion of the xml input that belongs to this specialized classNEWLINE and initialize internal parametersNEWLINE @ In, xmlNode, xml.etree.Element, Xml element nodeNEWLINE @ Out, NoneNEWLINE """NEWLINE self.distParams = {}NEWLINE paramInput = ScipyMetric.getInputSpecification()()NEWLINE paramInput.parseNode(xmlNode)NEWLINE for child in paramInput.subparts:NEWLINE if child.getName() == "metricType":NEWLINE self.metricType = list(elem.strip() for elem in child.value.split('|'))NEWLINE if len(self.metricType) != 2:NEWLINE self.raiseAnError(IOError, "Metric type: '", child.value, "' is not correct, please check the user manual for the correct metric type!")NEWLINE else:NEWLINE self.distParams[child.getName()] = child.valueNEWLINENEWLINE if self.metricType[0] not in self.__class__.availMetrics.keys() or self.metricType[1] not in self.__class__.availMetrics[self.metricType[0]].keys():NEWLINE self.raiseAnError(IOError, "Metric '", self.name, "' with metricType '", self.metricType[0], "|", self.metricType[1], "' is not valid!")NEWLINENEWLINE def __evaluateLocal__(self, x, y, weights = None, axis = 0, **kwargs):NEWLINE """NEWLINE This method computes difference between two points x and y based on given metricNEWLINE @ In, x, 1-D numpy.ndarray, array containing data of x.NEWLINE @ In, y, 1-D numpy.ndarray, array containing data of y.NEWLINE @ In, weights, array_like (numpy.array or list), optional, weights associated the metric methodNEWLINE @ In, axis, integer, optional, default is 0, not used in this metricNEWLINE @ In, kwargs, dict, dictionary of parameters characteristic of each metricNEWLINE @ Out, value, float, metric resultNEWLINE """NEWLINE if isinstance(x,np.ndarray) and isinstance(y,np.ndarray):NEWLINE assert(x.shape == y.shape, "Input data x, y should have the same shape!")NEWLINE # TODO: weights are supported in scipy.spatial.distance for many distance metrics in v1.0.0NEWLINE # when we switch to scipy 1.0.0, we can enable weights in our metrics calculationsNEWLINE sv = str(scipy.__version__).split('.')NEWLINE if int(sv[0]) > 0:NEWLINE if weights is not None and 'w' not in self.distParams.keys():NEWLINE self.distParams['w'] = weightsNEWLINE # FIXME: In Scipy version 1.1.0, the function scipy.spatial.distance.canberra andNEWLINE # scipy.spatial.distance.sokalmichener will accept the weights, and the calculated results fromNEWLINE # these functions will affected by the normalization of the weights. The following is disabled forNEWLINE # this purpose --- wangc July 17, 2018NEWLINE # For future development, please pay attention to canberra, minkowski, and sokalmichener metricsNEWLINE #if 'w' in self.distParams.keys():NEWLINE # Normalized weights, since methods exist in Scipy are using unnormalized weightsNEWLINE #self.distParams['w'] = np.asarray(self.distParams['w'])/np.sum(self.distParams['w'])NEWLINE else:NEWLINE if 'w' in self.distParams.keys():NEWLINE self.raiseAWarning("Weights will not be used, since weights provided with key word 'w' is not supported for your current version of scipy!")NEWLINE self.distParams.pop('w')NEWLINE dictTemp = utils.mergeDictionaries(kwargs, self.distParams)NEWLINE try:NEWLINE value = self.__class__.availMetrics[self.metricType[0]][self.metricType[1]](x, y, **dictTemp)NEWLINE except TypeError as e:NEWLINE self.raiseAWarning('There are some unexpected keyword arguments found in Metric with type', self.metricType[1])NEWLINE self.raiseAnError(TypeError, 'Input parameters error: \n', str(e), '\n')NEWLINE else:NEWLINE self.raiseAnError(IOError, "Input data type is not correct!")NEWLINENEWLINE return valueNEWLINE def DetectCollision(characterPosX, characterPosY, character, obstaclePosX, obstaclePosY, obstacle):NEWLINE MARGIN_ERROR = 18 # error with image pixelsNEWLINE collision = FalseNEWLINENEWLINE print("Character:",characterPosX, characterPosY, "\tObstacle", obstaclePosX, obstaclePosY)NEWLINE if ( characterPosX + MARGIN_ERROR < (obstaclePosX + obstacle.getWidth() )NEWLINE and (characterPosX + character[0]) > obstaclePosX + MARGIN_ERRORNEWLINE and characterPosY + MARGIN_ERROR < (obstaclePosY) NEWLINE and (characterPosY + character[1]) > obstaclePosY + MARGIN_ERROR):NEWLINE collision = TrueNEWLINENEWLINE return collisionNEWLINENEWLINE import matplotlib.pyplot as pltNEWLINENEWLINENEWLINEdef analyze(context, perf):NEWLINE ax1 = plt.subplot(211)NEWLINE perf.portfolio_value.plot(ax=ax1)NEWLINE ax2 = plt.subplot(212, sharex=ax1)NEWLINE perf.AAPL.plot(ax=ax2)NEWLINE plt.gcf().set_size_inches(18, 8)NEWLINE plt.show()NEWLINE """NEWLINEModule: 'ujson' on micropython-v1.15-esp8266NEWLINE"""NEWLINE# MCU: {'ver': 'v1.15', 'port': 'esp8266', 'arch': 'xtensa', 'sysname': 'esp8266', 'release': '1.15', 'name': 'micropython', 'mpy': 9733, 'version': '1.15', 'machine': 'ESP module with ESP8266', 'build': '', 'nodename': 'esp8266', 'platform': 'esp8266', 'family': 'micropython'}NEWLINE# Stubber: 1.5.4NEWLINEfrom typing import AnyNEWLINENEWLINENEWLINEdef dump(*args, **kwargs) -> Any:NEWLINE ...NEWLINENEWLINENEWLINEdef dumps(*args, **kwargs) -> Any:NEWLINE ...NEWLINENEWLINENEWLINEdef load(*args, **kwargs) -> Any:NEWLINE ...NEWLINENEWLINENEWLINEdef loads(*args, **kwargs) -> Any:NEWLINE ...NEWLINE import torch.nn as nnNEWLINEimport numpy as npNEWLINEimport matplotlib.pyplot as pltNEWLINEfrom PIL import ImageNEWLINEimport cv2NEWLINENEWLINENEWLINEdef color2hist(color):NEWLINE color = np.asarray(color).flatten()NEWLINE padding_width = 255 - np.max(color)NEWLINE color = plt.hist(color, bins=np.max(color))[0]NEWLINE color /= sum(color)NEWLINE color = np.asarray(color)NEWLINE color = np.pad(color, [0, padding_width], mode='constant', constant_values=0)NEWLINENEWLINE return colorNEWLINENEWLINENEWLINEdef img2hist(path, space='RGB'):NEWLINE assert space in ['RGB', 'LAB']NEWLINE image = cv2.imread(path)NEWLINENEWLINE if space == 'RGB':NEWLINE image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)NEWLINE r, g, b = cv2.split(image)NEWLINE r = color2hist(r)NEWLINE g = color2hist(g)NEWLINE b = color2hist(b)NEWLINENEWLINE return r, g, bNEWLINENEWLINE elif space == 'LAB':NEWLINE image = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)NEWLINE l, a, b = cv2.split(image)NEWLINE l = color2hist(l)NEWLINE a = color2hist(a)NEWLINE b = color2hist(b)NEWLINENEWLINE return l, a, bNEWLINENEWLINE elif space == 'HSV':NEWLINE image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)NEWLINE h, s, v = cv2.split(image)NEWLINE h = color2hist(h)NEWLINE s = color2hist(s)NEWLINE v = color2hist(v)NEWLINENEWLINE return h, s, vNEWLINENEWLINE elif space == 'YCbCr' or 'YCrCb':NEWLINE image = cv2.cvtColor(image, cv2.COLOR_BGR2YCrCb)NEWLINE Y, Cr, Cb = cv2.split(image)NEWLINE Y = color2hist(Y)NEWLINE Cr = color2hist(Cr)NEWLINE Cb = color2hist(Cb)NEWLINENEWLINE return Y, Cr, CbNEWLINENEWLINENEWLINEdef weight_init(module):NEWLINE class_name = module.__class__.__name__NEWLINE if class_name.find('Conv') != -1:NEWLINE module.weight.detach().normal_(0.0, 0.02)NEWLINENEWLINE elif class_name.find('BatchNorm') != -1:NEWLINE module.weight.detach().normal_(1.0, 0.02)NEWLINE module.bias.detach().fill_(0.0)NEWLINENEWLINENEWLINEdef block(module, normalization=True, transpose=False, relu=True, dropout=False):NEWLINE layers = []NEWLINENEWLINE if relu:NEWLINE layers.append(nn.ReLU(inplace=True))NEWLINE elif not relu:NEWLINE layers.append(nn.LeakyReLU(0.2, inplace=True))NEWLINENEWLINE layers.append(module)NEWLINENEWLINE if normalization:NEWLINE if transpose:NEWLINE layers.append(nn.BatchNorm2d(module.weight.size()[1]))NEWLINE elif not transpose:NEWLINE layers.append(nn.BatchNorm2d(module.weight.size()[0]))NEWLINENEWLINE if dropout:NEWLINE layers.append(nn.Dropout2d(0.5, inplace=True))NEWLINENEWLINE return nn.Sequential(*layers)NEWLINENEWLINENEWLINEdef get_grid_shape(opt):NEWLINE assert opt.patch_size in [1, 16, 70, 286]NEWLINE patch_to_grid_dict = {1: (256, 256), 16: (62, 62), 70: (30, 30), 286: (6, 6)}NEWLINENEWLINE return (opt.batch_size, 1, *patch_to_grid_dict[opt.patch_size])NEWLINENEWLINENEWLINEdef adjust_dynamic_range(data, drange_in, drange_out): # define a function for scaling a dataNEWLINE if drange_in != drange_out: # if the range of pixel values are different for input and outputNEWLINE scale = (np.float32(drange_out[1]) - np.float32(drange_out[0]))/(np.float32(drange_in[1]) - np.float32(drange_in[0]))NEWLINE # calculate a scaling factorNEWLINE bias = (np.float32(drange_out[0]) - np.float32(drange_in[0])*scale)NEWLINE # calculate a biasNEWLINE data = data*scale + biasNEWLINE # change the input data based on the scalining factor and biasNEWLINE return data # return the scaled data whose pixel values are within drange_outNEWLINENEWLINENEWLINEdef tensor2image(image_tensor): # define a function for changing torch.tensor to a numpy array before saving imageNEWLINE np_image = image_tensor.squeeze().cpu().float().numpy()NEWLINE # squeeze a input tensor (which means to delete dimensions with value 1) and convert it to cpu tensor(this is forNEWLINE # the case you use GPU during training). Ensure the pixel values have float type and finally convert to numpy array.NEWLINE if len(np_image.shape) == 2: # if the array has only two dimensions (which means it is gray image)NEWLINE pass # pass without changing the order of the axesNEWLINE elif len(np_image.shape) == 3: # if the array has three dimensions (which means t is color(RGB) image)NEWLINE np_image = np.transpose(np_image, (1, 2, 0)) # change the order of the axes from (C, H, W) to (H, W, C)NEWLINENEWLINE np_image = adjust_dynamic_range(np_image, drange_in=[-1., 1.], drange_out=[0, 255]) # scale the pixel valuesNEWLINE np_image = np.clip(np_image, 0, 255).astype(np.uint8) # make its type uint8 so that you can save the imageNEWLINE return np_image # return the processed imageNEWLINENEWLINENEWLINEdef save_image(image_tensor, path): # define a function for saving processed imageNEWLINE np_image = tensor2image(image_tensor) # change a torch.tensor to a numpy imageNEWLINE pil_image = Image.fromarray(np_image) # convert the numpy image to Image objectNEWLINE pil_image.save(path + '.png', mode='PNG') # save the image with given path and modeNEWLINE # Copyright (c) Facebook, Inc. and its affiliates.NEWLINE#NEWLINE# This source code is licensed under the MIT license found in theNEWLINE# LICENSE file in the root directory of this source tree.NEWLINENEWLINEimport mathNEWLINENEWLINEimport torchNEWLINEimport torch.nn.functional as FNEWLINENEWLINEfrom fairseq import utilsNEWLINENEWLINEfrom fairseq.criterions import FairseqCriterion, register_criterionNEWLINENEWLINENEWLINE@register_criterion('ngram_language_loss')NEWLINEclass NgramLmLoss(FairseqCriterion):NEWLINE """NEWLINE Implementation for the loss used in masked language model (MLM) training.NEWLINE """NEWLINE def __init__(self, args, task):NEWLINE super().__init__(args, task)NEWLINE self.eps = args.label_smoothingNEWLINE self.disable_ngram_loss = args.disable_ngram_lossNEWLINENEWLINE @staticmethodNEWLINE def add_args(parser):NEWLINE """Add criterion-specific arguments to the parser."""NEWLINE parser.add_argument(NEWLINE '--label-smoothing',NEWLINE default=0.,NEWLINE type=float,NEWLINE metavar='D',NEWLINE help='epsilon for label smoothing, 0 means no label smoothing')NEWLINE parser.add_argument('--disable-ngram-loss',NEWLINE action='store_true',NEWLINE help='only comput basic stat')NEWLINENEWLINE def forward(self, model, sample, reduce=True):NEWLINE """Compute the loss for the given sample.NEWLINE Returns a tuple with three elements:NEWLINE 1) the lossNEWLINE 2) the sample size, which is used as the denominator for the gradientNEWLINE 3) logging outputs to display while trainingNEWLINE """NEWLINE # compute MLM lossNEWLINE logits_list = model(**sample['net_input'], return_all_hiddens=False)[0]NEWLINE targets = model.get_targets(sample, [logits_list[0]])NEWLINENEWLINE ngram = len(logits_list)NEWLINE # [B, ngram, T]NEWLINE expend_targets = targets.new_zeros(NEWLINE ngram, targets.size(0), targets.size(1)).fill_(self.padding_idx)NEWLINE for i in range(ngram):NEWLINE if i > 0 and self.disable_ngram_loss:NEWLINE breakNEWLINENEWLINE padding_targets = torch.zeros_like(targets).fill_(self.padding_idx)NEWLINE if 'target_idx' in sample:NEWLINE expend_targets[i, :, :] = torch.where(NEWLINE sample['target_idx'] >= i, targets, padding_targets)NEWLINE else:NEWLINE expend_targets[i, :, :] = targetsNEWLINE targets = expend_targetsNEWLINENEWLINE logits = torch.cat(logits_list, dim=0)NEWLINENEWLINE lprobs = F.log_softmax(NEWLINE logits.view(-1, logits.size(-1)),NEWLINE dim=-1,NEWLINE dtype=torch.float32,NEWLINE )NEWLINENEWLINE loss = F.nll_loss(NEWLINE lprobs,NEWLINE targets.view(-1),NEWLINE reduction='sum',NEWLINE ignore_index=self.padding_idx,NEWLINE )NEWLINENEWLINE if self.eps > 0.:NEWLINE smooth_loss = -lprobs.sum(dim=-1, keepdim=True)NEWLINE non_pad_mask = targets.ne(self.padding_idx).view(-1)NEWLINE smooth_loss = smooth_loss[non_pad_mask]NEWLINE smooth_loss = smooth_loss.sum()NEWLINENEWLINE eps_i = self.eps / lprobs.size(-1)NEWLINE loss = (1. - self.eps) * loss + eps_i * smooth_lossNEWLINENEWLINE sample_size = targets.ne(self.padding_idx).int().sum().item()NEWLINENEWLINE logging_output = {NEWLINE 'loss': utils.item(loss.data) if reduce else loss.data,NEWLINE 'ntokens': sample['ntokens'],NEWLINE 'nsentences': sample['nsentences'],NEWLINE 'sample_size': sample_size,NEWLINE }NEWLINE return loss, sample_size, logging_outputNEWLINENEWLINE @staticmethodNEWLINE def aggregate_logging_outputs(logging_outputs):NEWLINE """Aggregate logging outputs from data parallel training."""NEWLINE loss = sum(log.get('loss', 0) for log in logging_outputs)NEWLINE ntokens = sum(log.get('ntokens', 0) for log in logging_outputs)NEWLINE nsentences = sum(log.get('nsentences', 0) for log in logging_outputs)NEWLINE sample_size = sum(log.get('sample_size', 0) for log in logging_outputs)NEWLINENEWLINE agg_output = {NEWLINE 'loss': loss / sample_size / math.log(2),NEWLINE 'ntokens': ntokens,NEWLINE 'nsentences': nsentences,NEWLINE 'sample_size': sample_size,NEWLINE }NEWLINE return agg_outputNEWLINE __all__ = [NEWLINE 'dates',NEWLINE 'dictionary',NEWLINE 'greetings',NEWLINE 'ircbot',NEWLINE 'js',NEWLINE 'listcommands',NEWLINE 'locator',NEWLINE 'pip',NEWLINE 'repeats',NEWLINE 'scheme',NEWLINE 'storedresponses',NEWLINE]NEWLINE from unittest import TestCaseNEWLINEimport numpy as npNEWLINEimport osNEWLINEimport pickleNEWLINEimport loggingNEWLINENEWLINEfrom qcodes.data.data_array import DataArrayNEWLINEfrom qcodes.data.io import DiskIONEWLINEfrom qcodes.data.data_set import load_data, new_data, DataSetNEWLINEfrom qcodes.utils.helpers import LogCaptureNEWLINENEWLINEfrom .data_mocks import (MockFormatter, MatchIO,NEWLINE DataSet2D, DataSet1D,NEWLINE DataSetCombined, RecordingMockFormatter)NEWLINENEWLINEfrom .common import strip_qcNEWLINENEWLINENEWLINEclass TestDataArray(TestCase):NEWLINENEWLINE def test_attributes(self):NEWLINE pname = 'Betty Sue'NEWLINE plabel = 'The best apple pie this side of Wenatchee'NEWLINE pfullname = 'bert'NEWLINENEWLINE class MockParam:NEWLINE name = pnameNEWLINE label = plabelNEWLINENEWLINE def __init__(self, full_name=None):NEWLINE self.full_name = full_nameNEWLINENEWLINE name = 'Oscar'NEWLINE label = 'The grouch. GRR!'NEWLINE fullname = 'ernie'NEWLINE array_id = 24601NEWLINE set_arrays = ('awesomeness', 'chocolate content')NEWLINE shape = 'Ginornous'NEWLINE action_indices = (1, 2, 3, 4, 5)NEWLINENEWLINE p_data = DataArray(parameter=MockParam(pfullname), name=name,NEWLINE label=label, full_name=fullname)NEWLINE p_data2 = DataArray(parameter=MockParam(pfullname))NEWLINENEWLINE # explicitly given name and label override parameter valsNEWLINE self.assertEqual(p_data.name, name)NEWLINE self.assertEqual(p_data.label, label)NEWLINE self.assertEqual(p_data.full_name, fullname)NEWLINE self.assertEqual(p_data2.name, pname)NEWLINE self.assertEqual(p_data2.label, plabel)NEWLINE self.assertEqual(p_data2.full_name, pfullname)NEWLINE # test default valuesNEWLINE self.assertIsNone(p_data.array_id)NEWLINE self.assertEqual(p_data.shape, ())NEWLINE self.assertEqual(p_data.action_indices, ())NEWLINE self.assertEqual(p_data.set_arrays, ())NEWLINE self.assertIsNone(p_data.ndarray)NEWLINENEWLINE np_data = DataArray(name=name, label=label, array_id=array_id,NEWLINE set_arrays=set_arrays, shape=shape,NEWLINE action_indices=action_indices)NEWLINE self.assertEqual(np_data.name, name)NEWLINE self.assertEqual(np_data.label, label)NEWLINE # no full name or parameter - use nameNEWLINE self.assertEqual(np_data.full_name, name)NEWLINE # test simple assignmentsNEWLINE self.assertEqual(np_data.array_id, array_id)NEWLINE self.assertEqual(np_data.set_arrays, set_arrays)NEWLINE self.assertEqual(np_data.shape, shape)NEWLINE self.assertEqual(np_data.action_indices, action_indices)NEWLINENEWLINE name_data = DataArray(name=name)NEWLINE self.assertEqual(name_data.label, name)NEWLINENEWLINE blank_data = DataArray()NEWLINE self.assertIsNone(blank_data.name)NEWLINENEWLINE def test_preset_data(self):NEWLINE onetwothree = [NEWLINE # lists and tuples workNEWLINE [1.0, 2.0, 3.0],NEWLINE (1.0, 2.0, 3.0),NEWLINENEWLINE # iterators get automatically cast to floatsNEWLINE (i + 1 for i in range(3)),NEWLINE map(float, range(1, 4)),NEWLINENEWLINE # and of course numpy arrays themselves workNEWLINE np.array([1.0, 2.0, 3.0]),NEWLINE ]NEWLINENEWLINE expected123 = [1.0, 2.0, 3.0]NEWLINENEWLINE for item in onetwothree:NEWLINE data = DataArray(preset_data=item)NEWLINE self.assertEqual(data.ndarray.tolist(), expected123)NEWLINE self.assertEqual(data.shape, (3, ))NEWLINENEWLINE # you can re-initialize a DataArray with the same shape data,NEWLINE # but not with a different shapeNEWLINE list456 = [4, 5, 6]NEWLINE data.init_data(data=list456)NEWLINE self.assertEqual(data.ndarray.tolist(), list456)NEWLINE with self.assertRaises(ValueError):NEWLINE data.init_data([1, 2])NEWLINE self.assertEqual(data.ndarray.tolist(), list456)NEWLINE self.assertEqual(data.shape, (3, ))NEWLINENEWLINE # you can call init_data again with no data, and nothing changesNEWLINE data.init_data()NEWLINE self.assertEqual(data.ndarray.tolist(), list456)NEWLINE self.assertEqual(data.shape, (3, ))NEWLINENEWLINE # multidimensional works tooNEWLINE list2d = [[1, 2], [3, 4]]NEWLINE data2 = DataArray(preset_data=list2d)NEWLINE self.assertEqual(data2.ndarray.tolist(), list2d)NEWLINE self.assertEqual(data2.shape, (2, 2))NEWLINENEWLINE def test_init_data_error(self):NEWLINE data = DataArray(preset_data=[1, 2])NEWLINE data.shape = (3, )NEWLINENEWLINE # not sure when this would happen... but if you call init_dataNEWLINE # and it notices an inconsistency between shape and the actualNEWLINE # data that's already there, it raises an errorNEWLINE with self.assertRaises(ValueError):NEWLINE data.init_data()NEWLINENEWLINE def test_clear(self):NEWLINE nan = float('nan')NEWLINE data = DataArray(preset_data=[1, 2])NEWLINE data.clear()NEWLINE # sometimes it's annoying that nan != nanNEWLINE self.assertEqual(repr(data.ndarray.tolist()), repr([nan, nan]))NEWLINENEWLINE def test_edit_and_mark(self):NEWLINE data = DataArray(preset_data=[[1, 2], [3, 4]])NEWLINE self.assertEqual(data[0].tolist(), [1, 2])NEWLINE self.assertEqual(data[0, 1], 2)NEWLINENEWLINE data.modified_range = NoneNEWLINE self.assertIsNone(data.last_saved_index)NEWLINENEWLINE self.assertEqual(len(data), 2)NEWLINE data[0] = np.array([5, 6])NEWLINE data[1, 0] = 7NEWLINE self.assertEqual(data.ndarray.tolist(), [[5, 6], [7, 4]])NEWLINENEWLINE self.assertEqual(data.modified_range, (0, 2))NEWLINENEWLINE # as if we saved the first two points... the third should stillNEWLINE # show as modifiedNEWLINE data.mark_saved(1)NEWLINE self.assertEqual(data.last_saved_index, 1)NEWLINE self.assertEqual(data.modified_range, (2, 2))NEWLINENEWLINE # now we save the third point... no modifications left.NEWLINE data.mark_saved(2)NEWLINE self.assertEqual(data.last_saved_index, 2)NEWLINE self.assertEqual(data.modified_range, None)NEWLINENEWLINE data.clear_save()NEWLINE self.assertEqual(data.last_saved_index, None)NEWLINE self.assertEqual(data.modified_range, (0, 2))NEWLINENEWLINE def test_edit_and_mark_slice(self):NEWLINE data = DataArray(preset_data=[[1] * 5] * 6)NEWLINENEWLINE self.assertEqual(data.shape, (6, 5))NEWLINE data.modified_range = NoneNEWLINENEWLINE data[:4:2, 2:] = 2NEWLINE self.assertEqual(data.tolist(), [NEWLINE [1, 1, 2, 2, 2],NEWLINE [1, 1, 1, 1, 1],NEWLINE [1, 1, 2, 2, 2],NEWLINE [1, 1, 1, 1, 1],NEWLINE [1, 1, 1, 1, 1],NEWLINE [1, 1, 1, 1, 1]NEWLINE ])NEWLINE self.assertEqual(data.modified_range, (2, 14))NEWLINENEWLINE def test_repr(self):NEWLINE array2d = [[1, 2], [3, 4]]NEWLINE arrayrepr = repr(np.array(array2d))NEWLINE array_id = (3, 4)NEWLINE data = DataArray(preset_data=array2d)NEWLINENEWLINE self.assertEqual(repr(data), 'DataArray[2,2]:\n' + arrayrepr)NEWLINENEWLINE data.array_id = array_idNEWLINE self.assertEqual(repr(data), 'DataArray[2,2]: ' + str(array_id) +NEWLINE '\n' + arrayrepr)NEWLINENEWLINE def test_nest_empty(self):NEWLINE data = DataArray()NEWLINENEWLINE self.assertEqual(data.shape, ())NEWLINENEWLINE mock_set_array = 'not really an array but we don\'t check'NEWLINE mock_set_array2 = 'another one'NEWLINENEWLINE data.nest(2, action_index=44, set_array=mock_set_array)NEWLINE data.nest(3, action_index=66, set_array=mock_set_array2)NEWLINENEWLINE # the array doesn't exist until you initialize itNEWLINE self.assertIsNone(data.ndarray)NEWLINENEWLINE # but other attributes are setNEWLINE self.assertEqual(data.shape, (3, 2))NEWLINE self.assertEqual(data.action_indices, (66, 44))NEWLINE self.assertEqual(data.set_arrays, (mock_set_array2, mock_set_array))NEWLINENEWLINE data.init_data()NEWLINE self.assertEqual(data.ndarray.shape, (3, 2))NEWLINENEWLINE # after initializing data, you can't nest anymore because this isn'tNEWLINE # a preset arrayNEWLINE with self.assertRaises(RuntimeError):NEWLINE data.nest(4)NEWLINENEWLINE def test_nest_preset(self):NEWLINE data = DataArray(preset_data=[1, 2])NEWLINE data.nest(3)NEWLINE self.assertEqual(data.shape, (3, 2))NEWLINE self.assertEqual(data.ndarray.tolist(), [[1, 2]] * 3)NEWLINE self.assertEqual(data.action_indices, ())NEWLINE self.assertEqual(data.set_arrays, (data,))NEWLINENEWLINE # test that the modified range gets correctly set toNEWLINE # (0, 2*3-1 = 5)NEWLINE self.assertEqual(data.modified_range, (0, 5))NEWLINENEWLINE # you need a set array for all but the inner nestingNEWLINE with self.assertRaises(TypeError):NEWLINE data.nest(4)NEWLINENEWLINE def test_data_set_property(self):NEWLINE data = DataArray(preset_data=[1, 2])NEWLINE self.assertIsNone(data.data_set)NEWLINENEWLINE mock_data_set = 'pretend this is a DataSet, we don\'t check type'NEWLINE mock_data_set2 = 'you can only assign to another after first clearing'NEWLINE data.data_set = mock_data_setNEWLINE self.assertEqual(data.data_set, mock_data_set)NEWLINENEWLINE with self.assertRaises(RuntimeError):NEWLINE data.data_set = mock_data_set2NEWLINENEWLINE data.data_set = NoneNEWLINE self.assertIsNone(data.data_set)NEWLINE data.data_set = mock_data_set2NEWLINE self.assertEqual(data.data_set, mock_data_set2)NEWLINENEWLINE def test_fraction_complete(self):NEWLINE data = DataArray(shape=(5, 10))NEWLINE self.assertIsNone(data.ndarray)NEWLINE self.assertEqual(data.fraction_complete(), 0.0)NEWLINENEWLINE data.init_data()NEWLINE self.assertEqual(data.fraction_complete(), 0.0)NEWLINENEWLINE # index = 1 * 10 + 7 - add 1 (for index 0) and you get 18NEWLINE # each index is 2% of the total, so this is 36%NEWLINE data[1, 7] = 1NEWLINE self.assertEqual(data.fraction_complete(), 18/50)NEWLINENEWLINE # add a last_saved_index but modified_range is still biggerNEWLINE data.mark_saved(13)NEWLINE self.assertEqual(data.fraction_complete(), 18/50)NEWLINENEWLINE # now last_saved_index winsNEWLINE data.mark_saved(19)NEWLINE self.assertEqual(data.fraction_complete(), 20/50)NEWLINENEWLINE # now pretend we get more info from syncingNEWLINE data.synced_index = 22NEWLINE self.assertEqual(data.fraction_complete(), 23/50)NEWLINENEWLINENEWLINEclass TestLoadData(TestCase):NEWLINENEWLINE def test_no_saved_data(self):NEWLINE with self.assertRaises(IOError):NEWLINE load_data('_no/such/file_')NEWLINENEWLINE def test_load_false(self):NEWLINE with self.assertRaises(ValueError):NEWLINE load_data(False)NEWLINENEWLINE def test_get_read(self):NEWLINE data = load_data(formatter=MockFormatter(), location='here!')NEWLINE self.assertEqual(data.has_read_data, True)NEWLINE self.assertEqual(data.has_read_metadata, True)NEWLINENEWLINENEWLINEclass TestDataSetMetaData(TestCase):NEWLINENEWLINE def test_snapshot(self):NEWLINE data = new_data(location=False)NEWLINE expected_snap = {NEWLINE '__class__': 'qcodes.data.data_set.DataSet',NEWLINE 'location': False,NEWLINE 'arrays': {},NEWLINE 'formatter': 'qcodes.data.gnuplot_format.GNUPlotFormat',NEWLINE }NEWLINE snap = strip_qc(data.snapshot())NEWLINENEWLINE # handle io separately so we don't need to figure out our pathNEWLINE self.assertIn('DiskIO', snap['io'])NEWLINE del snap['io']NEWLINE self.assertEqual(snap, expected_snap)NEWLINENEWLINE # even though we removed io from the snapshot, it's still in .metadataNEWLINE self.assertIn('io', data.metadata)NEWLINENEWLINE # then do the same transformations to metadata to check it tooNEWLINE del data.metadata['io']NEWLINE strip_qc(data.metadata)NEWLINE self.assertEqual(data.metadata, expected_snap)NEWLINENEWLINE # location is False so read_metadata should be a noopNEWLINE data.metadata = {'food': 'Fried chicken'}NEWLINE data.read_metadata()NEWLINE self.assertEqual(data.metadata, {'food': 'Fried chicken'})NEWLINENEWLINE # snapshot should never delete things from metadata, only add or updateNEWLINE data.metadata['location'] = 'Idaho'NEWLINE snap = strip_qc(data.snapshot())NEWLINE expected_snap['food'] = 'Fried chicken'NEWLINE del snap['io']NEWLINE self.assertEqual(snap, expected_snap)NEWLINENEWLINENEWLINEclass TestNewData(TestCase):NEWLINENEWLINE @classmethodNEWLINE def setUpClass(cls):NEWLINE cls.original_lp = DataSet.location_providerNEWLINENEWLINE @classmethodNEWLINE def tearDownClass(cls):NEWLINE DataSet.location_provider = cls.original_lpNEWLINENEWLINE def test_overwrite(self):NEWLINE io = MatchIO([1])NEWLINENEWLINE with self.assertRaises(FileExistsError):NEWLINE new_data(location='somewhere', io=io)NEWLINENEWLINE data = new_data(location='somewhere', io=io, overwrite=True,)NEWLINE self.assertEqual(data.location, 'somewhere')NEWLINENEWLINE def test_location_functions(self):NEWLINE def my_location(io, record):NEWLINE return 'data/{}'.format((record or {}).get('name') or 'LOOP!')NEWLINENEWLINE def my_location2(io, record):NEWLINE name = (record or {}).get('name') or 'loop?'NEWLINE return 'data/{}/folder'.format(name)NEWLINENEWLINE DataSet.location_provider = my_locationNEWLINENEWLINE self.assertEqual(new_data().location, 'data/LOOP!')NEWLINE self.assertEqual(new_data(name='cheese').location, 'data/cheese')NEWLINENEWLINE data = new_data(location=my_location2)NEWLINE self.assertEqual(data.location, 'data/loop?/folder')NEWLINE data = new_data(location=my_location2, name='iceCream')NEWLINE self.assertEqual(data.location, 'data/iceCream/folder')NEWLINENEWLINENEWLINEclass TestDataSet(TestCase):NEWLINENEWLINE def test_constructor_errors(self):NEWLINE # no location - only allowed with load_dataNEWLINE with self.assertRaises(ValueError):NEWLINE DataSet()NEWLINE # wrong typeNEWLINE with self.assertRaises(ValueError):NEWLINE DataSet(location=42)NEWLINENEWLINE def test_write_copy(self):NEWLINE data = DataSet1D(location=False)NEWLINE mockbase = os.path.abspath('some_folder')NEWLINE data.io = DiskIO(mockbase)NEWLINENEWLINE mr = (2, 3)NEWLINE mr_full = (0, 4)NEWLINE lsi = 1NEWLINE data.x_set.modified_range = mrNEWLINE data.y.modified_range = mrNEWLINE data.x_set.last_saved_index = lsiNEWLINE data.y.last_saved_index = lsiNEWLINENEWLINE with self.assertRaises(TypeError):NEWLINE data.write_copy()NEWLINENEWLINE with self.assertRaises(TypeError):NEWLINE data.write_copy(path='some/path', io_manager=DiskIO('.'))NEWLINENEWLINE with self.assertRaises(TypeError):NEWLINE data.write_copy(path='some/path', location='something/else')NEWLINENEWLINE data.formatter = RecordingMockFormatter()NEWLINE data.write_copy(path='/some/abs/path')NEWLINE self.assertEqual(data.formatter.write_calls,NEWLINE [(None, '/some/abs/path')])NEWLINE self.assertEqual(data.formatter.write_metadata_calls,NEWLINE [(None, '/some/abs/path', False)])NEWLINE # check that the formatter gets called as if nothing has been savedNEWLINE self.assertEqual(data.formatter.modified_ranges,NEWLINE [{'x_set': mr_full, 'y': mr_full}])NEWLINE self.assertEqual(data.formatter.last_saved_indices,NEWLINE [{'x_set': None, 'y': None}])NEWLINE # but the dataset afterward has its original mods backNEWLINE self.assertEqual(data.x_set.modified_range, mr)NEWLINE self.assertEqual(data.y.modified_range, mr)NEWLINE self.assertEqual(data.x_set.last_saved_index, lsi)NEWLINE self.assertEqual(data.y.last_saved_index, lsi)NEWLINENEWLINE # recreate the formatter to clear the calls attributesNEWLINE data.formatter = RecordingMockFormatter()NEWLINE data.write_copy(location='some/rel/path')NEWLINE self.assertEqual(data.formatter.write_calls,NEWLINE [(mockbase, 'some/rel/path')])NEWLINE self.assertEqual(data.formatter.write_metadata_calls,NEWLINE [(mockbase, 'some/rel/path', False)])NEWLINENEWLINE mockbase2 = os.path.abspath('some/other/folder')NEWLINE io2 = DiskIO(mockbase2)NEWLINENEWLINE with self.assertRaises(ValueError):NEWLINE # if location=False we need to specify it in write_copyNEWLINE data.write_copy(io_manager=io2)NEWLINENEWLINE data.location = 'yet/another/path'NEWLINE data.formatter = RecordingMockFormatter()NEWLINE data.write_copy(io_manager=io2)NEWLINE self.assertEqual(data.formatter.write_calls,NEWLINE [(mockbase2, 'yet/another/path')])NEWLINE self.assertEqual(data.formatter.write_metadata_calls,NEWLINE [(mockbase2, 'yet/another/path', False)])NEWLINENEWLINE def test_pickle_dataset(self):NEWLINE # Test pickling of DataSet objectNEWLINE # If the data_manager is set to None, then the object should pickle.NEWLINE m = DataSet2D()NEWLINE pickle.dumps(m)NEWLINENEWLINE def test_default_parameter(self):NEWLINE # Test whether the default_array function worksNEWLINE m = DataSet2D()NEWLINENEWLINE # test we can run with default argumentsNEWLINE name = m.default_parameter_name()NEWLINENEWLINE # test with paramnameNEWLINE name = m.default_parameter_name(paramname='z')NEWLINE self.assertEqual(name, 'z')NEWLINE # test we can get the array instead of the nameNEWLINE array = m.default_parameter_array(paramname='z')NEWLINE self.assertEqual(array, m.z)NEWLINENEWLINE # first non-setpoint arrayNEWLINE array = m.default_parameter_array()NEWLINE self.assertEqual(array, m.z)NEWLINENEWLINE # test with metadataNEWLINE m.metadata = dict({'default_parameter_name': 'x_set'})NEWLINE name = m.default_parameter_name()NEWLINE self.assertEqual(name, 'x_set')NEWLINENEWLINE # test the fallback: no name matches, no non-setpoint arrayNEWLINE x = DataArray(name='x', label='X', preset_data=(1., 2., 3., 4., 5.), is_setpoint=True)NEWLINE m= new_data(arrays=(x,), name='onlysetpoint')NEWLINE name=m.default_parameter_name(paramname='dummy')NEWLINE self.assertEqual(name, 'x_set')NEWLINENEWLINE def test_fraction_complete(self):NEWLINE empty_data = new_data(arrays=(), location=False)NEWLINE self.assertEqual(empty_data.fraction_complete(), 0.0)NEWLINENEWLINE data = DataSetCombined(location=False)NEWLINE self.assertEqual(data.fraction_complete(), 1.0)NEWLINENEWLINE # alter only the measured arrays, check that only these are usedNEWLINE # to calculate fraction_completeNEWLINE data.y1.modified_range = (0, 0) # 1 of 2NEWLINE data.y2.modified_range = (0, 0) # 1 of 2NEWLINE data.z1.modified_range = (0, 2) # 3 of 6NEWLINE data.z2.modified_range = (0, 2) # 3 of 6NEWLINE self.assertEqual(data.fraction_complete(), 0.5)NEWLINENEWLINE # mark more things complete using last_saved_index and synced_indexNEWLINE data.y1.last_saved_index = 1 # 2 of 2NEWLINE data.z1.synced_index = 5 # 6 of 6NEWLINE self.assertEqual(data.fraction_complete(), 0.75)NEWLINENEWLINE def mock_sync(self):NEWLINE i = self.sync_indexNEWLINE self.syncing_array[i] = iNEWLINE self.sync_index = i + 1NEWLINE return self.sync_index < self.syncing_array.sizeNEWLINENEWLINE def failing_func(self):NEWLINE raise RuntimeError('it is called failing_func for a reason!')NEWLINENEWLINE def logging_func(self):NEWLINE logging.info('background at index {}'.format(self.sync_index))NEWLINENEWLINE def test_complete(self):NEWLINE array = DataArray(name='y', shape=(5,))NEWLINE array.init_data()NEWLINE data = new_data(arrays=(array,), location=False)NEWLINE self.syncing_array = arrayNEWLINE self.sync_index = 0NEWLINE data.sync = self.mock_syncNEWLINE bf = DataSet.background_functionsNEWLINE bf['fail'] = self.failing_funcNEWLINE bf['log'] = self.logging_funcNEWLINENEWLINE with LogCapture() as logs:NEWLINE # grab info and warnings but not debug messagesNEWLINE logging.getLogger().setLevel(logging.INFO)NEWLINE data.complete(delay=0.001)NEWLINENEWLINE logs = logs.valueNEWLINENEWLINE expected_logs = [NEWLINE 'waiting for DataSet to complete',NEWLINE 'DataSet: 0% complete',NEWLINE 'RuntimeError: it is called failing_func for a reason!',NEWLINE 'background at index 1',NEWLINE 'DataSet: 20% complete',NEWLINE 'RuntimeError: it is called failing_func for a reason!',NEWLINE 'background function fail failed twice in a row, removing it',NEWLINE 'background at index 2',NEWLINE 'DataSet: 40% complete',NEWLINE 'background at index 3',NEWLINE 'DataSet: 60% complete',NEWLINE 'background at index 4',NEWLINE 'DataSet: 80% complete',NEWLINE 'background at index 5',NEWLINE 'DataSet is complete'NEWLINE ]NEWLINENEWLINE log_index = 0NEWLINE for line in expected_logs:NEWLINE self.assertIn(line, logs, logs)NEWLINE try:NEWLINE log_index_new = logs.index(line, log_index)NEWLINE except ValueError:NEWLINE raise ValueError('line {} not found after {} in: \n {}'.format(NEWLINE line, log_index, logs))NEWLINE self.assertTrue(log_index_new >= log_index, logs)NEWLINE log_index = log_index_new + len(line) + 1 # +1 for \nNEWLINE self.assertEqual(log_index, len(logs), logs)NEWLINE import wxNEWLINENEWLINEfrom meerk40t.gui.scene.sceneconst import (NEWLINE RESPONSE_ABORT,NEWLINE RESPONSE_CHAIN,NEWLINE RESPONSE_CONSUME,NEWLINE)NEWLINEfrom meerk40t.gui.toolwidgets.toolwidget import ToolWidgetNEWLINEfrom meerk40t.svgelements import Ellipse, PathNEWLINENEWLINENEWLINEclass EllipseTool(ToolWidget):NEWLINE """NEWLINE Ellipse Drawing Tool.NEWLINENEWLINE Adds Circle with click and drag.NEWLINE """NEWLINENEWLINE def __init__(self, scene):NEWLINE ToolWidget.__init__(self, scene)NEWLINE self.start_position = NoneNEWLINE self.p1 = NoneNEWLINE self.p2 = NoneNEWLINENEWLINE def process_draw(self, gc: wx.GraphicsContext):NEWLINE if self.p1 is not None and self.p2 is not None:NEWLINE x0 = min(self.p1.real, self.p2.real)NEWLINE y0 = min(self.p1.imag, self.p2.imag)NEWLINE x1 = max(self.p1.real, self.p2.real)NEWLINE y1 = max(self.p1.imag, self.p2.imag)NEWLINE gc.SetPen(self.pen)NEWLINE gc.SetBrush(wx.TRANSPARENT_BRUSH)NEWLINE gc.DrawEllipse(x0, y0, x1 - x0, y1 - y0)NEWLINENEWLINE def event(self, window_pos=None, space_pos=None, event_type=None):NEWLINE response = RESPONSE_CHAINNEWLINE if event_type == "leftdown":NEWLINE self.scene.tool_active = TrueNEWLINE self.p1 = complex(space_pos[0], space_pos[1])NEWLINE response = RESPONSE_CONSUMENEWLINE elif event_type == "move":NEWLINE self.p2 = complex(space_pos[0], space_pos[1])NEWLINE self.scene.request_refresh()NEWLINE response = RESPONSE_CONSUMENEWLINE elif event_type == "leftup":NEWLINE self.scene.tool_active = FalseNEWLINE try:NEWLINE if self.p1 is None:NEWLINE returnNEWLINE self.p2 = complex(space_pos[0], space_pos[1])NEWLINE x0 = min(self.p1.real, self.p2.real)NEWLINE y0 = min(self.p1.imag, self.p2.imag)NEWLINE x1 = max(self.p1.real, self.p2.real)NEWLINE y1 = max(self.p1.imag, self.p2.imag)NEWLINE ellipse = Ellipse(NEWLINE (x1 + x0) / 2.0,NEWLINE (y1 + y0) / 2.0,NEWLINE abs(x0 - x1) / 2,NEWLINE abs(y0 - y1) / 2,NEWLINE stroke="blue",NEWLINE stroke_width=1000,NEWLINE )NEWLINE if not ellipse.is_degenerate():NEWLINE elements = self.scene.context.elementsNEWLINE node = elements.elem_branch.add(shape=ellipse, type="elem ellipse")NEWLINE elements.classify([node])NEWLINE self.p1 = NoneNEWLINE self.p2 = NoneNEWLINE except IndexError:NEWLINE passNEWLINE self.scene.request_refresh()NEWLINE response = RESPONSE_ABORTNEWLINE elif event_type == "lost":NEWLINE self.scene.tool_active = FalseNEWLINE return responseNEWLINE '''NEWLINEData structure of the input .npz:NEWLINEthe data is save in python dictionary format with keys: 'acs', 'ep_rets', 'rews', 'obs'NEWLINEthe values of each item is a list storing the expert trajectory sequentiallyNEWLINEa transition can be: (data['obs'][t], data['acs'][t], data['obs'][t+1]) and get reward data['rews'][t]NEWLINE'''NEWLINENEWLINEfrom baselines import loggerNEWLINEimport numpy as npNEWLINENEWLINENEWLINEclass Dset(object):NEWLINE def __init__(self, inputs, labels, randomize):NEWLINE self.inputs = inputsNEWLINE self.labels = labelsNEWLINE assert len(self.inputs) == len(self.labels)NEWLINE self.randomize = randomizeNEWLINE self.num_pairs = len(inputs)NEWLINE self.init_pointer()NEWLINENEWLINE def init_pointer(self):NEWLINE self.pointer = 0NEWLINE if self.randomize:NEWLINE idx = np.arange(self.num_pairs)NEWLINE np.random.shuffle(idx)NEWLINE self.inputs = self.inputs[idx, :]NEWLINE self.labels = self.labels[idx, :]NEWLINENEWLINE def get_next_batch(self, batch_size):NEWLINE # if batch_size is negative -> return allNEWLINE if batch_size < 0:NEWLINE return self.inputs, self.labelsNEWLINE if self.pointer + batch_size >= self.num_pairs:NEWLINE self.init_pointer()NEWLINE end = self.pointer + batch_sizeNEWLINE inputs = self.inputs[self.pointer:end, :]NEWLINE labels = self.labels[self.pointer:end, :]NEWLINE self.pointer = endNEWLINE return inputs, labelsNEWLINENEWLINENEWLINEclass Mujoco_Dset(object):NEWLINE def __init__(self, expert_path, gen_f, train_fraction=0.7, traj_limitation=-1, randomize=True):NEWLINE if type(expert_path) is str:NEWLINE expert_path = [expert_path]NEWLINE self.gen_f = gen_fNEWLINE traj_data = np.load(expert_path.pop(), allow_pickle=True)NEWLINE traj_data = traj_data[()]NEWLINE while len(expert_path) and (traj_limitation < 0 or len(traj_data['obs']) < traj_limitation):NEWLINE next_f = expert_path.pop()NEWLINE try:NEWLINE next_data = np.load(next_f, allow_pickle=True)NEWLINE next_data = next_data[()]NEWLINE for key in traj_data:NEWLINE traj_data[key].extend(next_data[key])NEWLINE except Exception as e:NEWLINE logger.log('Could not load pickled dataset from {0}'.format(next_f))NEWLINE if traj_limitation < 0:NEWLINE traj_limitation = len(traj_data['obs'])NEWLINE obs = np.array(traj_data['obs'][:traj_limitation])NEWLINE acs = np.array(traj_data['acs'][:traj_limitation])NEWLINENEWLINE # obs, acs: shape (N, L, ) + S where N = # episodes, L = episode lengthNEWLINE # and S is the environment observation/action space.NEWLINE # Flatten to (N * L, prod(S))NEWLINE if len(obs.shape) > 2:NEWLINE self.obs = np.reshape(obs, [-1, np.prod(obs.shape[2:])])NEWLINE self.acs = np.reshape(acs, [-1, np.prod(acs.shape[2:])])NEWLINE else:NEWLINE self.obs = np.vstack(obs)NEWLINE self.acs = np.vstack(acs)NEWLINENEWLINE self.rets = traj_data['ep_rets'][:traj_limitation]NEWLINE self.avg_ret = np.sum([np.sum(r) for r in self.rets])/len(self.rets)NEWLINE self.std_ret = np.std(np.array([np.sum(r) for r in self.rets]))NEWLINE if len(self.acs) > 2:NEWLINE self.acs = np.squeeze(self.acs)NEWLINE assert len(self.obs) == len(self.acs)NEWLINE self.num_traj = min(traj_limitation, len(traj_data['obs']))NEWLINE self.num_transition = len(self.obs)NEWLINE self.randomize = randomizeNEWLINE self.dset = Dset(self.obs, self.acs, self.randomize)NEWLINE # for behavior cloningNEWLINE self.train_set = Dset(self.obs[:int(self.num_transition*train_fraction), :],NEWLINE self.acs[:int(self.num_transition*train_fraction), :],NEWLINE self.randomize)NEWLINE self.val_set = Dset(self.obs[int(self.num_transition*train_fraction):, :],NEWLINE self.acs[int(self.num_transition*train_fraction):, :],NEWLINE self.randomize)NEWLINE self.log_info()NEWLINENEWLINE def log_info(self):NEWLINE logger.log("Total trajectories: %d" % self.num_traj)NEWLINE logger.log("Total transitions: %d" % self.num_transition)NEWLINE logger.log("Average returns: %f" % self.avg_ret)NEWLINE logger.log("Std for returns: %f" % self.std_ret)NEWLINENEWLINE def get_next_batch(self, batch_size, split=None):NEWLINE if split is None:NEWLINE return self.dset.get_next_batch(batch_size)NEWLINE elif split == 'train':NEWLINE return self.train_set.get_next_batch(batch_size)NEWLINE elif split == 'val':NEWLINE return self.val_set.get_next_batch(batch_size)NEWLINE else:NEWLINE raise NotImplementedErrorNEWLINENEWLINE def plot(self):NEWLINE import matplotlib.pyplot as pltNEWLINE plt.hist(self.rets)NEWLINE plt.savefig("histogram_rets.png")NEWLINE plt.close()NEWLINENEWLINENEWLINEdef test(expert_path, traj_limitation, plot):NEWLINE dset = Mujoco_Dset(expert_path, traj_limitation=traj_limitation)NEWLINE if plot:NEWLINE dset.plot()NEWLINENEWLINEif __name__ == '__main__':NEWLINE import argparseNEWLINE parser = argparse.ArgumentParser()NEWLINE parser.add_argument("--expert_path", type=str, default="../data/deterministic.trpo.Hopper.0.00.npz")NEWLINE parser.add_argument("--traj_limitation", type=int, default=None)NEWLINE parser.add_argument("--plot", type=bool, default=False)NEWLINE args = parser.parse_args()NEWLINE test(args.expert_path, args.traj_limitation, args.plot)NEWLINE """numpy.distutils.fcompilerNEWLINENEWLINEContains FCompiler, an abstract base class that defines the interfaceNEWLINEfor the numpy.distutils Fortran compiler abstraction model.NEWLINENEWLINETerminology:NEWLINENEWLINETo be consistent, where the term 'executable' is used, it means the singleNEWLINEfile, like 'gcc', that is executed, and should be a string. In contrast,NEWLINE'command' means the entire command line, like ['gcc', '-c', 'file.c'], andNEWLINEshould be a list.NEWLINENEWLINEBut note that FCompiler.executables is actually a dictionary of commands.NEWLINENEWLINE"""NEWLINEfrom __future__ import division, absolute_import, print_functionNEWLINENEWLINE__all__ = ['FCompiler', 'new_fcompiler', 'show_fcompilers',NEWLINE 'dummy_fortran_file']NEWLINENEWLINEimport osNEWLINEimport sysNEWLINEimport reNEWLINEimport typesNEWLINEtry:NEWLINE setNEWLINEexcept NameError:NEWLINE from sets import Set as setNEWLINENEWLINEfrom numpy.compat import open_latin1NEWLINENEWLINEfrom distutils.sysconfig import get_python_libNEWLINEfrom distutils.fancy_getopt import FancyGetoptNEWLINEfrom distutils.errors import DistutilsModuleError, \NEWLINE DistutilsExecError, CompileError, LinkError, DistutilsPlatformErrorNEWLINEfrom distutils.util import split_quoted, strtoboolNEWLINENEWLINEfrom numpy.distutils.ccompiler import CCompiler, gen_lib_optionsNEWLINEfrom numpy.distutils import logNEWLINEfrom numpy.distutils.misc_util import is_string, all_strings, is_sequence, \NEWLINE make_temp_file, get_shared_lib_extensionNEWLINEfrom numpy.distutils.environment import EnvironmentConfigNEWLINEfrom numpy.distutils.exec_command import find_executableNEWLINEfrom numpy.distutils.compat import get_exceptionNEWLINENEWLINE__metaclass__ = typeNEWLINENEWLINEclass CompilerNotFound(Exception):NEWLINE passNEWLINENEWLINEdef flaglist(s):NEWLINE if is_string(s):NEWLINE return split_quoted(s)NEWLINE else:NEWLINE return sNEWLINENEWLINEdef str2bool(s):NEWLINE if is_string(s):NEWLINE return strtobool(s)NEWLINE return bool(s)NEWLINENEWLINEdef is_sequence_of_strings(seq):NEWLINE return is_sequence(seq) and all_strings(seq)NEWLINENEWLINEclass FCompiler(CCompiler):NEWLINE """Abstract base class to define the interface that must be implementedNEWLINE by real Fortran compiler classes.NEWLINENEWLINE Methods that subclasses may redefine:NEWLINENEWLINE update_executables(), find_executables(), get_version()NEWLINE get_flags(), get_flags_opt(), get_flags_arch(), get_flags_debug()NEWLINE get_flags_f77(), get_flags_opt_f77(), get_flags_arch_f77(),NEWLINE get_flags_debug_f77(), get_flags_f90(), get_flags_opt_f90(),NEWLINE get_flags_arch_f90(), get_flags_debug_f90(),NEWLINE get_flags_fix(), get_flags_linker_so()NEWLINENEWLINE DON'T call these methods (except get_version) afterNEWLINE constructing a compiler instance or inside any other method.NEWLINE All methods, except update_executables() and find_executables(),NEWLINE may call the get_version() method.NEWLINENEWLINE After constructing a compiler instance, always call customize(dist=None)NEWLINE method that finalizes compiler construction and makes the followingNEWLINE attributes available:NEWLINE compiler_f77NEWLINE compiler_f90NEWLINE compiler_fixNEWLINE linker_soNEWLINE archiverNEWLINE ranlibNEWLINE librariesNEWLINE library_dirsNEWLINE """NEWLINENEWLINE # These are the environment variables and distutils keys used.NEWLINE # Each configuration descripition isNEWLINE # (, , , )NEWLINE # The hook names are handled by the self._environment_hook method.NEWLINE # - names starting with 'self.' call methods in this classNEWLINE # - names starting with 'exe.' return the key in the executables dictNEWLINE # - names like 'flags.YYY' return self.get_flag_YYY()NEWLINE # convert is either None or a function to convert a string to theNEWLINE # appropiate type used.NEWLINENEWLINE distutils_vars = EnvironmentConfig(NEWLINE distutils_section='config_fc',NEWLINE noopt = (None, None, 'noopt', str2bool),NEWLINE noarch = (None, None, 'noarch', str2bool),NEWLINE debug = (None, None, 'debug', str2bool),NEWLINE verbose = (None, None, 'verbose', str2bool),NEWLINE )NEWLINENEWLINE command_vars = EnvironmentConfig(NEWLINE distutils_section='config_fc',NEWLINE compiler_f77 = ('exe.compiler_f77', 'F77', 'f77exec', None),NEWLINE compiler_f90 = ('exe.compiler_f90', 'F90', 'f90exec', None),NEWLINE compiler_fix = ('exe.compiler_fix', 'F90', 'f90exec', None),NEWLINE version_cmd = ('exe.version_cmd', None, None, None),NEWLINE linker_so = ('exe.linker_so', 'LDSHARED', 'ldshared', None),NEWLINE linker_exe = ('exe.linker_exe', 'LD', 'ld', None),NEWLINE archiver = (None, 'AR', 'ar', None),NEWLINE ranlib = (None, 'RANLIB', 'ranlib', None),NEWLINE )NEWLINENEWLINE flag_vars = EnvironmentConfig(NEWLINE distutils_section='config_fc',NEWLINE f77 = ('flags.f77', 'F77FLAGS', 'f77flags', flaglist),NEWLINE f90 = ('flags.f90', 'F90FLAGS', 'f90flags', flaglist),NEWLINE free = ('flags.free', 'FREEFLAGS', 'freeflags', flaglist),NEWLINE fix = ('flags.fix', None, None, flaglist),NEWLINE opt = ('flags.opt', 'FOPT', 'opt', flaglist),NEWLINE opt_f77 = ('flags.opt_f77', None, None, flaglist),NEWLINE opt_f90 = ('flags.opt_f90', None, None, flaglist),NEWLINE arch = ('flags.arch', 'FARCH', 'arch', flaglist),NEWLINE arch_f77 = ('flags.arch_f77', None, None, flaglist),NEWLINE arch_f90 = ('flags.arch_f90', None, None, flaglist),NEWLINE debug = ('flags.debug', 'FDEBUG', 'fdebug', flaglist),NEWLINE debug_f77 = ('flags.debug_f77', None, None, flaglist),NEWLINE debug_f90 = ('flags.debug_f90', None, None, flaglist),NEWLINE flags = ('self.get_flags', 'FFLAGS', 'fflags', flaglist),NEWLINE linker_so = ('flags.linker_so', 'LDFLAGS', 'ldflags', flaglist),NEWLINE linker_exe = ('flags.linker_exe', 'LDFLAGS', 'ldflags', flaglist),NEWLINE ar = ('flags.ar', 'ARFLAGS', 'arflags', flaglist),NEWLINE )NEWLINENEWLINE language_map = {'.f': 'f77',NEWLINE '.for': 'f77',NEWLINE '.F': 'f77', # XXX: needs preprocessorNEWLINE '.ftn': 'f77',NEWLINE '.f77': 'f77',NEWLINE '.f90': 'f90',NEWLINE '.F90': 'f90', # XXX: needs preprocessorNEWLINE '.f95': 'f90',NEWLINE }NEWLINE language_order = ['f90', 'f77']NEWLINENEWLINENEWLINE # These will be set by the subclassNEWLINENEWLINE compiler_type = NoneNEWLINE compiler_aliases = ()NEWLINE version_pattern = NoneNEWLINENEWLINE possible_executables = []NEWLINE executables = {NEWLINE 'version_cmd': ["f77", "-v"],NEWLINE 'compiler_f77': ["f77"],NEWLINE 'compiler_f90': ["f90"],NEWLINE 'compiler_fix': ["f90", "-fixed"],NEWLINE 'linker_so': ["f90", "-shared"],NEWLINE 'linker_exe': ["f90"],NEWLINE 'archiver': ["ar", "-cr"],NEWLINE 'ranlib': None,NEWLINE }NEWLINENEWLINE # If compiler does not support compiling Fortran 90 then it canNEWLINE # suggest using another compiler. For example, gnu would suggestNEWLINE # gnu95 compiler type when there are F90 sources.NEWLINE suggested_f90_compiler = NoneNEWLINENEWLINE compile_switch = "-c"NEWLINE object_switch = "-o " # Ending space matters! It will be strippedNEWLINE # but if it is missing then object_switchNEWLINE # will be prefixed to object file name byNEWLINE # string concatenation.NEWLINE library_switch = "-o " # Ditto!NEWLINENEWLINE # Switch to specify where module files are created and searchedNEWLINE # for USE statement. Normally it is a string and also here endingNEWLINE # space matters. See above.NEWLINE module_dir_switch = NoneNEWLINENEWLINE # Switch to specify where module files are searched for USE statement.NEWLINE module_include_switch = '-I'NEWLINENEWLINE pic_flags = [] # Flags to create position-independent codeNEWLINENEWLINE src_extensions = ['.for', '.ftn', '.f77', '.f', '.f90', '.f95', '.F', '.F90']NEWLINE obj_extension = ".o"NEWLINENEWLINE shared_lib_extension = get_shared_lib_extension()NEWLINE static_lib_extension = ".a" # or .libNEWLINE static_lib_format = "lib%s%s" # or %s%sNEWLINE shared_lib_format = "%s%s"NEWLINE exe_extension = ""NEWLINENEWLINE _exe_cache = {}NEWLINENEWLINE _executable_keys = ['version_cmd', 'compiler_f77', 'compiler_f90',NEWLINE 'compiler_fix', 'linker_so', 'linker_exe', 'archiver',NEWLINE 'ranlib']NEWLINENEWLINE # This will be set by new_fcompiler when called inNEWLINE # command/{build_ext.py, build_clib.py, config.py} files.NEWLINE c_compiler = NoneNEWLINENEWLINE # extra_{f77,f90}_compile_args are set by build_ext.build_extension methodNEWLINE extra_f77_compile_args = []NEWLINE extra_f90_compile_args = []NEWLINENEWLINE def __init__(self, *args, **kw):NEWLINE CCompiler.__init__(self, *args, **kw)NEWLINE self.distutils_vars = self.distutils_vars.clone(self._environment_hook)NEWLINE self.command_vars = self.command_vars.clone(self._environment_hook)NEWLINE self.flag_vars = self.flag_vars.clone(self._environment_hook)NEWLINE self.executables = self.executables.copy()NEWLINE for e in self._executable_keys:NEWLINE if e not in self.executables:NEWLINE self.executables[e] = NoneNEWLINENEWLINE # Some methods depend on .customize() being called first, soNEWLINE # this keeps track of whether that's happened yet.NEWLINE self._is_customised = FalseNEWLINENEWLINE def __copy__(self):NEWLINE obj = self.__new__(self.__class__)NEWLINE obj.__dict__.update(self.__dict__)NEWLINE obj.distutils_vars = obj.distutils_vars.clone(obj._environment_hook)NEWLINE obj.command_vars = obj.command_vars.clone(obj._environment_hook)NEWLINE obj.flag_vars = obj.flag_vars.clone(obj._environment_hook)NEWLINE obj.executables = obj.executables.copy()NEWLINE return objNEWLINENEWLINE def copy(self):NEWLINE return self.__copy__()NEWLINENEWLINE # Use properties for the attributes used by CCompiler. Setting themNEWLINE # as attributes from the self.executables dictionary is error-prone,NEWLINE # so we get them from there each time.NEWLINE def _command_property(key):NEWLINE def fget(self):NEWLINE assert self._is_customisedNEWLINE return self.executables[key]NEWLINE return property(fget=fget)NEWLINE version_cmd = _command_property('version_cmd')NEWLINE compiler_f77 = _command_property('compiler_f77')NEWLINE compiler_f90 = _command_property('compiler_f90')NEWLINE compiler_fix = _command_property('compiler_fix')NEWLINE linker_so = _command_property('linker_so')NEWLINE linker_exe = _command_property('linker_exe')NEWLINE archiver = _command_property('archiver')NEWLINE ranlib = _command_property('ranlib')NEWLINENEWLINE # Make our terminology consistent.NEWLINE def set_executable(self, key, value):NEWLINE self.set_command(key, value)NEWLINENEWLINE def set_commands(self, **kw):NEWLINE for k, v in kw.items():NEWLINE self.set_command(k, v)NEWLINENEWLINE def set_command(self, key, value):NEWLINE if not key in self._executable_keys:NEWLINE raise ValueError(NEWLINE "unknown executable '%s' for class %s" %NEWLINE (key, self.__class__.__name__))NEWLINE if is_string(value):NEWLINE value = split_quoted(value)NEWLINE assert value is None or is_sequence_of_strings(value[1:]), (key, value)NEWLINE self.executables[key] = valueNEWLINENEWLINE ######################################################################NEWLINE ## Methods that subclasses may redefine. But don't call these methods!NEWLINE ## They are private to FCompiler class and may return unexpectedNEWLINE ## results if used elsewhere. So, you have been warned..NEWLINENEWLINE def find_executables(self):NEWLINE """Go through the self.executables dictionary, and attempt toNEWLINE find and assign appropiate executables.NEWLINENEWLINE Executable names are looked for in the environment (environmentNEWLINE variables, the distutils.cfg, and command line), the 0th-element ofNEWLINE the command list, and the self.possible_executables list.NEWLINENEWLINE Also, if the 0th element is "" or "", the Fortran 77NEWLINE or the Fortran 90 compiler executable is used, unless overriddenNEWLINE by an environment setting.NEWLINENEWLINE Subclasses should call this if overriden.NEWLINE """NEWLINE assert self._is_customisedNEWLINE exe_cache = self._exe_cacheNEWLINE def cached_find_executable(exe):NEWLINE if exe in exe_cache:NEWLINE return exe_cache[exe]NEWLINE fc_exe = find_executable(exe)NEWLINE exe_cache[exe] = exe_cache[fc_exe] = fc_exeNEWLINE return fc_exeNEWLINE def verify_command_form(name, value):NEWLINE if value is not None and not is_sequence_of_strings(value):NEWLINE raise ValueError(NEWLINE "%s value %r is invalid in class %s" %NEWLINE (name, value, self.__class__.__name__))NEWLINE def set_exe(exe_key, f77=None, f90=None):NEWLINE cmd = self.executables.get(exe_key, None)NEWLINE if not cmd:NEWLINE return NoneNEWLINE # Note that we get cmd[0] here if the environment doesn'tNEWLINE # have anything setNEWLINE exe_from_environ = getattr(self.command_vars, exe_key)NEWLINE if not exe_from_environ:NEWLINE possibles = [f90, f77] + self.possible_executablesNEWLINE else:NEWLINE possibles = [exe_from_environ] + self.possible_executablesNEWLINENEWLINE seen = set()NEWLINE unique_possibles = []NEWLINE for e in possibles:NEWLINE if e == '':NEWLINE e = f77NEWLINE elif e == '':NEWLINE e = f90NEWLINE if not e or e in seen:NEWLINE continueNEWLINE seen.add(e)NEWLINE unique_possibles.append(e)NEWLINENEWLINE for exe in unique_possibles:NEWLINE fc_exe = cached_find_executable(exe)NEWLINE if fc_exe:NEWLINE cmd[0] = fc_exeNEWLINE return fc_exeNEWLINE self.set_command(exe_key, None)NEWLINE return NoneNEWLINENEWLINE ctype = self.compiler_typeNEWLINE f90 = set_exe('compiler_f90')NEWLINE if not f90:NEWLINE f77 = set_exe('compiler_f77')NEWLINE if f77:NEWLINE log.warn('%s: no Fortran 90 compiler found' % ctype)NEWLINE else:NEWLINE raise CompilerNotFound('%s: f90 nor f77' % ctype)NEWLINE else:NEWLINE f77 = set_exe('compiler_f77', f90=f90)NEWLINE if not f77:NEWLINE log.warn('%s: no Fortran 77 compiler found' % ctype)NEWLINE set_exe('compiler_fix', f90=f90)NEWLINENEWLINE set_exe('linker_so', f77=f77, f90=f90)NEWLINE set_exe('linker_exe', f77=f77, f90=f90)NEWLINE set_exe('version_cmd', f77=f77, f90=f90)NEWLINE set_exe('archiver')NEWLINE set_exe('ranlib')NEWLINENEWLINE def update_executables(elf):NEWLINE """Called at the beginning of customisation. Subclasses shouldNEWLINE override this if they need to set up the executables dictionary.NEWLINENEWLINE Note that self.find_executables() is run afterwards, so theNEWLINE self.executables dictionary values can contain or asNEWLINE the command, which will be replaced by the found F77 or F90NEWLINE compiler.NEWLINE """NEWLINE passNEWLINENEWLINE def get_flags(self):NEWLINE """List of flags common to all compiler types."""NEWLINE return [] + self.pic_flagsNEWLINENEWLINE def _get_command_flags(self, key):NEWLINE cmd = self.executables.get(key, None)NEWLINE if cmd is None:NEWLINE return []NEWLINE return cmd[1:]NEWLINENEWLINE def get_flags_f77(self):NEWLINE """List of Fortran 77 specific flags."""NEWLINE return self._get_command_flags('compiler_f77')NEWLINE def get_flags_f90(self):NEWLINE """List of Fortran 90 specific flags."""NEWLINE return self._get_command_flags('compiler_f90')NEWLINE def get_flags_free(self):NEWLINE """List of Fortran 90 free format specific flags."""NEWLINE return []NEWLINE def get_flags_fix(self):NEWLINE """List of Fortran 90 fixed format specific flags."""NEWLINE return self._get_command_flags('compiler_fix')NEWLINE def get_flags_linker_so(self):NEWLINE """List of linker flags to build a shared library."""NEWLINE return self._get_command_flags('linker_so')NEWLINE def get_flags_linker_exe(self):NEWLINE """List of linker flags to build an executable."""NEWLINE return self._get_command_flags('linker_exe')NEWLINE def get_flags_ar(self):NEWLINE """List of archiver flags. """NEWLINE return self._get_command_flags('archiver')NEWLINE def get_flags_opt(self):NEWLINE """List of architecture independent compiler flags."""NEWLINE return []NEWLINE def get_flags_arch(self):NEWLINE """List of architecture dependent compiler flags."""NEWLINE return []NEWLINE def get_flags_debug(self):NEWLINE """List of compiler flags to compile with debugging information."""NEWLINE return []NEWLINENEWLINE get_flags_opt_f77 = get_flags_opt_f90 = get_flags_optNEWLINE get_flags_arch_f77 = get_flags_arch_f90 = get_flags_archNEWLINE get_flags_debug_f77 = get_flags_debug_f90 = get_flags_debugNEWLINENEWLINE def get_libraries(self):NEWLINE """List of compiler libraries."""NEWLINE return self.libraries[:]NEWLINE def get_library_dirs(self):NEWLINE """List of compiler library directories."""NEWLINE return self.library_dirs[:]NEWLINENEWLINE def get_version(self, force=False, ok_status=[0]):NEWLINE assert self._is_customisedNEWLINE version = CCompiler.get_version(self, force=force, ok_status=ok_status)NEWLINE if version is None:NEWLINE raise CompilerNotFound()NEWLINE return versionNEWLINENEWLINE ############################################################NEWLINENEWLINE ## Public methods:NEWLINENEWLINE def customize(self, dist = None):NEWLINE """Customize Fortran compiler.NEWLINENEWLINE This method gets Fortran compiler specific information fromNEWLINE (i) class definition, (ii) environment, (iii) distutils configNEWLINE files, and (iv) command line (later overrides earlier).NEWLINENEWLINE This method should be always called after constructing aNEWLINE compiler instance. But not in __init__ because DistributionNEWLINE instance is needed for (iii) and (iv).NEWLINE """NEWLINE log.info('customize %s' % (self.__class__.__name__))NEWLINENEWLINE self._is_customised = TrueNEWLINENEWLINE self.distutils_vars.use_distribution(dist)NEWLINE self.command_vars.use_distribution(dist)NEWLINE self.flag_vars.use_distribution(dist)NEWLINENEWLINE self.update_executables()NEWLINENEWLINE # find_executables takes care of setting the compiler commands,NEWLINE # version_cmd, linker_so, linker_exe, ar, and ranlibNEWLINE self.find_executables()NEWLINENEWLINE noopt = self.distutils_vars.get('noopt', False)NEWLINE noarch = self.distutils_vars.get('noarch', noopt)NEWLINE debug = self.distutils_vars.get('debug', False)NEWLINENEWLINE f77 = self.command_vars.compiler_f77NEWLINE f90 = self.command_vars.compiler_f90NEWLINENEWLINE f77flags = []NEWLINE f90flags = []NEWLINE freeflags = []NEWLINE fixflags = []NEWLINENEWLINE if f77:NEWLINE f77flags = self.flag_vars.f77NEWLINE if f90:NEWLINE f90flags = self.flag_vars.f90NEWLINE freeflags = self.flag_vars.freeNEWLINE # XXX Assuming that free format is default for f90 compiler.NEWLINE fix = self.command_vars.compiler_fixNEWLINE if fix:NEWLINE fixflags = self.flag_vars.fix + f90flagsNEWLINENEWLINE oflags, aflags, dflags = [], [], []NEWLINE # examine get_flags__ for extra flagsNEWLINE # only add them if the method is different from get_flags_NEWLINE def get_flags(tag, flags):NEWLINE # note that self.flag_vars. calls self.get_flags_()NEWLINE flags.extend(getattr(self.flag_vars, tag))NEWLINE this_get = getattr(self, 'get_flags_' + tag)NEWLINE for name, c, flagvar in [('f77', f77, f77flags),NEWLINE ('f90', f90, f90flags),NEWLINE ('f90', fix, fixflags)]:NEWLINE t = '%s_%s' % (tag, name)NEWLINE if c and this_get is not getattr(self, 'get_flags_' + t):NEWLINE flagvar.extend(getattr(self.flag_vars, t))NEWLINE if not noopt:NEWLINE get_flags('opt', oflags)NEWLINE if not noarch:NEWLINE get_flags('arch', aflags)NEWLINE if debug:NEWLINE get_flags('debug', dflags)NEWLINENEWLINE fflags = self.flag_vars.flags + dflags + oflags + aflagsNEWLINENEWLINE if f77:NEWLINE self.set_commands(compiler_f77=[f77]+f77flags+fflags)NEWLINE if f90:NEWLINE self.set_commands(compiler_f90=[f90]+freeflags+f90flags+fflags)NEWLINE if fix:NEWLINE self.set_commands(compiler_fix=[fix]+fixflags+fflags)NEWLINENEWLINENEWLINE #XXX: Do we need LDSHARED->SOSHARED, LDFLAGS->SOFLAGSNEWLINE linker_so = self.linker_soNEWLINE if linker_so:NEWLINE linker_so_flags = self.flag_vars.linker_soNEWLINE if sys.platform.startswith('aix'):NEWLINE python_lib = get_python_lib(standard_lib=1)NEWLINE ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix')NEWLINE python_exp = os.path.join(python_lib, 'config', 'python.exp')NEWLINE linker_so = [ld_so_aix] + linker_so + ['-bI:'+python_exp]NEWLINE self.set_commands(linker_so=linker_so+linker_so_flags)NEWLINENEWLINE linker_exe = self.linker_exeNEWLINE if linker_exe:NEWLINE linker_exe_flags = self.flag_vars.linker_exeNEWLINE self.set_commands(linker_exe=linker_exe+linker_exe_flags)NEWLINENEWLINE ar = self.command_vars.archiverNEWLINE if ar:NEWLINE arflags = self.flag_vars.arNEWLINE self.set_commands(archiver=[ar]+arflags)NEWLINENEWLINE self.set_library_dirs(self.get_library_dirs())NEWLINE self.set_libraries(self.get_libraries())NEWLINENEWLINE def dump_properties(self):NEWLINE """Print out the attributes of a compiler instance."""NEWLINE props = []NEWLINE for key in list(self.executables.keys()) + \NEWLINE ['version', 'libraries', 'library_dirs',NEWLINE 'object_switch', 'compile_switch']:NEWLINE if hasattr(self, key):NEWLINE v = getattr(self, key)NEWLINE props.append((key, None, '= '+repr(v)))NEWLINE props.sort()NEWLINENEWLINE pretty_printer = FancyGetopt(props)NEWLINE for l in pretty_printer.generate_help("%s instance properties:" \NEWLINE % (self.__class__.__name__)):NEWLINE if l[:4]==' --':NEWLINE l = ' ' + l[4:]NEWLINE print(l)NEWLINENEWLINE ###################NEWLINENEWLINE def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):NEWLINE """Compile 'src' to product 'obj'."""NEWLINE src_flags = {}NEWLINE if is_f_file(src) and not has_f90_header(src):NEWLINE flavor = ':f77'NEWLINE compiler = self.compiler_f77NEWLINE src_flags = get_f77flags(src)NEWLINE extra_compile_args = self.extra_f77_compile_args or []NEWLINE elif is_free_format(src):NEWLINE flavor = ':f90'NEWLINE compiler = self.compiler_f90NEWLINE if compiler is None:NEWLINE raise DistutilsExecError('f90 not supported by %s needed for %s'\NEWLINE % (self.__class__.__name__, src))NEWLINE extra_compile_args = self.extra_f90_compile_args or []NEWLINE else:NEWLINE flavor = ':fix'NEWLINE compiler = self.compiler_fixNEWLINE if compiler is None:NEWLINE raise DistutilsExecError('f90 (fixed) not supported by %s needed for %s'\NEWLINE % (self.__class__.__name__, src))NEWLINE extra_compile_args = self.extra_f90_compile_args or []NEWLINE if self.object_switch[-1]==' ':NEWLINE o_args = [self.object_switch.strip(), obj]NEWLINE else:NEWLINE o_args = [self.object_switch.strip()+obj]NEWLINENEWLINE assert self.compile_switch.strip()NEWLINE s_args = [self.compile_switch, src]NEWLINENEWLINE if extra_compile_args:NEWLINE log.info('extra %s options: %r' \NEWLINE % (flavor[1:], ' '.join(extra_compile_args)))NEWLINENEWLINE extra_flags = src_flags.get(self.compiler_type, [])NEWLINE if extra_flags:NEWLINE log.info('using compile options from source: %r' \NEWLINE % ' '.join(extra_flags))NEWLINENEWLINE command = compiler + cc_args + extra_flags + s_args + o_args \NEWLINE + extra_postargs + extra_compile_argsNEWLINENEWLINE display = '%s: %s' % (os.path.basename(compiler[0]) + flavor,NEWLINE src)NEWLINE try:NEWLINE self.spawn(command, display=display)NEWLINE except DistutilsExecError:NEWLINE msg = str(get_exception())NEWLINE raise CompileError(msg)NEWLINENEWLINE def module_options(self, module_dirs, module_build_dir):NEWLINE options = []NEWLINE if self.module_dir_switch is not None:NEWLINE if self.module_dir_switch[-1]==' ':NEWLINE options.extend([self.module_dir_switch.strip(), module_build_dir])NEWLINE else:NEWLINE options.append(self.module_dir_switch.strip()+module_build_dir)NEWLINE else:NEWLINE print('XXX: module_build_dir=%r option ignored' % (module_build_dir))NEWLINE print('XXX: Fix module_dir_switch for ', self.__class__.__name__)NEWLINE if self.module_include_switch is not None:NEWLINE for d in [module_build_dir]+module_dirs:NEWLINE options.append('%s%s' % (self.module_include_switch, d))NEWLINE else:NEWLINE print('XXX: module_dirs=%r option ignored' % (module_dirs))NEWLINE print('XXX: Fix module_include_switch for ', self.__class__.__name__)NEWLINE return optionsNEWLINENEWLINE def library_option(self, lib):NEWLINE return "-l" + libNEWLINE def library_dir_option(self, dir):NEWLINE return "-L" + dirNEWLINENEWLINE def link(self, target_desc, objects,NEWLINE output_filename, output_dir=None, libraries=None,NEWLINE library_dirs=None, runtime_library_dirs=None,NEWLINE export_symbols=None, debug=0, extra_preargs=None,NEWLINE extra_postargs=None, build_temp=None, target_lang=None):NEWLINE objects, output_dir = self._fix_object_args(objects, output_dir)NEWLINE libraries, library_dirs, runtime_library_dirs = \NEWLINE self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)NEWLINENEWLINE lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs,NEWLINE libraries)NEWLINE if is_string(output_dir):NEWLINE output_filename = os.path.join(output_dir, output_filename)NEWLINE elif output_dir is not None:NEWLINE raise TypeError("'output_dir' must be a string or None")NEWLINENEWLINE if self._need_link(objects, output_filename):NEWLINE if self.library_switch[-1]==' ':NEWLINE o_args = [self.library_switch.strip(), output_filename]NEWLINE else:NEWLINE o_args = [self.library_switch.strip()+output_filename]NEWLINENEWLINE if is_string(self.objects):NEWLINE ld_args = objects + [self.objects]NEWLINE else:NEWLINE ld_args = objects + self.objectsNEWLINE ld_args = ld_args + lib_opts + o_argsNEWLINE if debug:NEWLINE ld_args[:0] = ['-g']NEWLINE if extra_preargs:NEWLINE ld_args[:0] = extra_preargsNEWLINE if extra_postargs:NEWLINE ld_args.extend(extra_postargs)NEWLINE self.mkpath(os.path.dirname(output_filename))NEWLINE if target_desc == CCompiler.EXECUTABLE:NEWLINE linker = self.linker_exe[:]NEWLINE else:NEWLINE linker = self.linker_so[:]NEWLINE command = linker + ld_argsNEWLINE try:NEWLINE self.spawn(command)NEWLINE except DistutilsExecError:NEWLINE msg = str(get_exception())NEWLINE raise LinkError(msg)NEWLINE else:NEWLINE log.debug("skipping %s (up-to-date)", output_filename)NEWLINENEWLINE def _environment_hook(self, name, hook_name):NEWLINE if hook_name is None:NEWLINE return NoneNEWLINE if is_string(hook_name):NEWLINE if hook_name.startswith('self.'):NEWLINE hook_name = hook_name[5:]NEWLINE hook = getattr(self, hook_name)NEWLINE return hook()NEWLINE elif hook_name.startswith('exe.'):NEWLINE hook_name = hook_name[4:]NEWLINE var = self.executables[hook_name]NEWLINE if var:NEWLINE return var[0]NEWLINE else:NEWLINE return NoneNEWLINE elif hook_name.startswith('flags.'):NEWLINE hook_name = hook_name[6:]NEWLINE hook = getattr(self, 'get_flags_' + hook_name)NEWLINE return hook()NEWLINE else:NEWLINE return hook_name()NEWLINENEWLINE ## class FCompilerNEWLINENEWLINE_default_compilers = (NEWLINE # sys.platform mappingsNEWLINE ('win32', ('gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95',NEWLINE 'intelvem', 'intelem')),NEWLINE ('cygwin.*', ('gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95')),NEWLINE ('linux.*', ('gnu95', 'intel', 'lahey', 'pg', 'absoft', 'nag', 'vast', 'compaq',NEWLINE 'intele', 'intelem', 'gnu', 'g95', 'pathf95')),NEWLINE ('darwin.*', ('gnu95', 'nag', 'absoft', 'ibm', 'intel', 'gnu', 'g95', 'pg')),NEWLINE ('sunos.*', ('sun', 'gnu', 'gnu95', 'g95')),NEWLINE ('irix.*', ('mips', 'gnu', 'gnu95',)),NEWLINE ('aix.*', ('ibm', 'gnu', 'gnu95',)),NEWLINE # os.name mappingsNEWLINE ('posix', ('gnu', 'gnu95',)),NEWLINE ('nt', ('gnu', 'gnu95',)),NEWLINE ('mac', ('gnu95', 'gnu', 'pg')),NEWLINE )NEWLINENEWLINEfcompiler_class = NoneNEWLINEfcompiler_aliases = NoneNEWLINENEWLINEdef load_all_fcompiler_classes():NEWLINE """Cache all the FCompiler classes found in modules in theNEWLINE numpy.distutils.fcompiler package.NEWLINE """NEWLINE from glob import globNEWLINE global fcompiler_class, fcompiler_aliasesNEWLINE if fcompiler_class is not None:NEWLINE returnNEWLINE pys = os.path.join(os.path.dirname(__file__), '*.py')NEWLINE fcompiler_class = {}NEWLINE fcompiler_aliases = {}NEWLINE for fname in glob(pys):NEWLINE module_name, ext = os.path.splitext(os.path.basename(fname))NEWLINE module_name = 'numpy.distutils.fcompiler.' + module_nameNEWLINE __import__ (module_name)NEWLINE module = sys.modules[module_name]NEWLINE if hasattr(module, 'compilers'):NEWLINE for cname in module.compilers:NEWLINE klass = getattr(module, cname)NEWLINE desc = (klass.compiler_type, klass, klass.description)NEWLINE fcompiler_class[klass.compiler_type] = descNEWLINE for alias in klass.compiler_aliases:NEWLINE if alias in fcompiler_aliases:NEWLINE raise ValueError("alias %r defined for both %s and %s"NEWLINE % (alias, klass.__name__,NEWLINE fcompiler_aliases[alias][1].__name__))NEWLINE fcompiler_aliases[alias] = descNEWLINENEWLINEdef _find_existing_fcompiler(compiler_types,NEWLINE osname=None, platform=None,NEWLINE requiref90=False,NEWLINE c_compiler=None):NEWLINE from numpy.distutils.core import get_distributionNEWLINE dist = get_distribution(always=True)NEWLINE for compiler_type in compiler_types:NEWLINE v = NoneNEWLINE try:NEWLINE c = new_fcompiler(plat=platform, compiler=compiler_type,NEWLINE c_compiler=c_compiler)NEWLINE c.customize(dist)NEWLINE v = c.get_version()NEWLINE if requiref90 and c.compiler_f90 is None:NEWLINE v = NoneNEWLINE new_compiler = c.suggested_f90_compilerNEWLINE if new_compiler:NEWLINE log.warn('Trying %r compiler as suggested by %r 'NEWLINE 'compiler for f90 support.' % (compiler_type,NEWLINE new_compiler))NEWLINE c = new_fcompiler(plat=platform, compiler=new_compiler,NEWLINE c_compiler=c_compiler)NEWLINE c.customize(dist)NEWLINE v = c.get_version()NEWLINE if v is not None:NEWLINE compiler_type = new_compilerNEWLINE if requiref90 and c.compiler_f90 is None:NEWLINE raise ValueError('%s does not support compiling f90 codes, 'NEWLINE 'skipping.' % (c.__class__.__name__))NEWLINE except DistutilsModuleError:NEWLINE log.debug("_find_existing_fcompiler: compiler_type='%s' raised DistutilsModuleError", compiler_type)NEWLINE except CompilerNotFound:NEWLINE log.debug("_find_existing_fcompiler: compiler_type='%s' not found", compiler_type)NEWLINE if v is not None:NEWLINE return compiler_typeNEWLINE return NoneNEWLINENEWLINEdef available_fcompilers_for_platform(osname=None, platform=None):NEWLINE if osname is None:NEWLINE osname = os.nameNEWLINE if platform is None:NEWLINE platform = sys.platformNEWLINE matching_compiler_types = []NEWLINE for pattern, compiler_type in _default_compilers:NEWLINE if re.match(pattern, platform) or re.match(pattern, osname):NEWLINE for ct in compiler_type:NEWLINE if ct not in matching_compiler_types:NEWLINE matching_compiler_types.append(ct)NEWLINE if not matching_compiler_types:NEWLINE matching_compiler_types.append('gnu')NEWLINE return matching_compiler_typesNEWLINENEWLINEdef get_default_fcompiler(osname=None, platform=None, requiref90=False,NEWLINE c_compiler=None):NEWLINE """Determine the default Fortran compiler to use for the givenNEWLINE platform."""NEWLINE matching_compiler_types = available_fcompilers_for_platform(osname,NEWLINE platform)NEWLINE compiler_type = _find_existing_fcompiler(matching_compiler_types,NEWLINE osname=osname,NEWLINE platform=platform,NEWLINE requiref90=requiref90,NEWLINE c_compiler=c_compiler)NEWLINE return compiler_typeNEWLINENEWLINE# Flag to avoid rechecking for Fortran compiler every timeNEWLINEfailed_fcompiler = FalseNEWLINENEWLINEdef new_fcompiler(plat=None,NEWLINE compiler=None,NEWLINE verbose=0,NEWLINE dry_run=0,NEWLINE force=0,NEWLINE requiref90=False,NEWLINE c_compiler = None):NEWLINE """Generate an instance of some FCompiler subclass for the suppliedNEWLINE platform/compiler combination.NEWLINE """NEWLINE global failed_fcompilerNEWLINE if failed_fcompiler:NEWLINE return NoneNEWLINENEWLINE load_all_fcompiler_classes()NEWLINE if plat is None:NEWLINE plat = os.nameNEWLINE if compiler is None:NEWLINE compiler = get_default_fcompiler(plat, requiref90=requiref90,NEWLINE c_compiler=c_compiler)NEWLINE if compiler in fcompiler_class:NEWLINE module_name, klass, long_description = fcompiler_class[compiler]NEWLINE elif compiler in fcompiler_aliases:NEWLINE module_name, klass, long_description = fcompiler_aliases[compiler]NEWLINE else:NEWLINE msg = "don't know how to compile Fortran code on platform '%s'" % platNEWLINE if compiler is not None:NEWLINE msg = msg + " with '%s' compiler." % compilerNEWLINE msg = msg + " Supported compilers are: %s)" \NEWLINE % (','.join(fcompiler_class.keys()))NEWLINE log.warn(msg)NEWLINE failed_fcompiler = TrueNEWLINE return NoneNEWLINENEWLINE compiler = klass(verbose=verbose, dry_run=dry_run, force=force)NEWLINE compiler.c_compiler = c_compilerNEWLINE return compilerNEWLINENEWLINEdef show_fcompilers(dist=None):NEWLINE """Print list of available compilers (used by the "--help-fcompiler"NEWLINE option to "config_fc").NEWLINE """NEWLINE if dist is None:NEWLINE from distutils.dist import DistributionNEWLINE from numpy.distutils.command.config_compiler import config_fcNEWLINE dist = Distribution()NEWLINE dist.script_name = os.path.basename(sys.argv[0])NEWLINE dist.script_args = ['config_fc'] + sys.argv[1:]NEWLINE try:NEWLINE dist.script_args.remove('--help-fcompiler')NEWLINE except ValueError:NEWLINE passNEWLINE dist.cmdclass['config_fc'] = config_fcNEWLINE dist.parse_config_files()NEWLINE dist.parse_command_line()NEWLINE compilers = []NEWLINE compilers_na = []NEWLINE compilers_ni = []NEWLINE if not fcompiler_class:NEWLINE load_all_fcompiler_classes()NEWLINE platform_compilers = available_fcompilers_for_platform()NEWLINE for compiler in platform_compilers:NEWLINE v = NoneNEWLINE log.set_verbosity(-2)NEWLINE try:NEWLINE c = new_fcompiler(compiler=compiler, verbose=dist.verbose)NEWLINE c.customize(dist)NEWLINE v = c.get_version()NEWLINE except (DistutilsModuleError, CompilerNotFound):NEWLINE e = get_exception()NEWLINE log.debug("show_fcompilers: %s not found" % (compiler,))NEWLINE log.debug(repr(e))NEWLINENEWLINE if v is None:NEWLINE compilers_na.append(("fcompiler="+compiler, None,NEWLINE fcompiler_class[compiler][2]))NEWLINE else:NEWLINE c.dump_properties()NEWLINE compilers.append(("fcompiler="+compiler, None,NEWLINE fcompiler_class[compiler][2] + ' (%s)' % v))NEWLINENEWLINE compilers_ni = list(set(fcompiler_class.keys()) - set(platform_compilers))NEWLINE compilers_ni = [("fcompiler="+fc, None, fcompiler_class[fc][2])NEWLINE for fc in compilers_ni]NEWLINENEWLINE compilers.sort()NEWLINE compilers_na.sort()NEWLINE compilers_ni.sort()NEWLINE pretty_printer = FancyGetopt(compilers)NEWLINE pretty_printer.print_help("Fortran compilers found:")NEWLINE pretty_printer = FancyGetopt(compilers_na)NEWLINE pretty_printer.print_help("Compilers available for this "NEWLINE "platform, but not found:")NEWLINE if compilers_ni:NEWLINE pretty_printer = FancyGetopt(compilers_ni)NEWLINE pretty_printer.print_help("Compilers not available on this platform:")NEWLINE print("For compiler details, run 'config_fc --verbose' setup command.")NEWLINENEWLINENEWLINEdef dummy_fortran_file():NEWLINE fo, name = make_temp_file(suffix='.f')NEWLINE fo.write(" subroutine dummy()\n end\n")NEWLINE fo.close()NEWLINE return name[:-2]NEWLINENEWLINENEWLINEis_f_file = re.compile(r'.*[.](for|ftn|f77|f)\Z', re.I).matchNEWLINE_has_f_header = re.compile(r'-[*]-\s*fortran\s*-[*]-', re.I).searchNEWLINE_has_f90_header = re.compile(r'-[*]-\s*f90\s*-[*]-', re.I).searchNEWLINE_has_fix_header = re.compile(r'-[*]-\s*fix\s*-[*]-', re.I).searchNEWLINE_free_f90_start = re.compile(r'[^c*!]\s*[^\s\d\t]', re.I).matchNEWLINENEWLINEdef is_free_format(file):NEWLINE """Check if file is in free format Fortran."""NEWLINE # f90 allows both fixed and free format, assuming fixed unlessNEWLINE # signs of free format are detected.NEWLINE result = 0NEWLINE f = open_latin1(file, 'r')NEWLINE line = f.readline()NEWLINE n = 10000 # the number of non-comment lines to scan for hintsNEWLINE if _has_f_header(line):NEWLINE n = 0NEWLINE elif _has_f90_header(line):NEWLINE n = 0NEWLINE result = 1NEWLINE while n>0 and line:NEWLINE line = line.rstrip()NEWLINE if line and line[0]!='!':NEWLINE n -= 1NEWLINE if (line[0]!='\t' and _free_f90_start(line[:5])) or line[-1:]=='&':NEWLINE result = 1NEWLINE breakNEWLINE line = f.readline()NEWLINE f.close()NEWLINE return resultNEWLINENEWLINEdef has_f90_header(src):NEWLINE f = open_latin1(src, 'r')NEWLINE line = f.readline()NEWLINE f.close()NEWLINE return _has_f90_header(line) or _has_fix_header(line)NEWLINENEWLINE_f77flags_re = re.compile(r'(c|)f77flags\s*\(\s*(?P\w+)\s*\)\s*=\s*(?P.*)', re.I)NEWLINEdef get_f77flags(src):NEWLINE """NEWLINE Search the first 20 lines of fortran 77 code for line patternNEWLINE `CF77FLAGS()=`NEWLINE Return a dictionary {:}.NEWLINE """NEWLINE flags = {}NEWLINE f = open_latin1(src, 'r')NEWLINE i = 0NEWLINE for line in f:NEWLINE i += 1NEWLINE if i>20: breakNEWLINE m = _f77flags_re.match(line)NEWLINE if not m: continueNEWLINE fcname = m.group('fcname').strip()NEWLINE fflags = m.group('fflags').strip()NEWLINE flags[fcname] = split_quoted(fflags)NEWLINE f.close()NEWLINE return flagsNEWLINENEWLINE# TODO: implement get_f90flags and use it in _compile similarly to get_f77flagsNEWLINENEWLINEif __name__ == '__main__':NEWLINE show_fcompilers()NEWLINE formatter = "%r %r %r %r"NEWLINEprint (formatter % (1 ,2 ,3 , 4))NEWLINEprint (formatter % ("one","two","three","four"))NEWLINEprint (formatter % (True, False, False, True))NEWLINEprint (formatter % (formatter ,formatter, formatter, formatter))NEWLINEprint (formatter % NEWLINE ("I had this thing.",NEWLINE "That you could type up right.",NEWLINE "But it didn't sing.",NEWLINE "So I said goodnight.")NEWLINE )NEWLINE NEWLINE # simple_xls.py: write simple Excel spreadsheetsNEWLINE# Copyright (C) University of Manchester 2013-2019 Peter BriggsNEWLINE#NEWLINE########################################################################NEWLINE#NEWLINE# simple_xls.pyNEWLINE#NEWLINE#########################################################################NEWLINENEWLINE"""NEWLINESimple spreadsheet module intended to provide a nicer programmatic interfaceNEWLINEto Excel spreadsheet generation.NEWLINENEWLINEIt is currently built on top of SpreadSheet.py, which itself uses the xlwt,NEWLINExlrd and xlutils modules. In future the relevant parts may be rewritten toNEWLINEremove the dependence on Spreadsheet.py and call the appropriate xl* classesNEWLINEand functions directly.NEWLINENEWLINEExample usageNEWLINE-------------NEWLINENEWLINEStart by making a workbook, represented by an XLSWorkBook object:NEWLINENEWLINE>>> wb = XLSWorkBook("Test")NEWLINENEWLINEThen add worksheets to this:NEWLINENEWLINE>>> wb.add_work_sheet('test')NEWLINE>>> wb.add_work_sheet('data',"My Data")NEWLINENEWLINEWorksheets have an id and an optional title. Ids must be unique and canNEWLINEbe used to fetch the XLSWorkSheet object that represent the worksheet:NEWLINENEWLINE>>> data = wb.worksheet['data']NEWLINENEWLINECells can be addressed directly using various notations:NEWLINENEWLINE>>> data['A1'] = "Column 1"NEWLINE>>> data['A']['1'] = "Updated value"NEWLINE>>> data['AZ']['3'] = "Another value"NEWLINENEWLINEThe extent of the sheet is defined by the outermost populated rows andNEWLINEcolumnsNEWLINENEWLINE>>> data.last_column # outermost populated columnNEWLINE>>> data.last_row # outermost populated rowNEWLINENEWLINEThere are various other methods for returning the next row or column; seeNEWLINEthe documentation for the XLSWorkSheet class.NEWLINENEWLINEData can be added cell-wise (i.e. referencing individual cells as above),NEWLINErow-wise, column-wise and block-wise.NEWLINENEWLINEColumn-wise operations include inserting a column (shifting columns aboveNEWLINEit along one to make space):NEWLINENEWLINE>>> data.insert_column('B',data=['hello','goodbye','whatev'])NEWLINENEWLINEAppend a column (writing data to the first empty column at the end ofNEWLINEthe sheet):NEWLINENEWLINE>>> data.append_column(data=['hello','goodbye','whatev'])NEWLINENEWLINEWrite data to a column, overwriting any existing values:NEWLINENEWLINE>>> data.write_column(data=['hello','goodbye','whatev'])NEWLINENEWLINEData can be specified as a list, text or as a single value which isNEWLINErepeated for each cell (i.e. a "fill" value).NEWLINENEWLINESimilar row-wise operations also exist:NEWLINENEWLINE>>> data.insert_row(4,data=['Dozy','Beaky','Mick','Titch'])NEWLINE>>> data.append_row(data=['Dozy','Beaky','Mick','Titch'])NEWLINE>>> data.write_row(4,data=['Dozy','Beaky','Mick','Titch'])NEWLINENEWLINEBlock-wise data can be added via a tab and newline-delimited string:NEWLINENEWLINE>>> data.insert_block_data("This\tis\t\tsome\n\trandom\n\tdata")NEWLINE>>> data.insert_block_data("This\tis\t\tsome\n\tMORE\trandom\n\tdata",NEWLINE... col='M',row=7)NEWLINENEWLINEFormulae can be specified by prefixing a '=' symbol to the start of theNEWLINEcell contents, e.g.:NEWLINENEWLINE>>> data['A3'] = '=A1+A2'NEWLINENEWLINE'?' and '#' are special characters that can be used to indicate 'currentNEWLINErow' and 'current column' respectively, e.g.:NEWLINENEWLINE>>> data.fill_column('A','=B?+C?') # evaluates to 'B1+C1' (A1), 'B2+C2' (A2) etcNEWLINENEWLINEStyling and formatting information can be associated with a cell, eitherNEWLINEwhen adding column, row or block data or by using the 'set_style' method.NEWLINEIn each case the styling information is passed via an XLSStyle object, e.g.NEWLINENEWLINE>>> data.set_style(XLSStyle(number_format=NumberFormats.PERCENTAGE),'A3')NEWLINENEWLINEThe workbook can be saved to file:NEWLINENEWLINE>>> wb.save_as_xls('test.xls')NEWLINENEWLINEAlternatively the contents of a sheet (or a subset) can be rendered as text:NEWLINENEWLINE>>> data.render_as_text(include_columns_and_rows=True,NEWLINE... eval_formulae=True,NEWLINE... include_styles=True)NEWLINE>>> data.render_as_text(start='B1',end='C6',include_columns_and_rows=True)NEWLINENEWLINE"""NEWLINENEWLINE#######################################################################NEWLINE# Import modules that this module depends onNEWLINE#######################################################################NEWLINENEWLINEfrom builtins import strNEWLINEimport reNEWLINEtry:NEWLINE from collections.abc import IteratorNEWLINEexcept ImportError:NEWLINE from collections import IteratorNEWLINEimport loggingNEWLINEimport xlsxwriterNEWLINEfrom . import SpreadsheetNEWLINEfrom .utils import OrderedDictionaryNEWLINEfrom builtins import rangeNEWLINENEWLINE#######################################################################NEWLINE# ConstantsNEWLINE#######################################################################NEWLINENEWLINE# Value to assign to failed evaluationsNEWLINEBAD_REF="## !REF ##"NEWLINENEWLINE# Number formatsNEWLINEclass NumberFormats(object):NEWLINE THOUSAND_SEPARATOR=0NEWLINE PERCENTAGE=1NEWLINENEWLINE# Spreadsheet limitsNEWLINEclass XLSLimits(object):NEWLINE """NEWLINE Limits for XLS filesNEWLINE """NEWLINE MAX_LEN_WORKSHEET_TITLE = 31 # Max worksheet title lengthNEWLINE MAX_LEN_WORKSHEET_CELL_VALUE = 250 # Maximum no. of characters in cellNEWLINE MAX_NUMBER_ROWS_PER_WORKSHEET = 65536 # Max number of rows per worksheetNEWLINE MAX_NUMBER_COLS_PER_WORKSHEET = 256 # Max nuber of columns per worksheetNEWLINENEWLINEclass XLSXLimits(object):NEWLINE """NEWLINE Limits for XLSX filesNEWLINE """NEWLINE MAX_LEN_WORKSHEET_TITLE = 31 # Max worksheet title lengthNEWLINE MAX_LEN_WORKSHEET_CELL_VALUE = 1024 # Maximum no. of characters in cellNEWLINE MAX_NUMBER_ROWS_PER_WORKSHEET = 1048576 # Max number of rows per worksheetNEWLINE MAX_NUMBER_COLS_PER_WORKSHEET = 16384 # Max nuber of columns per worksheetNEWLINENEWLINEclass Limits(XLSLimits):NEWLINE """NEWLINE Limits for XLS files (kept for backwards compatibility)NEWLINE """NEWLINENEWLINE#######################################################################NEWLINE# Class definitionsNEWLINE#######################################################################NEWLINENEWLINEclass XLSWorkBook(object):NEWLINE """Class for creating an Excel (xls) spreadsheetNEWLINENEWLINE An XLSWorkBook instance provides an interface to creating anNEWLINE Excel spreadsheet.NEWLINENEWLINE It consists of a collection of XLSWorkSheet objects, eachNEWLINE of which represents a sheet in the workbook.NEWLINENEWLINE Sheets are created and appended using the add_work_sheetNEWLINE method:NEWLINENEWLINE >>> xls = XLSWorkBook()NEWLINE >>> sheet = xls('example')NEWLINE NEWLINE Sheets are kept in the 'worksheet' property and can be acquiredNEWLINE by name:NEWLINENEWLINE >>> sheet = xls.worksheet['example']NEWLINENEWLINE Once the worksheet(s) have been populated an XLS file can beNEWLINE created using the 'save_as_xls' method:NEWLINENEWLINE >>> xls.save_as_xls('example.xls')NEWLINENEWLINE """NEWLINE def __init__(self,title=None):NEWLINE """Create a new XLSWorkBook instanceNEWLINENEWLINE Arguments:NEWLINE title: optional, a title for the work bookNEWLINENEWLINE """NEWLINE self.title = titleNEWLINE self.worksheet = OrderedDictionary()NEWLINENEWLINE def add_work_sheet(self,name,title=None):NEWLINE """Create and append a new worksheetNEWLINENEWLINE Creates a new XLSWorkSheet object and appends itNEWLINE to the workbook.NEWLINENEWLINE Arguments:NEWLINE name: unique name for the worksheetNEWLINE title: optional, title for the worksheet - defaults toNEWLINE the name.NEWLINENEWLINE Returns:NEWLINE New XLSWorkSheet object.NEWLINENEWLINE """NEWLINE if name in self.worksheet:NEWLINE raise KeyError("Worksheet called '%s' already exists" %NEWLINE name)NEWLINE if title is None:NEWLINE title = nameNEWLINE self.worksheet[name] = XLSWorkSheet(title)NEWLINE return self.worksheet[name]NEWLINENEWLINE def save_as_xls(self,filen):NEWLINE """Output the workbook contents to an Excel-format fileNEWLINENEWLINE Arguments:NEWLINE filen: name of the file to write the workbook to.NEWLINENEWLINE """NEWLINE xls = Spreadsheet.Workbook()NEWLINE for name in self.worksheet:NEWLINE worksheet = self.worksheet[name]NEWLINE ws = xls.addSheet(worksheet.title)NEWLINE ws.addText(worksheet.render_as_text(include_styles=True))NEWLINE if worksheet.freeze_panes is not None:NEWLINE col = column_index_to_integer(NEWLINE CellIndex(worksheet.freeze_panes).column)NEWLINE row = CellIndex(worksheet.freeze_panes).row - 1NEWLINE ws.freezePanes(column=col,row=row)NEWLINE xls.save(filen)NEWLINENEWLINE def save_as_xlsx(self,filen):NEWLINE """Output the workbook contents to an XLSX-format fileNEWLINENEWLINE Arguments:NEWLINE filen: name of the file to write the workbook to.NEWLINENEWLINE """NEWLINE xlsx = xlsxwriter.Workbook(filen)NEWLINE styles = {}NEWLINE default_min_col_width = 7NEWLINE for name in self.worksheet:NEWLINE worksheet = self.worksheet[name]NEWLINE ws = xlsx.add_worksheet(worksheet.title)NEWLINE # Write content to worksheet cell by cellNEWLINE start = CellIndex('A1')NEWLINE end = CellIndex(cell(worksheet.last_column,NEWLINE worksheet.last_row))NEWLINE for col in ColumnRange(start.column,end.column):NEWLINE # Maximum column widthNEWLINE max_width = default_min_col_widthNEWLINE for row in range(start.row,end.row+1):NEWLINE # Get the valueNEWLINE value = worksheet.render_cell(cell(col,row),NEWLINE eval_formulae=False,NEWLINE apply_format=False)NEWLINE # Handle styles for this cellNEWLINE style = worksheet.get_style(cell(col,row))NEWLINE if style:NEWLINE style_name = style.nameNEWLINE try:NEWLINE xlsx_fmt = styles[style_name]NEWLINE except KeyError:NEWLINE xlsx_fmt = xlsx.add_format()NEWLINE if style.bold:NEWLINE xlsx_fmt.set_bold()NEWLINE if style.color is not None:NEWLINE xlsx_fmt.set_color(style.color)NEWLINE if style.bgcolor is not None:NEWLINE xlsx_fmt.set_bg_color(style.bgcolor)NEWLINE if style.font_size is not None:NEWLINE xlsx_fmt.set_font_size(style.font_size)NEWLINE styles[style_name] = xlsx_fmtNEWLINE else:NEWLINE xlsx_fmt = NoneNEWLINE # Deal with cell contentNEWLINE if value.startswith('='):NEWLINE # Cell contains formulaNEWLINE result = eval_formula(value,worksheet)NEWLINE ws.write_formula(cell(col,row),value,xlsx_fmt,result)NEWLINE col_width = len(str(result))NEWLINE else:NEWLINE # Deal with a data itemNEWLINE # Attempt to convert to a number typeNEWLINE # i.e. integer/floatNEWLINE try:NEWLINE # Try integerNEWLINE value = int(str(value))NEWLINE except ValueError:NEWLINE # Not an integer, try floatNEWLINE try:NEWLINE value = float(str(value))NEWLINE except ValueError:NEWLINE # Not a float eitherNEWLINE passNEWLINE # Write to the worksheetNEWLINE ws.write(cell(col,row),value,xlsx_fmt)NEWLINE col_width = len(str(value))NEWLINE # Handle column widthsNEWLINE max_width = max(max_width,col_width)NEWLINE # Set the column widthNEWLINE icol = column_index_to_integer(col)NEWLINE ws.set_column(icol,icol,max_width*1.2)NEWLINE # Handle freeze panesNEWLINE if worksheet.freeze_panes is not None:NEWLINE ws.freeze_panes(worksheet.freeze_panes)NEWLINE xlsx.close()NEWLINENEWLINEclass XLSWorkSheet(object):NEWLINE """Class for creating sheets within an XLS workbook.NEWLINENEWLINE XLSWorkSheet objects represent a sheet within an ExcelNEWLINE workbook.NEWLINENEWLINE Cells are addressed within the sheet using Excel notationNEWLINE i.e. (columns start at index 'A' and rows atNEWLINE '1', examples are 'A1' or 'D19'):NEWLINENEWLINE >>> ws = XLSWorkSheet('example')NEWLINE >>> ws['A1'] = 'some data'NEWLINE >>> value = ws['A1']NEWLINENEWLINE If there is no data stored for the cell then 'None' isNEWLINE returned. Any cell can addressed without errors.NEWLINENEWLINE Data can also be added column-wise, row-wise or as aNEWLINE "block" of tab- and new-line delimited data:NEWLINENEWLINE >>> ws.insert_column_data('B',[1,2,3])NEWLINE >>> ws.insert_row_data(4,['x','y','z'])NEWLINE >>> ws.insert_block_data("This\tis\nthe\tdata")NEWLINENEWLINE A column can be "filled" with a single repeating value:NEWLINE NEWLINE >>> ws.fill_column('D','single value')NEWLINENEWLINE The extent of the sheet can be determined from theNEWLINE 'last_column' and last_row' properties; the 'next_column'NEWLINE and 'next_row' properties report the next empty columnNEWLINE and row respectively.NEWLINENEWLINE Cells can contain Excel-style formula by adding anNEWLINE equals sign to the start of the value. Typically formulaeNEWLINE reference other cells and perform mathematical operationsNEWLINE on them, e.g.:NEWLINENEWLINE >>> ws['E11'] = "=A1+A2"NEWLINENEWLINE Wildcard characters can be used which will be automaticallyNEWLINE translated into the cell column ('#') or row ('?'), forNEWLINE example:NEWLINENEWLINE >>> ws['F46'] = "=#47+#48"NEWLINENEWLINE will be transformed to "=F47+F48".NEWLINENEWLINE Styles can be applied to cells, using either the 'set_style'NEWLINE method or via the 'style' argument of some methods, toNEWLINE associate an XLSStyle object. Associated XLSStyle objectsNEWLINE can be retrieved using the 'get_style' method.NEWLINENEWLINE The value of an individual cell can be 'rendered' forNEWLINE output using the 'render_cell' method:NEWLINENEWLINE >>> print(ws.render_cell('F46'))NEWLINENEWLINE All or part of the sheet can be rendered as a tab- andNEWLINE newline-delimited string by using the 'render_as_text'NEWLINE method:NEWLINENEWLINE >>> print(ws.render_as_text())NEWLINENEWLINE """NEWLINE def __init__(self,title):NEWLINE """Create new XLSWorkSheet objectNEWLINENEWLINE Arguments:NEWLINE title: title string for the worksheetNEWLINENEWLINE """NEWLINE self.title = str(title)[:Spreadsheet.MAX_LEN_WORKSHEET_TITLE]NEWLINE self.data = {}NEWLINE self.styles = {}NEWLINE self.rows = []NEWLINE self.columns = []NEWLINE self.freeze_panes = NoneNEWLINENEWLINE def __setitem__(self,idx,value):NEWLINE """Implement 'x[idx] = value'NEWLINENEWLINE """NEWLINE idx = CellIndex(idx)NEWLINE if not idx.is_full:NEWLINE raise KeyError("Invalid index: '%s'" % idx)NEWLINE self.data[idx.idx] = valueNEWLINE if idx.column not in self.columns:NEWLINE self.columns.append(idx.column)NEWLINE self.columns = sorted(self.columns,key=lambda x: x[::-1])NEWLINE if idx.row not in self.rows:NEWLINE self.rows.append(idx.row)NEWLINE self.rows.sort()NEWLINENEWLINE def __getitem__(self,idx):NEWLINE """Implement 'value = x[idx]'NEWLINENEWLINE """NEWLINE if str(idx).isalpha():NEWLINE return XLSColumn(idx,parent=self)NEWLINE else:NEWLINE try:NEWLINE return self.data[idx]NEWLINE except Exception as ex:NEWLINE return NoneNEWLINENEWLINE def __delitem__(self,idx):NEWLINE """Implement 'del(x[idx])'NEWLINENEWLINE """NEWLINE try:NEWLINE del(self.data[idx])NEWLINE except KeyError:NEWLINE passNEWLINE idx = CellIndex(idx)NEWLINE if self.column_is_empty(idx.column):NEWLINE self.columns.remove(idx.column)NEWLINE if self.row_is_empty(idx.row):NEWLINE self.rows.remove(idx.row)NEWLINENEWLINE @propertyNEWLINE def last_column(self):NEWLINE """Return index of last column with dataNEWLINENEWLINE """NEWLINE try:NEWLINE return self.columns[-1]NEWLINE except IndexError:NEWLINE return 'A'NEWLINENEWLINE @propertyNEWLINE def next_column(self):NEWLINE """Index of first empty column after highest index with dataNEWLINENEWLINE """NEWLINE if len(self.columns):NEWLINE return column_integer_to_index(column_index_to_integer(self.last_column)+1)NEWLINE else:NEWLINE return 'A'NEWLINENEWLINE @propertyNEWLINE def last_row(self):NEWLINE """Return index of last row with dataNEWLINENEWLINE """NEWLINE try:NEWLINE return int(self.rows[-1])NEWLINE except IndexError:NEWLINE return 1NEWLINENEWLINE @propertyNEWLINE def next_row(self):NEWLINE """Index of first empty row after highest index with dataNEWLINENEWLINE """NEWLINE if len(self.rows):NEWLINE return self.last_row + 1NEWLINE else:NEWLINE return 1NEWLINENEWLINE def column_is_empty(self,col):NEWLINE """Determine whether a column is emptyNEWLINENEWLINE Returns False if any cells in the column are populated,NEWLINE otherwise returns True.NEWLINENEWLINE """NEWLINE if col not in self.columns:NEWLINE return TrueNEWLINE for row in self.rows:NEWLINE if self[cell(col,row)] is not None:NEWLINE return FalseNEWLINE return TrueNEWLINENEWLINE def row_is_empty(self,row):NEWLINE """Determine whether a row is emptyNEWLINENEWLINE Returns False if any cells in the row are populated,NEWLINE otherwise returns True.NEWLINENEWLINE """NEWLINE if row not in self.rows:NEWLINE return TrueNEWLINE for col in self.columns:NEWLINE if self[cell(col,row)] is not None:NEWLINE return FalseNEWLINE return TrueNEWLINENEWLINE def columnof(self,s,row=1):NEWLINE """Return column index for cell which matches stringNEWLINENEWLINE Return index of first column where the content matchesNEWLINE the specified string 's'.NEWLINENEWLINE Arguments:NEWLINE s: string to search forNEWLINE row: row to search in (defaults to 1)NEWLINENEWLINE Returns:NEWLINE Column index of first matching cell. Raises LookUpErrorNEWLINE if no match is found.NEWLINENEWLINE """NEWLINE for col in self.columns:NEWLINE if self[cell(col,row)] == s:NEWLINE return colNEWLINE raise LookupError("No match for '%s' in row %d" % (s,row))NEWLINENEWLINE def insert_column(self,position,data=None,text=None,fill=None,from_row=None,style=None):NEWLINE """Create a new column at the specified column positionNEWLINENEWLINE Inserts a new column at the specified column position,NEWLINE pushing up the column currently at that position plus allNEWLINE higher positioned columns.NEWLINENEWLINE By default the inserted column is empty, however data canNEWLINE be specified to populate the column.NEWLINENEWLINE Arguments:NEWLINE position: column index specifying position to insert theNEWLINE column atNEWLINE data: optional, list of data items to populate theNEWLINE inserted columnNEWLINE text: optional, tab-delimited string of text to be usedNEWLINE to populate the inserted columnNEWLINE fill: optional, single data item to be repeated to fillNEWLINE the inserted columnNEWLINE from_row: optional, if specified then inserted column isNEWLINE populated from that row onwardsNEWLINE style: optional, an XLSStyle object to associate with theNEWLINE data being insertedNEWLINENEWLINE Returns:NEWLINE The index of the inserted column.NEWLINENEWLINE """NEWLINE # Get list of all columns we want to move (in reverse order)NEWLINE columns_to_bump = []NEWLINE try:NEWLINE i = self.columns.index(position)NEWLINE columns_to_bump = self.columns[i:][::-1]NEWLINE except ValueError:NEWLINE for col in self.columns:NEWLINE if cmp_column_indices(col,position) > -1:NEWLINE i = self.columns.index(col)NEWLINE columns_to_bump = self.columns[i:][::-1]NEWLINE breakNEWLINE # Shift columns, if requiredNEWLINE for col in columns_to_bump:NEWLINE next_col = column_integer_to_index(column_index_to_integer(col)+1)NEWLINE for row in range(1,self.last_row+1):NEWLINE # Get cell indexNEWLINE idx = cell(col,row)NEWLINE if idx in self.data:NEWLINE # Copy contents to next columnNEWLINE self.data[cell(next_col,row)] = self.data[idx]NEWLINE # Remove this cellNEWLINE del(self.data[idx])NEWLINE # Append a new last column index to list of columnsNEWLINE self.columns.append(self.next_column)NEWLINE # Remove the inserted column index from the list of columnsNEWLINE if position in self.columns:NEWLINE self.columns.remove(position)NEWLINE # Now insert data at the new positionNEWLINE self.write_column(position,data=data,text=text,fill=fill,from_row=from_row,style=style)NEWLINE return positionNEWLINENEWLINE def append_column(self,data=None,text=None,fill=None,from_row=None,style=None):NEWLINE """Create a new column at the end of the sheetNEWLINENEWLINE Appends a new column at the end of the worksheet i.e. in theNEWLINE first available empty column.NEWLINENEWLINE By default the appended column is empty, however data canNEWLINE be specified to populate the column.NEWLINENEWLINE Arguments:NEWLINE data: optional, list of data items to populate theNEWLINE inserted columnNEWLINE text: optional, tab-delimited string of text to be usedNEWLINE to populate the inserted columnNEWLINE fill: optional, single data item to be repeated to fillNEWLINE the inserted columnNEWLINE from_row: optional, if specified then inserted column isNEWLINE populated from that row onwardsNEWLINE style: optional, an XLSStyle object to associate with theNEWLINE data being insertedNEWLINENEWLINE Returns:NEWLINE The index of the appended column.NEWLINENEWLINE """NEWLINE new_col = self.next_columnNEWLINE # Now insert data into the new positionNEWLINE self.write_column(new_col,data=data,text=text,fill=fill,from_row=from_row,style=style)NEWLINE return new_colNEWLINENEWLINE def write_column(self,col,data=None,text=None,fill=None,from_row=None,style=None):NEWLINE """Write data to rows in a columnNEWLINENEWLINE Data can be specified as a list, a newline-delimited string, orNEWLINE as a single repeated data item.NEWLINENEWLINE Arguments:NEWLINE data: optional, list of data items to populate theNEWLINE inserted columnNEWLINE text: optional, newline-delimited string of text to be usedNEWLINE to populate the inserted columnNEWLINE fill: optional, single data item to be repeated to fillNEWLINE the inserted columnNEWLINE from_row: optional, if specified then inserted column isNEWLINE populated from that row onwardsNEWLINE style: optional, an XLSStyle object to associate with theNEWLINE data being insertedNEWLINENEWLINE """NEWLINE # Set initial rowNEWLINE if from_row is None:NEWLINE from_row = 1NEWLINE # Write in data from a listNEWLINE if data is not None:NEWLINE items = dataNEWLINE elif text is not None:NEWLINE items = text.split('\n')NEWLINE elif fill is not None:NEWLINE items = [fill for i in range(from_row,self.last_row+1)]NEWLINE else:NEWLINE # Nothing to doNEWLINE returnNEWLINE # Add column index to list of columnsNEWLINE if col not in self.columns:NEWLINE self.columns.append(col)NEWLINE # Write data items to cellsNEWLINE row = from_rowNEWLINE for item in items:NEWLINE self.data[cell(col,row)] = itemNEWLINE if row not in self.rows:NEWLINE self.rows.append(row)NEWLINE if style is not None:NEWLINE self.set_style(style,cell(col,row))NEWLINE row += 1NEWLINE # Sort the column and row indicesNEWLINE self.columns = sorted(self.columns,key=lambda x: x[::-1])NEWLINE self.rows.sort()NEWLINENEWLINE def insert_column_data(self,col,data,start=None,style=None):NEWLINE """Insert list of data into a columnNEWLINENEWLINE Data items are supplied as a list, with each item in the listNEWLINE being inserted into the next row in the column.NEWLINENEWLINE By default items are inserted starting from row 1, unless aNEWLINE starting row is explicitly specified via the 'start' argument.NEWLINENEWLINE *** THIS METHOD IS DEPRECATED ***NEWLINENEWLINE Consider using insert_column, append_column or write_data.NEWLINENEWLINE Arguments:NEWLINE col: index of column to insert the data into (e.g. 'A','MZ')NEWLINE data: list of data itemsNEWLINE start: (optional) first row to insert data intoNEWLINE style: (optional) XLSStyle object to be associated with eachNEWLINE cell that has data inserted into itNEWLINENEWLINE """NEWLINE # Insert data items from a list into a column in the spreadsheetNEWLINE if start is None:NEWLINE i = 1NEWLINE else:NEWLINE i = int(start)NEWLINE for item in data:NEWLINE self[cell(col,i)] = itemNEWLINE if style is not None:NEWLINE self.set_style(style,cell(col,i))NEWLINE i += 1NEWLINENEWLINE def rowof(self,s,column='A'):NEWLINE """Return row index for cell which matches stringNEWLINENEWLINE Return index of first row where the content matchesNEWLINE the specified string 's'.NEWLINENEWLINE Arguments:NEWLINE s: string to search forNEWLINE column: column to search in (defaults to 'A')NEWLINENEWLINE Returns:NEWLINE Row index of first matching cell. Raises LookUpErrorNEWLINE if no match is found.NEWLINENEWLINE """NEWLINE # Get row where cell in row matches 'name'NEWLINE # i.e. look up a row indexNEWLINE for row in range(1,self.last_row+1):NEWLINE if self[cell(column,row)] == s:NEWLINE return rowNEWLINE raise LookupError("No match for '%s' in column '%s'" %NEWLINE (s,column))NEWLINENEWLINE def insert_row(self,position,data=None,text=None,fill=None,from_column=None,style=None):NEWLINE """Create a new row at the specified row positionNEWLINENEWLINE Inserts a new row at the specified row position,NEWLINE pushing up the row currently at that position plus allNEWLINE higher positioned row.NEWLINENEWLINE By default the inserted row is empty, however data canNEWLINE be specified to populate the column.NEWLINENEWLINE Arguments:NEWLINE position: row index specifying position to insert theNEWLINE row atNEWLINE data: optional, list of data items to populate theNEWLINE inserted rowNEWLINE text: optional, newline-delimited string of text to be usedNEWLINE to populate the inserted rowNEWLINE fill: optional, single data item to be repeated to fillNEWLINE the inserted rowNEWLINE from_row: optional, if specified then inserted row isNEWLINE populated from that column onwardsNEWLINE style: optional, an XLSStyle object to associate with theNEWLINE data being insertedNEWLINENEWLINE Returns:NEWLINE The index of the inserted row.NEWLINENEWLINE """NEWLINE # Create a new row before the specified rowNEWLINE # All rows above it move up one positionNEWLINE # 'New' row position is actually 'before_row'NEWLINE # Bump all rows up one positionNEWLINE # Get list of all rows we want to move (in reverse order)NEWLINE row_list = list(range(self.last_row,position-1,-1))NEWLINE for row in row_list:NEWLINE next_row = row + 1NEWLINE for col in self.columns:NEWLINE # Get cell indexNEWLINE idx = cell(col,row)NEWLINE if idx in self.data:NEWLINE # Copy contents to next rowNEWLINE self.data[cell(col,next_row)] = self.data[idx]NEWLINE # Remove this cellNEWLINE del(self.data[idx])NEWLINE # Add a new last row index to the list of rowsNEWLINE self.rows.append(self.next_row)NEWLINE # Remove the inserted row index from the listNEWLINE if position in self.rows:NEWLINE self.rows.remove(position)NEWLINE # Now insert data at the new positionNEWLINE self.write_row(position,data=data,text=text,fill=fill,from_column=from_column,style=style)NEWLINE return positionNEWLINENEWLINE def append_row(self,data=None,text=None,fill=None,from_column=None,style=None):NEWLINE """Create a new row at the end of the sheetNEWLINENEWLINE Appends a new row at the end of the worksheet i.e. in theNEWLINE first available empty row.NEWLINENEWLINE By default the appended row is empty, however data canNEWLINE be specified to populate the row.NEWLINENEWLINE Arguments:NEWLINE data: optional, list of data items to populate theNEWLINE inserted rowNEWLINE text: optional, newline-delimited string of text to be usedNEWLINE to populate the inserted rowNEWLINE fill: optional, single data item to be repeated to fillNEWLINE the inserted rowNEWLINE from_row: optional, if specified then inserted row isNEWLINE populated from that column onwardsNEWLINE style: optional, an XLSStyle object to associate with theNEWLINE data being insertedNEWLINENEWLINE Returns:NEWLINE The index of the inserted row.NEWLINENEWLINE """NEWLINE # Create a new row at the end of the sheetNEWLINE new_row = self.next_rowNEWLINE # Now insert data into the new positionNEWLINE self.write_row(new_row,data=data,text=text,fill=fill,from_column=from_column,style=style)NEWLINE return new_rowNEWLINENEWLINE def write_row(self,row,data=None,text=None,fill=None,from_column=None,style=None):NEWLINE """Write data to rows in a columnNEWLINENEWLINE Data can be specified as a list, a tab-delimited string, orNEWLINE as a single repeated data item.NEWLINENEWLINE Arguments:NEWLINE row: row index specifying which rowNEWLINE data: optional, list of data items to populate theNEWLINE inserted rowNEWLINE text: optional, tab-delimited string of text to be usedNEWLINE to populate the inserted rowNEWLINE from_column: optional, if specified then inserted row isNEWLINE populated from that column onwardsNEWLINE style: optional, an XLSStyle object to associate with theNEWLINE data being insertedNEWLINENEWLINE """NEWLINE # Set initial columnNEWLINE if from_column is None:NEWLINE from_column = 'A'NEWLINE # Write in data from a listNEWLINE if data is not None:NEWLINE items = dataNEWLINE elif text is not None:NEWLINE items = text.split('\t')NEWLINE elif fill is not None:NEWLINE items = [fill for i in range(from_row,self.last_row+1)]NEWLINE else:NEWLINE # Nothing to doNEWLINE returnNEWLINE # Add row index to list of rowsNEWLINE if row not in self.rows:NEWLINE self.rows.append(row)NEWLINE # Write data items to cellsNEWLINE col = from_columnNEWLINE for item in items:NEWLINE self.data[cell(col,row)] = itemNEWLINE if col not in self.columns:NEWLINE self.columns.append(col)NEWLINE if style is not None:NEWLINE self.set_style(style,cell(col,row))NEWLINE col = incr_col(col)NEWLINE # Sort the column and row indicesNEWLINE self.columns = sorted(self.columns,key=lambda x: x[::-1])NEWLINE self.rows.sort()NEWLINENEWLINE def insert_row_data(self,row,data,start=None,style=None):NEWLINE """Insert list of data into a rowNEWLINENEWLINE Data items are supplied as a list, with each item in the listNEWLINE being inserted into the next column in the row.NEWLINENEWLINE By default items are inserted starting from column 'A', unless aNEWLINE starting column is explicitly specified via the 'start' argument.NEWLINENEWLINE *** THIS METHOD IS DEPRECATED ***NEWLINENEWLINE Consider using insert_row, append_row or write_row.NEWLINENEWLINE Arguments:NEWLINE row: index of row to insert the data into (e.g. 1, 112)NEWLINE data: list of data itemsNEWLINE start: (optional) first column to insert data intoNEWLINE style: (optional) XLSStyle object to be associated with eachNEWLINE cell that has data inserted into itNEWLINENEWLINE """NEWLINE # Insert data items from a list into a row in the spreadsheetNEWLINE if start is None:NEWLINE i = column_index_to_integer('A')NEWLINE else:NEWLINE i = column_index_to_integer(start)NEWLINE for item in data:NEWLINE self[cell(column_integer_to_index(i),row)] = itemNEWLINE if style is not None:NEWLINE self.set_style(style,cell(column_integer_to_index(i),row))NEWLINE i += 1NEWLINENEWLINE def insert_block_data(self,data,col=None,row=None,style=None):NEWLINE """Insert data items from a block of textNEWLINENEWLINE Data items are supplied via a block of tab- and newline-delimitedNEWLINE text. Each tab-delimited item is inserted into the next column inNEWLINE a row; newlines indicate that subsequent items are inserted intoNEWLINE the next row.NEWLINENEWLINE By default items are inserted starting from cell 'A1'; a differentNEWLINE starting cell can be explicitly specified via the 'col' and 'row'NEWLINE arguments.NEWLINENEWLINE Arguments:NEWLINE data: block of tab- and newline-delimited dataNEWLINE col: (optional) first column to insert data intoNEWLINE row: (optional) first row to insert data intoNEWLINE style: (optional) XLSStyle object to be associated with eachNEWLINE cell that has data inserted into itNEWLINENEWLINE """NEWLINE # Insert data items from a block of text into the spreadsheetNEWLINE # Text must be tab and newline delimitedNEWLINE if row is None:NEWLINE j = int(1)NEWLINE else:NEWLINE j = int(row)NEWLINE for line in data.split('\n'):NEWLINE if col is None:NEWLINE i = column_index_to_integer('A')NEWLINE else:NEWLINE i = column_index_to_integer(col)NEWLINE for item in line.strip('\n').split('\t'):NEWLINE icol = column_integer_to_index(i)NEWLINE if not item:NEWLINE item = NoneNEWLINE self[cell(icol,j)] = itemNEWLINE if style is not None:NEWLINE self.set_style(style,cell(icol,j))NEWLINE i += 1NEWLINE j += 1NEWLINENEWLINE def fill_column(self,column,item,start=None,end=None,style=None):NEWLINE """Fill a column with a single repeated data itemNEWLINENEWLINE A single data item is inserted into all rows in the specifiedNEWLINE column which have at least one data item already in any columnNEWLINE in the worksheet. A different range of rows can be specifiedNEWLINE via the 'start' and 'end' arguments.NEWLINENEWLINE *** THIS METHOD IS DEPRECATED ***NEWLINENEWLINE Consider using insert_column, append_column or write_data.NEWLINENEWLINE Arguments:NEWLINE column: index of column to insert the item into (e.g. 'A','MZ')NEWLINE item: data item to be repeatedNEWLINE start: (optional) first row to insert data intoNEWLINE end: (optional) last row to insert data intoNEWLINE style: (optional) XLSStyle object to be associated with eachNEWLINE cell that has data inserted into itNEWLINENEWLINE """NEWLINE # Fill a column with the same data itemNEWLINE if (start is None or end is None) and (not self.columns and not self.rows):NEWLINE # Empty sheet, nothing to fillNEWLINE returnNEWLINE if start is None:NEWLINE i = 1NEWLINE else:NEWLINE i = int(start)NEWLINE if end is None:NEWLINE j = self.last_rowNEWLINE else:NEWLINE j = int(end)NEWLINE for row in range(i,j+1):NEWLINE self[cell(column,row)] = itemNEWLINE if style is not None:NEWLINE self.set_style(style,cell(column,row))NEWLINENEWLINE def set_style(self,cell_style,start,end=None):NEWLINE """Associate style information with one or more cellsNEWLINE NEWLINE Associates a specified XLSStyle object with a singleNEWLINE cell, or with a range of cells (if a second cell indexNEWLINE is supplied).NEWLINENEWLINE The style associated with a cell can be fetched usingNEWLINE the 'get_style' method.NEWLINENEWLINE Arguments:NEWLINE cell_style: XLSStyle objectNEWLINE start: cell index e.g. 'A1'NEWLINE end: (optional) second cell index; together withNEWLINE 'start' this defines a range of cells to associateNEWLINE the style with.NEWLINE NEWLINE """NEWLINE if end is None:NEWLINE # Specified a single cell targetNEWLINE self.styles[start] = cell_styleNEWLINE returnNEWLINE # Specify a range of cellsNEWLINE start_cell = CellIndex(start)NEWLINE end_cell = CellIndex(end)NEWLINE for col in ColumnRange(start_cell.column,end_cell.column):NEWLINE for row in range(start_cell.row,end_cell.row+1):NEWLINE self.styles[cell(col,row)] = cell_styleNEWLINENEWLINE def get_style(self,idx):NEWLINE """Return the style information associated with a cellNEWLINENEWLINE Returns an XLSStyle object associated with the specificNEWLINE cell.NEWLINENEWLINE If no style was previously associated then return a newNEWLINE XLSStyle object.NEWLINENEWLINE Arguments:NEWLINE idx: cell index e.g 'A1'NEWLINENEWLINE Returns:NEWLINE XLSStyle object.NEWLINENEWLINE """NEWLINE try:NEWLINE return self.styles[idx]NEWLINE except KeyError:NEWLINE # Return empty style objectNEWLINE return XLSStyle()NEWLINENEWLINE def render_cell(self,idx,eval_formulae=False,apply_format=False):NEWLINE """Text representation of value stored in a cellNEWLINENEWLINE Create a text representation of a cell's contents. If the cellNEWLINE contains a formula then '?'s will be replaced with the row indexNEWLINE and '#'s with the column index. Optionally the formula can alsoNEWLINE be evaluated, and any style information associated with the cellNEWLINE can also be rendered.NEWLINENEWLINE Arguments:NEWLINE idx: cell index e.g. 'A1'NEWLINE eval_formulae: (optional) if True then if the cell containsNEWLINE a formula, attempt to evaluate it and return the result.NEWLINE Otherwise return the formula itself (this is the default)NEWLINE apply_format: (optional) if True then format numbers accordingNEWLINE to the formatting information associated with the cellNEWLINE (default is not to apply formatting).NEWLINENEWLINE Returns:NEWLINE String representing the cell contents.NEWLINENEWLINE """NEWLINE item = self[idx]NEWLINE if item is None:NEWLINE # Empty itemNEWLINE return ''NEWLINE try:NEWLINE if item.startswith('='):NEWLINE # FormulaNEWLINE item = item.replace('?',NEWLINE str(CellIndex(idx).row)).replace('#',NEWLINE str(CellIndex(idx).column))NEWLINE if eval_formulae:NEWLINE logging.debug("Evaluating %s from %s" % (item,idx))NEWLINE item = eval_formula(item,self)NEWLINE except AttributeError:NEWLINE passNEWLINE if apply_format:NEWLINE style = self.get_style(idx)NEWLINE if style is not None:NEWLINE try:NEWLINE return format_value(item,style.number_format)NEWLINE except Exception as ex:NEWLINE logging.debug("Exception: %s" % ex)NEWLINE raise exNEWLINE else:NEWLINE return str(item)NEWLINENEWLINE def render_as_text(self,include_columns_and_rows=False,NEWLINE include_styles=False,NEWLINE eval_formulae=False,NEWLINE apply_format=False,NEWLINE start=None,end=None):NEWLINE """Text representation of all or part of the worksheetNEWLINENEWLINE All or part of the sheet can be rendered as a tab- andNEWLINE newline-delimited string.NEWLINENEWLINE Arguments:NEWLINE include_columns_and_rows: (optional) if True then also outputNEWLINE a header row of column indices, and a column of row indicesNEWLINE (default is to not output columns and rows).NEWLINE include_styles: (optional) if True then also render the stylingNEWLINE information associated with the cell (default is not to applyNEWLINE styling).NEWLINE apply_format: (optional) if True then format numbers accordingNEWLINE to the formatting information associated with the cellNEWLINE (default is not to apply formatting).NEWLINE eval_formulae: (optional) if True then if the cell containsNEWLINE a formula, attempt to evaluate it and return the result.NEWLINE Otherwise return the formula itself (this is the default)NEWLINE start: (optional) specify the top-lefthand most cell index toNEWLINE start rendering from (default is 'A1').NEWLINE end: (optional) specify the bottom-righthand most cell indexNEWLINE to finish rendering at (default is the cell corresponding toNEWLINE the highest column and row indices. Note that this cell mayNEWLINE be empty.)NEWLINENEWLINE Returns:NEWLINE String containing the rendered sheet or sheet subset, with itemsNEWLINE within a row separated by tabs, and rows separated by newlines.NEWLINENEWLINE """NEWLINE # Output worksheet as text (i.e. string)NEWLINE if start is None:NEWLINE start = CellIndex('A1')NEWLINE else:NEWLINE start = CellIndex(start)NEWLINE if end is None:NEWLINE end = CellIndex(cell(self.last_column,self.last_row))NEWLINE else:NEWLINE end = CellIndex(end)NEWLINE text = []NEWLINE if include_columns_and_rows:NEWLINE line = ['']NEWLINE for col in ColumnRange(start.column,end.column):NEWLINE line.append(col)NEWLINE text.append('\t'.join(line))NEWLINE for row in range(start.row,end.row+1):NEWLINE line = []NEWLINE if include_columns_and_rows:NEWLINE line.append(u'%s' % row)NEWLINE for col in ColumnRange(start.column,end.column):NEWLINE value = self.render_cell(cell(col,row),NEWLINE eval_formulae=eval_formulae,NEWLINE apply_format=apply_format)NEWLINE if include_styles:NEWLINE value = self.get_style(cell(col,row)).style(value)NEWLINE line.append(u"%s" % value)NEWLINE text.append('\t'.join(line))NEWLINE return '\n'.join(text)NEWLINENEWLINEclass XLSStyle(object):NEWLINE """Class representing a set of styling and formatting dataNEWLINENEWLINE An XLSStyle object represents a collection of data used forNEWLINE styling and formatting cell values on output to an Excel file.NEWLINENEWLINE The style attributes can be set on instantiation, or queriedNEWLINE and modified afterwards.NEWLINENEWLINE The attributes are:NEWLINENEWLINE bold: whether text is bold or not (boolean)NEWLINE color: text color (name)NEWLINE bgcolor: background color (name)NEWLINE wrap: whether text in a cell should wrap (boolean)NEWLINE border: style of cell border (thick, medium, thin etc)NEWLINE number_format: a format code from the NumbersFormat classNEWLINE font_size: font size in points (integer)NEWLINE centre: whether text is centred in the cell (boolean)NEWLINE shrink_to_fit: whether to shrink cell to fit the contents.NEWLINENEWLINE The 'name' property can be used to generate a name for the styleNEWLINE based on the attributes that have been set, for example:NEWLINENEWLINE >>> XLSStyle(bold=true).nameNEWLINE ... '__bold__'NEWLINENEWLINE """NEWLINE def __init__(self,bold=False,color=None,bgcolor=None,wrap=False,NEWLINE border=None,number_format=None,font_size=None,centre=False,NEWLINE shrink_to_fit=False):NEWLINE """Create a new XLSStyle objectNEWLINENEWLINE The available arguments are the same as the attributes.NEWLINENEWLINE """NEWLINE self.bold=boldNEWLINE self.color=colorNEWLINE self.bgcolor=bgcolorNEWLINE self.wrap=wrapNEWLINE self.border=borderNEWLINE self.number_format=number_formatNEWLINE self.font_size = font_sizeNEWLINE self.centre = centreNEWLINE self.shrink_to_fit = shrink_to_fitNEWLINENEWLINE def __nonzero__(self):NEWLINE return self.__bool__()NEWLINENEWLINE def __bool__(self):NEWLINE return \NEWLINE (self.bold) or \NEWLINE (self.color is not None) or \NEWLINE (self.bgcolor is not None) or \NEWLINE (self.wrap) or \NEWLINE (self.border is not None) or \NEWLINE (self.number_format is not None) or \NEWLINE (self.font_size is not None) or \NEWLINE (self.centre) or \NEWLINE (self.shrink_to_fit)NEWLINENEWLINE @propertyNEWLINE def name(self):NEWLINE """Return a name based on the attributesNEWLINE """NEWLINE name = []NEWLINE if self.bold:NEWLINE name.append('bold')NEWLINE if self.color is not None:NEWLINE name.append('color=%s' % self.color)NEWLINE if self.bgcolor is not None:NEWLINE name.append('bgcolor=%s' % self.bgcolor)NEWLINE if self.wrap:NEWLINE name.append('wrap')NEWLINE if self.border is not None:NEWLINE name.append('border=%s' % self.border)NEWLINE if self.number_format is not None:NEWLINE name.append('number_format=%s' % self.number_format)NEWLINE if self.font_size is not None:NEWLINE name.append('font_size=%s' % self.font_size)NEWLINE if self.centre:NEWLINE name.append('centre')NEWLINE if self.shrink_to_fit:NEWLINE name.append('shrink_to_fit')NEWLINE name = '__'.join(name)NEWLINE if name:NEWLINE return '__%s__' % nameNEWLINE else:NEWLINE return ''NEWLINENEWLINE def style(self,item):NEWLINE """Wrap 'item' with ... tagsNEWLINENEWLINE Given a string (or object that can be rendered as a string)NEWLINE return the string representation surrounded by NEWLINE tags, where the tag attributes describe the styleNEWLINE information stored in the XLSStyle object:NEWLINENEWLINE font=boldNEWLINE color=(color)NEWLINE bgcolor=(color)NEWLINE wrapNEWLINE border=(border)NEWLINE number_format=(format)NEWLINE font_size=(size)NEWLINE centreNEWLINE shrink_to_fitNEWLINENEWLINE """NEWLINE style = []NEWLINE if self.bold:NEWLINE style.append("font=bold")NEWLINE if self.color is not None:NEWLINE style.append("color=%s" % self.color)NEWLINE if self.bgcolor is not None:NEWLINE style.append("bgcolor=%s" % self.bgcolor)NEWLINE if self.wrap:NEWLINE style.append("wrap")NEWLINE if self.border is not None:NEWLINE style.append("border=%s" % self.border)NEWLINE if self.number_format is not None:NEWLINE style.append("number_format=%s" % self.excel_number_format)NEWLINE if self.font_size is not None:NEWLINE style.append("font_size=%s" % self.font_size)NEWLINE if self.centre:NEWLINE style.append("centre")NEWLINE if self.shrink_to_fit:NEWLINE style.append("shrink_to_fit")NEWLINE if style:NEWLINE return "" % (' '.join(style),item)NEWLINE else:NEWLINE return itemNEWLINENEWLINE @propertyNEWLINE def excel_number_format(self):NEWLINE """Return an Excel-style equivalent of the stored number formatNEWLINENEWLINE Returns an Excel-style number format, or None if the formatNEWLINE isn't set or is unrecognised.NEWLINENEWLINE """NEWLINE if self.number_format == NumberFormats.THOUSAND_SEPARATOR:NEWLINE return "#,###"NEWLINE elif self.number_format == NumberFormats.PERCENTAGE:NEWLINE return "0.0%"NEWLINE return NoneNEWLINENEWLINEclass ColumnRange(Iterator):NEWLINE """Iterator for a range of column indicesNEWLINENEWLINE Range-style iterator for iterating over alphabetical columnNEWLINE indices, e.g.NEWLINENEWLINE >>> for c in ColumnRange('A','Z'):NEWLINE ... print(c)NEWLINENEWLINE """NEWLINE def __init__(self,i,j=None,include_end=True,reverse=False):NEWLINE """Create an iterator for a range of column indicesNEWLINENEWLINE Acts like 'range' i.e.:NEWLINENEWLINE ColumnRange('C'): equivalent to ['A','B','C']NEWLINE ColumnRange('C',include_end=False): ['A','B']NEWLINE ColumnRange('C','F'): ['C','D','E','F']NEWLINE ColumnRange(''C','F',include_end=False): ['C','D','E']NEWLINENEWLINE Arguments:NEWLINE i: defines start column if j is not None, orNEWLINE end column if j is not None (in which caseNEWLINE start column will be 'A')NEWLINE j: defines end column (if not None)NEWLINE include_end: if True then the end column is alsoNEWLINE included; otherwise it is omitted.NEWLINE reverse: if True then the columns are returned inNEWLINE descending orderNEWLINENEWLINE """NEWLINE self.incr = 1NEWLINE if j is None:NEWLINE self.start = column_index_to_integer('A')NEWLINE self.end = column_index_to_integer(i)NEWLINE else:NEWLINE self.start = column_index_to_integer(i)NEWLINE self.end = column_index_to_integer(j)NEWLINE if reverse:NEWLINE self.end,self.start = self.start,self.endNEWLINE self.incr = -1NEWLINE self.column = self.start-self.incrNEWLINE if include_end:NEWLINE self.end += self.incrNEWLINENEWLINE def next(self):NEWLINE """Implements Iterator subclass 'next' method (Python 2 only)NEWLINENEWLINE """NEWLINE return self.__next__()NEWLINENEWLINE def __next__(self):NEWLINE """Implements Iterator subclass '__next__' methodNEWLINENEWLINE """NEWLINE self.column = self.column + self.incrNEWLINE if self.column == self.end:NEWLINE raise StopIterationNEWLINE return column_integer_to_index(self.column)NEWLINENEWLINEclass CellIndex(object):NEWLINE """Convenience class for handling XLS-style cell indicesNEWLINENEWLINE The CellIndex class provides a way of handling XLS-styleNEWLINE cell indices i.e. 'A1', 'BZ112' etc.NEWLINENEWLINE Given a putative cell index it extracts the column andNEWLINE row which can then be accessed via the 'column' andNEWLINE 'row' attributes respectively.NEWLINENEWLINE The 'is_full' property reports whether the suppliedNEWLINE index is actually a 'full' index with both column andNEWLINE row specifiers. If it is just a column or just a rowNEWLINE then only the appropriate 'column' or 'row' attributesNEWLINE will be set.NEWLINENEWLINE """NEWLINE def __init__(self,idx):NEWLINE """Create a new CellIndex instanceNEWLINENEWLINE ArgumentsNEWLINE idx: cell index e.g. 'A1', 'BZ112'NEWLINENEWLINE """NEWLINE self.idx = str(idx)NEWLINE try:NEWLINE r = re.compile(r'^([A-Z]+)([0-9]+)$').match(idx)NEWLINE self.column = r.group(1)NEWLINE self.row = int(r.group(2))NEWLINE except:NEWLINE self.column = NoneNEWLINE self.row = NoneNEWLINE if str(idx).isalpha():NEWLINE self.column = idxNEWLINE elif str(idx).isdigit():NEWLINE self.row = int(idx)NEWLINENEWLINE @propertyNEWLINE def is_full(self):NEWLINE """Return True if index has both column and row informationNEWLINENEWLINE """ NEWLINE return not (self.column is None or self.row is None)NEWLINENEWLINE def __repr__(self):NEWLINE """Implement __repr__ built-in; returns cell indexNEWLINENEWLINE """NEWLINE return "%s%s" % ('' if self.column is None else self.column,NEWLINE '' if self.row is None else self.row)NEWLINENEWLINEclass XLSColumn(object):NEWLINE """Class representing a column in a XLSWorkSheetNEWLINENEWLINE An XLSColumn object provides access to data in a columnNEWLINE from a XLSWorkSheet object. Typically one can be returnedNEWLINE by doing something like:NEWLINENEWLINE >>> colA = ws['A']NEWLINE NEWLINE and individual cell values then accessed by row numberNEWLINE alone, e.g.:NEWLINENEWLINE >>> value = colA['1']NEWLINE >>> colA['2'] = "New value"NEWLINE NEWLINE """NEWLINE def __init__(self,column_index,parent=None):NEWLINE """Create a new XLSColumn instanceNEWLINENEWLINE ArgumentsNEWLINE column_index: column indexNEWLINE parent: parent XLSWorkSheet objectNEWLINENEWLINE """NEWLINE self.index = column_indexNEWLINE self.parent = parentNEWLINENEWLINE def __setitem__(self,idx,value):NEWLINE """Implement set item i.e. x['key'] = valueNEWLINENEWLINE """NEWLINE self.parent[self.full_index(idx)] = valueNEWLINENEWLINE def __getitem__(self,idx):NEWLINE """Implement get item i.e. y['key'] returns valueNEWLINENEWLINE """NEWLINE try:NEWLINE return self.parent[self.full_index(idx)]NEWLINE except Exception as ex:NEWLINE return NoneNEWLINENEWLINE def full_index(self,row):NEWLINE """Return the full index for a cell in the columnNEWLINENEWLINE Given a row index, returns the index of the cellNEWLINE that this addresses within the column (e.g. if theNEWLINE column is 'A' then row 2 addresses cell 'A2').NEWLINENEWLINE """NEWLINE return cell(self.index,row)NEWLINENEWLINE#######################################################################NEWLINE# FunctionsNEWLINE#######################################################################NEWLINENEWLINEdef cmp_column_indices(x,y):NEWLINE """Comparision function for column indicesNEWLINENEWLINE x and y are XLS-style column indices e.g. 'A', 'B', 'AA' etc.NEWLINENEWLINE Returns -1 if x is a column index less than y, 1 if it isNEWLINE greater than y, and 0 if it's equal.NEWLINENEWLINE """NEWLINE # Do string comparision on reverse of column indicesNEWLINE return (x[::-1] > y[::-1]) - (x[::-1] < y[::-1])NEWLINENEWLINEdef cell(col,row):NEWLINE """Return XLS cell index for column and rowNEWLINENEWLINE E.g. cell('A',3) returns 'A3'NEWLINENEWLINE """NEWLINE return "%s%s" % (col,row)NEWLINENEWLINEdef incr_col(col,incr=1):NEWLINE """Return column index incremented by specific number of positionsNEWLINENEWLINE Arguments:NEWLINE col: index of column to be incrementedNEWLINE incr: optional, number of cells to shift by. Can be negativeNEWLINE to go backwards. Defaults to 1 i.e. next column along.NEWLINENEWLINE """NEWLINE return column_integer_to_index(column_index_to_integer(col)+incr)NEWLINENEWLINEdef column_index_to_integer(col):NEWLINE """Convert XLS-style column index into equivalent integerNEWLINENEWLINE Given a column index e.g. 'A', 'BZ' etc, converts itNEWLINE to the integer equivalent using zero-based countingNEWLINE system (so 'A' is equivalent to zero, 'B' to 1 etc).NEWLINENEWLINE """NEWLINE # Convert column index e.g. 'A', 'BZ' etc toNEWLINE # integer equivalentNEWLINE idx = 0NEWLINE i = 0NEWLINE for c in col[::-1]:NEWLINE idx = idx + pow(26,i)*(ord(c)-64)NEWLINE i += 1NEWLINE return idx-1NEWLINENEWLINEdef column_integer_to_index(idx):NEWLINE """Convert integer column index to XLS-style equivalentNEWLINENEWLINE Given an integer index, converts it to the XLS-styleNEWLINE equivalent e.g. 'A', 'BZ' etc, using a zero-basedNEWLINE counting system (so zero is equivalent to 'A', 1 to 'B'NEWLINE etc).NEWLINENEWLINE """NEWLINE # Convert integer column to index equivalentNEWLINE col = ''NEWLINE while idx >= 0:NEWLINE col += chr((idx%26)+65)NEWLINE idx = idx//26-1NEWLINE return col[::-1]NEWLINENEWLINEdef eval_formula(item,worksheet):NEWLINE """Evaluate a formula using the contents of a worksheetNEWLINENEWLINE Given an item, attempts an Excel-style evaluation.NEWLINENEWLINE If the item doesn't start with '=' then it is returned as-is.NEWLINE Otherwise the function attempts to evaluate the formula,NEWLINE including looking up (and if necessary also evaluating) theNEWLINE contents of any cells that are referenced.NEWLINENEWLINE *** Note that the implementation of the evaluation is veryNEWLINE simplistic and cannot handle complex formulae or functionsNEWLINENEWLINE Currently it can only deal with:NEWLINENEWLINE * basic mathematical operations (+-*/)NEWLINENEWLINE """NEWLINE # Evaluate a formula from a cell item and return the computed valueNEWLINE logging.debug("Item is %s" % item)NEWLINE if item.startswith('='):NEWLINE item = item[1:]NEWLINE logging.debug("Item reset to %s" % item)NEWLINE else:NEWLINE logging.debug("Returning %s" % item)NEWLINE return itemNEWLINE ops = "+-/*"NEWLINE formula = ''NEWLINE arg = ''NEWLINE nargs = 0NEWLINE for c in item:NEWLINE logging.debug(c)NEWLINE if c not in ops:NEWLINE arg += cNEWLINE else:NEWLINE logging.debug("-> %s" % arg)NEWLINE if CellIndex(arg).is_full:NEWLINE arg = worksheet.render_cell(arg,eval_formulae=True)NEWLINE logging.debug("-> %s" % arg)NEWLINE try:NEWLINE arg = convert_to_number(arg) NEWLINE if c == '/':NEWLINE arg = float(arg)NEWLINE except ValueError:NEWLINE # Failed to convert to numberNEWLINE logging.debug("Error converting %s to number" % arg)NEWLINE return BAD_REFNEWLINE formula = formula + str(arg) + cNEWLINE nargs += 1NEWLINE arg = ''NEWLINE logging.debug("-> %s" % formula)NEWLINE # End of stringNEWLINE if CellIndex(arg).is_full:NEWLINE arg = worksheet.render_cell(arg,eval_formulae=True)NEWLINE if nargs:NEWLINE try:NEWLINE arg = convert_to_number(arg)NEWLINE except ValueError:NEWLINE # Failed to convert to floatNEWLINE logging.debug("Error converting %s to number" % arg)NEWLINE return BAD_REFNEWLINE else:NEWLINE # Single value was referencedNEWLINE try:NEWLINE return convert_to_number(arg)NEWLINE except ValueError:NEWLINE return argNEWLINE formula = formula + str(arg)NEWLINE logging.debug("Formula '%s'" % formula)NEWLINE if re.compile(r"^[0-9+\-\/\*]+").match(formula):NEWLINE try:NEWLINE item = eval(formula)NEWLINE except Exception as ex:NEWLINE logging.debug("Error processing %s: %s" % (item,ex))NEWLINE return BAD_REFNEWLINE else:NEWLINE item = formulaNEWLINE return itemNEWLINENEWLINEdef convert_to_number(s):NEWLINE """Convert a number to float or int as appropriateNEWLINENEWLINE Raises ValueError if neither conversion is possible.NEWLINENEWLINE """NEWLINE if is_int(s):NEWLINE return int(s)NEWLINE elif is_float(s):NEWLINE return float(s)NEWLINE raise ValueError("%s not a number?" % s)NEWLINENEWLINEdef is_float(s):NEWLINE """Test if a number is a floatNEWLINE """NEWLINE try:NEWLINE return str(float(s)) == sNEWLINE except ValueError:NEWLINE return FalseNEWLINENEWLINEdef is_int(s):NEWLINE """Test if a number is an integerNEWLINE """NEWLINE try:NEWLINE return str(int(s)) == sNEWLINE except ValueError:NEWLINE return FalseNEWLINENEWLINEdef format_value(value,number_format=None):NEWLINE """Format a cell value based on the specified number formatNEWLINENEWLINE """NEWLINE logging.debug("format_value: %s (%s) %s" % (value,type(value),number_format))NEWLINE if number_format is None:NEWLINE return str(value)NEWLINE if number_format == NumberFormats.PERCENTAGE:NEWLINE # Convert to percentageNEWLINE logging.debug("Percentage")NEWLINE return "%.1f%%" % (float(value) * 100.0)NEWLINE if number_format == NumberFormats.THOUSAND_SEPARATOR:NEWLINE # Add thousands separatorNEWLINE i = int(value)NEWLINE value = []NEWLINE while i >= 1000:NEWLINE value.append("%03d" % (i%1000))NEWLINE i = i//1000NEWLINE value.append(str(i))NEWLINE value = value[::-1]NEWLINE return ','.join(value)NEWLINE # Unknown, do nothingNEWLINE return str(value)NEWLINENEWLINE#######################################################################NEWLINE# Example usageNEWLINE#######################################################################NEWLINENEWLINEif __name__ == "__main__":NEWLINE wb = XLSWorkBook("Test")NEWLINENEWLINE wb.add_work_sheet('test')NEWLINE wb.add_work_sheet('test2')NEWLINE wb.add_work_sheet('data',"Data")NEWLINE print("%s" % wb.worksheet['test'].title)NEWLINE print("%s" % wb.worksheet['test2'].title)NEWLINE print("%s" % wb.worksheet['data'].title)NEWLINENEWLINE data = wb.worksheet['data']NEWLINE data['A1'] = "Column 1"NEWLINE print("%s" % data['A1'])NEWLINE print("%s" % data['A2'])NEWLINE print("%s" % data['A']['1'])NEWLINE data['A']['1'] = "Updated value"NEWLINE print("%s" % data['A1'])NEWLINENEWLINE data['B']['12'] = "Another value"NEWLINE data['Z']['5'] = "And another"NEWLINE data['AZ']['3'] = "Yet another"NEWLINE data['AB']['3'] = "And another again"NEWLINE NEWLINE print("%s,%s" % (data.columns,data.rows))NEWLINENEWLINE print(data.render_as_text(include_columns_and_rows=True,NEWLINE eval_formulae=True,NEWLINE include_styles=True))NEWLINENEWLINE print(data.render_as_text(start='B1',NEWLINE end='C6',NEWLINE include_columns_and_rows=True))NEWLINENEWLINE # Examples rendering into XLS and XLSX outputNEWLINE wb = XLSWorkBook("Test")NEWLINE ws = wb.add_work_sheet('test','Test')NEWLINE # TextNEWLINE ws['A1'] = "Arbitrary text"NEWLINE # FormulaNEWLINE ws['A3'] = "Formula example:"NEWLINE ws['A5'] = 2NEWLINE ws['B5'] = 5NEWLINE ws['A6'] = "Sum"NEWLINE ws['B6'] = "=A5+B5"NEWLINE # Set styles on formulaNEWLINE ws.set_style(XLSStyle(bold=True),'A6')NEWLINE ws.set_style(XLSStyle(bold=True),'B6')NEWLINE # More style examplesNEWLINE ws['A9'] = "Bold"NEWLINE ws.set_style(XLSStyle(bold=True),'A9')NEWLINE ws['A10'] = "Red"NEWLINE ws.set_style(XLSStyle(color='red'),'A10')NEWLINE ws['A11'] = "White on green"NEWLINE ws.set_style(XLSStyle(bold=True,color='white',bgcolor='green'),'A11')NEWLINE ws['A12'] = "Black on gray"NEWLINE ws.set_style(XLSStyle(bold=True,color='black',bgcolor='gray25'),'A12')NEWLINE # Freeze panesNEWLINE ws = wb.add_work_sheet('freeze','Freeze')NEWLINE ws.append_row(data=('X','Y','Z'),NEWLINE style=XLSStyle(color='white',NEWLINE bgcolor='green',NEWLINE bold=True))NEWLINE for i in range(100):NEWLINE ws.append_row(data=(i,i*2,'=A?+B?'))NEWLINE ws.freeze_panes = 'A2'NEWLINE # Save out to XLS(X) filesNEWLINE wb.save_as_xls('test.xls')NEWLINE wb.save_as_xlsx('test.xlsx')NEWLINENEWLINE from __future__ import unicode_literalsNEWLINENEWLINEfrom django.conf import settingsNEWLINEfrom django import templateNEWLINEfrom django.contrib.humanize.templatetags.humanize import intcommaNEWLINEfrom django.template.defaultfilters import stringfilterNEWLINENEWLINEfrom wagtail.wagtailcore import hooksNEWLINEfrom wagtail.wagtailcore.models import get_navigation_menu_items, UserPagePermissionsProxy, PageViewRestrictionNEWLINEfrom wagtail.wagtailcore.utils import camelcase_to_underscore, escape_scriptNEWLINEfrom wagtail.wagtailcore.utils import cautious_slugify as _cautious_slugifyNEWLINEfrom wagtail.wagtailadmin.menu import admin_menuNEWLINENEWLINEfrom wagtail.utils.pagination import DEFAULT_PAGE_KEYNEWLINENEWLINENEWLINEregister = template.Library()NEWLINENEWLINEregister.filter('intcomma', intcomma)NEWLINENEWLINE@register.inclusion_tag('wagtailadmin/shared/explorer_nav.html')NEWLINEdef explorer_nav():NEWLINE return {NEWLINE 'nodes': get_navigation_menu_items()NEWLINE }NEWLINENEWLINENEWLINE@register.inclusion_tag('wagtailadmin/shared/explorer_nav_child.html')NEWLINEdef explorer_subnav(nodes):NEWLINE return {NEWLINE 'nodes': nodesNEWLINE }NEWLINENEWLINENEWLINE@register.inclusion_tag('wagtailadmin/shared/main_nav.html', takes_context=True)NEWLINEdef main_nav(context):NEWLINE request = context['request']NEWLINENEWLINE return {NEWLINE 'menu_html': admin_menu.render_html(request),NEWLINE 'request': request,NEWLINE }NEWLINENEWLINE@register.simple_tagNEWLINEdef main_nav_js():NEWLINE return admin_menu.media['js']NEWLINENEWLINENEWLINE@register.filter("ellipsistrim")NEWLINEdef ellipsistrim(value, max_length):NEWLINE if len(value) > max_length:NEWLINE truncd_val = value[:max_length]NEWLINE if not len(value) == (max_length + 1) and value[max_length + 1] != " ":NEWLINE truncd_val = truncd_val[:truncd_val.rfind(" ")]NEWLINE return truncd_val + "..."NEWLINE return valueNEWLINENEWLINENEWLINE@register.filterNEWLINEdef fieldtype(bound_field):NEWLINE try:NEWLINE return camelcase_to_underscore(bound_field.field.__class__.__name__)NEWLINE except AttributeError:NEWLINE try:NEWLINE return camelcase_to_underscore(bound_field.__class__.__name__)NEWLINE except AttributeError:NEWLINE return ""NEWLINENEWLINENEWLINE@register.filterNEWLINEdef widgettype(bound_field):NEWLINE try:NEWLINE return camelcase_to_underscore(bound_field.field.widget.__class__.__name__)NEWLINE except AttributeError:NEWLINE try:NEWLINE return camelcase_to_underscore(bound_field.widget.__class__.__name__)NEWLINE except AttributeError:NEWLINE return ""NEWLINENEWLINENEWLINE@register.assignment_tag(takes_context=True)NEWLINEdef page_permissions(context, page):NEWLINE """NEWLINE Usage: {% page_permissions page as page_perms %}NEWLINE Sets the variable 'page_perms' to a PagePermissionTester object that can be queried to find outNEWLINE what actions the current logged-in user can perform on the given page.NEWLINE """NEWLINE # Create a UserPagePermissionsProxy object to represent the user's global permissions, andNEWLINE # cache it in the context for the duration of the page request, if one does not exist alreadyNEWLINE if 'user_page_permissions' not in context:NEWLINE context['user_page_permissions'] = UserPagePermissionsProxy(context['request'].user)NEWLINENEWLINE # Now retrieve a PagePermissionTester from it, specific to the given pageNEWLINE return context['user_page_permissions'].for_page(page)NEWLINENEWLINENEWLINE@register.assignment_tag(takes_context=True)NEWLINEdef test_page_is_public(context, page):NEWLINE """NEWLINE Usage: {% test_page_is_public page as is_public %}NEWLINE Sets 'is_public' to True iff there are no page view restrictions in place onNEWLINE this page.NEWLINE Caches the list of page view restrictions in the context, to avoid repeatedNEWLINE DB queries on repeated calls.NEWLINE """NEWLINE if 'all_page_view_restriction_paths' not in context:NEWLINE context['all_page_view_restriction_paths'] = PageViewRestriction.objects.select_related('page').values_list('page__path', flat=True)NEWLINENEWLINE is_private = any([NEWLINE page.path.startswith(restricted_path)NEWLINE for restricted_path in context['all_page_view_restriction_paths']NEWLINE ])NEWLINENEWLINE return not is_privateNEWLINENEWLINENEWLINE@register.simple_tagNEWLINEdef hook_output(hook_name):NEWLINE """NEWLINE Example: {% hook_output 'insert_editor_css' %}NEWLINE Whenever we have a hook whose functions take no parameters and return a string, this tag can be usedNEWLINE to output the concatenation of all of those return values onto the page.NEWLINE Note that the output is not escaped - it is the hook function's responsibility to escape unsafe content.NEWLINE """NEWLINE snippets = [fn() for fn in hooks.get_hooks(hook_name)]NEWLINE return ''.join(snippets)NEWLINENEWLINENEWLINE@register.assignment_tagNEWLINEdef usage_count_enabled():NEWLINE return getattr(settings, 'WAGTAIL_USAGE_COUNT_ENABLED', False)NEWLINENEWLINENEWLINE@register.assignment_tagNEWLINEdef base_url_setting():NEWLINE return getattr(settings, 'BASE_URL', None)NEWLINENEWLINENEWLINEclass EscapeScriptNode(template.Node):NEWLINE TAG_NAME = 'escapescript'NEWLINENEWLINE def __init__(self, nodelist):NEWLINE super(EscapeScriptNode, self).__init__()NEWLINE self.nodelist = nodelistNEWLINENEWLINE def render(self, context):NEWLINE out = self.nodelist.render(context)NEWLINE return escape_script(out)NEWLINENEWLINE @classmethodNEWLINE def handle(cls, parser, token):NEWLINE nodelist = parser.parse(('end' + EscapeScriptNode.TAG_NAME,))NEWLINE parser.delete_first_token()NEWLINE return cls(nodelist)NEWLINENEWLINEregister.tag(EscapeScriptNode.TAG_NAME, EscapeScriptNode.handle)NEWLINENEWLINENEWLINE# Helpers for Widget.render_with_errors, our extension to the Django widget API that allows widgets toNEWLINE# take on the responsibility of rendering their own error messagesNEWLINE@register.filterNEWLINEdef render_with_errors(bound_field):NEWLINE """NEWLINE Usage: {{ field|render_with_errors }} as opposed to {{ field }}.NEWLINE If the field (a BoundField instance) has errors on it, and the associated widget implementsNEWLINE a render_with_errors method, call that; otherwise, call the regular widget rendering mechanism.NEWLINE """NEWLINE widget = bound_field.field.widgetNEWLINE if bound_field.errors and hasattr(widget, 'render_with_errors'):NEWLINE return widget.render_with_errors(bound_field.html_name, bound_field.value(), attrs={'id': bound_field.auto_id}, errors=bound_field.errors)NEWLINE else:NEWLINE return bound_field.as_widget()NEWLINENEWLINE@register.filterNEWLINEdef has_unrendered_errors(bound_field):NEWLINE """NEWLINE Return true if this field has errors that were not accounted for by render_with_errors, becauseNEWLINE the widget does not support the render_with_errors methodNEWLINE """NEWLINE return bound_field.errors and not hasattr(bound_field.field.widget, 'render_with_errors')NEWLINENEWLINENEWLINE@register.filter(is_safe=True)NEWLINE@stringfilterNEWLINEdef cautious_slugify(value):NEWLINE return _cautious_slugify(value)NEWLINENEWLINENEWLINE@register.simple_tag(takes_context=True)NEWLINEdef querystring(context, **kwargs):NEWLINE """NEWLINE Print out the current querystring. Any keyword arguments to this templateNEWLINE tag will be added to the querystring before it is printed out.NEWLINENEWLINE NEWLINENEWLINE Will result in something like:NEWLINENEWLINE NEWLINE """NEWLINE request = context['request']NEWLINE querydict = request.GET.copy()NEWLINE # Can't do querydict.update(kwargs), because QueryDict.update() appends toNEWLINE # the list of values, instead of replacing the values.NEWLINE for key, value in kwargs.items():NEWLINE if value is None:NEWLINE # Remove the key if the value is NoneNEWLINE querydict.pop(key, None)NEWLINE else:NEWLINE # Set the key otherwiseNEWLINE querydict[key] = valueNEWLINENEWLINE return '?' + querydict.urlencode()NEWLINENEWLINENEWLINE@register.simple_tag(takes_context=True)NEWLINEdef pagination_querystring(context, page_number, page_key=DEFAULT_PAGE_KEY):NEWLINE """NEWLINE Print out a querystring with an updated page number:NEWLINENEWLINE {% if page.has_next_page %}NEWLINE Next pageNEWLINE {% endif %}NEWLINE """NEWLINE return querystring(context, **{page_key: page_number})NEWLINENEWLINENEWLINE@register.inclusion_tag("wagtailadmin/pages/listing/_pagination.html",NEWLINE takes_context=True)NEWLINEdef paginate(context, page, base_url='', page_key=DEFAULT_PAGE_KEY,NEWLINE classnames=''):NEWLINE """NEWLINE Print pagination previous/next links, and the page count. Take theNEWLINE following arguments:NEWLINENEWLINE pageNEWLINE The current page of results. This should be a Django pagination `Page`NEWLINE instanceNEWLINENEWLINE base_urlNEWLINE The base URL of the next/previous page, with no querystring.NEWLINE This is optional, and defaults to the current page by just printing theNEWLINE querystring for the next/previous page.NEWLINENEWLINE page_keyNEWLINE The name of the page variable in the query string. Defaults to the sameNEWLINE name as used in the :func:`~wagtail.utils.pagination.paginate`NEWLINE function.NEWLINENEWLINE classnamesNEWLINE Extra classes to add to the next/previous links.NEWLINE """NEWLINE request = context['request']NEWLINE return {NEWLINE 'base_url': base_url,NEWLINE 'classnames': classnames,NEWLINE 'request': request,NEWLINE 'page': page,NEWLINE 'page_key': page_key,NEWLINE 'paginator': page.paginator,NEWLINE }NEWLINE # Generated by Django 3.0.6 on 2020-05-16 05:00NEWLINENEWLINEfrom django.db import migrations, modelsNEWLINEimport django.db.models.deletionNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE initial = TrueNEWLINENEWLINE dependencies = [NEWLINE ('books', '0002_auto_20200513_0504'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.CreateModel(NEWLINE name='Inventory',NEWLINE fields=[NEWLINE ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),NEWLINE ('for_sale', models.BooleanField(default=True)),NEWLINE ('price', models.FloatField()),NEWLINE ('book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='books.Book')),NEWLINE ],NEWLINE ),NEWLINE ]NEWLINE innings_format='{team} : {total}/{wickets} || {over}|{overs}\n\t\t\t{ball_by}'NEWLINEclass matchstats:NEWLINE NEWLINE def __init__(self,mcode,team1,team2,overs):NEWLINE self.match_stats={'mcode':mcode,'date_time':None,'team1':team1,'team2':team2,'overs':overs,'status':None,'score1':[None,0,0,0,overs,None],'score2':[None,0,0,0,overs,None],'runs_to_win':None,'1st_innings':None,'2nd_innings':None}NEWLINE self.mcode=mcodeNEWLINE self.team1=team1NEWLINE self.team2=team2NEWLINE self.truns=0NEWLINE self.twickets=0NEWLINE self.over=0NEWLINE self.overs=oversNEWLINE self.score=''NEWLINE self.innings=''NEWLINE self.target=0NEWLINE self.balls=0NEWLINE NEWLINE def set_score(self,score,innings,bat):NEWLINE self.match_stats[score][0:4]=bat,self.truns,self.twickets,self.overNEWLINE score_list=self.match_stats[score]NEWLINE self.score=scoreNEWLINE self.innings=inningsNEWLINE self.match_stats[innings]=innings_format.format(team=score_list[0],total=score_list[1],wickets=score_list[2],over=score_list[3],overs=score_list[4],ball_by='')NEWLINE NEWLINE def innings_view(self):NEWLINE score_list=self.match_stats[self.score]NEWLINE self.match_stats[self.innings]=innings_format.format(team=score_list[0],total=score_list[1],wickets=score_list[2],over=score_list[3],overs=score_list[4],ball_by=score_list[5])NEWLINE NEWLINE def update_score(self,run,disp_over):NEWLINE self.truns+=runNEWLINE self.balls+=1NEWLINE self.over=disp_overNEWLINE self.match_stats[self.score][1]=self.trunsNEWLINE self.match_stats[self.score][3]=self.overNEWLINE self.innings_view()NEWLINE def update_ball_by(self,ball_by_ball):NEWLINE ball_str='['NEWLINE for ball in ball_by_ball:NEWLINE ball_str=ball_str+' '+ballNEWLINE ball_str+=']'NEWLINE self.match_stats[self.score][5]=ball_strNEWLINE self.innings_view()NEWLINE def delete_ball_by(self):NEWLINE self.match_stats[self.score][5]=''NEWLINE self.innings_view()NEWLINE NEWLINE def extras(self,run):NEWLINE self.truns+=runNEWLINE self.match_stats[self.score][1]=self.trunsNEWLINE self.innings_view()NEWLINENEWLINE def score_reset(self):NEWLINE self.truns=0NEWLINE self.over=0NEWLINE self.twickets=0NEWLINE self.balls=0NEWLINENEWLINE def calc_balls_left(self):NEWLINE balls_left=(self.overs*6)-self.ballsNEWLINE runs_to_win=self.target-self.trunsNEWLINE return balls_left,runs_to_winNEWLINE def result_check(self,balls_left):NEWLINE if self.truns>=self.target:NEWLINE return 'WIN'NEWLINE elif self.truns==(self.target-1) and balls_left==0:NEWLINE return 'DRAW'NEWLINE elif self.trunsNEWLINE# NEWLINE# This module is under the UIUC open-source license. See NEWLINE# github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txtNEWLINE# for license details.NEWLINE"""NEWLINE"""NEWLINEimport numpy as npNEWLINEfrom ._batch_bioreactor import BatchBioreactorNEWLINEfrom scipy.integrate import odeintNEWLINEfrom thermosteam.reaction import Reaction, ParallelReactionNEWLINENEWLINE__all__ = ('Fermentation',)NEWLINENEWLINEclass Fermentation(BatchBioreactor):NEWLINE """NEWLINE Create a Fermentation object which models large-scale batch fermentationNEWLINE for the production of 1st generation ethanol using yeastNEWLINE [1]_ [2]_ [3]_ [4]_. A compound with CAS 'Yeast' must be present.NEWLINE Only sucrose and glucose are taken into account for conversion.NEWLINE Conversion is based on reaction time, `tau`. Cleaning and unloading time,NEWLINE `tau_0`, fraction of working volume, `V_wf`, and number of reactors,NEWLINE `N_reactors`, are attributes that can be changed. Cost of a reactorNEWLINE is based on the NREL batch fermentation tank cost assuming volumetricNEWLINE scaling with a 6/10th exponent [5]_. NEWLINE NEWLINE ParametersNEWLINE ----------NEWLINE ins : streamsNEWLINE Inlet fluids to be mixed into the fermentor.NEWLINE outs : stream sequenceNEWLINE * [0] VentNEWLINE * [1] EffluentNEWLINE tau : floatNEWLINE Reaction time.NEWLINE N : int, optionalNEWLINE Number of batch reactorsNEWLINE V : float, optionalNEWLINE Target volume of reactors [m^3].NEWLINE T=305.15 : floatNEWLINE Temperature of reactor [K].NEWLINE P=101325 : floatNEWLINE Operating pressure of reactor [Pa].NEWLINE Nmin=2 : intNEWLINE Minimum number of fermentors.NEWLINE Nmax=36: intNEWLINE Maximum number of fermentors. NEWLINE efficiency=0.9 : float, optionalNEWLINE User enforced efficiency.NEWLINE iskinetic=False: bool, optionalNEWLINE If True, `Fermenation.kinetic_model` will be used.NEWLINE NEWLINE NotesNEWLINE -----NEWLINE Either N or V must be given.NEWLINE NEWLINE ExamplesNEWLINE --------NEWLINE Simulate a Fermentation object which models batch fermentation for theNEWLINE production of 1st generation ethanol using yeast.NEWLINE NEWLINE >>> from biorefineries.lipidcane import chemicalsNEWLINE >>> from biosteam.units import FermentationNEWLINE >>> from biosteam import Stream, settingsNEWLINE >>> settings.set_thermo(chemicals)NEWLINE >>> feed = Stream('feed',NEWLINE ... Water=1.20e+05,NEWLINE ... Glucose=1.89e+03,NEWLINE ... Sucrose=2.14e+04,NEWLINE ... DryYeast=1.03e+04,NEWLINE ... units='kg/hr',NEWLINE ... T=32+273.15)NEWLINE >>> F1 = Fermentation('F1',NEWLINE ... ins=feed, outs=('CO2', 'product'),NEWLINE ... tau=8, efficiency=0.90, N=8)NEWLINE >>> F1.simulate()NEWLINE >>> F1.show()NEWLINE Fermentation: F1NEWLINE ins...NEWLINE [0] feedNEWLINE phase: 'l', T: 305.15 K, P: 101325 PaNEWLINE flow (kmol/hr): Water 6.66e+03NEWLINE Glucose 10.5NEWLINE Sucrose 62.5NEWLINE Yeast 415NEWLINE [1] missing streamNEWLINE outs...NEWLINE [0] CO2NEWLINE phase: 'g', T: 304.19 K, P: 101325 PaNEWLINE flow (kmol/hr): Water 9.48NEWLINE Ethanol 3.52NEWLINE CO2 244NEWLINE [1] productNEWLINE phase: 'l', T: 304.19 K, P: 101325 PaNEWLINE flow (kmol/hr): Water 6.59e+03NEWLINE Ethanol 240NEWLINE Glucose 4.07NEWLINE Yeast 484NEWLINE >>> F1.results()NEWLINE Fermentation Units F1NEWLINE Power Rate kW 66.6NEWLINE Cost USD/hr 5.21NEWLINE Chilled water Duty kJ/hr -7.55e+06NEWLINE Flow kmol/hr 5.06e+03NEWLINE Cost USD/hr 37.8NEWLINE Design Reactor volume m3 247NEWLINE Batch time hr 12.6NEWLINE Loading time hr 1.57NEWLINE Number of reactors 8NEWLINE Recirculation flow rate m3/hr 17.7NEWLINE Reactor duty kJ/hr 7.55e+06NEWLINE Cleaning and unloading time hr 3NEWLINE Working volume fraction 0.9NEWLINE Purchase cost Heat exchangers USD 1.02e+05NEWLINE Reactors USD 1.87e+06NEWLINE Agitators USD 1.17e+05NEWLINE Cleaning in place USD 8.9e+04NEWLINE Recirculation pumps USD 1.26e+05NEWLINE Total purchase cost USD 2.31e+06NEWLINE Utility cost USD/hr 43NEWLINE NEWLINE ReferencesNEWLINE ----------NEWLINE .. [1] Oliveira, Samuel C., et al. "Discrimination between ethanol NEWLINE inhibition models in a continuous alcoholic fermentation process usingNEWLINE flocculating yeast." Applied biochemistry and biotechnology 74.3 (1998): 161-172.NEWLINE NEWLINE .. [2] Oliveira, Samuel C., et al. "Continuous ethanol fermentation in aNEWLINE tower reactor with flocculating yeast recycle: scale-up effects on processNEWLINE performance, kinetic parameters and model predictions." BioprocessNEWLINE Engineering 20.6 (1999): 525-530.NEWLINE NEWLINE .. [3] Oliveira, Samuel C., et al. "Mathematical modeling of a continuousNEWLINE alcoholic fermentation process in a two-stage tower reactor cascade withNEWLINE flocculating yeast recycle." Bioprocess and biosystems engineering 38.3NEWLINE (2015): 469-479.NEWLINE NEWLINE .. [4] Oliveira, Samuel C., et al. "Kinetic Modeling of 1‐G EthanolNEWLINE Fermentations." Fermentation Processes. InTech, 2017.NEWLINE NEWLINE .. [5] D. Humbird, R. Davis, L. Tao, C. Kinchin, D. Hsu, and A. AdenNEWLINE National. Renewable Energy Laboratory Golden, Colorado. P. Schoen,NEWLINE J. Lukas, B. Olthof, M. Worley, D. Sexton, and D. Dudgeon. Harris GroupNEWLINE Inc. Seattle, Washington and Atlanta, Georgia. Process Design and EconomicsNEWLINE for Biochemical Conversion of Lignocellulosic Biomass to Ethanol Dilute-AcidNEWLINE Pretreatment and Enzymatic Hydrolysis of Corn Stover. May 2011. TechnicalNEWLINE Report NREL/TP-5100-47764NEWLINE NEWLINE """NEWLINE line = 'Fermentation'NEWLINE NEWLINE #: tuple[float] Kinetic parameters for the kinetic model. Default constants are fitted for Oliveria's model (mu_m1, mu_m2, Ks1, Ks2, Pm1, Pm2, Xm, Y_PS, a)NEWLINE kinetic_constants = (0.31, # mu_m1NEWLINE 1.01, # mu_m2NEWLINE 1.88, # Ks1NEWLINE 2.81, # Ks2NEWLINE 82.8, # Pm1NEWLINE 108.2, # Pm2NEWLINE 113.4, # XmNEWLINE 0.45, # Y_PSNEWLINE 0.18) # aNEWLINE NEWLINE def __init__(self, ID='', ins=None, outs=(), thermo=None, *, NEWLINE tau, N=None, V=None, T=305.15, P=101325., Nmin=2, Nmax=36,NEWLINE efficiency=0.9, iskinetic=False):NEWLINE BatchBioreactor.__init__(self, ID, ins, outs, thermo,NEWLINE tau=tau, N=N, V=V, T=T, P=P, Nmin=Nmin, Nmax=Nmax)NEWLINE self._load_components()NEWLINE self.iskinetic = iskineticNEWLINE chemicals = self.chemicalsNEWLINE self.hydrolysis_reaction = Reaction('Sucrose + Water -> 2Glucose', 'Sucrose', 1.00, chemicals)NEWLINE self.fermentation_reaction = Reaction('Glucose -> 2Ethanol + 2CO2', 'Glucose', efficiency, chemicals)NEWLINE self.cell_growth_reaction = cell_growth = Reaction('Glucose -> Yeast', 'Glucose', 0.70, chemicals, basis='wt')NEWLINE cell_growth.basis = 'mol'NEWLINE if all([i in self.chemicals for i in ('FFA', 'DAG', 'TAG', 'Glycerol')]):NEWLINE self.lipid_reaction = self.oil_reaction = ParallelReaction([NEWLINE Reaction('TAG + 3Water -> 3FFA + Glycerol', 'TAG', 0.23, chemicals),NEWLINE Reaction('TAG + Water -> FFA + DAG', 'TAG', 0.02, chemicals)NEWLINE ])NEWLINE else:NEWLINE self.lipid_reaction = NoneNEWLINE self.efficiency = efficiencyNEWLINE NEWLINE def _calc_efficiency(self, feed, tau): # pragma: no coverNEWLINE # Get initial concentrationsNEWLINE y, e, s, w = feed.indices(['Yeast',NEWLINE '64-17-5',NEWLINE '492-61-5',NEWLINE '7732-18-5'])NEWLINE mass = feed.massNEWLINE F_vol = feed.F_volNEWLINE concentration_in = mass/F_volNEWLINE X0, P0, S0 = (concentration_in[i] for i in (y, e, s))NEWLINE NEWLINE # Integrate to get final concentrationNEWLINE t = np.linspace(0, tau, 1000)NEWLINE C_t = odeint(self.kinetic_model, (X0, P0, S0), t,NEWLINE args=self.kinetic_constants)NEWLINE # Cache dataNEWLINE self._X = C_t[:, 0]NEWLINE self._P = C_t[:, 1]NEWLINE self._S = S = C_t[:, 2]NEWLINE NEWLINE # Calculate efficiencyNEWLINE Sf = S[-1]NEWLINE Sf = Sf if Sf > 0 else 0NEWLINE Y_PS = self.kinetic_constants[-2]NEWLINE eff = (S0 - Sf)/S0 * Y_PS/0.511NEWLINE return effNEWLINE NEWLINE @staticmethodNEWLINE def kinetic_model(z, t, *kinetic_constants): # pragma: no coverNEWLINE """NEWLINE Return change of yeast, ethanol, and substrate concentration in kg/m3.NEWLINE NEWLINE ParametersNEWLINE ----------NEWLINE z : Iterable with (X, E, S) [-]:NEWLINE * X: Yeast concentration (kg/m3)NEWLINE * P: Ethanol concentration (kg/m3)NEWLINE * S: Substrate concentration (kg/m3)NEWLINE NEWLINE t : floatNEWLINE Time pointNEWLINE NEWLINE *kinetic_constantsNEWLINE * mu_m1: Maximum specific growth rate (1/hr)NEWLINE * mu_m2: Maximum specific ethanol production rate (g-product/g-cell-hr)NEWLINE * Ks1: Sugar saturation constant for growth (g/L)NEWLINE * Ks2: Sugar saturation constant for product (g/L)NEWLINE * Pm1: Maximum product concentration at zero growth [mu_m1=0] (g/L)NEWLINE * Pm2: Maximum product concentration [mu_m2=0] (g/L)NEWLINE * Xm: Maximum cell concentration [mu_m1=0] (g/L)NEWLINE * Y_PS: Ethanol yield based on sugar consumedNEWLINE * a: Toxic powerNEWLINE NEWLINE """NEWLINE mu_m1, mu_m2, Ks1, Ks2, Pm1, Pm2, Xm, Y_PS, a = kinetic_constantsNEWLINE NEWLINE # Current yeast, ethanol, and glucose concentration (kg/m3)NEWLINE X, P, S = zNEWLINE NEWLINE # Compute coefficientsNEWLINE mu_X = mu_m1 * (S/(Ks1 + S)) * (1 - P/Pm1)**a*((1-X/Xm))NEWLINE mu_P = mu_m2 * (S/(Ks2 + S)) * (1 - P/Pm2)NEWLINE mu_S = mu_P/0.45NEWLINE NEWLINE # Compute derivativesNEWLINE dXdt = mu_X * XNEWLINE dPdt = (mu_P * X)NEWLINE dSdt = - mu_S * XNEWLINE return (dXdt, dPdt, dSdt)NEWLINENEWLINE @propertyNEWLINE def efficiency(self):NEWLINE return self.fermentation_reaction.XNEWLINE @efficiency.setterNEWLINE def efficiency(self, efficiency):NEWLINE self.fermentation_reaction.X = efficiencyNEWLINENEWLINE def _run(self):NEWLINE vent, effluent = self.outsNEWLINE effluent.mix_from(self.ins)NEWLINE self.hydrolysis_reaction(effluent)NEWLINE if self.iskinetic:NEWLINE self.fermentation_reaction.X = self._calc_efficiency(effluent, self._tau)NEWLINE self.fermentation_reaction(effluent)NEWLINE self.cell_growth_reaction(effluent)NEWLINE if self.lipid_reaction: self.lipid_reaction(effluent)NEWLINE vent.empty()NEWLINE vent.receive_vent(effluent)NEWLINE #!/usr/bin/env python3NEWLINE# Copyright (c) Meta Platforms, Inc. and affiliates.NEWLINE# All rights reserved.NEWLINE#NEWLINE# This source code is licensed under the BSD-style license found in theNEWLINE# LICENSE file in the root directory of this source tree.NEWLINENEWLINEfrom typing import List, OptionalNEWLINENEWLINEimport torchNEWLINEfrom torch import nnNEWLINEfrom torchrec.modules.embedding_modules import EmbeddingBagCollectionNEWLINEfrom torchrec.modules.mlp import MLPNEWLINEfrom torchrec.sparse.jagged_tensor import (NEWLINE KeyedJaggedTensor,NEWLINE KeyedTensor,NEWLINE)NEWLINENEWLINE# Sphinx Documentation Text (for user-facing classes only)NEWLINENEWLINE"""NEWLINE.. fb:display_title::NEWLINE DLRM APINEWLINE=====NEWLINENotations uses throughout:NEWLINENEWLINEF: number of sparseFeaturesNEWLINED: embedding_dimension of sparse featuresNEWLINEB: batch_sizeNEWLINEnum_features: number of dense featuresNEWLINENEWLINE"""NEWLINENEWLINENEWLINEdef choose(n: int, k: int) -> int:NEWLINE """NEWLINE Simple implementation of math.comb for python 3.7 compatibilityNEWLINE """NEWLINE if 0 <= k <= n:NEWLINE ntok = 1NEWLINE ktok = 1NEWLINE for t in range(1, min(k, n - k) + 1):NEWLINE ntok *= nNEWLINE ktok *= tNEWLINE n -= 1NEWLINE return ntok // ktokNEWLINE else:NEWLINE return 0NEWLINENEWLINENEWLINEclass SparseArch(nn.Module):NEWLINE """NEWLINE Processes the Sparse Features of DLRM. Does Embedding Lookup for allNEWLINE EmbeddingBag and Embedding features of each collection.NEWLINENEWLINE Constructor Args:NEWLINE embedding_bag_collection: EmbeddingBagCollection,NEWLINENEWLINE Call Args:NEWLINE features: KeyedJaggedTensor,NEWLINENEWLINE Returns:NEWLINE KeyedJaggedTensor - size F * D X BNEWLINENEWLINE Example:NEWLINE >>> eb1_config = EmbeddingBagConfig(NEWLINE name="t1", embedding_dim=3, num_embeddings=10, feature_names=["f1"]NEWLINE )NEWLINE eb2_config = EmbeddingBagConfig(NEWLINE name="t2", embedding_dim=4, num_embeddings=10, feature_names=["f2"]NEWLINE )NEWLINE ebc_config = EmbeddingBagCollectionConfig(tables=[eb1_config, eb2_config])NEWLINENEWLINE ebc = EmbeddingBagCollection(config=ebc_config)NEWLINENEWLINE # 0 1 2 <-- batchNEWLINE # 0 [0,1] None [2]NEWLINE # 1 [3] [4] [5,6,7]NEWLINE # ^NEWLINE # featureNEWLINE features = KeyedJaggedTensor.from_offsets_sync(NEWLINE keys=["f1", "f2"],NEWLINE values=torch.tensor([0, 1, 2, 3, 4, 5, 6, 7]),NEWLINE offsets=torch.tensor([0, 2, 2, 3, 4, 5, 8]),NEWLINE )NEWLINENEWLINE sparse_arch(features)NEWLINE """NEWLINENEWLINE def __init__(self, embedding_bag_collection: EmbeddingBagCollection) -> None:NEWLINE super().__init__()NEWLINE self.embedding_bag_collection: EmbeddingBagCollection = embedding_bag_collectionNEWLINENEWLINE def forward(NEWLINE self,NEWLINE features: KeyedJaggedTensor,NEWLINE ) -> KeyedTensor:NEWLINE return self.embedding_bag_collection(features)NEWLINENEWLINENEWLINEclass DenseArch(nn.Module):NEWLINE """NEWLINE Processes the dense features of DLRM model.NEWLINENEWLINE Constructor Args:NEWLINE in_features: int - size of the input.NEWLINE layer_sizes: List[int] - list of layer sizes.NEWLINE device: (Optional[torch.device]).NEWLINENEWLINE Call Args:NEWLINE features: torch.Tensor - size B X num_featuresNEWLINENEWLINE Returns:NEWLINE torch.Tensor - size B X DNEWLINENEWLINE Example:NEWLINE >>> B = 20NEWLINE D = 3NEWLINE dense_arch = DenseArch(10, layer_sizes=[15, D])NEWLINE dense_embedded = dense_arch(torch.rand((B, 10)))NEWLINE """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE in_features: int,NEWLINE layer_sizes: List[int],NEWLINE device: Optional[torch.device] = None,NEWLINE ) -> None:NEWLINE super().__init__()NEWLINE self.model: nn.Module = MLP(NEWLINE in_features, layer_sizes, bias=True, activation="relu", device=deviceNEWLINE )NEWLINENEWLINE def forward(self, features: torch.Tensor) -> torch.Tensor:NEWLINE return self.model(features)NEWLINENEWLINENEWLINEclass InteractionArch(nn.Module):NEWLINE """NEWLINE Processes the output of both SparseArch (sparse_features) and DenseArchNEWLINE (dense_features). Returns the pairwise dot product of each sparse feature pair,NEWLINE the dot product of each sparse features with the output of the dense layer,NEWLINE and the dense layer itself (all concatenated).NEWLINENEWLINE NOTE: The dimensionality of the dense_features (D) is expected to match theNEWLINE dimensionality of the sparse_features so that the dot products between them can beNEWLINE computed.NEWLINENEWLINE Constructor Args:NEWLINE num_sparse_features: int - size FNEWLINENEWLINE Call Args:NEWLINE dense_features: torch.Tensor - size B X DNEWLINE sparse_features: KeyedJaggedTensor - size F * D X BNEWLINENEWLINE Returns:NEWLINE torch.Tensor - B X (D + F + F choose 2)NEWLINENEWLINE Example:NEWLINE >>> D = 3NEWLINE B = 10NEWLINE keys = ["f1", "f2"]NEWLINE F = len(keys)NEWLINE inter_arch = InteractionArch(num_sparse_features=F)NEWLINENEWLINE dense_features = torch.rand((B, D))NEWLINENEWLINE sparse_features = KeyedTensor(NEWLINE keys=keys,NEWLINE length_per_key=[D, D],NEWLINE values=torch.rand((B, D * F)),NEWLINE )NEWLINENEWLINE # B X (D + F + F choose 2)NEWLINE concat_dense = inter_arch(dense_features, sparse_features)NEWLINE """NEWLINENEWLINE def __init__(self, num_sparse_features: int) -> None:NEWLINE super().__init__()NEWLINE self.F = num_sparse_featuresNEWLINE self.triu_indices: torch.Tensor = torch.triu_indices(NEWLINE self.F + 1, self.F + 1, offset=1NEWLINE )NEWLINENEWLINE def forward(NEWLINE self, dense_features: torch.Tensor, sparse_features: KeyedTensorNEWLINE ) -> torch.Tensor:NEWLINE if self.F <= 0:NEWLINE return dense_featuresNEWLINE (B, D) = dense_features.shapeNEWLINENEWLINE sparse_values = sparse_features.values().reshape(B, self.F, D)NEWLINE combined_values = torch.cat((dense_features.unsqueeze(1), sparse_values), dim=1)NEWLINENEWLINE # dense/sparse + sparse/sparse interactionNEWLINE # size B X (F + F choose 2)NEWLINE interactions = torch.bmm(NEWLINE combined_values, torch.transpose(combined_values, 1, 2)NEWLINE )NEWLINE interactions_flat = interactions[:, self.triu_indices[0], self.triu_indices[1]]NEWLINENEWLINE return torch.cat((dense_features, interactions_flat), dim=1)NEWLINENEWLINENEWLINEclass OverArch(nn.Module):NEWLINE """NEWLINE Final Arch of DLRM - simple MLP over OverArch.NEWLINENEWLINE Constructor Args:NEWLINE in_features: intNEWLINE layer_sizes: list[int]NEWLINE device: (Optional[torch.device]).NEWLINENEWLINE Call Args:NEWLINE features: torch.TensorNEWLINENEWLINE Returns:NEWLINE torch.Tensor - size B X layer_sizes[-1]NEWLINENEWLINE Example:NEWLINE >>> B = 20NEWLINE D = 3NEWLINE over_arch = OverArch(10, [5, 1])NEWLINE logits = over_arch(torch.rand((B, 10)))NEWLINE """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE in_features: int,NEWLINE layer_sizes: List[int],NEWLINE device: Optional[torch.device] = None,NEWLINE ) -> None:NEWLINE super().__init__()NEWLINE if len(layer_sizes) <= 1:NEWLINE raise ValueError("OverArch must have multiple layers.")NEWLINE self.model: nn.Module = nn.Sequential(NEWLINE MLP(NEWLINE in_features,NEWLINE layer_sizes[:-1],NEWLINE bias=True,NEWLINE activation="relu",NEWLINE device=device,NEWLINE ),NEWLINE nn.Linear(layer_sizes[-2], layer_sizes[-1], bias=True, device=device),NEWLINE )NEWLINENEWLINE def forward(self, features: torch.Tensor) -> torch.Tensor:NEWLINE return self.model(features)NEWLINENEWLINENEWLINEclass DLRM(nn.Module):NEWLINE """NEWLINE Recsys model from "Deep Learning Recommendation Model for Personalization andNEWLINE Recommendation Systems" (https://arxiv.org/abs/1906.00091). Processes sparseNEWLINE features by learning pooled embeddings for each feature. Learns the relationshipNEWLINE between dense features and sparse features by projecting dense features into theNEWLINE same embedding space. Also, learns the pairwise relationships between sparseNEWLINE features.NEWLINENEWLINE The module assumes all sparse features have the same embedding dimensionNEWLINE (i.e, each EmbeddingBagConfig uses the same embedding_dim)NEWLINENEWLINE Constructor Args:NEWLINE embedding_bag_collection (EmbeddingBagCollection): collection of embedding bagsNEWLINE used to define SparseArch.NEWLINE dense_in_features (int): the dimensionality of the dense input features.NEWLINE dense_arch_layer_sizes (list[int]): the layer sizes for the DenseArch.NEWLINE over_arch_layer_sizes (list[int]): the layer sizes for the OverArch. NOTE: TheNEWLINE output dimension of the InteractionArch should not be manually specifiedNEWLINE here.NEWLINE dense_device: (Optional[torch.device]).NEWLINENEWLINE Call Args:NEWLINE dense_features: torch.Tensor,NEWLINE sparse_features: KeyedJaggedTensor,NEWLINENEWLINE Returns:NEWLINE torch.Tensor - logits with size B X 1NEWLINENEWLINE Example:NEWLINE >>> B = 2NEWLINE D = 8NEWLINENEWLINE eb1_config = EmbeddingBagConfig(NEWLINE name="t1", embedding_dim=D, num_embeddings=100, feature_names=["f1", "f3"]NEWLINE )NEWLINE eb2_config = EmbeddingBagConfig(NEWLINE name="t2",NEWLINE embedding_dim=D,NEWLINE num_embeddings=100,NEWLINE feature_names=["f2"],NEWLINE )NEWLINE ebc_config = EmbeddingBagCollectionConfig(tables=[eb1_config, eb2_config])NEWLINENEWLINE ebc = EmbeddingBagCollection(config=ebc_config)NEWLINE model = DLRM(NEWLINE embedding_bag_collection=ebc,NEWLINE dense_in_features=100,NEWLINE dense_arch_layer_sizes=[20],NEWLINE over_arch_layer_sizes=[5, 1],NEWLINE )NEWLINENEWLINE features = torch.rand((B, 100))NEWLINENEWLINE # 0 1NEWLINE # 0 [1,2] [4,5]NEWLINE # 1 [4,3] [2,9]NEWLINE # ^NEWLINE # featureNEWLINE sparse_features = KeyedJaggedTensor.from_offsets_sync(NEWLINE keys=["f1", "f3"],NEWLINE values=torch.tensor([1, 2, 4, 5, 4, 3, 2, 9]),NEWLINE offsets=torch.tensor([0, 2, 4, 6, 8]),NEWLINE )NEWLINENEWLINE logits = model(NEWLINE dense_features=features,NEWLINE sparse_features=sparse_features,NEWLINE )NEWLINE """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE embedding_bag_collection: EmbeddingBagCollection,NEWLINE dense_in_features: int,NEWLINE dense_arch_layer_sizes: List[int],NEWLINE over_arch_layer_sizes: List[int],NEWLINE dense_device: Optional[torch.device] = None,NEWLINE ) -> None:NEWLINE super().__init__()NEWLINE assert (NEWLINE len(embedding_bag_collection.embedding_bag_configs) > 0NEWLINE ), "At least one embedding bag is required"NEWLINE for i in range(1, len(embedding_bag_collection.embedding_bag_configs)):NEWLINE conf_prev = embedding_bag_collection.embedding_bag_configs[i - 1]NEWLINE conf = embedding_bag_collection.embedding_bag_configs[i]NEWLINE assert (NEWLINE conf_prev.embedding_dim == conf.embedding_dimNEWLINE ), "All EmbeddingBagConfigs must have the same dimension"NEWLINE embedding_dim: int = embedding_bag_collection.embedding_bag_configs[NEWLINE 0NEWLINE ].embedding_dimNEWLINE if dense_arch_layer_sizes[-1] != embedding_dim:NEWLINE raise ValueError(NEWLINE f"embedding_bag_collection dimension ({embedding_dim}) and final dense "NEWLINE "arch layer size ({dense_arch_layer_sizes[-1]}) must match."NEWLINE )NEWLINENEWLINE num_feature_names = sum(NEWLINE [NEWLINE len(conf.feature_names)NEWLINE for conf in embedding_bag_collection.embedding_bag_configsNEWLINE ]NEWLINE )NEWLINENEWLINE over_in_features = (NEWLINE embedding_dim + choose(num_feature_names, 2) + num_feature_namesNEWLINE )NEWLINENEWLINE self.sparse_arch = SparseArch(embedding_bag_collection)NEWLINE self.dense_arch = DenseArch(NEWLINE in_features=dense_in_features,NEWLINE layer_sizes=dense_arch_layer_sizes,NEWLINE device=dense_device,NEWLINE )NEWLINE self.inter_arch = InteractionArch(num_sparse_features=num_feature_names)NEWLINE self.over_arch = OverArch(NEWLINE in_features=over_in_features,NEWLINE layer_sizes=over_arch_layer_sizes,NEWLINE device=dense_device,NEWLINE )NEWLINENEWLINE def forward(NEWLINE self,NEWLINE dense_features: torch.Tensor,NEWLINE sparse_features: KeyedJaggedTensor,NEWLINE ) -> torch.Tensor:NEWLINE embedded_dense = self.dense_arch(dense_features)NEWLINE embedded_sparse = self.sparse_arch(sparse_features)NEWLINE concatenated_dense = self.inter_arch(NEWLINE dense_features=embedded_dense, sparse_features=embedded_sparseNEWLINE )NEWLINE logits = self.over_arch(concatenated_dense)NEWLINE return logitsNEWLINE #!/usr/bin/env python2NEWLINEimport numpy as npNEWLINEimport path_parserNEWLINEfrom mpl_toolkits.mplot3d import Axes3DNEWLINEimport matplotlib.pyplot as pltNEWLINEfrom matplotlib import cmNEWLINEfrom matplotlib.ticker import LinearLocator, FormatStrFormatterNEWLINEfrom scipy.spatial import KDTreeNEWLINE#ruta='sample_map_origin_map.txt'NEWLINEruta='Trayectoria3.txt'NEWLINENEWLINEdef main():NEWLINE arr_in=np.array(list(path_parser.read_points(ruta)))NEWLINE print arr_inNEWLINEif __name__ == '__main__':NEWLINE main() # Copyright 2015 The Chromium Authors. All rights reserved.NEWLINE# Use of this source code is governed by a BSD-style license that can beNEWLINE# found in the LICENSE file.NEWLINE"""Determines support level for different steps for masters."""NEWLINENEWLINEfrom services.deps import GetOSPlatformNameNEWLINEfrom model.wf_config import FinditConfigNEWLINENEWLINE# Explicitly list unsupported masters. Additional work might be needed in orderNEWLINE# to support them.NEWLINE_UNSUPPORTED_MASTERS = [NEWLINE 'chromium.lkgr', # Disable as results are not showed on Sheriff-o-Matic.NEWLINE 'chromium.gpu', # Disable as too many false positives.NEWLINE 'chromium.memory.fyi',NEWLINE 'chromium.gpu.fyi',NEWLINE 'chromium.perf',NEWLINE]NEWLINENEWLINENEWLINEdef _ConvertOldMastersFormatToNew(masters_to_disallowed_steps):NEWLINE """Converts the old masters format to the new rules dict.NEWLINENEWLINE Args:NEWLINE masters_to_disallowed_steps: A dict in the format:NEWLINE {NEWLINE 'master1': ['step1', 'step2', ...],NEWLINE 'master2': ['step3', 'step4', ...]NEWLINE }NEWLINENEWLINE Returns:NEWLINE A dict in the latest rules dict format:NEWLINE {NEWLINE 'supported_masters': {NEWLINE 'master1': {NEWLINE 'unsupported_steps: ['step1', 'step2', ...], (if any)NEWLINE }NEWLINE },NEWLINE 'global': {}NEWLINE }NEWLINE """NEWLINE supported_masters = {}NEWLINE steps_for_masters_rules_in_latest_format = {NEWLINE 'supported_masters': supported_masters,NEWLINE 'global': {}NEWLINE }NEWLINENEWLINE for master, unsupported_steps in masters_to_disallowed_steps.iteritems():NEWLINE supported_masters[master] = {}NEWLINE if unsupported_steps:NEWLINE supported_masters[master]['unsupported_steps'] = unsupported_stepsNEWLINENEWLINE return steps_for_masters_rules_in_latest_formatNEWLINENEWLINENEWLINEdef GetStepsForMastersRules(settings=None, version=None):NEWLINE if settings is None:NEWLINE settings = FinditConfig.Get(version)NEWLINE return (settings.steps_for_masters_rules orNEWLINE _ConvertOldMastersFormatToNew(settings.masters_to_disallowed_steps))NEWLINENEWLINENEWLINEdef MasterIsSupported(master_name):NEWLINE """Returns ``True`` if the given master is supported, otherwise ``False``."""NEWLINE return master_name in GetStepsForMastersRules()['supported_masters']NEWLINENEWLINENEWLINEdef StepIsSupportedForMaster(step_name, master_name):NEWLINE """Determines whether or not a step is supported for the given build master.NEWLINENEWLINE Args:NEWLINE step_name: The name of the step to check.NEWLINE master_name: The name of the build master to check.NEWLINENEWLINE Returns:NEWLINE True if Findit supports analyzing the failure, False otherwise.NEWLINE Rules:NEWLINE 1. If a master is not supported, then neither are any of its steps.NEWLINE 2. If a master specifies check_global = True, then all of its steps areNEWLINE supported except those according to those blacklisted under global.NEWLINE 3. If a master specifies check_global = True, but also specifies aNEWLINE supported_steps, then supported_steps is to override any blacklistedNEWLINE steps under global.NEWLINE 4. If a master specifies check_global = True, but also species its ownNEWLINE unsupported_list, those unsupported_steps are in addition to thoseNEWLINE under global.NEWLINE 5. If a master specifies check_global = False, then all steps underNEWLINE 'supported_steps' are always supported and nothing else.NEWLINE 'unsupported_steps' is not allowed.NEWLINE """NEWLINE if not MasterIsSupported(master_name):NEWLINE return FalseNEWLINENEWLINE steps_for_masters_rules = GetStepsForMastersRules()NEWLINE supported_masters = steps_for_masters_rules['supported_masters']NEWLINENEWLINE supported_master = supported_masters[master_name]NEWLINE check_global = supported_master.get('check_global', True)NEWLINENEWLINE if not check_global:NEWLINE supported_steps = supported_master['supported_steps']NEWLINE return step_name in supported_stepsNEWLINENEWLINE supported_steps = supported_master.get('supported_steps', [])NEWLINE unsupported_steps = supported_master.get('unsupported_steps', [])NEWLINE global_unsupported_steps = (NEWLINE steps_for_masters_rules['global'].get('unsupported_steps', []))NEWLINENEWLINE return (step_name in supported_steps orNEWLINE (step_name not in unsupported_steps andNEWLINE step_name not in global_unsupported_steps))NEWLINENEWLINENEWLINEdef EnableStrictRegexForCompileLinkFailures(wf_mastername, wf_buildername):NEWLINE """Returns True if strict regex should be used for the given builder."""NEWLINE trybot_config = FinditConfig.Get().builders_to_trybots.get(NEWLINE wf_mastername, {}).get(wf_buildername, {})NEWLINE return trybot_config.get('strict_regex', False)NEWLINENEWLINENEWLINEdef ShouldSkipTestTryJobs(wf_mastername, wf_buildername):NEWLINE """Returns True if test try jobs should be triggered.NEWLINENEWLINE By default, test try jobs should be supported unless the master/builderNEWLINE specifies to bail out.NEWLINENEWLINE Args:NEWLINE wf_mastername: The mastername of a waterfall builder.NEWLINE wf_buildername: The buildername of a waterfall builder.NEWLINENEWLINE Returns:NEWLINE True if test try jobs are to be skipped, False otherwise.NEWLINE """NEWLINE trybot_config = FinditConfig.Get().builders_to_trybots.get(NEWLINE wf_mastername, {}).get(wf_buildername, {})NEWLINE return trybot_config.get('not_run_tests', False)NEWLINENEWLINENEWLINEdef GetTryJobSettings():NEWLINE return FinditConfig().Get().try_job_settingsNEWLINENEWLINENEWLINEdef GetSwarmingSettings():NEWLINE return FinditConfig().Get().swarming_settingsNEWLINENEWLINENEWLINEdef GetDownloadBuildDataSettings():NEWLINE return FinditConfig().Get().download_build_data_settingsNEWLINENEWLINENEWLINEdef GetActionSettings():NEWLINE return FinditConfig().Get().action_settingsNEWLINENEWLINENEWLINEdef GetCheckFlakeSettings():NEWLINE return FinditConfig().Get().check_flake_settingsNEWLINENEWLINENEWLINEdef GetFlakeDetectionSettings():NEWLINE return FinditConfig.Get().flake_detection_settingsNEWLINENEWLINENEWLINEdef GetCodeCoverageSettings():NEWLINE return FinditConfig().Get().code_coverage_settingsNEWLINENEWLINENEWLINEdef GetCodeReviewSettings():NEWLINE return FinditConfig().Get().code_review_settingsNEWLINE # coding: utf-8NEWLINENEWLINE"""NEWLINE SendinBlue APINEWLINENEWLINE SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at https://github.com/orgs/sendinblue **Possible responses** | Code | Message | | :-------------: | ------------- | | 200 | OK. Successful Request | | 201 | OK. Successful Creation | | 202 | OK. Request accepted | | 204 | OK. Successful Update/Deletion | | 400 | Error. Bad Request | | 401 | Error. Authentication Needed | | 402 | Error. Not enough credit, plan upgrade needed | | 403 | Error. Permission denied | | 404 | Error. Object does not exist | | 405 | Error. Method not allowed | | 406 | Error. Not Acceptable | # noqa: E501NEWLINENEWLINE OpenAPI spec version: 3.0.0NEWLINE Contact: contact@sendinblue.comNEWLINE Generated by: https://github.com/swagger-api/swagger-codegen.gitNEWLINE"""NEWLINENEWLINENEWLINEimport pprintNEWLINEimport re # noqa: F401NEWLINENEWLINEimport sixNEWLINENEWLINENEWLINEclass GetSmsCampaigns(object):NEWLINE """NOTE: This class is auto generated by the swagger code generator program.NEWLINENEWLINE Do not edit the class manually.NEWLINE """NEWLINENEWLINE """NEWLINE Attributes:NEWLINE swagger_types (dict): The key is attribute nameNEWLINE and the value is attribute type.NEWLINE attribute_map (dict): The key is attribute nameNEWLINE and the value is json key in definition.NEWLINE """NEWLINE swagger_types = {NEWLINE 'campaigns': 'list[object]',NEWLINE 'count': 'int'NEWLINE }NEWLINENEWLINE attribute_map = {NEWLINE 'campaigns': 'campaigns',NEWLINE 'count': 'count'NEWLINE }NEWLINENEWLINE def __init__(self, campaigns=None, count=None): # noqa: E501NEWLINE """GetSmsCampaigns - a model defined in Swagger""" # noqa: E501NEWLINENEWLINE self._campaigns = NoneNEWLINE self._count = NoneNEWLINE self.discriminator = NoneNEWLINENEWLINE if campaigns is not None:NEWLINE self.campaigns = campaignsNEWLINE if count is not None:NEWLINE self.count = countNEWLINENEWLINE @propertyNEWLINE def campaigns(self):NEWLINE """Gets the campaigns of this GetSmsCampaigns. # noqa: E501NEWLINENEWLINENEWLINE :return: The campaigns of this GetSmsCampaigns. # noqa: E501NEWLINE :rtype: list[object]NEWLINE """NEWLINE return self._campaignsNEWLINENEWLINE @campaigns.setterNEWLINE def campaigns(self, campaigns):NEWLINE """Sets the campaigns of this GetSmsCampaigns.NEWLINENEWLINENEWLINE :param campaigns: The campaigns of this GetSmsCampaigns. # noqa: E501NEWLINE :type: list[object]NEWLINE """NEWLINENEWLINE self._campaigns = campaignsNEWLINENEWLINE @propertyNEWLINE def count(self):NEWLINE """Gets the count of this GetSmsCampaigns. # noqa: E501NEWLINENEWLINE Number of SMS campaigns retrieved # noqa: E501NEWLINENEWLINE :return: The count of this GetSmsCampaigns. # noqa: E501NEWLINE :rtype: intNEWLINE """NEWLINE return self._countNEWLINENEWLINE @count.setterNEWLINE def count(self, count):NEWLINE """Sets the count of this GetSmsCampaigns.NEWLINENEWLINE Number of SMS campaigns retrieved # noqa: E501NEWLINENEWLINE :param count: The count of this GetSmsCampaigns. # noqa: E501NEWLINE :type: intNEWLINE """NEWLINENEWLINE self._count = countNEWLINENEWLINE def to_dict(self):NEWLINE """Returns the model properties as a dict"""NEWLINE result = {}NEWLINENEWLINE for attr, _ in six.iteritems(self.swagger_types):NEWLINE value = getattr(self, attr)NEWLINE if isinstance(value, list):NEWLINE result[attr] = list(map(NEWLINE lambda x: x.to_dict() if hasattr(x, "to_dict") else x,NEWLINE valueNEWLINE ))NEWLINE elif hasattr(value, "to_dict"):NEWLINE result[attr] = value.to_dict()NEWLINE elif isinstance(value, dict):NEWLINE result[attr] = dict(map(NEWLINE lambda item: (item[0], item[1].to_dict())NEWLINE if hasattr(item[1], "to_dict") else item,NEWLINE value.items()NEWLINE ))NEWLINE else:NEWLINE result[attr] = valueNEWLINE if issubclass(GetSmsCampaigns, dict):NEWLINE for key, value in self.items():NEWLINE result[key] = valueNEWLINENEWLINE return resultNEWLINENEWLINE def to_str(self):NEWLINE """Returns the string representation of the model"""NEWLINE return pprint.pformat(self.to_dict())NEWLINENEWLINE def __repr__(self):NEWLINE """For `print` and `pprint`"""NEWLINE return self.to_str()NEWLINENEWLINE def __eq__(self, other):NEWLINE """Returns true if both objects are equal"""NEWLINE if not isinstance(other, GetSmsCampaigns):NEWLINE return FalseNEWLINENEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Returns true if both objects are not equal"""NEWLINE return not self == otherNEWLINE # coding=utf-8NEWLINE"""NEWLINEThis code was generated byNEWLINE\ / _ _ _| _ _NEWLINE | (_)\/(_)(_|\/| |(/_ v1.0.0NEWLINE / /NEWLINE"""NEWLINENEWLINEfrom twilio.base import deserializeNEWLINEfrom twilio.base import valuesNEWLINEfrom twilio.base.instance_context import InstanceContextNEWLINEfrom twilio.base.instance_resource import InstanceResourceNEWLINEfrom twilio.base.list_resource import ListResourceNEWLINEfrom twilio.base.page import PageNEWLINENEWLINENEWLINEclass KeyList(ListResource):NEWLINE """ """NEWLINENEWLINE def __init__(self, version, account_sid):NEWLINE """NEWLINE Initialize the KeyListNEWLINENEWLINE :param Version version: Version that contains the resourceNEWLINE :param account_sid: A 34 character string that uniquely identifies this resource.NEWLINENEWLINE :returns: twilio.rest.api.v2010.account.key.KeyListNEWLINE :rtype: twilio.rest.api.v2010.account.key.KeyListNEWLINE """NEWLINE super(KeyList, self).__init__(version)NEWLINENEWLINE # Path SolutionNEWLINE self._solution = {'account_sid': account_sid, }NEWLINE self._uri = '/Accounts/{account_sid}/Keys.json'.format(**self._solution)NEWLINENEWLINE def stream(self, limit=None, page_size=None):NEWLINE """NEWLINE Streams KeyInstance records from the API as a generator stream.NEWLINE This operation lazily loads records as efficiently as possible until the limitNEWLINE is reached.NEWLINE The results are returned as a generator, so this operation is memory efficient.NEWLINENEWLINE :param int limit: Upper limit for the number of records to return. stream()NEWLINE guarantees to never return more than limit. Default is no limitNEWLINE :param int page_size: Number of records to fetch per request, when not set will useNEWLINE the default value of 50 records. If no page_size is definedNEWLINE but a limit is defined, stream() will attempt to read theNEWLINE limit with the most efficient page size, i.e. min(limit, 1000)NEWLINENEWLINE :returns: Generator that will yield up to limit resultsNEWLINE :rtype: list[twilio.rest.api.v2010.account.key.KeyInstance]NEWLINE """NEWLINE limits = self._version.read_limits(limit, page_size)NEWLINENEWLINE page = self.page(page_size=limits['page_size'], )NEWLINENEWLINE return self._version.stream(page, limits['limit'], limits['page_limit'])NEWLINENEWLINE def list(self, limit=None, page_size=None):NEWLINE """NEWLINE Lists KeyInstance records from the API as a list.NEWLINE Unlike stream(), this operation is eager and will load `limit` records intoNEWLINE memory before returning.NEWLINENEWLINE :param int limit: Upper limit for the number of records to return. list() guaranteesNEWLINE never to return more than limit. Default is no limitNEWLINE :param int page_size: Number of records to fetch per request, when not set will useNEWLINE the default value of 50 records. If no page_size is definedNEWLINE but a limit is defined, list() will attempt to read the limitNEWLINE with the most efficient page size, i.e. min(limit, 1000)NEWLINENEWLINE :returns: Generator that will yield up to limit resultsNEWLINE :rtype: list[twilio.rest.api.v2010.account.key.KeyInstance]NEWLINE """NEWLINE return list(self.stream(limit=limit, page_size=page_size, ))NEWLINENEWLINE def page(self, page_token=values.unset, page_number=values.unset,NEWLINE page_size=values.unset):NEWLINE """NEWLINE Retrieve a single page of KeyInstance records from the API.NEWLINE Request is executed immediatelyNEWLINENEWLINE :param str page_token: PageToken provided by the APINEWLINE :param int page_number: Page Number, this value is simply for client stateNEWLINE :param int page_size: Number of records to return, defaults to 50NEWLINENEWLINE :returns: Page of KeyInstanceNEWLINE :rtype: twilio.rest.api.v2010.account.key.KeyPageNEWLINE """NEWLINE params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })NEWLINENEWLINE response = self._version.page(NEWLINE 'GET',NEWLINE self._uri,NEWLINE params=params,NEWLINE )NEWLINENEWLINE return KeyPage(self._version, response, self._solution)NEWLINENEWLINE def get_page(self, target_url):NEWLINE """NEWLINE Retrieve a specific page of KeyInstance records from the API.NEWLINE Request is executed immediatelyNEWLINENEWLINE :param str target_url: API-generated URL for the requested results pageNEWLINENEWLINE :returns: Page of KeyInstanceNEWLINE :rtype: twilio.rest.api.v2010.account.key.KeyPageNEWLINE """NEWLINE response = self._version.domain.twilio.request(NEWLINE 'GET',NEWLINE target_url,NEWLINE )NEWLINENEWLINE return KeyPage(self._version, response, self._solution)NEWLINENEWLINE def get(self, sid):NEWLINE """NEWLINE Constructs a KeyContextNEWLINENEWLINE :param sid: The unique string that identifies the resourceNEWLINENEWLINE :returns: twilio.rest.api.v2010.account.key.KeyContextNEWLINE :rtype: twilio.rest.api.v2010.account.key.KeyContextNEWLINE """NEWLINE return KeyContext(self._version, account_sid=self._solution['account_sid'], sid=sid, )NEWLINENEWLINE def __call__(self, sid):NEWLINE """NEWLINE Constructs a KeyContextNEWLINENEWLINE :param sid: The unique string that identifies the resourceNEWLINENEWLINE :returns: twilio.rest.api.v2010.account.key.KeyContextNEWLINE :rtype: twilio.rest.api.v2010.account.key.KeyContextNEWLINE """NEWLINE return KeyContext(self._version, account_sid=self._solution['account_sid'], sid=sid, )NEWLINENEWLINE def __repr__(self):NEWLINE """NEWLINE Provide a friendly representationNEWLINENEWLINE :returns: Machine friendly representationNEWLINE :rtype: strNEWLINE """NEWLINE return ''NEWLINENEWLINENEWLINEclass KeyPage(Page):NEWLINE """ """NEWLINENEWLINE def __init__(self, version, response, solution):NEWLINE """NEWLINE Initialize the KeyPageNEWLINENEWLINE :param Version version: Version that contains the resourceNEWLINE :param Response response: Response from the APINEWLINE :param account_sid: A 34 character string that uniquely identifies this resource.NEWLINENEWLINE :returns: twilio.rest.api.v2010.account.key.KeyPageNEWLINE :rtype: twilio.rest.api.v2010.account.key.KeyPageNEWLINE """NEWLINE super(KeyPage, self).__init__(version, response)NEWLINENEWLINE # Path SolutionNEWLINE self._solution = solutionNEWLINENEWLINE def get_instance(self, payload):NEWLINE """NEWLINE Build an instance of KeyInstanceNEWLINENEWLINE :param dict payload: Payload response from the APINEWLINENEWLINE :returns: twilio.rest.api.v2010.account.key.KeyInstanceNEWLINE :rtype: twilio.rest.api.v2010.account.key.KeyInstanceNEWLINE """NEWLINE return KeyInstance(self._version, payload, account_sid=self._solution['account_sid'], )NEWLINENEWLINE def __repr__(self):NEWLINE """NEWLINE Provide a friendly representationNEWLINENEWLINE :returns: Machine friendly representationNEWLINE :rtype: strNEWLINE """NEWLINE return ''NEWLINENEWLINENEWLINEclass KeyContext(InstanceContext):NEWLINE """ """NEWLINENEWLINE def __init__(self, version, account_sid, sid):NEWLINE """NEWLINE Initialize the KeyContextNEWLINENEWLINE :param Version version: Version that contains the resourceNEWLINE :param account_sid: The SID of the Account that created the resource to fetchNEWLINE :param sid: The unique string that identifies the resourceNEWLINENEWLINE :returns: twilio.rest.api.v2010.account.key.KeyContextNEWLINE :rtype: twilio.rest.api.v2010.account.key.KeyContextNEWLINE """NEWLINE super(KeyContext, self).__init__(version)NEWLINENEWLINE # Path SolutionNEWLINE self._solution = {'account_sid': account_sid, 'sid': sid, }NEWLINE self._uri = '/Accounts/{account_sid}/Keys/{sid}.json'.format(**self._solution)NEWLINENEWLINE def fetch(self):NEWLINE """NEWLINE Fetch a KeyInstanceNEWLINENEWLINE :returns: Fetched KeyInstanceNEWLINE :rtype: twilio.rest.api.v2010.account.key.KeyInstanceNEWLINE """NEWLINE params = values.of({})NEWLINENEWLINE payload = self._version.fetch(NEWLINE 'GET',NEWLINE self._uri,NEWLINE params=params,NEWLINE )NEWLINENEWLINE return KeyInstance(NEWLINE self._version,NEWLINE payload,NEWLINE account_sid=self._solution['account_sid'],NEWLINE sid=self._solution['sid'],NEWLINE )NEWLINENEWLINE def update(self, friendly_name=values.unset):NEWLINE """NEWLINE Update the KeyInstanceNEWLINENEWLINE :param unicode friendly_name: A string to describe the resourceNEWLINENEWLINE :returns: Updated KeyInstanceNEWLINE :rtype: twilio.rest.api.v2010.account.key.KeyInstanceNEWLINE """NEWLINE data = values.of({'FriendlyName': friendly_name, })NEWLINENEWLINE payload = self._version.update(NEWLINE 'POST',NEWLINE self._uri,NEWLINE data=data,NEWLINE )NEWLINENEWLINE return KeyInstance(NEWLINE self._version,NEWLINE payload,NEWLINE account_sid=self._solution['account_sid'],NEWLINE sid=self._solution['sid'],NEWLINE )NEWLINENEWLINE def delete(self):NEWLINE """NEWLINE Deletes the KeyInstanceNEWLINENEWLINE :returns: True if delete succeeds, False otherwiseNEWLINE :rtype: boolNEWLINE """NEWLINE return self._version.delete('delete', self._uri)NEWLINENEWLINE def __repr__(self):NEWLINE """NEWLINE Provide a friendly representationNEWLINENEWLINE :returns: Machine friendly representationNEWLINE :rtype: strNEWLINE """NEWLINE context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())NEWLINE return ''.format(context)NEWLINENEWLINENEWLINEclass KeyInstance(InstanceResource):NEWLINE """ """NEWLINENEWLINE def __init__(self, version, payload, account_sid, sid=None):NEWLINE """NEWLINE Initialize the KeyInstanceNEWLINENEWLINE :returns: twilio.rest.api.v2010.account.key.KeyInstanceNEWLINE :rtype: twilio.rest.api.v2010.account.key.KeyInstanceNEWLINE """NEWLINE super(KeyInstance, self).__init__(version)NEWLINENEWLINE # Marshaled PropertiesNEWLINE self._properties = {NEWLINE 'sid': payload['sid'],NEWLINE 'friendly_name': payload['friendly_name'],NEWLINE 'date_created': deserialize.rfc2822_datetime(payload['date_created']),NEWLINE 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']),NEWLINE }NEWLINENEWLINE # ContextNEWLINE self._context = NoneNEWLINE self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], }NEWLINENEWLINE @propertyNEWLINE def _proxy(self):NEWLINE """NEWLINE Generate an instance context for the instance, the context is capable ofNEWLINE performing various actions. All instance actions are proxied to the contextNEWLINENEWLINE :returns: KeyContext for this KeyInstanceNEWLINE :rtype: twilio.rest.api.v2010.account.key.KeyContextNEWLINE """NEWLINE if self._context is None:NEWLINE self._context = KeyContext(NEWLINE self._version,NEWLINE account_sid=self._solution['account_sid'],NEWLINE sid=self._solution['sid'],NEWLINE )NEWLINE return self._contextNEWLINENEWLINE @propertyNEWLINE def sid(self):NEWLINE """NEWLINE :returns: The unique string that identifies the resourceNEWLINE :rtype: unicodeNEWLINE """NEWLINE return self._properties['sid']NEWLINENEWLINE @propertyNEWLINE def friendly_name(self):NEWLINE """NEWLINE :returns: The string that you assigned to describe the resourceNEWLINE :rtype: unicodeNEWLINE """NEWLINE return self._properties['friendly_name']NEWLINENEWLINE @propertyNEWLINE def date_created(self):NEWLINE """NEWLINE :returns: The RFC 2822 date and time in GMT that the resource was createdNEWLINE :rtype: datetimeNEWLINE """NEWLINE return self._properties['date_created']NEWLINENEWLINE @propertyNEWLINE def date_updated(self):NEWLINE """NEWLINE :returns: The RFC 2822 date and time in GMT that the resource was last updatedNEWLINE :rtype: datetimeNEWLINE """NEWLINE return self._properties['date_updated']NEWLINENEWLINE def fetch(self):NEWLINE """NEWLINE Fetch a KeyInstanceNEWLINENEWLINE :returns: Fetched KeyInstanceNEWLINE :rtype: twilio.rest.api.v2010.account.key.KeyInstanceNEWLINE """NEWLINE return self._proxy.fetch()NEWLINENEWLINE def update(self, friendly_name=values.unset):NEWLINE """NEWLINE Update the KeyInstanceNEWLINENEWLINE :param unicode friendly_name: A string to describe the resourceNEWLINENEWLINE :returns: Updated KeyInstanceNEWLINE :rtype: twilio.rest.api.v2010.account.key.KeyInstanceNEWLINE """NEWLINE return self._proxy.update(friendly_name=friendly_name, )NEWLINENEWLINE def delete(self):NEWLINE """NEWLINE Deletes the KeyInstanceNEWLINENEWLINE :returns: True if delete succeeds, False otherwiseNEWLINE :rtype: boolNEWLINE """NEWLINE return self._proxy.delete()NEWLINENEWLINE def __repr__(self):NEWLINE """NEWLINE Provide a friendly representationNEWLINENEWLINE :returns: Machine friendly representationNEWLINE :rtype: strNEWLINE """NEWLINE context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())NEWLINE return ''.format(context)NEWLINE #!/usr/bin/env python3NEWLINE# Copyright (c) 2014-2020 The Vadercoin Core developersNEWLINE# Distributed under the MIT software license, see the accompanyingNEWLINE# file COPYING or http://www.opensource.org/licenses/mit-license.php.NEWLINENEWLINE"""NEWLINE ZMQ example using python3's asyncioNEWLINENEWLINE Vadercoin should be started with the command line arguments:NEWLINE vadercoind -testnet -daemon \NEWLINE -zmqpubrawtx=tcp://127.0.0.1:28332 \NEWLINE -zmqpubrawblock=tcp://127.0.0.1:28332 \NEWLINE -zmqpubhashtx=tcp://127.0.0.1:28332 \NEWLINE -zmqpubhashblock=tcp://127.0.0.1:28332 \NEWLINE -zmqpubsequence=tcp://127.0.0.1:28332NEWLINENEWLINE We use the asyncio library here. `self.handle()` installs itself as aNEWLINE future at the end of the function. Since it never returns with the eventNEWLINE loop having an empty stack of futures, this creates an infinite loop. AnNEWLINE alternative is to wrap the contents of `handle` inside `while True`.NEWLINENEWLINE A blocking example using python 2.7 can be obtained from the git history:NEWLINE https://github.com/vadercoin/vadercoin/blob/37a7fe9e440b83e2364d5498931253937abe9294/contrib/zmq/zmq_sub.pyNEWLINE"""NEWLINENEWLINEimport binasciiNEWLINEimport asyncioNEWLINEimport zmqNEWLINEimport zmq.asyncioNEWLINEimport signalNEWLINEimport structNEWLINEimport sysNEWLINENEWLINEif (sys.version_info.major, sys.version_info.minor) < (3, 5):NEWLINE print("This example only works with Python 3.5 and greater")NEWLINE sys.exit(1)NEWLINENEWLINEport = 28332NEWLINENEWLINEclass ZMQHandler():NEWLINE def __init__(self):NEWLINE self.loop = asyncio.get_event_loop()NEWLINE self.zmqContext = zmq.asyncio.Context()NEWLINENEWLINE self.zmqSubSocket = self.zmqContext.socket(zmq.SUB)NEWLINE self.zmqSubSocket.setsockopt(zmq.RCVHWM, 0)NEWLINE self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashblock")NEWLINE self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashtx")NEWLINE self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawblock")NEWLINE self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawtx")NEWLINE self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "sequence")NEWLINE self.zmqSubSocket.connect("tcp://127.0.0.1:%i" % port)NEWLINENEWLINE async def handle(self) :NEWLINE topic, body, seq = await self.zmqSubSocket.recv_multipart()NEWLINE sequence = "Unknown"NEWLINE if len(seq) == 4:NEWLINE sequence = str(struct.unpack('\n'NEWLINE '\n'NEWLINE '\n'NEWLINE )NEWLINE """NEWLINE Created by howie.hu at 2022-01-21.NEWLINE Description: 执行分发动作NEWLINE - 执行命令: PIPENV_DOTENV_LOCATION=./pro.env pipenv run python src/sender/action.pyNEWLINE Changelog: all notable changes to this file will be documentedNEWLINE"""NEWLINEimport timeNEWLINENEWLINEfrom src.config import ConfigNEWLINEfrom src.databases import MongodbManagerNEWLINEfrom src.sender.send_factory import send_factoryNEWLINEfrom src.utils.log import LOGGERNEWLINENEWLINENEWLINEdef send_doc(sender_conf: dict):NEWLINE """NEWLINE 对文章进行分发NEWLINE Args:NEWLINE sender_conf (dict): 分发配置NEWLINE """NEWLINE sender_list = sender_conf["sender_list"]NEWLINE query_days = sender_conf.get("query_days", 2)NEWLINE delta_time = sender_conf.get("delta_time", 3)NEWLINE skip_ads = sender_conf.get("skip_ads", False)NEWLINE if sender_list:NEWLINE # 是否启用分发器NEWLINE mongo_base = MongodbManager.get_mongo_base(mongodb_config=Config.MONGODB_CONFIG)NEWLINE coll = mongo_base.get_collection(coll_name="liuli_articles")NEWLINE cur_ts = int(time.time())NEWLINE filter_dict = {NEWLINE # 时间范围,除第一次外后面其实可以去掉NEWLINE "doc_ts": {"$gte": cur_ts - (query_days * 24 * 60 * 60), "$lte": cur_ts},NEWLINE }NEWLINE if skip_ads:NEWLINE filter_dict.update(NEWLINE {NEWLINE # 至少打上一个模型标签NEWLINE "cos_model": {"$exists": True},NEWLINE # 判定结果为非广告NEWLINE "cos_model.result": 1,NEWLINE }NEWLINE )NEWLINE # 查找所有可分发文章NEWLINE for each_data in coll.find(filter_dict):NEWLINE # 分别分发给各个目标NEWLINE for send_type in sender_list:NEWLINE # 暂时固定,测试NEWLINE init_config = sender_conf.get(f"{send_type}_init_config", {})NEWLINE cos_model_resp = each_data.get("cos_model", {})NEWLINE doc_cus_des = ""NEWLINE if cos_model_resp:NEWLINE # 经过模型判断NEWLINE if cos_model_resp["result"] == 1:NEWLINE # 广告标记NEWLINE doc_cus_des = f"👿广告[概率:{cos_model_resp['probability']}]"NEWLINE else:NEWLINE doc_cus_des = "🤓非广告"NEWLINENEWLINE each_data["doc_cus_des"] = doc_cus_desNEWLINE # 每次分发休眠一定时间NEWLINE time.sleep(delta_time)NEWLINE send_factory(NEWLINE send_type=send_type, init_config=init_config, send_data=each_dataNEWLINE )NEWLINE else:NEWLINE LOGGER.warn("未配置分发器!")NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE send_config = {NEWLINE "sender_list": ["wecom"],NEWLINE "query_days": 7,NEWLINE "skip_ads": False,NEWLINE "delta_time": 3,NEWLINE }NEWLINE send_doc(send_config)NEWLINE import numpy as npNEWLINEfrom sklearn.calibration import CalibratedClassifierCVNEWLINEfrom sklearn.datasets import load_breast_cancerNEWLINEfrom sklearn.ensemble import BaggingClassifierNEWLINEfrom sklearn.linear_model import LogisticRegressionNEWLINEfrom sklearn.linear_model import PerceptronNEWLINEfrom sklearn.model_selection import train_test_splitNEWLINEfrom sklearn.preprocessing import StandardScalerNEWLINEfrom sklearn.svm import SVCNEWLINENEWLINEfrom deslib.dcs.a_posteriori import APosterioriNEWLINE# DCS techniquesNEWLINEfrom deslib.dcs.a_priori import APrioriNEWLINEfrom deslib.dcs.lca import LCANEWLINEfrom deslib.dcs.mcb import MCBNEWLINEfrom deslib.dcs.mla import MLANEWLINEfrom deslib.dcs.ola import OLANEWLINEfrom deslib.dcs.rank import RankNEWLINE# DES techniquesNEWLINEfrom deslib.des.des_clustering import DESClusteringNEWLINEfrom deslib.des.des_knn import DESKNNNEWLINEfrom deslib.des.des_p import DESPNEWLINEfrom deslib.des.knop import KNOPNEWLINEfrom deslib.des.knora_e import KNORAENEWLINEfrom deslib.des.knora_u import KNORAUNEWLINEfrom deslib.des.meta_des import METADESNEWLINEfrom deslib.des.probabilistic import RRC, MinimumDifference, DESKLNEWLINE# Static techniquesNEWLINEfrom deslib.static.oracle import OracleNEWLINEfrom deslib.static.single_best import SingleBestNEWLINEfrom deslib.static.static_selection import StaticSelectionNEWLINENEWLINENEWLINEdef test_label_encoder_integration_list_classifiers():NEWLINE rng = np.random.RandomState(123456)NEWLINE X_dsel, X_test, X_train, y_dsel, y_test, y_train = load_dataset(encode_labels=['no', 'yes'], rng=rng)NEWLINENEWLINE pool_classifiers = [LogisticRegression(), SVC(probability=True)]NEWLINE [clf.fit(X_train, y_train) for clf in pool_classifiers]NEWLINENEWLINE knorau = KNORAU(pool_classifiers)NEWLINE knorau.fit(X_dsel, y_dsel)NEWLINENEWLINE this_score = knorau.score(X_test, y_test)NEWLINE assert np.isclose(this_score, 0.9574468085106383)NEWLINENEWLINENEWLINEdef test_label_encoder_integration_sklearn_ensembles():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers(encode_labels=['no', 'yes'])NEWLINENEWLINE knorau = KNORAU(pool_classifiers)NEWLINE knorau.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(knorau.score(X_test, y_test), 0.97340425531914898)NEWLINENEWLINENEWLINEdef setup_classifiers(encode_labels=None):NEWLINE rng = np.random.RandomState(123456)NEWLINENEWLINE X_dsel, X_test, X_train, y_dsel, y_test, y_train = load_dataset(encode_labels, rng)NEWLINE model = CalibratedClassifierCV(Perceptron(max_iter=5))NEWLINE # Train a pool of 100 classifiersNEWLINE pool_classifiers = BaggingClassifier(model, n_estimators=10, random_state=rng)NEWLINE pool_classifiers.fit(X_train, y_train)NEWLINE return pool_classifiers, X_dsel, y_dsel, X_test, y_testNEWLINENEWLINENEWLINEdef load_dataset(encode_labels, rng):NEWLINE # Generate a classification datasetNEWLINE data = load_breast_cancer()NEWLINE X = data.dataNEWLINE y = data.targetNEWLINE if encode_labels is not None:NEWLINE y = np.take(encode_labels, y)NEWLINE # split the data into training and test dataNEWLINE X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=rng)NEWLINE # Scale the variables to have 0 mean and unit varianceNEWLINE scalar = StandardScaler()NEWLINE X_train = scalar.fit_transform(X_train)NEWLINE X_test = scalar.transform(X_test)NEWLINE # Split the data into training and DSEL for DS techniquesNEWLINE X_train, X_dsel, y_train, y_dsel = train_test_split(X_train, y_train, test_size=0.5, random_state=rng)NEWLINE # Considering a pool composed of 10 base classifiersNEWLINE # Calibrating Perceptrons to estimate probabilitiesNEWLINE return X_dsel, X_test, X_train, y_dsel, y_test, y_trainNEWLINENEWLINENEWLINEdef test_knorau():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE knorau = KNORAU(pool_classifiers)NEWLINE knorau.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(knorau.score(X_test, y_test), 0.97340425531914898)NEWLINENEWLINENEWLINEdef test_kne():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE kne = KNORAE(pool_classifiers)NEWLINE kne.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(kne.score(X_test, y_test), 0.973404255319148)NEWLINENEWLINENEWLINEdef test_desp():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE desp = DESP(pool_classifiers)NEWLINE desp.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(desp.score(X_test, y_test), 0.97340425531914898)NEWLINENEWLINENEWLINEdef test_ola():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE ola = OLA(pool_classifiers)NEWLINE ola.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(ola.score(X_test, y_test), 0.96808510638297873)NEWLINENEWLINENEWLINEdef test_lca():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE lca = LCA(pool_classifiers)NEWLINE lca.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(lca.score(X_test, y_test), 0.96808510638297873)NEWLINENEWLINENEWLINEdef test_MLA():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE mla = MLA(pool_classifiers)NEWLINE mla.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(mla.score(X_test, y_test), 0.96808510638297873)NEWLINENEWLINENEWLINEdef test_mcb():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINE rng = np.random.RandomState(123456)NEWLINENEWLINE mcb = MCB(pool_classifiers, rng=rng)NEWLINE mcb.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(mcb.score(X_test, y_test), 0.96276595744680848)NEWLINENEWLINENEWLINEdef test_apriori():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINE rng = np.random.RandomState(123456)NEWLINENEWLINE apriori = APriori(pool_classifiers, rng=rng)NEWLINE apriori.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(apriori.score(X_test, y_test), 0.97872340425531912)NEWLINENEWLINENEWLINEdef test_rank():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE rank = Rank(pool_classifiers)NEWLINE rank.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(rank.score(X_test, y_test), 0.973404255319149)NEWLINENEWLINENEWLINEdef test_aposteriori():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINE rng = np.random.RandomState(123456)NEWLINENEWLINE a_posteriori = APosteriori(pool_classifiers, rng=rng)NEWLINE a_posteriori.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(a_posteriori.score(X_test, y_test), 0.96276595744680848)NEWLINENEWLINENEWLINEdef test_meta():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE meta_des = METADES(pool_classifiers)NEWLINE meta_des.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(meta_des.score(X_test, y_test), 0.973404255319149)NEWLINENEWLINENEWLINEdef test_rrc():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE rrc = RRC(pool_classifiers)NEWLINE rrc.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(rrc.score(X_test, y_test), 0.97340425531914898)NEWLINENEWLINENEWLINEdef test_deskl():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE deskl = DESKL(pool_classifiers)NEWLINE deskl.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(deskl.score(X_test, y_test), 0.97340425531914898)NEWLINENEWLINENEWLINEdef test_minimum_diff():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE minimum_diff = MinimumDifference(pool_classifiers)NEWLINE minimum_diff.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(minimum_diff.score(X_test, y_test), 0.97340425531914898)NEWLINENEWLINENEWLINEdef test_knop():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE knop = KNOP(pool_classifiers)NEWLINE knop.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(knop.score(X_test, y_test), 0.97340425531914898)NEWLINENEWLINENEWLINEdef test_desknn():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE desknn = DESKNN(pool_classifiers)NEWLINE desknn.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(desknn.score(X_test, y_test), 0.97340425531914898)NEWLINENEWLINENEWLINEdef test_des_clustering():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINE rng = np.random.RandomState(123456)NEWLINENEWLINE des_clustering = DESClustering(pool_classifiers, rng=rng)NEWLINE des_clustering.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(des_clustering.score(X_test, y_test), 0.97872340425531912)NEWLINENEWLINENEWLINEdef test_oracle():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE oracle = Oracle(pool_classifiers)NEWLINE assert np.isclose(oracle.score(X_test, y_test), 0.99468085106382975)NEWLINENEWLINENEWLINEdef test_single_best():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE single_best = SingleBest(pool_classifiers)NEWLINE single_best.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(single_best.score(X_test, y_test), 0.97872340425531912)NEWLINENEWLINENEWLINEdef test_static_selection():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE static_selection = StaticSelection(pool_classifiers)NEWLINE static_selection.fit(X_dsel, y_dsel)NEWLINE assert np.isclose(static_selection.score(X_test, y_test), 0.96808510638297873)NEWLINENEWLINENEWLINE# ------------------------------------------ Testing predict_proba -----------------------------------NEWLINEdef test_kne_proba():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE kne = KNORAE(pool_classifiers)NEWLINE kne.fit(X_dsel, y_dsel)NEWLINE probas = kne.predict_proba(X_test)NEWLINE expected = np.load('deslib/tests/expected_values/kne_proba_integration.npy')NEWLINE assert np.allclose(probas, expected)NEWLINENEWLINENEWLINEdef test_desp_proba():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE desp = DESP(pool_classifiers)NEWLINE desp.fit(X_dsel, y_dsel)NEWLINE probas = desp.predict_proba(X_test)NEWLINE expected = np.load('deslib/tests/expected_values/desp_proba_integration.npy')NEWLINE assert np.allclose(probas, expected)NEWLINENEWLINENEWLINEdef test_ola_proba():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE ola = OLA(pool_classifiers)NEWLINE ola.fit(X_dsel, y_dsel)NEWLINE probas = ola.predict_proba(X_test)NEWLINE expected = np.load('deslib/tests/expected_values/ola_proba_integration.npy')NEWLINE assert np.allclose(probas, expected)NEWLINENEWLINENEWLINEdef test_mcb_proba():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINE rng = np.random.RandomState(123456)NEWLINENEWLINE mcb = MCB(pool_classifiers, rng=rng)NEWLINE mcb.fit(X_dsel, y_dsel)NEWLINE probas = mcb.predict_proba(X_test)NEWLINE expected = np.load('deslib/tests/expected_values/mcb_proba_integration.npy')NEWLINE assert np.allclose(probas, expected)NEWLINENEWLINENEWLINEdef test_desknn_proba():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE desknn = DESKNN(pool_classifiers)NEWLINE desknn.fit(X_dsel, y_dsel)NEWLINE probas = desknn.predict_proba(X_test)NEWLINE expected = np.load('deslib/tests/expected_values/desknn_proba_integration.npy')NEWLINE assert np.allclose(probas, expected)NEWLINENEWLINENEWLINEdef test_des_clustering_proba():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINE rng = np.random.RandomState(123456)NEWLINENEWLINE des_clustering = DESClustering(pool_classifiers, rng=rng)NEWLINE des_clustering.fit(X_dsel, y_dsel)NEWLINE probas = des_clustering.predict_proba(X_test)NEWLINE expected = np.load('deslib/tests/expected_values/des_clustering_proba_integration.npy')NEWLINE assert np.allclose(probas, expected)NEWLINENEWLINENEWLINEdef test_knop_proba():NEWLINE pool_classifiers, X_dsel, y_dsel, X_test, y_test = setup_classifiers()NEWLINENEWLINE knop = KNOP(pool_classifiers)NEWLINE knop.fit(X_dsel, y_dsel)NEWLINE probas = knop.predict_proba(X_test)NEWLINE expected = np.load('deslib/tests/expected_values/knop_proba_integration.npy')NEWLINE assert np.allclose(probas, expected) #coding:utf-8NEWLINEimport codecsNEWLINEimport osNEWLINEimport sysNEWLINE NEWLINEtry:NEWLINE from setuptools import setupNEWLINEexcept:NEWLINE from distutils.core import setupNEWLINE"""NEWLINE打包的用的setup必须引入,NEWLINE"""NEWLINE NEWLINEdef read(fname):NEWLINENEWLINE return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read()NEWLINE NEWLINE NEWLINE NEWLINENAME = "quantaxis"NEWLINE"""NEWLINE名字,一般放你包的名字即可NEWLINE"""NEWLINEPACKAGES = ["QUANTAXIS", "QUANTAXIS.QAFetch","QUANTAXIS.QACmd", "QUANTAXIS.QAMarket", "QUANTAXIS.QABacktest","QUANTAXIS.QASQL" ,"QUANTAXIS.QATask", "QUANTAXIS.QASpider","QUANTAXIS.QASU","QUANTAXIS.QAUtil","QUANTAXIS.QAARP","QUANTAXIS.QASignal","QUANTAXIS.QAMath","QUANTAXIS.QAIndicator"]NEWLINE"""NEWLINE包含的包,可以多个,这是一个列表NEWLINE"""NEWLINE NEWLINEDESCRIPTION = "QUANTAXIS:Quantitative Financial Strategy Framework"NEWLINENEWLINE NEWLINELONG_DESCRIPTION = read("README.rst")NEWLINE"""NEWLINE参见read方法说明NEWLINE"""NEWLINE NEWLINEKEYWORDS = ["quantaxis","quant","finance"]NEWLINE"""NEWLINE关于当前包的一些关键字,方便PyPI进行分类。NEWLINE"""NEWLINE NEWLINEAUTHOR = "yutiansut"NEWLINENEWLINEAUTHOR_EMAIL = "yutiansut@qq.com"NEWLINE NEWLINEURL = "http://www.yutiansut.com"NEWLINENEWLINEVERSION = "0.3.9b1.dev19"NEWLINENEWLINE NEWLINELICENSE = "MIT"NEWLINENEWLINE NEWLINEsetup(NEWLINE name = NAME,NEWLINE version = VERSION,NEWLINE description = DESCRIPTION,NEWLINE long_description = LONG_DESCRIPTION,NEWLINE classifiers = [NEWLINE 'License :: OSI Approved :: MIT License',NEWLINE 'Programming Language :: Python',NEWLINE 'Intended Audience :: Developers',NEWLINE 'Operating System :: OS Independent',NEWLINE ],NEWLINE install_requires = ['tushare>=0.7.4','pymongo>=3.4','celery>=4.0.0','six>=1.10.0'],NEWLINE keywords = KEYWORDS,NEWLINE author = AUTHOR,NEWLINE author_email = AUTHOR_EMAIL,NEWLINE url = URL,NEWLINE license = LICENSE,NEWLINE packages = PACKAGES,NEWLINE include_package_data=True,NEWLINE zip_safe=True,NEWLINE)NEWLINE NEWLINE## 把上面的变量填入了一个setup()中即可。 # Copyright 2019 The TensorFlow Authors. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE# ==============================================================================NEWLINE"""Public API for tf.linalg.sparse namespace."""NEWLINENEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import print_functionNEWLINENEWLINE# go/tf-wildcard-importNEWLINE# pylint: disable=wildcard-importNEWLINEfrom tensorflow.python.ops.linalg.sparse.sparse_csr_matrix_grad import *NEWLINEfrom tensorflow.python.ops.linalg.sparse.sparse_csr_matrix_ops import *NEWLINE# pylint: enable=wildcard-importNEWLINE from django.shortcuts import renderNEWLINEfrom django.contrib.auth.models import UserNEWLINEfrom django.http import Http404NEWLINEfrom django.views.generic import DetailViewNEWLINEfrom django.contrib.auth.decorators import login_requiredNEWLINEfrom django.utils.decorators import method_decoratorNEWLINEfrom django.shortcuts import get_object_or_404NEWLINENEWLINEfrom comics.models import (NEWLINE Comic,NEWLINE Post,NEWLINE ContributorNEWLINE)NEWLINENEWLINENEWLINEclass ProfileView(DetailView):NEWLINE template_name="profile.html"NEWLINE model = UserNEWLINENEWLINE def dispatch(self, *args, **kwargs):NEWLINE if kwargs.get('username'):NEWLINE self.user = get_object_or_404(User, username=kwargs.get('username'))NEWLINE elif self.request.user:NEWLINE self.user = self.request.userNEWLINE else:NEWLINE raise Http404()NEWLINE return super(ProfileView, self).dispatch(*args, **kwargs)NEWLINENEWLINE def get_object(self):NEWLINE return self.userNEWLINENEWLINE def get_context_data(self, **kwargs):NEWLINE context = super(ProfileView, self).get_context_data(**kwargs)NEWLINENEWLINE contributions = Contributor.objects.filter(contributor=self.user)NEWLINENEWLINE comics = Comic.published_comics.filter(NEWLINE post__contributor__in=contributionsNEWLINE ).order_by('-published')NEWLINENEWLINE posts = Post.published_posts.filter(NEWLINE contributor__in=contributionsNEWLINE ).exclude(NEWLINE id__in=comics.values_list('post')NEWLINE ).order_by('-published')NEWLINENEWLINE context['display_user'] = self.userNEWLINE context['posts'] = postsNEWLINE context['comics'] = comicsNEWLINENEWLINE return context # coding=utf-8NEWLINE# --------------------------------------------------------------------------NEWLINE# Copyright (c) Microsoft Corporation. All rights reserved.NEWLINE# Licensed under the MIT License. See License.txt in the project root forNEWLINE# license information.NEWLINE#NEWLINE# Code generated by Microsoft (R) AutoRest Code Generator.NEWLINE# Changes may cause incorrect behavior and will be lost if the code isNEWLINE# regenerated.NEWLINE# --------------------------------------------------------------------------NEWLINENEWLINEfrom .task_step_properties import TaskStepPropertiesNEWLINENEWLINENEWLINEclass DockerBuildStep(TaskStepProperties):NEWLINE """The Docker build step.NEWLINENEWLINE Variables are only populated by the server, and will be ignored whenNEWLINE sending a request.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar base_image_dependencies: List of base image dependencies for a step.NEWLINE :vartype base_image_dependencies:NEWLINE list[~azure.mgmt.containerregistry.v2019_04_01.models.BaseImageDependency]NEWLINE :param context_path: The URL(absolute or relative) of the source contextNEWLINE for the task step.NEWLINE :type context_path: strNEWLINE :param context_access_token: The token (git PAT or SAS token of storageNEWLINE account blob) associated with the context for a step.NEWLINE :type context_access_token: strNEWLINE :param type: Required. Constant filled by server.NEWLINE :type type: strNEWLINE :param image_names: The fully qualified image names including theNEWLINE repository and tag.NEWLINE :type image_names: list[str]NEWLINE :param is_push_enabled: The value of this property indicates whether theNEWLINE image built should be pushed to the registry or not. Default value: True .NEWLINE :type is_push_enabled: boolNEWLINE :param no_cache: The value of this property indicates whether the imageNEWLINE cache is enabled or not. Default value: False .NEWLINE :type no_cache: boolNEWLINE :param docker_file_path: Required. The Docker file path relative to theNEWLINE source context.NEWLINE :type docker_file_path: strNEWLINE :param target: The name of the target build stage for the docker build.NEWLINE :type target: strNEWLINE :param arguments: The collection of override arguments to be used whenNEWLINE executing this build step.NEWLINE :type arguments:NEWLINE list[~azure.mgmt.containerregistry.v2019_04_01.models.Argument]NEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'base_image_dependencies': {'readonly': True},NEWLINE 'type': {'required': True},NEWLINE 'docker_file_path': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'base_image_dependencies': {'key': 'baseImageDependencies', 'type': '[BaseImageDependency]'},NEWLINE 'context_path': {'key': 'contextPath', 'type': 'str'},NEWLINE 'context_access_token': {'key': 'contextAccessToken', 'type': 'str'},NEWLINE 'type': {'key': 'type', 'type': 'str'},NEWLINE 'image_names': {'key': 'imageNames', 'type': '[str]'},NEWLINE 'is_push_enabled': {'key': 'isPushEnabled', 'type': 'bool'},NEWLINE 'no_cache': {'key': 'noCache', 'type': 'bool'},NEWLINE 'docker_file_path': {'key': 'dockerFilePath', 'type': 'str'},NEWLINE 'target': {'key': 'target', 'type': 'str'},NEWLINE 'arguments': {'key': 'arguments', 'type': '[Argument]'},NEWLINE }NEWLINENEWLINE def __init__(self, **kwargs):NEWLINE super(DockerBuildStep, self).__init__(**kwargs)NEWLINE self.image_names = kwargs.get('image_names', None)NEWLINE self.is_push_enabled = kwargs.get('is_push_enabled', True)NEWLINE self.no_cache = kwargs.get('no_cache', False)NEWLINE self.docker_file_path = kwargs.get('docker_file_path', None)NEWLINE self.target = kwargs.get('target', None)NEWLINE self.arguments = kwargs.get('arguments', None)NEWLINE self.type = 'Docker'NEWLINE from service import ServiceScraper, ServiceSoundDetector, ServiceLanguageDetectorNEWLINENEWLINEif __name__ == "__main__":NEWLINE services = [ServiceScraper, ServiceSoundDetector, ServiceLanguageDetector]NEWLINENEWLINE for service in services:NEWLINE s = service()NEWLINE s.process() #NEWLINE# Copyright (c) 2021 Project CHIP AuthorsNEWLINE# All rights reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE#NEWLINENEWLINE# Needed to use types in type hints before they are fully defined.NEWLINEfrom __future__ import annotationsNEWLINENEWLINEfrom asyncio.futures import FutureNEWLINEimport ctypesNEWLINEfrom dataclasses import dataclass, fieldNEWLINEfrom typing import Tuple, Type, Union, List, Any, Callable, Dict, SetNEWLINEfrom ctypes import CFUNCTYPE, c_char_p, c_size_t, c_void_p, c_uint64, c_uint32, c_uint16, c_uint8, py_object, c_uint64NEWLINEfrom rich.pretty import pprintNEWLINENEWLINEfrom .ClusterObjects import Cluster, ClusterAttributeDescriptor, ClusterEventNEWLINEimport chip.exceptionsNEWLINEimport chip.interaction_modelNEWLINEimport chip.tlvNEWLINEfrom enum import Enum, uniqueNEWLINEimport inspectNEWLINEimport sysNEWLINEimport loggingNEWLINEimport threadingNEWLINEimport builtinsNEWLINENEWLINENEWLINE@uniqueNEWLINEclass EventTimestampType(Enum):NEWLINE SYSTEM = 0NEWLINE EPOCH = 1NEWLINENEWLINENEWLINE@uniqueNEWLINEclass EventPriority(Enum):NEWLINE DEBUG = 1NEWLINE INFO = 2NEWLINE CRITICAL = 3NEWLINENEWLINENEWLINE@dataclassNEWLINEclass AttributePath:NEWLINE EndpointId: int = NoneNEWLINE ClusterId: int = NoneNEWLINE AttributeId: int = NoneNEWLINENEWLINE def __init__(self, EndpointId: int = None, Cluster=None, Attribute=None, ClusterId=None, AttributeId=None):NEWLINE self.EndpointId = EndpointIdNEWLINE if Cluster is not None:NEWLINE # Wildcard read for a specific clusterNEWLINE if (Attribute is not None) or (ClusterId is not None) or (AttributeId is not None):NEWLINE raise Warning(NEWLINE "Attribute, ClusterId and AttributeId is ignored when Cluster is specified")NEWLINE self.ClusterId = Cluster.idNEWLINE returnNEWLINE if Attribute is not None:NEWLINE if (ClusterId is not None) or (AttributeId is not None):NEWLINE raise Warning(NEWLINE "ClusterId and AttributeId is ignored when Attribute is specified")NEWLINE self.ClusterId = Attribute.cluster_idNEWLINE self.AttributeId = Attribute.attribute_idNEWLINE returnNEWLINE self.ClusterId = ClusterIdNEWLINE self.AttributeId = AttributeIdNEWLINENEWLINE def __str__(self) -> str:NEWLINE return f"{self.EndpointId}/{self.ClusterId}/{self.AttributeId}"NEWLINENEWLINE def __hash__(self):NEWLINE return str(self).__hash__()NEWLINENEWLINENEWLINE@dataclassNEWLINEclass TypedAttributePath:NEWLINE ''' Encapsulates an attribute path that has strongly typed references to cluster and attributeNEWLINE cluster object types. These types serve as keys into the attribute cache.NEWLINE '''NEWLINE ClusterType: Cluster = NoneNEWLINE AttributeType: ClusterAttributeDescriptor = NoneNEWLINE AttributeName: str = NoneNEWLINE Path: AttributePath = NoneNEWLINENEWLINE def __init__(self, ClusterType: Cluster = None, AttributeType: ClusterAttributeDescriptor = None,NEWLINE Path: AttributePath = None):NEWLINE ''' Only one of either ClusterType and AttributeType OR Path may be provided.NEWLINE '''NEWLINENEWLINE #NEWLINE # First, let's populate ClusterType and AttributeType. If it's already provided,NEWLINE # we can continue onwards to deriving the label. Otherwise, we'll need toNEWLINE # walk the attribute index to find the right type information.NEWLINE #NEWLINE if (ClusterType is not None and AttributeType is not None):NEWLINE self.ClusterType = ClusterTypeNEWLINE self.AttributeType = AttributeTypeNEWLINE else:NEWLINE if (Path is None):NEWLINE raise ValueError("Path should have a valid value")NEWLINENEWLINE for cluster, attribute in _AttributeIndex:NEWLINE attributeType = _AttributeIndex[(cluster, attribute)][0]NEWLINE clusterType = _AttributeIndex[(cluster, attribute)][1]NEWLINENEWLINE if (clusterType.id == Path.ClusterId and attributeType.attribute_id == Path.AttributeId):NEWLINE self.ClusterType = clusterTypeNEWLINE self.AttributeType = attributeTypeNEWLINE breakNEWLINENEWLINE if (self.ClusterType is None or self.AttributeType is None):NEWLINE raise Exception("Schema not found")NEWLINENEWLINE # Next, let's figure out the label.NEWLINE for field in self.ClusterType.descriptor.Fields:NEWLINE if (field.Tag != self.AttributeType.attribute_id):NEWLINE continueNEWLINENEWLINE self.AttributeName = field.LabelNEWLINENEWLINE if (self.AttributeName is None):NEWLINE raise Exception("Schema not found")NEWLINENEWLINE self.Path = PathNEWLINE self.ClusterId = self.ClusterType.idNEWLINE self.AttributeId = self.AttributeType.attribute_idNEWLINENEWLINENEWLINE@dataclassNEWLINEclass EventPath:NEWLINE EndpointId: int = NoneNEWLINE ClusterId: int = NoneNEWLINE EventId: int = NoneNEWLINENEWLINE def __init__(self, EndpointId: int = None, Cluster=None, Event=None, ClusterId=None, EventId=None):NEWLINE self.EndpointId = EndpointIdNEWLINE if Cluster is not None:NEWLINE # Wildcard read for a specific clusterNEWLINE if (Event is not None) or (ClusterId is not None) or (EventId is not None):NEWLINE raise Warning(NEWLINE "Event, ClusterId and AttributeId is ignored when Cluster is specified")NEWLINE self.ClusterId = Cluster.idNEWLINE returnNEWLINE if Event is not None:NEWLINE if (ClusterId is not None) or (EventId is not None):NEWLINE raise Warning(NEWLINE "ClusterId and EventId is ignored when Event is specified")NEWLINE self.ClusterId = Event.cluster_idNEWLINE self.EventId = Event.event_idNEWLINE returnNEWLINE self.ClusterId = ClusterIdNEWLINE self.EventId = EventIdNEWLINENEWLINE def __str__(self) -> str:NEWLINE return f"{self.EndpointId}/{self.ClusterId}/{self.EventId}"NEWLINENEWLINE def __hash__(self):NEWLINE return str(self).__hash__()NEWLINENEWLINENEWLINE@dataclassNEWLINEclass AttributePathWithListIndex(AttributePath):NEWLINE ListIndex: int = NoneNEWLINENEWLINENEWLINE@dataclassNEWLINEclass EventHeader:NEWLINE EndpointId: int = NoneNEWLINE Event: ClusterEvent = NoneNEWLINE EventNumber: int = NoneNEWLINE Priority: EventPriority = NoneNEWLINE Timestamp: int = NoneNEWLINE TimestampType: EventTimestampType = NoneNEWLINENEWLINE def __init__(self, EndpointId: int = None, Event=None, EventNumber=None, Priority=None, Timestamp=None, TimestampType=None):NEWLINE self.EndpointId = EndpointIdNEWLINE self.Event = EventNEWLINE self.EventNumber = EventNumberNEWLINE self.Priority = PriorityNEWLINE self.Timestamp = TimestampNEWLINE self.Timestamp = TimestampTypeNEWLINENEWLINE def __str__(self) -> str:NEWLINE return f"{self.EndpointId}/{self.Event.cluster_id}/{self.Event.event_id}/{self.EventNumber}/{self.Priority}/{self.Timestamp}/{self.TimestampType}"NEWLINENEWLINENEWLINE@dataclassNEWLINEclass AttributeStatus:NEWLINE Path: AttributePathNEWLINE Status: Union[chip.interaction_model.Status, int]NEWLINENEWLINENEWLINE@dataclassNEWLINEclass EventStatus:NEWLINE Header: EventHeaderNEWLINE Status: chip.interaction_model.StatusNEWLINENEWLINENEWLINEAttributeWriteResult = AttributeStatusNEWLINENEWLINENEWLINE@dataclassNEWLINEclass AttributeDescriptorWithEndpoint:NEWLINE EndpointId: intNEWLINE Attribute: ClusterAttributeDescriptorNEWLINENEWLINENEWLINE@dataclassNEWLINEclass EventDescriptorWithEndpoint:NEWLINE EndpointId: intNEWLINE Event: ClusterEventNEWLINENEWLINENEWLINE@dataclassNEWLINEclass AttributeWriteRequest(AttributeDescriptorWithEndpoint):NEWLINE Data: AnyNEWLINENEWLINENEWLINEAttributeReadRequest = AttributeDescriptorWithEndpointNEWLINEEventReadRequest = EventDescriptorWithEndpointNEWLINENEWLINENEWLINE@dataclassNEWLINEclass AttributeReadResult(AttributeStatus):NEWLINE Data: Any = NoneNEWLINENEWLINENEWLINE@dataclassNEWLINEclass ValueDecodeFailure:NEWLINE ''' Encapsulates a failure to decode a TLV value into a cluster object.NEWLINE Some exceptions have custom fields, so run str(ReasonException) to get more info.NEWLINE '''NEWLINENEWLINE TLVValue: Any = NoneNEWLINE Reason: Exception = NoneNEWLINENEWLINENEWLINE@dataclassNEWLINEclass EventReadResult(EventStatus):NEWLINE Data: Any = NoneNEWLINENEWLINENEWLINE_AttributeIndex = {}NEWLINE_EventIndex = {}NEWLINE_ClusterIndex = {}NEWLINENEWLINENEWLINEdef _BuildAttributeIndex():NEWLINE ''' Build internal attribute index for locating the corresponding cluster object by path in the future.NEWLINE We do this because this operation will take a long time when there are lots of attributes, it takes about 300ms for a single query.NEWLINE This is acceptable during init, but unacceptable when the server returns lots of attributes at the same time.NEWLINE '''NEWLINE for clusterName, obj in inspect.getmembers(sys.modules['chip.clusters.Objects']):NEWLINE if ('chip.clusters.Objects' in str(obj)) and inspect.isclass(obj):NEWLINE for objName, subclass in inspect.getmembers(obj):NEWLINE if inspect.isclass(subclass) and (('Attributes') in str(subclass)):NEWLINE for attributeName, attribute in inspect.getmembers(subclass):NEWLINE if inspect.isclass(attribute):NEWLINE base_classes = inspect.getmro(attribute)NEWLINENEWLINE # Only match on classes that extend the ClusterAttributeDescriptor classNEWLINE matched = [NEWLINE value for value in base_classes if 'ClusterAttributeDescriptor' in str(value)]NEWLINE if (matched == []):NEWLINE continueNEWLINENEWLINE _AttributeIndex[(attribute.cluster_id, attribute.attribute_id)] = (eval(NEWLINE 'chip.clusters.Objects.' + clusterName + '.Attributes.' + attributeName), obj)NEWLINENEWLINENEWLINEdef _BuildClusterIndex():NEWLINE ''' Build internal cluster index for locating the corresponding cluster object by path in the future.NEWLINE '''NEWLINE for clusterName, obj in inspect.getmembers(sys.modules['chip.clusters.Objects']):NEWLINE if ('chip.clusters.Objects' in str(obj)) and inspect.isclass(obj):NEWLINE _ClusterIndex[obj.id] = objNEWLINENEWLINENEWLINE@dataclassNEWLINEclass SubscriptionParameters:NEWLINE MinReportIntervalFloorSeconds: intNEWLINE MaxReportIntervalCeilingSeconds: intNEWLINENEWLINENEWLINE@dataclassNEWLINEclass AttributeCache:NEWLINE ''' A cache that stores data & errors returned in read/subscribe reports, but organizes it topologicallyNEWLINE in a collection of nested dictionaries. The organization follows the natural data model composition ofNEWLINE the device: endpoint, then cluster, then attribute.NEWLINENEWLINE TLV data (or ValueDecodeFailure in the case of IM status codes) are stored for each attribute inNEWLINE attributeTLVCache[endpoint][cluster][attribute].NEWLINENEWLINE Upon completion of data population, it can be retrieved in a more friendly cluster object format,NEWLINE with two options available. In both options, data is in the dictionary is key'ed not by the raw numericNEWLINE cluster and attribute IDs, but instead by the cluster object descriptor types for each of those generatedNEWLINE cluster objects.NEWLINENEWLINE E.g Clusters.TestCluster is the literal key for indexing the test cluster.NEWLINE Clusters.TestCluster.Attributes.Int16u is the listeral key for indexing an attribute in the test cluster.NEWLINENEWLINE This strongly typed keys permit a more natural and safer form of indexing.NEWLINE '''NEWLINE returnClusterObject: bool = FalseNEWLINE attributeTLVCache: Dict[int, Dict[int, Dict[int, bytes]]] = field(NEWLINE default_factory=lambda: {})NEWLINE attributeCache: Dict[int, List[Cluster]] = field(NEWLINE default_factory=lambda: {})NEWLINENEWLINE def UpdateTLV(self, path: AttributePath, data: Union[bytes, ValueDecodeFailure]):NEWLINE ''' Store data in TLV since that makes it easiest to eventually convert to either theNEWLINE cluster or attribute view representations (see below in UpdateCachedData).NEWLINE '''NEWLINE if (path.EndpointId not in self.attributeTLVCache):NEWLINE self.attributeTLVCache[path.EndpointId] = {}NEWLINENEWLINE endpointCache = self.attributeTLVCache[path.EndpointId]NEWLINE if (path.ClusterId not in endpointCache):NEWLINE endpointCache[path.ClusterId] = {}NEWLINENEWLINE clusterCache = endpointCache[path.ClusterId]NEWLINE if (path.AttributeId not in clusterCache):NEWLINE clusterCache[path.AttributeId] = NoneNEWLINENEWLINE clusterCache[path.AttributeId] = dataNEWLINENEWLINE def UpdateCachedData(self):NEWLINE ''' This converts the raw TLV data into a cluster object format.NEWLINENEWLINE Two formats are available:NEWLINE 1. Attribute-View (returnClusterObject=False): Dict[EndpointId, Dict[ClusterObjectType, Dict[AttributeObjectType, AttributeValue]]]NEWLINE 2. Cluster-View (returnClusterObject=True): Dict[EndpointId, Dict[ClusterObjectType, ClusterValue]]NEWLINENEWLINE In the attribute-view, only attributes that match the original path criteria are present in the dictionary. The attribute values canNEWLINE either be the actual data for the attribute, or a ValueDecodeFailure in the case of non-success IM status codes, or other errors encountered during decode.NEWLINENEWLINE In the cluster-view, a cluster object that corresponds to all attributes on a given cluster instance is returned,NEWLINE regardless of the subset of attributes read. For attributes not returned in the report, defaults are used. If a cluster cannot be decoded,NEWLINE instead of a cluster object value, a ValueDecodeFailure shall be present.NEWLINE '''NEWLINENEWLINE tlvCache = self.attributeTLVCacheNEWLINE attributeCache = self.attributeCacheNEWLINENEWLINE for endpoint in tlvCache:NEWLINE if (endpoint not in attributeCache):NEWLINE attributeCache[endpoint] = {}NEWLINENEWLINE endpointCache = attributeCache[endpoint]NEWLINENEWLINE for cluster in tlvCache[endpoint]:NEWLINE clusterType = _ClusterIndex[cluster]NEWLINE if (clusterType is None):NEWLINE raise Exception("Cannot find cluster in cluster index")NEWLINENEWLINE if (clusterType not in endpointCache):NEWLINE endpointCache[clusterType] = {}NEWLINENEWLINE clusterCache = endpointCache[clusterType]NEWLINENEWLINE if (self.returnClusterObject):NEWLINE try:NEWLINE # Since the TLV data is already organized by attribute tags, we can trivially convert to a cluster object representation.NEWLINE endpointCache[clusterType] = clusterType.FromDict(NEWLINE data=clusterType.descriptor.TagDictToLabelDict([], tlvCache[endpoint][cluster]))NEWLINE except Exception as ex:NEWLINE logging.error(NEWLINE f"Error converting TLV to Cluster Object for path: Endpoint = {endpoint}, cluster = {str(clusterType)}")NEWLINE logging.error(f"|-- Exception: {repr(ex)}")NEWLINE decodedValue = ValueDecodeFailure(NEWLINE tlvCache[endpoint][cluster], ex)NEWLINE endpointCache[clusterType] = decodedValueNEWLINE else:NEWLINE for attribute in tlvCache[endpoint][cluster]:NEWLINE value = tlvCache[endpoint][cluster][attribute]NEWLINENEWLINE attributeType = _AttributeIndex[(NEWLINE cluster, attribute)][0]NEWLINE if (attributeType is None):NEWLINE raise Exception(NEWLINE "Cannot find attribute in attribute index")NEWLINENEWLINE if (attributeType not in clusterCache):NEWLINE clusterCache[attributeType] = {}NEWLINENEWLINE if (type(value) is ValueDecodeFailure):NEWLINE logging.error(NEWLINE f"For path: Endpoint = {endpoint}, Attribute = {str(attributeType)}, got IM Error: {str(value.Reason)}")NEWLINE clusterCache[attributeType] = valueNEWLINE else:NEWLINE try:NEWLINE decodedValue = attributeType.FromTagDictOrRawValue(NEWLINE tlvCache[endpoint][cluster][attribute])NEWLINE except Exception as ex:NEWLINE logging.error(NEWLINE f"Error converting TLV to Cluster Object for path: Endpoint = {endpoint}, Attribute = {str(attributeType)}")NEWLINE logging.error(f"|-- Exception: {repr(ex)}")NEWLINE decodedValue = ValueDecodeFailure(value, ex)NEWLINENEWLINE clusterCache[attributeType] = decodedValueNEWLINENEWLINENEWLINEclass SubscriptionTransaction:NEWLINE def __init__(self, transaction: 'AsyncReadTransaction', subscriptionId, devCtrl):NEWLINE self._onAttributeChangeCb = DefaultAttributeChangeCallbackNEWLINE self._onEventChangeCb = DefaultEventChangeCallbackNEWLINE self._readTransaction = transactionNEWLINE self._subscriptionId = subscriptionIdNEWLINE self._devCtrl = devCtrlNEWLINENEWLINE def GetAttributes(self):NEWLINE ''' Returns the attribute value cache tracking the latest state on the publisher.NEWLINE '''NEWLINE return self._readTransaction._cache.attributeCacheNEWLINENEWLINE def GetAttribute(self, path: TypedAttributePath) -> Any:NEWLINE ''' Returns a specific attribute given a TypedAttributePath.NEWLINE '''NEWLINE data = self._readTransaction._cache.attributeCacheNEWLINENEWLINE if (self._readTransaction._cache.returnClusterObject):NEWLINE return eval(f'data[path.Path.EndpointId][path.ClusterType].{path.AttributeName}')NEWLINE else:NEWLINE return data[path.Path.EndpointId][path.ClusterType][path.AttributeType]NEWLINENEWLINE def GetEvents(self):NEWLINE return self._readTransaction.GetAllEventValues()NEWLINENEWLINE def SetAttributeUpdateCallback(self, callback: Callable[[TypedAttributePath, SubscriptionTransaction], None]):NEWLINE '''NEWLINE Sets the callback function for the attribute value change event, accepts a Callable accepts an attribute path and the cached data.NEWLINE '''NEWLINE if callback is not None:NEWLINE self._onAttributeChangeCb = callbackNEWLINENEWLINE def SetEventUpdateCallback(self, callback: Callable[[EventReadResult, SubscriptionTransaction], None]):NEWLINE if callback is not None:NEWLINE self._onEventChangeCb = callbackNEWLINENEWLINE @propertyNEWLINE def OnAttributeChangeCb(self) -> Callable[[TypedAttributePath, SubscriptionTransaction], None]:NEWLINE return self._onAttributeChangeCbNEWLINENEWLINE @propertyNEWLINE def OnEventChangeCb(self) -> Callable[[EventReadResult, SubscriptionTransaction], None]:NEWLINE return self._onEventChangeCbNEWLINENEWLINE def Shutdown(self):NEWLINE self._devCtrl.ZCLShutdownSubscription(self._subscriptionId)NEWLINENEWLINE def __repr__(self):NEWLINE return f''NEWLINENEWLINENEWLINEdef DefaultAttributeChangeCallback(path: TypedAttributePath, transaction: SubscriptionTransaction):NEWLINE data = transaction.GetAttribute(path)NEWLINE value = {NEWLINE 'Endpoint': path.Path.EndpointId,NEWLINE 'Attribute': path.AttributeType,NEWLINE 'Value': dataNEWLINE }NEWLINENEWLINE print("Attribute Changed:")NEWLINE pprint(value, expand_all=True)NEWLINENEWLINENEWLINEdef DefaultEventChangeCallback(data: EventReadResult, transaction: SubscriptionTransaction):NEWLINE print("Received Event:")NEWLINE pprint(data, expand_all=True)NEWLINENEWLINENEWLINEdef _BuildEventIndex():NEWLINE ''' Build internal event index for locating the corresponding cluster object by path in the future.NEWLINE We do this because this operation will take a long time when there are lots of events, it takes about 300ms for a single query.NEWLINE This is acceptable during init, but unacceptable when the server returns lots of events at the same time.NEWLINE '''NEWLINE for clusterName, obj in inspect.getmembers(sys.modules['chip.clusters.Objects']):NEWLINE if ('chip.clusters.Objects' in str(obj)) and inspect.isclass(obj):NEWLINE for objName, subclass in inspect.getmembers(obj):NEWLINE if inspect.isclass(subclass) and (('Events' == objName)):NEWLINE for eventName, event in inspect.getmembers(subclass):NEWLINE if inspect.isclass(event):NEWLINE base_classes = inspect.getmro(event)NEWLINENEWLINE # Only match on classes that extend the ClusterEventescriptor classNEWLINE matched = [NEWLINE value for value in base_classes if 'ClusterEvent' in str(value)]NEWLINE if (matched == []):NEWLINE continueNEWLINENEWLINE _EventIndex[str(EventPath(ClusterId=event.cluster_id, EventId=event.event_id))] = eval(NEWLINE 'chip.clusters.Objects.' + clusterName + '.Events.' + eventName)NEWLINENEWLINENEWLINEclass TransactionType(Enum):NEWLINE READ_EVENTS = 1NEWLINE READ_ATTRIBUTES = 2NEWLINENEWLINENEWLINEclass AsyncReadTransaction:NEWLINE def __init__(self, future: Future, eventLoop, devCtrl, transactionType: TransactionType, returnClusterObject: bool):NEWLINE self._event_loop = eventLoopNEWLINE self._future = futureNEWLINE self._subscription_handler = NoneNEWLINE self._events = []NEWLINE self._devCtrl = devCtrlNEWLINE self._transactionType = transactionTypeNEWLINE self._cache = AttributeCache(returnClusterObject=returnClusterObject)NEWLINE self._changedPathSet = set()NEWLINENEWLINE def GetAllEventValues(self):NEWLINE return self._eventsNEWLINENEWLINE def _handleAttributeData(self, path: AttributePathWithListIndex, status: int, data: bytes):NEWLINE try:NEWLINE imStatus = statusNEWLINE try:NEWLINE imStatus = chip.interaction_model.Status(status)NEWLINE except:NEWLINE passNEWLINENEWLINE if (imStatus != chip.interaction_model.Status.Success):NEWLINE attributeValue = ValueDecodeFailure(NEWLINE None, chip.interaction_model.InteractionModelError(imStatus))NEWLINE else:NEWLINE tlvData = chip.tlv.TLVReader(data).get().get("Any", {})NEWLINE attributeValue = tlvDataNEWLINENEWLINE self._cache.UpdateTLV(path, attributeValue)NEWLINE self._changedPathSet.add(path)NEWLINENEWLINE except Exception as ex:NEWLINE logging.exception(ex)NEWLINENEWLINE def handleAttributeData(self, path: AttributePath, status: int, data: bytes):NEWLINE self._handleAttributeData(path, status, data)NEWLINENEWLINE def _handleEventData(self, header: EventHeader, path: EventPath, data: bytes):NEWLINE try:NEWLINE eventType = _EventIndex.get(str(path), None)NEWLINE eventValue = NoneNEWLINE tlvData = chip.tlv.TLVReader(data).get().get("Any", {})NEWLINE if eventType is None:NEWLINE eventValue = ValueDecodeFailure(NEWLINE tlvData, LookupError("event schema not found"))NEWLINE else:NEWLINE try:NEWLINE eventValue = eventType.FromTLV(data)NEWLINE except Exception as ex:NEWLINE logging.error(NEWLINE f"Error convering TLV to Cluster Object for path: Endpoint = {path.EndpointId}/Cluster = {path.ClusterId}/Event = {path.EventId}")NEWLINE logging.error(NEWLINE f"Failed Cluster Object: {str(eventType)}")NEWLINE logging.error(ex)NEWLINE eventValue = ValueDecodeFailure(NEWLINE tlvData, ex)NEWLINENEWLINE # If we're in debug mode, raise the exception so that we can better debug what's happening.NEWLINE if (builtins.enableDebugMode):NEWLINE raiseNEWLINENEWLINE eventResult = EventReadResult(NEWLINE Header=header, Data=eventValue, Status=chip.interaction_model.Status.Success)NEWLINE self._events.append(eventResult)NEWLINENEWLINE if (self._subscription_handler is not None):NEWLINE self._subscription_handler.OnEventChangeCb(NEWLINE eventResult, self._subscription_handler)NEWLINENEWLINE except Exception as ex:NEWLINE logging.exception(ex)NEWLINENEWLINE def handleEventData(self, header: EventHeader, path: EventPath, data: bytes):NEWLINE self._handleEventData(header, path, data)NEWLINENEWLINE def _handleError(self, chipError: int):NEWLINE self._future.set_exception(NEWLINE chip.exceptions.ChipStackError(chipError))NEWLINENEWLINE def handleError(self, chipError: int):NEWLINE self._event_loop.call_soon_threadsafe(NEWLINE self._handleError, chipErrorNEWLINE )NEWLINENEWLINE def _handleSubscriptionEstablished(self, subscriptionId):NEWLINE if not self._future.done():NEWLINE self._subscription_handler = SubscriptionTransaction(NEWLINE self, subscriptionId, self._devCtrl)NEWLINE self._future.set_result(self._subscription_handler)NEWLINENEWLINE def handleSubscriptionEstablished(self, subscriptionId):NEWLINE self._event_loop.call_soon_threadsafe(NEWLINE self._handleSubscriptionEstablished, subscriptionId)NEWLINENEWLINE def _handleReportBegin(self):NEWLINE passNEWLINENEWLINE def _handleReportEnd(self):NEWLINE self._cache.UpdateCachedData()NEWLINENEWLINE if (self._subscription_handler is not None):NEWLINE for change in self._changedPathSet:NEWLINE self._subscription_handler.OnAttributeChangeCb(NEWLINE TypedAttributePath(Path=change), self._subscription_handler)NEWLINENEWLINE # Clear it out once we've notified of all changes in this transaction.NEWLINE self._changedPathSet = set()NEWLINENEWLINE def _handleDone(self):NEWLINE if not self._future.done():NEWLINE if (self._transactionType == TransactionType.READ_EVENTS):NEWLINE self._future.set_result(self._events)NEWLINE else:NEWLINE self._future.set_result(self._cache.attributeCache)NEWLINENEWLINE def handleDone(self):NEWLINE self._event_loop.call_soon_threadsafe(self._handleDone)NEWLINENEWLINE def handleReportBegin(self):NEWLINE passNEWLINENEWLINE def handleReportEnd(self):NEWLINE # self._event_loop.call_soon_threadsafe(self._handleReportEnd)NEWLINE self._handleReportEnd()NEWLINENEWLINENEWLINEclass AsyncWriteTransaction:NEWLINE def __init__(self, future: Future, eventLoop):NEWLINE self._event_loop = eventLoopNEWLINE self._future = futureNEWLINE self._res = []NEWLINENEWLINE def _handleResponse(self, path: AttributePath, status: int):NEWLINE try:NEWLINE imStatus = chip.interaction_model.Status(status)NEWLINE self._res.append(AttributeWriteResult(Path=path, Status=imStatus))NEWLINE except:NEWLINE self._res.append(AttributeWriteResult(Path=path, Status=status))NEWLINENEWLINE def handleResponse(self, path: AttributePath, status: int):NEWLINE self._event_loop.call_soon_threadsafe(NEWLINE self._handleResponse, path, status)NEWLINENEWLINE def _handleError(self, chipError: int):NEWLINE self._future.set_exception(NEWLINE chip.exceptions.ChipStackError(chipError))NEWLINENEWLINE def handleError(self, chipError: int):NEWLINE self._event_loop.call_soon_threadsafe(NEWLINE self._handleError, chipErrorNEWLINE )NEWLINENEWLINE def _handleDone(self):NEWLINE if not self._future.done():NEWLINE self._future.set_result(self._res)NEWLINENEWLINE def handleDone(self):NEWLINE self._event_loop.call_soon_threadsafe(self._handleDone)NEWLINENEWLINENEWLINE_OnReadAttributeDataCallbackFunct = CFUNCTYPE(NEWLINE None, py_object, c_uint16, c_uint32, c_uint32, c_uint32, c_void_p, c_size_t)NEWLINE_OnSubscriptionEstablishedCallbackFunct = CFUNCTYPE(None, py_object, c_uint64)NEWLINE_OnReadEventDataCallbackFunct = CFUNCTYPE(NEWLINE None, py_object, c_uint16, c_uint32, c_uint32, c_uint32, c_uint8, c_uint64, c_uint8, c_void_p, c_size_t)NEWLINE_OnReadErrorCallbackFunct = CFUNCTYPE(NEWLINE None, py_object, c_uint32)NEWLINE_OnReadDoneCallbackFunct = CFUNCTYPE(NEWLINE None, py_object)NEWLINE_OnReportBeginCallbackFunct = CFUNCTYPE(NEWLINE None, py_object)NEWLINE_OnReportEndCallbackFunct = CFUNCTYPE(NEWLINE None, py_object)NEWLINENEWLINENEWLINE@_OnReadAttributeDataCallbackFunctNEWLINEdef _OnReadAttributeDataCallback(closure, endpoint: int, cluster: int, attribute: int, status, data, len):NEWLINE dataBytes = ctypes.string_at(data, len)NEWLINE closure.handleAttributeData(AttributePath(NEWLINE EndpointId=endpoint, ClusterId=cluster, AttributeId=attribute), status, dataBytes[:])NEWLINENEWLINENEWLINE@_OnReadEventDataCallbackFunctNEWLINEdef _OnReadEventDataCallback(closure, endpoint: int, cluster: int, event: int, number: int, priority: int, timestamp: int, timestampType: int, data, len):NEWLINE dataBytes = ctypes.string_at(data, len)NEWLINE path = EventPath(ClusterId=cluster, EventId=event)NEWLINE closure.handleEventData(EventHeader(NEWLINE EndpointId=endpoint, EventNumber=number, Priority=EventPriority(priority), Timestamp=timestamp, TimestampType=EventTimestampType(timestampType)), path, dataBytes[:])NEWLINENEWLINENEWLINE@_OnSubscriptionEstablishedCallbackFunctNEWLINEdef _OnSubscriptionEstablishedCallback(closure, subscriptionId):NEWLINE closure.handleSubscriptionEstablished(subscriptionId)NEWLINENEWLINENEWLINE@_OnReadErrorCallbackFunctNEWLINEdef _OnReadErrorCallback(closure, chiperror: int):NEWLINE closure.handleError(chiperror)NEWLINENEWLINENEWLINE@_OnReportBeginCallbackFunctNEWLINEdef _OnReportBeginCallback(closure):NEWLINE closure.handleReportBegin()NEWLINENEWLINENEWLINE@_OnReportEndCallbackFunctNEWLINEdef _OnReportEndCallback(closure):NEWLINE closure.handleReportEnd()NEWLINENEWLINENEWLINE@_OnReadDoneCallbackFunctNEWLINEdef _OnReadDoneCallback(closure):NEWLINE closure.handleDone()NEWLINE ctypes.pythonapi.Py_DecRef(ctypes.py_object(closure))NEWLINENEWLINENEWLINE_OnWriteResponseCallbackFunct = CFUNCTYPE(NEWLINE None, py_object, c_uint16, c_uint32, c_uint32, c_uint16)NEWLINE_OnWriteErrorCallbackFunct = CFUNCTYPE(NEWLINE None, py_object, c_uint32)NEWLINE_OnWriteDoneCallbackFunct = CFUNCTYPE(NEWLINE None, py_object)NEWLINENEWLINENEWLINE@_OnWriteResponseCallbackFunctNEWLINEdef _OnWriteResponseCallback(closure, endpoint: int, cluster: int, attribute: int, status):NEWLINE closure.handleResponse(AttributePath(NEWLINE EndpointId=endpoint, ClusterId=cluster, AttributeId=attribute), status)NEWLINENEWLINENEWLINE@_OnWriteErrorCallbackFunctNEWLINEdef _OnWriteErrorCallback(closure, chiperror: int):NEWLINE closure.handleError(chiperror)NEWLINENEWLINENEWLINE@_OnWriteDoneCallbackFunctNEWLINEdef _OnWriteDoneCallback(closure):NEWLINE closure.handleDone()NEWLINE ctypes.pythonapi.Py_DecRef(ctypes.py_object(closure))NEWLINENEWLINENEWLINEdef WriteAttributes(future: Future, eventLoop, device, attributes: List[AttributeWriteRequest]) -> int:NEWLINE handle = chip.native.GetLibraryHandle()NEWLINE transaction = AsyncWriteTransaction(future, eventLoop)NEWLINENEWLINE writeargs = []NEWLINE for attr in attributes:NEWLINE path = chip.interaction_model.AttributePathIBstruct.parse(NEWLINE b'\x00' * chip.interaction_model.AttributePathIBstruct.sizeof())NEWLINE path.EndpointId = attr.EndpointIdNEWLINE path.ClusterId = attr.Attribute.cluster_idNEWLINE path.AttributeId = attr.Attribute.attribute_idNEWLINE path = chip.interaction_model.AttributePathIBstruct.build(path)NEWLINE tlv = attr.Attribute.ToTLV(None, attr.Data)NEWLINE writeargs.append(ctypes.c_char_p(path))NEWLINE writeargs.append(ctypes.c_char_p(bytes(tlv)))NEWLINE writeargs.append(ctypes.c_int(len(tlv)))NEWLINENEWLINE ctypes.pythonapi.Py_IncRef(ctypes.py_object(transaction))NEWLINE res = handle.pychip_WriteClient_WriteAttributes(NEWLINE ctypes.py_object(transaction), device, ctypes.c_size_t(len(attributes)), *writeargs)NEWLINE if res != 0:NEWLINE ctypes.pythonapi.Py_DecRef(ctypes.py_object(transaction))NEWLINE return resNEWLINENEWLINENEWLINEdef ReadAttributes(future: Future, eventLoop, device, devCtrl, attributes: List[AttributePath], returnClusterObject: bool = True, subscriptionParameters: SubscriptionParameters = None) -> int:NEWLINE handle = chip.native.GetLibraryHandle()NEWLINE transaction = AsyncReadTransaction(NEWLINE future, eventLoop, devCtrl, TransactionType.READ_ATTRIBUTES, returnClusterObject)NEWLINENEWLINE readargs = []NEWLINE for attr in attributes:NEWLINE path = chip.interaction_model.AttributePathIBstruct.parse(NEWLINE b'\xff' * chip.interaction_model.AttributePathIBstruct.sizeof())NEWLINE if attr.EndpointId is not None:NEWLINE path.EndpointId = attr.EndpointIdNEWLINE if attr.ClusterId is not None:NEWLINE path.ClusterId = attr.ClusterIdNEWLINE if attr.AttributeId is not None:NEWLINE path.AttributeId = attr.AttributeIdNEWLINE path = chip.interaction_model.AttributePathIBstruct.build(path)NEWLINE readargs.append(ctypes.c_char_p(path))NEWLINENEWLINE ctypes.pythonapi.Py_IncRef(ctypes.py_object(transaction))NEWLINE minInterval = 0NEWLINE maxInterval = 0NEWLINE if subscriptionParameters is not None:NEWLINE minInterval = subscriptionParameters.MinReportIntervalFloorSecondsNEWLINE maxInterval = subscriptionParameters.MaxReportIntervalCeilingSecondsNEWLINE res = handle.pychip_ReadClient_ReadAttributes(NEWLINE ctypes.py_object(transaction), device,NEWLINE ctypes.c_bool(subscriptionParameters is not None),NEWLINE ctypes.c_uint32(minInterval), ctypes.c_uint32(maxInterval),NEWLINE ctypes.c_size_t(len(attributes)), *readargs)NEWLINE if res != 0:NEWLINE ctypes.pythonapi.Py_DecRef(ctypes.py_object(transaction))NEWLINE return resNEWLINENEWLINENEWLINEdef ReadEvents(future: Future, eventLoop, device, devCtrl, events: List[EventPath], subscriptionParameters: SubscriptionParameters = None) -> int:NEWLINE handle = chip.native.GetLibraryHandle()NEWLINE transaction = AsyncReadTransaction(NEWLINE future, eventLoop, devCtrl, TransactionType.READ_EVENTS, False)NEWLINENEWLINE readargs = []NEWLINE for attr in events:NEWLINE path = chip.interaction_model.EventPathIBstruct.parse(NEWLINE b'\xff' * chip.interaction_model.EventPathIBstruct.sizeof())NEWLINE if attr.EndpointId is not None:NEWLINE path.EndpointId = attr.EndpointIdNEWLINE if attr.ClusterId is not None:NEWLINE path.ClusterId = attr.ClusterIdNEWLINE if attr.EventId is not None:NEWLINE path.EventId = attr.EventIdNEWLINE path = chip.interaction_model.EventPathIBstruct.build(path)NEWLINE readargs.append(ctypes.c_char_p(path))NEWLINENEWLINE ctypes.pythonapi.Py_IncRef(ctypes.py_object(transaction))NEWLINE minInterval = 0NEWLINE maxInterval = 0NEWLINE if subscriptionParameters is not None:NEWLINE minInterval = subscriptionParameters.MinReportIntervalFloorSecondsNEWLINE maxInterval = subscriptionParameters.MaxReportIntervalCeilingSecondsNEWLINE res = handle.pychip_ReadClient_ReadEvents(NEWLINE ctypes.py_object(transaction), device,NEWLINE ctypes.c_bool(subscriptionParameters is not None),NEWLINE ctypes.c_uint32(minInterval), ctypes.c_uint32(maxInterval),NEWLINE ctypes.c_size_t(len(events)), *readargs)NEWLINE if res != 0:NEWLINE ctypes.pythonapi.Py_DecRef(ctypes.py_object(transaction))NEWLINE return resNEWLINENEWLINENEWLINEdef Init():NEWLINE handle = chip.native.GetLibraryHandle()NEWLINENEWLINE # Uses one of the type decorators as an indicator for everything beingNEWLINE # initialized.NEWLINE if not handle.pychip_WriteClient_InitCallbacks.argtypes:NEWLINE setter = chip.native.NativeLibraryHandleMethodArguments(handle)NEWLINENEWLINE handle.pychip_WriteClient_WriteAttributes.restype = c_uint32NEWLINE setter.Set('pychip_WriteClient_InitCallbacks', None, [NEWLINE _OnWriteResponseCallbackFunct, _OnWriteErrorCallbackFunct, _OnWriteDoneCallbackFunct])NEWLINE handle.pychip_ReadClient_ReadAttributes.restype = c_uint32NEWLINE setter.Set('pychip_ReadClient_InitCallbacks', None, [NEWLINE _OnReadAttributeDataCallbackFunct, _OnReadEventDataCallbackFunct, _OnSubscriptionEstablishedCallbackFunct, _OnReadErrorCallbackFunct, _OnReadDoneCallbackFunct,NEWLINE _OnReportBeginCallbackFunct, _OnReportEndCallbackFunct])NEWLINENEWLINE handle.pychip_WriteClient_InitCallbacks(NEWLINE _OnWriteResponseCallback, _OnWriteErrorCallback, _OnWriteDoneCallback)NEWLINE handle.pychip_ReadClient_InitCallbacks(NEWLINE _OnReadAttributeDataCallback, _OnReadEventDataCallback, _OnSubscriptionEstablishedCallback, _OnReadErrorCallback, _OnReadDoneCallback,NEWLINE _OnReportBeginCallback, _OnReportEndCallback)NEWLINENEWLINE _BuildAttributeIndex()NEWLINE _BuildClusterIndex()NEWLINE _BuildEventIndex()NEWLINE import osNEWLINEimport pickleNEWLINEimport uuidNEWLINENEWLINEimport dagstermillNEWLINEfrom dagstermill.io_managers import local_output_notebook_io_managerNEWLINENEWLINEfrom dagster import (NEWLINE Field,NEWLINE FileHandle,NEWLINE InputDefinition,NEWLINE Int,NEWLINE List,NEWLINE ModeDefinition,NEWLINE OutputDefinition,NEWLINE ResourceDefinition,NEWLINE String,NEWLINE composite_solid,NEWLINE fs_io_manager,NEWLINE job,NEWLINE pipeline,NEWLINE repository,NEWLINE resource,NEWLINE solid,NEWLINE)NEWLINEfrom dagster.core.storage.file_manager import local_file_managerNEWLINEfrom dagster.utils import PICKLE_PROTOCOL, file_relative_pathNEWLINENEWLINEtry:NEWLINE from dagster_pandas import DataFrameNEWLINENEWLINE DAGSTER_PANDAS_PRESENT = TrueNEWLINEexcept ImportError:NEWLINE DAGSTER_PANDAS_PRESENT = FalseNEWLINENEWLINEtry:NEWLINE import sklearn as _NEWLINENEWLINE SKLEARN_PRESENT = TrueNEWLINEexcept ImportError:NEWLINE SKLEARN_PRESENT = FalseNEWLINENEWLINEtry:NEWLINE import matplotlib as _NEWLINENEWLINE MATPLOTLIB_PRESENT = TrueNEWLINEexcept ImportError:NEWLINE MATPLOTLIB_PRESENT = FalseNEWLINENEWLINENEWLINEclass BasicTest:NEWLINE def __init__(self, x):NEWLINE self.x = xNEWLINENEWLINE def __repr__(self):NEWLINE return "BasicTest: {x}".format(x=str(self.x))NEWLINENEWLINENEWLINEdef nb_test_path(name):NEWLINE return file_relative_path(__file__, f"notebooks/{name}.ipynb")NEWLINENEWLINENEWLINEdef test_nb_solid(name, **kwargs):NEWLINE output_defs = kwargs.pop("output_defs", [OutputDefinition(is_required=False)])NEWLINENEWLINE return dagstermill.define_dagstermill_solid(NEWLINE name=name,NEWLINE notebook_path=nb_test_path(name),NEWLINE output_notebook_name="notebook",NEWLINE output_defs=output_defs,NEWLINE **kwargs,NEWLINE )NEWLINENEWLINENEWLINEdef test_nb_op(name, path, **kwargs):NEWLINE output_defs = kwargs.pop("output_defs", [OutputDefinition(is_required=False)])NEWLINENEWLINE return dagstermill.define_dagstermill_op(NEWLINE name=name,NEWLINE notebook_path=path,NEWLINE output_notebook_name="notebook",NEWLINE output_defs=output_defs,NEWLINE **kwargs,NEWLINE )NEWLINENEWLINENEWLINEdefault_mode_defs = [NEWLINE ModeDefinition(NEWLINE resource_defs={NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE "io_manager": fs_io_manager,NEWLINE }NEWLINE )NEWLINE]NEWLINENEWLINENEWLINEhello_world = test_nb_solid("hello_world", output_defs=[])NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_world_pipeline():NEWLINE hello_world()NEWLINENEWLINENEWLINEhello_world_op = test_nb_op(NEWLINE "hello_world_op",NEWLINE nb_test_path("hello_world"),NEWLINE output_defs=[],NEWLINE)NEWLINENEWLINENEWLINEdef build_hello_world_job():NEWLINE @job(NEWLINE resource_defs={NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE }NEWLINE )NEWLINE def hello_world_job():NEWLINE hello_world_op()NEWLINENEWLINE return hello_world_jobNEWLINENEWLINENEWLINEhello_world_with_custom_tags_and_description = dagstermill.define_dagstermill_solid(NEWLINE name="hello_world_custom",NEWLINE notebook_path=nb_test_path("hello_world"),NEWLINE output_notebook_name="notebook",NEWLINE tags={"foo": "bar"},NEWLINE description="custom description",NEWLINE)NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_world_with_custom_tags_and_description_pipeline():NEWLINE hello_world_with_custom_tags_and_description()NEWLINENEWLINENEWLINEhello_world_config = test_nb_solid(NEWLINE "hello_world_config",NEWLINE config_schema={"greeting": Field(String, is_required=False, default_value="hello")},NEWLINE)NEWLINENEWLINENEWLINEgoodbye_config = dagstermill.define_dagstermill_solid(NEWLINE name="goodbye_config",NEWLINE notebook_path=nb_test_path("print_dagstermill_context_solid_config"),NEWLINE output_notebook_name="notebook",NEWLINE config_schema={"farewell": Field(String, is_required=False, default_value="goodbye")},NEWLINE)NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_world_config_pipeline():NEWLINE hello_world_config()NEWLINE goodbye_config()NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef alias_config_pipeline():NEWLINE hello_world_config.alias("aliased_greeting")()NEWLINE goodbye_config.alias("aliased_goodbye")()NEWLINENEWLINENEWLINE@solid(input_defs=[InputDefinition("notebook")])NEWLINEdef load_notebook(notebook):NEWLINE return notebookNEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_world_with_output_notebook_pipeline():NEWLINE notebook = hello_world()NEWLINE load_notebook(notebook)NEWLINENEWLINENEWLINEhello_world_no_output_notebook_no_file_manager = dagstermill.define_dagstermill_solid(NEWLINE name="hello_world_no_output_notebook_no_file_manager",NEWLINE notebook_path=nb_test_path("hello_world"),NEWLINE)NEWLINENEWLINENEWLINE@pipelineNEWLINEdef hello_world_no_output_notebook_no_file_manager_pipeline():NEWLINE hello_world_no_output_notebook_no_file_manager()NEWLINENEWLINENEWLINEhello_world_no_output_notebook = dagstermill.define_dagstermill_solid(NEWLINE name="hello_world_no_output_notebook",NEWLINE notebook_path=nb_test_path("hello_world"),NEWLINE)NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_world_no_output_notebook_pipeline():NEWLINE hello_world_no_output_notebook()NEWLINENEWLINENEWLINEhello_world_output = test_nb_solid("hello_world_output", output_defs=[OutputDefinition(str)])NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_world_output_pipeline():NEWLINE hello_world_output()NEWLINENEWLINENEWLINEhello_world_explicit_yield = test_nb_solid(NEWLINE "hello_world_explicit_yield", output_defs=[OutputDefinition(str)]NEWLINE)NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_world_explicit_yield_pipeline():NEWLINE hello_world_explicit_yield()NEWLINENEWLINENEWLINEhello_logging = test_nb_solid("hello_logging")NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef hello_logging_pipeline():NEWLINE hello_logging()NEWLINENEWLINENEWLINEadd_two_numbers = test_nb_solid(NEWLINE "add_two_numbers",NEWLINE input_defs=[NEWLINE InputDefinition(name="a", dagster_type=Int),NEWLINE InputDefinition(name="b", dagster_type=Int),NEWLINE ],NEWLINE output_defs=[OutputDefinition(Int)],NEWLINE)NEWLINENEWLINENEWLINEmult_two_numbers = test_nb_solid(NEWLINE "mult_two_numbers",NEWLINE input_defs=[NEWLINE InputDefinition(name="a", dagster_type=Int),NEWLINE InputDefinition(name="b", dagster_type=Int),NEWLINE ],NEWLINE output_defs=[OutputDefinition(Int)],NEWLINE)NEWLINENEWLINENEWLINE@solidNEWLINEdef return_one():NEWLINE return 1NEWLINENEWLINENEWLINE@solidNEWLINEdef return_two():NEWLINE return 2NEWLINENEWLINENEWLINE@solidNEWLINEdef return_three():NEWLINE return 3NEWLINENEWLINENEWLINE@solidNEWLINEdef return_four():NEWLINE return 4NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef add_pipeline():NEWLINE add_two_numbers(return_one(), return_two())NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef double_add_pipeline():NEWLINE add_two_numbers.alias("add_two_numbers_1")(return_one(), return_two())NEWLINE add_two_numbers.alias("add_two_numbers_2")(return_three(), return_four())NEWLINENEWLINENEWLINE@solid(input_defs=[], config_schema=Int)NEWLINEdef load_constant(context):NEWLINE return context.solid_configNEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef notebook_dag_pipeline():NEWLINE a = load_constant.alias("load_a")()NEWLINE b = load_constant.alias("load_b")()NEWLINE num, _ = add_two_numbers(a, b)NEWLINE mult_two_numbers(num, b)NEWLINENEWLINENEWLINEerror_notebook = test_nb_solid("error_notebook")NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef error_pipeline():NEWLINE error_notebook()NEWLINENEWLINENEWLINEif DAGSTER_PANDAS_PRESENT and SKLEARN_PRESENT and MATPLOTLIB_PRESENT:NEWLINENEWLINE clean_data = test_nb_solid("clean_data", output_defs=[OutputDefinition(DataFrame)])NEWLINENEWLINE # FIXME add an output to thisNEWLINE tutorial_LR = test_nb_solid(NEWLINE "tutorial_LR",NEWLINE input_defs=[InputDefinition(name="df", dagster_type=DataFrame)],NEWLINE )NEWLINENEWLINE tutorial_RF = test_nb_solid(NEWLINE "tutorial_RF",NEWLINE input_defs=[InputDefinition(name="df", dagster_type=DataFrame)],NEWLINE )NEWLINENEWLINE @pipeline(mode_defs=default_mode_defs)NEWLINE def tutorial_pipeline():NEWLINE dfr, _ = clean_data()NEWLINE # FIXME get better names for theseNEWLINE tutorial_LR(dfr)NEWLINE tutorial_RF(dfr)NEWLINENEWLINENEWLINE@solid("resource_solid", required_resource_keys={"list"})NEWLINEdef resource_solid(context):NEWLINE context.resources.list.append("Hello, solid!")NEWLINE return TrueNEWLINENEWLINENEWLINEhello_world_resource = test_nb_solid(NEWLINE "hello_world_resource",NEWLINE input_defs=[InputDefinition("nonce")],NEWLINE required_resource_keys={"list"},NEWLINE)NEWLINENEWLINEhello_world_resource_with_exception = test_nb_solid(NEWLINE "hello_world_resource_with_exception",NEWLINE input_defs=[InputDefinition("nonce")],NEWLINE required_resource_keys={"list"},NEWLINE)NEWLINENEWLINENEWLINEclass FilePickleList:NEWLINE # This is not thread- or anything else-safeNEWLINE def __init__(self, path):NEWLINE self.closed = FalseNEWLINE self.id = str(uuid.uuid4())[-6:]NEWLINE self.path = pathNEWLINE self.list = []NEWLINE if not os.path.exists(self.path):NEWLINE self.write()NEWLINE self.read()NEWLINE self.open()NEWLINENEWLINE def open(self):NEWLINE self.read()NEWLINE self.append("Opened")NEWLINENEWLINE def append(self, obj):NEWLINE self.read()NEWLINE self.list.append(self.id + ": " + obj)NEWLINE self.write()NEWLINENEWLINE def read(self):NEWLINE with open(self.path, "rb") as fd:NEWLINE self.list = pickle.load(fd)NEWLINE return self.listNEWLINENEWLINE def write(self):NEWLINE with open(self.path, "wb") as fd:NEWLINE pickle.dump(self.list, fd, protocol=PICKLE_PROTOCOL)NEWLINENEWLINE def close(self):NEWLINE self.append("Closed")NEWLINE self.closed = TrueNEWLINENEWLINENEWLINE@resource(config_schema=Field(String))NEWLINEdef filepicklelist_resource(init_context):NEWLINE filepicklelist = FilePickleList(init_context.resource_config)NEWLINE try:NEWLINE yield filepicklelistNEWLINE finally:NEWLINE filepicklelist.close()NEWLINENEWLINENEWLINE@pipeline(NEWLINE mode_defs=[NEWLINE ModeDefinition(NEWLINE name="test",NEWLINE resource_defs={NEWLINE "list": ResourceDefinition(lambda _: []),NEWLINE "io_manager": fs_io_manager,NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE },NEWLINE ),NEWLINE ModeDefinition(NEWLINE name="prod",NEWLINE resource_defs={NEWLINE "list": filepicklelist_resource,NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE "io_manager": fs_io_manager,NEWLINE },NEWLINE ),NEWLINE ]NEWLINE)NEWLINEdef resource_pipeline():NEWLINE hello_world_resource(resource_solid())NEWLINENEWLINENEWLINE@pipeline(NEWLINE mode_defs=[NEWLINE ModeDefinition(NEWLINE resource_defs={NEWLINE "list": filepicklelist_resource,NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE "io_manager": fs_io_manager,NEWLINE }NEWLINE )NEWLINE ]NEWLINE)NEWLINEdef resource_with_exception_pipeline():NEWLINE hello_world_resource_with_exception(resource_solid())NEWLINENEWLINENEWLINEbad_kernel = test_nb_solid("bad_kernel")NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef bad_kernel_pipeline():NEWLINE bad_kernel()NEWLINENEWLINENEWLINEreimport = test_nb_solid(NEWLINE "reimport", input_defs=[InputDefinition("l", List[int])], output_defs=[OutputDefinition(int)]NEWLINE)NEWLINENEWLINENEWLINE@solidNEWLINEdef lister():NEWLINE return [1, 2, 3]NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef reimport_pipeline():NEWLINE reimport(lister())NEWLINENEWLINENEWLINEyield_3 = test_nb_solid("yield_3", output_defs=[OutputDefinition(Int)])NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef yield_3_pipeline():NEWLINE yield_3()NEWLINENEWLINENEWLINEyield_obj = test_nb_solid("yield_obj")NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef yield_obj_pipeline():NEWLINE yield_obj()NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef retries_pipeline():NEWLINE test_nb_solid("raise_retry")()NEWLINE test_nb_solid("yield_retry")()NEWLINENEWLINENEWLINE@pipeline(mode_defs=default_mode_defs)NEWLINEdef failure_pipeline():NEWLINE test_nb_solid("raise_failure")()NEWLINE test_nb_solid("yield_failure")()NEWLINENEWLINENEWLINEyield_something = test_nb_solid(NEWLINE "yield_something",NEWLINE input_defs=[InputDefinition("obj", str)],NEWLINE output_defs=[OutputDefinition(str, "result")],NEWLINE)NEWLINENEWLINENEWLINE@solidNEWLINEdef fan_in(a, b):NEWLINE return f"{a} {b}"NEWLINENEWLINENEWLINE@pipeline(NEWLINE mode_defs=[NEWLINE ModeDefinition(NEWLINE resource_defs={NEWLINE "io_manager": fs_io_manager,NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE }NEWLINE )NEWLINE ]NEWLINE)NEWLINEdef fan_in_notebook_pipeline():NEWLINE val_a, _ = yield_something.alias("solid_1")()NEWLINE val_b, _ = yield_something.alias("solid_2")()NEWLINE fan_in(val_a, val_b)NEWLINENEWLINENEWLINE@pipeline(NEWLINE mode_defs=[NEWLINE ModeDefinition(NEWLINE resource_defs={NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE }NEWLINE )NEWLINE ]NEWLINE)NEWLINEdef fan_in_notebook_pipeline_in_mem():NEWLINE val_a, _ = yield_something.alias("solid_1")()NEWLINE val_b, _ = yield_something.alias("solid_2")()NEWLINE fan_in(val_a, val_b)NEWLINENEWLINENEWLINE@composite_solidNEWLINEdef outer():NEWLINE yield_something()NEWLINENEWLINENEWLINE@pipeline(NEWLINE mode_defs=[NEWLINE ModeDefinition(NEWLINE resource_defs={NEWLINE "io_manager": fs_io_manager,NEWLINE "output_notebook_io_manager": local_output_notebook_io_manager,NEWLINE }NEWLINE )NEWLINE ]NEWLINE)NEWLINEdef composite_pipeline():NEWLINE outer()NEWLINENEWLINENEWLINE###################################################################################################NEWLINE# Back compatNEWLINE###################################################################################################NEWLINENEWLINEhello_world_legacy = dagstermill.define_dagstermill_solid(NEWLINE name="hello_world_legacy",NEWLINE notebook_path=nb_test_path("hello_world"),NEWLINE output_notebook="notebook",NEWLINE)NEWLINENEWLINENEWLINE@solid(input_defs=[InputDefinition("notebook", dagster_type=FileHandle)])NEWLINEdef load_notebook_legacy(notebook):NEWLINE return os.path.exists(notebook.path_desc)NEWLINENEWLINENEWLINE@pipeline(NEWLINE mode_defs=[NEWLINE ModeDefinition(NEWLINE resource_defs={NEWLINE "io_manager": fs_io_manager,NEWLINE "file_manager": local_file_manager,NEWLINE }NEWLINE )NEWLINE ]NEWLINE)NEWLINEdef hello_world_with_output_notebook_pipeline_legacy():NEWLINE notebook = hello_world_legacy()NEWLINE load_notebook_legacy(notebook)NEWLINENEWLINENEWLINE@repositoryNEWLINEdef notebook_repo():NEWLINE pipelines = [NEWLINE bad_kernel_pipeline,NEWLINE error_pipeline,NEWLINE hello_world_pipeline,NEWLINE hello_world_with_custom_tags_and_description_pipeline,NEWLINE hello_world_config_pipeline,NEWLINE hello_world_explicit_yield_pipeline,NEWLINE hello_world_output_pipeline,NEWLINE hello_world_with_output_notebook_pipeline,NEWLINE hello_logging_pipeline,NEWLINE resource_pipeline,NEWLINE resource_with_exception_pipeline,NEWLINE add_pipeline,NEWLINE notebook_dag_pipeline,NEWLINE reimport_pipeline,NEWLINE yield_3_pipeline,NEWLINE yield_obj_pipeline,NEWLINE retries_pipeline,NEWLINE failure_pipeline,NEWLINE fan_in_notebook_pipeline_in_mem,NEWLINE fan_in_notebook_pipeline,NEWLINE hello_world_no_output_notebook_no_file_manager_pipeline,NEWLINE hello_world_with_output_notebook_pipeline_legacy,NEWLINE ]NEWLINE if DAGSTER_PANDAS_PRESENT and SKLEARN_PRESENT and MATPLOTLIB_PRESENT:NEWLINE pipelines += [tutorial_pipeline]NEWLINENEWLINE return pipelinesNEWLINE # ==============================================================================NEWLINE# zero.pyNEWLINE# ==============================================================================NEWLINENEWLINEimport osNEWLINEimport sysNEWLINENEWLINEERROR = FalseNEWLINENEWLINEdef main(function):NEWLINE try:NEWLINE arguments = sys.argv[1:]NEWLINE assert argumentsNEWLINE for path in arguments:NEWLINE assert os.path.isdir(path)NEWLINE for path in arguments:NEWLINE engine(path, function)NEWLINE except:NEWLINE sys.stdout.write('Usage: %s ' % os.path.basename(sys.argv[0]))NEWLINENEWLINEdef engine(path, function):NEWLINE global ERRORNEWLINE for root, dirs, files in os.walk(path):NEWLINE for name in files:NEWLINE path = os.path.join(root, name)NEWLINE try:NEWLINE function(path)NEWLINE except:NEWLINE sys.stderr.write('%sError: %s' % (ERROR and '\n' or '', path))NEWLINE ERROR = TrueNEWLINENEWLINEdef zero(path):NEWLINE size = os.path.getsize(path)NEWLINE if size:NEWLINE data = open(path, 'wb')NEWLINE todo = sizeNEWLINE if todo >= 2 ** 20:NEWLINE buff = '\x00' * 2 ** 20NEWLINE while todo >= 2 ** 20:NEWLINE data.write(buff)NEWLINE todo = size - data.tell()NEWLINE data.write('\x00' * todo)NEWLINE data.close()NEWLINENEWLINEif __name__ == '__main__':NEWLINE main(zero)NEWLINENEWLINE# ==============================================================================NEWLINE# upper.pyNEWLINE# ==============================================================================NEWLINENEWLINEimport zeroNEWLINENEWLINEdef upper(path):NEWLINE root, ext = zero.os.path.splitext(path)NEWLINE upper = ext.upper()NEWLINE if ext != upper:NEWLINE zero.os.rename(path, root + upper)NEWLINENEWLINEif __name__ == '__main__':NEWLINE zero.main(upper)NEWLINENEWLINE# ==============================================================================NEWLINE# untar.pyNEWLINE# ==============================================================================NEWLINENEWLINEimport zeroNEWLINEimport tarfileNEWLINENEWLINEif __name__ == '__main__':NEWLINE zero.main(lambda path: tarfile.open(path).extractall(NEWLINE zero.os.path.dirname(path)))NEWLINENEWLINE# ==============================================================================NEWLINE# remove.pyNEWLINE# ==============================================================================NEWLINENEWLINEimport zeroNEWLINENEWLINEif __name__ == '__main__':NEWLINE zero.main(zero.os.remove)NEWLINENEWLINE# ==============================================================================NEWLINE# one.pyNEWLINE# ==============================================================================NEWLINENEWLINEimport zeroNEWLINENEWLINEdef one(path):NEWLINE size = zero.os.path.getsize(path)NEWLINE if size:NEWLINE data = open(path, 'wb')NEWLINE todo = sizeNEWLINE if todo >= 2 ** 20:NEWLINE buff = '\xFF' * 2 ** 20NEWLINE while todo >= 2 ** 20:NEWLINE data.write(buff)NEWLINE todo = size - data.tell()NEWLINE data.write('\xFF' * todo)NEWLINE data.close()NEWLINENEWLINEif __name__ == '__main__':NEWLINE zero.main(one)NEWLINENEWLINE# ==============================================================================NEWLINE# lower.pyNEWLINE# ==============================================================================NEWLINENEWLINEimport zeroNEWLINENEWLINEdef lower(path):NEWLINE root, ext = zero.os.path.splitext(path)NEWLINE lower = ext.lower()NEWLINE if ext != lower:NEWLINE zero.os.rename(path, root + lower)NEWLINENEWLINEif __name__ == '__main__':NEWLINE zero.main(lower)NEWLINENEWLINE# ==============================================================================NEWLINE# random.pyNEWLINE# ==============================================================================NEWLINENEWLINEimport zeroNEWLINENEWLINEdef kaos(path):NEWLINE size = zero.os.path.getsize(path)NEWLINE if size:NEWLINE data = open(path, 'wb')NEWLINE todo = sizeNEWLINE while todo:NEWLINE data.write(zero.os.urandom(min(todo, 2 ** 20)))NEWLINE todo = size - data.tell()NEWLINE data.close()NEWLINENEWLINEif __name__ == '__main__':NEWLINE zero.main(kaos)NEWLINENEWLINE# ==============================================================================NEWLINE# name.pyNEWLINE# ==============================================================================NEWLINENEWLINEimport zeroNEWLINEimport randomNEWLINENEWLINESTRING = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'NEWLINENEWLINEdef ident(path):NEWLINE d, b = zero.os.path.split(path)NEWLINE zero.os.rename(path, zero.os.path.join(d, ''.join(random.sample(NEWLINE STRING, len(STRING))) + zero.os.path.splitext(b)[1]))NEWLINENEWLINEif __name__ == '__main__':NEWLINE zero.main(ident)NEWLINENEWLINE# ==============================================================================NEWLINE# newlines.pyNEWLINE# ==============================================================================NEWLINENEWLINEimport zeroNEWLINENEWLINETABLE = ''.join(map(chr, range(256)))NEWLINEDELETECHARS = ''.join(c for c in TABLE if len(repr(c)) != 6)NEWLINENEWLINEdef convert(path):NEWLINE if not file(path, 'rb').read(2 ** 20).translate(TABLE, DELETECHARS):NEWLINE data = file(path, 'r').read()NEWLINE file(path, 'w').write(data)NEWLINENEWLINEif __name__ == '__main__':NEWLINE zero.main(convert)NEWLINENEWLINE# ==============================================================================NEWLINE# extension.pyNEWLINE# ==============================================================================NEWLINENEWLINEimport zeroNEWLINENEWLINEdef bias(path):NEWLINE root, ext = zero.os.path.splitext(path)NEWLINE if not ext[1:]:NEWLINE zero.os.rename(path, root + '.txt')NEWLINENEWLINEif __name__ == '__main__':NEWLINE zero.main(bias)NEWLINE # coding=utf-8NEWLINE# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***NEWLINE# *** Do not edit by hand unless you're certain you know what you are doing! ***NEWLINENEWLINEimport jsonNEWLINEimport warningsNEWLINEimport pulumiNEWLINEimport pulumi.runtimeNEWLINEfrom typing import UnionNEWLINEfrom .. import utilities, tablesNEWLINENEWLINEclass Registry(pulumi.CustomResource):NEWLINE admin_enabled: pulumi.Output[bool]NEWLINE """NEWLINE Specifies whether the admin user is enabled. Defaults to `false`.NEWLINE """NEWLINE admin_password: pulumi.Output[str]NEWLINE """NEWLINE The Password associated with the Container Registry Admin account - if the admin account is enabled.NEWLINE """NEWLINE admin_username: pulumi.Output[str]NEWLINE """NEWLINE The Username associated with the Container Registry Admin account - if the admin account is enabled.NEWLINE """NEWLINE georeplication_locations: pulumi.Output[list]NEWLINE """NEWLINE A list of Azure locations where the container registry should be geo-replicated.NEWLINE """NEWLINE location: pulumi.Output[str]NEWLINE """NEWLINE Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.NEWLINE """NEWLINE login_server: pulumi.Output[str]NEWLINE """NEWLINE The URL that can be used to log into the container registry.NEWLINE """NEWLINE name: pulumi.Output[str]NEWLINE """NEWLINE Specifies the name of the Container Registry. Changing this forces a new resource to be created.NEWLINE """NEWLINE network_rule_set: pulumi.Output[dict]NEWLINE """NEWLINE A `network_rule_set` block as documented below.NEWLINENEWLINE * `default_action` (`str`) - The behaviour for requests matching no rules. Either `Allow` or `Deny`. Defaults to `Allow`NEWLINE * `ip_rules` (`list`) - One or more `ip_rule` blocks as defined below.NEWLINE * `action` (`str`) - The behaviour for requests matching this rule. At this time the only supported value is `Allow`NEWLINE * `ipRange` (`str`) - The CIDR block from which requests will match the rule.NEWLINENEWLINE * `virtualNetworks` (`list`) - One or more `virtual_network` blocks as defined below.NEWLINE * `action` (`str`) - The behaviour for requests matching this rule. At this time the only supported value is `Allow`NEWLINE * `subnet_id` (`str`) - The subnet id from which requests will match the rule.NEWLINE """NEWLINE resource_group_name: pulumi.Output[str]NEWLINE """NEWLINE The name of the resource group in which to create the Container Registry. Changing this forces a new resource to be created.NEWLINE """NEWLINE sku: pulumi.Output[str]NEWLINE """NEWLINE The SKU name of the container registry. Possible values are `Basic`, `Standard` and `Premium`. `Classic` (which was previously `Basic`) is supported only for existing resources.NEWLINE """NEWLINE storage_account_id: pulumi.Output[str]NEWLINE """NEWLINE The ID of a Storage Account which must be located in the same Azure Region as the Container Registry.NEWLINE """NEWLINE tags: pulumi.Output[dict]NEWLINE """NEWLINE A mapping of tags to assign to the resource.NEWLINE """NEWLINE def __init__(__self__, resource_name, opts=None, admin_enabled=None, georeplication_locations=None, location=None, name=None, network_rule_set=None, resource_group_name=None, sku=None, storage_account_id=None, tags=None, __props__=None, __name__=None, __opts__=None):NEWLINE """NEWLINE Manages an Azure Container Registry.NEWLINENEWLINE ## Example UsageNEWLINENEWLINENEWLINENEWLINE ```pythonNEWLINE import pulumiNEWLINE import pulumi_azure as azureNEWLINENEWLINE rg = azure.core.ResourceGroup("rg", location="West US")NEWLINE acr = azure.containerservice.Registry("acr",NEWLINE resource_group_name=rg.name,NEWLINE location=rg.location,NEWLINE sku="Premium",NEWLINE admin_enabled=False,NEWLINE georeplication_locations=[NEWLINE "East US",NEWLINE "West Europe",NEWLINE ])NEWLINE ```NEWLINENEWLINENEWLINE :param str resource_name: The name of the resource.NEWLINE :param pulumi.ResourceOptions opts: Options for the resource.NEWLINE :param pulumi.Input[bool] admin_enabled: Specifies whether the admin user is enabled. Defaults to `false`.NEWLINE :param pulumi.Input[list] georeplication_locations: A list of Azure locations where the container registry should be geo-replicated.NEWLINE :param pulumi.Input[str] location: Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.NEWLINE :param pulumi.Input[str] name: Specifies the name of the Container Registry. Changing this forces a new resource to be created.NEWLINE :param pulumi.Input[dict] network_rule_set: A `network_rule_set` block as documented below.NEWLINE :param pulumi.Input[str] resource_group_name: The name of the resource group in which to create the Container Registry. Changing this forces a new resource to be created.NEWLINE :param pulumi.Input[str] sku: The SKU name of the container registry. Possible values are `Basic`, `Standard` and `Premium`. `Classic` (which was previously `Basic`) is supported only for existing resources.NEWLINE :param pulumi.Input[str] storage_account_id: The ID of a Storage Account which must be located in the same Azure Region as the Container Registry.NEWLINE :param pulumi.Input[dict] tags: A mapping of tags to assign to the resource.NEWLINENEWLINE The **network_rule_set** object supports the following:NEWLINENEWLINE * `default_action` (`pulumi.Input[str]`) - The behaviour for requests matching no rules. Either `Allow` or `Deny`. Defaults to `Allow`NEWLINE * `ip_rules` (`pulumi.Input[list]`) - One or more `ip_rule` blocks as defined below.NEWLINE * `action` (`pulumi.Input[str]`) - The behaviour for requests matching this rule. At this time the only supported value is `Allow`NEWLINE * `ipRange` (`pulumi.Input[str]`) - The CIDR block from which requests will match the rule.NEWLINENEWLINE * `virtualNetworks` (`pulumi.Input[list]`) - One or more `virtual_network` blocks as defined below.NEWLINE * `action` (`pulumi.Input[str]`) - The behaviour for requests matching this rule. At this time the only supported value is `Allow`NEWLINE * `subnet_id` (`pulumi.Input[str]`) - The subnet id from which requests will match the rule.NEWLINE """NEWLINE if __name__ is not None:NEWLINE warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)NEWLINE resource_name = __name__NEWLINE if __opts__ is not None:NEWLINE warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)NEWLINE opts = __opts__NEWLINE if opts is None:NEWLINE opts = pulumi.ResourceOptions()NEWLINE if not isinstance(opts, pulumi.ResourceOptions):NEWLINE raise TypeError('Expected resource options to be a ResourceOptions instance')NEWLINE if opts.version is None:NEWLINE opts.version = utilities.get_version()NEWLINE if opts.id is None:NEWLINE if __props__ is not None:NEWLINE raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')NEWLINE __props__ = dict()NEWLINENEWLINE __props__['admin_enabled'] = admin_enabledNEWLINE __props__['georeplication_locations'] = georeplication_locationsNEWLINE __props__['location'] = locationNEWLINE __props__['name'] = nameNEWLINE __props__['network_rule_set'] = network_rule_setNEWLINE if resource_group_name is None:NEWLINE raise TypeError("Missing required property 'resource_group_name'")NEWLINE __props__['resource_group_name'] = resource_group_nameNEWLINE __props__['sku'] = skuNEWLINE __props__['storage_account_id'] = storage_account_idNEWLINE __props__['tags'] = tagsNEWLINE __props__['admin_password'] = NoneNEWLINE __props__['admin_username'] = NoneNEWLINE __props__['login_server'] = NoneNEWLINE super(Registry, __self__).__init__(NEWLINE 'azure:containerservice/registry:Registry',NEWLINE resource_name,NEWLINE __props__,NEWLINE opts)NEWLINENEWLINE @staticmethodNEWLINE def get(resource_name, id, opts=None, admin_enabled=None, admin_password=None, admin_username=None, georeplication_locations=None, location=None, login_server=None, name=None, network_rule_set=None, resource_group_name=None, sku=None, storage_account_id=None, tags=None):NEWLINE """NEWLINE Get an existing Registry resource's state with the given name, id, and optional extraNEWLINE properties used to qualify the lookup.NEWLINENEWLINE :param str resource_name: The unique name of the resulting resource.NEWLINE :param str id: The unique provider ID of the resource to lookup.NEWLINE :param pulumi.ResourceOptions opts: Options for the resource.NEWLINE :param pulumi.Input[bool] admin_enabled: Specifies whether the admin user is enabled. Defaults to `false`.NEWLINE :param pulumi.Input[str] admin_password: The Password associated with the Container Registry Admin account - if the admin account is enabled.NEWLINE :param pulumi.Input[str] admin_username: The Username associated with the Container Registry Admin account - if the admin account is enabled.NEWLINE :param pulumi.Input[list] georeplication_locations: A list of Azure locations where the container registry should be geo-replicated.NEWLINE :param pulumi.Input[str] location: Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.NEWLINE :param pulumi.Input[str] login_server: The URL that can be used to log into the container registry.NEWLINE :param pulumi.Input[str] name: Specifies the name of the Container Registry. Changing this forces a new resource to be created.NEWLINE :param pulumi.Input[dict] network_rule_set: A `network_rule_set` block as documented below.NEWLINE :param pulumi.Input[str] resource_group_name: The name of the resource group in which to create the Container Registry. Changing this forces a new resource to be created.NEWLINE :param pulumi.Input[str] sku: The SKU name of the container registry. Possible values are `Basic`, `Standard` and `Premium`. `Classic` (which was previously `Basic`) is supported only for existing resources.NEWLINE :param pulumi.Input[str] storage_account_id: The ID of a Storage Account which must be located in the same Azure Region as the Container Registry.NEWLINE :param pulumi.Input[dict] tags: A mapping of tags to assign to the resource.NEWLINENEWLINE The **network_rule_set** object supports the following:NEWLINENEWLINE * `default_action` (`pulumi.Input[str]`) - The behaviour for requests matching no rules. Either `Allow` or `Deny`. Defaults to `Allow`NEWLINE * `ip_rules` (`pulumi.Input[list]`) - One or more `ip_rule` blocks as defined below.NEWLINE * `action` (`pulumi.Input[str]`) - The behaviour for requests matching this rule. At this time the only supported value is `Allow`NEWLINE * `ipRange` (`pulumi.Input[str]`) - The CIDR block from which requests will match the rule.NEWLINENEWLINE * `virtualNetworks` (`pulumi.Input[list]`) - One or more `virtual_network` blocks as defined below.NEWLINE * `action` (`pulumi.Input[str]`) - The behaviour for requests matching this rule. At this time the only supported value is `Allow`NEWLINE * `subnet_id` (`pulumi.Input[str]`) - The subnet id from which requests will match the rule.NEWLINE """NEWLINE opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))NEWLINENEWLINE __props__ = dict()NEWLINENEWLINE __props__["admin_enabled"] = admin_enabledNEWLINE __props__["admin_password"] = admin_passwordNEWLINE __props__["admin_username"] = admin_usernameNEWLINE __props__["georeplication_locations"] = georeplication_locationsNEWLINE __props__["location"] = locationNEWLINE __props__["login_server"] = login_serverNEWLINE __props__["name"] = nameNEWLINE __props__["network_rule_set"] = network_rule_setNEWLINE __props__["resource_group_name"] = resource_group_nameNEWLINE __props__["sku"] = skuNEWLINE __props__["storage_account_id"] = storage_account_idNEWLINE __props__["tags"] = tagsNEWLINE return Registry(resource_name, opts=opts, __props__=__props__)NEWLINE def translate_output_property(self, prop):NEWLINE return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or propNEWLINENEWLINE def translate_input_property(self, prop):NEWLINE return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or propNEWLINENEWLINE # Generated by Django 3.1.4 on 2021-02-06 21:18NEWLINENEWLINEfrom django.db import migrationsNEWLINENEWLINENEWLINEdef register_micropub_scopes(apps, schema):NEWLINENEWLINE MMicropubScope = apps.get_model("indieweb", "MMicropubScope")NEWLINENEWLINE MMicropubScope.objects.get_or_create(key="create", name="Create")NEWLINE MMicropubScope.objects.get_or_create(key="update", name="Update")NEWLINE MMicropubScope.objects.get_or_create(key="delete", name="Delete")NEWLINE MMicropubScope.objects.get_or_create(key="draft", name="Draft")NEWLINE MMicropubScope.objects.get_or_create(key="media", name="Media")NEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ("indieweb", "0003_ttoken"),NEWLINE ]NEWLINENEWLINE operations = [migrations.RunPython(register_micropub_scopes, reverse_code=migrations.RunPython.noop)]NEWLINE """Set up the Python API for dingz devices."""NEWLINEimport osNEWLINENEWLINEimport sysNEWLINENEWLINEfrom setuptools import setup, find_packagesNEWLINENEWLINEhere = os.path.abspath(os.path.dirname(__file__))NEWLINENEWLINEwith open(os.path.join(here, "README.rst"), encoding="utf-8") as readme:NEWLINE long_description = readme.read()NEWLINENEWLINEif sys.argv[-1] == "publish":NEWLINE os.system("python3 setup.py sdist upload")NEWLINE sys.exit()NEWLINENEWLINEsetup(NEWLINE name="python-dingz",NEWLINE version="0.4.0.dev1",NEWLINE description="Python API for interacting with Dingz devices",NEWLINE long_description=long_description,NEWLINE url="https://github.com/home-assistant-ecosystem/python-dingz",NEWLINE author="Fabian Affolter",NEWLINE author_email="fabian@affolter-engineering.ch",NEWLINE license="Apache License 2.0",NEWLINE install_requires=["aiohttp<4", "async_timeout<4", "click"],NEWLINE packages=find_packages(),NEWLINE zip_safe=True,NEWLINE include_package_data=True,NEWLINE entry_points={"console_scripts": ["dingz = dingz.cli:main"]},NEWLINE classifiers=[NEWLINE "Development Status :: 3 - Alpha",NEWLINE "Environment :: Console",NEWLINE "Intended Audience :: Developers",NEWLINE "License :: OSI Approved :: Apache Software License",NEWLINE "Operating System :: MacOS :: MacOS X",NEWLINE "Operating System :: Microsoft :: Windows",NEWLINE "Operating System :: POSIX",NEWLINE "Programming Language :: Python :: 3.7",NEWLINE "Programming Language :: Python :: 3.8",NEWLINE "Topic :: Utilities",NEWLINE ],NEWLINE)NEWLINE # -*- coding: utf-8 -*-NEWLINE"""NEWLINECreated on Thu Jan 14 12:58:41 2015NEWLINE@author: Tony SaadNEWLINE"""NEWLINE# -*- coding: utf-8 -*-NEWLINENEWLINEimport numpy as npNEWLINEimport argparseNEWLINEimport osNEWLINEfrom xml.dom import minidomNEWLINEfrom shutil import copyfileNEWLINEimport matplotlib.pyplot as pltNEWLINENEWLINE#------------------------------------------------------------------------------NEWLINE"""NEWLINEGiven a 3D array A of size (Nx, Ny, Nz) (representative of a CFD mesh), NEWLINEthis function computes a new array B of size (Nx/2, Ny/2, Nz/2)NEWLINEsuch that the entries in B are the averaged values of corresponding cells in A.NEWLINESpecifically, for a cell centered scalar quantity that lives on A, every cellNEWLINEin B corresponds to the average of the 8 cells in A.NEWLINE@author: Tony SaadNEWLINE"""NEWLINEdef average(phi):NEWLINE # get the dimensions of the input arrayNEWLINE shape = phi.shapeNEWLINE nx0 = shape[0]NEWLINE ny0 = shape[1]NEWLINE nz0 = shape[2]NEWLINE # we will average two points in each dimensionNEWLINE nx = nx0/2NEWLINE ny = ny0/2NEWLINE nz = nz0/2NEWLINE phiAv = np.zeros([nx,ny,nz])NEWLINE for iav in range(0,nx):NEWLINE for jav in range(0,ny):NEWLINE for kav in range(0,nz): NEWLINE i = 2*iavNEWLINE j = 2*javNEWLINE k = 2*kavNEWLINE average = (phi[i,j,k] + phi[i+1,j,k] + phi[i,j+1,k] + phi[i,j,k+1] + phi[i+1,j+1,k] + phi[i+1,j,k+1] + phi[i,j+1,k+1] + phi[i+1,j+1,k+1])/8.0NEWLINE# average = (phi[i,j,k] + phi[i,j+1,k] + phi[i,j,k+1] + phi[i,j+1,k+1] )/4.0NEWLINE phiAv[iav,jav,kav] = averageNEWLINE return phiAvNEWLINENEWLINE#------------------------------------------------------------------------------NEWLINEdef main():NEWLINE parser = argparse.ArgumentParser(description=NEWLINE 'Computes spatial order of accuracy without the need of an anlytical solution. The method '+NEWLINE 'is based on computing numerical solutions at refined timesteps and then computing the '+NEWLINE 'order as p = ln[(f3 - f2)/(f2 - f1)]/ln(0.5).' +NEWLINE ' The cleanest way to operate this script is to make a copy of it in a new directory. Then '+NEWLINE 'copy the ups file to that directory and execute the script.' )NEWLINE NEWLINE parser.add_argument('-ups',NEWLINE help='The input file to run.',required=True) NEWLINE NEWLINE parser.add_argument('-levels',NEWLINE help='The number of spatial refinement levels.', type=int) NEWLINE NEWLINE parser.add_argument('-nsteps',NEWLINE help='The number of timesteps. Defaults to 1.', type=int) NEWLINE NEWLINE parser.add_argument('-suspath',NEWLINE help='The path to sus.',required=True)NEWLINE NEWLINE parser.add_argument('-vars', required=True,NEWLINE help='Comma seperated list of variables for which the temporal order is to be computed. example: -vars "var1, my var".')NEWLINE NEWLINE args = parser.parse_args()NEWLINE NEWLINE # if the number of levels is not provided, set it to 3NEWLINE if args.levels is None:NEWLINE args.levels = 3NEWLINE NEWLINE # if the number of levels is <2, then reset it to 3NEWLINE if (args.levels < 2):NEWLINE print 'The number of levels has to be >= 3. Setting levels to 3'NEWLINE args.levels = 3NEWLINE NEWLINE rootups = args.upsNEWLINE nLevels = args.levelsNEWLINE NEWLINE # cleanup the list of variables for which the order is to be computedNEWLINE myvars = [x.strip() for x in args.vars.split(',')]NEWLINE NEWLINE # first makes copies of the ups filesNEWLINE fnames = []NEWLINE basename = os.path.basename(rootups)NEWLINE basename = os.path.splitext(basename)[0]NEWLINE for i in range(0,nLevels):NEWLINE #fname = os.path.splitext(rootups)[0] + '-t' + str(i) + '.ups' NEWLINE fname = basename + '-t' + str(i) + '.ups'NEWLINE fnames.append(fname)NEWLINE copyfile(rootups, fname) NEWLINE NEWLINE # now loop over the copied files and change the dt and the uda nameNEWLINE refinement = 1NEWLINE maxSteps = 1NEWLINE NEWLINE if args.nsteps is not None:NEWLINE maxSteps = args.nstepsNEWLINE NEWLINE args.suspath = os.path.normpath(args.suspath)NEWLINE args.suspath = os.path.abspath(args.suspath)NEWLINE print args.suspathNEWLINE os.system('ln -fs ' + args.suspath + '/sus sus')NEWLINE os.system('ln -fs ' + args.suspath + '/tools/extractors/lineextract lineextract')NEWLINE NEWLINE # find total number of procs and resolutionNEWLINE xmldoc = minidom.parse(rootups)NEWLINE for node in xmldoc.getElementsByTagName('patches'):NEWLINE P = (str(node.firstChild.data).strip()).split(',')NEWLINE P0=int(P[0].split('[')[1])NEWLINE P1=int(P[1])NEWLINE P2=int(P[2].split(']')[0])NEWLINE total_proc = P0*P1*P2NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('resolution'):NEWLINE P = (str(node.firstChild.data).strip()).split(',')NEWLINE Nx=int(P[0].split('[')[1])NEWLINE Ny=int(P[1])NEWLINE Nz=int(P[2].split(']')[0])NEWLINE NEWLINE for fname in fnames:NEWLINE print 'now updating xml for ', fnameNEWLINE basename = os.path.splitext(fname)[0]NEWLINE xmldoc = minidom.parse(fname)NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('filebase'):NEWLINE node.firstChild.replaceWholeText(basename + '.uda')NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('resolution'):NEWLINE node.firstChild.replaceWholeText('[' + str(Nx*refinement) + ',' + str(Ny*refinement) + ',' + str(Nz*refinement) + ']')NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('max_Timesteps'):NEWLINE node.firstChild.replaceWholeText(maxSteps*refinement)NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('delt_min'):NEWLINE dtmin = float(node.firstChild.data)NEWLINE dtmin = dtmin/refinementNEWLINE node.firstChild.replaceWholeText(dtmin)NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('delt_max'):NEWLINE node.firstChild.replaceWholeText(dtmin)NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('outputTimestepInterval'):NEWLINE node.firstChild.replaceWholeText('1')NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('maxTime'):NEWLINE node.firstChild.replaceWholeText('100')NEWLINE NEWLINE refinement *= 2NEWLINE f = open(fname, 'w') NEWLINE xmldoc.writexml(f) NEWLINE f.close()NEWLINE NEWLINE # now run the filesNEWLINE counter = 0NEWLINE refinement = 1NEWLINE for fname in fnames:NEWLINE os.system('mpirun -np '+ str(total_proc) + ' ' + './sus' + ' ' + fname + ' > log.txt')NEWLINE udaName = os.path.splitext(fname)[0] + '.uda'NEWLINE # #EXTRACT THE variablesNEWLINE for var in myvars: NEWLINE outFile = str(var) + '-t' + str(counter) + '.txt'NEWLINE the_command = './lineextract -pr 32 -q -v ' + str(var) + ' -timestep ' + str(maxSteps*refinement) + ' -istart 0 0 0 -iend ' + str(Nx*refinement - 1)+' '+str(Ny*refinement -1)+' '+str(Nz*refinement - 1)+ ' -o ' + outFile +' -uda '+udaNameNEWLINE print 'Executing command: ', the_commandNEWLINE os.system(the_command)NEWLINE NEWLINE os.system('rm ' + fname) NEWLINE refinement *= 2NEWLINE counter += 1NEWLINE NEWLINE #now load the data and compute the errorsNEWLINE print '---------------- SPATIAL ORDER -------------------'NEWLINE for var in myvars: NEWLINE phiAll = []NEWLINE refinement = 1NEWLINE for i in range(0,nLevels):NEWLINE datname = str(var) + '-t' + str(i) + '.txt'NEWLINE phi = np.loadtxt(datname)NEWLINE phi = np.reshape(phi[:,3],(Nx*refinement,Ny*refinement,Nz*refinement),'F') # take the last column of phi and reshapeNEWLINE phiAll.append(phi)NEWLINE # phit = average(phi) # average phiNEWLINE # plt.matshow(phi[:,:,0])NEWLINE # plt.matshow(phit[:,:,0])NEWLINE # plt.show()NEWLINE refinement *= 2NEWLINE os.system('rm ' + datname)NEWLINE NEWLINE # local errorsNEWLINE errAll = []NEWLINE for i in range(0,nLevels-1):NEWLINE #phiav = average(phiAll[i+1]) NEWLINE diff = average(phiAll[i+1]) - phiAll[i]NEWLINE #plt.matshow(diff[:,:,0]) NEWLINE shape = diff.shapeNEWLINE size = shape[0]*shape[1]*shape[2]NEWLINE diff = diff.reshape(size)NEWLINE err = np.linalg.norm(diff,np.inf)NEWLINE errAll.append(err)NEWLINE NEWLINE #plt.show() NEWLINE # now compute orderNEWLINE print '-----------------------------' NEWLINE print ' VARIABLE: ', varNEWLINE print '-----------------------------'NEWLINE for i in range(0,nLevels-2):NEWLINE print np.log( errAll[i+1]/errAll[i] ) / np.log(0.5)NEWLINE NEWLINE os.system('rm -rf *.uda*')NEWLINE os.system('rm -rf *.dot')NEWLINE os.system('rm log.txt') NEWLINENEWLINE#------------------------------------------------------------------------------NEWLINEif __name__ == "__main__":NEWLINE main() import sysNEWLINEimport rdkitNEWLINEfrom argparse import ArgumentParserNEWLINEfrom rdkit import Chem, DataStructsNEWLINEfrom rdkit.Chem import AllChemNEWLINEfrom rdkit.Chem.Scaffolds import MurckoScaffoldNEWLINENEWLINEparser = ArgumentParser()NEWLINEparser.add_argument('--ref_path', required=True)NEWLINEargs = parser.parse_args()NEWLINENEWLINElg = rdkit.RDLogger.logger() NEWLINElg.setLevel(rdkit.RDLogger.CRITICAL)NEWLINENEWLINEpred_data = [line.split()[:3] for line in sys.stdin]NEWLINEpred_mols = [mol for mol,x,y in pred_data if float(x) >= 0.5 and float(y) >= 0.5]NEWLINENEWLINEfraction_actives = len(pred_mols) / len(pred_data)NEWLINEprint('fraction actives:', fraction_actives)NEWLINENEWLINEwith open(args.ref_path) as f:NEWLINE next(f)NEWLINE true_mols = [line.split(',')[0] for line in f]NEWLINEprint('number of active reference', len(true_mols))NEWLINENEWLINEtrue_mols = [Chem.MolFromSmiles(s) for s in true_mols]NEWLINEtrue_mols = [x for x in true_mols if x is not None]NEWLINEtrue_fps = [AllChem.GetMorganFingerprintAsBitVect(x, 3, 2048) for x in true_mols]NEWLINENEWLINEpred_mols = [Chem.MolFromSmiles(s) for s in pred_mols]NEWLINEpred_mols = [x for x in pred_mols if x is not None]NEWLINEpred_fps = [AllChem.GetMorganFingerprintAsBitVect(x, 3, 2048) for x in pred_mols]NEWLINENEWLINEfraction_similar = 0NEWLINEfor i in range(len(pred_fps)):NEWLINE sims = DataStructs.BulkTanimotoSimilarity(pred_fps[i], true_fps)NEWLINE if max(sims) >= 0.4:NEWLINE fraction_similar += 1NEWLINENEWLINEprint('novelty:', 1 - fraction_similar / len(pred_mols))NEWLINENEWLINEsimilarity = 0NEWLINEfor i in range(len(pred_fps)):NEWLINE sims = DataStructs.BulkTanimotoSimilarity(pred_fps[i], pred_fps[:i])NEWLINE similarity += sum(sims)NEWLINENEWLINEn = len(pred_fps) NEWLINEn_pairs = n * (n - 1) / 2NEWLINEdiversity = 1 - similarity / n_pairsNEWLINEprint('diversity:', diversity)NEWLINENEWLINE import unittestNEWLINENEWLINEfrom py_asciimath.utils.utils import UtilsMatNEWLINENEWLINENEWLINEclass TestUtilsMat(unittest.TestCase):NEWLINE def setUp(self):NEWLINE passNEWLINENEWLINE # Returns True if the string contains 4 a.NEWLINE def test_check_mat_ok_1(self):NEWLINE b, _ = UtilsMat.check_mat("[1,2], [1,2]")NEWLINE self.assertTrue(b)NEWLINENEWLINE def test_check_mat_ok_2(self):NEWLINE b, _ = UtilsMat.check_mat("[], []")NEWLINE self.assertTrue(b)NEWLINENEWLINE def test_check_mat_ok_3(self):NEWLINE b, _ = UtilsMat.check_mat("[[,[,]],[[,],]], [[[[,],],],[,[,[,]]]]")NEWLINE self.assertTrue(b)NEWLINENEWLINE def test_check_mat_ok_4(self):NEWLINE b, _ = UtilsMat.check_mat("[,], [,]")NEWLINE self.assertTrue(b)NEWLINENEWLINE def test_check_mat_fail_1(self):NEWLINE b, _ = UtilsMat.check_mat("[], [,]")NEWLINE self.assertFalse(b)NEWLINENEWLINE def test_check_mat_fail_2(self):NEWLINE b, _ = UtilsMat.check_mat("[,], []")NEWLINE self.assertFalse(b)NEWLINENEWLINE def test_check_mat_fail_3(self):NEWLINE b, _ = UtilsMat.check_mat("[,][,]")NEWLINE self.assertFalse(b)NEWLINENEWLINE def test_check_mat_fail_4(self):NEWLINE b, _ = UtilsMat.check_mat("[,],[")NEWLINE self.assertFalse(b)NEWLINENEWLINE def test_check_mat_fail_5(self):NEWLINE b, _ = UtilsMat.check_mat("[1,2],[1,2,[1,2],[3,4]")NEWLINE self.assertFalse(b)NEWLINENEWLINE def test_check_mat_fail_6(self):NEWLINE b, _ = UtilsMat.check_mat("[,],")NEWLINE self.assertFalse(b)NEWLINENEWLINE def test_check_mat_fail_7(self):NEWLINE b, _ = UtilsMat.check_mat("[,]],")NEWLINE self.assertFalse(b)NEWLINENEWLINE def test_check_mat_fail_8(self):NEWLINE b, _ = UtilsMat.check_mat("[,],,")NEWLINE self.assertFalse(b)NEWLINENEWLINE def test_check_mat_fail_9(self):NEWLINE b, _ = UtilsMat.check_mat("[][]")NEWLINE self.assertFalse(b)NEWLINENEWLINE def test_check_mat_fail_10(self):NEWLINE b, _ = UtilsMat.check_mat("[]")NEWLINE self.assertFalse(b)NEWLINENEWLINE def test_get_mat_ok_1(self):NEWLINE s = UtilsMat.get_latex_mat(NEWLINE "\\left[1 , 2\\right] , \\left[1 , 2\\right]"NEWLINE )NEWLINE self.assertEqual(s, "1 & 2 \\\\ 1 & 2")NEWLINENEWLINE def test_get_mat_ok_2(self):NEWLINE s = UtilsMat.get_latex_mat(NEWLINE "\\left[1 , 2\\right] , \\left[1 , \\right]"NEWLINE )NEWLINE self.assertEqual(s, "1 & 2 \\\\ 1 & \\null")NEWLINENEWLINE def test_get_mat_ok_3(self):NEWLINE s = UtilsMat.get_latex_mat("\\left[\\right] , \\left[\\right]")NEWLINE self.assertEqual(s, "\\null \\\\ \\null")NEWLINENEWLINE def test_get_mat_ok_4(self):NEWLINE s = UtilsMat.get_latex_mat("\\left[,\\right] , \\left[,\\right]")NEWLINE self.assertEqual(s, "\\null & \\null \\\\ \\null & \\null")NEWLINENEWLINE def test_check_get_mat_ok_4(self):NEWLINE s = "\\left[2*[x+n], 3(int x dx)\\right], \\left[sqrt(x), a\\right]"NEWLINE b, row_par = UtilsMat.check_mat(s)NEWLINE self.assertTrue(b)NEWLINE self.assertEqual(row_par, ["[", "]"])NEWLINE m = UtilsMat.get_latex_mat(s, row_par)NEWLINE self.assertEqual(m, "2*[x+n] & 3(int x dx) \\\\ sqrt(x) & a")NEWLINENEWLINE def test_check_get_mat_fail_1(self):NEWLINE s = "\\left[2*[x+n], 3(int x dx)\\right, \\left[sqrt(x), a\\right]"NEWLINE b, row_par = UtilsMat.check_mat(s)NEWLINE self.assertFalse(b)NEWLINE self.assertEqual(row_par, [])NEWLINE m = UtilsMat.get_latex_mat(s, row_par)NEWLINE self.assertNotEqual(m, "2*[x+n] & 3(int x dx) \\\\ sqrt(x) & a")NEWLINENEWLINE def test_get_row_par_1(self):NEWLINE s = "{1+2]"NEWLINE i, row_par = UtilsMat.get_row_par(s)NEWLINE self.assertEqual(i, -1)NEWLINE self.assertEqual(row_par, [])NEWLINENEWLINE def test_get_row_par_2(self):NEWLINE s = "{1+2]"NEWLINE ok, row_par = UtilsMat.check_mat(s)NEWLINE self.assertFalse(ok)NEWLINE self.assertEqual(row_par, [])NEWLINENEWLINE def test_get_mathml_mat_1(self):NEWLINE s = "[1,2"NEWLINE ok, row_par = UtilsMat.check_mat(s)NEWLINE self.assertFalse(ok)NEWLINE self.assertEqual(row_par, [])NEWLINE mat = UtilsMat.get_mathml_mat(s, row_par)NEWLINE self.assertEqual(s, mat)NEWLINENEWLINE def test_get_mathml_mat_2(self):NEWLINE s = "[1,[2]]"NEWLINE ok, row_par = UtilsMat.check_mat(s)NEWLINE self.assertFalse(ok)NEWLINE self.assertEqual(row_par, [])NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE unittest.main()NEWLINE from struct import unpackNEWLINENEWLINENEWLINEclass FloatLookup:NEWLINE def __init__(self, data): # data: Tuple[float]NEWLINE self.data = dataNEWLINE self.range_ = len(data)NEWLINENEWLINE @staticmethodNEWLINE def get_lookup_from_double(file) -> 'FloatLookup':NEWLINE range_, = unpack('>i', file.read(4))NEWLINE values = tuple(unpack('>{}d'.format(range_), file.read(range_ * 8)))NEWLINE return FloatLookup(values)NEWLINENEWLINE def get(self, n: int) -> float:NEWLINE if 0 <= n < self.range_:NEWLINE return self.data[n]NEWLINE else:NEWLINE raise ValueError("Value is out of range") import unittestNEWLINEimport osNEWLINEfrom ...BaseTestCase import BaseTestCaseNEWLINEfrom kombi.Task import TaskNEWLINEfrom kombi.Crawler.Fs import FsCrawlerNEWLINENEWLINEclass ResizeImageTaskTest(BaseTestCase):NEWLINE """Test ResizeImage task."""NEWLINENEWLINE __sourcePath = os.path.join(BaseTestCase.dataTestsDirectory(), "testSeq.0001.exr")NEWLINE __targetPath = os.path.join(BaseTestCase.tempDirectory(), "testToDelete.jpg")NEWLINENEWLINE def testResizeImage(self):NEWLINE """NEWLINE Test that the ResizeImage task works properly.NEWLINE """NEWLINE crawler = FsCrawler.createFromPath(self.__sourcePath)NEWLINE resizeTask = Task.create('resizeImage')NEWLINE resizeTask.add(crawler, self.__targetPath)NEWLINE resizeTask.setOption("width", "480")NEWLINE resizeTask.setOption("height", "270")NEWLINE for convertToRGBA in [False, True]:NEWLINE resizeTask.setOption("convertToRGBA", convertToRGBA)NEWLINE result = resizeTask.output()NEWLINE self.assertEqual(len(result), 1)NEWLINE crawler = result[0]NEWLINE self.assertEqual(crawler.var("width"), 480)NEWLINE self.assertEqual(crawler.var("height"), 270)NEWLINENEWLINE @classmethodNEWLINE def tearDownClass(cls):NEWLINE """NEWLINE Remove the file that was copied.NEWLINE """NEWLINE os.remove(cls.__targetPath)NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE unittest.main()NEWLINE """NEWLINE :codeauthor: Megan WilhiteNEWLINE"""NEWLINENEWLINENEWLINEimport pytestNEWLINEimport salt.modules.mac_service as mac_serviceNEWLINEfrom salt.exceptions import CommandExecutionErrorNEWLINEfrom tests.support.mixins import LoaderModuleMockMixinNEWLINEfrom tests.support.mock import MagicMock, patchNEWLINEfrom tests.support.unit import TestCaseNEWLINENEWLINENEWLINEclass MacServiceTestCase(TestCase, LoaderModuleMockMixin):NEWLINE """NEWLINE TestCase for salt.modules.mac_service moduleNEWLINE """NEWLINENEWLINE def setup_loader_modules(self):NEWLINE return {mac_service: {"__context__": {}}}NEWLINENEWLINE def test_service_disabled_when_enabled(self):NEWLINE """NEWLINE test service.disabled when service is enabledNEWLINE """NEWLINE srv_name = "com.apple.atrun"NEWLINE cmd = 'disabled services = {\n\t"com.saltstack.salt.minion" => false\n\t"com.apple.atrun" => false\n{'NEWLINE domain_ret = MagicMock(return_value=("", ""))NEWLINE with patch.object(mac_service, "_get_domain_target", domain_ret):NEWLINE with patch.object(mac_service, "launchctl", MagicMock(return_value=cmd)):NEWLINE assert mac_service.disabled(srv_name) is FalseNEWLINENEWLINE def test_service_disabled_when_disabled(self):NEWLINE """NEWLINE test service.disabled when service is disabledNEWLINE """NEWLINE srv_name = "com.apple.atrun"NEWLINE cmd = 'disabled services = {\n\t"com.saltstack.salt.minion" => false\n\t"com.apple.atrun" => true\n{'NEWLINE domain_ret = MagicMock(return_value=("", ""))NEWLINE with patch.object(mac_service, "_get_domain_target", domain_ret):NEWLINE with patch.object(mac_service, "launchctl", MagicMock(return_value=cmd)):NEWLINE assert mac_service.disabled(srv_name) is TrueNEWLINENEWLINE def test_service_disabled_srvname_wrong(self):NEWLINE """NEWLINE test service.disabled when service is just slightly wrongNEWLINE """NEWLINE srv_names = ["com.apple.atru", "com", "apple"]NEWLINE cmd = 'disabled services = {\n\t"com.saltstack.salt.minion" => false\n\t"com.apple.atrun" => true\n}'NEWLINE domain_ret = MagicMock(return_value=("", ""))NEWLINE with patch.object(mac_service, "_get_domain_target", domain_ret):NEWLINE for name in srv_names:NEWLINE with patch.object(NEWLINE mac_service, "launchctl", MagicMock(return_value=cmd)NEWLINE ):NEWLINE assert mac_service.disabled(name) is FalseNEWLINENEWLINE def test_service_disabled_status_upper_case(self):NEWLINE """NEWLINE test service.disabled when disabled status is uppercaseNEWLINE """NEWLINE srv_name = "com.apple.atrun"NEWLINE cmd = 'disabled services = {\n\t"com.saltstack.salt.minion" => false\n\t"com.apple.atrun" => True\n{'NEWLINE domain_ret = MagicMock(return_value=("", ""))NEWLINE with patch.object(mac_service, "_get_domain_target", domain_ret):NEWLINE with patch.object(mac_service, "launchctl", MagicMock(return_value=cmd)):NEWLINE assert mac_service.disabled(srv_name) is TrueNEWLINENEWLINE def test_service_enabled_when_enabled(self):NEWLINE """NEWLINE test service.enabled when not disabledNEWLINE """NEWLINE mock_cmd = MagicMock(return_value=False)NEWLINE with patch.dict(mac_service.__salt__, {"service.disabled": mock_cmd}):NEWLINE assert mac_service.enabled("com.apple.atrun") is TrueNEWLINENEWLINE def test_service_enabled_when_disabled(self):NEWLINE """NEWLINE test service.enabled if service is disabledNEWLINE """NEWLINE mock_cmd = MagicMock(return_value=True)NEWLINE with patch.dict(mac_service.__salt__, {"service.disabled": mock_cmd}):NEWLINE assert mac_service.enabled("com.apple.atrun") is FalseNEWLINENEWLINE def test_service_loaded_when_true(self):NEWLINE """NEWLINE test service.loaded with a loaded service.NEWLINE """NEWLINE mock_cmd = MagicMock(return_value="some_service_string")NEWLINE with patch.dict(mac_service.__salt__, {"service.list": mock_cmd}):NEWLINE assert mac_service.loaded("com.apple.atrun") is TrueNEWLINENEWLINE def test_service_loaded_when_false(self):NEWLINE """NEWLINE test service.loaded with an unloaded service.NEWLINE """NEWLINE mock_cmd = MagicMock(side_effect=CommandExecutionError)NEWLINE with patch.dict(mac_service.__salt__, {"service.list": mock_cmd}):NEWLINE assert mac_service.loaded("com.apple.atrun") is FalseNEWLINENEWLINE def test_service_keep_alive_pathstate_file_rm(self):NEWLINE """NEWLINE test _always_running_service when keep_aliveNEWLINE has pathstate set in plist file and file doesn't existNEWLINE """NEWLINE srv_name = "com.apple.atrun"NEWLINE info = {NEWLINE "plist": {NEWLINE "EnableTransactions": True,NEWLINE "ProgramArguments": ["/usr/libexec/ntpd-wrapper"],NEWLINE "Label": "org.ntp.ntpd",NEWLINE "KeepAlive": {"PathState": {"/private/etc/ntp.conf": True}},NEWLINE }NEWLINE }NEWLINENEWLINE with patch.object(mac_service, "show", MagicMock(return_value=info)):NEWLINE with patch("os.path.exists", MagicMock(return_value=False)):NEWLINE assert mac_service._always_running_service(srv_name) is FalseNEWLINENEWLINE def test_service_keep_alive_empty(self):NEWLINE """NEWLINE test _always_running_service when keep_aliveNEWLINE is emptyNEWLINE """NEWLINE srv_name = "com.apple.atrun"NEWLINE info = {NEWLINE "plist": {NEWLINE "EnableTransactions": True,NEWLINE "ProgramArguments": ["/usr/libexec/ntpd-wrapper"],NEWLINE "Label": "org.ntp.ntpd",NEWLINE "KeepAlive": {},NEWLINE }NEWLINE }NEWLINENEWLINE with patch.object(mac_service, "show", MagicMock(return_value=info)):NEWLINE with patch("os.path.exists", MagicMock(return_value=False)):NEWLINE assert mac_service._always_running_service(srv_name) is FalseNEWLINENEWLINE def test_service_keep_alive_pathstate_false(self):NEWLINE """NEWLINE test _always_running_service when keep_aliveNEWLINE has pathstate set in plist file and file is falseNEWLINE """NEWLINE srv_name = "com.apple.atrun"NEWLINE info = {NEWLINE "plist": {NEWLINE "EnableTransactions": True,NEWLINE "ProgramArguments": ["/usr/libexec/ntpd-wrapper"],NEWLINE "Label": "org.ntp.ntpd",NEWLINE "KeepAlive": {"PathState": {"/private/etc/ntp.conf": False}},NEWLINE }NEWLINE }NEWLINENEWLINE with patch.object(mac_service, "show", MagicMock(return_value=info)):NEWLINE with patch("os.path.exists", MagicMock(return_value=False)):NEWLINE assert mac_service._always_running_service(srv_name) is TrueNEWLINENEWLINE def test_service_keep_alive_pathstate(self):NEWLINE """NEWLINE test _always_running_service when keep_aliveNEWLINE has pathstate set in plist fileNEWLINE """NEWLINE srv_name = "com.apple.atrun"NEWLINE info = {NEWLINE "plist": {NEWLINE "EnableTransactions": True,NEWLINE "ProgramArguments": ["/usr/libexec/ntpd-wrapper"],NEWLINE "Label": "org.ntp.ntpd",NEWLINE "KeepAlive": {"PathState": {"/private/etc/ntp.conf": True}},NEWLINE }NEWLINE }NEWLINENEWLINE with patch.object(mac_service, "show", MagicMock(return_value=info)):NEWLINE with patch("os.path.exists", MagicMock(return_value=True)):NEWLINE assert mac_service._always_running_service(srv_name) is TrueNEWLINENEWLINE def test_service_keep_alive(self):NEWLINE """NEWLINE test _always_running_service when keep_alive setNEWLINE """NEWLINE srv_name = "com.apple.atrun"NEWLINE info = {NEWLINE "plist": {NEWLINE "EnableTransactions": True,NEWLINE "ProgramArguments": ["/usr/libexec/ntpd-wrapper"],NEWLINE "Label": "org.ntp.ntpd",NEWLINE "KeepAlive": True,NEWLINE }NEWLINE }NEWLINENEWLINE with patch.object(mac_service, "show", MagicMock(return_value=info)):NEWLINE assert mac_service._always_running_service(srv_name) is TrueNEWLINENEWLINE def test_service_keep_alive_false(self):NEWLINE """NEWLINE test _always_running_service when keep_alive FalseNEWLINE """NEWLINE srv_name = "com.apple.atrun"NEWLINE info = {NEWLINE "plist": {NEWLINE "EnableTransactions": True,NEWLINE "ProgramArguments": ["/usr/libexec/ntpd-wrapper"],NEWLINE "Label": "org.ntp.ntpd",NEWLINE "KeepAlive": False,NEWLINE }NEWLINE }NEWLINENEWLINE with patch.object(mac_service, "show", MagicMock(return_value=info)):NEWLINE assert mac_service._always_running_service(srv_name) is FalseNEWLINENEWLINE def test_service_keep_alive_missing(self):NEWLINE """NEWLINE test _always_running_service when keep_alive not in dictNEWLINE """NEWLINE srv_name = "com.apple.atrun"NEWLINE info = {NEWLINE "plist": {NEWLINE "EnableTransactions": True,NEWLINE "ProgramArguments": ["/usr/libexec/ntpd-wrapper"],NEWLINE "Label": "org.ntp.ntpd",NEWLINE }NEWLINE }NEWLINENEWLINE with patch.object(mac_service, "show", MagicMock(return_value=info)):NEWLINE assert mac_service._always_running_service(srv_name) is FalseNEWLINENEWLINE def test_service_keep_alive_wrong_setting(self):NEWLINE """NEWLINE test _always_running_service when keep_aliveNEWLINE has pathstate set in plist fileNEWLINE """NEWLINE srv_name = "com.apple.atrun"NEWLINE info = {NEWLINE "plist": {NEWLINE "EnableTransactions": True,NEWLINE "ProgramArguments": ["/usr/libexec/ntpd-wrapper"],NEWLINE "Label": "org.ntp.ntpd",NEWLINE "KeepAlive": {"Doesnotexist": {"doesnt_exist": True}},NEWLINE }NEWLINE }NEWLINENEWLINE with patch.object(mac_service, "show", MagicMock(return_value=info)):NEWLINE assert mac_service._always_running_service(srv_name) is FalseNEWLINENEWLINE def test_service_name_change_salt_minion(self):NEWLINE srv_name = "salt-minion"NEWLINE info = {NEWLINE "com.saltstack.salt.minion": {NEWLINE "file_name": "com.saltstack.salt.minion.plist",NEWLINE "file_path": "/Library/LaunchDaemons/com.saltstack.salt.minion.plist",NEWLINE "plist": {NEWLINE "HardResourceLimits": {"NumberOfFiles": 100000},NEWLINE "KeepAlive": True,NEWLINE "Label": "com.saltstack.salt.minion",NEWLINE "ProgramArguments": ["/opt/salt/bin/start-salt-minion.sh"],NEWLINE "RunAtLoad": True,NEWLINE "SoftResourceLimits": {"NumberOfFiles": 100000},NEWLINE },NEWLINE }NEWLINE }NEWLINE with patch.dict(NEWLINE mac_service.__utils__,NEWLINE {"mac_utils.available_services": MagicMock(return_value=info)},NEWLINE ):NEWLINE assert (NEWLINE mac_service._get_service(srv_name) == info["com.saltstack.salt.minion"]NEWLINE )NEWLINENEWLINE def test_service_name_change_salt_master(self):NEWLINE srv_name = "salt-master"NEWLINE info = {NEWLINE "com.saltstack.salt.master": {NEWLINE "file_name": "com.saltstack.salt.master.plist",NEWLINE "file_path": "/Library/LaunchDaemons/com.saltstack.salt.master.plist",NEWLINE "plist": {NEWLINE "HardResourceLimits": {"NumberOfFiles": 100000},NEWLINE "KeepAlive": True,NEWLINE "Label": "com.saltstack.salt.master",NEWLINE "ProgramArguments": ["/opt/salt/bin/start-salt-master.sh"],NEWLINE "RunAtLoad": True,NEWLINE "SoftResourceLimits": {"NumberOfFiles": 100000},NEWLINE },NEWLINE }NEWLINE }NEWLINE with patch.dict(NEWLINE mac_service.__utils__,NEWLINE {"mac_utils.available_services": MagicMock(return_value=info)},NEWLINE ):NEWLINE assert (NEWLINE mac_service._get_service(srv_name) == info["com.saltstack.salt.master"]NEWLINE )NEWLINENEWLINE def test_service_name_change_salt_api(self):NEWLINE srv_name = "salt-api"NEWLINE info = {NEWLINE "com.saltstack.salt.api": {NEWLINE "file_name": "com.saltstack.salt.api.plist",NEWLINE "file_path": "/Library/LaunchDaemons/com.saltstack.salt.api.plist",NEWLINE "plist": {NEWLINE "HardResourceLimits": {"NumberOfFiles": 100000},NEWLINE "KeepAlive": True,NEWLINE "Label": "com.saltstack.salt.api",NEWLINE "ProgramArguments": ["/opt/salt/bin/start-salt-api.sh"],NEWLINE "RunAtLoad": True,NEWLINE "SoftResourceLimits": {"NumberOfFiles": 100000},NEWLINE },NEWLINE }NEWLINE }NEWLINE with patch.dict(NEWLINE mac_service.__utils__,NEWLINE {"mac_utils.available_services": MagicMock(return_value=info)},NEWLINE ):NEWLINE assert mac_service._get_service(srv_name) == info["com.saltstack.salt.api"]NEWLINENEWLINE def test_service_name_change_salt_syndic(self):NEWLINE srv_name = "salt-syndic"NEWLINE info = {NEWLINE "com.saltstack.salt.syndic": {NEWLINE "file_name": "com.saltstack.salt.syndic.plist",NEWLINE "file_path": "/Library/LaunchDaemons/com.saltstack.salt.syndic.plist",NEWLINE "plist": {NEWLINE "HardResourceLimits": {"NumberOfFiles": 100000},NEWLINE "KeepAlive": True,NEWLINE "Label": "com.saltstack.salt.syndic",NEWLINE "ProgramArguments": ["/opt/salt/bin/start-salt-syndic.sh"],NEWLINE "RunAtLoad": True,NEWLINE "SoftResourceLimits": {"NumberOfFiles": 100000},NEWLINE },NEWLINE }NEWLINE }NEWLINE with patch.dict(NEWLINE mac_service.__utils__,NEWLINE {"mac_utils.available_services": MagicMock(return_value=info)},NEWLINE ):NEWLINE assert (NEWLINE mac_service._get_service(srv_name) == info["com.saltstack.salt.syndic"]NEWLINE )NEWLINENEWLINE def test_service_restart_already_loaded(self):NEWLINE mock_cmd = MagicMock(return_value=True)NEWLINE salt_dict = {NEWLINE "service.loaded": mock_cmd,NEWLINE "service.stop": mock_cmd,NEWLINE "service.start": mock_cmd,NEWLINE }NEWLINE with patch.dict(mac_service.__salt__, salt_dict):NEWLINE assert mac_service.restart("com.salt") is TrueNEWLINENEWLINE def test_service_restart_not_loaded(self):NEWLINE salt_dict = {NEWLINE "service.loaded": MagicMock(return_value=False),NEWLINE "service.start": MagicMock(return_value=True),NEWLINE }NEWLINE with patch.dict(mac_service.__salt__, salt_dict):NEWLINE assert mac_service.restart("com.salt") is TrueNEWLINENEWLINE def test_service_restart_failed_stop(self):NEWLINE salt_dict = {NEWLINE "service.loaded": MagicMock(return_value=True),NEWLINE "service.stop": MagicMock(side_effect=CommandExecutionError),NEWLINE }NEWLINE with patch.dict(mac_service.__salt__, salt_dict):NEWLINE with pytest.raises(CommandExecutionError):NEWLINE assert mac_service.restart("com.salt")NEWLINENEWLINE def test_service_restart_failed_start(self):NEWLINE salt_dict = {NEWLINE "service.loaded": MagicMock(return_value=False),NEWLINE "service.start": MagicMock(side_effect=CommandExecutionError),NEWLINE }NEWLINE with patch.dict(mac_service.__salt__, salt_dict):NEWLINE with pytest.raises(CommandExecutionError):NEWLINE assert mac_service.restart("com.salt")NEWLINENEWLINE def test_service_status_no_service(self):NEWLINE """NEWLINE Test service status with no service foundNEWLINE """NEWLINE with patch.object(NEWLINE mac_service, "_get_service", MagicMock(side_effect=CommandExecutionError)NEWLINE ):NEWLINE assert mac_service.status("com.salt") is FalseNEWLINENEWLINE @patch.object(mac_service, "_launch_agent", lambda _: False)NEWLINE @patch.object(mac_service, "_get_service", lambda _: {"": ""})NEWLINE @patch.object(mac_service, "_always_running_service", lambda _: True)NEWLINE def test_service_status_on_daemon_with_pid(self):NEWLINE """NEWLINE Test service status on dameon with PID.NEWLINE """NEWLINE mock_service_list = '{\n\t"LimitLoadToSessionType" = "System";\n\t"Label" = "com.salt";\n\t"OnDemand" = false;\n\t"LastExitStatus" = 0;\n\t"PID" = 218;\n\t"Program" = "/opt/salt";\n\t\t"--disable-keepalive";\n\t);\n};'NEWLINE salt_dict = {NEWLINE "service.list": MagicMock(return_value=mock_service_list),NEWLINE }NEWLINE with patch.dict(mac_service.__salt__, salt_dict):NEWLINE assert mac_service.status("com.salt") is TrueNEWLINENEWLINE @patch.object(mac_service, "_launch_agent", lambda _: True)NEWLINE @patch.object(mac_service, "_get_service", lambda _: {"": ""})NEWLINE @patch.object(mac_service, "_always_running_service", lambda _: True)NEWLINE def test_service_status_on_agent_with_pid(self):NEWLINE """NEWLINE Test service status on LaunchAgent with PID.NEWLINE """NEWLINE mock_service_list = '{\n\t"LimitLoadToSessionType" = "Aqua";\n\t"Label" = "com.salt";\n\t"OnDemand" = false;\n\t"LastExitStatus" = 19968;\n\t"PID" = 218;\n\t"Program" = "/opt/salt";\n\t"ProgramArguments" = (\n\t\t"/opt/salt";\n\t\t"--syslog";\n\t);\n};'NEWLINE salt_dict = {NEWLINE "service.list": MagicMock(return_value=mock_service_list),NEWLINE }NEWLINE utils_dict = {NEWLINE "mac_utils.console_user": MagicMock(return_value="spongebob"),NEWLINE }NEWLINE with patch.dict(mac_service.__salt__, salt_dict):NEWLINE with patch.dict(mac_service.__utils__, utils_dict):NEWLINE assert mac_service.status("com.salt") is TrueNEWLINENEWLINE @patch.object(mac_service, "_launch_agent", lambda _: True)NEWLINE @patch.object(mac_service, "_get_service", lambda _: {"": ""})NEWLINE @patch.object(mac_service, "_always_running_service", lambda _: True)NEWLINE def test_service_status_on_agent_with_no_pid_and_should_be_running(self):NEWLINE """NEWLINE Test service status on LaunchAgent with No PID and should be running.NEWLINE """NEWLINE mock_service_list = '{\n\t"LimitLoadToSessionType" = "Aqua";\n\t"Label" = "com.salt";\n\t"OnDemand" = false;\n\t"LastExitStatus" = 19968;\n\t"Program" = "/opt/salt";\n\t"ProgramArguments" = (\n\t\t"/opt/salt";\n\t\t"--syslog";\n\t);\n};'NEWLINE salt_dict = {NEWLINE "service.list": MagicMock(return_value=mock_service_list),NEWLINE }NEWLINE utils_dict = {NEWLINE "mac_utils.console_user": MagicMock(return_value="spongebob"),NEWLINE }NEWLINE with patch.dict(mac_service.__salt__, salt_dict):NEWLINE with patch.dict(mac_service.__utils__, utils_dict):NEWLINE assert mac_service.status("com.salt") is FalseNEWLINENEWLINE @patch.object(mac_service, "_launch_agent", lambda _: False)NEWLINE @patch.object(mac_service, "_get_service", lambda _: {"": ""})NEWLINE @patch.object(mac_service, "_always_running_service", lambda _: True)NEWLINE def test_service_status_on_daemon_with_no_pid_and_should_be_running(self):NEWLINE """NEWLINE Test service status on LaunchDaemon with no PID and anNEWLINE always running service that is loaded.NEWLINE """NEWLINE mock_service_list = '{\n\t"LimitLoadToSessionType" = "System";\n\t"Label" = "com.salt";\n\t"OnDemand" = false;\n\t"LastExitStatus" = 19968;\n\t"Program" = "/opt/salt.sh";\n\t"ProgramArguments" = (\n\t\t"/opt/salt.sh";\n\t\t"--disable-keepalive";\n\t);\n};'NEWLINE salt_dict = {NEWLINE "service.list": MagicMock(return_value=mock_service_list),NEWLINE }NEWLINE with patch.dict(mac_service.__salt__, salt_dict):NEWLINE assert mac_service.status("com.salt") is FalseNEWLINENEWLINE @patch.object(mac_service, "_launch_agent", lambda _: False)NEWLINE @patch.object(mac_service, "_get_service", lambda _: {"": ""})NEWLINE @patch.object(mac_service, "_always_running_service", lambda _: False)NEWLINE def test_service_status_on_daemon_with_no_pid_and_not_always_running(self):NEWLINE """NEWLINE Test service status on LaunchDaemon with no PID and not an alwaysNEWLINE running service.NEWLINE """NEWLINE mock_service_list = '{\n\t"LimitLoadToSessionType" = "System";\n\t"Label" = "com.salt";\n\t"OnDemand" = false;\n\t"LastExitStatus" = 19968;\n\t"Program" = "/opt/salt.sh";\n\t"ProgramArguments" = (\n\t\t"/opt/salt.sh";\n\t\t"--disable-keepalive";\n\t);\n};'NEWLINE salt_dict = {NEWLINE "service.list": MagicMock(return_value=mock_service_list),NEWLINE }NEWLINE with patch.dict(mac_service.__salt__, salt_dict):NEWLINE assert mac_service.status("com.salt") is TrueNEWLINENEWLINE @patch.object(mac_service, "_launch_agent", lambda _: False)NEWLINE @patch.object(mac_service, "_get_service", lambda _: {"": ""})NEWLINE @patch.object(mac_service, "_always_running_service", lambda _: False)NEWLINE def test_service_status_on_daemon_with_failing_list_check(self):NEWLINE """NEWLINE Test service status on LaunchDaemon with no PID on anNEWLINE always running service that is loaded.NEWLINE """NEWLINE mock_service_list = '{\n\t"LimitLoadToSessionType" = "System";\n\t"Label" = "com.salt";\n\t"OnDemand" = false;\n\t"LastExitStatus" = 19968;\n\t"Program" = "/opt/salt.sh";\n\t"ProgramArguments" = (\n\t\t"/opt/salt.sh";\n\t\t"--disable-keepalive";\n\t);\n};'NEWLINE salt_dict = {NEWLINE "service.list": MagicMock(side_effect=CommandExecutionError),NEWLINE }NEWLINE with patch.dict(mac_service.__salt__, salt_dict):NEWLINE assert mac_service.status("com.salt") is FalseNEWLINENEWLINE def test_get_service_on_service_dead(self):NEWLINE """NEWLINE Test service.dead changes.NEWLINE https://github.com/saltstack/salt/issues/57907NEWLINE """NEWLINE utils_dict = {NEWLINE "mac_utils.available_services": MagicMock(return_value={}),NEWLINE }NEWLINE context_dict = {NEWLINE "using_cached_services": True,NEWLINE "service.state": "dead",NEWLINE }NEWLINE name_in_service = MagicMock(side_effect=[{}, {"com.salt": True}])NEWLINE with patch.dict(mac_service.__utils__, utils_dict):NEWLINE with patch.object(mac_service, "_name_in_services", name_in_service):NEWLINE with patch.dict(mac_service.__context__, context_dict):NEWLINE with pytest.raises(CommandExecutionError):NEWLINE assert mac_service._get_service("com.salt")NEWLINE # find the service on a second go with no service.deadNEWLINE with patch.dict(mac_service.__context__, {}):NEWLINE assert mac_service._get_service("com.salt") == {"com.salt": True}NEWLINE # coding=utf-8NEWLINE# --------------------------------------------------------------------------NEWLINE# Copyright (c) Microsoft Corporation. All rights reserved.NEWLINE# Licensed under the MIT License. See License.txt in the project root forNEWLINE# license information.NEWLINE#NEWLINE# Code generated by Microsoft (R) AutoRest Code Generator.NEWLINE# Changes may cause incorrect behavior and will be lost if the code isNEWLINE# regenerated.NEWLINE# --------------------------------------------------------------------------NEWLINENEWLINEfrom msrest.service_client import SDKClientNEWLINEfrom msrest import Serializer, DeserializerNEWLINENEWLINEfrom ._configuration import ContainerRegistryManagementClientConfigurationNEWLINEfrom .operations import RegistriesOperationsNEWLINEfrom .operations import OperationsNEWLINEfrom .operations import ReplicationsOperationsNEWLINEfrom .operations import WebhooksOperationsNEWLINEfrom .operations import RunsOperationsNEWLINEfrom .operations import TasksOperationsNEWLINEfrom . import modelsNEWLINENEWLINENEWLINEclass ContainerRegistryManagementClient(SDKClient):NEWLINE """ContainerRegistryManagementClientNEWLINENEWLINE :ivar config: Configuration for client.NEWLINE :vartype config: ContainerRegistryManagementClientConfigurationNEWLINENEWLINE :ivar registries: Registries operationsNEWLINE :vartype registries: azure.mgmt.containerregistry.v2019_05_01.operations.RegistriesOperationsNEWLINE :ivar operations: Operations operationsNEWLINE :vartype operations: azure.mgmt.containerregistry.v2019_05_01.operations.OperationsNEWLINE :ivar replications: Replications operationsNEWLINE :vartype replications: azure.mgmt.containerregistry.v2019_05_01.operations.ReplicationsOperationsNEWLINE :ivar webhooks: Webhooks operationsNEWLINE :vartype webhooks: azure.mgmt.containerregistry.v2019_05_01.operations.WebhooksOperationsNEWLINE :ivar runs: Runs operationsNEWLINE :vartype runs: azure.mgmt.containerregistry.v2019_05_01.operations.RunsOperationsNEWLINE :ivar tasks: Tasks operationsNEWLINE :vartype tasks: azure.mgmt.containerregistry.v2019_05_01.operations.TasksOperationsNEWLINENEWLINE :param credentials: Credentials needed for the client to connect to Azure.NEWLINE :type credentials: :mod:`A msrestazure CredentialsNEWLINE object`NEWLINE :param subscription_id: The Microsoft Azure subscription ID.NEWLINE :type subscription_id: strNEWLINE :param str base_url: Service URLNEWLINE """NEWLINENEWLINE def __init__(NEWLINE self, credentials, subscription_id, base_url=None):NEWLINENEWLINE self.config = ContainerRegistryManagementClientConfiguration(credentials, subscription_id, base_url)NEWLINE super(ContainerRegistryManagementClient, self).__init__(self.config.credentials, self.config)NEWLINENEWLINE client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}NEWLINE self._serialize = Serializer(client_models)NEWLINE self._deserialize = Deserializer(client_models)NEWLINENEWLINE self.registries = RegistriesOperations(NEWLINE self._client, self.config, self._serialize, self._deserialize)NEWLINE self.operations = Operations(NEWLINE self._client, self.config, self._serialize, self._deserialize)NEWLINE self.replications = ReplicationsOperations(NEWLINE self._client, self.config, self._serialize, self._deserialize)NEWLINE self.webhooks = WebhooksOperations(NEWLINE self._client, self.config, self._serialize, self._deserialize)NEWLINE self.runs = RunsOperations(NEWLINE self._client, self.config, self._serialize, self._deserialize)NEWLINE self.tasks = TasksOperations(NEWLINE self._client, self.config, self._serialize, self._deserialize)NEWLINE class RenderContentBase():NEWLINE '''NEWLINE This defines the data common for all content type renderersNEWLINE '''NEWLINENEWLINE def __init__(self, question_bundle):NEWLINE self.question_list = question_bundle.splitlines()NEWLINENEWLINE self.close_tokens = ')」}>』'NEWLINE self.tokens = '(「{<『'NEWLINENEWLINE self.ts_reading ='('NEWLINE self.te_reading =')'NEWLINE self.ts_writing ='「'NEWLINE self.te_writing ='」'NEWLINE self.ts_furi = '『'NEWLINE self.te_furi = '』'NEWLINE self.ts_combo ='{'NEWLINE self.te_combo ='}'NEWLINE self.ts_bonus ='<'NEWLINE self.te_bonus ='>'NEWLINE self.split = '|'NEWLINE # Licensed under a 3-clause BSD style license - see LICENSE.rstNEWLINENEWLINE"""NEWLINEThis module provides utility functions for the models packageNEWLINE"""NEWLINENEWLINENEWLINEfrom collections import dequeNEWLINEfrom collections.abc import MutableMappingNEWLINEfrom inspect import signatureNEWLINENEWLINEimport numpy as npNEWLINENEWLINENEWLINEfrom ..utils import isiterable, check_broadcastNEWLINEfrom ..utils.compat import NUMPY_LT_1_14NEWLINENEWLINEfrom .. import units as uNEWLINENEWLINE__all__ = ['ExpressionTree', 'AliasDict', 'check_broadcast',NEWLINE 'poly_map_domain', 'comb', 'ellipse_extent']NEWLINENEWLINENEWLINEclass ExpressionTree:NEWLINE __slots__ = ['left', 'right', 'value', 'inputs', 'outputs']NEWLINENEWLINE def __init__(self, value, left=None, right=None, inputs=None, outputs=None):NEWLINE self.value = valueNEWLINE self.inputs = inputsNEWLINE self.outputs = outputsNEWLINE self.left = leftNEWLINENEWLINE # Two subtrees can't be the same *object* or else traverse_postorderNEWLINE # breaks, so we just always copy the right subtree to subvert that.NEWLINE if right is not None and left is right:NEWLINE right = right.copy()NEWLINENEWLINE self.right = rightNEWLINENEWLINE def __getstate__(self):NEWLINE # For some reason the default pickle protocol on Python 2 does not justNEWLINE # do this. On Python 3 it's not a problem.NEWLINE return dict((slot, getattr(self, slot)) for slot in self.__slots__)NEWLINENEWLINE def __setstate__(self, state):NEWLINE for slot, value in state.items():NEWLINE setattr(self, slot, value)NEWLINENEWLINE @staticmethodNEWLINE def _recursive_lookup(branch, adict, key):NEWLINE if isinstance(branch, ExpressionTree):NEWLINE return adict[key]NEWLINE else:NEWLINE return branch, keyNEWLINENEWLINE @propertyNEWLINE def inputs_map(self):NEWLINE """NEWLINE Map the names of the inputs to this ExpressionTree to the inputs to the leaf models.NEWLINE """NEWLINE inputs_map = {}NEWLINE if not isinstance(self.value, str): # If we don't have an operator the mapping is trivialNEWLINE return {inp: (self.value, inp) for inp in self.inputs}NEWLINENEWLINE elif self.value == '|':NEWLINE for inp in self.inputs:NEWLINE m, inp2 = self._recursive_lookup(self.left, self.left.inputs_map, inp)NEWLINE inputs_map[inp] = m, inp2NEWLINENEWLINE elif self.value == '&':NEWLINE for i, inp in enumerate(self.inputs):NEWLINE if i < len(self.left.inputs): # Get from leftNEWLINE m, inp2 = self._recursive_lookup(self.left,NEWLINE self.left.inputs_map,NEWLINE self.left.inputs[i])NEWLINE inputs_map[inp] = m, inp2NEWLINE else: # Get from rightNEWLINE m, inp2 = self._recursive_lookup(self.right,NEWLINE self.right.inputs_map,NEWLINE self.right.inputs[i - len(self.left.inputs)])NEWLINE inputs_map[inp] = m, inp2NEWLINENEWLINE else:NEWLINE for inp in self.left.inputs:NEWLINE m, inp2 = self._recursive_lookup(self.left, self.left.inputs_map, inp)NEWLINE inputs_map[inp] = m, inp2NEWLINENEWLINE return inputs_mapNEWLINENEWLINE @propertyNEWLINE def outputs_map(self):NEWLINE """NEWLINE Map the names of the outputs to this ExpressionTree to the outputs to the leaf models.NEWLINE """NEWLINE outputs_map = {}NEWLINE if not isinstance(self.value, str): # If we don't have an operator the mapping is trivialNEWLINE return {out: (self.value, out) for out in self.outputs}NEWLINENEWLINE elif self.value == '|':NEWLINE for out in self.outputs:NEWLINE m, out2 = self._recursive_lookup(self.right, self.right.outputs_map, out)NEWLINE outputs_map[out] = m, out2NEWLINENEWLINE elif self.value == '&':NEWLINE for i, out in enumerate(self.outputs):NEWLINE if i < len(self.left.outputs): # Get from leftNEWLINE m, out2 = self._recursive_lookup(self.left,NEWLINE self.left.outputs_map,NEWLINE self.left.outputs[i])NEWLINE outputs_map[out] = m, out2NEWLINE else: # Get from rightNEWLINE m, out2 = self._recursive_lookup(self.right,NEWLINE self.right.outputs_map,NEWLINE self.right.outputs[i - len(self.left.outputs)])NEWLINE outputs_map[out] = m, out2NEWLINENEWLINE else:NEWLINE for out in self.left.outputs:NEWLINE m, out2 = self._recursive_lookup(self.left, self.left.outputs_map, out)NEWLINE outputs_map[out] = m, out2NEWLINENEWLINE return outputs_mapNEWLINENEWLINE @propertyNEWLINE def isleaf(self):NEWLINE return self.left is None and self.right is NoneNEWLINENEWLINE def traverse_preorder(self):NEWLINE stack = deque([self])NEWLINE while stack:NEWLINE node = stack.pop()NEWLINE yield nodeNEWLINENEWLINE if node.right is not None:NEWLINE stack.append(node.right)NEWLINE if node.left is not None:NEWLINE stack.append(node.left)NEWLINENEWLINE def traverse_inorder(self):NEWLINE stack = deque()NEWLINE node = selfNEWLINE while stack or node is not None:NEWLINE if node is not None:NEWLINE stack.append(node)NEWLINE node = node.leftNEWLINE else:NEWLINE node = stack.pop()NEWLINE yield nodeNEWLINE node = node.rightNEWLINENEWLINE def traverse_postorder(self):NEWLINE stack = deque([self])NEWLINE last = NoneNEWLINE while stack:NEWLINE node = stack[-1]NEWLINE if last is None or node is last.left or node is last.right:NEWLINE if node.left is not None:NEWLINE stack.append(node.left)NEWLINE elif node.right is not None:NEWLINE stack.append(node.right)NEWLINE elif node.left is last and node.right is not None:NEWLINE stack.append(node.right)NEWLINE else:NEWLINE yield stack.pop()NEWLINE last = nodeNEWLINENEWLINE def evaluate(self, operators, getter=None, start=0, stop=None):NEWLINE """Evaluate the expression represented by this tree.NEWLINENEWLINE ``Operators`` should be a dictionary mapping operator names ('tensor',NEWLINE 'product', etc.) to a function that implements that operator for theNEWLINE correct number of operands.NEWLINENEWLINE If given, ``getter`` is a function evaluated on each *leaf* node'sNEWLINE value before applying the operator between them. This could be used,NEWLINE for example, to operate on an attribute of the node values rather thanNEWLINE directly on the node values. The ``getter`` is passed both the indexNEWLINE of the leaf (a count starting at 0 that is incremented after each leafNEWLINE is found) and the leaf node itself.NEWLINENEWLINE The ``start`` and ``stop`` arguments allow evaluating a sub-expressionNEWLINE within the expression tree.NEWLINENEWLINE TODO: Document this better.NEWLINE """NEWLINENEWLINE stack = deque()NEWLINENEWLINE if getter is None:NEWLINE getter = lambda idx, value: valueNEWLINENEWLINE if start is None:NEWLINE start = 0NEWLINENEWLINE leaf_idx = 0NEWLINE for node in self.traverse_postorder():NEWLINE if node.isleaf:NEWLINE # For a "tree" containing just a single operator at the rootNEWLINE # Also push the index of this leaf onto the stack, which willNEWLINE # prove useful for evaluating subexpressionsNEWLINE stack.append((getter(leaf_idx, node.value), leaf_idx))NEWLINE leaf_idx += 1NEWLINE else:NEWLINE operator = operators[node.value]NEWLINENEWLINE if len(stack) < 2:NEWLINE # Skip this operator if there are not enough operands onNEWLINE # the stack; this can happen if some operands were skippedNEWLINE # when evaluating a sub-expressionNEWLINE continueNEWLINENEWLINE right = stack.pop()NEWLINE left = stack.pop()NEWLINE operands = []NEWLINENEWLINE for operand in (left, right):NEWLINE # idx is the leaf index; -1 if not a leaf nodeNEWLINE if operand[-1] == -1:NEWLINE operands.append(operand)NEWLINE else:NEWLINE operand, idx = operandNEWLINE if start <= idx and (stop is None or idx < stop):NEWLINE operands.append((operand, idx))NEWLINENEWLINE if len(operands) == 2:NEWLINE # evaluate the operator with the given operands and placeNEWLINE # the result on the stack (with -1 for the "leaf index"NEWLINE # since this result is not a leaf nodeNEWLINE left, right = operandsNEWLINE stack.append((operator(left[0], right[0]), -1))NEWLINE elif len(operands) == 0:NEWLINE # Just push the left one back on the stackNEWLINE # TODO: Explain and/or refactor this betterNEWLINE # This is here because even if both operands were "skipped"NEWLINE # due to being outside the (start, stop) range, we've onlyNEWLINE # skipped one operator. But there should be at least 2NEWLINE # operators involving these operands, so we push the oneNEWLINE # from the left back onto the stack so that the nextNEWLINE # operator will be skipped as well. Should probably comeNEWLINE # up with an easier to follow way to write this algorithmNEWLINE stack.append(left)NEWLINE else:NEWLINE # one or more of the operands was not included in theNEWLINE # sub-expression slice, so don't evaluate the operator;NEWLINE # instead place left over operands (if any) back on theNEWLINE # stack for later useNEWLINE stack.extend(operands)NEWLINENEWLINE return stack.pop()[0]NEWLINENEWLINE def copy(self):NEWLINE # Hopefully this won't blow the stack for any practical case; if such aNEWLINE # case arises that this won't work then I suppose we can find anNEWLINE # iterative approach.NEWLINENEWLINE children = []NEWLINE for child in (self.left, self.right):NEWLINE if isinstance(child, ExpressionTree):NEWLINE children.append(child.copy())NEWLINE else:NEWLINE children.append(child)NEWLINENEWLINE return self.__class__(self.value, left=children[0], right=children[1])NEWLINENEWLINE def format_expression(self, operator_precedence, format_leaf=None):NEWLINE leaf_idx = 0NEWLINE operands = deque()NEWLINENEWLINE if format_leaf is None:NEWLINE format_leaf = lambda i, l: '[{0}]'.format(i)NEWLINENEWLINE for node in self.traverse_postorder():NEWLINE if node.isleaf:NEWLINE operands.append(format_leaf(leaf_idx, node))NEWLINE leaf_idx += 1NEWLINE continueNEWLINENEWLINE oper_order = operator_precedence[node.value]NEWLINE right = operands.pop()NEWLINE left = operands.pop()NEWLINENEWLINE if (node.left is not None and not node.left.isleaf andNEWLINE operator_precedence[node.left.value] < oper_order):NEWLINE left = '({0})'.format(left)NEWLINE if (node.right is not None and not node.right.isleaf andNEWLINE operator_precedence[node.right.value] < oper_order):NEWLINE right = '({0})'.format(right)NEWLINENEWLINE operands.append(' '.join((left, node.value, right)))NEWLINENEWLINE return ''.join(operands)NEWLINENEWLINENEWLINEclass AliasDict(MutableMapping):NEWLINE """NEWLINE Creates a `dict` like object that wraps an existing `dict` or otherNEWLINE `MutableMapping`, along with a `dict` of *key aliases* that translateNEWLINE between specific keys in this dict to different keys in the underlyingNEWLINE dict.NEWLINENEWLINE In other words, keys that do not have an associated alias are accessed andNEWLINE stored like a normal `dict`. However, a key that has an alias is accessedNEWLINE and stored to the "parent" dict via the alias.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE parent : dict-likeNEWLINE The parent `dict` that aliased keys and accessed from and stored to.NEWLINENEWLINE aliases : dict-likeNEWLINE Maps keys in this dict to their associated keys in the parent dict.NEWLINENEWLINE ExamplesNEWLINE --------NEWLINENEWLINE >>> parent = {'a': 1, 'b': 2, 'c': 3}NEWLINE >>> aliases = {'foo': 'a', 'bar': 'c'}NEWLINE >>> alias_dict = AliasDict(parent, aliases)NEWLINE >>> alias_dict['foo']NEWLINE 1NEWLINE >>> alias_dict['bar']NEWLINE 3NEWLINENEWLINE Keys in the original parent dict are not visible if they were notNEWLINE aliased::NEWLINENEWLINE >>> alias_dict['b']NEWLINE Traceback (most recent call last):NEWLINE ...NEWLINE KeyError: 'b'NEWLINENEWLINE Likewise, updates to aliased keys are reflected back in the parent dict::NEWLINENEWLINE >>> alias_dict['foo'] = 42NEWLINE >>> alias_dict['foo']NEWLINE 42NEWLINE >>> parent['a']NEWLINE 42NEWLINENEWLINE However, updates/insertions to keys that are *not* aliased are notNEWLINE reflected in the parent dict::NEWLINENEWLINE >>> alias_dict['qux'] = 99NEWLINE >>> alias_dict['qux']NEWLINE 99NEWLINE >>> 'qux' in parentNEWLINE FalseNEWLINENEWLINE In particular, updates on the `AliasDict` to a key that is equal toNEWLINE one of the aliased keys in the parent dict does *not* update the parentNEWLINE dict. For example, ``alias_dict`` aliases ``'foo'`` to ``'a'``. ButNEWLINE assigning to a key ``'a'`` on the `AliasDict` does not impact theNEWLINE parent::NEWLINENEWLINE >>> alias_dict['a'] = 'nope'NEWLINE >>> alias_dict['a']NEWLINE 'nope'NEWLINE >>> parent['a']NEWLINE 42NEWLINE """NEWLINENEWLINE _store_type = dictNEWLINE """NEWLINE Subclasses may override this to use other mapping types as the underlyingNEWLINE storage, for example an `OrderedDict`. However, even in this caseNEWLINE additional work may be needed to get things like the ordering right.NEWLINE """NEWLINENEWLINE def __init__(self, parent, aliases):NEWLINE self._parent = parentNEWLINE self._store = self._store_type()NEWLINE self._aliases = dict(aliases)NEWLINENEWLINE def __getitem__(self, key):NEWLINE if key in self._aliases:NEWLINE try:NEWLINE return self._parent[self._aliases[key]]NEWLINE except KeyError:NEWLINE raise KeyError(key)NEWLINENEWLINE return self._store[key]NEWLINENEWLINE def __setitem__(self, key, value):NEWLINE if key in self._aliases:NEWLINE self._parent[self._aliases[key]] = valueNEWLINE else:NEWLINE self._store[key] = valueNEWLINENEWLINE def __delitem__(self, key):NEWLINE if key in self._aliases:NEWLINE try:NEWLINE del self._parent[self._aliases[key]]NEWLINE except KeyError:NEWLINE raise KeyError(key)NEWLINE else:NEWLINE del self._store[key]NEWLINENEWLINE def __iter__(self):NEWLINE """NEWLINE First iterates over keys from the parent dict (if the aliased keys areNEWLINE present in the parent), followed by any keys in the local store.NEWLINE """NEWLINENEWLINE for key, alias in self._aliases.items():NEWLINE if alias in self._parent:NEWLINE yield keyNEWLINENEWLINE for key in self._store:NEWLINE yield keyNEWLINENEWLINE def __len__(self):NEWLINE # TODO:NEWLINE # This could be done more efficiently, but at present the use case forNEWLINE # it is narrow if non-existent.NEWLINE return len(list(iter(self)))NEWLINENEWLINE def __repr__(self):NEWLINE # repr() just like any other dict--this should look transparentNEWLINE store_copy = self._store_type()NEWLINE for key, alias in self._aliases.items():NEWLINE if alias in self._parent:NEWLINE store_copy[key] = self._parent[alias]NEWLINENEWLINE store_copy.update(self._store)NEWLINENEWLINE return repr(store_copy)NEWLINENEWLINENEWLINEclass _BoundingBox(tuple):NEWLINE """NEWLINE Base class for models with custom bounding box templates (methods thatNEWLINE return an actual bounding box tuple given some adjustable parameters--seeNEWLINE for example `~astropy.modeling.models.Gaussian1D.bounding_box`).NEWLINENEWLINE On these classes the ``bounding_box`` property still returns a `tuple`NEWLINE giving the default bounding box for that instance of the model. But thatNEWLINE tuple may also be a subclass of this class that is callable, and allowsNEWLINE a new tuple to be returned using a user-supplied value for any adjustableNEWLINE parameters to the bounding box.NEWLINE """NEWLINENEWLINE _model = NoneNEWLINENEWLINE def __new__(cls, input_, _model=None):NEWLINE self = super().__new__(cls, input_)NEWLINE if _model is not None:NEWLINE # Bind this _BoundingBox (most likely a subclass) to a ModelNEWLINE # instance so that its __call__ can access the modelNEWLINE self._model = _modelNEWLINENEWLINE return selfNEWLINENEWLINE def __call__(self, *args, **kwargs):NEWLINE raise NotImplementedError(NEWLINE "This bounding box is fixed by the model and does not have "NEWLINE "adjustable parameters.")NEWLINENEWLINE @classmethodNEWLINE def validate(cls, model, bounding_box):NEWLINE """NEWLINE Validate a given bounding box sequence against the given model (whichNEWLINE may be either a subclass of `~astropy.modeling.Model` or an instanceNEWLINE thereof, so long as the ``.inputs`` attribute is defined.NEWLINENEWLINE Currently this just checks that the bounding_box is either a 2-tupleNEWLINE of lower and upper bounds for 1-D models, or an N-tuple of 2-tuplesNEWLINE for N-D models.NEWLINENEWLINE This also returns a normalized version of the bounding_box input toNEWLINE ensure it is always an N-tuple (even for the 1-D case).NEWLINE """NEWLINENEWLINE nd = model.n_inputsNEWLINENEWLINE if nd == 1:NEWLINE if (not isiterable(bounding_box)NEWLINE or np.shape(bounding_box) not in ((2,), (1, 2))):NEWLINE raise ValueError(NEWLINE "Bounding box for {0} model must be a sequence of length "NEWLINE "2 consisting of a lower and upper bound, or a 1-tuple "NEWLINE "containing such a sequence as its sole element.".format(NEWLINE model.name))NEWLINENEWLINE if len(bounding_box) == 1:NEWLINE return cls((tuple(bounding_box[0]),))NEWLINE else:NEWLINE return cls(tuple(bounding_box))NEWLINE else:NEWLINE if (not isiterable(bounding_box)NEWLINE or np.shape(bounding_box) != (nd, 2)):NEWLINE raise ValueError(NEWLINE "Bounding box for {0} model must be a sequence of length "NEWLINE "{1} (the number of model inputs) consisting of pairs of "NEWLINE "lower and upper bounds for those inputs on which to "NEWLINE "evaluate the model.".format(model.name, nd))NEWLINENEWLINE return cls(tuple(bounds) for bounds in bounding_box)NEWLINENEWLINENEWLINEdef make_binary_operator_eval(oper, f, g):NEWLINE """NEWLINE Given a binary operator (as a callable of two arguments) ``oper`` andNEWLINE two callables ``f`` and ``g`` which accept the same arguments,NEWLINE returns a *new* function that takes the same arguments as ``f`` and ``g``,NEWLINE but passes the outputs of ``f`` and ``g`` in the given ``oper``.NEWLINENEWLINE ``f`` and ``g`` are assumed to return tuples (which may be 1-tuples). TheNEWLINE given operator is applied element-wise to tuple outputs).NEWLINENEWLINE ExampleNEWLINE -------NEWLINENEWLINE >>> from operator import addNEWLINE >>> def prod(x, y):NEWLINE ... return (x * y,)NEWLINE ...NEWLINE >>> sum_of_prod = make_binary_operator_eval(add, prod, prod)NEWLINE >>> sum_of_prod(3, 5)NEWLINE (30,)NEWLINE """NEWLINENEWLINE return lambda inputs, params: \NEWLINE tuple(oper(x, y) for x, y in zip(f(inputs, params),NEWLINE g(inputs, params)))NEWLINENEWLINENEWLINEdef poly_map_domain(oldx, domain, window):NEWLINE """NEWLINE Map domain into window by shifting and scaling.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE oldx : arrayNEWLINE original coordinatesNEWLINE domain : list or tuple of length 2NEWLINE function domainNEWLINE window : list or tuple of length 2NEWLINE range into which to map the domainNEWLINE """NEWLINE domain = np.array(domain, dtype=np.float64)NEWLINE window = np.array(window, dtype=np.float64)NEWLINE scl = (window[1] - window[0]) / (domain[1] - domain[0])NEWLINE off = (window[0] * domain[1] - window[1] * domain[0]) / (domain[1] - domain[0])NEWLINE return off + scl * oldxNEWLINENEWLINENEWLINEdef comb(N, k):NEWLINE """NEWLINE The number of combinations of N things taken k at a time.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE N : int, arrayNEWLINE Number of things.NEWLINE k : int, arrayNEWLINE Number of elements taken.NEWLINENEWLINE """NEWLINE if (k > N) or (N < 0) or (k < 0):NEWLINE return 0NEWLINE val = 1NEWLINE for j in range(min(k, N - k)):NEWLINE val = (val * (N - j)) / (j + 1)NEWLINE return valNEWLINENEWLINENEWLINEdef array_repr_oneline(array):NEWLINE """NEWLINE Represents a multi-dimensional Numpy array flattened onto a single line.NEWLINE """NEWLINE sep = ',' if NUMPY_LT_1_14 else ', 'NEWLINE r = np.array2string(array, separator=sep, suppress_small=True)NEWLINE return ' '.join(l.strip() for l in r.splitlines())NEWLINENEWLINENEWLINEdef combine_labels(left, right):NEWLINE """NEWLINE For use with the join operator &: Combine left input/output labels withNEWLINE right input/output labels.NEWLINENEWLINE If none of the labels conflict then this just returns a sum of tuples.NEWLINE However if *any* of the labels conflict, this appends '0' to the left-handNEWLINE labels and '1' to the right-hand labels so there is no ambiguity).NEWLINE """NEWLINENEWLINE if set(left).intersection(right):NEWLINE left = tuple(l + '0' for l in left)NEWLINE right = tuple(r + '1' for r in right)NEWLINENEWLINE return left + rightNEWLINENEWLINENEWLINEdef ellipse_extent(a, b, theta):NEWLINE """NEWLINE Calculates the extent of a box encapsulating a rotated 2D ellipse.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE a : float or `~astropy.units.Quantity`NEWLINE Major axis.NEWLINE b : float or `~astropy.units.Quantity`NEWLINE Minor axis.NEWLINE theta : float or `~astropy.units.Quantity`NEWLINE Rotation angle. If given as a floating-point value, it is assumed to beNEWLINE in radians.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE offsets : tupleNEWLINE The absolute value of the offset distances from the ellipse center thatNEWLINE define its bounding box region, ``(dx, dy)``.NEWLINENEWLINE ExamplesNEWLINE --------NEWLINE .. plot::NEWLINE :include-source:NEWLINENEWLINE import numpy as npNEWLINE import matplotlib.pyplot as pltNEWLINE from astropy.modeling.models import Ellipse2DNEWLINE from astropy.modeling.utils import ellipse_extent, render_modelNEWLINENEWLINE amplitude = 1NEWLINE x0 = 50NEWLINE y0 = 50NEWLINE a = 30NEWLINE b = 10NEWLINE theta = np.pi/4NEWLINENEWLINE model = Ellipse2D(amplitude, x0, y0, a, b, theta)NEWLINENEWLINE dx, dy = ellipse_extent(a, b, theta)NEWLINENEWLINE limits = [x0 - dx, x0 + dx, y0 - dy, y0 + dy]NEWLINENEWLINE model.bounding_box = limitsNEWLINENEWLINE image = render_model(model)NEWLINENEWLINE plt.imshow(image, cmap='binary', interpolation='nearest', alpha=.5,NEWLINE extent = limits)NEWLINE plt.show()NEWLINE """NEWLINENEWLINE t = np.arctan2(-b * np.tan(theta), a)NEWLINE dx = a * np.cos(t) * np.cos(theta) - b * np.sin(t) * np.sin(theta)NEWLINENEWLINE t = np.arctan2(b, a * np.tan(theta))NEWLINE dy = b * np.sin(t) * np.cos(theta) + a * np.cos(t) * np.sin(theta)NEWLINENEWLINE if isinstance(dx, u.Quantity) or isinstance(dy, u.Quantity):NEWLINE return np.abs(u.Quantity([dx, dy]))NEWLINE else:NEWLINE return np.abs([dx, dy])NEWLINENEWLINENEWLINEdef get_inputs_and_params(func):NEWLINE """NEWLINE Given a callable, determine the input variables and theNEWLINE parameters.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE func : callableNEWLINENEWLINE ReturnsNEWLINE -------NEWLINE inputs, params : tupleNEWLINE Each entry is a list of inspect.Parameter objectsNEWLINE """NEWLINE sig = signature(func)NEWLINENEWLINE inputs = []NEWLINE params = []NEWLINE for param in sig.parameters.values():NEWLINE if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):NEWLINE raise ValueError("Signature must not have *args or **kwargs")NEWLINE if param.default == param.empty:NEWLINE inputs.append(param)NEWLINE else:NEWLINE params.append(param)NEWLINENEWLINE return inputs, paramsNEWLINENEWLINENEWLINEdef _parameter_with_unit(parameter, unit):NEWLINE if parameter.unit is None:NEWLINE return parameter.value * unitNEWLINE else:NEWLINE return parameter.quantity.to(unit)NEWLINENEWLINENEWLINEdef _parameter_without_unit(value, old_unit, new_unit):NEWLINE if old_unit is None:NEWLINE return valueNEWLINE else:NEWLINE return value * old_unit.to(new_unit)NEWLINENEWLINENEWLINEdef _combine_equivalency_dict(keys, eq1=None, eq2=None):NEWLINE # Given two dictionaries that give equivalencies for a set of keys, forNEWLINE # example input value names, return a dictionary that includes all theNEWLINE # equivalenciesNEWLINE eq = {}NEWLINE for key in keys:NEWLINE eq[key] = []NEWLINE if eq1 is not None and key in eq1:NEWLINE eq[key].extend(eq1[key])NEWLINE if eq2 is not None and key in eq2:NEWLINE eq[key].extend(eq2[key])NEWLINE return eqNEWLINENEWLINENEWLINEdef _to_radian(value):NEWLINE """ Convert ``value`` to radian. """NEWLINE if isinstance(value, u.Quantity):NEWLINE return value.to(u.rad)NEWLINE else:NEWLINE return np.deg2rad(value)NEWLINENEWLINENEWLINEdef _to_orig_unit(value, raw_unit=None, orig_unit=None):NEWLINE """ Convert value with ``raw_unit`` to ``orig_unit``. """NEWLINE if raw_unit is not None:NEWLINE return (value * raw_unit).to(orig_unit)NEWLINE else:NEWLINE return np.rad2deg(value)NEWLINE # -*- coding: utf-8 -*-NEWLINE"""NEWLINECreated on Thu Jan 14 12:58:41 2015NEWLINE@author: Tony SaadNEWLINE"""NEWLINE# -*- coding: utf-8 -*-NEWLINENEWLINEimport numpy as npNEWLINEimport argparseNEWLINEimport osNEWLINEfrom xml.dom import minidomNEWLINEfrom shutil import copyfileNEWLINEimport matplotlib.pyplot as pltNEWLINENEWLINE#------------------------------------------------------------------------------NEWLINE"""NEWLINEGiven a 3D array A of size (Nx, Ny, Nz) (representative of a CFD mesh), NEWLINEthis function computes a new array B of size (Nx/2, Ny/2, Nz/2)NEWLINEsuch that the entries in B are the averaged values of corresponding cells in A.NEWLINESpecifically, for a cell centered scalar quantity that lives on A, every cellNEWLINEin B corresponds to the average of the 8 cells in A.NEWLINE@author: Tony SaadNEWLINE"""NEWLINEdef average(phi):NEWLINE # get the dimensions of the input arrayNEWLINE shape = phi.shapeNEWLINE nx0 = shape[0]NEWLINE ny0 = shape[1]NEWLINE nz0 = shape[2]NEWLINE # we will average two points in each dimensionNEWLINE nx = nx0/2NEWLINE ny = ny0/2NEWLINE nz = nz0/2NEWLINE phiAv = np.zeros([nx,ny,nz])NEWLINE for iav in range(0,nx):NEWLINE for jav in range(0,ny):NEWLINE for kav in range(0,nz): NEWLINE i = 2*iavNEWLINE j = 2*javNEWLINE k = 2*kavNEWLINE average = (phi[i,j,k] + phi[i+1,j,k] + phi[i,j+1,k] + phi[i,j,k+1] + phi[i+1,j+1,k] + phi[i+1,j,k+1] + phi[i,j+1,k+1] + phi[i+1,j+1,k+1])/8.0NEWLINE# average = (phi[i,j,k] + phi[i,j+1,k] + phi[i,j,k+1] + phi[i,j+1,k+1] )/4.0NEWLINE phiAv[iav,jav,kav] = averageNEWLINE return phiAvNEWLINENEWLINE#------------------------------------------------------------------------------NEWLINEdef main():NEWLINE parser = argparse.ArgumentParser(description=NEWLINE 'Computes spatial order of accuracy without the need of an anlytical solution. The method '+NEWLINE 'is based on computing numerical solutions at refined timesteps and then computing the '+NEWLINE 'order as p = ln[(f3 - f2)/(f2 - f1)]/ln(0.5).' +NEWLINE ' The cleanest way to operate this script is to make a copy of it in a new directory. Then '+NEWLINE 'copy the ups file to that directory and execute the script.' )NEWLINE NEWLINE parser.add_argument('-ups',NEWLINE help='The input file to run.',required=True) NEWLINE NEWLINE parser.add_argument('-levels',NEWLINE help='The number of spatial refinement levels.', type=int) NEWLINE NEWLINE parser.add_argument('-nsteps',NEWLINE help='The number of timesteps. Defaults to 1.', type=int) NEWLINE NEWLINE parser.add_argument('-suspath',NEWLINE help='The path to sus.',required=True)NEWLINE NEWLINE parser.add_argument('-vars', required=True,NEWLINE help='Comma seperated list of variables for which the temporal order is to be computed. example: -vars "var1, my var".')NEWLINE NEWLINE args = parser.parse_args()NEWLINE NEWLINE # if the number of levels is not provided, set it to 3NEWLINE if args.levels is None:NEWLINE args.levels = 3NEWLINE NEWLINE # if the number of levels is <2, then reset it to 3NEWLINE if (args.levels < 2):NEWLINE print 'The number of levels has to be >= 3. Setting levels to 3'NEWLINE args.levels = 3NEWLINE NEWLINE rootups = args.upsNEWLINE nLevels = args.levelsNEWLINE NEWLINE # cleanup the list of variables for which the order is to be computedNEWLINE myvars = [x.strip() for x in args.vars.split(',')]NEWLINE NEWLINE # first makes copies of the ups filesNEWLINE fnames = []NEWLINE basename = os.path.basename(rootups)NEWLINE basename = os.path.splitext(basename)[0]NEWLINE for i in range(0,nLevels):NEWLINE #fname = os.path.splitext(rootups)[0] + '-t' + str(i) + '.ups' NEWLINE fname = basename + '-t' + str(i) + '.ups'NEWLINE fnames.append(fname)NEWLINE copyfile(rootups, fname) NEWLINE NEWLINE # now loop over the copied files and change the dt and the uda nameNEWLINE refinement = 1NEWLINE maxSteps = 1NEWLINE NEWLINE if args.nsteps is not None:NEWLINE maxSteps = args.nstepsNEWLINE NEWLINE args.suspath = os.path.normpath(args.suspath)NEWLINE args.suspath = os.path.abspath(args.suspath)NEWLINE print args.suspathNEWLINE os.system('ln -fs ' + args.suspath + '/sus sus')NEWLINE os.system('ln -fs ' + args.suspath + '/tools/extractors/lineextract lineextract')NEWLINE NEWLINE # find total number of procs and resolutionNEWLINE xmldoc = minidom.parse(rootups)NEWLINE for node in xmldoc.getElementsByTagName('patches'):NEWLINE P = (str(node.firstChild.data).strip()).split(',')NEWLINE P0=int(P[0].split('[')[1])NEWLINE P1=int(P[1])NEWLINE P2=int(P[2].split(']')[0])NEWLINE total_proc = P0*P1*P2NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('resolution'):NEWLINE P = (str(node.firstChild.data).strip()).split(',')NEWLINE Nx=int(P[0].split('[')[1])NEWLINE Ny=int(P[1])NEWLINE Nz=int(P[2].split(']')[0])NEWLINE NEWLINE for fname in fnames:NEWLINE print 'now updating xml for ', fnameNEWLINE basename = os.path.splitext(fname)[0]NEWLINE xmldoc = minidom.parse(fname)NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('filebase'):NEWLINE node.firstChild.replaceWholeText(basename + '.uda')NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('resolution'):NEWLINE node.firstChild.replaceWholeText('[' + str(Nx*refinement) + ',' + str(Ny*refinement) + ',' + str(Nz*refinement) + ']')NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('max_Timesteps'):NEWLINE node.firstChild.replaceWholeText(maxSteps*refinement)NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('delt_min'):NEWLINE dtmin = float(node.firstChild.data)NEWLINE dtmin = dtmin/refinementNEWLINE node.firstChild.replaceWholeText(dtmin)NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('delt_max'):NEWLINE node.firstChild.replaceWholeText(dtmin)NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('outputTimestepInterval'):NEWLINE node.firstChild.replaceWholeText('1')NEWLINE NEWLINE for node in xmldoc.getElementsByTagName('maxTime'):NEWLINE node.firstChild.replaceWholeText('100')NEWLINE NEWLINE refinement *= 2NEWLINE f = open(fname, 'w') NEWLINE xmldoc.writexml(f) NEWLINE f.close()NEWLINE NEWLINE # now run the filesNEWLINE counter = 0NEWLINE refinement = 1NEWLINE for fname in fnames:NEWLINE os.system('mpirun -np '+ str(total_proc) + ' ' + './sus' + ' ' + fname + ' > log.txt')NEWLINE udaName = os.path.splitext(fname)[0] + '.uda'NEWLINE # #EXTRACT THE variablesNEWLINE for var in myvars: NEWLINE outFile = str(var) + '-t' + str(counter) + '.txt'NEWLINE the_command = './lineextract -pr 32 -q -v ' + str(var) + ' -timestep ' + str(maxSteps*refinement) + ' -istart 0 0 0 -iend ' + str(Nx*refinement - 1)+' '+str(Ny*refinement -1)+' '+str(Nz*refinement - 1)+ ' -o ' + outFile +' -uda '+udaNameNEWLINE print 'Executing command: ', the_commandNEWLINE os.system(the_command)NEWLINE NEWLINE os.system('rm ' + fname) NEWLINE refinement *= 2NEWLINE counter += 1NEWLINE NEWLINE #now load the data and compute the errorsNEWLINE print '---------------- SPATIAL ORDER -------------------'NEWLINE for var in myvars: NEWLINE phiAll = []NEWLINE refinement = 1NEWLINE for i in range(0,nLevels):NEWLINE datname = str(var) + '-t' + str(i) + '.txt'NEWLINE phi = np.loadtxt(datname)NEWLINE phi = np.reshape(phi[:,3],(Nx*refinement,Ny*refinement,Nz*refinement),'F') # take the last column of phi and reshapeNEWLINE phiAll.append(phi)NEWLINE # phit = average(phi) # average phiNEWLINE # plt.matshow(phi[:,:,0])NEWLINE # plt.matshow(phit[:,:,0])NEWLINE # plt.show()NEWLINE refinement *= 2NEWLINE os.system('rm ' + datname)NEWLINE NEWLINE # local errorsNEWLINE errAll = []NEWLINE for i in range(0,nLevels-1):NEWLINE #phiav = average(phiAll[i+1]) NEWLINE diff = average(phiAll[i+1]) - phiAll[i]NEWLINE #plt.matshow(diff[:,:,0]) NEWLINE shape = diff.shapeNEWLINE size = shape[0]*shape[1]*shape[2]NEWLINE diff = diff.reshape(size)NEWLINE err = np.linalg.norm(diff,np.inf)NEWLINE errAll.append(err)NEWLINE NEWLINE #plt.show() NEWLINE # now compute orderNEWLINE print '-----------------------------' NEWLINE print ' VARIABLE: ', varNEWLINE print '-----------------------------'NEWLINE for i in range(0,nLevels-2):NEWLINE print np.log( errAll[i+1]/errAll[i] ) / np.log(0.5)NEWLINE NEWLINE os.system('rm -rf *.uda*')NEWLINE os.system('rm -rf *.dot')NEWLINE os.system('rm log.txt') NEWLINENEWLINE#------------------------------------------------------------------------------NEWLINEif __name__ == "__main__":NEWLINE main() from django.apps import AppConfigNEWLINENEWLINENEWLINEclass GiftConfig(AppConfig):NEWLINE name = 'gift'NEWLINE # Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINE"""UI tests for /bundle page"""NEWLINENEWLINEimport osNEWLINEfrom typing import ListNEWLINENEWLINEimport allureNEWLINEimport pytestNEWLINEfrom adcm_client.objects import ADCMClient, BundleNEWLINEfrom adcm_pytest_plugin import utilsNEWLINEfrom adcm_pytest_plugin.utils import catch_failedNEWLINEfrom selenium.common.exceptions import ElementClickInterceptedExceptionNEWLINENEWLINEfrom tests.conftest import DUMMY_CLUSTER_BUNDLENEWLINEfrom tests.ui_tests.app.app import ADCMTestNEWLINEfrom tests.ui_tests.app.page.admin.page import AdminIntroPageNEWLINEfrom tests.ui_tests.app.page.bundle.page import BundlePageNEWLINEfrom tests.ui_tests.app.page.bundle_list.page import BundleListPage, BundleInfoNEWLINEfrom tests.ui_tests.app.page.cluster_list.page import ClusterListPageNEWLINEfrom tests.ui_tests.app.page.host_list.page import HostListPageNEWLINENEWLINELICENSE_FP = os.path.join(utils.get_data_dir(__file__), 'license.txt')NEWLINENEWLINECLUSTER_CE_CONFIG = DUMMY_CLUSTER_BUNDLENEWLINENEWLINECLUSTER_EE_CONFIG = [NEWLINE {NEWLINE **CLUSTER_CE_CONFIG[0],NEWLINE 'description': 'enterprise description',NEWLINE 'license': 'license.txt',NEWLINE 'edition': 'enterprise',NEWLINE }NEWLINE]NEWLINENEWLINEPROVIDER_CONFIG = [NEWLINE {NEWLINE 'type': 'provider',NEWLINE 'name': 'test_provider',NEWLINE 'version': '2.15-dev',NEWLINE },NEWLINE {NEWLINE 'type': 'host',NEWLINE 'name': 'Test Host',NEWLINE 'description': 'Test Host Description',NEWLINE 'version': '2.15-dev',NEWLINE },NEWLINE]NEWLINENEWLINENEWLINEdef _assert_bundle_info_value(attribute: str, actual_info: BundleInfo, expected_info: BundleInfo):NEWLINE actual_value = getattr(actual_info, attribute)NEWLINE expected_value = getattr(expected_info, attribute)NEWLINE assert actual_value == expected_value, f"Bundle's {attribute} should be {expected_value}, not {actual_value}"NEWLINENEWLINENEWLINE# pylint: disable=redefined-outer-nameNEWLINE@allure.step('Check bundle list is empty')NEWLINEdef _check_bundle_list_is_empty(page: BundleListPage):NEWLINE assert (row_count := page.table.row_count) == 0, f'Bundle list should be empty, but {row_count} records was found'NEWLINENEWLINENEWLINE@allure.step('Check bundle is listed in table')NEWLINEdef _open_bundle_list_and_check_info(page: BundleListPage, expected_info: BundleInfo):NEWLINE """NEWLINE Open bundle list page, check that exactly 1 row is presented and check it's infoNEWLINE """NEWLINE page.open()NEWLINE assert (NEWLINE row_count := page.table.row_countNEWLINE ) == 1, f'Bundle list should have exactly 1 record, but {row_count} was found'NEWLINE bundle_info = page.get_bundle_info()NEWLINE check_bundle_info_is_equal(bundle_info, expected_info)NEWLINENEWLINENEWLINE@allure.step('Check bundle info')NEWLINEdef check_bundle_info_is_equal(actual_info: BundleInfo, expected_info: BundleInfo):NEWLINE """Assert bundle attrs values"""NEWLINE for attr in ('name', 'description', 'version', 'edition'):NEWLINE _assert_bundle_info_value(attr, actual_info, expected_info)NEWLINENEWLINENEWLINE@pytest.fixture()NEWLINE# pylint: disable-next=unused-argumentNEWLINEdef page(app_fs: ADCMTest, login_to_adcm_over_api) -> BundleListPage:NEWLINE """Get BundleListPage after authorization"""NEWLINE return BundleListPage(app_fs.driver, app_fs.adcm.url).open()NEWLINENEWLINENEWLINE@allure.title("Upload bundles")NEWLINE@pytest.fixture()NEWLINEdef upload_bundles(create_bundle_archives: List[str], sdk_client_fs: ADCMClient) -> List[Bundle]:NEWLINE """Upload bundles to ADCM"""NEWLINE return [sdk_client_fs.upload_from_fs(path) for path in create_bundle_archives]NEWLINENEWLINENEWLINE@pytest.fixture()NEWLINEdef _create_cluster(upload_bundles: List[Bundle]):NEWLINE """Upload bundles and create cluster from first bundle"""NEWLINE upload_bundles[0].cluster_create('Best Cluster Ever')NEWLINENEWLINENEWLINE@pytest.mark.smoke()NEWLINEdef test_ce_bundle_upload(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload community bundle"""NEWLINE bundle_params = BundleInfo(NEWLINE name="test_cluster", version="1.5", edition="community", description="community description"NEWLINE )NEWLINE page.upload_bundle(create_bundle_archives[0])NEWLINE bundle_info = page.get_bundle_info()NEWLINE check_bundle_info_is_equal(bundle_info, bundle_params)NEWLINENEWLINENEWLINE@pytest.mark.smoke()NEWLINE@pytest.mark.parametrize("create_bundle_archives", [([CLUSTER_EE_CONFIG], LICENSE_FP)], indirect=True)NEWLINEdef test_ee_bundle_upload(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload enterprise bundle and accept licence"""NEWLINE bundle_params = BundleInfo(NEWLINE name='test_cluster',NEWLINE version='1.5',NEWLINE edition='enterprise',NEWLINE description='enterprise description',NEWLINE )NEWLINE page.upload_bundle(create_bundle_archives[0])NEWLINE page.accept_licence()NEWLINE bundle_info = page.get_bundle_info()NEWLINE check_bundle_info_is_equal(bundle_info, bundle_params)NEWLINENEWLINENEWLINE@pytest.mark.smoke()NEWLINEdef test_delete_bundle(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload bundle and delete it"""NEWLINE with allure.step('Upload bundle'):NEWLINE page.upload_bundle(create_bundle_archives[0])NEWLINE assert page.table.row_count == 1, 'One bundle should be uploaded'NEWLINE with allure.step('Delete bundle'):NEWLINE page.delete_bundle()NEWLINE assert page.table.row_count == 0, 'No bundle should be listed in the table'NEWLINENEWLINENEWLINE@pytest.mark.parametrize(NEWLINE "create_bundle_archives", [([CLUSTER_CE_CONFIG, CLUSTER_EE_CONFIG], LICENSE_FP)], indirect=TrueNEWLINE)NEWLINEdef test_two_bundles(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload two bundles"""NEWLINE with allure.step('Upload 1st bundle'), page.table.wait_rows_change():NEWLINE page.upload_bundle(create_bundle_archives[0])NEWLINE with allure.step('Upload 2nd bundle'), page.table.wait_rows_change():NEWLINE page.upload_bundle(create_bundle_archives[1])NEWLINE with allure.step('Check there are exactly 2 rows'):NEWLINE rows = page.table.row_countNEWLINE assert rows == 2, f'Row amount should be 2, but only {rows} is presented'NEWLINENEWLINENEWLINE@allure.issue("https://arenadata.atlassian.net/browse/ADCM-2010")NEWLINE@pytest.mark.skip(reason="Not worked using selenoid https://github.com/aerokube/selenoid/issues/844")NEWLINE@pytest.mark.parametrize(NEWLINE "create_bundle_archives", [([CLUSTER_CE_CONFIG, CLUSTER_EE_CONFIG], LICENSE_FP)], indirect=TrueNEWLINE)NEWLINEdef test_accept_license_with_two_bundles_upload_at_once(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload two bundles and accept license"""NEWLINE with page.table.wait_rows_change():NEWLINE page.upload_bundles(create_bundle_archives)NEWLINE with catch_failed(ElementClickInterceptedException, "License was not accepted by single button click"):NEWLINE page.accept_licence(row_num=1)NEWLINENEWLINENEWLINE@pytest.mark.smoke()NEWLINEdef test_open_bundle_from_table(page: BundleListPage, upload_bundles: List[Bundle]):NEWLINE """Test open bundle object page from list of bundles"""NEWLINE with allure.step('Open bundle object page from bundle list'):NEWLINE page.click_bundle_in_row(page.table.get_row())NEWLINE with allure.step('Check object page is opened'):NEWLINE object_page = BundlePage(page.driver, page.base_url, upload_bundles[0].id)NEWLINE object_page.wait_page_is_opened()NEWLINENEWLINENEWLINE@pytest.mark.smoke()NEWLINEdef test_open_main_menu_on_bundle_page(page: BundleListPage, upload_bundles: List[Bundle]):NEWLINE """Open main menu on bundle detailed page"""NEWLINE with allure.step('Open bundle object page'):NEWLINE object_page = BundlePage(page.driver, page.base_url, upload_bundles[0].id)NEWLINE object_page.open()NEWLINE object_page.open_main_menu()NEWLINE object_page.check_all_main_menu_fields_are_presented()NEWLINENEWLINENEWLINE@pytest.mark.usefixtures('upload_bundles')NEWLINEdef test_open_adcm_main_menu(page: BundleListPage):NEWLINE """Open main menu by clicking on the menu icon in toolbar"""NEWLINE page.click_on_home_button_on_tooltip()NEWLINE AdminIntroPage(page.driver, page.base_url).wait_page_is_opened()NEWLINENEWLINENEWLINE@pytest.mark.usefixtures("_create_cluster")NEWLINEdef test_delete_bundle_with_created_cluster(page: BundleListPage):NEWLINE """NEWLINE Bundle should not be deleted if an object defined in it is createdNEWLINE """NEWLINE page.delete_bundle()NEWLINE page.check_at_least_one_bundle_is_presented()NEWLINENEWLINENEWLINE@pytest.mark.smoke()NEWLINE@pytest.mark.parametrize(NEWLINE "create_bundle_archives",NEWLINE [[PROVIDER_CONFIG]],NEWLINE indirect=True,NEWLINE ids=['provider_bundle'],NEWLINE)NEWLINEdef test_upload_provider_bundle_from_another_page(NEWLINE page: BundleListPage, app_fs: ADCMTest, create_bundle_archives: List[str]NEWLINE):NEWLINE """NEWLINE Upload bundle from host list and check it is presented in tableNEWLINE """NEWLINE expected_info = BundleInfo(name='test_provider', version='2.15-dev', edition='community', description='')NEWLINE _check_bundle_list_is_empty(page)NEWLINE with allure.step('Create bundle from host creation popup'):NEWLINE host_list_page = HostListPage(app_fs.driver, app_fs.adcm.url).open()NEWLINE host_list_page.upload_bundle_from_host_create_popup(create_bundle_archives[0])NEWLINE _open_bundle_list_and_check_info(page, expected_info)NEWLINENEWLINENEWLINE@pytest.mark.smoke()NEWLINE@pytest.mark.parametrize(NEWLINE "create_bundle_archives",NEWLINE [[CLUSTER_CE_CONFIG]],NEWLINE indirect=True,NEWLINE ids=['cluster_bundle'],NEWLINE)NEWLINEdef test_upload_cluster_bundle_from_another_page(NEWLINE page: BundleListPage, app_fs: ADCMTest, create_bundle_archives: List[str]NEWLINE):NEWLINE """Upload bundle from cluster list and check it is presented in table"""NEWLINE expected_info = BundleInfo(NEWLINE name='test_cluster', version='1.5', edition='community', description='community description'NEWLINE )NEWLINE _check_bundle_list_is_empty(page)NEWLINE with allure.step('Create bundle from cluster creation popup'):NEWLINE cluster_page = ClusterListPage(app_fs.driver, app_fs.adcm.url).open()NEWLINE cluster_page.upload_bundle_from_cluster_create_popup(create_bundle_archives[0])NEWLINE _open_bundle_list_and_check_info(page, expected_info)NEWLINENEWLINENEWLINE@pytest.mark.parametrize(NEWLINE "create_bundle_archives",NEWLINE [[[{'type': 'cluster', 'name': f'ihavetodance-{i}', 'version': f'{i}-ver'}] for i in range(12)]],NEWLINE indirect=True,NEWLINE)NEWLINE@pytest.mark.usefixtures("upload_bundles")NEWLINEdef test_bundle_list_pagination(page: BundleListPage):NEWLINE """Upload 12 bundles and check pagination"""NEWLINE params = {'on_first_page': 10, 'on_second_page': 2}NEWLINE page.close_info_popup()NEWLINE page.table.check_pagination(params['on_second_page'])NEWLINE # Copyright (C) 2020-2021 Intel CorporationNEWLINE# SPDX-License-Identifier: Apache-2.0NEWLINENEWLINE"""You may copy this file as the starting point of your own model."""NEWLINENEWLINEimport numpy as npNEWLINEfrom logging import getLoggerNEWLINEfrom torchvision.datasets import ImageFolderNEWLINEfrom torchvision.transforms import ToTensorNEWLINEfrom torch.utils.data import random_splitNEWLINEfrom urllib.request import urlretrieveNEWLINEfrom hashlib import sha384NEWLINEfrom os import path, makedirsNEWLINEfrom zipfile import ZipFileNEWLINEfrom tqdm import tqdmNEWLINEimport torchNEWLINEfrom collections.abc import IterableNEWLINENEWLINElogger = getLogger(__name__)NEWLINENEWLINENEWLINEclass HistologyDataset(ImageFolder):NEWLINE """Colorectal Histology Dataset."""NEWLINENEWLINE URL = "https://zenodo.org/record/53169/files/Kather_" \NEWLINE "texture_2016_image_tiles_5000.zip?download=1"NEWLINE FILENAME = "Kather_texture_2016_image_tiles_5000.zip"NEWLINE FOLDER_NAME = "Kather_texture_2016_image_tiles_5000"NEWLINE ZIP_SHA384 = '7d86abe1d04e68b77c055820c2a4c582a1d25d2983e38ab724e'\NEWLINE 'ac75affce8b7cb2cbf5ba68848dcfd9d84005d87d6790'NEWLINE DEFAULT_PATH = path.join(path.expanduser('~'), '.openfl', 'data')NEWLINENEWLINE def __init__(self, root: str = DEFAULT_PATH, **kwargs) -> None:NEWLINE """Initialize."""NEWLINE makedirs(root, exist_ok=True)NEWLINE filepath = path.join(root, HistologyDataset.FILENAME)NEWLINE if not path.exists(filepath):NEWLINE self.pbar = tqdm(total=None)NEWLINE urlretrieve(HistologyDataset.URL, filepath, self.report_hook) # nosecNEWLINE assert sha384(open(filepath, 'rb').read( # nosecNEWLINE path.getsize(filepath))).hexdigest() == HistologyDataset.ZIP_SHA384NEWLINE with ZipFile(filepath, 'r') as f:NEWLINE f.extractall(root)NEWLINENEWLINE super(HistologyDataset, self).__init__(NEWLINE path.join(root, HistologyDataset.FOLDER_NAME), **kwargs)NEWLINENEWLINE def report_hook(self, count, block_size, total_size):NEWLINE """Update progressbar."""NEWLINE if self.pbar.total is None and total_size:NEWLINE self.pbar.total = total_sizeNEWLINE progress_bytes = count * block_sizeNEWLINE self.pbar.update(progress_bytes - self.pbar.n)NEWLINENEWLINE def __getitem__(self, index):NEWLINE """Allow getting items by slice index."""NEWLINE if isinstance(index, Iterable):NEWLINE return [super(HistologyDataset, self).__getitem__(i) for i in index]NEWLINE else:NEWLINE return super(HistologyDataset, self).__getitem__(index)NEWLINENEWLINENEWLINEdef one_hot(labels, classes):NEWLINE """NEWLINE One Hot encode a vector.NEWLINENEWLINE Args:NEWLINE labels (list): List of labels to onehot encodeNEWLINE classes (int): Total number of categorical classesNEWLINENEWLINE Returns:NEWLINE np.array: Matrix of one-hot encoded labelsNEWLINE """NEWLINE return np.eye(classes)[labels]NEWLINENEWLINENEWLINEdef _load_raw_datashards(shard_num, collaborator_count, train_split_ratio=0.8):NEWLINE """NEWLINE Load the raw data by shard.NEWLINENEWLINE Returns tuples of the dataset shard divided into training and validation.NEWLINENEWLINE Args:NEWLINE shard_num (int): The shard number to useNEWLINE collaborator_count (int): The number of collaborators in the federationNEWLINENEWLINE Returns:NEWLINE 2 tuples: (image, label) of the training, validation datasetNEWLINE """NEWLINE dataset = HistologyDataset(transform=ToTensor())NEWLINE n_train = int(train_split_ratio * len(dataset))NEWLINE n_valid = len(dataset) - n_trainNEWLINE ds_train, ds_val = random_split(NEWLINE dataset, lengths=[n_train, n_valid], generator=torch.manual_seed(0))NEWLINENEWLINE # create the shardsNEWLINE X_train, y_train = list(zip(*ds_train[shard_num::collaborator_count]))NEWLINE X_train, y_train = np.stack(X_train), np.array(y_train)NEWLINENEWLINE X_valid, y_valid = list(zip(*ds_val[shard_num::collaborator_count]))NEWLINE X_valid, y_valid = np.stack(X_valid), np.array(y_valid)NEWLINENEWLINE return (X_train, y_train), (X_valid, y_valid)NEWLINENEWLINENEWLINEdef load_histology_shard(shard_num, collaborator_count,NEWLINE categorical=False, channels_last=False, **kwargs):NEWLINE """NEWLINE Load the Histology dataset.NEWLINENEWLINE Args:NEWLINE shard_num (int): The shard to use from the datasetNEWLINE collaborator_count (int): The number of collaborators in the federationNEWLINE categorical (bool): True = convert the labels to one-hot encodedNEWLINE vectors (Default = True)NEWLINE channels_last (bool): True = The input images have the channelsNEWLINE last (Default = True)NEWLINE **kwargs: Additional parameters to pass to the functionNEWLINENEWLINE Returns:NEWLINE list: The input shapeNEWLINE int: The number of classesNEWLINE numpy.ndarray: The training dataNEWLINE numpy.ndarray: The training labelsNEWLINE numpy.ndarray: The validation dataNEWLINE numpy.ndarray: The validation labelsNEWLINE """NEWLINE img_rows, img_cols = 150, 150NEWLINE num_classes = 8NEWLINENEWLINE (X_train, y_train), (X_valid, y_valid) = _load_raw_datashards(NEWLINE shard_num, collaborator_count)NEWLINENEWLINE if channels_last:NEWLINE X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 3)NEWLINE X_valid = X_valid.reshape(X_valid.shape[0], img_rows, img_cols, 3)NEWLINE input_shape = (img_rows, img_cols, 3)NEWLINE else:NEWLINE X_train = X_train.reshape(X_train.shape[0], 3, img_rows, img_cols)NEWLINE X_valid = X_valid.reshape(X_valid.shape[0], 3, img_rows, img_cols)NEWLINE input_shape = (3, img_rows, img_cols)NEWLINENEWLINE logger.info(f'Histology > X_train Shape : {X_train.shape}')NEWLINE logger.info(f'Histology > y_train Shape : {y_train.shape}')NEWLINE logger.info(f'Histology > Train Samples : {X_train.shape[0]}')NEWLINE logger.info(f'Histology > Valid Samples : {X_valid.shape[0]}')NEWLINENEWLINE if categorical:NEWLINE # convert class vectors to binary class matricesNEWLINE y_train = one_hot(y_train, num_classes)NEWLINE y_valid = one_hot(y_valid, num_classes)NEWLINENEWLINE return input_shape, num_classes, X_train, y_train, X_valid, y_validNEWLINE #!/usr/bin/env pythonNEWLINENEWLINEimport jsonNEWLINEimport sysNEWLINEimport requestsNEWLINEfrom bs4 import BeautifulSoupNEWLINENEWLINEresponse = requests.get('http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html')NEWLINEsoup = BeautifulSoup(response.text)NEWLINENEWLINEsection_h3 = soup.find(id='query-DescribeInstances-filters')NEWLINEsection_div = section_h3.find_parent('div', attrs={'class': 'section'})NEWLINENEWLINEfilter_names = []NEWLINEfor term in section_div.select('div.variablelist dt span.term'):NEWLINE filter_name = term.get_text()NEWLINE if not filter_name.startswith('tag:'):NEWLINE filter_names.append(filter_name)NEWLINEfilter_names.sort()NEWLINENEWLINEjson.dump(filter_names, sys.stdout, indent=4)NEWLINE """NEWLINE Models to manage users and profilesNEWLINE"""NEWLINEfrom django.db import modelsNEWLINEfrom django.contrib.auth.models import UserNEWLINEfrom django.conf import settingsNEWLINEfrom django.utils.translation import gettext_lazy as _NEWLINENEWLINEfrom geotrek.common.utils import reifyNEWLINENEWLINENEWLINEclass Structure(models.Model):NEWLINE """NEWLINE Represents an organisational structure, to which users are related.NEWLINE """NEWLINE name = models.CharField(max_length=256, verbose_name=_("Nom"), db_index=True)NEWLINENEWLINE def __str__(self):NEWLINE return self.nameNEWLINENEWLINE class Meta:NEWLINE verbose_name = _("Structure")NEWLINE verbose_name_plural = _("Structures")NEWLINE ordering = ['name']NEWLINE permissions = (("can_bypass_structure", _("Can bypass structure")),)NEWLINENEWLINENEWLINEdef default_structure():NEWLINE """ Create default structure if necessary """NEWLINE return Structure.objects.get_or_create(name=settings.DEFAULT_STRUCTURE_NAME)[0]NEWLINENEWLINENEWLINEdef default_structure_pk():NEWLINE return default_structure().pkNEWLINENEWLINENEWLINEclass StructureRelated(models.Model):NEWLINE """NEWLINE A mixin used for any entities that belong to a structureNEWLINE """NEWLINE structure = models.ForeignKey(Structure, default=default_structure_pk, on_delete=models.CASCADE,NEWLINE verbose_name=_("Related structure"))NEWLINENEWLINE check_structure_in_forms = TrueNEWLINENEWLINE def same_structure(self, user):NEWLINE """ Returns True if the user is in the same structure or hasNEWLINE bypass_structure permission, False otherwise. """NEWLINE return (user.profile.structure == self.structureNEWLINE or user.is_superuserNEWLINE or user.has_perm('authent.can_bypass_structure'))NEWLINENEWLINE class Meta:NEWLINE abstract = TrueNEWLINE verbose_name = _("Related structures")NEWLINE verbose_name_plural = _("Related structure")NEWLINENEWLINENEWLINEclass StructureOrNoneRelated(models.Model):NEWLINE """NEWLINE A mixin used for any entities that belong to a structure or None entityNEWLINE """NEWLINE structure = models.ForeignKey(Structure, on_delete=models.CASCADE,NEWLINE verbose_name=_("Related structure"), blank=True, null=True)NEWLINENEWLINE objects = models.Manager()NEWLINE check_structure_in_forms = TrueNEWLINENEWLINE class Meta:NEWLINE abstract = TrueNEWLINE verbose_name = _("Related structures")NEWLINE verbose_name_plural = _("Related structure")NEWLINENEWLINENEWLINEclass UserProfile(StructureRelated):NEWLINE """NEWLINE A custom user profileNEWLINE """NEWLINE user = models.OneToOneField(User, unique=True, on_delete=models.CASCADE)NEWLINE extended_username = models.CharField(blank=True, max_length=200, default="", verbose_name=_('Extended username'))NEWLINENEWLINE class Meta:NEWLINE verbose_name = _("User's profile")NEWLINE verbose_name_plural = _("User's profiles")NEWLINENEWLINE def __str__(self):NEWLINE return _("Profile for %s") % self.userNEWLINENEWLINENEWLINEUser.profile = reify(lambda u: UserProfile.objects.get_or_create(user=u)[0])NEWLINE import argparseNEWLINEimport osNEWLINEfrom math import log10NEWLINENEWLINEimport pandas as pdNEWLINEimport torch.optim as optimNEWLINEimport torch.utils.dataNEWLINEimport torchvision.utils as utilsNEWLINEfrom torch.autograd import VariableNEWLINEfrom torch.utils.data import DataLoaderNEWLINEfrom tqdm import tqdmNEWLINENEWLINEimport pytorch_ssimNEWLINEfrom data_utils import TrainDatasetFromFolder, ValDatasetFromFolder, display_transformNEWLINEfrom loss import GeneratorLossNEWLINEfrom model import GeneratorNEWLINE# from PGD import *NEWLINE# from model import DiscriminatorNEWLINEimport timeNEWLINEfrom torch.utils.tensorboard import writerNEWLINEimport torch.nn.functional as FNEWLINEimport torch.nn as nnNEWLINEfrom distillmodel import DiscriminatorNEWLINENEWLINEparser = argparse.ArgumentParser('PGDSRGAN') # progressive growing discriminator SRGANNEWLINENEWLINEparser.add_argument('--fsize', default=128, type=int)NEWLINEparser.add_argument('--crop_size', default=96, type=int, help='training images crop size')NEWLINEparser.add_argument('--upscale_factor', default=4, type=int, choices=[2, 4, 8],NEWLINE help='super resolution upscale factor')NEWLINEparser.add_argument('--num_epochs', default=80, type=int, help='train epoch number')NEWLINEparser.add_argument('--batch_size', default=32, type=int)NEWLINEparser.add_argument('--TICK', type=int, default=1000)NEWLINEparser.add_argument('--trans_tick', type=int, default=200)NEWLINEparser.add_argument('--stabile_tick', type=int, default=100)NEWLINEparser.add_argument('--is_fade', type=bool, default=False)NEWLINEparser.add_argument('--grow', type=int, default=0)NEWLINEparser.add_argument('--max_grow', type=int, default=3)NEWLINEparser.add_argument('--when_to_grow', type=int, default=256) # discriminator 증가 언제NEWLINEparser.add_argument('--version', type=int, default=0) # 1/4, 1/2, 1 -> 1, 2, 3로 주자NEWLINEparser.add_argument('--kd_range', type=int, default=5)NEWLINEparser.add_argument('--kd1', type=int, default=12)NEWLINEparser.add_argument('--kd2', type=int, default=42)NEWLINENEWLINENEWLINEdef distill_loss(y, label, score, T, alpha):NEWLINE return nn.KLDivLoss()(F.log_softmax(y / T),NEWLINE F.softmax(score / T)) * (T * T * 2.0 + alpha) + \NEWLINE F.binary_cross_entropy(y, label) * (1 - alpha)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE opt = parser.parse_args()NEWLINENEWLINE CROP_SIZE = opt.crop_sizeNEWLINE UPSCALE_FACTOR = opt.upscale_factorNEWLINE NUM_EPOCHS = opt.num_epochsNEWLINE batch_size = opt.batch_sizeNEWLINE count_image_number = 0NEWLINE trns_tick = opt.trans_tickNEWLINE stab_tick = opt.stabile_tickNEWLINE is_fade = opt.is_fadeNEWLINE change_iter = opt.when_to_growNEWLINE version = opt.versionNEWLINE kd_range = opt.kd_rangeNEWLINE kd1 = opt.kd1NEWLINE kd2 = opt.kd2NEWLINE cur_grow = 0NEWLINENEWLINE delta = 1.0 / (2 * trns_tick + 2 * stab_tick)NEWLINE d_alpha = 1.0 * batch_size / trns_tick / opt.TICKNEWLINENEWLINE fadein = {'dis': is_fade}NEWLINENEWLINE writer = writer.SummaryWriter('runs/distill')NEWLINENEWLINE train_set = TrainDatasetFromFolder('../data/train/gt', crop_size=CROP_SIZE,NEWLINE upscale_factor=UPSCALE_FACTOR,NEWLINE batch_size=batch_size)NEWLINE val_set = ValDatasetFromFolder('../data/val/gt',NEWLINE upscale_factor=UPSCALE_FACTOR)NEWLINE train_loader = DataLoader(dataset=train_set, num_workers=4, batch_size=batch_size, shuffle=True)NEWLINE val_loader = DataLoader(dataset=val_set, num_workers=1, batch_size=1, shuffle=False)NEWLINENEWLINE netG = Generator(UPSCALE_FACTOR)NEWLINE print('# generator parameters:', sum(param.numel() for param in netG.parameters()))NEWLINE # netD = Discriminator(opt)NEWLINE netD = Discriminator(opt)NEWLINENEWLINE print('# discriminator parameters:', sum(param.numel() for param in netD.parameters()))NEWLINE generator_criterion = GeneratorLoss()NEWLINENEWLINE print(torch.cuda.is_available())NEWLINENEWLINE if torch.cuda.is_available():NEWLINE netG.cuda()NEWLINE netD.cuda()NEWLINE print(netD)NEWLINE generator_criterion.cuda()NEWLINENEWLINE optimizerG = optim.Adam(netG.parameters())NEWLINE optimizerD = optim.Adam(netD.parameters())NEWLINENEWLINE results = {'d_loss': [], 'g_loss': [], 'd_score': [], 'g_score': [], 'psnr': [], 'ssim': []}NEWLINENEWLINE start = time.time()NEWLINE cnt = 0NEWLINE ncnt = 0NEWLINE distill_batch = 0NEWLINENEWLINE for epoch in range(1, NUM_EPOCHS + 1):NEWLINE epoch_flag = 0NEWLINENEWLINE train_bar = tqdm(train_loader, leave=True)NEWLINE running_results = {'batch_sizes': 0, 'd_loss': 0, 'g_loss': 0, 'd_score': 0, 'g_score': 0, 'distill_loss': 0}NEWLINENEWLINE netG.train()NEWLINE netD.train()NEWLINENEWLINE if kd1 < epoch <= kd1 + kd_range + 1 or kd2 < epoch <= kd2 + kd_range + 1:NEWLINE writer.add_scalar("loss/KD_loss", running_results['distill_loss'] / distill_batch,NEWLINE epoch - 1)NEWLINENEWLINE i = 0NEWLINE for data, target in train_bar: # train epoch (lr, hr)NEWLINE count_image_number += batch_sizeNEWLINE i += 1NEWLINENEWLINE g_update_first = TrueNEWLINE running_results['batch_sizes'] += batch_sizeNEWLINENEWLINE if kd1 <= epoch <= (kd1 + kd_range - 1) or kd2 <= epoch <= (kd2 + kd_range - 1): # discriminator KDNEWLINE epoch_flag = 1NEWLINE distill_batch += batch_sizeNEWLINE if (epoch == kd1 and cnt == 0) or (epoch == kd2 and cnt == 0):NEWLINE print("KD Phase start!")NEWLINE cnt = cnt + 1NEWLINE ncnt = 0NEWLINE opt.version = opt.version + 1NEWLINE student = Discriminator(opt)NEWLINE optimizersD = optim.Adam(student.parameters())NEWLINE print(student)NEWLINE student.cuda()NEWLINENEWLINE netG.eval()NEWLINE netD.eval()NEWLINE student.train()NEWLINE real_img = Variable(target)NEWLINE real_img = real_img.cuda()NEWLINENEWLINE z = Variable(data)NEWLINE z = z.cuda()NEWLINENEWLINE fake_img = netG(z) # lr->hrNEWLINENEWLINE netD.zero_grad()NEWLINENEWLINE teacher_fake_out = netD(fake_img).mean().reshape(1) # 학습해야함NEWLINE student_fake_out = student(fake_img).mean().reshape(1)NEWLINENEWLINE student_real_out = student(real_img).mean().reshape(1)NEWLINE teacher_real_out = netD(real_img).mean().reshape(1)NEWLINENEWLINE one = torch.Tensor([1]).reshape(1)NEWLINE one = one.cuda()NEWLINENEWLINE zero = torch.Tensor([0]).reshape(1)NEWLINE zero = zero.cuda()NEWLINENEWLINE distill_real_loss = distill_loss(student_real_out, one, teacher_real_out, 10, 0.5)NEWLINE distill_fake_loss = distill_loss(student_fake_out, zero, teacher_fake_out, 10, 0.5)NEWLINENEWLINE total_distill_loss = 0.3*distill_real_loss + 0.7*distill_fake_lossNEWLINE optimizerD.zero_grad()NEWLINE optimizersD.zero_grad()NEWLINE # writer.add_scalar("loss/distill_loss", total_distill_loss, epoch)NEWLINENEWLINE running_results['distill_loss'] += total_distill_lossNEWLINENEWLINE total_distill_loss.backward()NEWLINE optimizerD.step()NEWLINE optimizersD.step()NEWLINENEWLINE if (epoch == kd1 + kd_range - 1 and ncnt == 0 and i == len(train_loader)) or (NEWLINE epoch == kd2 + kd_range - 1 and ncnt == 0 and i == len(train_loader)): # +1NEWLINE print('netD is dumped with Student\n')NEWLINE netD = studentNEWLINE optimizerD = optimizersDNEWLINE epoch_flag = 0NEWLINE cnt = 0NEWLINE ncnt = 1NEWLINENEWLINE ############################NEWLINE # (1) Update D network: maximize D(x)-1-D(G(z))NEWLINE ###########################NEWLINE if epoch < kd1 or (kd1 + kd_range - 1 < epoch < kd2) or epoch > kd2 + kd_range - 1:NEWLINENEWLINE real_img = Variable(target)NEWLINE if torch.cuda.is_available():NEWLINE real_img = real_img.cuda()NEWLINE z = Variable(data)NEWLINE if torch.cuda.is_available():NEWLINE z = z.cuda()NEWLINE fake_img = netG(z)NEWLINENEWLINE netD.zero_grad()NEWLINE real_out = netD(real_img).mean()NEWLINE fake_out = netD(fake_img).mean()NEWLINE d_loss = 1 - real_out + fake_outNEWLINENEWLINE d_loss.backward(retain_graph=True)NEWLINE optimizerD.step()NEWLINENEWLINE ############################NEWLINE # (2) Update G network: minimize 1-D(G(z)) + Perception Loss + Image Loss + TV LossNEWLINE ###########################NEWLINE netG.zero_grad()NEWLINE ## The two lines below are added to prevent runetime error in Google Colab ##NEWLINE fake_img = netG(z)NEWLINE fake_out = netD(fake_img).mean()NEWLINE ##NEWLINE g_loss = generator_criterion(fake_out, fake_img, real_img)NEWLINENEWLINE g_loss.backward()NEWLINENEWLINE optimizerG.step()NEWLINENEWLINE # loss for current batch before optimizationNEWLINE running_results['g_loss'] += g_loss.item() * batch_sizeNEWLINE running_results['d_loss'] += d_loss.item() * batch_sizeNEWLINE running_results['d_score'] += real_out.item() * batch_sizeNEWLINE running_results['g_score'] += fake_out.item() * batch_sizeNEWLINENEWLINE # train_bar.set_description(desc='[%d/%d] Loss_D: %.4f Loss_G: %.4f D(x): %.4f D(G(z)): %.4f' % (NEWLINE # epoch, NUM_EPOCHS, running_results['d_loss'] / running_results['batch_sizes'],NEWLINE # running_results['g_loss'] / running_results['batch_sizes'],NEWLINE # running_results['d_score'] / running_results['batch_sizes'],NEWLINE # running_results['g_score'] / running_results['batch_sizes']))NEWLINENEWLINE if epoch < kd1 or (kd1 + kd_range - 1 < epoch < kd2) or epoch > kd2 + kd_range - 1:NEWLINE print('[%d/%d] Loss_D: %.4f Loss_G: %.4f D(x): %.4f D(G(z)): %.4f' % (NEWLINE epoch, NUM_EPOCHS, running_results['d_loss'] / running_results['batch_sizes'],NEWLINE running_results['g_loss'] / running_results['batch_sizes'],NEWLINE running_results['d_score'] / running_results['batch_sizes'],NEWLINE running_results['g_score'] / running_results['batch_sizes']))NEWLINENEWLINE netG.eval()NEWLINE out_path = 'training_results/SRF_' + '/'NEWLINE if not os.path.exists(out_path):NEWLINE os.makedirs(out_path)NEWLINENEWLINE with torch.no_grad():NEWLINE val_bar = tqdm(val_loader)NEWLINE valing_results = {'mse': 0, 'ssims': 0, 'psnr': 0, 'ssim': 0, 'batch_sizes': 0}NEWLINE val_images = []NEWLINE for val_lr, val_hr_restore, val_hr in val_bar:NEWLINE batch_size = val_lr.size(0)NEWLINE valing_results['batch_sizes'] += batch_sizeNEWLINE lr = val_lrNEWLINE hr = val_hrNEWLINE if torch.cuda.is_available():NEWLINE lr = lr.cuda()NEWLINE hr = hr.cuda()NEWLINE sr = netG(lr)NEWLINENEWLINE batch_mse = ((sr - hr) ** 2).data.mean()NEWLINE valing_results['mse'] += batch_mse * batch_sizeNEWLINE batch_ssim = pytorch_ssim.ssim(sr, hr).item()NEWLINE valing_results['ssims'] += batch_ssim * batch_sizeNEWLINE valing_results['psnr'] = 10 * log10(NEWLINE (hr.max() ** 2) / (valing_results['mse'] / valing_results['batch_sizes']))NEWLINE valing_results['ssim'] = valing_results['ssims'] / valing_results['batch_sizes']NEWLINE # val_bar.set_description(NEWLINE # desc='[converting LR images to SR images] PSNR: %.4f dB SSIM: %.4f' % (NEWLINE # valing_results['psnr'], valing_results['ssim']))NEWLINENEWLINE val_images.extend(NEWLINE [display_transform()(val_hr_restore.squeeze(0)), display_transform()(hr.data.cpu().squeeze(0)),NEWLINE display_transform()(sr.data.cpu().squeeze(0))]) # bicubic, gt, srNEWLINE print('PSNR: %.4f dB SSIM: %.4f' % (valing_results['psnr'], valing_results['ssim']))NEWLINE val_images = torch.stack(val_images)NEWLINE val_images = torch.chunk(val_images, val_images.size(0) // 15)NEWLINE val_save_bar = tqdm(val_images)NEWLINE index = 1NEWLINE print('[saving training results]')NEWLINE for image in val_save_bar:NEWLINE image = utils.make_grid(image, nrow=3, padding=5)NEWLINE utils.save_image(image, out_path + 'epoch_%d_index_%d.png' % (epoch, index), padding=5)NEWLINE index += 1NEWLINENEWLINE # save model parametersNEWLINE torch.save(netG.state_dict(), 'epochs/netG_epoch_%d_%d.pth' % (UPSCALE_FACTOR, epoch))NEWLINE torch.save(netD.state_dict(), 'epochs/netD_epoch_%d_%d.pth' % (UPSCALE_FACTOR, epoch))NEWLINE # save loss\scores\psnr\ssimNEWLINE results['d_loss'].append(running_results['d_loss'] / running_results['batch_sizes'])NEWLINE results['g_loss'].append(running_results['g_loss'] / running_results['batch_sizes'])NEWLINE results['d_score'].append(running_results['d_score'] / running_results['batch_sizes'])NEWLINE results['g_score'].append(running_results['g_score'] / running_results['batch_sizes'])NEWLINE results['psnr'].append(valing_results['psnr'])NEWLINE results['ssim'].append(valing_results['ssim'])NEWLINENEWLINE writer.add_scalar('VAL/psnr', valing_results['psnr'], epoch)NEWLINE writer.add_scalar('VAL/ssim', valing_results['ssim'], epoch)NEWLINE writer.add_scalar("loss/G_loss", running_results['g_loss'] / running_results['batch_sizes'], epoch)NEWLINE writer.add_scalar("loss/D_loss", running_results['d_loss'] / running_results['batch_sizes'], epoch)NEWLINENEWLINE writer.flush()NEWLINE writer.close()NEWLINE end = time.time()NEWLINE print('time elapsed: ', end - start)NEWLINE # coding=utf-8NEWLINE# Copyright 2020 The HuggingFace NLP Authors.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE""" BLEU metric. """NEWLINENEWLINEimport nlpNEWLINENEWLINEfrom .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.pyNEWLINENEWLINENEWLINE_CITATION = """\NEWLINE@INPROCEEDINGS{Papineni02bleu:a,NEWLINE author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},NEWLINE title = {BLEU: a Method for Automatic Evaluation of Machine Translation},NEWLINE booktitle = {},NEWLINE year = {2002},NEWLINE pages = {311--318}NEWLINE}NEWLINE@inproceedings{lin-och-2004-orange,NEWLINE title = "{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation",NEWLINE author = "Lin, Chin-Yew andNEWLINE Och, Franz Josef",NEWLINE booktitle = "{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics",NEWLINE month = "aug 23{--}aug 27",NEWLINE year = "2004",NEWLINE address = "Geneva, Switzerland",NEWLINE publisher = "COLING",NEWLINE url = "https://www.aclweb.org/anthology/C04-1072",NEWLINE pages = "501--507",NEWLINE}NEWLINE"""NEWLINENEWLINE_DESCRIPTION = """\NEWLINEBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.NEWLINEQuality is considered to be the correspondence between a machine's output and that of a human: "the closer a machine translation is to a professional human translation,NEWLINEthe better it is" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, andNEWLINEremains one of the most popular automated and inexpensive metrics.NEWLINENEWLINEScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.NEWLINEThose scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctnessNEWLINEare not taken into account[citation needed].NEWLINENEWLINEBLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1NEWLINErepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of theNEWLINEreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additionalNEWLINEreference translations will increase the BLEU score.NEWLINE"""NEWLINENEWLINE_KWARGS_DESCRIPTION = """NEWLINEComputes BLEU score of translated segments against one or more references.NEWLINEArgs:NEWLINE predictions: list of translations to score.NEWLINE Each translation should be tokenized into a list of tokens.NEWLINE references: list of lists of references for each translation.NEWLINE Each reference should be tokenized into a list of tokens.NEWLINE max_order: Maximum n-gram order to use when computing BLEU score.NEWLINE smooth: Whether or not to apply Lin et al. 2004 smoothing.NEWLINEReturns:NEWLINE 'bleu': bleu score,NEWLINE 'precisions': geometric mean of n-gram precisions,NEWLINE 'brevity_penalty': brevity penalty,NEWLINE 'length_ratio': ratio of lengths,NEWLINE 'translation_length': translation_length,NEWLINE 'reference_length': reference_lengthNEWLINE"""NEWLINENEWLINEclass Bleu(nlp.Metric):NEWLINE def _info(self):NEWLINE return nlp.MetricInfo(NEWLINE description=_DESCRIPTION,NEWLINE citation=_CITATION,NEWLINE inputs_description=_KWARGS_DESCRIPTION,NEWLINE features=nlp.Features({NEWLINE 'predictions': nlp.Sequence(nlp.Value('string', id='token'), id='sequence'),NEWLINE 'references': nlp.Sequence(nlp.Sequence(nlp.Value('string', id='token'), id='sequence'), id='references'),NEWLINE }),NEWLINE codebase_urls=["https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py"],NEWLINE reference_urls=["https://en.wikipedia.org/wiki/BLEU",NEWLINE "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213"]NEWLINE )NEWLINENEWLINE def _compute(self, predictions, references, max_order=4, smooth=False):NEWLINE score = compute_bleu(reference_corpus=references, translation_corpus=predictions, max_order=max_order, smooth=smooth)NEWLINE (bleu, precisions, bp, ratio, translation_length, reference_length) = scoreNEWLINE return {'bleu': bleu,NEWLINE 'precisions': precisions,NEWLINE 'brevity_penalty': bp,NEWLINE 'length_ratio': ratio,NEWLINE 'translation_length': translation_length,NEWLINE 'reference_length': reference_length}NEWLINE # Copyright 2020 Google LLCNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# https://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE""" Helper functions to create test resources.NEWLINENEWLINE"""NEWLINEfrom vm_network_migration_end_to_end_tests.utils import *NEWLINENEWLINENEWLINEclass TestResourceCreator:NEWLINE def __init__(self, google_api_interface):NEWLINE self.google_api_interface = google_api_interfaceNEWLINE self.legacy_network_name = 'end-to-end-test-legacy-network'NEWLINE self.network_name = 'end-to-end-test-vpc-network'NEWLINE self.subnetwork_name = 'end-to-end-test-subnet-network'NEWLINE try:NEWLINE self.legacy_network_selfLink = \NEWLINE self.google_api_interface.get_network(self.legacy_network_name)[NEWLINE 'selfLink']NEWLINE except:NEWLINE self.legacy_network_selfLink = \NEWLINE self.google_api_interface.create_legacy_network(NEWLINE 'end-to-end-test-legacy-network')['targetLink']NEWLINE try:NEWLINE self.network_selfLink = \NEWLINE self.google_api_interface.get_network(self.network_name)[NEWLINE 'selfLink']NEWLINE except:NEWLINE self.network_selfLink = self.google_api_interface.create_non_auto_network(NEWLINE self.network_name)NEWLINE try:NEWLINE self.subnetwork_selfLink = \NEWLINE self.google_api_interface.get_subnetwork(self.subnetwork_name)[NEWLINE 'selfLink']NEWLINE except:NEWLINE self.subnetwork_selfLink = self.google_api_interface.create_subnetwork_using_random_ip_range(NEWLINE self.subnetwork_name, self.network_selfLink)['targetLink']NEWLINE print('Created subnetwork: ', self.subnetwork_selfLink)NEWLINENEWLINE self.legacy_template_name = 'end-to-end-test-legacy-template'NEWLINE try:NEWLINE self.legacy_instance_template_selfLink = \NEWLINE self.google_api_interface.get_instance_template_body(NEWLINE self.legacy_template_name)['selfLink']NEWLINE except:NEWLINE self.legacy_instance_template_selfLink = \NEWLINE self.create_instance_template(NEWLINE 'sample_instance_template.json',NEWLINE 'end-to-end-test-legacy-template')[NEWLINE 'targetLink']NEWLINENEWLINE self.healthcheck_name = 'end-to-end-test-tcp-80-health-check'NEWLINE try:NEWLINE self.tcp_80_health_check_selfLink = \NEWLINE self.google_api_interface.get_healthcheck(NEWLINE self.healthcheck_name)[NEWLINE 'selfLink']NEWLINENEWLINE except:NEWLINE self.tcp_80_health_check_selfLink = \NEWLINE self.create_tcp_80_health_check(self.healthcheck_name)[NEWLINE 'targetLink']NEWLINENEWLINE def create_tcp_80_health_check(self, healthcheck_name):NEWLINENEWLINE config = {NEWLINE "name": healthcheck_name,NEWLINE "description": "",NEWLINE "checkIntervalSec": 5,NEWLINE "timeoutSec": 5,NEWLINE "unhealthyThreshold": 2,NEWLINE "healthyThreshold": 2,NEWLINE "type": "TCP",NEWLINE "tcpHealthCheck": {NEWLINE "port": 80,NEWLINE "proxyHeader": "NONE"NEWLINE },NEWLINE "kind": "compute#healthCheck"NEWLINE }NEWLINE return self.google_api_interface.add_healthcheck(config)NEWLINENEWLINE def create_instance_template(self, instance_template_file,NEWLINE instance_template_name):NEWLINE config = read_json_file(NEWLINE instance_template_file)NEWLINE config['name'] = instance_template_nameNEWLINE config['properties']['networkInterfaces'][0][NEWLINE 'network'] = self.legacy_network_selfLinkNEWLINENEWLINE return self.google_api_interface.create_instance_template(config)NEWLINENEWLINE def add_additional_disk_to_instance(self, instance_name, disk_name,NEWLINE disk_file):NEWLINE disk_config = read_json_file(NEWLINE disk_file)NEWLINE disk_config['name'] = disk_nameNEWLINE disk_selfLink = self.google_api_interface.create_disk(disk_config)[NEWLINE 'targetLink']NEWLINE self.google_api_interface.attach_disk(instance_name, disk_selfLink)NEWLINENEWLINE def create_instance_using_template(self, instance_name, template_selfLink):NEWLINE instance_configs = {NEWLINE "name": instance_nameNEWLINE }NEWLINE return self.google_api_interface.create_instance(instance_configs,NEWLINE template_selfLink)NEWLINENEWLINE def create_unmanaged_instance_group(self,NEWLINE unmanaged_instance_group_name,NEWLINE list_of_instance_names):NEWLINE unmanaged_instance_group_configs = {NEWLINE "name": unmanaged_instance_group_name,NEWLINE "description": ""NEWLINE }NEWLINENEWLINE return self.google_api_interface.create_unmanaged_instance_group_with_instances(NEWLINE unmanaged_instance_group_configs, list_of_instance_names)NEWLINENEWLINE def create_regional_managed_instance_group(self, instance_template_selfLink,NEWLINE group_name,NEWLINE managed_instance_group_file_name,NEWLINE autoscaler_file_name=None):NEWLINE managed_instance_group_configs = read_json_file(NEWLINE managed_instance_group_file_name)NEWLINENEWLINE managed_instance_group_configs[NEWLINE 'instanceTemplate'] = instance_template_selfLinkNEWLINE managed_instance_group_configs['name'] = group_nameNEWLINE operation = self.google_api_interface.create_multi_zone_managed_instance_group(NEWLINE managed_instance_group_configs)NEWLINE instance_group_selfLink = operation['targetLink']NEWLINE if autoscaler_file_name != None:NEWLINE autoscaler_configs = read_json_file(autoscaler_file_name)NEWLINE autoscaler_configs['target'] = instance_group_selfLinkNEWLINE autoscaler_configs['name'] = group_nameNEWLINE self.google_api_interface.create_region_autoscaler(NEWLINE autoscaler_configs)NEWLINE return operationNEWLINENEWLINE def create_target_pool_with_health_check(self, target_pool_file_name,NEWLINE target_pool_name,NEWLINE instance_group_name_list,NEWLINE instance_selfLinks,NEWLINE health_check_selfLink=None):NEWLINE target_pool_configs = read_json_file(target_pool_file_name)NEWLINE target_pool_configs['name'] = target_pool_nameNEWLINE if health_check_selfLink != None:NEWLINE target_pool_configs['healthChecks'] = [health_check_selfLink]NEWLINE operation = \NEWLINE self.google_api_interface.create_target_pool(target_pool_configs)NEWLINE target_pool_selfLink = operation['targetLink']NEWLINE for regional_instance_group in instance_group_name_list:NEWLINE self.google_api_interface.regional_instance_group_set_target_pool(NEWLINE regional_instance_group,NEWLINE target_pool_selfLink)NEWLINE for instance_selfLink in instance_selfLinks:NEWLINE self.google_api_interface.add_instances_to_target_pool(NEWLINE target_pool_configs[NEWLINE 'name'],NEWLINE instance_selfLink)NEWLINE return operationNEWLINENEWLINE def create_global_backend_service(self, backend_service_file_name,NEWLINE backend_service_name,NEWLINE instance_group_selfLinks):NEWLINE backend_service_configs = read_json_file(backend_service_file_name)NEWLINE backend_service_configs['name'] = backend_service_nameNEWLINE backend_service_configs['healthChecks'] = [NEWLINE self.tcp_80_health_check_selfLink]NEWLINE for instance_group_selfLink in instance_group_selfLinks:NEWLINE backend_service_configs['backends'].append({NEWLINE "description": "",NEWLINE "group": instance_group_selfLink,NEWLINE "balancingMode": "UTILIZATION",NEWLINE "maxUtilization": 0.8,NEWLINE "capacityScaler": 1NEWLINE })NEWLINE return self.google_api_interface.create_global_backend_service(NEWLINE backend_service_configs)NEWLINENEWLINE def create_regional_backend_service(self, backend_service_file_name,NEWLINE backend_service_name,NEWLINE instance_group_selfLinks):NEWLINE backend_service_configs = read_json_file(backend_service_file_name)NEWLINE backend_service_configs['name'] = backend_service_nameNEWLINE backend_service_configs['healthChecks'] = [NEWLINE self.tcp_80_health_check_selfLink]NEWLINE for instance_group_selfLink in instance_group_selfLinks:NEWLINE backend_service_configs['backends'].append({NEWLINE "description": "",NEWLINE "group": instance_group_selfLink,NEWLINE "balancingMode": "CONNECTION"NEWLINE })NEWLINE backend_service_configs['network'] = self.legacy_network_selfLinkNEWLINE return self.google_api_interface.create_regional_backend_service(NEWLINE backend_service_configs)NEWLINENEWLINE def create_urlmapping(self, url_mapping_name, backend_service_selfLink):NEWLINE url_configs = {NEWLINE "name": url_mapping_name,NEWLINE "defaultService": backend_service_selfLink,NEWLINE "kind": "compute#urlMap"NEWLINE }NEWLINE return self.google_api_interface.create_urlmapping(url_configs)NEWLINENEWLINE def create_urlmapping_using_two_backend_service(self, url_mapping_name,NEWLINE backend_service_selfLinks):NEWLINE url_configs = {NEWLINE "name": url_mapping_name,NEWLINE "hostRules": [NEWLINE {NEWLINE "hosts": [NEWLINE "www.example.come"NEWLINE ],NEWLINE "pathMatcher": "path-matcher-1"NEWLINE }NEWLINE ],NEWLINE "pathMatchers": [NEWLINE {NEWLINE "name": "path-matcher-1",NEWLINE "defaultService": backend_service_selfLinks[1],NEWLINE "pathRules": [NEWLINE {NEWLINE "service": backend_service_selfLinks[1],NEWLINE "paths": [NEWLINE "/test/*"NEWLINE ]NEWLINE }NEWLINE ]NEWLINE }NEWLINE ],NEWLINE "defaultService": backend_service_selfLinks[0],NEWLINE }NEWLINE return self.google_api_interface.create_urlmapping(url_configs)NEWLINENEWLINE def create_http_target_proxy(self, target_proxy_name, urlmapping_selfLink):NEWLINE return self.google_api_interface.create_http_proxy(target_proxy_name,NEWLINE urlmapping_selfLink)NEWLINENEWLINE def create_global_forwarding_rule_with_target(self,NEWLINE forwarding_rule_file_name,NEWLINE forwarding_rule_name,NEWLINE target_selfLink,NEWLINE network_selfLink=None):NEWLINE forwarding_rule_configs = read_json_file(forwarding_rule_file_name)NEWLINE forwarding_rule_configs['name'] = forwarding_rule_nameNEWLINE forwarding_rule_configs['target'] = target_selfLinkNEWLINE if network_selfLink != None:NEWLINE forwarding_rule_configs['network'] = network_selfLinkNEWLINE return self.google_api_interface.create_global_forwarding_rule(NEWLINE forwarding_rule_configs)NEWLINENEWLINE def create_global_forwarding_rule_with_backend_service(self,NEWLINE forwarding_rule_file_name,NEWLINE forwarding_rule_name,NEWLINE backend_service_selfLink):NEWLINE forwarding_rule_configs = read_json_file(forwarding_rule_file_name)NEWLINE forwarding_rule_configs['name'] = forwarding_rule_nameNEWLINE forwarding_rule_configs['backendService'] = backend_service_selfLinkNEWLINE return self.google_api_interface.create_global_forwarding_rule(NEWLINE forwarding_rule_configs)NEWLINENEWLINE def create_regional_forwarding_rule_with_target(self,NEWLINE forwarding_rule_file_name,NEWLINE forwarding_rule_name,NEWLINE target_selfLink):NEWLINE forwarding_rule_configs = read_json_file(forwarding_rule_file_name)NEWLINE forwarding_rule_configs['name'] = forwarding_rule_nameNEWLINE forwarding_rule_configs['target'] = target_selfLinkNEWLINE if 'backendService' in forwarding_rule_configs:NEWLINE del forwarding_rule_configs['backendService']NEWLINE forwarding_rule_configs['network'] = self.legacy_network_selfLinkNEWLINE return self.google_api_interface.create_regional_forwarding_rule(NEWLINE forwarding_rule_configs)NEWLINENEWLINE def create_regional_forwarding_rule_with_backend_service(self,NEWLINE forwarding_rule_file_name,NEWLINE forwarding_rule_name,NEWLINE backend_service_selfLink):NEWLINE forwarding_rule_configs = read_json_file(forwarding_rule_file_name)NEWLINE forwarding_rule_configs['name'] = forwarding_rule_nameNEWLINE forwarding_rule_configs['backendService'] = backend_service_selfLinkNEWLINE forwarding_rule_configs['network'] = self.legacy_network_selfLinkNEWLINE return self.google_api_interface.create_regional_forwarding_rule(NEWLINE forwarding_rule_configs)NEWLINENEWLINE def create_a_target_instance(self, target_instance_name, instance_selfLink):NEWLINE target_instance_configs = {NEWLINE "name": target_instance_name,NEWLINE "description": "",NEWLINE "natPolicy": "NO_NAT",NEWLINE "instance": instance_selfLinkNEWLINE }NEWLINE return self.google_api_interface.create_target_instance(NEWLINE target_instance_configs)NEWLINE # GENERATED BY KOMAND SDK - DO NOT EDITNEWLINEfrom .action import SketchifyNEWLINE from django_asservio_core.models import (NEWLINE CodeDictionary, NameDictionary,NEWLINE Dictionary, DescriptionDictionaryNEWLINE)NEWLINENEWLINENEWLINEclass Code(CodeDictionary):NEWLINE """Code dictionary."""NEWLINE passNEWLINENEWLINENEWLINEclass Name(NameDictionary):NEWLINE """Name dictionary."""NEWLINE passNEWLINENEWLINENEWLINEclass Description(DescriptionDictionary):NEWLINE """Description dictionary."""NEWLINE passNEWLINENEWLINENEWLINEclass Info(Dictionary):NEWLINE """Regular dictionary."""NEWLINE passNEWLINE # This file is part of the Astrometry.net suite.NEWLINE# Licensed under a 3-clause BSD style license - see LICENSENEWLINENEWLINE# Generates FITS tables from CSV lists of OpenNGC entries and names.NEWLINENEWLINEfrom __future__ import print_functionNEWLINENEWLINEimport csvNEWLINENEWLINEfrom astrometry.util.fits import fits_tableNEWLINEimport numpy as npNEWLINENEWLINENEWLINEdef convert_openngc_entries():NEWLINE entries = []NEWLINENEWLINE with open('openngc-entries.csv') as f:NEWLINE for is_ngc, num, ra, dec, size in csv.reader(f, delimiter=';'):NEWLINE is_ngc = (is_ngc == '1')NEWLINE num = int(num)NEWLINE ra = float(ra) if ra else 0.0NEWLINE dec = float(dec) if dec else 0.0NEWLINENEWLINE # Convert from diameter in arcmins to radius in degrees.NEWLINE radius = float(size) / (2.0 * 60.0) if size else 0.0NEWLINENEWLINE entries.append({NEWLINE 'is_ngc': is_ngc,NEWLINE 'ra': ra,NEWLINE 'dec': dec,NEWLINE 'radius': radius,NEWLINE 'num': num,NEWLINE })NEWLINENEWLINE T = fits_table()NEWLINE for key in ['is_ngc', 'ra', 'dec', 'radius', 'num']:NEWLINE T.set(key, [x[key] for x in entries])NEWLINENEWLINE T.to_np_arrays()NEWLINENEWLINE T.name = np.array(['NGC %i' % n if isngc else 'IC %i' % nNEWLINE for n, isngc in zip(T.num, T.is_ngc)])NEWLINENEWLINE for key in ['ra', 'dec', 'radius']:NEWLINE T.set(key, T.get(key).astype(np.float32))NEWLINE T.num = T.num.astype(np.int16)NEWLINENEWLINE units_dict = {NEWLINE 'ra': 'deg',NEWLINE 'dec': 'deg',NEWLINE 'radius': 'deg',NEWLINE }NEWLINENEWLINE NGC = T[T.is_ngc]NEWLINE NGC.rename('num', 'ngcnum')NEWLINE NGC.delete_column('is_ngc')NEWLINE units = [units_dict.get(c, '') for c in NGC.get_columns()]NEWLINE NGC.writeto('openngc-ngc.fits', units=units)NEWLINENEWLINE IC = T[np.logical_not(T.is_ngc)]NEWLINE IC.rename('num', 'icnum')NEWLINE IC.delete_column('is_ngc')NEWLINE units = [units_dict.get(c, '') for c in IC.get_columns()]NEWLINE IC.writeto('openngc-ic.fits', units=units)NEWLINENEWLINENEWLINEdef convert_openngc_names():NEWLINE names = []NEWLINENEWLINE with open('openngc-names.csv') as f:NEWLINE for is_ngc, num, name in csv.reader(f, delimiter=';'):NEWLINENEWLINE is_ngc = bool(is_ngc)NEWLINENEWLINE num = int(num)NEWLINENEWLINE identifier = '%s%d' % ('' if is_ngc else 'I', num)NEWLINENEWLINE names.append({NEWLINE 'Object': name,NEWLINE 'Name': identifier,NEWLINE })NEWLINENEWLINE T = fits_table()NEWLINE for key in ['Object', 'Name']:NEWLINE T.set(key, [x[key] for x in names])NEWLINE T.writeto('openngc-names.fits')NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE convert_openngc_entries()NEWLINE convert_openngc_names()NEWLINE import reNEWLINENEWLINE_TESTS = [NEWLINE "//REL/RELIDO",NEWLINE "TS//SI-G/TK//RS/OC/NF",NEWLINE "TS//SI-ABC-DEF//OC/NF",NEWLINE "TS//SI-G ABCD EFGH-XYZ//OC/NF",NEWLINE "TS//ANB/SI/TK/XNB//NF",NEWLINE "TS//SAR-BP-123/CA-XYZ YYY//NF",NEWLINE "TS//RD-CNWDI//NF",NEWLINE "S//FRD-SIGMA 14 18//REL",NEWLINE "//CTS//BOHEMIA",NEWLINE "//DEU S//NF",NEWLINE "//NS//ATOMAL//OC",NEWLINE "//JOINT S//REL",NEWLINE "TS//FGI DEU GBR//REL TO USA, DEU, GBR",NEWLINE "//FGI S//NF",NEWLINE "S//NF",NEWLINE "S//NF/PR",NEWLINE "U//SSI",NEWLINE]NEWLINENEWLINE_PATTERN = "^(U?|C|(S|TS)?(\/\/(((\w|\-)+)(\s(\w|\-)+)*)((\/(\w|\-)+)(\s(\w|\-)+)*)*)?)\/\/((((\w|\-)+)|(REL( TO ((\w|\-)+)(,\s?((\w|\-)+))*)?))((\/((\w|\-)+)|(REL( TO ((\w|\-)+)(,(\w|\-)+)*)?))*))$"NEWLINENEWLINEdef main():NEWLINE prog = re.compile(_PATTERN)NEWLINE for s in _TESTS:NEWLINE result = prog.match(s)NEWLINE print(s + " " + str(result))NEWLINENEWLINEif __name__ == '__main__':NEWLINE main()NEWLINENEWLINENEWLINE #!/usr/bin/env pythonNEWLINE#-*- coding:utf-8 -*-NEWLINE# Author: Donny You(youansheng@gmail.com)NEWLINE# Evaluation of cityscape.NEWLINENEWLINENEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import print_functionNEWLINENEWLINEimport fnmatchNEWLINEimport argparseNEWLINEimport platformNEWLINEimport sysNEWLINENEWLINEtry:NEWLINE from itertools import izipNEWLINEexcept ImportError:NEWLINE izip = zipNEWLINENEWLINE# Cityscapes importsNEWLINEfrom val.scripts.seg.cityscape.evaluation.csHelpers import *NEWLINENEWLINE# C SupportNEWLINE# Enable the cython support for faster evaluation, this is necessary for speeding up your model resultsNEWLINE# Only tested for Ubuntu 64bit OSNEWLINECSUPPORT = TrueNEWLINE# Check if C-Support is available for better performanceNEWLINEif CSUPPORT:NEWLINE try:NEWLINE import val.scripts.seg.cityscape.evaluation.addToConfusionMatrix as addToConfusionMatrixNEWLINE except:NEWLINE CSUPPORT = FalseNEWLINENEWLINENEWLINE# A class to collect all bunch of dataNEWLINEclass CArgs(object):NEWLINE def __init__(self, data_path=None, out_path=None, predict_path=None):NEWLINE # Where to look for Cityscapes, note that data path is equal to gt pathNEWLINE if 'CITYSCAPES_DATASET' in os.environ:NEWLINE self.cityscapesPath = os.environ['CITYSCAPES_DATASET']NEWLINE else:NEWLINE self.cityscapesPath = os.path.join(data_path)NEWLINENEWLINE if 'CITYSCAPES_EXPORT_DIR' in os.environ:NEWLINE export_dir = os.environ['CITYSCAPES_EXPORT_DIR']NEWLINE if not os.path.isdir(export_dir):NEWLINE raise ValueError("CITYSCAPES_EXPORT_DIR {} is not a directory".format(export_dir))NEWLINE self.exportFile = "{}/resultPixelLevelSemanticLabeling.json".format(export_dir)NEWLINE else:NEWLINE self.exportFile = os.path.join(out_path, "evaluationResults", "resultPixelLevelSemanticLabeling.json")NEWLINE # Parameters that should be modified by userNEWLINE self.groundTruthSearch = os.path.join( self.cityscapesPath, "*", "*_gtFine_labelIds.png" )NEWLINENEWLINE # Remaining paramsNEWLINE self.evalInstLevelScore = TrueNEWLINE self.evalPixelAccuracy = FalseNEWLINE self.evalLabels = []NEWLINE self.printRow = 5NEWLINE self.normalized = TrueNEWLINE self.colorized = hasattr(sys.stderr, "isatty") and sys.stderr.isatty() and platform.system()=='Linux'NEWLINE self.bold = colors.BOLD if self.colorized else ""NEWLINE self.nocol = colors.ENDC if self.colorized else ""NEWLINE self.JSONOutput = TrueNEWLINE self.quiet = FalseNEWLINENEWLINE self.avgClassSize = {NEWLINE "bicycle" : 4672.3249222261 ,NEWLINE "caravan" : 36771.8241758242 ,NEWLINE "motorcycle" : 6298.7200839748 ,NEWLINE "rider" : 3930.4788056518 ,NEWLINE "bus" : 35732.1511111111 ,NEWLINE "train" : 67583.7075812274 ,NEWLINE "car" : 12794.0202738185 ,NEWLINE "person" : 3462.4756337644 ,NEWLINE "truck" : 27855.1264367816 ,NEWLINE "trailer" : 16926.9763313609 ,NEWLINE }NEWLINENEWLINE # store some parameters for finding predictions in the args variableNEWLINE # the values are filled when the method getPrediction is first calledNEWLINE self.predictionPath = predict_pathNEWLINE self.predictionWalk = NoneNEWLINENEWLINENEWLINE## method partNEWLINEdef getPrediction( args, groundTruthFile ):NEWLINE # determine the prediction path, if the method is first calledNEWLINE if not args.predictionPath:NEWLINE rootPath = NoneNEWLINE if 'CITYSCAPES_RESULTS' in os.environ:NEWLINE rootPath = os.environ['CITYSCAPES_RESULTS']NEWLINE elif 'CITYSCAPES_DATASET' in os.environ:NEWLINE rootPath = os.path.join( os.environ['CITYSCAPES_DATASET'] , "results" )NEWLINE else:NEWLINE rootPath = os.path.join(os.path.dirname(os.path.realpath(__file__)),'..','..','results')NEWLINENEWLINE if not os.path.isdir(rootPath):NEWLINE printError("Could not find a result root folder. Please read the instructions of this method.")NEWLINENEWLINE args.predictionPath = rootPathNEWLINENEWLINE # walk the prediction path, if not happened yetNEWLINE if not args.predictionWalk:NEWLINE walk = []NEWLINE for root, dirnames, filenames in os.walk(args.predictionPath):NEWLINE walk.append( (root,filenames) )NEWLINE args.predictionWalk = walkNEWLINENEWLINE csFile = getCsFileInfo(groundTruthFile)NEWLINE filePattern = "{}_{}_{}*.png".format( csFile.city , csFile.sequenceNb , csFile.frameNb )NEWLINENEWLINE predictionFile = NoneNEWLINE for root, filenames in args.predictionWalk:NEWLINE for filename in fnmatch.filter(filenames, filePattern):NEWLINE if not predictionFile:NEWLINE predictionFile = os.path.join(root, filename)NEWLINE else:NEWLINE printError("Found multiple predictions for ground truth {}".format(groundTruthFile))NEWLINENEWLINE if not predictionFile:NEWLINE printError("Found no prediction for ground truth {}".format(groundTruthFile))NEWLINENEWLINE return predictionFileNEWLINENEWLINE# Generate empty confusion matrix and create list of relevant labelsNEWLINEdef generateMatrix(args):NEWLINE args.evalLabels = []NEWLINE for label in labels:NEWLINE if (label.id < 0):NEWLINE continueNEWLINE # we append all found labels, regardless of being ignoredNEWLINE args.evalLabels.append(label.id)NEWLINE maxId = max(args.evalLabels)NEWLINE # We use longlong type to be sure that there are no overflowsNEWLINE return np.zeros(shape=(maxId + 1, maxId + 1), dtype=np.ulonglong)NEWLINENEWLINENEWLINEdef generateInstanceStats(args):NEWLINE instanceStats = {}NEWLINE instanceStats["classes"] = {}NEWLINE instanceStats["categories"] = {}NEWLINE for label in labels:NEWLINE if label.hasInstances and not label.ignoreInEval:NEWLINE instanceStats["classes"][label.name] = {}NEWLINE instanceStats["classes"][label.name]["tp"] = 0.0NEWLINE instanceStats["classes"][label.name]["tpWeighted"] = 0.0NEWLINE instanceStats["classes"][label.name]["fn"] = 0.0NEWLINE instanceStats["classes"][label.name]["fnWeighted"] = 0.0NEWLINE for category in category2labels:NEWLINE labelIds = []NEWLINE allInstances = TrueNEWLINE for label in category2labels[category]:NEWLINE if label.id < 0:NEWLINE continueNEWLINE if not label.hasInstances:NEWLINE allInstances = FalseNEWLINE breakNEWLINE labelIds.append(label.id)NEWLINE if not allInstances:NEWLINE continueNEWLINENEWLINE instanceStats["categories"][category] = {}NEWLINE instanceStats["categories"][category]["tp"] = 0.0NEWLINE instanceStats["categories"][category]["tpWeighted"] = 0.0NEWLINE instanceStats["categories"][category]["fn"] = 0.0NEWLINE instanceStats["categories"][category]["fnWeighted"] = 0.0NEWLINE instanceStats["categories"][category]["labelIds"] = labelIdsNEWLINENEWLINE return instanceStatsNEWLINENEWLINENEWLINE# Get absolute or normalized value from field in confusion matrix.NEWLINEdef getMatrixFieldValue(confMatrix, i, j, args):NEWLINE if args.normalized:NEWLINE rowSum = confMatrix[i].sum()NEWLINE if (rowSum == 0):NEWLINE return float('nan')NEWLINE return float(confMatrix[i][j]) / rowSumNEWLINE else:NEWLINE return confMatrix[i][j]NEWLINENEWLINENEWLINE# Calculate and return IOU score for a particular labelNEWLINEdef getIouScoreForLabel(label, confMatrix, args):NEWLINE if id2label[label].ignoreInEval:NEWLINE return float('nan')NEWLINENEWLINE # the number of true positive pixels for this labelNEWLINE # the entry on the diagonal of the confusion matrixNEWLINE tp = np.longlong(confMatrix[label, label])NEWLINENEWLINE # the number of false negative pixels for this labelNEWLINE # the row sum of the matching row in the confusion matrixNEWLINE # minus the diagonal entryNEWLINE fn = np.longlong(confMatrix[label, :].sum()) - tpNEWLINENEWLINE # the number of false positive pixels for this labelsNEWLINE # Only pixels that are not on a pixel with ground truth label that is ignoredNEWLINE # The column sum of the corresponding column in the confusion matrixNEWLINE # without the ignored rows and without the actual label of interestNEWLINE notIgnored = [l for l in args.evalLabels if not id2label[l].ignoreInEval and not l == label]NEWLINE fp = np.longlong(confMatrix[notIgnored, label].sum())NEWLINENEWLINE # the denominator of the IOU scoreNEWLINE denom = (tp + fp + fn)NEWLINE if denom == 0:NEWLINE return float('nan')NEWLINENEWLINE # return IOUNEWLINE return float(tp) / denomNEWLINENEWLINENEWLINE# Calculate and return IOU score for a particular labelNEWLINEdef getInstanceIouScoreForLabel(label, confMatrix, instStats, args):NEWLINE if id2label[label].ignoreInEval:NEWLINE return float('nan')NEWLINENEWLINE labelName = id2label[label].nameNEWLINE if not labelName in instStats["classes"]:NEWLINE return float('nan')NEWLINENEWLINE tp = instStats["classes"][labelName]["tpWeighted"]NEWLINE fn = instStats["classes"][labelName]["fnWeighted"]NEWLINE # false postives computed as aboveNEWLINE notIgnored = [l for l in args.evalLabels if not id2label[l].ignoreInEval and not l == label]NEWLINE fp = np.longlong(confMatrix[notIgnored, label].sum())NEWLINENEWLINE # the denominator of the IOU scoreNEWLINE denom = (tp + fp + fn)NEWLINE if denom == 0:NEWLINE return float('nan')NEWLINENEWLINE # return IOUNEWLINE return float(tp) / denomNEWLINENEWLINENEWLINE# Calculate prior for a particular class id.NEWLINEdef getPrior(label, confMatrix):NEWLINE return float(confMatrix[label, :].sum()) / confMatrix.sum()NEWLINENEWLINENEWLINE# Get average of scores.NEWLINE# Only computes the average over valid entries.NEWLINEdef getScoreAverage(scoreList, args):NEWLINE validScores = 0NEWLINE scoreSum = 0.0NEWLINE for score in scoreList:NEWLINE if not math.isnan(scoreList[score]):NEWLINE validScores += 1NEWLINE scoreSum += scoreList[score]NEWLINE if validScores == 0:NEWLINE return float('nan')NEWLINE return scoreSum / validScoresNEWLINENEWLINENEWLINE# Calculate and return IOU score for a particular categoryNEWLINEdef getIouScoreForCategory(category, confMatrix, args):NEWLINE # All labels in this categoryNEWLINE labels = category2labels[category]NEWLINE # The IDs of all valid labels in this categoryNEWLINE labelIds = [label.id for label in labels if not label.ignoreInEval and label.id in args.evalLabels]NEWLINE # If there are no valid labels, then return NaNNEWLINE if not labelIds:NEWLINE return float('nan')NEWLINENEWLINE # the number of true positive pixels for this categoryNEWLINE # this is the sum of all entries in the confusion matrixNEWLINE # where row and column belong to a label ID of this categoryNEWLINE tp = np.longlong(confMatrix[labelIds, :][:, labelIds].sum())NEWLINENEWLINE # the number of false negative pixels for this categoryNEWLINE # that is the sum of all rows of labels within this categoryNEWLINE # minus the number of true positive pixelsNEWLINE fn = np.longlong(confMatrix[labelIds, :].sum()) - tpNEWLINENEWLINE # the number of false positive pixels for this categoryNEWLINE # we count the column sum of all labels within this categoryNEWLINE # while skipping the rows of ignored labels and of labels within this categoryNEWLINE notIgnoredAndNotInCategory = [l for l in args.evalLabels ifNEWLINE not id2label[l].ignoreInEval and id2label[l].category != category]NEWLINE fp = np.longlong(confMatrix[notIgnoredAndNotInCategory, :][:, labelIds].sum())NEWLINENEWLINE # the denominator of the IOU scoreNEWLINE denom = (tp + fp + fn)NEWLINE if denom == 0:NEWLINE return float('nan')NEWLINENEWLINE # return IOUNEWLINE return float(tp) / denomNEWLINENEWLINENEWLINE# Calculate and return IOU score for a particular categoryNEWLINEdef getInstanceIouScoreForCategory(category, confMatrix, instStats, args):NEWLINE if not category in instStats["categories"]:NEWLINE return float('nan')NEWLINE labelIds = instStats["categories"][category]["labelIds"]NEWLINENEWLINE tp = instStats["categories"][category]["tpWeighted"]NEWLINE fn = instStats["categories"][category]["fnWeighted"]NEWLINENEWLINE # the number of false positive pixels for this categoryNEWLINE # same as aboveNEWLINE notIgnoredAndNotInCategory = [l for l in args.evalLabels ifNEWLINE not id2label[l].ignoreInEval and id2label[l].category != category]NEWLINE fp = np.longlong(confMatrix[notIgnoredAndNotInCategory, :][:, labelIds].sum())NEWLINENEWLINE # the denominator of the IOU scoreNEWLINE denom = (tp + fp + fn)NEWLINE if denom == 0:NEWLINE return float('nan')NEWLINENEWLINE # return IOUNEWLINE return float(tp) / denomNEWLINENEWLINENEWLINE# create a dictionary containing all relevant resultsNEWLINEdef createResultDict(confMatrix, classScores, classInstScores, categoryScores, categoryInstScores,NEWLINE perImageStats, args):NEWLINE # write JSON result fileNEWLINE wholeData = {}NEWLINE wholeData["confMatrix"] = confMatrix.tolist()NEWLINE wholeData["priors"] = {}NEWLINE wholeData["labels"] = {}NEWLINE for label in args.evalLabels:NEWLINE wholeData["priors"][id2label[label].name] = getPrior(label, confMatrix)NEWLINE wholeData["labels"][id2label[label].name] = labelNEWLINE wholeData["classScores"] = classScoresNEWLINE wholeData["classInstScores"] = classInstScoresNEWLINE wholeData["categoryScores"] = categoryScoresNEWLINE wholeData["categoryInstScores"] = categoryInstScoresNEWLINE wholeData["averageScoreClasses"] = getScoreAverage(classScores, args)NEWLINE wholeData["averageScoreInstClasses"] = getScoreAverage(classInstScores, args)NEWLINE wholeData["averageScoreCategories"] = getScoreAverage(categoryScores, args)NEWLINE wholeData["averageScoreInstCategories"] = getScoreAverage(categoryInstScores, args)NEWLINENEWLINE if perImageStats:NEWLINE wholeData["perImageScores"] = perImageStatsNEWLINENEWLINE return wholeDataNEWLINENEWLINENEWLINEdef writeJSONFile(wholeData, args):NEWLINE path = os.path.dirname(args.exportFile)NEWLINE ensurePath(path)NEWLINE writeDict2JSON(wholeData, args.exportFile)NEWLINENEWLINENEWLINE# Print confusion matrixNEWLINEdef printConfMatrix(confMatrix, args):NEWLINE # print lineNEWLINE print("\b{text:{fill}>{width}}".format(width=15, fill='-', text=" "), end=' ')NEWLINE for label in args.evalLabels:NEWLINE print("\b{text:{fill}>{width}}".format(width=args.printRow + 2, fill='-', text=" "), end=' ')NEWLINE print("\b{text:{fill}>{width}}".format(width=args.printRow + 3, fill='-', text=" "))NEWLINENEWLINE # print label namesNEWLINE print("\b{text:>{width}} |".format(width=13, text=""), end=' ')NEWLINE for label in args.evalLabels:NEWLINE print("\b{text:^{width}} |".format(width=args.printRow, text=id2label[label].name[0]), end=' ')NEWLINE print("\b{text:>{width}} |".format(width=6, text="Prior"))NEWLINENEWLINE # print lineNEWLINE print("\b{text:{fill}>{width}}".format(width=15, fill='-', text=" "), end=' ')NEWLINE for label in args.evalLabels:NEWLINE print("\b{text:{fill}>{width}}".format(width=args.printRow + 2, fill='-', text=" "), end=' ')NEWLINE print("\b{text:{fill}>{width}}".format(width=args.printRow + 3, fill='-', text=" "))NEWLINENEWLINE # print matrixNEWLINE for x in range(0, confMatrix.shape[0]):NEWLINE if (not x in args.evalLabels):NEWLINE continueNEWLINE # get prior of this labelNEWLINE prior = getPrior(x, confMatrix)NEWLINE # skip if label does not exist in ground truthNEWLINE if prior < 1e-9:NEWLINE continueNEWLINENEWLINE # print nameNEWLINE name = id2label[x].nameNEWLINE if len(name) > 13:NEWLINE name = name[:13]NEWLINE print("\b{text:>{width}} |".format(width=13, text=name), end=' ')NEWLINE # print matrix contentNEWLINE for y in range(0, len(confMatrix[x])):NEWLINE if (not y in args.evalLabels):NEWLINE continueNEWLINE matrixFieldValue = getMatrixFieldValue(confMatrix, x, y, args)NEWLINE print(getColorEntry(matrixFieldValue, args) + "\b{text:>{width}.2f} ".format(width=args.printRow,NEWLINE text=matrixFieldValue) + args.nocol,NEWLINE end=' ')NEWLINE # print priorNEWLINE print(getColorEntry(prior, args) + "\b{text:>{width}.4f} ".format(width=6, text=prior) + args.nocol)NEWLINE # print lineNEWLINE print("\b{text:{fill}>{width}}".format(width=15, fill='-', text=" "), end=' ')NEWLINE for label in args.evalLabels:NEWLINE print("\b{text:{fill}>{width}}".format(width=args.printRow + 2, fill='-', text=" "), end=' ')NEWLINE print("\b{text:{fill}>{width}}".format(width=args.printRow + 3, fill='-', text=" "), end=' ')NEWLINENEWLINENEWLINE# Print intersection-over-union scores for all classes.NEWLINEdef printClassScores(scoreList, instScoreList, args):NEWLINE if (args.quiet):NEWLINE returnNEWLINE print(args.bold + "classes IoU nIoU" + args.nocol)NEWLINE print("--------------------------------")NEWLINE for label in args.evalLabels:NEWLINE if (id2label[label].ignoreInEval):NEWLINE continueNEWLINE labelName = str(id2label[label].name)NEWLINE iouStr = getColorEntry(scoreList[labelName], args) + "{val:>5.3f}".format(NEWLINE val=scoreList[labelName]) + args.nocolNEWLINE niouStr = getColorEntry(instScoreList[labelName], args) + "{val:>5.3f}".format(NEWLINE val=instScoreList[labelName]) + args.nocolNEWLINE print("{:<14}: ".format(labelName) + iouStr + " " + niouStr)NEWLINENEWLINENEWLINE# Print intersection-over-union scores for all categorys.NEWLINEdef printCategoryScores(scoreDict, instScoreDict, args):NEWLINE if (args.quiet):NEWLINE returnNEWLINE print(args.bold + "categories IoU nIoU" + args.nocol)NEWLINE print("--------------------------------")NEWLINE for categoryName in scoreDict:NEWLINE if all(label.ignoreInEval for label in category2labels[categoryName]):NEWLINE continueNEWLINE iouStr = getColorEntry(scoreDict[categoryName], args) + "{val:>5.3f}".format(NEWLINE val=scoreDict[categoryName]) + args.nocolNEWLINE niouStr = getColorEntry(instScoreDict[categoryName], args) + "{val:>5.3f}".format(NEWLINE val=instScoreDict[categoryName]) + args.nocolNEWLINE print("{:<14}: ".format(categoryName) + iouStr + " " + niouStr)NEWLINENEWLINENEWLINEclass EvalPixel():NEWLINE def __init__(self, args, predictionImgList = None, groundTruthImgList = None):NEWLINE self.args = argsNEWLINE self.predictionImgList = predictionImgListNEWLINE self.groundTruthImgList = groundTruthImgListNEWLINE if predictionImgList is None or groundTruthImgList is None:NEWLINE self.groundTruthImgList, self.predictionImgList = self.getDefaultData(self.args)NEWLINENEWLINE # evaluate image in two listsNEWLINE def evaluateImgLists(self,predictionImgList, groundTruthImgList, args):NEWLINE if len(predictionImgList) != len(groundTruthImgList):NEWLINE printError("List of images for prediction and groundtruth are not of equal size.")NEWLINE confMatrix = generateMatrix(args)NEWLINE instStats = generateInstanceStats(args)NEWLINE perImageStats = {}NEWLINE nbPixels = 0NEWLINENEWLINE if not args.quiet:NEWLINE print("Evaluating {} pairs of images...".format(len(predictionImgList)))NEWLINENEWLINE # Evaluate all pairs of images and save them into a matrixNEWLINE for i in range(len(predictionImgList)):NEWLINE predictionImgFileName = predictionImgList[i]NEWLINE groundTruthImgFileName = groundTruthImgList[i]NEWLINE # print "Evaluate ", predictionImgFileName, "<>", groundTruthImgFileNameNEWLINE nbPixels += self.evaluatePair(predictionImgFileName, groundTruthImgFileName, confMatrix, instStats,NEWLINE perImageStats, args)NEWLINENEWLINE # sanity checkNEWLINE if confMatrix.sum() != nbPixels:NEWLINE printError(NEWLINE 'Number of analyzed pixels and entries in confusion matrix disagree: contMatrix {}, pixels {}'.format(NEWLINE confMatrix.sum(), nbPixels))NEWLINENEWLINE if not args.quiet:NEWLINE print("\rImages Processed: {}".format(i + 1), end=' ')NEWLINE sys.stdout.flush()NEWLINE if not args.quiet:NEWLINE print("\n")NEWLINENEWLINE # sanity checkNEWLINE if confMatrix.sum() != nbPixels:NEWLINE printError(NEWLINE 'Number of analyzed pixels and entries in confusion matrix disagree: contMatrix {}, pixels {}'.format(NEWLINE confMatrix.sum(), nbPixels))NEWLINENEWLINE # print confusion matrixNEWLINE if (not args.quiet):NEWLINE printConfMatrix(confMatrix, args)NEWLINENEWLINE # Calculate IOU scores on class level from matrixNEWLINE classScoreList = {}NEWLINE for label in args.evalLabels:NEWLINE labelName = id2label[label].nameNEWLINE classScoreList[labelName] = getIouScoreForLabel(label, confMatrix, args)NEWLINENEWLINE # Calculate instance IOU scores on class level from matrixNEWLINE classInstScoreList = {}NEWLINE for label in args.evalLabels:NEWLINE labelName = id2label[label].nameNEWLINE classInstScoreList[labelName] = getInstanceIouScoreForLabel(label, confMatrix, instStats, args)NEWLINENEWLINE # Print IOU scoresNEWLINE if (not args.quiet):NEWLINE print("")NEWLINE print("")NEWLINE printClassScores(classScoreList, classInstScoreList, args)NEWLINE iouAvgStr = getColorEntry(getScoreAverage(classScoreList, args), args) + "{avg:5.3f}".format(NEWLINE avg=getScoreAverage(classScoreList, args)) + args.nocolNEWLINE niouAvgStr = getColorEntry(getScoreAverage(classInstScoreList, args), args) + "{avg:5.3f}".format(NEWLINE avg=getScoreAverage(classInstScoreList, args)) + args.nocolNEWLINE print("--------------------------------")NEWLINE print("Score Average : " + iouAvgStr + " " + niouAvgStr)NEWLINE print("--------------------------------")NEWLINE print("")NEWLINENEWLINE # Calculate IOU scores on category level from matrixNEWLINE categoryScoreList = {}NEWLINE for category in category2labels.keys():NEWLINE categoryScoreList[category] = getIouScoreForCategory(category, confMatrix, args)NEWLINENEWLINE # Calculate instance IOU scores on category level from matrixNEWLINE categoryInstScoreList = {}NEWLINE for category in category2labels.keys():NEWLINE categoryInstScoreList[category] = getInstanceIouScoreForCategory(category, confMatrix, instStats, args)NEWLINENEWLINE # Print IOU scoresNEWLINE if (not args.quiet):NEWLINE print("")NEWLINE printCategoryScores(categoryScoreList, categoryInstScoreList, args)NEWLINE iouAvgStr = getColorEntry(getScoreAverage(categoryScoreList, args), args) + "{avg:5.3f}".format(NEWLINE avg=getScoreAverage(categoryScoreList, args)) + args.nocolNEWLINE niouAvgStr = getColorEntry(getScoreAverage(categoryInstScoreList, args), args) + "{avg:5.3f}".format(NEWLINE avg=getScoreAverage(categoryInstScoreList, args)) + args.nocolNEWLINE print("--------------------------------")NEWLINE print("Score Average : " + iouAvgStr + " " + niouAvgStr)NEWLINE print("--------------------------------")NEWLINE print("")NEWLINENEWLINE # write result fileNEWLINE allResultsDict = createResultDict(confMatrix, classScoreList, classInstScoreList, categoryScoreList,NEWLINE categoryInstScoreList, perImageStats, args)NEWLINE writeJSONFile(allResultsDict, args)NEWLINENEWLINE # return confusion matrixNEWLINE return allResultsDictNEWLINENEWLINE # Main evaluation method. Evaluates pairs of prediction and ground truthNEWLINE # images which are passed as arguments.NEWLINE def evaluatePair(self,predictionImgFileName, groundTruthImgFileName, confMatrix, instanceStats, perImageStats, args):NEWLINE # Loading all resources for evaluation.NEWLINE try:NEWLINE predictionImg = Image.open(predictionImgFileName)NEWLINE predictionNp = np.array(predictionImg)NEWLINE except:NEWLINE printError("Unable to load " + predictionImgFileName)NEWLINE try:NEWLINE groundTruthImg = Image.open(groundTruthImgFileName)NEWLINE groundTruthNp = np.array(groundTruthImg)NEWLINE except:NEWLINE printError("Unable to load " + groundTruthImgFileName)NEWLINE # load ground truth instances, if neededNEWLINE if args.evalInstLevelScore:NEWLINE groundTruthInstanceImgFileName = groundTruthImgFileName.replace("labelIds", "instanceIds")NEWLINE try:NEWLINE instanceImg = Image.open(groundTruthInstanceImgFileName)NEWLINE instanceNp = np.array(instanceImg)NEWLINE except:NEWLINE printError("Unable to load " + groundTruthInstanceImgFileName)NEWLINENEWLINE # Check for equal image sizesNEWLINE if (predictionImg.size[0] != groundTruthImg.size[0]):NEWLINE printError(NEWLINE "Image widths of " + predictionImgFileName + " and " + groundTruthImgFileName + " are not equal.")NEWLINE if (predictionImg.size[1] != groundTruthImg.size[1]):NEWLINE printError(NEWLINE "Image heights of " + predictionImgFileName + " and " + groundTruthImgFileName + " are not equal.")NEWLINE if (len(predictionNp.shape) != 2):NEWLINE printError("Predicted image has multiple channels.")NEWLINENEWLINE imgWidth = predictionImg.size[0]NEWLINE imgHeight = predictionImg.size[1]NEWLINE nbPixels = imgWidth * imgHeightNEWLINENEWLINE # Evaluate imagesNEWLINE if (CSUPPORT):NEWLINE # using cythonNEWLINE confMatrix = addToConfusionMatrix.cEvaluatePair(predictionNp, groundTruthNp, confMatrix, args.evalLabels)NEWLINE else:NEWLINE # the slower python wayNEWLINE for (groundTruthImgPixel, predictionImgPixel) in izip(groundTruthImg.getdata(), predictionImg.getdata()):NEWLINE if (not groundTruthImgPixel in args.evalLabels):NEWLINE printError("Unknown label with id {:}".format(groundTruthImgPixel))NEWLINENEWLINE confMatrix[groundTruthImgPixel][predictionImgPixel] += 1NEWLINENEWLINE if args.evalInstLevelScore:NEWLINE # Generate category masksNEWLINE categoryMasks = {}NEWLINE for category in instanceStats["categories"]:NEWLINE categoryMasks[category] = np.in1d(predictionNp,NEWLINE instanceStats["categories"][category]["labelIds"]).reshape(NEWLINE predictionNp.shape)NEWLINENEWLINE instList = np.unique(instanceNp[instanceNp > 1000])NEWLINE for instId in instList:NEWLINE labelId = int(instId / 1000)NEWLINE label = id2label[labelId]NEWLINE if label.ignoreInEval:NEWLINE continueNEWLINENEWLINE mask = instanceNp == instIdNEWLINE instSize = np.count_nonzero(mask)NEWLINENEWLINE tp = np.count_nonzero(predictionNp[mask] == labelId)NEWLINE fn = instSize - tpNEWLINENEWLINE weight = args.avgClassSize[label.name] / float(instSize)NEWLINE tpWeighted = float(tp) * weightNEWLINE fnWeighted = float(fn) * weightNEWLINENEWLINE instanceStats["classes"][label.name]["tp"] += tpNEWLINE instanceStats["classes"][label.name]["fn"] += fnNEWLINE instanceStats["classes"][label.name]["tpWeighted"] += tpWeightedNEWLINE instanceStats["classes"][label.name]["fnWeighted"] += fnWeightedNEWLINENEWLINE category = label.categoryNEWLINE if category in instanceStats["categories"]:NEWLINE catTp = 0NEWLINE catTp = np.count_nonzero(np.logical_and(mask, categoryMasks[category]))NEWLINE catFn = instSize - catTpNEWLINENEWLINE catTpWeighted = float(catTp) * weightNEWLINE catFnWeighted = float(catFn) * weightNEWLINENEWLINE instanceStats["categories"][category]["tp"] += catTpNEWLINE instanceStats["categories"][category]["fn"] += catFnNEWLINE instanceStats["categories"][category]["tpWeighted"] += catTpWeightedNEWLINE instanceStats["categories"][category]["fnWeighted"] += catFnWeightedNEWLINENEWLINE if args.evalPixelAccuracy:NEWLINE notIgnoredLabels = [l for l in args.evalLabels if not id2label[l].ignoreInEval]NEWLINE notIgnoredPixels = np.in1d(groundTruthNp, notIgnoredLabels, invert=True).reshape(groundTruthNp.shape)NEWLINE erroneousPixels = np.logical_and(notIgnoredPixels, (predictionNp != groundTruthNp))NEWLINE perImageStats[predictionImgFileName] = {}NEWLINE perImageStats[predictionImgFileName]["nbNotIgnoredPixels"] = np.count_nonzero(notIgnoredPixels)NEWLINE perImageStats[predictionImgFileName]["nbCorrectPixels"] = np.count_nonzero(erroneousPixels)NEWLINENEWLINE return nbPixelsNEWLINENEWLINENEWLINE # launch the processNEWLINE def run(self):NEWLINE self.evaluateImgLists(self.predictionImgList, self.groundTruthImgList, self.args)NEWLINENEWLINE # get the default dataNEWLINE def getDefaultData(self, args):NEWLINE groundTruthImgList, predictionImgList = [], []NEWLINE groundTruthImgList = glob.glob(args.groundTruthSearch)NEWLINE if not groundTruthImgList:NEWLINE printError("Cannot find any ground truth images to use for evaluation. Searched for: {}".format(NEWLINE args.groundTruthSearch))NEWLINE # get the corresponding prediction for each ground truth imagNEWLINE for gt in groundTruthImgList:NEWLINE predictionImgList.append(getPrediction(args, gt))NEWLINE return groundTruthImgList, predictionImgListNEWLINENEWLINENEWLINEclass CityScapeEvaluator(object):NEWLINENEWLINE def evaluate(self, pred_dir=None, gt_dir=None):NEWLINE """NEWLINE :param pred_dir: directory of model output results(must be consistent with val directory)NEWLINE :param gt_dir: directory of cityscape data(root)NEWLINE :return:NEWLINE """NEWLINE pred_path = pred_dirNEWLINE data_path = gt_dirNEWLINE print("evaluate the result...")NEWLINE args = CArgs(data_path=data_path, out_path=data_path, predict_path=pred_path)NEWLINE ob = EvalPixel(args)NEWLINE ob.run()NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE # python cityscape_evaluator.py --gt_dir ~/DataSet/CityScape/gtFine/valNEWLINE # --pred_dir ~/Projects/PyTorchCV/val/results/seg/cityscape/test_dir/image/labelNEWLINE parser = argparse.ArgumentParser()NEWLINE parser.add_argument('--gt_dir', default=None, type=str,NEWLINE dest='gt_dir', help='The directory of ground truth.')NEWLINE parser.add_argument('--pred_dir', default=None, type=str,NEWLINE dest='pred_dir', help='The directory of predicted labels.')NEWLINENEWLINE args = parser.parse_args()NEWLINENEWLINE cityscape_evaluator = CityScapeEvaluator()NEWLINE cityscape_evaluator.evaluate(pred_dir=args.pred_dir, gt_dir=args.gt_dir)NEWLINE # Copyright 2021 University College London. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE# ==============================================================================NEWLINE"""Keras objects registry.NEWLINENEWLINEKeras Declarative maintains its own object registry. There are a few differencesNEWLINEwith respect to the Keras registry:NEWLINENEWLINE * It includes non-serializable objects such as callbacks.NEWLINE * It does not prepend package prefixes to object names.NEWLINE * It supports objects of type `ObjectConfig` as identifiers.NEWLINE"""NEWLINENEWLINEimport inspectNEWLINENEWLINEimport tensorflow as tfNEWLINENEWLINEfrom keras_declarative import config as config_moduleNEWLINEfrom keras_declarative import hyperparamsNEWLINEfrom keras_declarative import predicatesNEWLINEfrom keras_declarative import utilNEWLINENEWLINENEWLINEdef get_list(get_fn):NEWLINE """Returns a function that retrieves a list of objects.NEWLINENEWLINE Args:NEWLINE get_fn: The get function to be used for individual identifiers.NEWLINENEWLINE Returns:NEWLINE A function that retrieves an object or a list of objects.NEWLINE """NEWLINE def get_list_fn(identifier):NEWLINE """Retrieves a list of objects.NEWLINENEWLINE Args:NEWLINE identifier: An object identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A list of Keras objects as class instances.NEWLINE """NEWLINE if isinstance(identifier, list):NEWLINE return [get_fn(ident) for ident in identifier]NEWLINE return get_fn(identifier)NEWLINE return get_list_fnNEWLINENEWLINENEWLINEdef get_nest(get_fn):NEWLINE """Returns a function that retrieves a nested structure of objects.NEWLINENEWLINE Nests include lists and dictionaries.NEWLINENEWLINE Args:NEWLINE get_fn: The get function to be used for individual identifiers.NEWLINENEWLINE Returns:NEWLINE A function that retrieves an object or a list of objects.NEWLINE """NEWLINE def get_nest_fn(identifier):NEWLINE """Retrieves a nested structure of objects.NEWLINENEWLINE Args:NEWLINE identifier: An object identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A list of Keras objects as class instances.NEWLINE """NEWLINE if isinstance(identifier, hyperparams.ParamsDict):NEWLINE identifier = identifier.as_dict()NEWLINE def _parse_nest(nest):NEWLINE if is_object_config(nest):NEWLINE return get_fn(nest)NEWLINE if isinstance(nest, dict):NEWLINE return {key: _parse_nest(value) for key, value in nest.items()}NEWLINE if isinstance(nest, list):NEWLINE return [_parse_nest(value) for value in nest]NEWLINE return get_fn(nest)NEWLINE return _parse_nest(identifier)NEWLINE return get_nest_fnNEWLINENEWLINENEWLINEdef get_callback(identifier):NEWLINE """Retrieve a Keras callback as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: A callback identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A Keras callback as a class instance.NEWLINE """NEWLINE return _get(identifier, _CALLBACK_OBJECTS, 'callback')NEWLINENEWLINENEWLINEdef get_layer(identifier):NEWLINE """Retrieve a Keras layer as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: A layer identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A Keras layer as a class instance.NEWLINE """NEWLINE return _get(identifier, _LAYER_OBJECTS, 'layer')NEWLINENEWLINENEWLINEdef get_loss(identifier):NEWLINE """Retrieve a Keras loss as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: A loss identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A Keras loss as a class instance.NEWLINE """NEWLINE return _get(identifier, _LOSS_OBJECTS, 'loss')NEWLINENEWLINENEWLINEdef get_metric(identifier):NEWLINE """Retrieve a Keras metric as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: A metric identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A Keras metric as a class instance.NEWLINE """NEWLINE return _get(identifier, _METRIC_OBJECTS, 'metric')NEWLINENEWLINENEWLINEdef get_optimizer(identifier):NEWLINE """Retrieve a Keras optimizer as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: An optimizer identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A Keras optimizer as a class instance.NEWLINE """NEWLINE return _get(identifier, _OPTIMIZER_OBJECTS, 'optimizer')NEWLINENEWLINENEWLINEdef get_predicate(identifier):NEWLINE """Retrieve a predicate as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: A predicate identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A predicate as a class instance.NEWLINE """NEWLINE return _get(identifier, _PREDICATE_OBJECTS, 'predicate')NEWLINENEWLINENEWLINEdef get_strategy(identifier):NEWLINE """Retrieve a TF distribution strategy as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: A strategy identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A TF distribution strategy as a class instance.NEWLINE """NEWLINE return _get(identifier, _STRATEGY_OBJECTS, 'strategy')NEWLINENEWLINENEWLINEdef _get(identifier, objects, objtype):NEWLINE """Retrieve an object as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: An object identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINE objects: A dictionary with the registered objects.NEWLINE objtype: A string with the type of object being retrieved. This is only usedNEWLINE to format error messages.NEWLINENEWLINE Returns:NEWLINE An instance of the object identified by `identifier`.NEWLINENEWLINE Raises:NEWLINE ValueError: If the identifier is invalid.NEWLINE RuntimeError: If an error occurs while initializing the object.NEWLINE """NEWLINE # If object is an external object, don't try to resolve it.NEWLINE if isinstance(identifier, util.ExternalObject):NEWLINE return identifierNEWLINENEWLINE if isinstance(identifier, config_module.ObjectConfig):NEWLINE identifier = identifier.as_dict()NEWLINENEWLINE if not identifier: # Might be `None` or an empty dict.NEWLINE return NoneNEWLINENEWLINE class_name, config = class_and_config_for_serialized_object(identifier)NEWLINENEWLINE if class_name not in objects:NEWLINE raise ValueError(f"No known {objtype} with name: {class_name}")NEWLINE obj = objects[class_name]NEWLINENEWLINE try:NEWLINE return obj(**config)NEWLINE except Exception as e:NEWLINE raise RuntimeError(NEWLINE f"An error occurred while initializing {class_name} with parameters: "NEWLINE f"{config}") from eNEWLINENEWLINENEWLINEdef class_and_config_for_serialized_object(identifier):NEWLINE """Returns the class name and config for a serialized object.NEWLINENEWLINE Args:NEWLINE identifier: An object identifier. Must be a string, a dictionary or anNEWLINE `ObjectConfig`.NEWLINENEWLINE Returns:NEWLINE A tuple containing the class name and its keyword arguments.NEWLINENEWLINE Raises:NEWLINE ValueError: If the identifier is invalid.NEWLINE """NEWLINE if isinstance(identifier, config_module.ObjectConfig):NEWLINE identifier = identifier.as_dict()NEWLINENEWLINE if isinstance(identifier, str):NEWLINE class_name, config = identifier, {}NEWLINENEWLINE elif isinstance(identifier, dict):NEWLINE if 'class_name' not in identifier or 'config' not in identifier:NEWLINE raise ValueError(NEWLINE f"Invalid identifier: {identifier}. Value is not a valid "NEWLINE f"configuration dictionary.")NEWLINE class_name = identifier['class_name']NEWLINE config = identifier['config']NEWLINENEWLINE else:NEWLINE raise ValueError(NEWLINE f"Invalid identifier: {identifier}. Value must be a string, a "NEWLINE f"dictionary or an `ObjectConfig`.")NEWLINENEWLINE return class_name, configNEWLINENEWLINENEWLINEdef is_object_config(config):NEWLINE """Check if input is a valid object configuration dict.NEWLINENEWLINE Args:NEWLINE config: The object to check.NEWLINENEWLINE Returns:NEWLINE True if input is a valid object configuration dict, false otherwise.NEWLINE """NEWLINE # A str or None are valid object configs.NEWLINE if isinstance(config, (str, type(None))):NEWLINE return TrueNEWLINENEWLINE # Otherwise, must be a dict or an object of type `ParamsDict`.NEWLINE if not isinstance(config, (dict, hyperparams.ParamsDict)):NEWLINE return FalseNEWLINENEWLINE # If a dict, must have two keys: class_name and config.NEWLINE d = config.as_dict() if isinstance(config, hyperparams.ParamsDict) else configNEWLINE if set(d.keys()) != {'class_name', 'config'}:NEWLINE return FalseNEWLINENEWLINE return TrueNEWLINENEWLINENEWLINEdef _find_objects(modules, objtype):NEWLINE """Finds objects of a certain type on the given modules.NEWLINENEWLINE Args:NEWLINE modules: A list of modules to search for objects.NEWLINE objtype: The type of objects to be searched for.NEWLINENEWLINE Returns:NEWLINE A dictionary containing the found objects.NEWLINE """NEWLINE objects = {}NEWLINE for module in modules:NEWLINE members = inspect.getmembers(module)NEWLINE for name, value in members:NEWLINE if inspect.isclass(value) and issubclass(value, objtype):NEWLINE objects[name] = valueNEWLINE return objectsNEWLINENEWLINENEWLINE_CALLBACK_MODULES = [NEWLINE tf.keras.callbacksNEWLINE]NEWLINENEWLINE_LAYER_MODULES = [NEWLINE tf.keras.layersNEWLINE]NEWLINENEWLINE_LOSS_MODULES = [NEWLINE tf.keras.losses,NEWLINE]NEWLINENEWLINE_METRIC_MODULES = [NEWLINE tf.keras.metrics,NEWLINE]NEWLINENEWLINE_OPTIMIZER_MODULES = [NEWLINE tf.keras.optimizersNEWLINE]NEWLINENEWLINE_PREDICATE_MODULES = [NEWLINE predicatesNEWLINE]NEWLINENEWLINE_STRATEGY_MODULES = [NEWLINE tf.distributeNEWLINE]NEWLINENEWLINENEWLINE# Try to discover objects from TensorFlow MRI, if it is installed.NEWLINEtry:NEWLINE import tensorflow_mri as tfmriNEWLINE _CALLBACK_MODULES.append(tfmri.callbacks)NEWLINE _LAYER_MODULES.extend([tfmri.layers])NEWLINE _LOSS_MODULES.append(tfmri.losses)NEWLINE _METRIC_MODULES.append(tfmri.metrics)NEWLINEexcept ImportError:NEWLINE passNEWLINENEWLINENEWLINE# Try to discover objects from TF Playground, if it is installed.NEWLINEtry:NEWLINE import tf_playground as tfpgNEWLINE _CALLBACK_MODULES.append(tfpg.callbacks)NEWLINE _LAYER_MODULES.append(tfpg.layers)NEWLINE _LOSS_MODULES.append(tfpg.losses)NEWLINE _METRIC_MODULES.append(tfpg.metrics)NEWLINEexcept ImportError:NEWLINE passNEWLINENEWLINENEWLINE_CALLBACK_OBJECTS = NoneNEWLINE_LAYER_OBJECTS = NoneNEWLINE_LOSS_OBJECTS = NoneNEWLINE_METRIC_OBJECTS = NoneNEWLINE_OPTIMIZER_OBJECTS = NoneNEWLINE_PREDICATE_OBJECTS = NoneNEWLINE_STRATEGY_OBJECTS = NoneNEWLINENEWLINENEWLINEdef discover_objects(custom_modules=None):NEWLINE """Discover Keras objects.NEWLINENEWLINE By default, this function searches for Keras objects in core TensorFlow andNEWLINE TensorFlow MRI (if installed).NEWLINENEWLINE Args:NEWLINE custom_modules: A list of custom modules to be searched for Keras objects.NEWLINE """NEWLINE global _CALLBACK_OBJECTSNEWLINE global _LAYER_OBJECTSNEWLINE global _LOSS_OBJECTSNEWLINE global _METRIC_OBJECTSNEWLINE global _OPTIMIZER_OBJECTSNEWLINE global _PREDICATE_OBJECTSNEWLINE global _STRATEGY_OBJECTSNEWLINENEWLINE custom_modules = custom_modules or []NEWLINENEWLINE _CALLBACK_OBJECTS = _find_objects(_CALLBACK_MODULES + custom_modules,NEWLINE tf.keras.callbacks.Callback)NEWLINENEWLINE _LAYER_OBJECTS = _find_objects(_LAYER_MODULES + custom_modules,NEWLINE tf.keras.layers.Layer)NEWLINENEWLINE _LOSS_OBJECTS = _find_objects(_LOSS_MODULES + custom_modules,NEWLINE tf.keras.losses.Loss)NEWLINENEWLINE _METRIC_OBJECTS = _find_objects(_METRIC_MODULES + custom_modules,NEWLINE tf.keras.metrics.Metric)NEWLINENEWLINE _OPTIMIZER_OBJECTS = _find_objects(_OPTIMIZER_MODULES + custom_modules,NEWLINE tf.keras.optimizers.Optimizer)NEWLINENEWLINE _PREDICATE_OBJECTS = _find_objects(_PREDICATE_MODULES, predicates.Predicate)NEWLINENEWLINE _STRATEGY_OBJECTS = _find_objects(_STRATEGY_MODULES, tf.distribute.Strategy)NEWLINENEWLINEdiscover_objects()NEWLINE #!/usr/bin/env python3NEWLINE# Copyright 2020-present NAVER Corp. Under BSD 3-clause licenseNEWLINENEWLINEimport argparseNEWLINEimport osNEWLINEimport loggingNEWLINEimport pathlibNEWLINENEWLINEimport path_to_kapture_localization # noqa: F401NEWLINEimport kapture_localization.utils.loggingNEWLINEfrom kapture_localization.utils.pairsfile import get_ordered_pairs_from_fileNEWLINENEWLINEimport kapture_localization.utils.path_to_kapture # noqa: F401NEWLINEimport kaptureNEWLINEimport kapture.utils.loggingNEWLINEfrom kapture.io.csv import table_to_fileNEWLINENEWLINElogger = kapture_localization.utils.logging.getLogger()NEWLINENEWLINENEWLINEdef slice_pairsfile(pairsfile_path: str,NEWLINE output_path: str,NEWLINE topk: int,NEWLINE threshold: float,NEWLINE startk: int,NEWLINE skip_if_na: bool):NEWLINE logger.info('slice_pairsfile...')NEWLINE similarity_dict = get_ordered_pairs_from_file(pairsfile_path)NEWLINENEWLINE # apply topk override + skip_if_naNEWLINE image_pairs = []NEWLINE for name_query, paired_images in sorted(similarity_dict.items()):NEWLINE paired_images_threshold = [x for x in paired_images if x[1] >= threshold]NEWLINE if startk + topk > len(paired_images_threshold):NEWLINE logger.debug(NEWLINE f'image {name_query} has {len(paired_images_threshold)} pairs, 'NEWLINE f'less than topk={topk} (with startk={startk})')NEWLINE if skip_if_na:NEWLINE logger.debug(f'skipping {name_query}')NEWLINE continueNEWLINE paired_images_threshold = paired_images_threshold[startk:startk+topk]NEWLINE for name_map, score in paired_images_threshold:NEWLINE image_pairs.append((name_query, name_map, score))NEWLINENEWLINE if len(image_pairs) > 0:NEWLINE os.umask(0o002)NEWLINE p = pathlib.Path(output_path)NEWLINE os.makedirs(str(p.parent.resolve()), exist_ok=True)NEWLINE with open(output_path, 'w') as fid:NEWLINE table_to_file(fid, image_pairs, header='# query_image, map_image, score')NEWLINE else:NEWLINE logger.info('no pairs written')NEWLINE logger.info('all done')NEWLINENEWLINENEWLINEdef slice_pairsfile_command_line():NEWLINE parser = argparse.ArgumentParser(description='Apply topk override / threshold on a pairsfile',NEWLINE formatter_class=argparse.ArgumentDefaultsHelpFormatter)NEWLINE parser_verbosity = parser.add_mutually_exclusive_group()NEWLINE parser_verbosity.add_argument('-v', '--verbose', nargs='?', default=logging.WARNING, const=logging.INFO,NEWLINE action=kapture.utils.logging.VerbosityParser,NEWLINE help='verbosity level (debug, info, warning, critical, ... or int value) [warning]')NEWLINE parser_verbosity.add_argument('-q', '--silent', '--quiet',NEWLINE action='store_const', dest='verbose', const=logging.CRITICAL)NEWLINE parser.add_argument('-i', '--input', required=True, help='path to input pairsfile')NEWLINE parser.add_argument('-o', '--output', required=True, help='path to output pairsfile')NEWLINE parser.add_argument('--topk',NEWLINE default=float('inf'),NEWLINE type=int,NEWLINE help='override pairfile topk with this one (must be inferior or equal)')NEWLINE parser.add_argument('--threshold', type=float, default=0,NEWLINE help='the minimum score threshold for pairs to be used')NEWLINE parser.add_argument('--startk',NEWLINE default=0,NEWLINE type=int,NEWLINE help='start position of topk')NEWLINE parser.add_argument('--skip-if-na', action='store_true', default=False,NEWLINE help='Skip query image if startk + topk greater than available pairs (i.e. na, not available)')NEWLINE args = parser.parse_args()NEWLINE logger.setLevel(args.verbose)NEWLINE if args.verbose <= logging.DEBUG:NEWLINE # also let kapture express its logsNEWLINE kapture.utils.logging.getLogger().setLevel(args.verbose)NEWLINENEWLINE logger.debug('kapture_slice_pairsfile.py \\\n' + ''.join(['\n\t{:13} = {}'.format(k, v)NEWLINE for k, v in vars(args).items()]))NEWLINE slice_pairsfile(args.input, args.output, args.topk, args.threshold, args.startk, args.skip_if_na)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE slice_pairsfile_command_line()NEWLINE # Generated by Django 3.0 on 2020-04-21 20:13NEWLINENEWLINEfrom django.db import migrations, modelsNEWLINEimport django.db.models.deletionNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE initial = TrueNEWLINENEWLINE dependencies = [NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.CreateModel(NEWLINE name='Hospital',NEWLINE fields=[NEWLINE ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),NEWLINE ('name', models.CharField(max_length=254, verbose_name='Nome')),NEWLINE ('city', models.CharField(max_length=254, verbose_name='Cidade')),NEWLINE ('phonenumber', models.CharField(max_length=16, verbose_name='Telefone')),NEWLINE ('email', models.EmailField(max_length=254, verbose_name='E-mail')),NEWLINE ],NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name='Patient',NEWLINE fields=[NEWLINE ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),NEWLINE ('name', models.CharField(max_length=254, verbose_name='Nome')),NEWLINE ('birthday', models.DateField(verbose_name='Data de Nascimento')),NEWLINE ('airways', models.CharField(choices=[('VM', 'Ventilação Mecânica'), ('AA', 'Ar Ambiente'), ('VNI', 'Ventilação não Invasiva')], default='AA', max_length=24, verbose_name='Vias Aéreas')),NEWLINE ('status', models.CharField(choices=[('S', 'Suspeito'), ('C', 'Confirmado'), ('D', 'Descartado')], default='S', max_length=10, verbose_name='Status COVID')),NEWLINE ('hospitalization_date', models.DateField(verbose_name='Data de Internação')),NEWLINE ('departure_date', models.DateField(verbose_name='Data de Saída')),NEWLINE ('cns', models.CharField(blank=True, default='', max_length=30, verbose_name='Carteira Nacional do SUS')),NEWLINE ('sisreg', models.CharField(blank=True, default='', max_length=30, verbose_name='Número no sistema Sisreg')),NEWLINE ('departure_reason', models.CharField(choices=[('A', 'Alta'), ('O', 'Óbito')], default='A', max_length=5, verbose_name='Motivo da Saída')),NEWLINE ('hospital', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='hospitals.Hospital', verbose_name='Hospital')),NEWLINE ],NEWLINE ),NEWLINE ]NEWLINE # -*- coding: utf-8 -*-NEWLINEfrom __future__ import unicode_literalsNEWLINENEWLINEfrom django.db import migrations, modelsNEWLINENEWLINEimport wagtail.core.fieldsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [("puput", "0001_initial")]NEWLINENEWLINE operations = [NEWLINE migrations.AlterField(NEWLINE model_name="blogpage",NEWLINE name="description",NEWLINE field=models.CharField(NEWLINE max_length=255,NEWLINE help_text="The blog description that will appear under the title.",NEWLINE verbose_name="Description",NEWLINE blank=True,NEWLINE ),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name="category",NEWLINE name="description",NEWLINE field=models.CharField(max_length=500, verbose_name="Description", blank=True),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name="category",NEWLINE name="name",NEWLINE field=models.CharField(max_length=80, unique=True, verbose_name="Category name"),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name="category",NEWLINE name="parent",NEWLINE field=models.ForeignKey(NEWLINE to="puput.Category",NEWLINE related_name="children",NEWLINE null=True,NEWLINE verbose_name="Parent category",NEWLINE blank=True,NEWLINE on_delete=models.SET_NULL,NEWLINE ),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name="entrypage",NEWLINE name="excerpt",NEWLINE field=wagtail.core.fields.RichTextField(NEWLINE help_text="Entry excerpt to be displayed on entries list. If this field is not filled, a truncate version of body text will be used.",NEWLINE verbose_name="excerpt",NEWLINE blank=True,NEWLINE ),NEWLINE ),NEWLINE ]NEWLINE import numpy as np # linear algebraNEWLINEimport pandas as pd # data processingNEWLINEimport datetime as dt # date and time processing functionsNEWLINEimport matplotlib.pyplot as plt # basic plotting NEWLINEimport matplotlib.dates as mdates # date processing in matplotlibNEWLINEfrom matplotlib.offsetbox import AnchoredTextNEWLINEimport mpld3NEWLINEplt.style.use('ggplot') # use ggplot styleNEWLINENEWLINE# read in the data from the provided csv fileNEWLINEdf = pd.read_csv('./static/seaice.csv')NEWLINENEWLINE# drop the 'Source Data' column as it obscures more useful columns and doesn't tell us muchNEWLINEdf.drop('Source Data', axis = 1, inplace=True)NEWLINENEWLINE# convert the provided 3 column date format to datetime format and set it as the indexNEWLINEdf['Date'] = pd.to_datetime(df[['Year','Month','Day']])NEWLINEdf.index = df['Date'].valuesNEWLINENEWLINE# split according to hemisphere, as we are expecting different trends for eachNEWLINEnorth = df[df['hemisphere'] == 'north']NEWLINEsouth = df[df['hemisphere'] == 'south']NEWLINENEWLINEdef dailyExtent():NEWLINE fig = plt.figure(figsize=(9,6))NEWLINE plt.subplot(2, 1, 1)NEWLINE plt.plot(north.index,north['Extent'], label='Northern Hemisphere')NEWLINE plt.plot(south.index,south['Extent'], label='Southern Hemisphere')NEWLINENEWLINE # add plot legend and titlesNEWLINE plt.legend(bbox_to_anchor=(0., -.362, 1., .102), loc=3, ncol=2, NEWLINE mode="expand", borderaxespad=0.)NEWLINE plt.ylabel('Sea ice extent (10^6 sq km)')NEWLINE plt.xlabel('Date')NEWLINE plt.title('Daily sea-ice extent');NEWLINE # saving to htmlNEWLINE save_html("dailyextent", fig)NEWLINENEWLINEdef annualAverage():NEWLINE # resample raw data into annual averagesNEWLINE northyear = north.resample('12M').mean()NEWLINE southyear = south.resample('12M').mean()NEWLINENEWLINE # remove the initial and final item as they aer averaged incorrectly (also indexes seem bad)NEWLINE northyear = northyear[1:-1]NEWLINE southyear = southyear[1:-1]NEWLINENEWLINE fig = plt.figure(figsize=(9,6))NEWLINE plt.subplot(2, 1, 1)NEWLINE plt.plot(northyear.index,northyear['Extent'], marker = '.', label='Northern Hemisphere')NEWLINE plt.plot(southyear.index,southyear['Extent'], marker = '.', label='Southern Hemisphere')NEWLINENEWLINE # add plot legend and titlesNEWLINE plt.legend(bbox_to_anchor=(0., -.362, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.)NEWLINE plt.ylabel('Sea ice extent (10^6 sq km)')NEWLINE plt.xlabel('Date')NEWLINE plt.title('Annual average sea-ice extent')NEWLINE # saving to htmlNEWLINE save_html("annualaverage", fig)NEWLINENEWLINEdef annualChange():NEWLINE # define date range to plot betweenNEWLINE start = 1978NEWLINE end = dt.datetime.now().year + 1NEWLINENEWLINE # define plotNEWLINE f, axarr = plt.subplots(2, sharex=True, figsize=(9,5))NEWLINENEWLINENEWLINE # organise plot axes (set x axis to months only and cycle colours according to gradient)NEWLINE month_fmt = mdates.DateFormatter('%b')NEWLINE axarr[0].xaxis.set_major_formatter(month_fmt)NEWLINE axarr[0].set_prop_cycle(plt.cycler('color', NEWLINE plt.cm.winter(np.linspace(0, 1, len(range(start, end))))))NEWLINE axarr[1].set_prop_cycle(plt.cycler('color', NEWLINE plt.cm.winter(np.linspace(0, 1, len(range(start, end))))))NEWLINENEWLINE # add plot legend and titlesNEWLINE axarr[0].set_ylabel('Sea ice extent (10^6 sq km)')NEWLINE axarr[1].set_ylabel('Sea ice extent (10^6 sq km)')NEWLINE axarr[0].set_xlabel('Month (NORTHERN HERMISPHERE)')NEWLINE axarr[1].set_xlabel('Month (SOUTHERN HERMISPHERE)')NEWLINE axarr[0].set_title('Annual change in sea-ice extent');NEWLINE axarr[0].add_artist(AnchoredText('Northern Hemisphere', loc=3))NEWLINE axarr[1].add_artist(AnchoredText('Southern Hemisphere', loc=2))NEWLINENEWLINE # loop for every year between the start year and currentNEWLINE for year in range(start, end):NEWLINE # create new dataframe for each year, NEWLINE # and set the year to 1972 so all are plotted on the same axisNEWLINE nyeardf = north[['Extent', 'Day', 'Month']][north['Year'] == year]NEWLINE nyeardf['Year'] = 1972NEWLINE nyeardf['Date'] = pd.to_datetime(nyeardf[['Year','Month','Day']])NEWLINE nyeardf.index = nyeardf['Date'].valuesNEWLINE NEWLINE syeardf = south[['Extent', 'Day', 'Month']][south['Year'] == year]NEWLINE syeardf['Year'] = 1972NEWLINE syeardf['Date'] = pd.to_datetime(syeardf[['Year','Month','Day']])NEWLINE syeardf.index = syeardf['Date'].valuesNEWLINE NEWLINE # plot each year individuallyNEWLINE axarr[0].plot(nyeardf.index,nyeardf['Extent'], label = year)NEWLINE axarr[1].plot(syeardf.index,syeardf['Extent'])NEWLINE save_html("annualchange", f)NEWLINENEWLINEdef save_html(filename, fig):NEWLINE # saving to htmlNEWLINE html_str = mpld3.fig_to_html(fig)NEWLINE Html_file= open("./templates/{}.html".format(filename),"w")NEWLINE Html_file.write(html_str)NEWLINE Html_file.close() import asyncioNEWLINEimport loggingNEWLINEimport pickleNEWLINENEWLINEimport timeNEWLINEfrom functools import partialNEWLINEfrom typing import Callable, Any, TypeVarNEWLINENEWLINEfrom aio_pika.exchange import ExchangeTypeNEWLINEfrom aio_pika.channel import ChannelNEWLINEfrom aio_pika.exceptions import UnroutableErrorNEWLINEfrom aio_pika.message import (NEWLINE Message, IncomingMessage, DeliveryMode, ReturnedMessageNEWLINE)NEWLINEfrom .base import Proxy, BaseNEWLINENEWLINElog = logging.getLogger(__name__)NEWLINENEWLINER = TypeVar('R')NEWLINEP = TypeVar('P')NEWLINECallbackType = Callable[[P], R]NEWLINENEWLINENEWLINEclass RPC(Base):NEWLINE __slots__ = ("channel", "loop", "proxy", "result_queue",NEWLINE "result_consumer_tag", "routes", "consumer_tags",NEWLINE "dlx_exchange",)NEWLINENEWLINE DLX_NAME = 'rpc.dlx'NEWLINE DELIVERY_MODE = DeliveryMode.NOT_PERSISTENTNEWLINENEWLINE __doc__ = """NEWLINE Remote Procedure Call helper.NEWLINENEWLINE Create an instance ::NEWLINENEWLINE rpc = await RPC.create(channel)NEWLINENEWLINE Registering python function ::NEWLINENEWLINE # RPC instance passes only keyword argumentsNEWLINE def multiply(*, x, y):NEWLINE return x * yNEWLINENEWLINE await rpc.register("multiply", multiply)NEWLINENEWLINE Call function through proxy ::NEWLINENEWLINE assert await rpc.proxy.multiply(x=2, y=3) == 6NEWLINENEWLINE Call function explicit ::NEWLINENEWLINE assert await rpc.call('multiply', dict(x=2, y=3)) == 6NEWLINENEWLINE """NEWLINENEWLINE def __init__(self, channel: Channel):NEWLINE self.channel = channelNEWLINE self.loop = self.channel.loopNEWLINE self.proxy = Proxy(self.call)NEWLINE self.result_queue = NoneNEWLINE self.futures = dict()NEWLINE self.result_consumer_tag = NoneNEWLINE self.routes = {}NEWLINE self.queues = {}NEWLINE self.consumer_tags = {}NEWLINE self.dlx_exchange = NoneNEWLINENEWLINE def create_future(self) -> asyncio.Future:NEWLINE future = self.loop.create_future()NEWLINE future_id = id(future)NEWLINE self.futures[future_id] = futureNEWLINE future.add_done_callback(lambda f: self.futures.pop(future_id, None))NEWLINE return futureNEWLINENEWLINE def close(self) -> asyncio.Task:NEWLINE async def closer():NEWLINE nonlocal selfNEWLINENEWLINE if self.result_queue is None:NEWLINE returnNEWLINENEWLINE for future in self.futures.values():NEWLINE future.set_exception(asyncio.CancelledError)NEWLINENEWLINE await self.result_queue.unbind(NEWLINE self.dlx_exchange, "",NEWLINE arguments={NEWLINE "From": self.result_queue.name,NEWLINE 'x-match': 'any',NEWLINE }NEWLINE )NEWLINENEWLINE await self.result_queue.cancel(self.result_consumer_tag)NEWLINE self.result_consumer_tag = NoneNEWLINENEWLINE await self.result_queue.delete()NEWLINE self.result_queue = NoneNEWLINENEWLINE return self.loop.create_task(closer())NEWLINENEWLINE async def initialize(self, **kwargs):NEWLINE if self.result_queue is not None:NEWLINE returnNEWLINENEWLINE self.result_queue = await self.channel.declare_queue(None, **kwargs)NEWLINENEWLINE self.dlx_exchange = await self.channel.declare_exchange(NEWLINE self.DLX_NAME,NEWLINE type=ExchangeType.HEADERS,NEWLINE auto_delete=True,NEWLINE )NEWLINENEWLINE await self.result_queue.bind(NEWLINE self.dlx_exchange, "",NEWLINE arguments={NEWLINE "From": self.result_queue.name,NEWLINE 'x-match': 'any',NEWLINE }NEWLINE )NEWLINENEWLINE self.result_consumer_tag = await self.result_queue.consume(NEWLINE self.on_result_message, exclusive=True, no_ack=TrueNEWLINE )NEWLINENEWLINE self.channel.add_on_return_callback(self.on_message_returned)NEWLINENEWLINE @classmethodNEWLINE async def create(cls, channel: Channel, **kwargs) -> "RPC":NEWLINE """ Creates a new instance of :class:`aio_pika.patterns.RPC`.NEWLINE You should use this method instead of :func:`__init__`,NEWLINE because :func:`create` returns coroutine and makes async initializeNEWLINENEWLINE :param channel: initialized instance of :class:`aio_pika.Channel`NEWLINE :returns: :class:`RPC`NEWLINENEWLINE """NEWLINE rpc = cls(channel)NEWLINE await rpc.initialize(**kwargs)NEWLINE return rpcNEWLINENEWLINE def on_message_returned(self, message: ReturnedMessage):NEWLINE correlation_id = int(NEWLINE message.correlation_idNEWLINE ) if message.correlation_id else NoneNEWLINENEWLINE future = self.futures.pop(correlation_id, None) # type: asyncio.FutureNEWLINENEWLINE if not future or future.done():NEWLINE log.warning("Unknown message was returned: %r", message)NEWLINE returnNEWLINENEWLINE future.set_exception(UnroutableError([message]))NEWLINENEWLINE async def on_result_message(self, message: IncomingMessage):NEWLINE correlation_id = int(NEWLINE message.correlation_idNEWLINE ) if message.correlation_id else NoneNEWLINENEWLINE future = self.futures.pop(correlation_id, None) # type: asyncio.FutureNEWLINENEWLINE if future is None:NEWLINE log.warning("Unknown message: %r", message)NEWLINE returnNEWLINENEWLINE try:NEWLINE payload = self.deserialize(message.body)NEWLINE except Exception as e:NEWLINE log.error("Failed to deserialize response on message: %r", message)NEWLINE future.set_exception(e)NEWLINE returnNEWLINENEWLINE if message.type == 'result':NEWLINE future.set_result(payload)NEWLINE elif message.type == 'error':NEWLINE future.set_exception(payload)NEWLINE elif message.type == 'call':NEWLINE future.set_exception(NEWLINE asyncio.TimeoutError("Message timed-out", message)NEWLINE )NEWLINE else:NEWLINE future.set_exception(NEWLINE RuntimeError("Unknown message type %r" % message.type)NEWLINE )NEWLINENEWLINE async def on_call_message(self, method_name: str, message: IncomingMessage):NEWLINE if method_name not in self.routes:NEWLINE log.warning("Method %r not registered in %r", method_name, self)NEWLINE returnNEWLINENEWLINE try:NEWLINE payload = self.deserialize(message.body)NEWLINE func = self.routes[method_name]NEWLINENEWLINE result = await self.execute(func, payload)NEWLINE result = self.serialize(result)NEWLINE message_type = 'result'NEWLINE except Exception as e:NEWLINE result = self.serialize_exception(e)NEWLINE message_type = 'error'NEWLINENEWLINE result_message = Message(NEWLINE result,NEWLINE delivery_mode=message.delivery_mode,NEWLINE correlation_id=message.correlation_id,NEWLINE timestamp=time.time(),NEWLINE type=message_type,NEWLINE )NEWLINENEWLINE await self.channel.default_exchange.publish(NEWLINE result_message,NEWLINE message.reply_to,NEWLINE mandatory=FalseNEWLINE )NEWLINENEWLINE message.ack()NEWLINENEWLINE def serialize(self, data: Any) -> bytes:NEWLINE """ Serialize data to the bytes.NEWLINE Uses `pickle` by default.NEWLINE You should overlap this method when you want to change serializerNEWLINENEWLINE :param data: Data which will be serializedNEWLINE :returns: bytesNEWLINE """NEWLINE return super().serialize(data)NEWLINENEWLINE def deserialize(self, data: Any) -> bytes:NEWLINE """ Deserialize data from bytes.NEWLINE Uses `pickle` by default.NEWLINE You should overlap this method when you want to change serializerNEWLINENEWLINE :param data: Data which will be deserializedNEWLINE :returns: :class:`Any`NEWLINE """NEWLINE return super().deserialize(data)NEWLINENEWLINE def serialize_exception(self, exception: Exception) -> bytes:NEWLINE """ Serialize python exception to bytesNEWLINENEWLINE :param exception: :class:`Exception`NEWLINE :return: bytesNEWLINE """NEWLINE return pickle.dumps(exception)NEWLINENEWLINE async def execute(self, func: CallbackType, payload: P) -> R:NEWLINE """ Executes rpc call. Might be overlapped. """NEWLINE return await func(**payload)NEWLINENEWLINE async def call(self, method_name, kwargs: dict=None, *,NEWLINE expiration: int=None, priority: int=128,NEWLINE delivery_mode: DeliveryMode=DELIVERY_MODE):NEWLINENEWLINE """ Call remote method and awaiting result.NEWLINENEWLINE :param method_name: Name of methodNEWLINE :param kwargs: Methos kwargsNEWLINE :param expiration:NEWLINE If not `None` messages which staying in queue longerNEWLINE will be returned and :class:`asyncio.TimeoutError` will be raised.NEWLINE :param priority: Message priorityNEWLINE :param delivery_mode: Call message delivery modeNEWLINE :raises asyncio.TimeoutError: when message expiredNEWLINE :raises CancelledError: when called :func:`RPC.cancel`NEWLINE :raises RuntimeError: internal errorNEWLINE """NEWLINENEWLINE future = self.create_future()NEWLINENEWLINE message = Message(NEWLINE body=self.serialize(kwargs or {}),NEWLINE type='call',NEWLINE timestamp=time.time(),NEWLINE priority=priority,NEWLINE correlation_id=id(future),NEWLINE delivery_mode=delivery_mode,NEWLINE reply_to=self.result_queue.name,NEWLINE headers={NEWLINE 'From': self.result_queue.nameNEWLINE }NEWLINE )NEWLINENEWLINE if expiration is not None:NEWLINE message.expiration = expirationNEWLINENEWLINE await self.channel.default_exchange.publish(NEWLINE message, routing_key=method_name, mandatory=TrueNEWLINE )NEWLINENEWLINE return await futureNEWLINENEWLINE async def register(self, method_name, func: CallbackType, **kwargs):NEWLINE """ Method creates a queue with name which equal ofNEWLINE `method_name` argument. Then subscribes this queue.NEWLINENEWLINE :param method_name: Method nameNEWLINE :param func:NEWLINE target function. Function **MUST** accept only keyword arguments.NEWLINE :param kwargs: arguments which will be passed to `queue_declare`NEWLINE :raises RuntimeError:NEWLINE Function already registered in this :class:`RPC` instanceNEWLINE or method_name already used.NEWLINE """NEWLINE arguments = kwargs.pop('arguments', {})NEWLINE arguments.update({NEWLINE 'x-dead-letter-exchange': self.DLX_NAME,NEWLINE })NEWLINENEWLINE kwargs['arguments'] = argumentsNEWLINENEWLINE queue = await self.channel.declare_queue(method_name, **kwargs)NEWLINENEWLINE if func in self.consumer_tags:NEWLINE raise RuntimeError('Function already registered')NEWLINENEWLINE if method_name in self.routes:NEWLINE raise RuntimeError(NEWLINE 'Method name already used for %r' % self.routes[method_name]NEWLINE )NEWLINENEWLINE self.consumer_tags[func] = await queue.consume(NEWLINE partial(self.on_call_message, method_name)NEWLINE )NEWLINENEWLINE self.routes[method_name] = asyncio.coroutine(func)NEWLINE self.queues[func] = queueNEWLINENEWLINE async def unregister(self, func):NEWLINE """ Cancels subscription to the method-queue.NEWLINENEWLINE :param func: FunctionNEWLINE """NEWLINE if func not in self.consumer_tags:NEWLINE returnNEWLINENEWLINE consumer_tag = self.consumer_tags.pop(func)NEWLINE queue = self.queues.pop(func)NEWLINENEWLINE await queue.cancel(consumer_tag)NEWLINENEWLINE self.routes.pop(queue.name)NEWLINE # Copyright 2020 Huawei Technologies Co., LtdNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE# ============================================================================NEWLINE"""FTRL"""NEWLINEfrom mindspore.ops import functional as F, composite as C, operations as PNEWLINEfrom mindspore.common import TensorNEWLINEimport mindspore.common.dtype as mstypeNEWLINEfrom mindspore._checkparam import Validator as validatorNEWLINEfrom mindspore._checkparam import RelNEWLINEfrom .optimizer import Optimizer, _apply_decay, _grad_scaleNEWLINENEWLINE_ftrl_opt = C.MultitypeFuncGraph("ftrl_opt")NEWLINENEWLINENEWLINE@_ftrl_opt.register("Function", "Function", "Function", "Function", "Number", "Number", "Number", "Tensor", "Tensor",NEWLINE "RowTensor", "Tensor", "Tensor", "Bool")NEWLINEdef _tensor_run_opt_with_sparse(opt, spars_opt, push, pull, l1, l2, lr_power, learning_rate, linear,NEWLINE gradient, weight, moment, ps_parameter):NEWLINE """Apply sparse ftrl optimizer to the weight parameter when the gradient is sparse."""NEWLINE success = TrueNEWLINE indices = gradient.indicesNEWLINE values = gradient.valuesNEWLINE if ps_parameter:NEWLINE op_shape = P.Shape()NEWLINE shapes = (op_shape(weight), op_shape(moment), op_shape(linear), op_shape(values), op_shape(indices))NEWLINE success = F.depend(success, pull(push((values, indices), shapes), weight))NEWLINE else:NEWLINE success = F.depend(success, spars_opt(weight, moment, linear, values, indices))NEWLINE return successNEWLINENEWLINENEWLINE@_ftrl_opt.register("Function", "Function", "Function", "Function", "Number", "Number", "Number", "Tensor", "Tensor",NEWLINE "Tensor", "Tensor", "Tensor", "Bool")NEWLINEdef _tensor_run_opt(opt, spars_opt, push, pull, l1, l2, lr_power, learning_rate, linear,NEWLINE gradient, weight, moment, ps_parameter):NEWLINE """Apply ftrl optimizer to the weight parameter."""NEWLINE success = TrueNEWLINE if ps_parameter:NEWLINE op_shape = P.Shape()NEWLINE success = F.depend(success, pull(push((gradient, learning_rate, l1, l2, lr_power),NEWLINE (op_shape(weight), op_shape(moment), op_shape(linear))), weight))NEWLINE else:NEWLINE success = F.depend(success, opt(weight, moment, linear, gradient, learning_rate, l1, l2, lr_power))NEWLINE return successNEWLINENEWLINENEWLINEdef _check_param(initial_accum, lr_power, l1, l2, use_locking, prim_name=None):NEWLINE """Check param."""NEWLINE validator.check_value_type("initial_accum", initial_accum, [float], prim_name)NEWLINE validator.check_number("initial_accum", initial_accum, 0.0, Rel.GE, prim_name)NEWLINENEWLINE validator.check_value_type("lr_power", lr_power, [float], prim_name)NEWLINE validator.check_number("lr_power", lr_power, 0.0, Rel.LE, prim_name)NEWLINENEWLINE validator.check_value_type("l1", l1, [float], prim_name)NEWLINE validator.check_number("l1", l1, 0.0, Rel.GE, prim_name)NEWLINENEWLINE validator.check_value_type("l2", l2, [float], prim_name)NEWLINE validator.check_number("l2", l2, 0.0, Rel.GE, prim_name)NEWLINENEWLINE validator.check_value_type("use_locking", use_locking, [bool], prim_name)NEWLINENEWLINENEWLINEclass FTRL(Optimizer):NEWLINE """NEWLINE Implement the FTRL algorithm with ApplyFtrl Operator.NEWLINENEWLINE FTRL is an online convex optimization algorithm that adaptively chooses its regularization functionNEWLINE based on the loss functions. Refer to paper `Adaptive Bound Optimization for Online Convex OptimizationNEWLINE `_. Refer to paper `Ad Click Prediction: a View from the TrenchesNEWLINE `_ for engineering document.NEWLINENEWLINE Note:NEWLINE When separating parameter groups, the weight decay in each group will be applied on the parameters if theNEWLINE weight decay is positive. When not separating parameter groups, the `weight_decay` in the API will be appliedNEWLINE on all of the parameters.NEWLINENEWLINE To improve parameter groups performance, the customized order of parameters can be supported.NEWLINENEWLINE The sparse strategy is applied while the SparseGatherV2 operator being used for forward network.NEWLINE The sparse feature is under continuous development. The sparse behavior is currently performed on the CPU.NEWLINENEWLINE Args:NEWLINE params (Union[list[Parameter], list[dict]]): When the `params` is a list of `Parameter` which will be updated,NEWLINE the element in `params` should be class `Parameter`. When the `params` is a list of `dict`, the "params",NEWLINE "lr", "weight_decay" and "order_params" are the keys can be parsed.NEWLINENEWLINE - params: Required. The value should be a list of `Parameter`.NEWLINENEWLINE - lr: Using different learning rate by separating parameters is currently not supported.NEWLINENEWLINE - weight_decay: Optional. If "weight_decay" in the keys, the value of corresponding weight decayNEWLINE will be used. If not, the `weight_decay` in the API will be used.NEWLINENEWLINE - order_params: Optional. If "order_params" in the keys, the value should be the order of parameters andNEWLINE the order will be followed in optimizer. There are no other keys in the `dict` and the parameters whichNEWLINE in the value of 'order_params' should be in one of group parameters.NEWLINENEWLINE initial_accum (float): The starting value for accumulators, must be zero or positive values. Default: 0.1.NEWLINE learning_rate (float): The learning rate value, should be zero or positive, dynamic learning rate is currentlyNEWLINE not supported. Default: 0.001.NEWLINE lr_power (float): Learning rate power controls how the learning rate decreases during training, must be lessNEWLINE than or equal to zero. Use fixed learning rate if lr_power is zero. Default: -0.5.NEWLINE l1 (float): l1 regularization strength, must be greater than or equal to zero. Default: 0.0.NEWLINE l2 (float): l2 regularization strength, must be greater than or equal to zero. Default: 0.0.NEWLINE use_locking (bool): If True use locks for update operation. Default: False.NEWLINE loss_scale (float): Value for the loss scale. It should be equal to or greater than 1.0. Default: 1.0.NEWLINE weight_decay (float): Weight decay value to multiply weight, must be zero or positive value. Default: 0.0.NEWLINENEWLINE Inputs:NEWLINE - **grads** (tuple[Tensor]) - The gradients of `params` in optimizer, the shape is as same as the `params`NEWLINE in optimizer.NEWLINENEWLINE Outputs:NEWLINE tuple[Parameter], the updated parameters, the shape is the same as `params`.NEWLINENEWLINE Examples:NEWLINE >>> net = Net()NEWLINE >>> #1) All parameters use the same learning rate and weight decayNEWLINE >>> optim = nn.FTRL(params=net.trainable_params())NEWLINE >>>NEWLINE >>> #2) Use parameter groups and set different valuesNEWLINE >>> conv_params = list(filter(lambda x: 'conv' in x.name, net.trainable_params()))NEWLINE >>> no_conv_params = list(filter(lambda x: 'conv' not in x.name, net.trainable_params()))NEWLINE >>> group_params = [{'params': conv_params, 'weight_decay': 0.01},NEWLINE >>> {'params': no_conv_params},NEWLINE >>> {'order_params': net.trainable_params()}]NEWLINE >>> optim = nn.FTRL(group_params, learning_rate=0.1, weight_decay=0.0)NEWLINE >>> # The conv_params's parameters will use weight decay of 0.01.NEWLINE >>> # The no_conv_params's parameters will use default weight decay of 0.0.NEWLINE >>> # The final parameters order in which the optimizer will be followed is the value of 'order_params'.NEWLINE >>>NEWLINE >>> loss = nn.SoftmaxCrossEntropyWithLogits()NEWLINE >>> model = Model(net, loss_fn=loss, optimizer=optim)NEWLINE """NEWLINE def __init__(self, params, initial_accum=0.1, learning_rate=0.001, lr_power=-0.5, l1=0.0, l2=0.0,NEWLINE use_locking=False, loss_scale=1.0, weight_decay=0.0):NEWLINE super(FTRL, self).__init__(learning_rate, params, weight_decay, loss_scale=loss_scale)NEWLINE if self.dynamic_lr or self.is_group_lr:NEWLINE raise ValueError('Dynamic learning rate or group learning rate is currently not supported.')NEWLINE _check_param(initial_accum, lr_power, l1, l2, use_locking, self.cls_name)NEWLINE self.moments = self.parameters.clone(prefix="moments", init=initial_accum)NEWLINE self.linear = self.parameters.clone(prefix="linear", init='zeros')NEWLINE self.l1 = l1NEWLINE self.l2 = l2NEWLINE self.lr_power = lr_powerNEWLINE if not self.is_group:NEWLINE self.decay_flags = tuple((lambda: True)() for x in self.parameters)NEWLINE self.hyper_map = C.HyperMap()NEWLINE self.opt = P.ApplyFtrl(use_locking=use_locking)NEWLINE self.sparse_opt = P.FusedSparseFtrl(learning_rate, l1, l2, lr_power, use_locking=use_locking)NEWLINE self._ps_pull = P.Pull()NEWLINE self._ps_push = P.Push("Ftrl", [0, 1, 2])NEWLINE self._ps_push.add_prim_attr("lr", learning_rate)NEWLINE self._ps_push.add_prim_attr("l1", l1)NEWLINE self._ps_push.add_prim_attr("l2", l2)NEWLINE self._ps_push.add_prim_attr("lr_power", lr_power)NEWLINENEWLINE def construct(self, grads):NEWLINE params = self.parametersNEWLINE moments = self.momentsNEWLINE linear = self.linearNEWLINE grads = self.decay_weight(grads)NEWLINE grads = self.scale_grad(grads)NEWLINE lr = self.get_lr()NEWLINENEWLINE success = self.map_(F.partial(_ftrl_opt, self.opt, self.sparse_opt, self._ps_push, self._ps_pull,NEWLINE self.l1, self.l2, self.lr_power, lr),NEWLINE linear, grads, params, moments, self.ps_parameters)NEWLINE return successNEWLINE # -*- coding: utf-8 -*-NEWLINE# Copyright 2020-2021 CERNNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE#NEWLINE# Authors:NEWLINE# - Cedric Serfon , 2020NEWLINE# - Eli Chadwick , 2020NEWLINE# - Martin Barisits , 2020-2021NEWLINE# - Benedikt Ziemons , 2020NEWLINENEWLINEfrom __future__ import print_functionNEWLINENEWLINEfrom rucio.api.permission import has_permissionNEWLINEfrom rucio.api.scope import list_scopesNEWLINENEWLINEfrom rucio.core.rse import get_rse_idNEWLINEfrom rucio.core import diracNEWLINEfrom rucio.common.exception import AccessDeniedNEWLINEfrom rucio.common.utils import extract_scopeNEWLINENEWLINENEWLINEdef add_files(lfns, issuer, ignore_availability):NEWLINE """NEWLINE Bulk add files :NEWLINE - Create the file and replica.NEWLINE - If doesn't exist create the dataset containing the file as well as a rule on the dataset on ANY sites.NEWLINE - Create all the ascendants of the dataset if they do not existNEWLINENEWLINE :param lfns: List of lfn (dictionary {'lfn': , 'rse': , 'bytes': , 'adler32': , 'guid': , 'pfn': }NEWLINE :param issuer: The issuer account.NEWLINE :param ignore_availability: A boolean to ignore blocked sites.NEWLINE """NEWLINE scopes = list_scopes()NEWLINE dids = []NEWLINE rses = {}NEWLINE for lfn in lfns:NEWLINE scope, name = extract_scope(lfn['lfn'], scopes)NEWLINE dids.append({'scope': scope, 'name': name})NEWLINE rse = lfn['rse']NEWLINE if rse not in rses:NEWLINE rse_id = get_rse_id(rse=rse)NEWLINE rses[rse] = rse_idNEWLINE lfn['rse_id'] = rses[rse]NEWLINENEWLINE # Check if the issuer can add dids and use skip_availabitlityNEWLINE for rse in rses:NEWLINE rse_id = rses[rse]NEWLINE kwargs = {'rse': rse, 'rse_id': rse_id}NEWLINE if not has_permission(issuer=issuer, action='add_replicas', kwargs=kwargs):NEWLINE raise AccessDenied('Account %s can not add file replicas on %s' % (issuer, rse))NEWLINE if not has_permission(issuer=issuer, action='skip_availability_check', kwargs=kwargs):NEWLINE ignore_availability = FalseNEWLINENEWLINE # Check if the issuer can add the filesNEWLINE kwargs = {'issuer': issuer, 'dids': dids}NEWLINE if not has_permission(issuer=issuer, action='add_dids', kwargs=kwargs):NEWLINE raise AccessDenied('Account %s can not bulk add data identifier' % (issuer))NEWLINENEWLINE dirac.add_files(lfns=lfns, account=issuer, ignore_availability=ignore_availability, session=None)NEWLINE import sysNEWLINEfrom esky import bdist_eskyNEWLINEfrom distutils.core import setupNEWLINE NEWLINE# for freezing with eskyNEWLINE# uncomment the block you want to run depending on your freezerNEWLINE# > python setup.py bdist_eskyNEWLINENEWLINE# Using py2exeNEWLINE#setup(NEWLINE# name = "example-app",NEWLINE# version = "0.2",NEWLINE# scripts = ["example.py"],NEWLINE# options = {"bdist_esky": {NEWLINE# "freezer_module":"py2exe",NEWLINE# }}NEWLINE#)NEWLINENEWLINE# Using py2appNEWLINE#setup(NEWLINE# name = "example-app",NEWLINE# version = "0.2",NEWLINE# scripts = ["example.py"],NEWLINE# options = {"bdist_esky": {NEWLINE# "freezer_module":"py2app"NEWLINE# }}NEWLINE# )NEWLINENEWLINE# cx freezeNEWLINEfrom esky.bdist_esky import ExecutableNEWLINEsetup(NEWLINE name = 'example-app',NEWLINE version = '0.2',NEWLINE #executables=[Executable('example.py')],NEWLINE options = {"bdist_esky": {NEWLINE "freezer_module":"cxfreeze"NEWLINE }},NEWLINE scripts = [Executable('example.py')],NEWLINE)NEWLINENEWLINE import cursesNEWLINEimport collectionsNEWLINEimport sysNEWLINEimport osNEWLINEfrom time import sleepNEWLINENEWLINE# File syntaxNEWLINE#NEWLINE# When there's not enough space for all elements UI will go into scroll modeNEWLINE#NEWLINE# Syntax:NEWLINE# script.py ui_example.txtNEWLINE#NEWLINE# an object is one line, split by ;NEWLINE# The first part is the Name the second part is the shell actionNEWLINE# Use the sample file to tweak colors.NEWLINE# Valid colors are: black, red, green, yellow, blue, magenta, cyan, whiteNEWLINE# Also valid colors are black2, red2, green2.. those are usually brighter versionsNEWLINE#NEWLINE# To run an inbuilt function just use an action as followed:NEWLINE# Show version;function:Show_versionNEWLINE#NEWLINE# To implement a quit button you can do so:NEWLINE# Quit menu;quitNEWLINE#NEWLINE# For more information check out the github readme: https://github.com/DiscordDigital/ui.py/NEWLINENEWLINEdef RunInbuiltFunction(function_name):NEWLINE if (function_name == "Show_version"):NEWLINE print("Running python version " + sys.version)NEWLINENEWLINEdef generate_sample_file():NEWLINE sample_file = open('sample_ui.txt','w')NEWLINE sample_file.write(NEWLINE """menutext=Sample UI!\nmaxh=3\ntitlecolor=white\nwindow_bg=blue\nobjcolor_text=white\nobjcolor_bg=blue\nobjcolor_sel_text=black\nobjcolor_sel_bg=white\nStart Nano;nano\nShow date;date\nCredits;echo Made by discord.digital\nShow Python version;function:Show_version\nQuit;quit"""NEWLINE )NEWLINE sample_file.close()NEWLINENEWLINEif len(sys.argv) != 2:NEWLINE print("Specify ui file")NEWLINE print("Get started by typing: " + sys.argv[0] + " sample")NEWLINE exit()NEWLINEelif (sys.argv[1] == "sample"):NEWLINE generate_sample_file()NEWLINE print("Created sample_ui.txt")NEWLINE print("Use it like that: " + sys.argv[0] + " sample_ui.txt")NEWLINE exit(0)NEWLINEelse:NEWLINE if not os.path.isfile(sys.argv[1]):NEWLINE print("File not found!")NEWLINE exit()NEWLINENEWLINEscreen = curses.initscr()NEWLINEcurses.curs_set(0)NEWLINEcurses.noecho()NEWLINEscreen.keypad(1)NEWLINEcurses.start_color()NEWLINEcurses.mousemask(1)NEWLINENEWLINEdef convert_text_to_color(text):NEWLINE textup = text.upper()NEWLINE if (textup == "BLACK"):NEWLINE return 0NEWLINE if (textup == "RED"):NEWLINE return 1NEWLINE if (textup == "GREEN"):NEWLINE return 2NEWLINE if (textup == "YELLOW"):NEWLINE return 3NEWLINE if (textup == "BLUE"):NEWLINE return 4NEWLINE if (textup == "MAGENTA"):NEWLINE return 5NEWLINE if (textup == "CYAN"):NEWLINE return 6NEWLINE if (textup == "WHITE"):NEWLINE return 7NEWLINE if (textup == "BLACK2"):NEWLINE return 8NEWLINE if (textup == "RED2"):NEWLINE return 9NEWLINE if (textup == "GREEN2"):NEWLINE return 10NEWLINE if (textup == "YELLOW2"):NEWLINE return 11NEWLINE if (textup == "BLUE2"):NEWLINE return 12NEWLINE if (textup == "MAGENTA2"):NEWLINE return 13NEWLINE if (textup == "CYAN2"):NEWLINE return 14NEWLINE if (textup == "WHITE2"):NEWLINE return 15NEWLINE NEWLINE return 7NEWLINENEWLINEobjects = collections.defaultdict(dict)NEWLINEobject_i = 0NEWLINEmenutext = "Menu"NEWLINEmaxh = 3NEWLINEtitlecolor = "white"NEWLINEwindow_bg = "black"NEWLINEobjcolor_text = "white"NEWLINEobjcolor_bg = "black"NEWLINEobjcolor_sel_text = "black"NEWLINEobjcolor_sel_bg = "white"NEWLINENEWLINEfp = open(sys.argv[1])NEWLINEfor _, line in enumerate(fp):NEWLINE if line.startswith("menutext="):NEWLINE menutext = line.replace('menutext=','').replace('\n','')NEWLINE elif line.startswith("maxh="):NEWLINE maxh = line.replace('maxh=','').replace('\n','')NEWLINE elif line.startswith("titlecolor="):NEWLINE titlecolor = line.replace('titlecolor=','').replace('\n','')NEWLINE elif line.startswith("window_bg="):NEWLINE window_bg = line.replace('window_bg=','').replace('\n','')NEWLINE elif line.startswith("objcolor_text="):NEWLINE objcolor_text = line.replace('objcolor_text=','').replace('\n','')NEWLINE elif line.startswith("objcolor_bg="):NEWLINE objcolor_bg = line.replace('objcolor_bg=','').replace('\n','')NEWLINE elif line.startswith("objcolor_sel_text="):NEWLINE objcolor_sel_text = line.replace('objcolor_sel_text=','').replace('\n','')NEWLINE elif line.startswith("objcolor_sel_bg="):NEWLINE objcolor_sel_bg = line.replace('objcolor_sel_bg=','').replace('\n','')NEWLINE else:NEWLINE if (line == '\n'):NEWLINE breakNEWLINE interface = line.split(';')NEWLINE objects[object_i]['Label'] = interface[0].replace('\n','')NEWLINE objects[object_i]['Action'] = interface[1].replace('\n','')NEWLINE object_i = object_i + 1NEWLINEfp.close()NEWLINENEWLINEcolorcode = convert_text_to_color(titlecolor)NEWLINEcolorcode_bg = convert_text_to_color(window_bg)NEWLINEcurses.init_pair(2, colorcode, colorcode_bg)NEWLINEcolorcode_text = convert_text_to_color(objcolor_text)NEWLINEcolorcode_bg = convert_text_to_color(objcolor_bg)NEWLINEcurses.init_pair(3, colorcode_text, colorcode_bg)NEWLINEcolorcode_text = convert_text_to_color(objcolor_sel_text)NEWLINEcolorcode_bg = convert_text_to_color(objcolor_sel_bg)NEWLINEcurses.init_pair(4, colorcode_text, colorcode_bg)NEWLINENEWLINEmaxh = int(maxh)NEWLINENEWLINEscreen.bkgd(' ', curses.color_pair(2))NEWLINENEWLINE_, x = screen.getmaxyx()NEWLINEtitlepad = curses.newpad(1, x-2)NEWLINEtitlepad.addstr(menutext, curses.color_pair(2))NEWLINEtitlepad.bkgd(' ', curses.color_pair(2) | curses.A_BOLD)NEWLINENEWLINEinfopad = curses.newpad(3, 15)NEWLINEinfopad.addstr("Press q to exit", curses.color_pair(2))NEWLINENEWLINEdef create_entry(text,startheight):NEWLINE _, x = screen.getmaxyx()NEWLINE pad = curses.newpad(maxh, x - 2)NEWLINE cheight = int(maxh / 2)NEWLINE tstart = int((x / 2) - (len(text) / 2))-1NEWLINE pad.addstr(cheight,tstart,text)NEWLINE pad.bkgd(' ', curses.color_pair(3))NEWLINE return padNEWLINENEWLINEdef select_entry(pad):NEWLINE global parseoffsetNEWLINE global selectNEWLINE global refreshlistNEWLINE global selectedpadNEWLINE global scrolldirectionNEWLINE global object_iNEWLINE global maxfitobjNEWLINE global resizeNEWLINE if (object_i > maxfitobj) or (parseoffset != 0):NEWLINE selectpad.erase()NEWLINE selectpad.resize(3,len(str(100) + "/") + len(str(object_i)))NEWLINE selectpad.addstr(str(select + 1) + "/" + str(object_i), curses.color_pair(2))NEWLINE selectpad.refresh(0, 0, 1, 2, 1, x-2)NEWLINE if (pad):NEWLINE if (selectedpad != None) and not (resize):NEWLINE deselect_entry(selectedpad)NEWLINE pad['pad'].bkgd(' ', curses.color_pair(4))NEWLINE cheight = int(maxh / 2)NEWLINE tstart = int((x / 2) - (len(pad['label']) / 2))-1NEWLINE pad['pad'].addstr(cheight,tstart,pad['label'])NEWLINE y, _ = pad['pad'].getbegyx()NEWLINE sy, sx = screen.getmaxyx()NEWLINE pad['pad'].refresh(0,0,y,1,sy,sx-2)NEWLINE selectedpad = padNEWLINE else:NEWLINE scrolldirection = "up"NEWLINE parseoffset = parseoffset - 1NEWLINE refreshlist = TrueNEWLINE screen.refresh() NEWLINENEWLINEdef deselect_entry(pad):NEWLINE pad['pad'].bkgd(' ', curses.color_pair(3))NEWLINE cheight = int(maxh / 2)NEWLINE tstart = int((x / 2) - (len(pad['label']) / 2))-1NEWLINE pad['pad'].addstr(cheight,tstart,pad['label'])NEWLINE y, _ = pad['pad'].getbegyx()NEWLINE sy, sx = screen.getmaxyx()NEWLINE pad['pad'].refresh(0,0,y,1,sy,sx-2)NEWLINE screen.refresh()NEWLINENEWLINEcurseLoop = TrueNEWLINEpads = FalseNEWLINEaction = FalseNEWLINEselect = 0NEWLINEselectedpad = NoneNEWLINEscroll = FalseNEWLINEparseoffset = 0NEWLINErefreshlist = FalseNEWLINEscrolldirection = "down"NEWLINENEWLINEseltext = "Selecting 0/0"NEWLINEselectpad = curses.newpad(3, len(seltext))NEWLINEselectpad.bkgd(' ', curses.color_pair(3))NEWLINENEWLINEy, x = screen.getmaxyx()NEWLINEscreensize = y - 4NEWLINEmaxfitobj = int(screensize / maxh)NEWLINENEWLINEwhile curseLoop:NEWLINE screen.refresh()NEWLINE resize = curses.is_term_resized(y, x)NEWLINE if resize is True:NEWLINE y, x = screen.getmaxyx()NEWLINE screen.clear()NEWLINE curses.resizeterm(y, x)NEWLINE screensize = y - 4NEWLINE maxfitobj = int(screensize / maxh)NEWLINE pads = FalseNEWLINE screen.refresh()NEWLINE else:NEWLINE try:NEWLINE titlepad.refresh(0, 0, 2, int((x/2)-(len(menutext)/2)), 2, x-2)NEWLINE infopad.refresh(0, 0, 1, x-17, 1, x-2)NEWLINE except:NEWLINE passNEWLINENEWLINE j = 4NEWLINE NEWLINE if (pads == False) or (refreshlist):NEWLINE pads = collections.defaultdict(dict)NEWLINENEWLINE if (object_i > maxfitobj):NEWLINE parserange = range(0 + parseoffset, maxfitobj + parseoffset)NEWLINE else:NEWLINE parserange = range(object_i)NEWLINE NEWLINE for i in parserange:NEWLINE pads[i]['pad'] = create_entry(objects[i]['Label'],j)NEWLINE try:NEWLINE pads[i]['pad'].refresh(0,0,j,1,y,x-2)NEWLINE except:NEWLINE passNEWLINE pads[i]['action'] = objects[i]['Action']NEWLINE pads[i]['label'] = objects[i]['Label']NEWLINE pads[i]['range-start'] = jNEWLINE pads[i]['range-end'] = j + maxhNEWLINE j = j + maxhNEWLINE if (refreshlist):NEWLINE if (scrolldirection == "down"):NEWLINE select = maxfitobj + parseoffset - 1NEWLINE select_entry(pads[select])NEWLINE if (scrolldirection == "up"):NEWLINE select = parseoffsetNEWLINE select_entry(pads[select])NEWLINE else:NEWLINE select = 0NEWLINE select_entry(pads[select])NEWLINE refreshlist = FalseNEWLINENEWLINE event = screen.getch()NEWLINE if event == ord("q"): breakNEWLINE if event == curses.KEY_MOUSE:NEWLINE try:NEWLINE _, _, my, _, _ = curses.getmouse()NEWLINE if (object_i > maxfitobj):NEWLINE parserange = range(0 + parseoffset, maxfitobj + parseoffset)NEWLINE else:NEWLINE parserange = range(object_i)NEWLINE for i in parserange:NEWLINE if (my >= pads[i]['range-start']) and (my < pads[i]['range-end']):NEWLINE if (selectedpad != None):NEWLINE deselect_entry(selectedpad)NEWLINE select_entry(pads[i])NEWLINE action = pads[i]['action']NEWLINE y, _ = pads[i]['pad'].getbegyx()NEWLINE sy, sx = screen.getmaxyx()NEWLINE pads[i]['pad'].refresh(0,0,y,1,sy,sx-2)NEWLINE sleep(0.2)NEWLINE curseLoop = FalseNEWLINE except:NEWLINE passNEWLINE if event == curses.KEY_UP:NEWLINE if (selectedpad == None):NEWLINE select = 0NEWLINE select_entry(pads[select])NEWLINE if (select != 0):NEWLINE select = select - 1NEWLINE select_entry(pads[select])NEWLINENEWLINE if event == curses.KEY_DOWN:NEWLINE if (selectedpad != None):NEWLINE if (select != maxfitobj + parseoffset - 1):NEWLINE if not (select == object_i - 1):NEWLINE select = select + 1NEWLINE deselect_entry(selectedpad)NEWLINE select_entry(pads[select])NEWLINE else:NEWLINE if (select == maxfitobj + parseoffset - 1):NEWLINE if (select != object_i - 1):NEWLINE select = select + 1NEWLINE parseoffset = parseoffset + 1NEWLINE scrolldirection = "down"NEWLINE refreshlist = TrueNEWLINE else:NEWLINE if (object_i == 1):NEWLINE select = 0NEWLINE select_entry(pads[select])NEWLINE else:NEWLINE select = 1NEWLINE select_entry(pads[select])NEWLINE if event == 10:NEWLINE if (selectedpad != None):NEWLINE action = objects[select]['Action']NEWLINE curseLoop = FalseNEWLINEcurses.endwin()NEWLINEsleep(0.1)NEWLINEif (action):NEWLINE if action.startswith("function:"):NEWLINE function = action.split(":")[1]NEWLINE RunInbuiltFunction(function)NEWLINE elif (action == "quit"):NEWLINE exit()NEWLINE else:NEWLINE os.system(action)NEWLINE #! /usr/vin/env pythonNEWLINE# -*-coding:utf8-*-NEWLINENEWLINEfrom collections import OrderedDictNEWLINENEWLINENEWLINEclass LRUCache(OrderedDict):NEWLINE '''不能存储可变类型对象,不能并发访问set()''' NEWLINENEWLINE def __init__(self,capacity):NEWLINE self.capacity = capacityNEWLINE self.cache = OrderedDict()NEWLINENEWLINENEWLINE def get(self,key):NEWLINE if self.cache.has_key(key):NEWLINE value = self.cache.pop(key)NEWLINE self.cache[key] = valueNEWLINE else:NEWLINE value = NoneNEWLINENEWLINE return valueNEWLINENEWLINENEWLINE def set(self,key,value):NEWLINE if self.cache.has_key(key):NEWLINE value = self.cache.pop(key)NEWLINE self.cache[key] = valueNEWLINE else:NEWLINE if len(self.cache) == self.capacity:NEWLINE self.cache.popitem(last = False) #pop出第一个itemNEWLINE self.cache[key] = valueNEWLINE else:NEWLINE self.cache[key] = valueNEWLINE # Copyright 2018 The TensorFlow Probability Authors.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE# ============================================================================NEWLINE"""Tests for VariationalGaussianProcess."""NEWLINENEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import print_functionNEWLINENEWLINE# Dependency importsNEWLINEimport numpy as npNEWLINENEWLINEimport tensorflow.compat.v1 as tf1NEWLINEimport tensorflow.compat.v2 as tfNEWLINENEWLINEfrom tensorflow_probability import distributions as tfdNEWLINEfrom tensorflow_probability import positive_semidefinite_kernels as psd_kernelsNEWLINEfrom tensorflow_probability.python.internal import tensorshape_utilNEWLINEfrom tensorflow_probability.python.internal import test_utilNEWLINENEWLINENEWLINEdef _np_kernel_matrix_fn(amp, length_scale, x, y):NEWLINE x = np.expand_dims(x, -2)[..., 0]NEWLINE y = np.expand_dims(y, -3)[..., 0]NEWLINE return amp ** 2 * np.exp(-.5 * ((x - y)**2) / (length_scale**2))NEWLINENEWLINENEWLINE# TODO(cgs, srvasude): Figure out good tests for correctness for VGP, and addNEWLINE# them here.NEWLINE# Potential start is constructing kernels for which the Nystrom approximation isNEWLINE# almost exact. This imples the VGP replicates the GP.NEWLINEclass _VariationalGaussianProcessTest(object):NEWLINENEWLINE def testShapes(self):NEWLINE # 5x5 grid of index points in R^2 and flatten to 25x2NEWLINE index_points = np.linspace(-4., 4., 5, dtype=np.float64)NEWLINE index_points = np.stack(np.meshgrid(index_points, index_points), axis=-1)NEWLINE index_points = np.reshape(index_points, [-1, 2])NEWLINE # ==> shape = [25, 2]NEWLINE batched_index_points = np.expand_dims(np.stack([index_points]*6), -3)NEWLINE # ==> shape = [6, 1, 25, 2]NEWLINENEWLINE # 9 inducing index points in R^2NEWLINE inducing_index_points = np.linspace(-4., 4., 3, dtype=np.float64)NEWLINE inducing_index_points = np.stack(np.meshgrid(inducing_index_points,NEWLINE inducing_index_points),NEWLINE axis=-1)NEWLINE inducing_index_points = np.reshape(inducing_index_points, [-1, 2])NEWLINE # ==> shape = [9, 2]NEWLINENEWLINE variational_inducing_observations_loc = np.zeros([3, 9], dtype=np.float64)NEWLINE variational_inducing_observations_scale = np.eye(9, dtype=np.float64)NEWLINENEWLINE # Kernel with batch_shape [2, 4, 1, 1]NEWLINE amplitude = np.array([1., 2.], np.float64).reshape([2, 1, 1, 1])NEWLINE length_scale = np.array([.1, .2, .3, .4], np.float64).reshape([1, 4, 1, 1])NEWLINENEWLINE jitter = np.float64(1e-6)NEWLINE observation_noise_variance = np.float64(1e-2)NEWLINENEWLINE if not self.is_static:NEWLINE amplitude = tf1.placeholder_with_default(amplitude, shape=None)NEWLINE length_scale = tf1.placeholder_with_default(length_scale, shape=None)NEWLINE batched_index_points = tf1.placeholder_with_default(NEWLINE batched_index_points, shape=None)NEWLINENEWLINE inducing_index_points = tf1.placeholder_with_default(NEWLINE inducing_index_points, shape=None)NEWLINE variational_inducing_observations_loc = tf1.placeholder_with_default(NEWLINE variational_inducing_observations_loc, shape=None)NEWLINE variational_inducing_observations_scale = tf1.placeholder_with_default(NEWLINE variational_inducing_observations_scale, shape=None)NEWLINENEWLINE kernel = psd_kernels.ExponentiatedQuadratic(amplitude, length_scale)NEWLINENEWLINE vgp = tfd.VariationalGaussianProcess(NEWLINE kernel=kernel,NEWLINE index_points=batched_index_points,NEWLINE inducing_index_points=inducing_index_points,NEWLINE variational_inducing_observations_loc=(NEWLINE variational_inducing_observations_loc),NEWLINE variational_inducing_observations_scale=(NEWLINE variational_inducing_observations_scale),NEWLINE observation_noise_variance=observation_noise_variance,NEWLINE jitter=jitter)NEWLINENEWLINE batch_shape = [2, 4, 6, 3]NEWLINE event_shape = [25]NEWLINE sample_shape = [9, 3]NEWLINENEWLINE samples = vgp.sample(sample_shape)NEWLINENEWLINE if self.is_static or tf.executing_eagerly():NEWLINE self.assertAllEqual(vgp.batch_shape_tensor(), batch_shape)NEWLINE self.assertAllEqual(vgp.event_shape_tensor(), event_shape)NEWLINE self.assertAllEqual(samples.shape,NEWLINE sample_shape + batch_shape + event_shape)NEWLINE self.assertAllEqual(vgp.batch_shape, batch_shape)NEWLINE self.assertAllEqual(vgp.event_shape, event_shape)NEWLINE self.assertAllEqual(samples.shape,NEWLINE sample_shape + batch_shape + event_shape)NEWLINE else:NEWLINE self.assertAllEqual(self.evaluate(vgp.batch_shape_tensor()), batch_shape)NEWLINE self.assertAllEqual(self.evaluate(vgp.event_shape_tensor()), event_shape)NEWLINE self.assertAllEqual(self.evaluate(samples).shape,NEWLINE sample_shape + batch_shape + event_shape)NEWLINE self.assertIsNone(tensorshape_util.rank(samples.shape))NEWLINE self.assertIsNone(tensorshape_util.rank(vgp.batch_shape))NEWLINE self.assertEqual(tensorshape_util.rank(vgp.event_shape), 1)NEWLINE self.assertIsNone(NEWLINE tf.compat.dimension_value(tensorshape_util.dims(vgp.event_shape)[0]))NEWLINENEWLINE def testOptimalVariationalShapes(self):NEWLINE # 5x5 grid of observation index points in R^2 and flatten to 25x2NEWLINE observation_index_points = np.linspace(-4., 4., 5, dtype=np.float64)NEWLINE observation_index_points = np.stack(NEWLINE np.meshgrid(NEWLINE observation_index_points, observation_index_points), axis=-1)NEWLINE observation_index_points = np.reshape(NEWLINE observation_index_points, [-1, 2])NEWLINE # ==> shape = [25, 2]NEWLINE observation_index_points = np.expand_dims(NEWLINE np.stack([observation_index_points]*6), -3)NEWLINE # ==> shape = [6, 1, 25, 2]NEWLINE observations = np.sin(observation_index_points[..., 0])NEWLINE # ==> shape = [6, 1, 25]NEWLINENEWLINE # 9 inducing index points in R^2NEWLINE inducing_index_points = np.linspace(-4., 4., 3, dtype=np.float64)NEWLINE inducing_index_points = np.stack(np.meshgrid(inducing_index_points,NEWLINE inducing_index_points),NEWLINE axis=-1)NEWLINE inducing_index_points = np.reshape(inducing_index_points, [-1, 2])NEWLINE # ==> shape = [9, 2]NEWLINENEWLINE # Kernel with batch_shape [2, 4, 1, 1]NEWLINE amplitude = np.array([1., 2.], np.float64).reshape([2, 1, 1, 1])NEWLINE length_scale = np.array([.1, .2, .3, .4], np.float64).reshape([1, 4, 1, 1])NEWLINENEWLINE jitter = np.float64(1e-6)NEWLINE observation_noise_variance = np.float64(1e-2)NEWLINENEWLINE if not self.is_static:NEWLINE amplitude = tf1.placeholder_with_default(amplitude, shape=None)NEWLINE length_scale = tf1.placeholder_with_default(length_scale, shape=None)NEWLINE observation_index_points = tf1.placeholder_with_default(NEWLINE observation_index_points, shape=None)NEWLINENEWLINE inducing_index_points = tf1.placeholder_with_default(NEWLINE inducing_index_points, shape=None)NEWLINE kernel = psd_kernels.ExponentiatedQuadratic(amplitude, length_scale)NEWLINENEWLINE loc, scale = tfd.VariationalGaussianProcess.optimal_variational_posterior(NEWLINE kernel=kernel,NEWLINE inducing_index_points=inducing_index_points,NEWLINE observation_index_points=observation_index_points,NEWLINE observations=observations,NEWLINE observation_noise_variance=observation_noise_variance,NEWLINE jitter=jitter,NEWLINE )NEWLINE # We should expect that loc has shape [2, 4, 6, 1, 9]. This is because:NEWLINE # * [2, 4] comes from the batch shape of the kernel.NEWLINE # * [6, 1] comes from the batch shape of the observations / observationNEWLINE # index points.NEWLINE # * [9] comes from the number of inducing points.NEWLINE # Similar reasoning applies to scale.NEWLINE self.assertAllEqual([2, 4, 6, 1, 9], tf.shape(input=loc))NEWLINE self.assertAllEqual([2, 4, 6, 1, 9, 9], tf.shape(input=scale))NEWLINENEWLINE def testVariationalLossShapes(self):NEWLINE # 2x2 grid of index points in R^2 and flatten to 4x2NEWLINE index_points = np.linspace(-4., 4., 2, dtype=np.float64)NEWLINE index_points = np.stack(np.meshgrid(index_points, index_points), axis=-1)NEWLINE index_points = np.reshape(index_points, [-1, 2])NEWLINE # ==> shape = [4, 2]NEWLINE batched_index_points = np.expand_dims(np.stack([index_points]*6), -3)NEWLINE # ==> shape = [6, 1, 4, 2]NEWLINENEWLINE # 3x3 grid of index points in R^2 and flatten to 9x2NEWLINE observation_index_points = np.linspace(-4., 4., 3, dtype=np.float64)NEWLINE observation_index_points = np.stack(NEWLINE np.meshgrid(NEWLINE observation_index_points, observation_index_points), axis=-1)NEWLINE observation_index_points = np.reshape(NEWLINE observation_index_points, [-1, 2])NEWLINE # ==> shape = [9, 2]NEWLINE observation_index_points = np.expand_dims(NEWLINE np.stack([observation_index_points]*6), -3)NEWLINE # ==> shape = [6, 1, 9, 2]NEWLINE observations = np.sin(observation_index_points[..., 0])NEWLINE # ==> shape = [6, 1, 9]NEWLINENEWLINE # 9 inducing index points in R^2NEWLINE inducing_index_points = np.linspace(-4., 4., 3, dtype=np.float64)NEWLINE inducing_index_points = np.stack(np.meshgrid(inducing_index_points,NEWLINE inducing_index_points),NEWLINE axis=-1)NEWLINE inducing_index_points = np.reshape(inducing_index_points, [-1, 2])NEWLINE # ==> shape = [9, 2]NEWLINENEWLINE variational_inducing_observations_loc = np.zeros([3, 9], dtype=np.float64)NEWLINE variational_inducing_observations_scale = np.eye(9, dtype=np.float64)NEWLINENEWLINE # Kernel with batch_shape [2, 4, 1, 1]NEWLINE amplitude = np.array([1., 2.], np.float64).reshape([2, 1, 1, 1])NEWLINE length_scale = np.array([.1, .2, .3, .4], np.float64).reshape([1, 4, 1, 1])NEWLINENEWLINE jitter = np.float64(1e-6)NEWLINE observation_noise_variance = np.float64(1e-2)NEWLINENEWLINE if not self.is_static:NEWLINE amplitude = tf1.placeholder_with_default(amplitude, shape=None)NEWLINE length_scale = tf1.placeholder_with_default(length_scale, shape=None)NEWLINE batched_index_points = tf1.placeholder_with_default(NEWLINE batched_index_points, shape=None)NEWLINENEWLINE observations = tf1.placeholder_with_default(observations, shape=None)NEWLINE observation_index_points = tf1.placeholder_with_default(NEWLINE observation_index_points, shape=None)NEWLINE inducing_index_points = tf1.placeholder_with_default(NEWLINE inducing_index_points, shape=None)NEWLINE variational_inducing_observations_loc = tf1.placeholder_with_default(NEWLINE variational_inducing_observations_loc, shape=None)NEWLINE variational_inducing_observations_scale = tf1.placeholder_with_default(NEWLINE variational_inducing_observations_scale, shape=None)NEWLINENEWLINE kernel = psd_kernels.ExponentiatedQuadratic(amplitude, length_scale)NEWLINENEWLINE vgp = tfd.VariationalGaussianProcess(NEWLINE kernel=kernel,NEWLINE index_points=batched_index_points,NEWLINE inducing_index_points=inducing_index_points,NEWLINE variational_inducing_observations_loc=(NEWLINE variational_inducing_observations_loc),NEWLINE variational_inducing_observations_scale=(NEWLINE variational_inducing_observations_scale),NEWLINE observation_noise_variance=observation_noise_variance,NEWLINE jitter=jitter)NEWLINENEWLINE loss = vgp.variational_loss(NEWLINE observations=observations,NEWLINE observation_index_points=observation_index_points)NEWLINE # Expect a scalar loss.NEWLINE self.assertAllClose([], tf.shape(input=loss))NEWLINENEWLINENEWLINE@test_util.test_all_tf_execution_regimesNEWLINEclass VariationalGaussianProcessStaticTest(NEWLINE _VariationalGaussianProcessTest, test_util.TestCase):NEWLINE is_static = TrueNEWLINENEWLINENEWLINE@test_util.test_all_tf_execution_regimesNEWLINEclass VariationalGaussianProcessDynamicTest(NEWLINE _VariationalGaussianProcessTest, test_util.TestCase):NEWLINE is_static = FalseNEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE tf.test.main()NEWLINE #!/usr/bin/env pythonNEWLINE# Copyright (c) 2011 Google Inc. All rights reserved.NEWLINE#NEWLINE# Redistribution and use in source and binary forms, with or withoutNEWLINE# modification, are permitted provided that the following conditions areNEWLINE# met:NEWLINE#NEWLINE# * Redistributions of source code must retain the above copyrightNEWLINE# notice, this list of conditions and the following disclaimer.NEWLINE# * Redistributions in binary form must reproduce the aboveNEWLINE# copyright notice, this list of conditions and the following disclaimerNEWLINE# in the documentation and/or other materials provided with theNEWLINE# distribution.NEWLINE# * Neither the name of Google Inc. nor the names of itsNEWLINE# contributors may be used to endorse or promote products derived fromNEWLINE# this software without specific prior written permission.NEWLINE#NEWLINE# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORSNEWLINE# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOTNEWLINE# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FORNEWLINE# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHTNEWLINE# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,NEWLINE# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOTNEWLINE# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,NEWLINE# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANYNEWLINE# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORTNEWLINE# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USENEWLINE# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.NEWLINENEWLINEimport osNEWLINEimport reNEWLINEtry:NEWLINE import jsonNEWLINEexcept ImportError:NEWLINE import simplejson as jsonNEWLINENEWLINEtype_traits = {NEWLINE "any": "*",NEWLINE "string": "string",NEWLINE "integer": "number",NEWLINE "number": "number",NEWLINE "boolean": "boolean",NEWLINE "array": "!Array.<*>",NEWLINE "object": "!Object",NEWLINE}NEWLINENEWLINEpromisified_domains = {NEWLINE "Accessibility",NEWLINE "Animation",NEWLINE "CSS",NEWLINE "Emulation",NEWLINE "Profiler"NEWLINE}NEWLINENEWLINEref_types = {}NEWLINENEWLINEdef full_qualified_type_id(domain_name, type_id):NEWLINE if type_id.find(".") == -1:NEWLINE return "%s.%s" % (domain_name, type_id)NEWLINE return type_idNEWLINENEWLINENEWLINEdef fix_camel_case(name):NEWLINE refined = re.sub(r'-(\w)', lambda pat: pat.group(1).upper(), name)NEWLINE refined = to_title_case(refined)NEWLINE return re.sub(r'(?i)HTML|XML|WML|API', lambda pat: pat.group(0).upper(), refined)NEWLINENEWLINENEWLINEdef to_title_case(name):NEWLINE return name[:1].upper() + name[1:]NEWLINENEWLINENEWLINEdef generate_enum(name, json):NEWLINE enum_members = []NEWLINE for member in json["enum"]:NEWLINE enum_members.append(" %s: \"%s\"" % (fix_camel_case(member), member))NEWLINE return "\n/** @enum {string} */\n%s = {\n%s\n};\n" % (name, (",\n".join(enum_members)))NEWLINENEWLINENEWLINEdef param_type(domain_name, param):NEWLINE if "type" in param:NEWLINE if param["type"] == "array":NEWLINE items = param["items"]NEWLINE return "!Array.<%s>" % param_type(domain_name, items)NEWLINE else:NEWLINE return type_traits[param["type"]]NEWLINE if "$ref" in param:NEWLINE type_id = full_qualified_type_id(domain_name, param["$ref"])NEWLINE if type_id in ref_types:NEWLINE return ref_types[type_id]NEWLINE else:NEWLINE print "Type not found: " + type_idNEWLINE return "!! Type not found: " + type_idNEWLINENEWLINENEWLINEdef load_schema(file, domains):NEWLINE input_file = open(file, "r")NEWLINE json_string = input_file.read()NEWLINE parsed_json = json.loads(json_string)NEWLINE domains.extend(parsed_json["domains"])NEWLINENEWLINENEWLINEdef generate_protocol_externs(output_path, file1, file2):NEWLINE domains = []NEWLINE load_schema(file1, domains)NEWLINE load_schema(file2, domains)NEWLINE output_file = open(output_path, "w")NEWLINENEWLINE output_file.write(NEWLINE"""NEWLINEvar InspectorBackend = {}NEWLINENEWLINEvar Protocol = {};NEWLINE/** @typedef {string}*/NEWLINEProtocol.Error;NEWLINE""")NEWLINENEWLINE for domain in domains:NEWLINE domain_name = domain["domain"]NEWLINE if "types" in domain:NEWLINE for type in domain["types"]:NEWLINE type_id = full_qualified_type_id(domain_name, type["id"])NEWLINE ref_types[type_id] = "%sAgent.%s" % (domain_name, type["id"])NEWLINENEWLINE for domain in domains:NEWLINE domain_name = domain["domain"]NEWLINE promisified = domain_name in promisified_domainsNEWLINENEWLINE output_file.write("\n\n/**\n * @constructor\n*/\n")NEWLINE output_file.write("Protocol.%sAgent = function(){};\n" % domain_name)NEWLINENEWLINE if "commands" in domain:NEWLINE for command in domain["commands"]:NEWLINE output_file.write("\n/**\n")NEWLINE params = []NEWLINE has_return_value = "returns" in commandNEWLINE explicit_parameters = promisified and has_return_valueNEWLINE if ("parameters" in command):NEWLINE for in_param in command["parameters"]:NEWLINE # All parameters are not optional in case of promisified domain with return value.NEWLINE if (not explicit_parameters and "optional" in in_param):NEWLINE params.append("opt_%s" % in_param["name"])NEWLINE output_file.write(" * @param {%s=} opt_%s\n" % (param_type(domain_name, in_param), in_param["name"]))NEWLINE else:NEWLINE params.append(in_param["name"])NEWLINE output_file.write(" * @param {%s} %s\n" % (param_type(domain_name, in_param), in_param["name"]))NEWLINE returns = []NEWLINE returns.append("?Protocol.Error")NEWLINE if ("error" in command):NEWLINE returns.append("%s=" % param_type(domain_name, command["error"]))NEWLINE if (has_return_value):NEWLINE for out_param in command["returns"]:NEWLINE if ("optional" in out_param):NEWLINE returns.append("%s=" % param_type(domain_name, out_param))NEWLINE else:NEWLINE returns.append("%s" % param_type(domain_name, out_param))NEWLINE callback_return_type = "void="NEWLINE if explicit_parameters:NEWLINE callback_return_type = "T"NEWLINE elif promisified:NEWLINE callback_return_type = "T="NEWLINE output_file.write(" * @param {function(%s):%s} opt_callback\n" % (", ".join(returns), callback_return_type))NEWLINE if (promisified):NEWLINE output_file.write(" * @return {!Promise.}\n")NEWLINE output_file.write(" * @template T\n")NEWLINE params.append("opt_callback")NEWLINENEWLINE output_file.write(" */\n")NEWLINE output_file.write("Protocol.%sAgent.prototype.%s = function(%s) {}\n" % (domain_name, command["name"], ", ".join(params)))NEWLINE output_file.write("/** @param {function(%s):void=} opt_callback */\n" % ", ".join(returns))NEWLINE output_file.write("Protocol.%sAgent.prototype.invoke_%s = function(obj, opt_callback) {}\n" % (domain_name, command["name"]))NEWLINENEWLINE output_file.write("\n\n\nvar %sAgent = function(){};\n" % domain_name)NEWLINENEWLINE if "types" in domain:NEWLINE for type in domain["types"]:NEWLINE if type["type"] == "object":NEWLINE typedef_args = []NEWLINE if "properties" in type:NEWLINE for property in type["properties"]:NEWLINE suffix = ""NEWLINE if ("optional" in property):NEWLINE suffix = "|undefined"NEWLINE if "enum" in property:NEWLINE enum_name = "%sAgent.%s%s" % (domain_name, type["id"], to_title_case(property["name"]))NEWLINE output_file.write(generate_enum(enum_name, property))NEWLINE typedef_args.append("%s:(%s%s)" % (property["name"], enum_name, suffix))NEWLINE else:NEWLINE typedef_args.append("%s:(%s%s)" % (property["name"], param_type(domain_name, property), suffix))NEWLINE if (typedef_args):NEWLINE output_file.write("\n/** @typedef {!{%s}} */\n%sAgent.%s;\n" % (", ".join(typedef_args), domain_name, type["id"]))NEWLINE else:NEWLINE output_file.write("\n/** @typedef {!Object} */\n%sAgent.%s;\n" % (domain_name, type["id"]))NEWLINE elif type["type"] == "string" and "enum" in type:NEWLINE output_file.write(generate_enum("%sAgent.%s" % (domain_name, type["id"]), type))NEWLINE elif type["type"] == "array":NEWLINE output_file.write("\n/** @typedef {!Array.} */\n%sAgent.%s;\n" % (param_type(domain_name, type["items"]), domain_name, type["id"]))NEWLINE else:NEWLINE output_file.write("\n/** @typedef {%s} */\n%sAgent.%s;\n" % (type_traits[type["type"]], domain_name, type["id"]))NEWLINENEWLINE output_file.write("/** @interface */\n")NEWLINE output_file.write("%sAgent.Dispatcher = function() {};\n" % domain_name)NEWLINE if "events" in domain:NEWLINE for event in domain["events"]:NEWLINE params = []NEWLINE if ("parameters" in event):NEWLINE output_file.write("/**\n")NEWLINE for param in event["parameters"]:NEWLINE if ("optional" in param):NEWLINE params.append("opt_%s" % param["name"])NEWLINE output_file.write(" * @param {%s=} opt_%s\n" % (param_type(domain_name, param), param["name"]))NEWLINE else:NEWLINE params.append(param["name"])NEWLINE output_file.write(" * @param {%s} %s\n" % (param_type(domain_name, param), param["name"]))NEWLINE output_file.write(" */\n")NEWLINE output_file.write("%sAgent.Dispatcher.prototype.%s = function(%s) {};\n" % (domain_name, event["name"], ", ".join(params)))NEWLINENEWLINE output_file.write("\n/** @constructor\n * @param {!Object.} agentsMap\n */\n")NEWLINE output_file.write("Protocol.Agents = function(agentsMap){this._agentsMap;};\n")NEWLINE output_file.write("/**\n * @param {string} domain\n * @param {!Object} dispatcher\n */\n")NEWLINE output_file.write("Protocol.Agents.prototype.registerDispatcher = function(domain, dispatcher){};\n")NEWLINE for domain in domains:NEWLINE domain_name = domain["domain"]NEWLINE uppercase_length = 0NEWLINE while uppercase_length < len(domain_name) and domain_name[uppercase_length].isupper():NEWLINE uppercase_length += 1NEWLINENEWLINE output_file.write("/** @return {!Protocol.%sAgent}*/\n" % domain_name)NEWLINE output_file.write("Protocol.Agents.prototype.%s = function(){};\n" % (domain_name[:uppercase_length].lower() + domain_name[uppercase_length:] + "Agent"))NEWLINENEWLINE output_file.write("/**\n * @param {!%sAgent.Dispatcher} dispatcher\n */\n" % domain_name)NEWLINE output_file.write("Protocol.Agents.prototype.register%sDispatcher = function(dispatcher) {}\n" % domain_name)NEWLINENEWLINENEWLINE output_file.close()NEWLINENEWLINEif __name__ == "__main__":NEWLINE import sysNEWLINE import os.pathNEWLINE program_name = os.path.basename(__file__)NEWLINE if len(sys.argv) < 5 or sys.argv[1] != "-o":NEWLINE sys.stderr.write("Usage: %s -o OUTPUT_FILE INPUT_FILE_1 INPUT_FILE_2\n" % program_name)NEWLINE exit(1)NEWLINE output_path = sys.argv[2]NEWLINE input_path_1 = sys.argv[3]NEWLINE input_path_2 = sys.argv[4]NEWLINE generate_protocol_externs(output_path, input_path_1, input_path_2)NEWLINE """Testing handling with CoreState."""NEWLINENEWLINEfrom supervisor.coresys import CoreSysNEWLINENEWLINENEWLINEasync def test_timezone(run_dir, coresys: CoreSys):NEWLINE """Test write corestate to /run/supervisor."""NEWLINENEWLINE assert coresys.timezone == "UTC"NEWLINE assert coresys.config.timezone is NoneNEWLINENEWLINE await coresys.dbus.timedate.connect()NEWLINE await coresys.dbus.timedate.update()NEWLINE assert coresys.timezone == "Etc/UTC"NEWLINENEWLINE coresys.config.timezone = "Europe/Zurich"NEWLINE assert coresys.timezone == "Europe/Zurich"NEWLINE import abcNEWLINEimport numpy as npNEWLINENEWLINEfrom . import _base_modelNEWLINENEWLINENEWLINEclass SklearnModel(_base_model.BaseModel, abc.ABC):NEWLINE """NEWLINE Parent class based on :obj:`~easyPheno.model._base_model.BaseModel` for all models with a sklearn-like API to shareNEWLINE functionalities. See :obj:`~easyPheno.model._base_model.BaseModel` for more information.NEWLINENEWLINE **Attributes**NEWLINENEWLINE *Inherited attributes*NEWLINENEWLINE See :obj:`~easyPheno.model._base_model.BaseModel`NEWLINE """NEWLINENEWLINE def retrain(self, X_retrain: np.array, y_retrain: np.array):NEWLINE """NEWLINE Implementation of the retraining for models with sklearn-like API.NEWLINE See :obj:`~easyPheno.model._base_model.BaseModel` for more information.NEWLINE """NEWLINE self.model.fit(X_retrain, np.ravel(y_retrain))NEWLINENEWLINE def predict(self, X_in: np.array) -> np.array:NEWLINE """NEWLINE Implementation of a prediction based on input features for models with sklearn-like API.NEWLINE See :obj:`~easyPheno.model._base_model.BaseModel` for more information.NEWLINE """NEWLINE return np.reshape(self.model.predict(X_in), (-1, 1))NEWLINENEWLINE def train_val_loop(self, X_train: np.array, y_train: np.array, X_val: np.array, y_val: np.array) -> np.array:NEWLINE """NEWLINE Implementation of a train and validation loop for models with sklearn-like API.NEWLINE See :obj:`~easyPheno.model._base_model.BaseModel` for more information.NEWLINE """NEWLINE self.model.fit(X_train, np.ravel(y_train))NEWLINE return self.predict(X_in=X_val)NEWLINE # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-NEWLINE#NEWLINE# Copyright 2002 Ben Escoto NEWLINE# Copyright 2007 Kenneth Loafman NEWLINE#NEWLINE# This file is part of duplicity.NEWLINE#NEWLINE# Duplicity is free software; you can redistribute it and/or modify itNEWLINE# under the terms of the GNU General Public License as published by theNEWLINE# Free Software Foundation; either version 2 of the License, or (at yourNEWLINE# option) any later version.NEWLINE#NEWLINE# Duplicity is distributed in the hope that it will be useful, butNEWLINE# WITHOUT ANY WARRANTY; without even the implied warranty ofNEWLINE# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNUNEWLINE# General Public License for more details.NEWLINE#NEWLINE# You should have received a copy of the GNU General Public LicenseNEWLINE# along with duplicity; if not, write to the Free Software Foundation,NEWLINE# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USANEWLINENEWLINE# The following can be redefined to use different shell commands fromNEWLINE# ssh or scp or to add more arguments. However, the replacements mustNEWLINE# have the same syntax. Also these strings will be executed by theNEWLINE# shell, so shouldn't have strange characters in them.NEWLINENEWLINEimport reNEWLINEimport stringNEWLINEimport timeNEWLINEimport osNEWLINENEWLINEimport duplicity.backendNEWLINEfrom duplicity import globalsNEWLINEfrom duplicity import logNEWLINEfrom duplicity import pexpectNEWLINEfrom duplicity.errors import * #@UnusedWildImportNEWLINENEWLINEclass SSHPExpectBackend(duplicity.backend.Backend):NEWLINE """This backend copies files using scp. List not supported"""NEWLINE def __init__(self, parsed_url):NEWLINE """scpBackend initializer"""NEWLINE duplicity.backend.Backend.__init__(self, parsed_url)NEWLINENEWLINE self.retry_delay = 10NEWLINENEWLINE self.scp_command = "scp"NEWLINE if globals.scp_command: self.scp_command = globals.scp_commandNEWLINENEWLINE self.sftp_command = "sftp"NEWLINE if globals.sftp_command: self.sftp_command = globals.sftp_commandNEWLINENEWLINE # host string of form [user@]hostnameNEWLINE if parsed_url.username:NEWLINE self.host_string = parsed_url.username + "@" + parsed_url.hostnameNEWLINE else:NEWLINE self.host_string = parsed_url.hostnameNEWLINE # make sure remote_dir is always validNEWLINE if parsed_url.path:NEWLINE # remove leading '/'NEWLINE self.remote_dir = re.sub(r'^/', r'', parsed_url.path, 1)NEWLINE else:NEWLINE self.remote_dir = '.'NEWLINE self.remote_prefix = self.remote_dir + '/'NEWLINE # maybe use different ssh portNEWLINE if parsed_url.port:NEWLINE globals.ssh_options = globals.ssh_options + " -oPort=%s" % parsed_url.portNEWLINE # set some defaults if user has not specified already.NEWLINE if "ServerAliveInterval" not in globals.ssh_options:NEWLINE globals.ssh_options += " -oServerAliveInterval=%d" % ((int)(globals.timeout / 2))NEWLINE if "ServerAliveCountMax" not in globals.ssh_options:NEWLINE globals.ssh_options += " -oServerAliveCountMax=2"NEWLINENEWLINE # set up passwordNEWLINE self.use_getpass = globals.ssh_askpassNEWLINE self.password = self.get_password()NEWLINENEWLINE def run_scp_command(self, commandline):NEWLINE """ Run an scp command, responding to password prompts """NEWLINE for n in range(1, globals.num_retries+1):NEWLINE if n > 1:NEWLINE # sleep before retryNEWLINE time.sleep(self.retry_delay)NEWLINE log.Info("Running '%s' (attempt #%d)" % (commandline, n))NEWLINE child = pexpect.spawn(commandline, timeout = None)NEWLINE if globals.ssh_askpass:NEWLINE state = "authorizing"NEWLINE else:NEWLINE state = "copying"NEWLINE while 1:NEWLINE if state == "authorizing":NEWLINE match = child.expect([pexpect.EOF,NEWLINE "(?i)timeout, server not responding",NEWLINE "(?i)pass(word|phrase .*):",NEWLINE "(?i)permission denied",NEWLINE "authenticity"])NEWLINE log.Debug("State = %s, Before = '%s'" % (state, child.before.strip()))NEWLINE if match == 0:NEWLINE log.Warn("Failed to authenticate")NEWLINE breakNEWLINE elif match == 1:NEWLINE log.Warn("Timeout waiting to authenticate")NEWLINE breakNEWLINE elif match == 2:NEWLINE child.sendline(self.password)NEWLINE state = "copying"NEWLINE elif match == 3:NEWLINE log.Warn("Invalid SSH password")NEWLINE breakNEWLINE elif match == 4:NEWLINE log.Warn("Remote host authentication failed (missing known_hosts entry?)")NEWLINE breakNEWLINE elif state == "copying":NEWLINE match = child.expect([pexpect.EOF,NEWLINE "(?i)timeout, server not responding",NEWLINE "stalled",NEWLINE "authenticity",NEWLINE "ETA"])NEWLINE log.Debug("State = %s, Before = '%s'" % (state, child.before.strip()))NEWLINE if match == 0:NEWLINE breakNEWLINE elif match == 1:NEWLINE log.Warn("Timeout waiting for response")NEWLINE breakNEWLINE elif match == 2:NEWLINE state = "stalled"NEWLINE elif match == 3:NEWLINE log.Warn("Remote host authentication failed (missing known_hosts entry?)")NEWLINE breakNEWLINE elif state == "stalled":NEWLINE match = child.expect([pexpect.EOF,NEWLINE "(?i)timeout, server not responding",NEWLINE "ETA"])NEWLINE log.Debug("State = %s, Before = '%s'" % (state, child.before.strip()))NEWLINE if match == 0:NEWLINE breakNEWLINE elif match == 1:NEWLINE log.Warn("Stalled for too long, aborted copy")NEWLINE breakNEWLINE elif match == 2:NEWLINE state = "copying"NEWLINE child.close(force = True)NEWLINE if child.exitstatus == 0:NEWLINE returnNEWLINE log.Warn("Running '%s' failed (attempt #%d)" % (commandline, n))NEWLINE log.Warn("Giving up trying to execute '%s' after %d attempts" % (commandline, globals.num_retries))NEWLINE raise BackendException("Error running '%s'" % commandline)NEWLINENEWLINE def run_sftp_command(self, commandline, commands):NEWLINE """ Run an sftp command, responding to password prompts, passing commands from list """NEWLINE maxread = 2000 # expected read buffer sizeNEWLINE responses = [pexpect.EOF,NEWLINE "(?i)timeout, server not responding",NEWLINE "sftp>",NEWLINE "(?i)pass(word|phrase .*):",NEWLINE "(?i)permission denied",NEWLINE "authenticity",NEWLINE "(?i)no such file or directory",NEWLINE "Couldn't delete file: No such file or directory",NEWLINE "Couldn't delete file",NEWLINE "open(.*): Failure"]NEWLINE max_response_len = max([len(p) for p in responses[1:]])NEWLINE for n in range(1, globals.num_retries+1):NEWLINE if n > 1:NEWLINE # sleep before retryNEWLINE time.sleep(self.retry_delay)NEWLINE log.Info("Running '%s' (attempt #%d)" % (commandline, n))NEWLINE child = pexpect.spawn(commandline, timeout = None, maxread=maxread)NEWLINE cmdloc = 0NEWLINE passprompt = 0NEWLINE while 1:NEWLINE msg = ""NEWLINE match = child.expect(responses,NEWLINE searchwindowsize=maxread+max_response_len)NEWLINE log.Debug("State = sftp, Before = '%s'" % (child.before.strip()))NEWLINE if match == 0:NEWLINE breakNEWLINE elif match == 1:NEWLINE msg = "Timeout waiting for response"NEWLINE breakNEWLINE if match == 2:NEWLINE if cmdloc < len(commands):NEWLINE command = commands[cmdloc]NEWLINE log.Info("sftp command: '%s'" % (command,))NEWLINE child.sendline(command)NEWLINE cmdloc += 1NEWLINE else:NEWLINE command = 'quit'NEWLINE child.sendline(command)NEWLINE res = child.beforeNEWLINE elif match == 3:NEWLINE passprompt += 1NEWLINE child.sendline(self.password)NEWLINE if (passprompt>1):NEWLINE raise BackendException("Invalid SSH password.")NEWLINE elif match == 4:NEWLINE if not child.before.strip().startswith("mkdir"):NEWLINE msg = "Permission denied"NEWLINE breakNEWLINE elif match == 5:NEWLINE msg = "Host key authenticity could not be verified (missing known_hosts entry?)"NEWLINE breakNEWLINE elif match == 6:NEWLINE if not child.before.strip().startswith("rm"):NEWLINE msg = "Remote file or directory does not exist in command='%s'" % (commandline,)NEWLINE breakNEWLINE elif match == 7:NEWLINE if not child.before.strip().startswith("Removing"):NEWLINE msg = "Could not delete file in command='%s'" % (commandline,)NEWLINE break;NEWLINE elif match == 8:NEWLINE msg = "Could not delete file in command='%s'" % (commandline,)NEWLINE breakNEWLINE elif match == 9:NEWLINE msg = "Could not open file in command='%s'" % (commandline,)NEWLINE breakNEWLINE child.close(force = True)NEWLINE if child.exitstatus == 0:NEWLINE return resNEWLINE log.Warn("Running '%s' with commands:\n %s\n failed (attempt #%d): %s" % (commandline, "\n ".join(commands), n, msg))NEWLINE raise BackendException("Giving up trying to execute '%s' with commands:\n %s\n after %d attempts" % (commandline, "\n ".join(commands), globals.num_retries))NEWLINENEWLINE def put(self, source_path, remote_filename = None):NEWLINE if globals.use_scp:NEWLINE self.put_scp(source_path, remote_filename = remote_filename)NEWLINE else:NEWLINE self.put_sftp(source_path, remote_filename = remote_filename)NEWLINENEWLINE def put_sftp(self, source_path, remote_filename = None):NEWLINE """Use sftp to copy source_dir/filename to remote computer"""NEWLINE if not remote_filename:NEWLINE remote_filename = source_path.get_filename()NEWLINE commands = ["put \"%s\" \"%s.%s.part\"" %NEWLINE (source_path.name, self.remote_prefix, remote_filename),NEWLINE "rename \"%s.%s.part\" \"%s%s\"" %NEWLINE (self.remote_prefix, remote_filename,self.remote_prefix, remote_filename)]NEWLINE commandline = ("%s %s %s" % (self.sftp_command,NEWLINE globals.ssh_options,NEWLINE self.host_string))NEWLINE self.run_sftp_command(commandline, commands)NEWLINENEWLINE def put_scp(self, source_path, remote_filename = None):NEWLINE """Use scp to copy source_dir/filename to remote computer"""NEWLINE if not remote_filename:NEWLINE remote_filename = source_path.get_filename()NEWLINE commandline = "%s %s %s %s:%s%s" % \NEWLINE (self.scp_command, globals.ssh_options, source_path.name, self.host_string,NEWLINE self.remote_prefix, remote_filename)NEWLINE self.run_scp_command(commandline)NEWLINENEWLINE def get(self, remote_filename, local_path):NEWLINE if globals.use_scp:NEWLINE self.get_scp(remote_filename, local_path)NEWLINE else:NEWLINE self.get_sftp(remote_filename, local_path)NEWLINENEWLINE def get_sftp(self, remote_filename, local_path):NEWLINE """Use sftp to get a remote file"""NEWLINE commands = ["get \"%s%s\" \"%s\"" %NEWLINE (self.remote_prefix, remote_filename, local_path.name)]NEWLINE commandline = ("%s %s %s" % (self.sftp_command,NEWLINE globals.ssh_options,NEWLINE self.host_string))NEWLINE self.run_sftp_command(commandline, commands)NEWLINE local_path.setdata()NEWLINE if not local_path.exists():NEWLINE raise BackendException("File %s not found locally after get "NEWLINE "from backend" % local_path.name)NEWLINENEWLINE def get_scp(self, remote_filename, local_path):NEWLINE """Use scp to get a remote file"""NEWLINE commandline = "%s %s %s:%s%s %s" % \NEWLINE (self.scp_command, globals.ssh_options, self.host_string, self.remote_prefix,NEWLINE remote_filename, local_path.name)NEWLINE self.run_scp_command(commandline)NEWLINE local_path.setdata()NEWLINE if not local_path.exists():NEWLINE raise BackendException("File %s not found locally after get "NEWLINE "from backend" % local_path.name)NEWLINENEWLINE def _list(self):NEWLINE """NEWLINE List files available for scpNEWLINENEWLINE Note that this command can get confused when dealing withNEWLINE files with newlines in them, as the embedded newlines cannotNEWLINE be distinguished from the file boundaries.NEWLINE """NEWLINE dirs = self.remote_dir.split(os.sep)NEWLINE if len(dirs) > 0:NEWLINE if not dirs[0] :NEWLINE dirs = dirs[1:]NEWLINE dirs[0]= '/' + dirs[0]NEWLINE mkdir_commands = [];NEWLINE for d in dirs:NEWLINE mkdir_commands += ["mkdir \"%s\"" % (d)] + ["cd \"%s\"" % (d)]NEWLINENEWLINE commands = mkdir_commands + ["ls -1"]NEWLINE commandline = ("%s %s %s" % (self.sftp_command,NEWLINE globals.ssh_options,NEWLINE self.host_string))NEWLINENEWLINE l = self.run_sftp_command(commandline, commands).split('\n')[1:]NEWLINENEWLINE return filter(lambda x: x, map(string.strip, l))NEWLINENEWLINE def delete(self, filename_list):NEWLINE """NEWLINE Runs sftp rm to delete files. Files must not require quoting.NEWLINE """NEWLINE commands = ["cd \"%s\"" % (self.remote_dir,)]NEWLINE for fn in filename_list:NEWLINE commands.append("rm \"%s\"" % fn)NEWLINE commandline = ("%s %s %s" % (self.sftp_command, globals.ssh_options, self.host_string))NEWLINE self.run_sftp_command(commandline, commands)NEWLINENEWLINEduplicity.backend.register_backend("ssh", SSHPExpectBackend)NEWLINEduplicity.backend.register_backend("scp", SSHPExpectBackend)NEWLINEduplicity.backend.register_backend("sftp", SSHPExpectBackend)NEWLINE # Generated by Django 2.2.4 on 2021-01-15 01:18NEWLINENEWLINEfrom django.db import migrations, modelsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ('users', '0019_puzzlesolution'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.AddField(NEWLINE model_name='puzzlesolution',NEWLINE name='previous_attempts',NEWLINE field=models.CharField(default='', max_length=2000),NEWLINE ),NEWLINE ]NEWLINE # -*- coding: utf-8 -*-NEWLINE# Copyright (c) Facebook, Inc. and its affiliates. All Rights ReservedNEWLINEimport loggingNEWLINEimport copyNEWLINEimport torchNEWLINEimport torchvisionNEWLINEimport numpy as npNEWLINEimport cv2NEWLINEfrom PIL import ImageNEWLINEfrom fvcore.common.file_io import PathManagerNEWLINEfrom fvcore.transforms.transform import NoOpTransform, TransformNEWLINENEWLINEfrom detectron2.data import MetadataCatalogNEWLINEfrom detectron2.data import detection_utils as utilsNEWLINEfrom detectron2.data import transforms as TNEWLINENEWLINEfrom .dataset import BB8_KEYPOINT_CONNECTION_RULES, FPS8_KEYPOINT_CONNECTION_RULESNEWLINE# from .structures import DensePoseDataRelative, DensePoseList, DensePoseTransformDataNEWLINENEWLINEclass RandomBlurTransform(Transform):NEWLINE def __init__(self, blur_sigma=1):NEWLINE super().__init__()NEWLINE self._set_attributes(locals())NEWLINENEWLINE def apply_image(self, img: np.ndarray, interp: str = None) -> np.ndarray:NEWLINE """NEWLINE Apply blur transform on the image(s).NEWLINENEWLINE Args:NEWLINE img (ndarray): of shape NxHxWxC, or HxWxC or HxW. The array can beNEWLINE of type uint8 in range [0, 255], or floating point in rangeNEWLINE [0, 1] or [0, 255].NEWLINE interp (str): keep this option for consistency, perform blur would notNEWLINE require interpolation.NEWLINE Returns:NEWLINE ndarray: blured image(s).NEWLINE """NEWLINE if img.dtype == np.uint8:NEWLINE img = img.astype(np.float32)NEWLINE img = cv2.GaussianBlur(img, (self.blur_sigma, self.blur_sigma), 0)NEWLINE return np.clip(img, 0, 255).astype(np.uint8)NEWLINE else:NEWLINE return cv2.GaussianBlur(img, (self.blur_sigma, self.blur_sigma), 0)NEWLINENEWLINE def apply_coords(self, coords: np.ndarray) -> np.ndarray:NEWLINE """NEWLINE Apply no transform on the coordinates.NEWLINE """NEWLINE return coordsNEWLINENEWLINE def apply_segmentation(self, segmentation: np.ndarray) -> np.ndarray:NEWLINE """NEWLINE Apply no transform on the full-image segmentation.NEWLINE """NEWLINE return segmentationNEWLINENEWLINEclass ColorJitterTransform(Transform):NEWLINE def __init__(self, brightness=None,NEWLINE contrast=None,NEWLINE saturation=None,NEWLINE hue=None):NEWLINE super().__init__()NEWLINE self._set_attributes(locals())NEWLINENEWLINE def apply_image(self, img: np.ndarray, interp: str = None) -> np.ndarray:NEWLINE """NEWLINE Apply color jitter transform on the image(s).NEWLINENEWLINE Args:NEWLINE img (ndarray): of shape NxHxWxC, or HxWxC or HxW. The array can beNEWLINE of type uint8 in range [0, 255], or floating point in rangeNEWLINE [0, 1] or [0, 255].NEWLINE interp (str): keep this option for consistency, perform color jitter would notNEWLINE require interpolation.NEWLINE Returns:NEWLINE ndarray: color jittered image(s).NEWLINE """NEWLINE self.color_jitter = torchvision.transforms.ColorJitter(NEWLINE brightness=self.brightness,NEWLINE contrast=self.contrast,NEWLINE saturation=self.saturation,NEWLINE hue=self.hue)NEWLINE img = np.asarray(self.color_jitter(Image.fromarray(np.ascontiguousarray(img, np.uint8))))NEWLINE return imgNEWLINE NEWLINE def apply_coords(self, coords: np.ndarray) -> np.ndarray:NEWLINE """NEWLINE Apply no transform on the coordinates.NEWLINE """NEWLINE return coordsNEWLINENEWLINE def apply_segmentation(self, segmentation: np.ndarray) -> np.ndarray:NEWLINE """NEWLINE Apply no transform on the full-image segmentation.NEWLINE """NEWLINE return segmentationNEWLINENEWLINEclass RandomBlur(T.TransformGen):NEWLINE """NEWLINE Randomly gussian blur an image.NEWLINE """NEWLINE def __init__(self, blur_prob=0.5, blur_sigma=None):NEWLINE super().__init__()NEWLINE self._init(locals())NEWLINENEWLINE def get_transform(self, img):NEWLINE do = self._rand_range() < self.blur_probNEWLINE if do:NEWLINE if self.blur_sigma is None:NEWLINE self.blur_sigma = np.random.choice([3, 5, 7, 9])NEWLINE return RandomBlurTransform(self.blur_sigma)NEWLINE else:NEWLINE return NoOpTransform()NEWLINENEWLINEclass ColorJitter(T.TransformGen):NEWLINE """NEWLINE Color jitter an image.NEWLINE """NEWLINE def __init__(self, brightness=None, contrast=None, saturation=None, hue=None):NEWLINE super().__init__()NEWLINE self._init(locals())NEWLINENEWLINE def get_transform(self, img):NEWLINE return ColorJitterTransform(self.brightness, self.contrast, self.saturation, self.hue)NEWLINENEWLINEdef create_sixdpose_keypoint_hflip_indices(dataset_names, keypoint_format):NEWLINE """NEWLINE Args:NEWLINE dataset_names (list[str]): list of dataset namesNEWLINE keypoint_format(str): bb8, fps8, or bb8+fps8NEWLINE Returns:NEWLINE ndarray[int]: a vector of size=#keypoints, storing theNEWLINE horizontally-flipped keypoint indices.NEWLINE """NEWLINE meta = MetadataCatalog.get(dataset_names[0])NEWLINE keypoint_flip_map = () # sixd pose has no filp mapNEWLINENEWLINE if keypoint_format == 'bb8':NEWLINE names = (NEWLINE "center",NEWLINE # bb8NEWLINE "bb8_0", "bb8_1",NEWLINE "bb8_2", "bb8_3",NEWLINE "bb8_4", "bb8_5",NEWLINE "bb8_6", "bb8_7",NEWLINE )NEWLINE connection_rules = BB8_KEYPOINT_CONNECTION_RULESNEWLINE meta.set(keypoint_names=names, keypoint_flip_map=keypoint_flip_map, keypoint_connection_rules=connection_rules)NEWLINE elif keypoint_format == 'fps8':NEWLINE names = (NEWLINE "center",NEWLINE # fps8NEWLINE "fps8_0", "fps8_1",NEWLINE "fps8_2", "fps8_3",NEWLINE "fps8_4", "fps8_5",NEWLINE "fps8_6", "fps8_7",NEWLINE )NEWLINE connection_rules = FPS8_KEYPOINT_CONNECTION_RULESNEWLINE meta.set(keypoint_names=names, keypoint_flip_map=keypoint_flip_map, keypoint_connection_rules=connection_rules)NEWLINE else:NEWLINE assert keypoint_format == 'bb8+fps8', keypoint_formatNEWLINE names = (NEWLINE "center",NEWLINE # bb8NEWLINE "bb8_0", "bb8_1",NEWLINE "bb8_2", "bb8_3",NEWLINE "bb8_4", "bb8_5",NEWLINE "bb8_6", "bb8_7",NEWLINE # fps8NEWLINE "fps8_0", "fps8_1",NEWLINE "fps8_2", "fps8_3",NEWLINE "fps8_4", "fps8_5",NEWLINE "fps8_6", "fps8_7",NEWLINE )NEWLINE connection_rules = BB8_KEYPOINT_CONNECTION_RULES + FPS8_KEYPOINT_CONNECTION_RULESNEWLINE meta.set(keypoint_names=names, keypoint_flip_map=keypoint_flip_map, keypoint_connection_rules=connection_rules)NEWLINE NEWLINE # TODO flip -> hflip NEWLINE flip_map = dict(keypoint_flip_map)NEWLINE flip_map.update({v: k for k, v in flip_map.items()})NEWLINE flipped_names = [i if i not in flip_map else flip_map[i] for i in names]NEWLINE flip_indices = [names.index(i) for i in flipped_names]NEWLINE return np.asarray(flip_indices)NEWLINENEWLINENEWLINEclass DatasetMapper:NEWLINE """NEWLINE A callable which takes a dataset dict in Detectron2 Dataset format,NEWLINE and map it into a format used by the model.NEWLINENEWLINE This is the default callable to be used to map your dataset dict into training data.NEWLINE You may need to follow it to implement your own one for customized logic.NEWLINENEWLINE The callable currently does the following:NEWLINENEWLINE 1. Read the image from "file_name"NEWLINE 2. Applies cropping/geometric transforms to the image and annotationsNEWLINE 3. Prepare data and annotations to Tensor and :class:`Instances`NEWLINE """NEWLINENEWLINE def __init__(self, cfg, is_train=True):NEWLINE if cfg.INPUT.CROP.ENABLED and is_train:NEWLINE self.crop_gen = T.RandomCrop(cfg.INPUT.CROP.TYPE, cfg.INPUT.CROP.SIZE)NEWLINE logging.getLogger(__name__).info("CropGen used in training: " + str(self.crop_gen))NEWLINE else:NEWLINE self.crop_gen = NoneNEWLINENEWLINE if cfg.INPUT.RANDOMBLUR.ENABLED and is_train:NEWLINE self.blur_gen = RandomBlur(cfg.INPUT.RANDOMBLUR.PROB)NEWLINE logging.getLogger(__name__).info("BlurGen used in training: " + str(self.blur_gen))NEWLINE else:NEWLINE self.blur_gen = None NEWLINENEWLINE if cfg.INPUT.COLORJITTER.ENABLED and is_train:NEWLINE self.colorjitter_gen = ColorJitter(cfg.INPUT.COLORJITTER.BRIGHTNESS, cfg.INPUT.COLORJITTER.CONTRAST,NEWLINE cfg.INPUT.COLORJITTER.SATURATION, cfg.INPUT.COLORJITTER.HUE)NEWLINE logging.getLogger(__name__).info("ColorJitterGen used in training: " + str(self.colorjitter_gen))NEWLINE else:NEWLINE self.colorjitter_gen = None NEWLINENEWLINE self.tfm_gens = utils.build_transform_gen(cfg, is_train)NEWLINENEWLINE # fmt: offNEWLINE self.img_format = cfg.INPUT.FORMATNEWLINE self.mask_on = cfg.MODEL.MASK_ON or cfg.MODEL.PVNET_ONNEWLINE self.mask_format = cfg.INPUT.MASK_FORMATNEWLINE self.keypoint_on = cfg.MODEL.KEYPOINT_ON or cfg.MODEL.PVNET_ON or cfg.MODEL.CRPNET_ON or cfg.MODEL.HCR_ONNEWLINE self.keypoint_format= cfg.INPUT.KEYPOINT_FORMATNEWLINE self.load_proposals = cfg.MODEL.LOAD_PROPOSALSNEWLINE # fmt: onNEWLINE if self.keypoint_on and is_train:NEWLINE # Flip only makes sense in trainingNEWLINE self.keypoint_hflip_indices = create_sixdpose_keypoint_hflip_indices(cfg.DATASETS.TRAIN, self.keypoint_format)NEWLINE else:NEWLINE self.keypoint_hflip_indices = NoneNEWLINENEWLINE if self.load_proposals:NEWLINE self.min_box_side_len = cfg.MODEL.PROPOSAL_GENERATOR.MIN_SIZENEWLINE self.proposal_topk = (NEWLINE cfg.DATASETS.PRECOMPUTED_PROPOSAL_TOPK_TRAINNEWLINE if is_trainNEWLINE else cfg.DATASETS.PRECOMPUTED_PROPOSAL_TOPK_TESTNEWLINE )NEWLINE self.is_train = is_trainNEWLINENEWLINE def __call__(self, dataset_dict):NEWLINE """NEWLINE Args:NEWLINE dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format.NEWLINENEWLINE Returns:NEWLINE dict: a format that builtin models in detectron2 acceptNEWLINE """NEWLINE dataset_dict = copy.deepcopy(dataset_dict) # it will be modified by code belowNEWLINE # USER: Write your own image loading if it's not from a fileNEWLINE image = utils.read_image(dataset_dict["file_name"], format=self.img_format)NEWLINE utils.check_image_size(dataset_dict, image)NEWLINENEWLINE if "annotations" not in dataset_dict:NEWLINE image, transforms = T.apply_transform_gens(NEWLINE ([self.crop_gen] if self.crop_gen else []) + NEWLINE ([self.blur_gen] if self.blur_gen else []) + NEWLINE ([self.colorjitter_gen] if self.colorjitter_gen else []) + self.tfm_gens, imageNEWLINE )NEWLINE else:NEWLINE # Crop around an instance if there are instances in the image.NEWLINE # USER: Remove if you don't use croppingNEWLINE if self.crop_gen:NEWLINE crop_tfm = utils.gen_crop_transform_with_instance(NEWLINE self.crop_gen.get_crop_size(image.shape[:2]),NEWLINE image.shape[:2],NEWLINE np.random.choice(dataset_dict["annotations"]),NEWLINE )NEWLINE image = crop_tfm.apply_image(image)NEWLINE if self.blur_gen:NEWLINE blur_tfm = self.blur_gen.get_transform(image)NEWLINE image = blur_tfm.apply_image(image)NEWLINE if self.colorjitter_gen:NEWLINE colorjitter_tfm = self.colorjitter_gen.get_transform(image)NEWLINE image = colorjitter_tfm.apply_image(image)NEWLINENEWLINE image, transforms = T.apply_transform_gens(self.tfm_gens, image)NEWLINE if self.colorjitter_gen:NEWLINE transforms = colorjitter_tfm + transformsNEWLINE if self.blur_gen:NEWLINE transforms = blur_tfm + transformsNEWLINE if self.crop_gen:NEWLINE transforms = crop_tfm + transformsNEWLINENEWLINE image_shape = image.shape[:2] # h, wNEWLINENEWLINE # Pytorch's dataloader is efficient on torch.Tensor due to shared-memory,NEWLINE # but not efficient on large generic data structures due to the use of pickle & mp.Queue.NEWLINE # Therefore it's important to use torch.Tensor.NEWLINE dataset_dict["image"] = torch.as_tensor(NEWLINE image.transpose(2, 0, 1).astype("float32")NEWLINE ).contiguous()NEWLINE # Can use uint8 if it turns out to be slow some dayNEWLINENEWLINE # USER: Remove if you don't use pre-computed proposals.NEWLINE if self.load_proposals:NEWLINE utils.transform_proposals(NEWLINE dataset_dict, image_shape, transforms, self.min_box_side_len, self.proposal_topkNEWLINE )NEWLINENEWLINE if not self.is_train:NEWLINE dataset_dict.pop("annotations", None)NEWLINE dataset_dict.pop("sem_seg_file_name", None)NEWLINE return dataset_dictNEWLINENEWLINE if "annotations" in dataset_dict:NEWLINE # USER: Modify this if you want to keep them for some reason.NEWLINE for anno in dataset_dict["annotations"]:NEWLINE if not self.mask_on:NEWLINE anno.pop("segmentation", None)NEWLINE if not self.keypoint_on:NEWLINE anno.pop("keypoints", None)NEWLINE # USER: load keypoints according to keypoint_formatNEWLINE else:NEWLINE keypts = anno["keypoints"]NEWLINE if 'bb8' in self.keypoint_format:NEWLINE corner_2d = np.array(anno["corner_2d"])NEWLINE corner_2d = np.insert(corner_2d, 2, 2, axis=1).flatten().tolist()NEWLINE keypts += corner_2dNEWLINE if 'fps8' in self.keypoint_format:NEWLINE fps_2d = np.array(anno["fps_2d"])NEWLINE fps_2d = np.insert(fps_2d, 2, 2, axis=1).flatten().tolist()NEWLINE keypts += fps_2dNEWLINE anno["keypoints"] = keyptsNEWLINENEWLINE # USER: Implement additional transformations if you have other types of dataNEWLINE annos = [NEWLINE utils.transform_instance_annotations(NEWLINE obj, transforms, image_shape, keypoint_hflip_indices=self.keypoint_hflip_indicesNEWLINE )NEWLINE for obj in dataset_dict.pop("annotations")NEWLINE if obj.get("iscrowd", 0) == 0NEWLINE ]NEWLINE instances = utils.annotations_to_instances(NEWLINE annos, image_shape, mask_format=self.mask_formatNEWLINE )NEWLINE # Create a tight bounding box from masks, useful when image is croppedNEWLINE if self.crop_gen and instances.has("gt_masks"):NEWLINE instances.gt_boxes = instances.gt_masks.get_bounding_boxes()NEWLINE dataset_dict["instances"] = utils.filter_empty_instances(instances)NEWLINENEWLINE # USER: Remove if you don't do semantic/panoptic segmentation.NEWLINE # if "sem_seg_file_name" in dataset_dict:NEWLINE # with PathManager.open(dataset_dict.pop("sem_seg_file_name"), "rb") as f:NEWLINE # sem_seg_gt = Image.open(f)NEWLINE # sem_seg_gt = np.asarray(sem_seg_gt, dtype="uint8")NEWLINE # sem_seg_gt = transforms.apply_segmentation(sem_seg_gt)NEWLINE # sem_seg_gt = torch.as_tensor(sem_seg_gt.astype("long"))NEWLINE # dataset_dict["sem_seg"] = sem_seg_gtNEWLINE return dataset_dictNEWLINENEWLINEclass COCODatasetMapper:NEWLINE """NEWLINE A callable which takes a dataset dict in Detectron2 Dataset format,NEWLINE and map it into a format used by the model.NEWLINENEWLINE This is the default callable to be used to map your dataset dict into training data.NEWLINE You may need to follow it to implement your own one for customized logic,NEWLINE such as a different way to read or transform images.NEWLINE See :doc:`/tutorials/data_loading` for details.NEWLINENEWLINE The callable currently does the following:NEWLINENEWLINE 1. Read the image from "file_name"NEWLINE 2. Applies cropping/geometric transforms to the image and annotationsNEWLINE 3. Prepare data and annotations to Tensor and :class:`Instances`NEWLINE """NEWLINENEWLINE def __init__(self, cfg, is_train=True):NEWLINE if cfg.INPUT.CROP.ENABLED and is_train:NEWLINE self.crop_gen = T.RandomCrop(cfg.INPUT.CROP.TYPE, cfg.INPUT.CROP.SIZE)NEWLINE logging.getLogger(__name__).info("CropGen used in training: " + str(self.crop_gen))NEWLINE else:NEWLINE self.crop_gen = NoneNEWLINENEWLINE self.tfm_gens = utils.build_transform_gen(cfg, is_train)NEWLINENEWLINE # fmt: offNEWLINE self.img_format = cfg.INPUT.FORMATNEWLINE self.mask_on = cfg.MODEL.MASK_ON or cfg.MODEL.PVNET_ONNEWLINE self.mask_format = cfg.INPUT.MASK_FORMATNEWLINE self.keypoint_on = cfg.MODEL.KEYPOINT_ON or cfg.MODEL.PVNET_ON or cfg.MODEL.CRPNET_ON or cfg.MODEL.HCR_ONNEWLINE self.load_proposals = cfg.MODEL.LOAD_PROPOSALSNEWLINE # fmt: onNEWLINE if self.keypoint_on and is_train:NEWLINE # Flip only makes sense in trainingNEWLINE self.keypoint_hflip_indices = utils.create_keypoint_hflip_indices(cfg.DATASETS.TRAIN)NEWLINE else:NEWLINE self.keypoint_hflip_indices = NoneNEWLINENEWLINE if self.load_proposals:NEWLINE self.min_box_side_len = cfg.MODEL.PROPOSAL_GENERATOR.MIN_SIZENEWLINE self.proposal_topk = (NEWLINE cfg.DATASETS.PRECOMPUTED_PROPOSAL_TOPK_TRAINNEWLINE if is_trainNEWLINE else cfg.DATASETS.PRECOMPUTED_PROPOSAL_TOPK_TESTNEWLINE )NEWLINE self.is_train = is_trainNEWLINENEWLINE def __call__(self, dataset_dict):NEWLINE """NEWLINE Args:NEWLINE dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format.NEWLINENEWLINE Returns:NEWLINE dict: a format that builtin models in detectron2 acceptNEWLINE """NEWLINE dataset_dict = copy.deepcopy(dataset_dict) # it will be modified by code belowNEWLINE # USER: Write your own image loading if it's not from a fileNEWLINE image = utils.read_image(dataset_dict["file_name"], format=self.img_format)NEWLINE utils.check_image_size(dataset_dict, image)NEWLINENEWLINE if "annotations" not in dataset_dict:NEWLINE image, transforms = T.apply_transform_gens(NEWLINE ([self.crop_gen] if self.crop_gen else []) + self.tfm_gens, imageNEWLINE )NEWLINE else:NEWLINE # Crop around an instance if there are instances in the image.NEWLINE # USER: Remove if you don't use croppingNEWLINE if self.crop_gen:NEWLINE crop_tfm = utils.gen_crop_transform_with_instance(NEWLINE self.crop_gen.get_crop_size(image.shape[:2]),NEWLINE image.shape[:2],NEWLINE np.random.choice(dataset_dict["annotations"]),NEWLINE )NEWLINE image = crop_tfm.apply_image(image)NEWLINE image, transforms = T.apply_transform_gens(self.tfm_gens, image)NEWLINE if self.crop_gen:NEWLINE transforms = crop_tfm + transformsNEWLINENEWLINE image_shape = image.shape[:2] # h, wNEWLINENEWLINE # Pytorch's dataloader is efficient on torch.Tensor due to shared-memory,NEWLINE # but not efficient on large generic data structures due to the use of pickle & mp.Queue.NEWLINE # Therefore it's important to use torch.Tensor.NEWLINE dataset_dict["image"] = torch.as_tensor(np.ascontiguousarray(image.transpose(2, 0, 1)))NEWLINENEWLINE # USER: Remove if you don't use pre-computed proposals.NEWLINE if self.load_proposals:NEWLINE utils.transform_proposals(NEWLINE dataset_dict, image_shape, transforms, self.min_box_side_len, self.proposal_topkNEWLINE )NEWLINENEWLINE if not self.is_train:NEWLINE # USER: Modify this if you want to keep them for some reason.NEWLINE dataset_dict.pop("annotations", None)NEWLINE dataset_dict.pop("sem_seg_file_name", None)NEWLINE return dataset_dictNEWLINENEWLINE if "annotations" in dataset_dict:NEWLINE # USER: Modify this if you want to keep them for some reason.NEWLINE for anno in dataset_dict["annotations"]:NEWLINE if not self.mask_on:NEWLINE anno.pop("segmentation", None)NEWLINE if not self.keypoint_on:NEWLINE anno.pop("keypoints", None)NEWLINENEWLINE # USER: Implement additional transformations if you have other types of dataNEWLINE annos = [NEWLINE utils.transform_instance_annotations(NEWLINE obj, transforms, image_shape, keypoint_hflip_indices=self.keypoint_hflip_indicesNEWLINE )NEWLINE for obj in dataset_dict.pop("annotations")NEWLINE if obj.get("iscrowd", 0) == 0NEWLINE ]NEWLINE instances = utils.annotations_to_instances(NEWLINE annos, image_shape, mask_format=self.mask_formatNEWLINE )NEWLINE # Create a tight bounding box from masks, useful when image is croppedNEWLINE if self.crop_gen and instances.has("gt_masks"):NEWLINE instances.gt_boxes = instances.gt_masks.get_bounding_boxes()NEWLINE dataset_dict["instances"] = utils.filter_empty_instances(instances)NEWLINENEWLINE # USER: Remove if you don't do semantic/panoptic segmentation.NEWLINE if "sem_seg_file_name" in dataset_dict:NEWLINE with PathManager.open(dataset_dict.pop("sem_seg_file_name"), "rb") as f:NEWLINE sem_seg_gt = Image.open(f)NEWLINE sem_seg_gt = np.asarray(sem_seg_gt, dtype="uint8")NEWLINE sem_seg_gt = transforms.apply_segmentation(sem_seg_gt)NEWLINE sem_seg_gt = torch.as_tensor(sem_seg_gt.astype("long"))NEWLINE dataset_dict["sem_seg"] = sem_seg_gtNEWLINE return dataset_dict """Objects, functions and constants relating to OCP bounds.NEWLINENEWLINEAttributesNEWLINE----------NEWLINEDEFAULT_ASSUME_INF_BOUNDS : boolNEWLINE Default as to whether Pycollo should treat unspecified bounds as beingNEWLINE numerically infinite.NEWLINEDEFAULT_INF_VALUE : floatNEWLINE Default numerical value for when Pycollo needs to use a finite numericalNEWLINE approximation for infinity.NEWLINENEWLINE"""NEWLINENEWLINENEWLINE__all__ = ["EndpointBounds", "PhaseBounds"]NEWLINENEWLINENEWLINEfrom abc import (ABC, abstractmethod)NEWLINEfrom collections import namedtupleNEWLINEfrom numbers import NumberNEWLINEfrom typing import (Iterable, Optional, Union)NEWLINENEWLINEimport numpy as npNEWLINEimport scipy.optimize as optimizeNEWLINEimport sympy as symNEWLINENEWLINEfrom .node import NodeNEWLINEfrom .typing import OptionalBoundsTypeNEWLINEfrom .utils import (fast_sympify,NEWLINE format_for_output,NEWLINE SUPPORTED_ITER_TYPES,NEWLINE symbol_primitives,NEWLINE )NEWLINENEWLINENEWLINE# Default values for settingsNEWLINEDEFAULT_ASSUME_INF_BOUNDS = TrueNEWLINEDEFAULT_BOUND_CLASH_ABSOLUTE_TOLERANCE = 1e-6NEWLINEDEFAULT_BOUND_CLASH_RELATIVE_TOLERANCE = 1e-6NEWLINEDEFAULT_NUMERICAL_INF = 10e19NEWLINEDEFAULT_OVERRIDE_ENDPOINTS = TrueNEWLINEDEFAULT_REMOVE_CONSTANT_VARIABLES = TrueNEWLINENEWLINENEWLINE# Data structuresNEWLINEphase_info_fields = ("name", "index", "backend")NEWLINEPhaseInfo = namedtuple("PhaseInfo", phase_info_fields)NEWLINE"""Data structure for information about OCP phases.NEWLINENEWLINEThese are mostly used to format descriptive error messages for the user.NEWLINENEWLINEFieldsNEWLINE------NEWLINEname : strNEWLINE The name associated with the phaseNEWLINEindex : intNEWLINE The index of the phase.NEWLINEbackend : :py:class:`PycolloPhaseData`NEWLINE The phase backend associated with the specified OCP phase.NEWLINENEWLINE"""NEWLINENEWLINEbounds_info_fields = ("user_bnds", "user_syms", "bnds_type", "num",NEWLINE "is_variable", "none_default_allowed")NEWLINEBoundsInfo = namedtuple("BoundsInfo",NEWLINE bounds_info_fields,NEWLINE defaults=[True, True])NEWLINE"""Data structure for storing information about user-supplied bounds.NEWLINENEWLINEFieldsNEWLINE------NEWLINEuser_bnds : objNEWLINE The bounds that the user has supplied.NEWLINEuser_syms : Iterable[sym.Symbols]NEWLINE An iterable of symbols relating to the user-supplied bounds (if available).NEWLINEbnds_type : strNEWLINE String indentifying the aspect of the OCP that the bounds relate to. MostlyNEWLINE used for formatting descriptive error messages for the user.NEWLINEnum : intNEWLINE The number of variables/constraints that should be expected for the type ofNEWLINE bounds in question.NEWLINEis_variable : boolNEWLINE `True` if the bound type in question is a variable, `False` if it is aNEWLINE constraint.NEWLINEnone_default_allowed : boolNEWLINE `True` if Pycollo should automatically handle the situation where no boundsNEWLINE have been supplied. `False` if an error should be raised.NEWLINENEWLINE"""NEWLINENEWLINENEWLINEclass BoundsABC(ABC):NEWLINENEWLINE @abstractmethodNEWLINE def optimal_control_problem(self):NEWLINE passNEWLINENEWLINE @abstractmethodNEWLINE def _process_and_check_user_values(self):NEWLINE passNEWLINENEWLINE @abstractmethodNEWLINE def _required_variable_bounds(self):NEWLINE passNEWLINENEWLINENEWLINEclass EndpointBounds(BoundsABC):NEWLINENEWLINE def __init__(self,NEWLINE optimal_control_problem,NEWLINE *,NEWLINE parameter_variables: OptionalBoundsType = None,NEWLINE endpoint_constraints: OptionalBoundsType = None,NEWLINE ):NEWLINENEWLINE self.ocp = optimal_control_problemNEWLINE self.parameter_variables = parameter_variablesNEWLINE self.endpoint_constraints = endpoint_constraintsNEWLINENEWLINE @propertyNEWLINE def optimal_control_problem(self):NEWLINE return self.ocpNEWLINENEWLINE def _process_and_check_user_values(self):NEWLINE self._backend = self.optimal_control_problem._backendNEWLINE self._INF = self.optimal_control_problem.settings.numerical_infNEWLINE self._process_parameter_vars()NEWLINE self._process_endpoint_cons()NEWLINENEWLINE def _process_parameter_vars(self):NEWLINE user_bnds = self.parameter_variablesNEWLINE user_syms = self._backend.s_var_userNEWLINE bnds_type = "parameter variable"NEWLINE num_expected = self._backend.num_s_var_fullNEWLINE bnds_info = BoundsInfo(user_bnds, user_syms, bnds_type, num_expected)NEWLINE self._s_bnd, self._s_needed = process_single_type_of_values(self,NEWLINE bnds_info)NEWLINENEWLINE def _process_endpoint_cons(self):NEWLINE num_b_con = self.optimal_control_problem.number_endpoint_constraintsNEWLINE user_bnds = self.endpoint_constraintsNEWLINE user_syms = [None] * num_b_conNEWLINE bnds_type = "endpoint constraints"NEWLINE num_expect = num_b_conNEWLINE bnds_info = BoundsInfo(user_bnds, user_syms, bnds_type, num_expect,NEWLINE False)NEWLINE self._b_con_bnd, needed = process_single_type_of_values(self,NEWLINE bnds_info)NEWLINENEWLINE def _required_variable_bounds(self):NEWLINE x_bnd = self._s_bnd[self._s_needed]NEWLINE return x_bndNEWLINENEWLINENEWLINEclass PhaseBounds(BoundsABC):NEWLINE """Bounds on variables and constraints associated with a phase.NEWLINENEWLINE This class currently behaves like a data class, however additionalNEWLINE functionality will be added in the future to support robust checking of theNEWLINE user-supplied values for the bounds.NEWLINENEWLINE Intended behaviour will be::NEWLINENEWLINE * None values will be treated as no bounds, i.e. ['-inf', 'inf'].NEWLINE * Single values will be treated as equal lower and upper bounds.NEWLINE * Mappings will be accepted for `state_variables`, `control_variables`,NEWLINE `initial_state_constraints` and `final_state_constraints`.NEWLINE * Keys in the mappings should be the strings of the correspondingNEWLINE `state_variables` or `control_variables` for the phase.NEWLINE * 'inf' values will be replaced by a large floating point value so thatNEWLINE scaling can be done automatically.NEWLINE * The 'inf' replacement value can be changed inNEWLINE `OptimalControlProblem.settings.numerical_inf`, the default is 1e19.NEWLINE * If a :obj:`np.ndarray` with size = (2, 2) is passed as a value thenNEWLINE the first dimension will be treated as corresponding to theNEWLINE variable or constraint to be bounded.NEWLINE * If iterables are passed then they may contain a combination of None,NEWLINE single numerical values, and pairs of numerical valuesNEWLINE * Symbolic expressions should also be allowed if they can be convertedNEWLINE into numerical values when processed alongside auxiliary data.NEWLINENEWLINE NotesNEWLINE -----NEWLINE * 'inf' values should be avoided where possible in order to give betterNEWLINE automatic scaling.NEWLINENEWLINE AttributesNEWLINE ----------NEWLINE phaseNEWLINE The phase with which these bounds will be associated. Default value isNEWLINE `None`.NEWLINE initial_timeNEWLINE Bounds on when the phase starts. Default value is `None`.NEWLINE final_timeNEWLINE Bounds on when the phase ends. Default value is `None`.NEWLINE state_variables:NEWLINE Bounds on the phase's state variables. Default value is `None`.NEWLINE control_variablesNEWLINE Bounds on the phase's control variables. Default value is `None`.NEWLINE integral_variablesNEWLINE Bounds on the phase's integral variables. Default value is `None`.NEWLINE path_constraintsNEWLINE Bounds on the phase's path constraints. Default value is `None`.NEWLINE initial_state_constraintsNEWLINE Bounds on the phase's state variables at the initial time. DefaultNEWLINE value is `None`.NEWLINE final_state_constraintsNEWLINE Bounds on the phase's state variables at the final time. Default valueNEWLINE is `None`.NEWLINE """NEWLINENEWLINE def __init__(self,NEWLINE phase: "Phase",NEWLINE *,NEWLINE initial_time: Optional[float] = None,NEWLINE final_time: Optional[float] = None,NEWLINE state_variables: OptionalBoundsType = None,NEWLINE control_variables: OptionalBoundsType = None,NEWLINE integral_variables: OptionalBoundsType = None,NEWLINE path_constraints: OptionalBoundsType = None,NEWLINE initial_state_constraints: OptionalBoundsType = None,NEWLINE final_state_constraints: OptionalBoundsType = None,NEWLINE ):NEWLINE """Bounds on variables and constraints associated with a phase.NEWLINENEWLINE ArgsNEWLINE ----NEWLINE phaseNEWLINE The phase with which these bounds will be associated.NEWLINE initial_timeNEWLINE Bounds on when the phase starts. Default value is `None`.NEWLINE final_timeNEWLINE Bounds on when the phase ends. Default value is `None`.NEWLINE state_variablesNEWLINE Bounds on the phase's state variables. Default value is `None`.NEWLINE control_variablesNEWLINE Bounds on the phase's control variables. Default value is `None`.NEWLINE integral_variablesNEWLINE Bounds on the phase's integral variables. Default value is `None`.NEWLINE path_constraintsNEWLINE Bounds on the phase's path constraints. Default value is `None`.NEWLINE initial_state_constraintsNEWLINE Bounds on the phase's state variables at the initial time. DefaultNEWLINE value is `None`.NEWLINE final_state_constraintsNEWLINE Bounds on the phase's state variables at the final time. DefaultNEWLINE value is `None`.NEWLINE """NEWLINE self.ocp = phase.optimal_control_problemNEWLINE self.phase = phaseNEWLINE self.initial_time = initial_timeNEWLINE self.final_time = final_timeNEWLINE self.state_variables = state_variablesNEWLINE self.control_variables = control_variablesNEWLINE self.integral_variables = integral_variablesNEWLINE self.path_constraints = path_constraintsNEWLINE self.initial_state_constraints = initial_state_constraintsNEWLINE self.final_state_constraints = final_state_constraintsNEWLINENEWLINE @propertyNEWLINE def optimal_control_problem(self):NEWLINE return self.phase.optimal_control_problemNEWLINENEWLINE def _process_and_check_user_values(self, phase_backend):NEWLINE self._backend = phase_backendNEWLINE self._INF = self.optimal_control_problem.settings.numerical_infNEWLINE p_info = self._get_phase_info(phase_backend)NEWLINE self._process_state_vars(p_info)NEWLINE self._process_control_vars(p_info)NEWLINE self._process_integral_vars(p_info)NEWLINE self._process_time_vars(p_info)NEWLINE self._process_path_cons(p_info)NEWLINE self._process_initial_state_cons(p_info)NEWLINE self._process_final_state_cons(p_info)NEWLINENEWLINE def _get_phase_info(self, phase_backend):NEWLINE phase_name = phase_backend.ocp_phase.nameNEWLINE phase_index = phase_backend.ocp_phase.phase_numberNEWLINE phase_info = PhaseInfo(phase_name, phase_index, phase_backend)NEWLINE return phase_infoNEWLINENEWLINE def _process_state_vars(self, p_info):NEWLINE user_bnds = self.state_variablesNEWLINE user_syms = p_info.backend.y_var_userNEWLINE bnds_type = "state variable"NEWLINE num_expect = p_info.backend.num_y_var_fullNEWLINE bnds_info = BoundsInfo(user_bnds, user_syms, bnds_type, num_expect)NEWLINE self._y_bnd, self._y_needed = process_single_type_of_values(self,NEWLINE bnds_info,NEWLINE p_info)NEWLINENEWLINE def _process_control_vars(self, p_info):NEWLINE user_bnd = self.control_variablesNEWLINE user_sym = p_info.backend.u_var_userNEWLINE bnd_type = "control variable"NEWLINE num_expect = p_info.backend.num_u_var_fullNEWLINE bnd_info = BoundsInfo(user_bnd, user_sym, bnd_type, num_expect)NEWLINE self._u_bnd, self._u_needed = process_single_type_of_values(self,NEWLINE bnd_info,NEWLINE p_info)NEWLINENEWLINE def _process_integral_vars(self, p_info):NEWLINE user_bnd = self.integral_variablesNEWLINE user_sym = p_info.backend.q_var_userNEWLINE bnd_type = "integral variable"NEWLINE num_expect = p_info.backend.num_q_var_fullNEWLINE bnd_info = BoundsInfo(user_bnd, user_sym, bnd_type, num_expect)NEWLINE self._q_bnd, self._q_needed = process_single_type_of_values(self,NEWLINE bnd_info,NEWLINE p_info)NEWLINENEWLINE def _process_path_cons(self, p_info):NEWLINE user_bnd = self.path_constraintsNEWLINE user_sym = [None] * p_info.backend.num_p_conNEWLINE bnd_type = "path constraints"NEWLINE num_expect = p_info.backend.num_p_conNEWLINE bnd_info = BoundsInfo(user_bnd, user_sym, bnd_type, num_expect, False)NEWLINE self._p_con_bnd, needed = process_single_type_of_values(self,NEWLINE bnd_info,NEWLINE p_info)NEWLINENEWLINE def _process_time_vars(self, p_info):NEWLINE user_bnd = [self.initial_time, self.final_time]NEWLINE user_sym = p_info.backend.t_var_userNEWLINE bnd_type = "time variable"NEWLINE num_expect = p_info.backend.num_t_var_fullNEWLINE bnd_info = BoundsInfo(user_bnd, user_sym, bnd_type, num_expect)NEWLINE self._t_bnd, self._t_needed = process_single_type_of_values(self,NEWLINE bnd_info,NEWLINE p_info)NEWLINE self._check_time_bounds_error((0, 0), (1, 0), p_info)NEWLINE self._check_time_bounds_error((0, 1), (1, 1), p_info)NEWLINENEWLINE def _check_time_bounds_error(self, i_1, i_2, p_info):NEWLINE arg_1 = self._t_bnd[i_1]NEWLINE arg_2 = self._t_bnd[i_2]NEWLINE if arg_1 > arg_2:NEWLINE self._raise_time_bounds_error(i_1, i_2, arg_1, arg_2, p_info)NEWLINENEWLINE def _raise_time_bounds_error(self, i_1, i_2, bnd_1, bnd_2, p_info):NEWLINE bnd_1_t0_or_tF = "initial" if i_1[0] == 0 else "final"NEWLINE bnd_1_lower_or_upper = "lower" if i_1[1] == 0 else "upper"NEWLINE bnd_2_t0_or_tF = "initial" if i_2[0] == 0 else "final"NEWLINE bnd_2_lower_or_upper = "lower" if i_2[1] == 0 else "upper"NEWLINE msg = (f"The {bnd_2_lower_or_upper} bound for the {bnd_2_t0_or_tF} "NEWLINE f"time ('{bnd_2}') must be greater than the "NEWLINE f"{bnd_1_lower_or_upper} bound for the {bnd_1_t0_or_tF} time "NEWLINE f"('{bnd_1}') in phase {p_info.name} (index #{p_info.index}).")NEWLINE raise ValueError(msg)NEWLINENEWLINE def _process_initial_state_cons(self, p_info):NEWLINE user_bnd = self.initial_state_constraintsNEWLINE user_sym = p_info.backend.y_var_userNEWLINE bnd_type = "initial state constraint"NEWLINE num_expect = p_info.backend.num_y_var_fullNEWLINE bnd_info = BoundsInfo(user_bnd, user_sym, bnd_type, num_expect, False)NEWLINE y_t0_bnd, self._y_t0_needed = process_single_type_of_values(self,NEWLINE bnd_info,NEWLINE p_info)NEWLINE if self.ocp.settings.override_endpoint_bounds:NEWLINE y_t0_bnd = self._override_endpoint_bounds(y_t0_bnd)NEWLINE self._y_t0_bnd = y_t0_bndNEWLINENEWLINE def _process_final_state_cons(self, p_info):NEWLINE user_bnd = self.final_state_constraintsNEWLINE user_sym = p_info.backend.y_var_userNEWLINE bnd_type = "final state constraint"NEWLINE num_expect = p_info.backend.num_y_var_fullNEWLINE bnd_info = BoundsInfo(user_bnd, user_sym, bnd_type, num_expect, False)NEWLINE y_tF_bnd, self._y_tF_needed = process_single_type_of_values(self,NEWLINE bnd_info,NEWLINE p_info)NEWLINE if self.ocp.settings.override_endpoint_bounds:NEWLINE y_tF_bnd = self._override_endpoint_bounds(y_tF_bnd)NEWLINE self._y_tF_bnd = y_tF_bndNEWLINENEWLINE def _override_endpoint_bounds(self, y_con_bnd):NEWLINE settings = self.ocp.settingsNEWLINE override = settings.override_endpoint_boundsNEWLINE lower_is_less = y_con_bnd[:, 0] < self._y_bnd[:, 0]NEWLINE if not override and np.any(lower_is_less):NEWLINE msg = (f"")NEWLINE raise ValueError(msg)NEWLINE y_con_bnd[lower_is_less, 0] = self._y_bnd[lower_is_less, 0]NEWLINE upper_is_more = y_con_bnd[:, 1] > self._y_bnd[:, 1]NEWLINE if not override and np.any(upper_is_more):NEWLINE msg = (f"")NEWLINE raise ValueError(msg)NEWLINE y_con_bnd[upper_is_more, 1] = self._y_bnd[upper_is_more, 1]NEWLINE return y_con_bndNEWLINENEWLINE # def _process_potential_dual_value_to_single_value(self, bnd_info, p_info):NEWLINE # bnd = bnd_info.user_bndNEWLINE # msg = (f"Single bounds in this form ('{bnd}') are not supported.")NEWLINE # is_list = isinstance(bnd, SUPPORTED_ITER_TYPES)NEWLINE # if not is_list:NEWLINE # raise TypeError(msg)NEWLINE # is_len_2 = len(bnd) == 2NEWLINE # if not is_len_2:NEWLINE # raise ValueError(msg)NEWLINE # is_pair_same = bnd[0] == bnd[1]NEWLINE # if not is_pair_same:NEWLINE # raise ValueError(msg)NEWLINE # bnd = bnd[0]NEWLINE # bnd_info = bnd_info._replace(user_bnds=bnd)NEWLINE # return bnd_infoNEWLINENEWLINE def _required_variable_bounds(self):NEWLINE y_bnd = self._y_bnd[self._y_needed]NEWLINE u_bnd = self._u_bnd[self._u_needed]NEWLINE q_bnd = self._q_bnd[self._q_needed]NEWLINE t_bnd = self._t_bnd[self._t_needed]NEWLINE x_bnd = np.vstack([y_bnd, u_bnd, q_bnd, t_bnd])NEWLINE return x_bndNEWLINENEWLINENEWLINEclass Bounds:NEWLINENEWLINE def __init__(self, ocp_backend):NEWLINE self.ocp_backend = ocp_backendNEWLINE self.process_and_check_user_values()NEWLINE self.collect_required_variable_bounds()NEWLINE self.collect_required_state_variable_endpoint_bounds()NEWLINE self.collect_constraint_bounds()NEWLINE self.add_unrequired_variables_to_auxiliary_data()NEWLINENEWLINE def process_and_check_user_values(self):NEWLINE for p in self.ocp_backend.p:NEWLINE p.ocp_phase.bounds._process_and_check_user_values(p)NEWLINE self.ocp_backend.ocp.bounds._process_and_check_user_values()NEWLINENEWLINE def collect_required_variable_bounds(self):NEWLINE x_bnd = []NEWLINE for p in self.ocp_backend.p:NEWLINE p_bnds = p.ocp_phase.boundsNEWLINE x_bnd.append(p_bnds._required_variable_bounds())NEWLINE x_bnd.append(self.ocp_backend.ocp.bounds._required_variable_bounds())NEWLINE self.x_bnd = np.vstack(x_bnd)NEWLINENEWLINE def collect_required_state_variable_endpoint_bounds(self):NEWLINE y_t0_bnd = []NEWLINE y_tF_bnd = []NEWLINE for p in self.ocp_backend.p:NEWLINE p_bnd = p.ocp_phase.boundsNEWLINE y_t0_bnd.append(p_bnd._y_t0_bnd[p_bnd._y_needed])NEWLINE y_tF_bnd.append(p_bnd._y_tF_bnd[p_bnd._y_needed])NEWLINE self.y_t0_bnd = np.vstack(y_t0_bnd)NEWLINE self.y_tF_bnd = np.vstack(y_tF_bnd)NEWLINENEWLINE @propertyNEWLINE def x_bnd_lower(self):NEWLINE return self.x_bnd[:, 0]NEWLINENEWLINE @propertyNEWLINE def x_bnd_upper(self):NEWLINE return self.x_bnd[:, 1]NEWLINENEWLINE def collect_constraint_bounds(self):NEWLINE passNEWLINENEWLINE def add_unrequired_variables_to_auxiliary_data(self):NEWLINE self.aux_data = {}NEWLINE for p in self.ocp_backend.p:NEWLINE p_bnd = p.ocp_phase.boundsNEWLINE self.aux_data.update({y: np.mean(value) NEWLINE for y, y_needed, value in zip(NEWLINE p.y_var_full, p_bnd._y_needed, p_bnd._y_bnd) NEWLINE if not y_needed})NEWLINE self.aux_data.update({u: np.mean(value) NEWLINE for u, u_needed, value in zip(NEWLINE p.u_var_full, p_bnd._u_needed, p_bnd._u_bnd) NEWLINE if not u_needed})NEWLINE self.aux_data.update({q: np.mean(value) NEWLINE for q, q_needed, value in zip(NEWLINE p.q_var_full, p_bnd._q_needed, p_bnd._q_bnd) NEWLINE if not q_needed})NEWLINE self.aux_data.update({t: np.mean(value) NEWLINE for t, t_needed, value in zip(NEWLINE p.t_var_full, p_bnd._t_needed, p_bnd._t_bnd) NEWLINE if not t_needed})NEWLINE prob_bnd = self.ocp_backend.ocp.boundsNEWLINE self.aux_data.update({s: np.mean(value) NEWLINE for s, s_needed, value in zip(NEWLINE self.ocp_backend.s_var_full, prob_bnd._s_needed, prob_bnd._s_bnd) NEWLINE if not s_needed})NEWLINENEWLINENEWLINE"""NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE"""NEWLINENEWLINENEWLINEdef process_single_type_of_values(bnds_obj, bnds_info, p_info=None):NEWLINE """Given a `BoundsInfo` object, process and determine if needed.NEWLINENEWLINE Bounds can either be passed by the user as:NEWLINE * a dictionary with the keys as the OCP symbols and the values as theNEWLINE bounds;NEWLINE * no bounds via the use of `None`; orNEWLINE * an iterable of supported type (e.g. tuple, list, np.ndarray) providedNEWLINE that the first dimension is the number of variables/constraints ofNEWLINE that type and the second dimension is either 1 or 2 (depending onNEWLINE the circumstance).NEWLINENEWLINE Note that some forms of bounds are not supported for specific types ofNEWLINE bounds.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE bnds_obj : Union[`EndpointBounds`, `PhaseBounds`]NEWLINE The parent bounds-related object for which this function is processingNEWLINE bounds for.NEWLINE bnds_info : `BoundsInfo`NEWLINE The bounds info that is being processed.NEWLINENEWLINE Returns:NEWLINE --------NEWLINE `tuple`NEWLINE Of length 2 with the first item being a :py:class:`ndarray ` withNEWLINE the correctly formatted bounds and the second item being anotherNEWLINE :py:class:`ndarray ` of type `bool` stating whether the boundsNEWLINE are needed (i.e. have they been determined to be equal in upper andNEWLINE lower bound so that Pycollo can remove them from the OCP and insteadNEWLINE treat them as variables).NEWLINENEWLINE RaisesNEWLINE ------NEWLINE TypeErrorNEWLINE If the bounds supplied by the user are of a type that cannot be handledNEWLINE by Pycollo.NEWLINENEWLINE """NEWLINE if isinstance(bnds_info.user_bnds, dict):NEWLINE bnds = process_mapping_bounds_instance(bnds_obj, bnds_info, p_info)NEWLINE elif bnds_info.user_bnds is None:NEWLINE bnds = process_none_bounds_instance(bnds_obj, bnds_info, p_info)NEWLINE elif isinstance(bnds_info.user_bnds, SUPPORTED_ITER_TYPES):NEWLINE bnds = process_iterable_bounds_instance(bnds_obj, bnds_info, p_info)NEWLINE else:NEWLINE formatted_valid_types = format_for_output(SUPPORTED_ITER_TYPES)NEWLINE msg = (f"Bounds for {bnds_info.bnds_type} cannot be supplied as a "NEWLINE f"{type(bnds_info.user_bnds)}, use one of: "NEWLINE f"{formatted_valid_types}")NEWLINE raise TypeError(msg)NEWLINE bnds, needed = check_lower_against_upper(bnds_obj, bnds, bnds_info, p_info)NEWLINE return bnds, neededNEWLINENEWLINENEWLINEdef process_mapping_bounds_instance(bnds_obj, bnds_info, p_info):NEWLINE """Used to process bounds supplied by the user as a `dict`.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE bnds_obj : Union[`EndpointBounds`, `PhaseBounds`]NEWLINE The parent bounds-related object for which this function is processingNEWLINE bounds for.NEWLINE bnds_info : `BoundsInfo`NEWLINE The bounds info that is being processed.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE listNEWLINE A list of lists with the outer length equal to the number of expectedNEWLINE bounds and the inner lengths all equal to 2.NEWLINENEWLINE RaisesNEWLINE ------NEWLINE TypeErrorNEWLINE If the bounds type is not supported for use of dictionary because thereNEWLINE aren't symbols associated with every variable/constraint of that type.NEWLINENEWLINE """NEWLINE if any(user_sym is None for user_sym in bnds_info.user_syms):NEWLINE msg = f"Can't use mapping for {bnds_info.bnds_type} bounds."NEWLINE raise TypeError(msg)NEWLINE bnds = []NEWLINE for bnd_i, user_sym in enumerate(bnds_info.user_syms):NEWLINE bnd = bnds_info.user_bnds.get(user_sym)NEWLINE bnd_info = BoundsInfo(bnd, user_sym, bnds_info.bnds_type, bnd_i)NEWLINE check_user_bound_missing(bnds_obj, bnd_info, p_info)NEWLINE bnd = as_lower_upper_pair(bnds_obj, bnd_info, p_info)NEWLINE bnds.append(bnd)NEWLINE return bndsNEWLINENEWLINENEWLINEdef check_user_bound_missing(bnds_obj, bnds_info, p_info):NEWLINE """Check if any user-supplied bounds for a specific type are missing.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE bnds_obj : Union[`EndpointBounds`, `PhaseBounds`]NEWLINE The parent bounds-related object for which this function is processingNEWLINE bounds for.NEWLINE bnds_info : `BoundsInfo`NEWLINE The bounds info that is being processed.NEWLINENEWLINE RaisesNEWLINE ------NEWLINE ValueErrorNEWLINE If there are bounds that need to be supplied by aren't.NEWLINENEWLINE """NEWLINE is_bnd_none = bnds_info.user_bnds is NoneNEWLINE is_inf_assumed = bnds_obj.ocp.settings.assume_inf_boundsNEWLINE if is_bnd_none and not is_inf_assumed:NEWLINE msg = (f"No bounds have been supplied for the {bnds_info.bnds_type} "NEWLINE f"'{bnds_info.user_syms}' (index #{bnds_info.num}).")NEWLINE raise ValueError(msg)NEWLINENEWLINENEWLINEdef process_iterable_bounds_instance(bnds_obj, bnds_info, p_info):NEWLINE """Used to process bounds supplied by the user as a `dict`.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE bnds_obj : Union[`EndpointBounds`, `PhaseBounds`]NEWLINE The parent bounds-related object for which this function is processingNEWLINE bounds for.NEWLINE bnds_info : `BoundsInfo`NEWLINE The bounds info that is being processed.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE listNEWLINE A list of lists with the outer length equal to the number of expectedNEWLINE bounds and the inner lengths all equal to 2.NEWLINENEWLINE RaisesNEWLINE ------NEWLINE TypeErrorNEWLINE If the bounds type is not supported for use of dictionary because thereNEWLINE aren't symbols associated with every variable/constraint of that type.NEWLINENEWLINE """NEWLINE supported_iter = isinstance(bnds_info.user_bnds[0], SUPPORTED_ITER_TYPES)NEWLINE if bnds_info.num == 1 and not supported_iter:NEWLINE bnds_info = bnds_info._replace(user_bnds=[bnds_info.user_bnds])NEWLINE bnds = []NEWLINE for bnd_i, bnd in enumerate(bnds_info.user_bnds):NEWLINE bnd_info = BoundsInfo(bnd, None, bnds_info.bnds_type, bnd_i)NEWLINE check_user_bound_missing(bnds_obj, bnd_info, p_info)NEWLINE bnd = as_lower_upper_pair(bnds_obj, bnd_info, p_info)NEWLINE bnds.append(bnd)NEWLINE return bndsNEWLINENEWLINENEWLINEdef process_none_bounds_instance(bnds_obj, bnds_info, p_info):NEWLINE """Used to process bounds supplied by the user as a `dict`.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE bnds_obj : Union[`EndpointBounds`, `PhaseBounds`]NEWLINE The parent bounds-related object for which this function is processingNEWLINE bounds for.NEWLINE bnds_info : `BoundsInfo`NEWLINE The bounds info that is being processed.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE listNEWLINE A list of lists with the outer length equal to the number of expectedNEWLINE bounds and the inner lengths all equal to 2.NEWLINENEWLINE RaisesNEWLINE ------NEWLINE TypeErrorNEWLINE If the bounds type is not supported for use of dictionary because thereNEWLINE aren't symbols associated with every variable/constraint of that type.NEWLINENEWLINE """NEWLINE bnds = []NEWLINE for bnd_i, user_sym in enumerate(bnds_info.user_syms):NEWLINE bnd = NoneNEWLINE bnd_info = BoundsInfo(bnd, user_sym, bnds_info.bnds_type, bnd_i)NEWLINE check_user_bound_missing(bnds_obj, bnd_info, p_info)NEWLINE bnd = as_lower_upper_pair(bnds_obj, bnd_info, p_info)NEWLINE bnds.append(bnd)NEWLINE return bndsNEWLINENEWLINENEWLINEdef as_lower_upper_pair(bnds_obj, bnds_info, p_info):NEWLINE """Get the user-supplied bounds as a lower-upper pair of numeric values.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE bnds_obj : Union[`EndpointBounds`, `PhaseBounds`]NEWLINE The parent bounds-related object for which this function is processingNEWLINE bounds for.NEWLINE bnds_info : `BoundsInfo`NEWLINE The bounds info that is being processed.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE `list`NEWLINE Pair of bounds as a lower bound (first) and an upper bound (second) inNEWLINE a `list`.NEWLINENEWLINE RaisesNEWLINE ------NEWLINE ValueErrorNEWLINE If the flattened user-supplied bounds are not either shape (1, ) orNEWLINE (2, ).NEWLINENEWLINE """NEWLINE bnds = np.array(bnds_info.user_bnds).flatten()NEWLINE if bnds.shape == (1, ):NEWLINE both = "lower and upper bounds"NEWLINE both_info = bnds_info._replace(user_bnds=bnds[0])NEWLINE lower_bnd = get_bound_as_number(bnds_obj, both_info, both, p_info)NEWLINE upper_bnd = lower_bndNEWLINE elif bnds.shape == (2, ):NEWLINE lower = "lower bound"NEWLINE upper = "upper bound"NEWLINE lower_info = bnds_info._replace(user_bnds=bnds[0])NEWLINE upper_info = bnds_info._replace(user_bnds=bnds[1])NEWLINE lower_bnd = get_bound_as_number(bnds_obj, lower_info, lower, p_info)NEWLINE upper_bnd = get_bound_as_number(bnds_obj, upper_info, upper, p_info)NEWLINE else:NEWLINE raise ValueErrorNEWLINE lower_bnd = -bnds_obj._INF if lower_bnd is None else lower_bndNEWLINE upper_bnd = bnds_obj._INF if upper_bnd is None else upper_bndNEWLINE return [lower_bnd, upper_bnd]NEWLINENEWLINENEWLINEdef get_bound_as_number(bnds_obj, bnds_info, lower_upper, p_info):NEWLINE """Format user-supplied bounds to be a number.NEWLINENEWLINE Users can potentially supply bounds as strings (such as "inf" etc.),NEWLINE numerical values from non-core Python (e.g. :py:type`float64 `,NEWLINE :py:type:`DM `), or as symbols (e.g. :py:type:`Symbol `,NEWLINE :py:type:`SX `) provided that they can be resolved as constants dueNEWLINE to auxiliary data supplied by the user.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE bnds_obj : Union[`EndpointBounds`, `PhaseBounds`]NEWLINE The parent bounds-related object for which this function is processingNEWLINE bounds for.NEWLINE bnds_info : `BoundsInfo`NEWLINE The bounds info that is being processed.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE floatNEWLINE The bound as a numerical value.NEWLINENEWLINE RaisesNEWLINE ------NEWLINE ValueErrorNEWLINE If the user-supplied bound is symbolic and contains a symbol primitiveNEWLINE that cannot be resolved down to a numerical value.NEWLINE NotImplementedErrorNEWLINE If the user supplies a string bound that is unsupported, e.g. 'nan'.NEWLINENEWLINE """NEWLINE bnds = bnds_info.user_bndsNEWLINE if bnds is None:NEWLINE return bndsNEWLINE elif isinstance(bnds, str):NEWLINE if bnds == "inf":NEWLINE return bnds_obj._INFNEWLINE elif bnds == "-inf":NEWLINE return -bnds_obj._INFNEWLINE try:NEWLINE bnds = float(bnds)NEWLINE except TypeError:NEWLINE msg = (f"A bound value of {bnds} is not supported.")NEWLINE raise NotImplementedError(msg)NEWLINE if isinstance(bnds, (np.float64, np.int64, float, int)):NEWLINE return float(bnds)NEWLINE bnds = bnds_obj.ocp._backend.substitute_pycollo_sym(bnds)NEWLINE if symbol_primitives(bnds):NEWLINE msg = (f"The user-supplied {lower_upper} for the "NEWLINE f"{bnds_info.bnds_type} '{bnd_info.user_syms}' "NEWLINE f"(index #{bnds_info.num}) of '{bnds}' "NEWLINE f"cannot be precomputed.")NEWLINE raise ValueError(msg)NEWLINE return float(bnds)NEWLINENEWLINENEWLINEdef check_lower_against_upper(bnds_obj, bnds, bnds_info, p_info):NEWLINE """Abstraction layer for checking lower bound against upper bound in pair.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE bnds_obj : Union[`EndpointBounds`, `PhaseBounds`]NEWLINE The parent bounds-related object for which this function is processingNEWLINE bounds for.NEWLINE bnds : `list`NEWLINE The pre-processed bounds.NEWLINE bnds_info : `BoundsInfo`NEWLINE The bounds info that is being processed.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE `tuple`NEWLINE The first index is an :py:type:`ndarray ` of shape (2, ) withNEWLINE the numerical lower and upper bounds for the bound in question and theNEWLINE second index is a `bool` of whether that bound pair is needed in theNEWLINE OCP (`True`) or if it can be treated as a constant (`False`).NEWLINENEWLINE """NEWLINE if not bnds:NEWLINE bnds = np.empty(shape=(0, 2), dtype=float)NEWLINE needed = np.empty(shape=0, dtype=bool)NEWLINE return bnds, neededNEWLINE bnds = np.array(bnds, dtype=float)NEWLINE bnds, needed = check_lower_same_as_upper_to_tol(bnds_obj, bnds, bnds_info,NEWLINE p_info)NEWLINE bnds = check_lower_less_than_upper(bnds_obj, bnds, bnds_info, p_info)NEWLINE return bnds, neededNEWLINENEWLINENEWLINEdef check_lower_same_as_upper_to_tol(bnds_obj, bnds, bnd_info, p_info):NEWLINE """Handle case where bounds are equal to floating precision.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE bnds_obj : Union[`EndpointBounds`, `PhaseBounds`]NEWLINE The parent bounds-related object for which this function is processingNEWLINE bounds for.NEWLINE bnds : `list`NEWLINE The pre-processed bounds.NEWLINE bnds_info : `BoundsInfo`NEWLINE The bounds info that is being processed.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE `tuple`NEWLINE The first index is an :py:type:`ndarray ` of shape (2, ) withNEWLINE the numerical lower and upper bounds for the bound in question and theNEWLINE second index is a `bool` of whether that bound pair is needed in theNEWLINE OCP (`True`) or if it can be treated as a constant (`False`).NEWLINENEWLINE """NEWLINE lower_bnds = bnds[:, 0]NEWLINE upper_bnds = bnds[:, 1]NEWLINE atol = bnds_obj.ocp.settings.bound_clash_relative_toleranceNEWLINE rtol = bnds_obj.ocp.settings.bound_clash_absolute_toleranceNEWLINE are_same = np.isclose(lower_bnds, upper_bnds, rtol=rtol, atol=atol)NEWLINE needed = extract_variables_to_constants(bnds_obj, bnds, are_same)NEWLINE mean_bnds = (lower_bnds + upper_bnds) / 2NEWLINE bnds[are_same, 0] = mean_bnds[are_same]NEWLINE bnds[are_same, 1] = mean_bnds[are_same]NEWLINE return bnds, neededNEWLINENEWLINENEWLINEdef check_lower_less_than_upper(bnds_obj, bnds, bnds_info, p_info):NEWLINE """Ensure the lower bound is less than the upper bound.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE bnds_obj : Union[`EndpointBounds`, `PhaseBounds`]NEWLINE The parent bounds-related object for which this function is processingNEWLINE bounds for.NEWLINE bnds : `list`NEWLINE The pre-processed bounds.NEWLINE bnds_info : `BoundsInfo`NEWLINE The bounds info that is being processed.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE :py:type:`ndarray `NEWLINE The lower-upper bound pair with shape (2, ).NEWLINENEWLINE RaisesNEWLINE ------NEWLINE ValueErrorNEWLINE If any lower bounds are greater than their upper bound.NEWLINENEWLINE """NEWLINE lower_bnds = bnds[:, 0]NEWLINE upper_bnds = bnds[:, 1]NEWLINE lower_less_than_upper = lower_bnds <= upper_bndsNEWLINE all_less_than = np.all(lower_less_than_upper)NEWLINE if not all_less_than:NEWLINE error_indices = np.flatnonzero(~lower_less_than_upper)NEWLINE error_syms = np.array(bnds_info.user_syms)[error_indices]NEWLINE plural_needed = len(error_indices) > 1NEWLINE bound_plural = "bounds" if plural_needed else "bound"NEWLINE index_plural = "indices" if plural_needed else "index"NEWLINE bnds_type_plural = (f"{bnds_info.bnds_type}"NEWLINE f"{'s' if plural_needed else ''}")NEWLINE user_syms_formatted = format_for_output(error_syms)NEWLINE user_indices_formatted = format_for_output(NEWLINE error_indices, wrapping_char="", prefix_char="#")NEWLINE lower_bnds_formatted = format_for_output(lower_bnds[error_indices])NEWLINE upper_bnds_formatted = format_for_output(upper_bnds[error_indices])NEWLINE msg = (f"The user-supplied upper {bound_plural} for the "NEWLINE f"{bnds_type_plural} {user_syms_formatted} ({index_plural} "NEWLINE f"{user_indices_formatted}) of {upper_bnds_formatted} "NEWLINE f"cannot be less than the user-supplied lower "NEWLINE f"{bound_plural} of {lower_bnds_formatted}.")NEWLINE raise ValueError(msg)NEWLINE return bndsNEWLINENEWLINENEWLINEdef extract_variables_to_constants(bnds_obj, bnds, are_same):NEWLINE """NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE bnds_obj : Union[`EndpointBounds`, `PhaseBounds`]NEWLINE The parent bounds-related object for which this function is processingNEWLINE bounds for.NEWLINE bnds : `list`NEWLINE The pre-processed bounds.NEWLINE are_same : `bool`NEWLINE If bounds are equal.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE boolNEWLINE `True` if the bounds pair are needed, `False` if not.NEWLINENEWLINE """NEWLINE if not bnds_obj.ocp.settings.remove_constant_variables:NEWLINE needed = np.full(bnds.shape[0], True)NEWLINE return neededNEWLINE needed = ~are_sameNEWLINE return neededNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE import matplotlib.pyplot as pltNEWLINEfrom sklearn.manifold import TSNENEWLINENEWLINE# Tsne PlotNEWLINEdef tsneplot(embeddings,labels,fig_path):NEWLINE print("********************* tSNE Plot*********************")NEWLINE X = TSNE(n_components=2,perplexity=100,n_iter=1000).fit_transform(embeddings)NEWLINE colors = ['#FF0000', '#06D506', '#0931F7', '#00FFFF', '#FFE500', '#F700FF', '#9300FF', '#FFD700','#10DADE'] # Red , Green, BlueNEWLINE for c in range(len(colors)):NEWLINE points = []NEWLINE for j in range(len(labels)):NEWLINE if (labels[j] == c):NEWLINE points.append(list(X[j]))NEWLINE x = []NEWLINE y = []NEWLINE for z in points:NEWLINE x.append(z[0])NEWLINE y.append(z[1])NEWLINE plt.plot(x, y, 'ro', c=colors[c], markersize=20, marker='.')NEWLINE plt.axis('off')NEWLINE plt.savefig(fig_path)NEWLINE plt.close() class ServerFlushed:NEWLINE def __init__(self, request):NEWLINE self.request = requestNEWLINE import pathlibNEWLINEimport randomNEWLINEimport reNEWLINENEWLINENEWLINEclass Tip:NEWLINE def __init__(self, html=None, ref_url=None, ref_name=None):NEWLINE self.html = htmlNEWLINE self.ref_url = ref_urlNEWLINE self.ref_name = ref_nameNEWLINENEWLINE @staticmethodNEWLINE def parse_meta(meta):NEWLINE meta = meta.split('\n')NEWLINE meta = [kv.split(': ') for kv in meta]NEWLINE meta = {k: v for k, v in meta}NEWLINE return metaNEWLINENEWLINE @classmethodNEWLINE def from_file(cls, path):NEWLINE with open(path, 'r') as f:NEWLINE html = f.read() # .split('\n')NEWLINE try:NEWLINE meta, content = re.split(r'\n-{3,}\n', html, maxsplit=1)NEWLINE except (IndexError, ValueError):NEWLINE return cls('parse error', '', '')NEWLINE meta = cls.parse_meta(meta)NEWLINE return cls(content, **meta)NEWLINENEWLINE def __repr__(self):NEWLINE return self.htmlNEWLINENEWLINE def _repr_html_(self):NEWLINE return self.nice_output()NEWLINENEWLINE def nice_output(self):NEWLINE html = f'''NEWLINE NEWLINE

NEWLINE Source: {self.ref_name}NEWLINE

NEWLINE '''NEWLINE return htmlNEWLINENEWLINENEWLINEdef random_tip():NEWLINE tip_list = pathlib.Path(__file__).parent / 'tip_files'NEWLINE tip_list = list(tip_list.iterdir())NEWLINE tip_file = random.choice(tip_list)NEWLINE tip = Tip.from_file(tip_file)NEWLINE return tipNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE random_tip()NEWLINE custoUnitario = [0.35, 0.45] # variável globalNEWLINEunidadesPorMetro = [37, 30] # variável globalNEWLINEcustoMateriaisPorMetro = [9, 7] # variável globalNEWLINEmetragemParedes = 200 # variável globalNEWLINENEWLINEdef calculaPrecoConstrucao():NEWLINE custosTotais = [] # variável localNEWLINE for i in range(len(custoUnitario)):NEWLINE # variáveis locais: custoTijolos, custoTotalPorMetro e custoTotalNEWLINE custoTijolos = custoUnitario[i] * unidadesPorMetro[i]NEWLINE custoTotalPorMetro = custoTijolos + custoMateriaisPorMetro[i]NEWLINE custoTotal = custoTotalPorMetro * metragemParedesNEWLINE custosTotais.append(custoTotal)NEWLINE print('método', i, custoTotal)NEWLINENEWLINE global menorCustoNEWLINE menorCusto = 100000 # variável globalNEWLINE for custo in custosTotais:NEWLINE if (custo < menorCusto):NEWLINE menorCusto = custoNEWLINENEWLINEcalculaPrecoConstrucao()NEWLINEprint('menor custo:', menorCusto)NEWLINE # Licensed to the Apache Software Foundation (ASF) under one or moreNEWLINE# contributor license agreements. See the NOTICE file distributed withNEWLINE# this work for additional information regarding copyright ownership.NEWLINE# The ASF licenses this file to You under the Apache License, Version 2.0NEWLINE# (the "License"); you may not use this file except in compliance withNEWLINE# the License. You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINEimport sysNEWLINEimport unittestNEWLINEfrom libcloud.utils.py3 import httplibNEWLINENEWLINEfrom libcloud.compute.base import Node, NodeSize, NodeImage, NodeLocationNEWLINEfrom libcloud.compute.drivers.voxel import VoxelNodeDriver as VoxelNEWLINEfrom libcloud.compute.types import InvalidCredsErrorNEWLINENEWLINEfrom libcloud.test import MockHttpNEWLINEfrom libcloud.test.file_fixtures import ComputeFileFixturesNEWLINENEWLINEfrom libcloud.test.secrets import VOXEL_PARAMSNEWLINENEWLINENEWLINEclass VoxelTest(unittest.TestCase):NEWLINENEWLINE def setUp(self):NEWLINENEWLINE Voxel.connectionCls.conn_class = VoxelMockHttpNEWLINE VoxelMockHttp.type = NoneNEWLINE self.driver = Voxel(*VOXEL_PARAMS)NEWLINENEWLINE def test_auth_failed(self):NEWLINE VoxelMockHttp.type = 'UNAUTHORIZED'NEWLINE try:NEWLINE self.driver.list_nodes()NEWLINE except Exception as e:NEWLINE self.assertTrue(isinstance(e, InvalidCredsError))NEWLINE else:NEWLINE self.fail('test should have thrown')NEWLINENEWLINE def test_response_failure(self):NEWLINE VoxelMockHttp.type = 'FAILURE'NEWLINENEWLINE try:NEWLINE self.driver.list_nodes()NEWLINE except Exception:NEWLINE passNEWLINE else:NEWLINE self.fail('Invalid response, but exception was not thrown')NEWLINENEWLINE def test_list_nodes(self):NEWLINE VoxelMockHttp.type = 'LIST_NODES'NEWLINE nodes = self.driver.list_nodes()NEWLINENEWLINE self.assertEqual(len(nodes), 1)NEWLINE self.assertEqual(nodes[0].name, 'www.voxel.net')NEWLINENEWLINE def test_list_sizes(self):NEWLINE sizes = self.driver.list_sizes()NEWLINENEWLINE self.assertEqual(len(sizes), 13)NEWLINENEWLINE def test_list_images(self):NEWLINE VoxelMockHttp.type = 'LIST_IMAGES'NEWLINE images = self.driver.list_images()NEWLINENEWLINE self.assertEqual(len(images), 1)NEWLINENEWLINE def test_list_locations(self):NEWLINE VoxelMockHttp.type = 'LIST_LOCATIONS'NEWLINE locations = self.driver.list_locations()NEWLINENEWLINE self.assertEqual(len(locations), 2)NEWLINE self.assertEqual(locations[0].name, 'Amsterdam')NEWLINENEWLINE def test_create_node_invalid_disk_size(self):NEWLINE image = NodeImage(NEWLINE id=1, name='Ubuntu 8.10 (intrepid)', driver=self.driver)NEWLINE size = NodeSize(NEWLINE 1, '256 slice', None, None, None, None, driver=self.driver)NEWLINE location = NodeLocation(id=1, name='Europe', country='England',NEWLINE driver=self.driver)NEWLINENEWLINE try:NEWLINE self.driver.create_node(name='foo', image=image, size=size,NEWLINE location=location)NEWLINE except ValueError:NEWLINE passNEWLINE else:NEWLINE self.fail('Invalid disk size provided but an exception was not'NEWLINE ' thrown')NEWLINENEWLINE def test_create_node(self):NEWLINE VoxelMockHttp.type = 'CREATE_NODE'NEWLINE image = NodeImage(NEWLINE id=1, name='Ubuntu 8.10 (intrepid)', driver=self.driver)NEWLINE size = NodeSize(NEWLINE 1, '256 slice', 1024, 500, None, None, driver=self.driver)NEWLINE location = NodeLocation(id=1, name='Europe', country='England',NEWLINE driver=self.driver)NEWLINENEWLINE node = self.driver.create_node(name='foo', image=image, size=size,NEWLINE location=location)NEWLINE self.assertEqual(node.id, '1234')NEWLINENEWLINE node = self.driver.create_node(name='foo', image=image, size=size,NEWLINE location=location, ex_voxel_access=True)NEWLINE self.assertEqual(node.id, '1234')NEWLINENEWLINE def test_reboot_node(self):NEWLINE VoxelMockHttp.type = 'REBOOT_NODE'NEWLINE node = Node(NEWLINE id=72258, name=None, state=None, public_ips=None, private_ips=None,NEWLINE driver=self.driver)NEWLINENEWLINE self.assertTrue(node.reboot())NEWLINENEWLINE def test_destroy_node(self):NEWLINE VoxelMockHttp.type = 'DESTROY_NODE'NEWLINE node = Node(NEWLINE id=72258, name=None, state=None, public_ips=None, private_ips=None,NEWLINE driver=self.driver)NEWLINENEWLINE self.assertTrue(node.destroy())NEWLINENEWLINENEWLINEclass VoxelMockHttp(MockHttp):NEWLINENEWLINE fixtures = ComputeFileFixtures('voxel')NEWLINENEWLINE def _UNAUTHORIZED(self, method, url, body, headers):NEWLINE body = self.fixtures.load('unauthorized.xml')NEWLINE return (httplib.OK, body, {}, httplib.responses[httplib.OK])NEWLINENEWLINE def _FAILURE(self, method, url, body, headers):NEWLINE body = self.fixtures.load('failure.xml')NEWLINE return (httplib.OK, body, {}, httplib.responses[httplib.OK])NEWLINENEWLINE def _LIST_NODES(self, method, url, body, headers):NEWLINE body = self.fixtures.load('nodes.xml')NEWLINE return (httplib.OK, body, {}, httplib.responses[httplib.OK])NEWLINENEWLINE def _LIST_IMAGES(self, method, url, body, headers):NEWLINE body = self.fixtures.load('images.xml')NEWLINE return (httplib.OK, body, {}, httplib.responses[httplib.OK])NEWLINENEWLINE def _LIST_LOCATIONS(self, method, url, body, headers):NEWLINE body = self.fixtures.load('locations.xml')NEWLINE return (httplib.OK, body, {}, httplib.responses[httplib.OK])NEWLINENEWLINE def _CREATE_NODE(self, method, url, body, headers):NEWLINE body = self.fixtures.load('create_node.xml')NEWLINE return (httplib.OK, body, {}, httplib.responses[httplib.OK])NEWLINENEWLINE def _REBOOT_NODE(self, method, url, body, headers):NEWLINE body = self.fixtures.load('success.xml')NEWLINE return (httplib.OK, body, {}, httplib.responses[httplib.OK])NEWLINENEWLINE def _DESTROY_NODE(self, method, url, body, headers):NEWLINE body = self.fixtures.load('success.xml')NEWLINE return (httplib.OK, body, {}, httplib.responses[httplib.OK])NEWLINENEWLINEif __name__ == '__main__':NEWLINE sys.exit(unittest.main())NEWLINE #!/usr/bin/env pythonNEWLINENEWLINE# Import modulesNEWLINEfrom pcl_helper import *NEWLINENEWLINENEWLINE# TODO: Define functions as requiredNEWLINENEWLINE# Callback function for your Point Cloud SubscriberNEWLINEdef pcl_callback(pcl_msg):NEWLINE # TODO: Convert ROS msg to PCL dataNEWLINE cloud = ros_to_pcl(pcl_msg)NEWLINENEWLINE # TODO: Voxel Grid DownsamplingNEWLINE # Create a VoxelGrid filter object for our input point cloudNEWLINE vox = cloud.make_voxel_grid_filter()NEWLINENEWLINE # Choose a voxel (also known as leaf) sizeNEWLINE # Note: this (1) is a poor choice of leaf sizeNEWLINE # Experiment and find the appropriate size!NEWLINE LEAF_SIZE = 0.01NEWLINENEWLINE # Set the voxel (or leaf) sizeNEWLINE vox.set_leaf_size(LEAF_SIZE, LEAF_SIZE, LEAF_SIZE)NEWLINENEWLINE # Call the filter function to obtain the resultant downsampled point cloudNEWLINE cloud_filtered = vox.filter()NEWLINENEWLINE # TODO: PassThrough FilterNEWLINE # Create a PassThrough filter object.NEWLINE passthrough = cloud_filtered.make_passthrough_filter()NEWLINENEWLINE # Assign axis and range to the passthrough filter object.NEWLINE filter_axis = 'z'NEWLINE passthrough.set_filter_field_name(filter_axis)NEWLINE axis_min = 0.6NEWLINE axis_max = 1.1NEWLINE passthrough.set_filter_limits(axis_min, axis_max)NEWLINENEWLINE # Finally use the filter function to obtain the resultant point cloud.NEWLINE cloud_filtered = passthrough.filter()NEWLINENEWLINE # TODO: RANSAC Plane SegmentationNEWLINE # Create the segmentation objectNEWLINE seg = cloud_filtered.make_segmenter()NEWLINENEWLINE # Set the model you wish to fitNEWLINE seg.set_model_type(pcl.SACMODEL_PLANE)NEWLINE seg.set_method_type(pcl.SAC_RANSAC)NEWLINENEWLINE # Max distance for a point to be considered fitting the modelNEWLINE # Experiment with different values for max_distanceNEWLINE # for segmenting the tableNEWLINE max_distance = 0.01NEWLINE seg.set_distance_threshold(max_distance)NEWLINE # Call the segment function to obtain set of inlier indices and model coefficientsNEWLINE inliers, coefficients = seg.segment()NEWLINENEWLINE # TODO: Extract inliers and outliersNEWLINE extracted_inliers = cloud_filtered.extract(inliers, negative=False) # tableNEWLINE extracted_outliers = cloud_filtered.extract(inliers, negative=True) # objects on tableNEWLINENEWLINE # TODO: Euclidean ClusteringNEWLINE # Apply function to convert XYZRGB to XYZNEWLINE white_cloud = XYZRGB_to_XYZ(extracted_outliers)NEWLINE tree = white_cloud.make_kdtree()NEWLINE # Create a cluster extraction objectNEWLINE ec = white_cloud.make_EuclideanClusterExtraction()NEWLINE # Set tolerances for distance thresholdNEWLINE # as well as minimum and maximum cluster size (in points)NEWLINE # NOTE: These are poor choices of clustering parametersNEWLINE # Your task is to experiment and find values that work for segmenting objects.NEWLINE ec.set_ClusterTolerance(0.02)NEWLINE ec.set_MinClusterSize(10)NEWLINE ec.set_MaxClusterSize(10000)NEWLINE # Search the k-d tree for clustersNEWLINE ec.set_SearchMethod(tree)NEWLINE # Extract indices for each of the discovered clustersNEWLINE cluster_indices = ec.Extract()NEWLINENEWLINE # TODO: Create Cluster-Mask Point Cloud to visualize each cluster separatelyNEWLINE # Assign a color corresponding to each segmented object in sceneNEWLINE cluster_color = get_color_list(len(cluster_indices))NEWLINENEWLINE color_cluster_point_list = []NEWLINENEWLINE for j, indices in enumerate(cluster_indices):NEWLINE for i, indice in enumerate(indices):NEWLINE color_cluster_point_list.append([white_cloud[indice][0],NEWLINE white_cloud[indice][1],NEWLINE white_cloud[indice][2],NEWLINE rgb_to_float(cluster_color[j])])NEWLINENEWLINE # Create new cloud containing all clusters, each with unique colorNEWLINE cluster_cloud = pcl.PointCloud_PointXYZRGB()NEWLINE cluster_cloud.from_list(color_cluster_point_list)NEWLINENEWLINE # TODO: Convert PCL data to ROS messagesNEWLINE ros_objects_cloud = pcl_to_ros(extracted_outliers)NEWLINE ros_table_cloud = pcl_to_ros(extracted_inliers)NEWLINE ros_cluster_cloud = pcl_to_ros(cluster_cloud)NEWLINENEWLINE # TODO: Publish ROS messagesNEWLINE pcl_objects_pub.publish(ros_objects_cloud)NEWLINE pcl_table_pub.publish(ros_table_cloud)NEWLINE pcl_cluster_pub.publish(ros_cluster_cloud)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINENEWLINE # TODO:ROS node initializationNEWLINE rospy.init_node('clustering', anonymous=True)NEWLINENEWLINE # TODO: Create SubscribersNEWLINE pcl_sub = rospy.Subscriber("/sensor_stick/point_cloud", pc2.PointCloud2, pcl_callback, queue_size=1)NEWLINENEWLINE # TODO: Create PublishersNEWLINE pcl_objects_pub = rospy.Publisher("/pcl_objects", PointCloud2, queue_size=1)NEWLINE pcl_table_pub = rospy.Publisher("/pcl_table", PointCloud2, queue_size=1)NEWLINE pcl_cluster_pub = rospy.Publisher("/pcl_cluster", PointCloud2, queue_size=1)NEWLINENEWLINE # Initialize color_listNEWLINE get_color_list.color_list = []NEWLINENEWLINE # TODO: Spin while node is not shutdownNEWLINE while not rospy.is_shutdown():NEWLINE rospy.spin()NEWLINE # coding=utf-8NEWLINE# Copyright 2019 The Google Research Authors.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINE# Lint as: python2, python3NEWLINE"""Binary for running temperature scaling, writing temperature param to disk."""NEWLINENEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINENEWLINEfrom __future__ import print_functionNEWLINENEWLINEimport jsonNEWLINEimport osNEWLINENEWLINEfrom absl import appNEWLINEfrom absl import flagsNEWLINENEWLINEimport numpy as npNEWLINEimport tensorflow.compat.v2 as tfNEWLINENEWLINEfrom uq_benchmark_2019 import array_utilsNEWLINEfrom uq_benchmark_2019 import calibration_libNEWLINEfrom uq_benchmark_2019 import metrics_libNEWLINEfrom uq_benchmark_2019 import uq_utilsNEWLINENEWLINEgfile = tf.io.gfileNEWLINEFLAGS = flags.FLAGSNEWLINENEWLINENUM_EXAMPLES = 20000NEWLINENEWLINENEWLINEdef _declare_flags():NEWLINE """Declare flags; not invoked when this module is imported as a library."""NEWLINE flags.DEFINE_string('prediction_path', None, 'Path to predictions file.')NEWLINENEWLINENEWLINEdef run(prediction_path):NEWLINE """Run temperature scaling."""NEWLINE stats = array_utils.load_stats_from_tfrecords(prediction_path)NEWLINE probs = stats['probs'].astype(np.float32)NEWLINE labels = stats['labels'].astype(np.int32)NEWLINE if len(labels.shape) > 1:NEWLINE labels = np.squeeze(labels, -1)NEWLINENEWLINE if probs.shape[0] > NUM_EXAMPLES:NEWLINE probs = probs[:NUM_EXAMPLES, :]NEWLINE labels = labels[:NUM_EXAMPLES]NEWLINENEWLINE probs = metrics_lib.soften_probabilities(probs=probs)NEWLINE logits = uq_utils.np_inverse_softmax(probs)NEWLINE temp = calibration_lib.find_scaling_temperature(labels, logits)NEWLINE with gfile.GFile(NEWLINE os.path.join(os.path.dirname(prediction_path),NEWLINE 'temperature_hparam.json'), 'w') as fh:NEWLINE fh.write(json.dumps({'temperature': temp}))NEWLINENEWLINENEWLINEdef main(argv):NEWLINE if len(argv) > 1:NEWLINE raise app.UsageError('Too many command-line arguments.')NEWLINE tf.enable_v2_behavior()NEWLINE run(FLAGS.prediction_path)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE _declare_flags()NEWLINE app.run(main)NEWLINE import argparseNEWLINENEWLINEfrom .virsh_cleanup import DEFAULT_SKIP_LIST, clean_virsh_resources, logNEWLINENEWLINENEWLINEdef _get_parsed_args() -> argparse.Namespace:NEWLINE parser = argparse.ArgumentParser(description="Clear libvrt resources")NEWLINE group = parser.add_mutually_exclusive_group()NEWLINE group.add_argument("-a", "--all", help="Clean all virsh resources", action="store_true")NEWLINE group.add_argument("-m", "--minikube", help="Clean only minikube resources", action="store_true")NEWLINE group.add_argument("--skip-minikube", help="Clean all but skip minikube resources", action="store_true")NEWLINE group.add_argument(NEWLINE "-f",NEWLINE "--filter",NEWLINE help="List of filter of resources to delete",NEWLINE nargs="*",NEWLINE type=str,NEWLINE default=None,NEWLINE )NEWLINE return parser.parse_args()NEWLINENEWLINENEWLINEdef main():NEWLINE log.info("===== CLEANING VIRSH RESOURCES =====")NEWLINE p_args = _get_parsed_args()NEWLINE skip_list = DEFAULT_SKIP_LISTNEWLINE resource_filter = []NEWLINE if p_args.minikube:NEWLINE resource_filter.append("minikube")NEWLINE elif p_args.filter:NEWLINE resource_filter = p_args.filterNEWLINE else:NEWLINE skip_list.extend(["minikube", "minikube-net"])NEWLINENEWLINE clean_virsh_resources(skip_list, resource_filter)NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE main()NEWLINE from Node import NodeNEWLINEfrom shutil import rmtreeNEWLINE# from config_creator import create_file_structureNEWLINEfrom sesamutils import sesam_loggerNEWLINEfrom os import mkdirNEWLINEfrom git import RepoNEWLINEimport subprocessNEWLINEfrom json import dumps as dump_jsonNEWLINENEWLINENEWLINEclass Gitter:NEWLINE def __init__(self, url, username, password_or_token, folder, branch):NEWLINE self.url = urlNEWLINE self.username = usernameNEWLINE self.password_or_token = password_or_tokenNEWLINE self.folder = folderNEWLINE self.branch = branchNEWLINENEWLINE self.LOGGER = sesam_logger('Git')NEWLINENEWLINE self.repo = self.clone_repo()NEWLINENEWLINE def clone_repo(self):NEWLINE self.try_to_delete_dir(self.folder)NEWLINE url = f'https://{self.username}:{self.password_or_token}@{self.url}'NEWLINE repo = Repo.clone_from(url, self.folder, branch=self.branch)NEWLINE return repoNEWLINENEWLINE def push_if_diff(self, dry_run=False):NEWLINE if self.is_there_a_diff():NEWLINE if dry_run:NEWLINE self.LOGGER.info('Dry run! Skipping push to repo.')NEWLINE else:NEWLINE self.push()NEWLINE self.LOGGER.info('Successfully pushed to git repo!')NEWLINE else:NEWLINE self.LOGGER.info('No current diff! Skipping push to repo.')NEWLINENEWLINE def is_there_a_diff(self):NEWLINE import subprocessNEWLINE bashCommand = 'git status'NEWLINE process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE, cwd=self.repo.working_dir + '/node/')NEWLINE output, error = process.communicate()NEWLINE if output.endswith(b"working tree clean\n"):NEWLINE return FalseNEWLINE else:NEWLINE self.LOGGER.info(f'Git status result : "{output}"')NEWLINE return TrueNEWLINENEWLINE def push(self):NEWLINE self.LOGGER.debug(f"Pushing to git repo {self.repo.remote}")NEWLINE self.repo.git.add([self.repo.working_dir])NEWLINE self.repo.index.commit(message='Update based on master node config')NEWLINE origin = self.repo.remote('origin')NEWLINE origin.push()NEWLINENEWLINE def try_to_delete_dir(self, directory):NEWLINE try:NEWLINE self.LOGGER.debug(f'Deleting directory "{directory}"')NEWLINE rmtree(directory, ignore_errors=True)NEWLINE except FileNotFoundError:NEWLINE self.LOGGER.info(f'Did not delete "{directory}" because it does not exist!.')NEWLINENEWLINE def try_to_make_dir(self, directory):NEWLINE try:NEWLINE self.LOGGER.debug(f'Creating directory "{directory}"')NEWLINE mkdir(directory)NEWLINE except FileExistsError:NEWLINE self.LOGGER.info(f'Did not create "{directory}" because it already exists!')NEWLINENEWLINE def create_node_file_structure(self, node: Node, env):NEWLINE self.try_to_delete_dir(f'{self.repo.working_dir}/node')NEWLINE for p in [NEWLINE f'{self.repo.working_dir}/node/',NEWLINE f'{self.repo.working_dir}/node/pipes/',NEWLINE f'{self.repo.working_dir}/node/systems/',NEWLINE f'{self.repo.working_dir}/node/variables/'NEWLINE ]:NEWLINE self.try_to_make_dir(p)NEWLINE tmp_file = NoneNEWLINE for conf in node.conf:NEWLINE if conf['type'] == 'pipe':NEWLINE tmp_file = open(f'{self.repo.working_dir}/node/pipes/{conf["_id"]}.conf.json', 'w+')NEWLINE if 'system' in conf['type']:NEWLINE tmp_file = open(f'{self.repo.working_dir}/node/systems/{conf["_id"]}.conf.json', 'w+')NEWLINE if conf['type'] == 'metadata':NEWLINE tmp_file = open(f'{self.repo.working_dir}/node/node-metadata.conf.json', 'w+')NEWLINE tmp_file.write(dump_json(conf, indent=2))NEWLINE if len([key for key in node.upload_vars]) != 0:NEWLINE tmp_file = open(f'{self.repo.working_dir}/node/variables/variables-{env}.json', 'w+')NEWLINE tmp_file.write(dump_json(node.upload_vars, indent=2))NEWLINE # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License").NEWLINE# You may not use this file except in compliance with the License.NEWLINE# A copy of the License is located atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# or in the "license" file accompanying this file. This file is distributedNEWLINE# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, eitherNEWLINE# express or implied. See the License for the specific language governingNEWLINE# permissions and limitations under the License.NEWLINENEWLINE# Standard library importsNEWLINEfrom typing import Dict, Optional, Tuple, ListNEWLINENEWLINE# Third-party importsNEWLINEimport numpy as npNEWLINENEWLINE# First-party importsNEWLINEfrom gluonts.model.common import TensorNEWLINEfrom gluonts.core.component import validatedNEWLINENEWLINE# Relative importsNEWLINEfrom .distribution import Distribution, _sample_multiple, getF, softplusNEWLINEfrom .distribution_output import DistributionOutputNEWLINENEWLINENEWLINEclass NegativeBinomial(Distribution):NEWLINE r"""NEWLINE Negative binomial distribution, i.e. the distribution of the number ofNEWLINE successes in a sequence of independet Bernoulli trials.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE muNEWLINE Tensor containing the means, of shape `(*batch_shape, *event_shape)`.NEWLINE alphaNEWLINE Tensor of the shape parameters, of shape `(*batch_shape, *event_shape)`.NEWLINE FNEWLINE """NEWLINENEWLINE is_reparameterizable = FalseNEWLINENEWLINE @validated()NEWLINE def __init__(self, mu: Tensor, alpha: Tensor, F=None) -> None:NEWLINE self.mu = muNEWLINE self.alpha = alphaNEWLINE self.F = F if F else getF(mu)NEWLINENEWLINE @propertyNEWLINE def batch_shape(self) -> Tuple:NEWLINE return self.mu.shapeNEWLINENEWLINE @propertyNEWLINE def event_shape(self) -> Tuple:NEWLINE return ()NEWLINENEWLINE @propertyNEWLINE def event_dim(self) -> int:NEWLINE return 0NEWLINENEWLINE def log_prob(self, x: Tensor) -> Tensor:NEWLINE alphaInv = 1.0 / self.alphaNEWLINE alpha_times_mu = self.alpha * self.muNEWLINE F = self.FNEWLINE ll = (NEWLINE x * F.log(alpha_times_mu / (1.0 + alpha_times_mu))NEWLINE - alphaInv * F.log1p(alpha_times_mu)NEWLINE + F.gammaln(x + alphaInv)NEWLINE - F.gammaln(x + 1.0)NEWLINE - F.gammaln(alphaInv)NEWLINE )NEWLINE return llNEWLINENEWLINE @propertyNEWLINE def mean(self) -> Tensor:NEWLINE return self.muNEWLINENEWLINE @propertyNEWLINE def stddev(self) -> Tensor:NEWLINE return self.F.sqrt(self.mu * (1.0 + self.mu * self.alpha))NEWLINENEWLINE def sample(NEWLINE self, num_samples: Optional[int] = None, dtype=np.float32NEWLINE ) -> Tensor:NEWLINE def s(mu: Tensor, alpha: Tensor) -> Tensor:NEWLINE F = self.FNEWLINE tol = 1e-5NEWLINE r = 1.0 / alphaNEWLINE theta = alpha * muNEWLINE r = F.minimum(F.maximum(tol, r), 1e10)NEWLINE theta = F.minimum(F.maximum(tol, theta), 1e10)NEWLINE x = F.minimum(F.random.gamma(r, theta), 1e6)NEWLINE return F.random.poisson(lam=x, dtype=dtype)NEWLINENEWLINE return _sample_multiple(NEWLINE s, mu=self.mu, alpha=self.alpha, num_samples=num_samplesNEWLINE )NEWLINENEWLINE @propertyNEWLINE def args(self) -> List:NEWLINE return [self.mu, self.alpha]NEWLINENEWLINENEWLINEclass NegativeBinomialOutput(DistributionOutput):NEWLINE args_dim: Dict[str, int] = {"mu": 1, "alpha": 1}NEWLINE distr_cls: type = NegativeBinomialNEWLINENEWLINE @classmethodNEWLINE def domain_map(cls, F, mu, alpha):NEWLINE epsilon = np.finfo(cls._dtype).eps # machine epsilonNEWLINENEWLINE mu = softplus(F, mu) + epsilonNEWLINE alpha = softplus(F, alpha) + epsilonNEWLINE return mu.squeeze(axis=-1), alpha.squeeze(axis=-1)NEWLINENEWLINE # Overwrites the parent class method.NEWLINE # We cannot scale using the affine transformation since negative binomial should return integers.NEWLINE # Instead we scale the parameters.NEWLINE def distribution(NEWLINE self,NEWLINE distr_args,NEWLINE loc: Optional[Tensor] = None,NEWLINE scale: Optional[Tensor] = None,NEWLINE ) -> NegativeBinomial:NEWLINE assert loc is NoneNEWLINE mu, alpha = distr_argsNEWLINE if scale is None:NEWLINE return NegativeBinomial(mu, alpha)NEWLINE else:NEWLINE F = getF(mu)NEWLINE mu = F.broadcast_mul(mu, scale)NEWLINE alpha = F.broadcast_mul(alpha, F.sqrt(scale + 1.0))NEWLINE return NegativeBinomial(mu, alpha, F)NEWLINENEWLINE @propertyNEWLINE def event_shape(self) -> Tuple:NEWLINE return ()NEWLINE """Testing handling with CoreState."""NEWLINENEWLINEfrom supervisor.coresys import CoreSysNEWLINENEWLINENEWLINEasync def test_timezone(run_dir, coresys: CoreSys):NEWLINE """Test write corestate to /run/supervisor."""NEWLINENEWLINE assert coresys.timezone == "UTC"NEWLINE assert coresys.config.timezone is NoneNEWLINENEWLINE await coresys.dbus.timedate.connect()NEWLINE await coresys.dbus.timedate.update()NEWLINE assert coresys.timezone == "Etc/UTC"NEWLINENEWLINE coresys.config.timezone = "Europe/Zurich"NEWLINE assert coresys.timezone == "Europe/Zurich"NEWLINE QUERY = """NEWLINEquery searchByQuery($query:SearchQueryJson!$testListings:Boolean!$smartHide:Boolean$recentHides:[ListingId!])@debug(testListings:$testListings){rentSearch(query:$query smartHide:$smartHide recentHides:$recentHides){...RentResultsMetaData resolvedQuery{...SearchMetadata ...ResultsHeading ...SeoFooterLinks ...SearchResultsBreadcrumb __typename}marketInsights{...ResultsMarketInsightsData __typename}exclusiveShowcase{...RentExclusiveShowcaseData __typename}results{...ResultsSummary ...ResultsPagination ...RentResultsSet ...SearchResultsTotalCount exact{totalCount items{listing{...on RentResidentialListing{id productDepth __typename}...PropertyCard ...RentDetailsAboveTheFold __typename}__typename}__typename}surrounding{items{listing{...on RentResidentialListing{id productDepth __typename}...PropertyCard ...RentDetailsAboveTheFold __typename}__typename}__typename}trackingData totalResultsCount __typename}consumerContext{loggedInStatus __typename}__typename}}fragment RentResultsMetaData on RentResolvedSearch{resolvedQuery{localities{display __typename}__typename}results{__typename totalResultsCount pagination{moreResultsAvailable __typename}exact{items{listing{__typename ...on RentResidentialListing{inspections{startTime endTime __typename}_links{canonical{href __typename}__typename}__typename}...ResidentialListingAddressMetaData}__typename}__typename}}__typename}fragment ResidentialListingAddressMetaData on ResidentialListing{address{display{shortAddress fullAddress __typename}suburb state postcode __typename}__typename}fragment SearchMetadata on ResolvedQuery{metadata{canonicalSearchId savedSearchQuery __typename}__typename}fragment ResultsHeading on ResolvedQuery{localities{display __typename}__typename}fragment SeoFooterLinks on ResolvedQuery{localities{display atlasId urlValue precision name __typename}__typename}fragment SearchResultsBreadcrumb on ResolvedQuery{localities{atlasId display name urlValue precision state parents{display name urlValue precision __typename}__typename}__typename}fragment ResultsMarketInsightsData on MarketInsights{title suburbProfileUrl{href __typename}__typename}fragment RentExclusiveShowcaseData on ExclusiveShowcase{...CommonExclusiveShowcaseData listings{...on RentResidentialListing{inspections{display{shortLabel __typename}__typename}__typename}__typename}__typename}fragment CommonExclusiveShowcaseData on ExclusiveShowcase{listings{title id listingCompany{id name media{logo{templatedUrl __typename}__typename}branding{primaryColour textColour __typename}__typename}media{mainImage{templatedUrl __typename}images{templatedUrl __typename}__typename}address{suburb display{shortAddress __typename}__typename}listers{name photo{templatedUrl __typename}__typename}_links{trackedCanonical{path __typename}__typename}...PrimaryFeatures __typename}__typename}fragment PrimaryFeatures on ResidentialListing{...GeneralFeatures ...PropertySize __typename}fragment GeneralFeatures on ResidentialListing{generalFeatures{bedrooms{value __typename}bathrooms{value __typename}parkingSpaces{value __typename}__typename}__typename}fragment PropertySize on ResidentialListing{propertySizes{building{displayValue sizeUnit{displayValue __typename}__typename}land{displayValue sizeUnit{displayValue __typename}__typename}preferred{sizeType size{displayValue sizeUnit{displayValue __typename}__typename}__typename}__typename}__typename}fragment ResultsSummary on SearchResults{totalResultsCount pagination{page pageSize __typename}__typename}fragment ResultsPagination on SearchResults{pagination{maxPageNumberAvailable __typename}__typename}fragment RentResultsSet on RentSearchResults{exact{items{listing{__typename}__typename}__typename}surrounding{totalCount items{listing{__typename}__typename}__typename}pagination{page __typename}__typename}fragment SearchResultsTotalCount on SearchResults{totalResultsCount __typename}fragment PropertyCard on Listing{__typename ...ResidentialPropertyCard ...ProjectProfile}fragment ResidentialPropertyCard on ResidentialListing{...PropertyCardLayout ...BrandingOnSearchResultsConfig ...BrandingResidential badge{...Badge __typename}...ResidentialListingCardHero ...Price ...ResidentialListingCardAddress ...PropertyCardPropertyType ...PropertyCardDetailsLink ...PropertyCardAgentInfo ...ResidentialLaunchButtons ...ResidentialMediaViewerForResults ...ResidentialListingBookmark ...PrimaryFeatures ...PropertySize ...ResidentialListingCardInspection ...InspectionAuction ...DateSold ...ResidentialListingMoreButton ...ResidentialShareListing __typename}fragment PropertyCardLayout on ResidentialListing{productDepth __typename}fragment BrandingOnSearchResultsConfig on ResidentialListing{viewConfiguration{searchResults{agencyBranding __typename}__typename}productDepth __typename}fragment BrandingResidential on ResidentialListing{listingCompany{...Branding __typename}__typename}fragment Branding on ListingCompany{id name branding{primaryColour __typename}media{logo{templatedUrl __typename}__typename}__typename}fragment Badge on ListingBadge{colour label __typename}fragment ResidentialListingCardHero on ResidentialListing{...PowerProfileSlide productDepth address{display{fullAddress __typename}__typename}media{mainImage{templatedUrl __typename}images{templatedUrl __typename}floorplans{templatedUrl __typename}__typename}__typename}fragment PowerProfileSlide on ResidentialListing{media{mainImage{templatedUrl __typename}__typename}_links{canonical{path __typename}__typename}listingCompany{name media{logo{templatedUrl __typename}__typename}branding{primaryColour __typename}_links{canonical{href __typename}__typename}__typename}listers{id agentId name jobTitle photo{templatedUrl __typename}_links{canonical{href __typename}__typename}showInMediaViewer __typename}__typename}fragment Price on ResidentialListing{price{display __typename}__typename}fragment ResidentialListingCardAddress on ResidentialListing{address{suburb display{shortAddress __typename}__typename}__typename}fragment PropertyCardPropertyType on ResidentialListing{propertyType{display __typename}__typename}fragment PropertyCardDetailsLink on ResidentialListing{_links{canonical{path __typename}__typename}__typename}fragment PropertyCardAgentInfo on ResidentialListing{viewConfiguration{searchResults{agentPhoto agentName __typename}__typename}listers{name photo{templatedUrl __typename}__typename}listingCompany{branding{textColour __typename}__typename}__typename}fragment ResidentialLaunchButtons on ResidentialListing{media{threeDimensionalTours{href __typename}videos{...on YouTubeVideo{id __typename}...on ExternalVideo{href __typename}__typename}__typename}__typename}fragment ResidentialMediaViewerForResults on ResidentialListing{...ResultsAdConfiguration ...ResidentialSlides __typename}fragment ResultsAdConfiguration on ResidentialListing{viewConfiguration{searchResults{adverts{photoGallery __typename}__typename}__typename}__typename}fragment ResidentialSlides on ResidentialListing{...PowerProfileSlide ...MediaViewerEventTracking ...ThreeDimensionalTourSlide ...VideoSlide ...PhotoOverlayWithGallerySlide media{images{templatedUrl __typename}floorplans{templatedUrl __typename}__typename}__typename}fragment MediaViewerEventTracking on ResidentialListing{listers{id agentId __typename}__typename}fragment ThreeDimensionalTourSlide on ResidentialListing{media{threeDimensionalTours{href __typename}__typename}__typename}fragment VideoSlide on ResidentialListing{media{videos{...on YouTubeVideo{__typename id}__typename}__typename}__typename}fragment PhotoOverlayWithGallerySlide on ResidentialListing{...BuilderProfile ...ParentAndSiblings __typename}fragment BuilderProfile on ResidentialListing{media{mainImage{templatedUrl __typename}__typename}listingCompany{...on Builder{name _links{canonical{templated href __typename}__typename}homeDesigns{totalCount designs{name price houseSizeRange{min{displayValue value __typename}max{displayValue value __typename}__typename}generalFeaturesDisplay{bedrooms bathrooms parkingSpaces __typename}_links{canonical{href templated __typename}__typename}media{mainImage{templatedUrl __typename}__typename}__typename}__typename}__typename}__typename}__typename}fragment ParentAndSiblings on BuyResidentialListing{id media{mainImage{templatedUrl __typename}__typename}parent{name _links{canonical{path __typename}__typename}childListings{totalCount results{id media{mainImage{templatedUrl __typename}__typename}title price{display __typename}propertyType{display __typename}_links{canonical{path __typename}__typename}propertySizes{land{displayValue sizeUnit{id displayValue __typename}__typename}__typename}...PrimaryFeatures __typename}__typename}__typename}__typename}fragment ResidentialListingBookmark on ResidentialListing{id __typename}fragment ResidentialListingCardInspection on ResidentialListing{...on BuyResidentialListing{inspections{display{shortLabel longLabel __typename}__typename}__typename}...on RentResidentialListing{inspections{display{shortLabel longLabel __typename}__typename}__typename}__typename}fragment InspectionAuction on ResidentialListing{...PropertyCardAuctionDate ...ResidentialListingCardInspection __typename}fragment PropertyCardAuctionDate on BuyResidentialListing{auction{dateTime{display{shortDate __typename}__typename}__typename}__typename}fragment DateSold on ResidentialListing{...on SoldResidentialListing{dateSold{display __typename}__typename}__typename}fragment ResidentialListingMoreButton on ResidentialListing{id __typename}fragment ResidentialShareListing on ResidentialListing{_links{canonical{href __typename}__typename}address{display{fullAddress __typename}__typename}__typename}fragment ProjectProfile on ProjectProfile{badge{...Badge __typename}...ProjectProfileCardParentListing ...ProjectProfileCardAddress ...ProjectProfileCardHero ...ProjectProfileAgency ...ProjectProfileBranding ...ProjectProfileBookmark ...PropertyCardChildListings ...ProjectLaunchButtons ...ProjectProfileNextOpenTime __typename}fragment ProjectProfileCardParentListing on ProjectProfile{name title productDepth _links{canonical{path __typename}__typename}__typename}fragment ProjectProfileCardAddress on ProjectProfile{address{suburb display{shortAddress __typename}__typename}__typename}fragment ProjectProfileCardHero on ProjectProfile{productDepth address{display{fullAddress __typename}__typename}media{mainImage{templatedUrl __typename}images{templatedUrl __typename}__typename}__typename}fragment ProjectProfileAgency on ProjectProfile{listingCompany{id name media{logo{templatedUrl __typename}__typename}__typename}viewConfiguration{searchResults{agencyBranding __typename}__typename}__typename}fragment ProjectProfileBranding on ProjectProfile{name productDepth media{logo{templatedUrl __typename}__typename}branding{primaryColour __typename}__typename}fragment ProjectProfileBookmark on ProjectProfile{id __typename}fragment PropertyCardChildListings on ProjectProfile{productDepth _links{canonical{path __typename}__typename}childListings{totalCount results{id price{display __typename}media{mainImage{templatedUrl __typename}__typename}address{display{fullAddress __typename}__typename}title _links{canonical{path __typename}__typename}...PrimaryFeatures __typename}__typename}__typename}fragment ProjectLaunchButtons on ProjectProfile{media{videos{...on YouTubeVideo{id __typename}...on ExternalVideo{href __typename}__typename}__typename}__typename}fragment ProjectProfileNextOpenTime on ProjectProfile{displayLocation{nextAvailableOpeningHours{nextAvailable{display{shortLabel longLabel __typename}__typename}__typename}__typename}__typename}fragment RentDetailsAboveTheFold on RentResidentialListing{aboveTheFoldId:id id badge{...Badge __typename}...Hero ...Price ...Address ...ResidentialShareListing ...Breadcrumb_ResidentialListing ...PrimaryFeatures ...PropertyCardPropertyType ...PropertyInfoPosterBoard ...InspectionsSummaryForRent ...Bond ...DateAvailableSummary ...BrandingOnContactAgentPanelConfig ...ResidentialContactAgentBranding ...AgentInfo ...AgencyInfo ...HeaderLeaderboard ...ListingCompanyHeaderBranding ...RentResidentialListingMetaData __typename}fragment Hero on ResidentialListing{...HeroImage ...ResidentialMediaTypeBar __typename}fragment HeroImage on ResidentialListing{address{display{fullAddress __typename}__typename}viewConfiguration{details{posterBoard __typename}__typename}media{mainImage{templatedUrl __typename}images{templatedUrl __typename}floorplans{templatedUrl __typename}threeDimensionalTours{href __typename}videos{...on YouTubeVideo{id __typename}...on ExternalVideo{href __typename}__typename}__typename}__typename}fragment ResidentialMediaTypeBar on ResidentialListing{media{images{templatedUrl __typename}floorplans{templatedUrl __typename}threeDimensionalTours{href __typename}videos{...on YouTubeVideo{id __typename}...on ExternalVideo{href __typename}__typename}__typename}__typename}fragment Address on ResidentialListing{address{suburb postcode state display{shortAddress __typename}__typename}__typename}fragment Breadcrumb_ResidentialListing on ResidentialListing{__typename id address{suburb state postcode display{shortAddress __typename}__typename}propertyType{id display __typename}_links{canonical{path __typename}__typename}}fragment PropertyInfoPosterBoard on ResidentialListing{viewConfiguration{details{posterBoard __typename}__typename}__typename}fragment InspectionsSummaryForRent on RentResidentialListing{inspections{display{longLabel __typename}__typename}__typename}fragment Bond on RentResidentialListing{bond{display __typename}__typename}fragment DateAvailableSummary on RentResidentialListing{availableDate{display __typename}__typename}fragment BrandingOnContactAgentPanelConfig on ResidentialListing{viewConfiguration{details{agencyBrandingOnSidePanel __typename}__typename}__typename}fragment ResidentialContactAgentBranding on ResidentialListing{productDepth listingCompany{name branding{primaryColour __typename}media{logo{templatedUrl __typename}__typename}_links{canonical{href __typename}__typename}__typename}__typename}fragment AgentInfo on ResidentialListing{listers{name photo{templatedUrl __typename}preferredPhoneNumber _links{canonical{href __typename}__typename}__typename}listingCompany{id businessPhone __typename}__typename}fragment AgencyInfo on ResidentialListing{viewConfiguration{details{agencyInfo __typename}__typename}listingCompany{...on Agency{name __typename address{display{fullAddress __typename}__typename}_links{canonical{href __typename}__typename}}__typename}__typename}fragment HeaderLeaderboard on ResidentialListing{viewConfiguration{details{adverts{headerLeaderboard __typename}__typename}__typename}__typename}fragment ListingCompanyHeaderBranding on ResidentialListing{viewConfiguration{details{branding{header{size __typename}__typename}__typename}__typename}listingCompany{name branding{primaryColour __typename}_links{canonical{href __typename}__typename}media{logo{templatedUrl __typename}__typename}__typename}__typename}fragment RentResidentialListingMetaData on RentResidentialListing{...ResidentialListingMetaData inspections{startTime endTime __typename}__typename}fragment ResidentialListingMetaData on ResidentialListing{__typename id description media{mainImage{templatedUrl __typename}images{__typename}__typename}_links{canonical{href path __typename}__typename}propertyType{id display __typename}address{display{shortAddress fullAddress __typename}suburb state postcode __typename}price{display __typename}generalFeatures{bedrooms{value __typename}__typename}propertySizes{land{displayValue sizeUnit{displayValue __typename}__typename}__typename}}NEWLINE"""NEWLINE from __future__ import absolute_importNEWLINENEWLINE__all__ = ["from_user", "from_member", "DEFAULT"]NEWLINENEWLINEimport warningsNEWLINENEWLINEfrom django.conf import settingsNEWLINEfrom django.utils.functional import cached_propertyNEWLINENEWLINEfrom sentry import rolesNEWLINEfrom sentry.auth.superuser import is_active_superuserNEWLINEfrom sentry.auth.system import is_system_authNEWLINEfrom sentry.models import (NEWLINE AuthIdentity,NEWLINE AuthProvider,NEWLINE OrganizationMember,NEWLINE Project,NEWLINE ProjectStatus,NEWLINE SentryApp,NEWLINE UserPermission,NEWLINE Team,NEWLINE)NEWLINENEWLINENEWLINEdef _sso_params(member):NEWLINE """NEWLINE Return a tuple of (requires_sso, sso_is_valid) for a given member.NEWLINE """NEWLINE # TODO(dcramer): we want to optimize this access pattern as its severalNEWLINE # network hops and needed in a lot of placesNEWLINE try:NEWLINE auth_provider = AuthProvider.objects.get(organization=member.organization_id)NEWLINE except AuthProvider.DoesNotExist:NEWLINE sso_is_valid = TrueNEWLINE requires_sso = FalseNEWLINE else:NEWLINE if auth_provider.flags.allow_unlinked:NEWLINE requires_sso = FalseNEWLINE sso_is_valid = TrueNEWLINE else:NEWLINE requires_sso = TrueNEWLINE try:NEWLINE auth_identity = AuthIdentity.objects.get(NEWLINE auth_provider=auth_provider, user=member.user_idNEWLINE )NEWLINE except AuthIdentity.DoesNotExist:NEWLINE sso_is_valid = FalseNEWLINE # If an owner is trying to gain access,NEWLINE # allow bypassing SSO if there are no otherNEWLINE # owners with SSO enabled.NEWLINE if member.role == roles.get_top_dog().id:NEWLINE requires_sso = AuthIdentity.objects.filter(NEWLINE auth_provider=auth_provider,NEWLINE user__in=OrganizationMember.objects.filter(NEWLINE organization=member.organization_id,NEWLINE role=roles.get_top_dog().id,NEWLINE user__is_active=True,NEWLINE )NEWLINE .exclude(id=member.id)NEWLINE .values_list("user_id"),NEWLINE ).exists()NEWLINE else:NEWLINE sso_is_valid = auth_identity.is_valid(member)NEWLINE return requires_sso, sso_is_validNEWLINENEWLINENEWLINEclass BaseAccess(object):NEWLINE is_active = FalseNEWLINE sso_is_valid = FalseNEWLINE requires_sso = FalseNEWLINE organization_id = NoneNEWLINE # teams with membershipNEWLINE teams = ()NEWLINE # projects with membershipNEWLINE projects = ()NEWLINE # if has_global_access is True, then any projectNEWLINE # matching organization_id is valid. This is used forNEWLINE # both `organization.allow_joinleave` and to indicateNEWLINE # that the role is global / a user is an active superuserNEWLINE has_global_access = FalseNEWLINE scopes = frozenset()NEWLINE permissions = frozenset()NEWLINE role = NoneNEWLINENEWLINE def has_permission(self, permission):NEWLINE """NEWLINE Return bool representing if the user has the given permission.NEWLINENEWLINE >>> access.has_permission('broadcasts.admin')NEWLINE """NEWLINE if not self.is_active:NEWLINE return FalseNEWLINE return permission in self.permissionsNEWLINENEWLINE def has_scope(self, scope):NEWLINE """NEWLINE Return bool representing if the user has the given scope.NEWLINENEWLINE >>> access.has_project('org:read')NEWLINE """NEWLINE if not self.is_active:NEWLINE return FalseNEWLINE return scope in self.scopesNEWLINENEWLINE def has_team(self, team):NEWLINE warnings.warn("has_team() is deprecated in favor of has_team_access", DeprecationWarning)NEWLINE return self.has_team_access(team)NEWLINENEWLINE def has_team_access(self, team):NEWLINE """NEWLINE Return bool representing if a user should have access to information for the given team.NEWLINENEWLINE >>> access.has_team_access(team)NEWLINE """NEWLINE if not self.is_active:NEWLINE return FalseNEWLINE if self.has_global_access and self.organization_id == team.organization_id:NEWLINE return TrueNEWLINE return team in self.teamsNEWLINENEWLINE def has_team_scope(self, team, scope):NEWLINE """NEWLINE Return bool representing if a user should have access with the given scope to informationNEWLINE for the given team.NEWLINENEWLINE >>> access.has_team_scope(team, 'team:read')NEWLINE """NEWLINE return self.has_team_access(team) and self.has_scope(scope)NEWLINENEWLINE def has_project_access(self, project):NEWLINE """NEWLINE Return bool representing if a user should have access to information for the given project.NEWLINENEWLINE >>> access.has_project_access(project)NEWLINE """NEWLINE if not self.is_active:NEWLINE return FalseNEWLINE if self.has_global_access and self.organization_id == project.organization_id:NEWLINE return TrueNEWLINE return project in self.projectsNEWLINENEWLINE def has_projects_access(self, projects):NEWLINE """NEWLINE Returns bool representing if a user should have access to every requested projectNEWLINE """NEWLINE return all([self.has_project_access(project) for project in projects])NEWLINENEWLINE def has_project_membership(self, project):NEWLINE """NEWLINE Return bool representing if a user has explicit membership for the given project.NEWLINENEWLINE >>> access.has_project_membership(project)NEWLINE """NEWLINE if not self.is_active:NEWLINE return FalseNEWLINE return project in self.projectsNEWLINENEWLINE def has_project_scope(self, project, scope):NEWLINE """NEWLINE Return bool representing if a user should have access with the given scope to informationNEWLINE for the given project.NEWLINENEWLINE >>> access.has_project_scope(project, 'project:read')NEWLINE """NEWLINE return self.has_project_access(project) and self.has_scope(scope)NEWLINENEWLINE def to_django_context(self):NEWLINE return {s.replace(":", "_"): self.has_scope(s) for s in settings.SENTRY_SCOPES}NEWLINENEWLINENEWLINEclass Access(BaseAccess):NEWLINE # TODO(dcramer): this is still a little gross, and ideally backend accessNEWLINE # would be based on the same scopes as API access so theres clarity inNEWLINE # what things meanNEWLINE def __init__(NEWLINE self,NEWLINE scopes,NEWLINE is_active,NEWLINE organization_id,NEWLINE teams,NEWLINE projects,NEWLINE has_global_access,NEWLINE sso_is_valid,NEWLINE requires_sso,NEWLINE permissions=None,NEWLINE role=None,NEWLINE ):NEWLINE self.organization_id = organization_idNEWLINE self.teams = teamsNEWLINE self.projects = projectsNEWLINE self.has_global_access = has_global_accessNEWLINE self.scopes = scopesNEWLINE if permissions is not None:NEWLINE self.permissions = permissionsNEWLINE if role is not None:NEWLINE self.role = roleNEWLINENEWLINE self.is_active = is_activeNEWLINE self.sso_is_valid = sso_is_validNEWLINE self.requires_sso = requires_ssoNEWLINENEWLINENEWLINEclass OrganizationGlobalAccess(BaseAccess):NEWLINE requires_sso = FalseNEWLINE sso_is_valid = TrueNEWLINE is_active = TrueNEWLINE has_global_access = TrueNEWLINE teams = ()NEWLINE projects = ()NEWLINE permissions = frozenset()NEWLINENEWLINE def __init__(self, organization, scopes=None):NEWLINE if scopes:NEWLINE self.scopes = scopesNEWLINE self.organization_id = organization.idNEWLINENEWLINE @cached_propertyNEWLINE def scopes(self):NEWLINE return settings.SENTRY_SCOPESNEWLINENEWLINE def has_team_access(self, team):NEWLINE return team.organization_id == self.organization_idNEWLINENEWLINE def has_project_access(self, project):NEWLINE return project.organization_id == self.organization_idNEWLINENEWLINE def has_scope(self, scope):NEWLINE return TrueNEWLINENEWLINENEWLINEclass OrganizationlessAccess(BaseAccess):NEWLINE is_active = TrueNEWLINENEWLINE def __init__(self, permissions=None):NEWLINE if permissions is not None:NEWLINE self.permissions = permissionsNEWLINENEWLINENEWLINEclass SystemAccess(BaseAccess):NEWLINE is_active = TrueNEWLINENEWLINE def has_permission(self, permission):NEWLINE return TrueNEWLINENEWLINE def has_scope(self, scope):NEWLINE return TrueNEWLINENEWLINE def has_team_access(self, team):NEWLINE return TrueNEWLINENEWLINE def has_project_access(self, project):NEWLINE return TrueNEWLINENEWLINE def has_project_membership(self, project):NEWLINE return TrueNEWLINENEWLINENEWLINEclass NoAccess(BaseAccess):NEWLINE requires_sso = FalseNEWLINE sso_is_valid = TrueNEWLINE is_active = FalseNEWLINE organization_id = NoneNEWLINE has_global_access = FalseNEWLINE teams = ()NEWLINE projects = ()NEWLINE memberships = ()NEWLINE scopes = frozenset()NEWLINE permissions = frozenset()NEWLINENEWLINENEWLINEdef from_request(request, organization=None, scopes=None):NEWLINE if not organization:NEWLINE return from_user(request.user, organization=organization, scopes=scopes)NEWLINENEWLINE if getattr(request.user, "is_sentry_app", False):NEWLINE return from_sentry_app(request.user, organization=organization)NEWLINENEWLINE if is_active_superuser(request):NEWLINE role = NoneNEWLINE # we special case superuser so that if they're a member of the orgNEWLINE # they must still follow SSO checks, but they gain global accessNEWLINE try:NEWLINE member = OrganizationMember.objects.get(user=request.user, organization=organization)NEWLINE except OrganizationMember.DoesNotExist:NEWLINE requires_sso, sso_is_valid = False, TrueNEWLINE else:NEWLINE requires_sso, sso_is_valid = _sso_params(member)NEWLINE role = member.roleNEWLINENEWLINE team_list = ()NEWLINENEWLINE project_list = ()NEWLINE return Access(NEWLINE scopes=scopes if scopes is not None else settings.SENTRY_SCOPES,NEWLINE is_active=True,NEWLINE organization_id=organization.id if organization else None,NEWLINE teams=team_list,NEWLINE projects=project_list,NEWLINE sso_is_valid=sso_is_valid,NEWLINE requires_sso=requires_sso,NEWLINE has_global_access=True,NEWLINE permissions=UserPermission.for_user(request.user.id),NEWLINE role=role,NEWLINE )NEWLINENEWLINE if hasattr(request, "auth") and not request.user.is_authenticated():NEWLINE return from_auth(request.auth, scopes=scopes)NEWLINENEWLINE return from_user(request.user, organization, scopes=scopes)NEWLINENEWLINENEWLINEdef from_sentry_app(user, organization=None):NEWLINE if not organization:NEWLINE return NoAccess()NEWLINENEWLINE sentry_app = SentryApp.objects.get(proxy_user=user)NEWLINENEWLINE if not sentry_app.is_installed_on(organization):NEWLINE return NoAccess()NEWLINENEWLINE team_list = list(Team.objects.filter(organization=organization))NEWLINE project_list = list(NEWLINE Project.objects.filter(status=ProjectStatus.VISIBLE, teams__in=team_list).distinct()NEWLINE )NEWLINENEWLINE return Access(NEWLINE scopes=sentry_app.scope_list,NEWLINE is_active=True,NEWLINE organization_id=organization.id,NEWLINE teams=team_list,NEWLINE projects=project_list,NEWLINE permissions=(),NEWLINE has_global_access=False,NEWLINE sso_is_valid=True,NEWLINE requires_sso=False,NEWLINE )NEWLINENEWLINENEWLINEdef from_user(user, organization=None, scopes=None):NEWLINE if not user or user.is_anonymous() or not user.is_active:NEWLINE return DEFAULTNEWLINENEWLINE if not organization:NEWLINE return OrganizationlessAccess(permissions=UserPermission.for_user(user.id))NEWLINENEWLINE try:NEWLINE om = OrganizationMember.objects.get(user=user, organization=organization)NEWLINE except OrganizationMember.DoesNotExist:NEWLINE return OrganizationlessAccess(permissions=UserPermission.for_user(user.id))NEWLINENEWLINE # ensure cached relationNEWLINE om.organization = organizationNEWLINENEWLINE return from_member(om, scopes=scopes)NEWLINENEWLINENEWLINEdef from_member(member, scopes=None):NEWLINE # TODO(dcramer): we want to optimize this access pattern as its severalNEWLINE # network hops and needed in a lot of placesNEWLINE requires_sso, sso_is_valid = _sso_params(member)NEWLINENEWLINE team_list = member.get_teams()NEWLINE project_list = list(NEWLINE Project.objects.filter(status=ProjectStatus.VISIBLE, teams__in=team_list).distinct()NEWLINE )NEWLINENEWLINE if scopes is not None:NEWLINE scopes = set(scopes) & member.get_scopes()NEWLINE else:NEWLINE scopes = member.get_scopes()NEWLINENEWLINE return Access(NEWLINE is_active=True,NEWLINE requires_sso=requires_sso,NEWLINE sso_is_valid=sso_is_valid,NEWLINE scopes=scopes,NEWLINE organization_id=member.organization_id,NEWLINE teams=team_list,NEWLINE projects=project_list,NEWLINE has_global_access=bool(member.organization.flags.allow_joinleave)NEWLINE or roles.get(member.role).is_global,NEWLINE permissions=UserPermission.for_user(member.user_id),NEWLINE role=member.role,NEWLINE )NEWLINENEWLINENEWLINEdef from_auth(auth, organization):NEWLINE if is_system_auth(auth):NEWLINE return SystemAccess()NEWLINE if auth.organization_id == organization.id:NEWLINE return OrganizationGlobalAccess(auth.organization)NEWLINE else:NEWLINE return DEFAULTNEWLINENEWLINENEWLINEDEFAULT = NoAccess()NEWLINE import openxc_threadNEWLINEimport threadingNEWLINEimport bluetoothNEWLINEimport datetimeNEWLINEimport pygameNEWLINEimport timeNEWLINEimport jsonNEWLINEimport osNEWLINENEWLINENEWLINE# SETTING VARIABLESNEWLINE# ColorsNEWLINEBLACK = (0, 0, 0)NEWLINEWHITE = (255, 255, 255)NEWLINEGREEN = (0, 255, 0)NEWLINERED = (255, 0, 0)NEWLINEBLUE = (0, 0, 255)NEWLINEYELLOW = (255, 255, 0)NEWLINENEWLINE# Window SizeNEWLINEWINDOW_WIDTH = 1024NEWLINEWINDOW_HEIGHT = 600NEWLINENEWLINE# Time range of the graphNEWLINETIME_RANGE = 60NEWLINEDATA_CAPTURE_FINISHED = FalseNEWLINENEWLINENEWLINE# THE CLASS THAT HAS THE DATANEWLINEclassdict = {}NEWLINENEWLINEclassdict["accelerator_pedal_position"] = NoneNEWLINEclassdict["steering_wheel_angle"] = NoneNEWLINEclassdict["vehicle_speed"] = NoneNEWLINEclassdict["engine_speed"] = NoneNEWLINEclassdict["brake_pedal_status"] = NoneNEWLINEclassdict["fuel_consumed"] = NoneNEWLINEclassdict["fuel_level"] = NoneNEWLINEclassdict["high_beam_status"] = NoneNEWLINEclassdict["ignition_status"] = NoneNEWLINEclassdict["latitude"] = NoneNEWLINEclassdict["longitude"] = NoneNEWLINEclassdict["odometer"] = NoneNEWLINEclassdict["parking_brake_status"] = NoneNEWLINEclassdict["torque_at_transmission"] = NoneNEWLINENEWLINEoptions = ["accelerator_pedal_position", "steering_wheel_angle", "vehicle_speed",NEWLINE "brake_pedal_status", "fuel_consumed", "fuel_level", "high_beam_status", "ignition_status",NEWLINE "latitude", "longitude", "odometer", "parking_brake_status",NEWLINE "torque_at_transmission", "transmission_gear_position"]NEWLINENEWLINENEWLINEcolumn_title = FalseNEWLINENEWLINE# THE FILE THAT STORES ALL THE DATANEWLINEcsvFile = open('data.csv', 'w')NEWLINENEWLINENEWLINE# MENU FOR THE CONSOLE DATA SELECTIONNEWLINEprint("-------------------------------------------------------------------------------------")NEWLINEprint("Choose the variables you want to measure and write the number, for multiple choices use a comma ','")NEWLINEprint("-------------------------------------------------------------------------------------\n\n")NEWLINENEWLINEfor t in range(len(options)):NEWLINE print("> Do you want to measure "+options[t]+" ? [" + str(t) + "] \n")NEWLINEanswer = input("variables \n")NEWLINENEWLINENEWLINE# WINDOW INITNEWLINE# Center the window on the screenNEWLINEos.environ['SDL_VIDEO_CENTERED'] = '1'NEWLINEpygame.init()NEWLINEWINDOW_SIZE = (WINDOW_WIDTH, WINDOW_HEIGHT)NEWLINEscreen = pygame.display.set_mode(WINDOW_SIZE)NEWLINENEWLINE# Title of the windowNEWLINEpygame.display.set_caption("OpenXC Data Grabber & Monitor")NEWLINENEWLINENEWLINEclock = pygame.time.Clock()NEWLINENEWLINEdata_thread = openxc_thread.OpenXCDataThread()NEWLINEdata_thread.start()NEWLINENEWLINE# Font to use, size, bold, italicsNEWLINEfont = pygame.font.SysFont('Calibri', 27, False, False)NEWLINENEWLINENEWLINE# DATA CAPTURE WHILE-LOOPNEWLINEwhile not DATA_CAPTURE_FINISHED:NEWLINE for event in pygame.event.get():NEWLINE if event.type == pygame.QUIT:NEWLINE DATA_CAPTURE_FINISHED = TrueNEWLINENEWLINE screen.fill(BLACK)NEWLINENEWLINE # RESETS EMPTY LINE VALUENEWLINE emptyLine = TrueNEWLINE line = ""NEWLINENEWLINE if '0' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.accelerator_pedal_position) != 0:NEWLINE line = line + \NEWLINE str(data_thread.accelerator_pedal_position[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("accelerator_pedal_position" + ",")NEWLINENEWLINE if '1' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.steering_wheel_angle) != 0:NEWLINE line = line + \NEWLINE str(data_thread.steering_wheel_angle[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("steering_wheel_angle" + ",")NEWLINENEWLINE if '2' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.vehicle_speed) != 0:NEWLINE line = line + \NEWLINE str(data_thread.vehicle_speed[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("vehicle_speed" + ",")NEWLINENEWLINE if '3' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.engine_speed) != 0:NEWLINE line = line + \NEWLINE str(data_thread.engine_speed[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("engine_speed" + ",")NEWLINENEWLINE if '4' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.brake_pedal_status) != 0:NEWLINE line = line + \NEWLINE str(data_thread.brake_pedal_status[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("brake_pedal_status" + ",")NEWLINENEWLINE if '5' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.fuel_consumed) != 0:NEWLINE line = line + \NEWLINE str(data_thread.fuel_consumed[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("fuel_consumed" + ",")NEWLINENEWLINE if '6' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.fuel_level) != 0:NEWLINE line = line + \NEWLINE str(data_thread.fuel_level[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("fuel_level" + ",")NEWLINENEWLINE if '7' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.high_beam_status) != 0:NEWLINE line = line + \NEWLINE str(data_thread.high_beam_status[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("high_beam_status" + ",")NEWLINENEWLINE if '8' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.ignition_status) != 0:NEWLINE line = line + \NEWLINE str(data_thread.ignition_status[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("ignition_status" + ",")NEWLINENEWLINE if '9' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.latitude) != 0:NEWLINE line = line + \NEWLINE str(data_thread.latitude[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("latitude" + ",")NEWLINENEWLINE if '10' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.longitude) != 0:NEWLINE line = line + \NEWLINE str(data_thread.longitude[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("longitude" + ",")NEWLINENEWLINE if '11' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.odometer) != 0:NEWLINE line = line + \NEWLINE str(data_thread.odometer[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("odometer" + ",")NEWLINENEWLINE if '12' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.parking_brake_status) != 0:NEWLINE line = line + \NEWLINE str(data_thread.parking_brake_status[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("parking_brake_status" + ",")NEWLINENEWLINE if '13' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.torque_at_transmission) != 0:NEWLINE line = line + \NEWLINE str(data_thread.torque_at_transmission[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("torque_at_transmission" + ",")NEWLINENEWLINE if '14' in answer:NEWLINE if column_title:NEWLINE if len(data_thread.transmission_gear_position) != 0:NEWLINE line = line + \NEWLINE str(data_thread.transmission_gear_position[-1][1]) + ","NEWLINE emptyLine = FalseNEWLINE else:NEWLINE csvFile.write("transmission_gear_position" + ",")NEWLINENEWLINE # ENGINE SPEEDNEWLINE if len(data_thread.engine_speed) == 0:NEWLINE text = font.render(data_thread.message, True, WHITE)NEWLINE else:NEWLINE text = font.render(NEWLINE "RPM (Revolutions Per Minute): "+str(data_thread.engine_speed[-1][1]), True, WHITE)NEWLINENEWLINE screen.blit(text, [10, 10])NEWLINENEWLINE # VEHICULE SPEEDNEWLINE if len(data_thread.vehicle_speed) == 0:NEWLINE text = font.render("", True, RED)NEWLINE else:NEWLINE text = font.render("Vehicle Speed: {:.1f} kph".format(NEWLINE data_thread.vehicle_speed[-1][1]), True, GREEN)NEWLINENEWLINE screen.blit(text, [10, 40])NEWLINENEWLINE # GEAR POSITIONNEWLINE if len(data_thread.transmission_gear_position) == 0:NEWLINE text = font.render("", True, RED)NEWLINE else:NEWLINE text = font.render(NEWLINE "Gear: "+str(data_thread.transmission_gear_position[-1][1]), True, YELLOW)NEWLINENEWLINE screen.blit(text, [10, 70])NEWLINENEWLINE # MAKE THE COLUMN NAMESNEWLINE if column_title:NEWLINE if not emptyLine:NEWLINE csvFile.write(line + "\n")NEWLINE else:NEWLINE csvFile.write("photo_name, \n")NEWLINE column_title = TrueNEWLINENEWLINE for i in range(0, len(data_thread.engine_speed)):NEWLINE if i > 0:NEWLINE speed_data_1 = data_thread.engine_speed[i-1][1]NEWLINE speed_data_2 = data_thread.engine_speed[i][1]NEWLINE time_data_1 = data_thread.engine_speed[i-1][0]NEWLINE time_data_2 = data_thread.engine_speed[i][0]NEWLINENEWLINE y1 = WINDOW_HEIGHT - (speed_data_1 / 15)NEWLINE y2 = WINDOW_HEIGHT - (speed_data_2 / 15)NEWLINENEWLINE current_time = time.time() * 1000NEWLINE x1 = WINDOW_WIDTH - ((current_time - time_data_1) /NEWLINE (TIME_RANGE * 1000.) * WINDOW_WIDTH)NEWLINE x2 = WINDOW_WIDTH - ((current_time - time_data_2) /NEWLINE (TIME_RANGE * 1000.) * WINDOW_WIDTH)NEWLINENEWLINE if x2 > 0:NEWLINE pygame.draw.line(screen, BLUE,NEWLINE [x1, y1],NEWLINE [x2, y2], 2)NEWLINENEWLINE pygame.display.flip()NEWLINE clock.tick(60)NEWLINENEWLINEpygame.quit()NEWLINE # *************************NEWLINE# |docname| - Runestone APINEWLINE# *************************NEWLINE# This module implements the API that the Runestone Components use to communicate with a Runestone Server.NEWLINE#NEWLINE# ImportsNEWLINE# =======NEWLINE# These are listed in the order prescribed by `PEP 8NEWLINE# `_.NEWLINEfrom collections import CounterNEWLINEimport datetimeNEWLINEfrom io import openNEWLINEimport jsonNEWLINEimport loggingNEWLINEfrom lxml import htmlNEWLINEimport mathNEWLINEimport osNEWLINEimport reNEWLINEimport subprocessNEWLINEfrom textwrap import dedentNEWLINEimport uuidNEWLINENEWLINE# Third-party importsNEWLINE# -------------------NEWLINEfrom bleach import cleanNEWLINEfrom dateutil.parser import parseNEWLINENEWLINE# Local application importsNEWLINE# -------------------------NEWLINEfrom feedback import is_server_feedback, fitb_feedback, lp_feedbackNEWLINEfrom rs_practice import _get_qualified_questionsNEWLINENEWLINElogger = logging.getLogger(settings.logger)NEWLINElogger.setLevel(settings.log_level)NEWLINENEWLINENEWLINEEVENT_TABLE = {NEWLINE "mChoice": "mchoice_answers",NEWLINE "fillb": "fitb_answers",NEWLINE "dragNdrop": "dragndrop_answers",NEWLINE "clickableArea": "clickablearea_answers",NEWLINE "parsons": "parsons_answers",NEWLINE "codelensq": "codelens_answers",NEWLINE "shortanswer": "shortanswer_answers",NEWLINE "fillintheblank": "fitb_answers",NEWLINE "mchoice": "mchoice_answers",NEWLINE "dragndrop": "dragndrop_answers",NEWLINE "clickablearea": "clickablearea_answers",NEWLINE "parsonsprob": "parsons_answers",NEWLINE}NEWLINENEWLINECOMMENT_MAP = {NEWLINE "sql": "--",NEWLINE "python": "#",NEWLINE "java": "//",NEWLINE "javascript": "//",NEWLINE "c": "//",NEWLINE "cpp": "//",NEWLINE}NEWLINENEWLINENEWLINEdef compareAndUpdateCookieData(sid: str):NEWLINE if (NEWLINE "ipuser" in request.cookiesNEWLINE and request.cookies["ipuser"].value != sidNEWLINE and request.cookies["ipuser"].value.endswith("@" + request.client)NEWLINE ):NEWLINE db.useinfo.update_or_insert(NEWLINE db.useinfo.sid == request.cookies["ipuser"].value, sid=sidNEWLINE )NEWLINENEWLINENEWLINE# EndpointsNEWLINE# =========NEWLINE#NEWLINE# .. _hsblog endpoint:NEWLINE#NEWLINE# hsblog endpointNEWLINE# ---------------NEWLINE# Given a JSON record of a clickstream event record the event in the ``useinfo`` table.NEWLINE# If the event is an answer to a runestone question record that answer in the database inNEWLINE# one of the xxx_answers tables.NEWLINE#NEWLINEdef hsblog():NEWLINE setCookie = FalseNEWLINE if auth.user:NEWLINE if request.vars.course != auth.user.course_name:NEWLINE return json.dumps(NEWLINE dict(NEWLINE log=False,NEWLINE message="You appear to have changed courses in another tab. Please switch to this course",NEWLINE )NEWLINE )NEWLINE sid = auth.user.usernameNEWLINE compareAndUpdateCookieData(sid)NEWLINE setCookie = True # we set our own cookie anyway to eliminate many of the extraneous anonymousNEWLINE # log entries that come from auth timing out even but the user hasn't reloadedNEWLINE # the page.NEWLINE else:NEWLINE if request.vars.clientLoginStatus == "true":NEWLINE logger.error("Session Expired")NEWLINE return json.dumps(dict(log=False, message="Session Expired"))NEWLINENEWLINE if "ipuser" in request.cookies:NEWLINE sid = request.cookies["ipuser"].valueNEWLINE setCookie = TrueNEWLINE else:NEWLINE sid = str(uuid.uuid1().int) + "@" + request.clientNEWLINE setCookie = TrueNEWLINE act = request.vars.get("act", "")NEWLINE div_id = request.vars.div_idNEWLINE event = request.vars.eventNEWLINE course = request.vars.courseNEWLINE # Get the current time, rounded to the nearest second -- this is how time time will be stored in the database.NEWLINE ts = datetime.datetime.utcnow()NEWLINE ts -= datetime.timedelta(microseconds=ts.microsecond)NEWLINE tt = request.vars.timeNEWLINE if not tt:NEWLINE tt = 0NEWLINENEWLINE try:NEWLINE db.useinfo.insert(NEWLINE sid=sid,NEWLINE act=act[0:512],NEWLINE div_id=div_id,NEWLINE event=event,NEWLINE timestamp=ts,NEWLINE course_id=course,NEWLINE )NEWLINE except Exception as e:NEWLINE logger.error(NEWLINE "failed to insert log record for {} in {} : {} {} {}".format(NEWLINE sid, course, div_id, event, actNEWLINE )NEWLINE )NEWLINE logger.error("Details: {}".format(e))NEWLINENEWLINE if event == "timedExam" and (act == "finish" or act == "reset" or act == "start"):NEWLINE logger.debug(act)NEWLINE if act == "reset":NEWLINE r = "T"NEWLINE else:NEWLINE r = NoneNEWLINENEWLINE try:NEWLINE db.timed_exam.insert(NEWLINE sid=sid,NEWLINE course_name=course,NEWLINE correct=int(request.vars.correct or 0),NEWLINE incorrect=int(request.vars.incorrect or 0),NEWLINE skipped=int(request.vars.skipped or 0),NEWLINE time_taken=int(tt),NEWLINE timestamp=ts,NEWLINE div_id=div_id,NEWLINE reset=r,NEWLINE )NEWLINE except Exception as e:NEWLINE logger.debug(NEWLINE "failed to insert a timed exam record for {} in {} : {}".format(NEWLINE sid, course, div_idNEWLINE )NEWLINE )NEWLINE logger.debug(NEWLINE "correct {} incorrect {} skipped {} time {}".format(NEWLINE request.vars.correct,NEWLINE request.vars.incorrect,NEWLINE request.vars.skipped,NEWLINE request.vars.time,NEWLINE )NEWLINE )NEWLINE logger.debug("Error: {}".format(e.message))NEWLINENEWLINE # Produce a default result.NEWLINE res = dict(log=True, timestamp=str(ts))NEWLINE try:NEWLINE pct = float(request.vars.percent)NEWLINE except ValueError:NEWLINE pct = NoneNEWLINE except TypeError:NEWLINE pct = NoneNEWLINENEWLINE # Process this event.NEWLINE if event == "mChoice" and auth.user:NEWLINE answer = request.vars.answerNEWLINE correct = request.vars.correctNEWLINE db.mchoice_answers.insert(NEWLINE sid=sid,NEWLINE timestamp=ts,NEWLINE div_id=div_id,NEWLINE answer=answer,NEWLINE correct=correct,NEWLINE course_name=course,NEWLINE percent=pct,NEWLINE )NEWLINE elif event == "fillb" and auth.user:NEWLINE answer_json = request.vars.answerNEWLINE correct = request.vars.correctNEWLINE # Grade on the server if needed.NEWLINE do_server_feedback, feedback = is_server_feedback(div_id, course)NEWLINE if do_server_feedback:NEWLINE correct, res_update = fitb_feedback(answer_json, feedback)NEWLINE res.update(res_update)NEWLINE pct = res["percent"]NEWLINENEWLINE # Save this data.NEWLINE db.fitb_answers.insert(NEWLINE sid=sid,NEWLINE timestamp=ts,NEWLINE div_id=div_id,NEWLINE answer=answer_json,NEWLINE correct=correct,NEWLINE course_name=course,NEWLINE percent=pct,NEWLINE )NEWLINENEWLINE elif event == "dragNdrop" and auth.user:NEWLINE answers = request.vars.answerNEWLINE minHeight = request.vars.minHeightNEWLINE correct = request.vars.correctNEWLINENEWLINE db.dragndrop_answers.insert(NEWLINE sid=sid,NEWLINE timestamp=ts,NEWLINE div_id=div_id,NEWLINE answer=answers,NEWLINE correct=correct,NEWLINE course_name=course,NEWLINE min_height=minHeight,NEWLINE percent=pct,NEWLINE )NEWLINE elif event == "clickableArea" and auth.user:NEWLINE correct = request.vars.correctNEWLINE db.clickablearea_answers.insert(NEWLINE sid=sid,NEWLINE timestamp=ts,NEWLINE div_id=div_id,NEWLINE answer=act,NEWLINE correct=correct,NEWLINE course_name=course,NEWLINE percent=pct,NEWLINE )NEWLINENEWLINE elif event == "parsons" and auth.user:NEWLINE correct = request.vars.correctNEWLINE answer = request.vars.answerNEWLINE source = request.vars.sourceNEWLINE db.parsons_answers.insert(NEWLINE sid=sid,NEWLINE timestamp=ts,NEWLINE div_id=div_id,NEWLINE answer=answer,NEWLINE source=source,NEWLINE correct=correct,NEWLINE course_name=course,NEWLINE percent=pct,NEWLINE )NEWLINENEWLINE elif event == "codelensq" and auth.user:NEWLINE correct = request.vars.correctNEWLINE answer = request.vars.answerNEWLINE source = request.vars.sourceNEWLINE db.codelens_answers.insert(NEWLINE sid=sid,NEWLINE timestamp=ts,NEWLINE div_id=div_id,NEWLINE answer=answer,NEWLINE source=source,NEWLINE correct=correct,NEWLINE course_name=course,NEWLINE percent=pct,NEWLINE )NEWLINENEWLINE elif event == "shortanswer" and auth.user:NEWLINE db.shortanswer_answers.insert(NEWLINE sid=sid,NEWLINE answer=act,NEWLINE div_id=div_id,NEWLINE timestamp=ts,NEWLINE course_name=course,NEWLINE )NEWLINENEWLINE elif event == "unittest" and auth.user:NEWLINE statslist = act.split(":")NEWLINE if "undefined" not in act:NEWLINE pct = float(statslist[1])NEWLINE passed = int(statslist[3])NEWLINE failed = int(statslist[5])NEWLINE if math.isnan(pct):NEWLINE pct = 0NEWLINE else:NEWLINE pct = passed = failed = 0NEWLINE logger.error(f"Got undefined unittest results for {div_id} {sid}")NEWLINE if pct >= 99.99999:NEWLINE correct = "T"NEWLINE else:NEWLINE correct = "F"NEWLINE db.unittest_answers.insert(NEWLINE sid=sid,NEWLINE timestamp=ts,NEWLINE div_id=div_id,NEWLINE correct=correct,NEWLINE passed=passed,NEWLINE failed=failed,NEWLINE course_name=course,NEWLINE percent=pct,NEWLINE )NEWLINENEWLINE elif event == "lp_build" and auth.user:NEWLINE ret, new_fields = db.lp_answers._validate_fields(NEWLINE dict(sid=sid, timestamp=ts, div_id=div_id, course_name=course)NEWLINE )NEWLINE if not ret.errors:NEWLINE do_server_feedback, feedback = is_server_feedback(div_id, course)NEWLINE if do_server_feedback:NEWLINE try:NEWLINE code_snippets = json.loads(request.vars.answer)["code_snippets"]NEWLINE except Exception:NEWLINE code_snippets = []NEWLINE result = lp_feedback(code_snippets, feedback)NEWLINE # If an error occurred or we're not testing, pass the answer through.NEWLINE res.update(result)NEWLINENEWLINE # Record the results in the database.NEWLINE correct = result.get("correct")NEWLINE answer = result.get("answer", {})NEWLINE answer["code_snippets"] = code_snippetsNEWLINE ret = db.lp_answers.validate_and_insert(NEWLINE sid=sid,NEWLINE timestamp=ts,NEWLINE div_id=div_id,NEWLINE answer=json.dumps(answer),NEWLINE correct=correct,NEWLINE course_name=course,NEWLINE )NEWLINE if ret.errors:NEWLINE res.setdefault("errors", []).append(ret.errors.as_dict())NEWLINE else:NEWLINE res["errors"] = ["No feedback provided."]NEWLINE else:NEWLINE res.setdefault("errors", []).append(ret.errors.as_dict())NEWLINENEWLINE response.headers["content-type"] = "application/json"NEWLINE if setCookie:NEWLINE response.cookies["ipuser"] = sidNEWLINE response.cookies["ipuser"]["expires"] = 24 * 3600 * 90NEWLINE response.cookies["ipuser"]["path"] = "/"NEWLINE if auth.user:NEWLINE response.cookies["last_course"] = auth.user.course_nameNEWLINE response.cookies["last_course"]["expires"] = 24 * 3600 * 90NEWLINE response.cookies["last_course"]["path"] = "/"NEWLINENEWLINE return json.dumps(res)NEWLINENEWLINENEWLINE# .. _runlog endpoint:NEWLINE#NEWLINE# runlog endpointNEWLINE# ---------------NEWLINE# The `logRunEvent` client-side function calls this endpoint to record TODO...NEWLINEdef runlog(): # Log errors and runs with codeNEWLINE # response.headers['content-type'] = 'application/json'NEWLINE setCookie = FalseNEWLINE if auth.user:NEWLINE if request.vars.course != auth.user.course_name:NEWLINE return json.dumps(NEWLINE dict(NEWLINE log=False,NEWLINE message="You appear to have changed courses in another tab. Please switch to this course",NEWLINE )NEWLINE )NEWLINE sid = auth.user.usernameNEWLINE setCookie = TrueNEWLINE else:NEWLINE if request.vars.clientLoginStatus == "true":NEWLINE logger.error("Session Expired")NEWLINE return json.dumps(dict(log=False, message="Session Expired"))NEWLINE if "ipuser" in request.cookies:NEWLINE sid = request.cookies["ipuser"].valueNEWLINE setCookie = TrueNEWLINE else:NEWLINE sid = str(uuid.uuid1().int) + "@" + request.clientNEWLINE setCookie = TrueNEWLINE div_id = request.vars.div_idNEWLINE course = request.vars.courseNEWLINE code = request.vars.code if request.vars.code else ""NEWLINE ts = datetime.datetime.utcnow()NEWLINE error_info = request.vars.errinfoNEWLINE pre = request.vars.prefix if request.vars.prefix else ""NEWLINE post = request.vars.suffix if request.vars.suffix else ""NEWLINE if error_info != "success":NEWLINE event = "ac_error"NEWLINE act = str(error_info)[:512]NEWLINE else:NEWLINE act = "run"NEWLINE if request.vars.event:NEWLINE event = request.vars.eventNEWLINE else:NEWLINE event = "activecode"NEWLINE num_tries = 3NEWLINE done = FalseNEWLINE while num_tries > 0 and not done:NEWLINE try:NEWLINE db.useinfo.insert(NEWLINE sid=sid,NEWLINE act=act,NEWLINE div_id=div_id,NEWLINE event=event,NEWLINE timestamp=ts,NEWLINE course_id=course,NEWLINE )NEWLINE done = TrueNEWLINE except Exception as e:NEWLINE logger.error(NEWLINE "probable Too Long problem trying to insert sid={} act={} div_id={} event={} timestamp={} course_id={} exception={}".format(NEWLINE sid, act, div_id, event, ts, course, eNEWLINE )NEWLINE )NEWLINE num_tries -= 1NEWLINE if num_tries == 0:NEWLINE raise Exception("Runlog Failed to insert into useinfo")NEWLINENEWLINE if auth.user:NEWLINE if "to_save" in request.vars and (NEWLINE request.vars.to_save == "True" or request.vars.to_save == "true"NEWLINE ):NEWLINE num_tries = 3NEWLINE done = FalseNEWLINE dbcourse = (NEWLINE db(db.courses.course_name == course).select(**SELECT_CACHE).first()NEWLINE )NEWLINE while num_tries > 0 and not done:NEWLINE try:NEWLINE db.code.insert(NEWLINE sid=sid,NEWLINE acid=div_id,NEWLINE code=code,NEWLINE emessage=error_info,NEWLINE timestamp=ts,NEWLINE course_id=dbcourse,NEWLINE language=request.vars.lang,NEWLINE )NEWLINE if request.vars.partner:NEWLINE if _same_class(sid, request.vars.partner):NEWLINE comchar = COMMENT_MAP.get(request.vars.lang, "#")NEWLINE newcode = (NEWLINE "{} This code was shared by {}\n\n".format(comchar, sid)NEWLINE + codeNEWLINE )NEWLINE db.code.insert(NEWLINE sid=request.vars.partner,NEWLINE acid=div_id,NEWLINE code=newcode,NEWLINE emessage=error_info,NEWLINE timestamp=ts,NEWLINE course_id=dbcourse,NEWLINE language=request.vars.lang,NEWLINE )NEWLINE else:NEWLINE res = {NEWLINE "message": "You must be enrolled in the same class as your partner"NEWLINE }NEWLINE return json.dumps(res)NEWLINE done = TrueNEWLINE except Exception as e:NEWLINE num_tries -= 1NEWLINE logger.error("INSERT into code FAILED retrying -- {}".format(e))NEWLINE if num_tries == 0:NEWLINE raise Exception("Runlog Failed to insert into code")NEWLINENEWLINE res = {"log": True}NEWLINE if setCookie:NEWLINE response.cookies["ipuser"] = sidNEWLINE response.cookies["ipuser"]["expires"] = 24 * 3600 * 90NEWLINE response.cookies["ipuser"]["path"] = "/"NEWLINE return json.dumps(res)NEWLINENEWLINENEWLINE# Ajax Handlers for saving and restoring active code blocksNEWLINENEWLINENEWLINEdef gethist():NEWLINENEWLINE """NEWLINE return the history of saved code by this user for a particular acidNEWLINE :Parameters:NEWLINE - `acid`: id of the active code blockNEWLINE - `user`: optional identifier for the owner of the codeNEWLINE :Return:NEWLINE - json object containing a list/array of source textsNEWLINE """NEWLINE codetbl = db.codeNEWLINE acid = request.vars.acidNEWLINENEWLINE # if vars.sid then we know this is being called from the grading interfaceNEWLINE if request.vars.sid:NEWLINE sid = request.vars.sidNEWLINE if auth.user and verifyInstructorStatus(NEWLINE auth.user.course_name, auth.user.idNEWLINE ): # noqa: F405NEWLINE course_id = auth.user.course_idNEWLINE else:NEWLINE course_id = NoneNEWLINE elif auth.user:NEWLINE sid = auth.user.usernameNEWLINE course_id = auth.user.course_idNEWLINE else:NEWLINE sid = NoneNEWLINE course_id = NoneNEWLINENEWLINE res = {}NEWLINE if sid:NEWLINE query = (NEWLINE (codetbl.sid == sid)NEWLINE & (codetbl.acid == acid)NEWLINE & (codetbl.course_id == course_id)NEWLINE & (codetbl.timestamp != None) # noqa: E711NEWLINE )NEWLINE res["acid"] = acidNEWLINE res["sid"] = sidNEWLINE # get the code they saved in chronological order; id order gets that for usNEWLINE r = db(query).select(orderby=codetbl.id)NEWLINE res["history"] = [row.code for row in r]NEWLINE res["timestamps"] = [NEWLINE row.timestamp.replace(tzinfo=datetime.timezone.utc).isoformat() for row in rNEWLINE ]NEWLINENEWLINE response.headers["content-type"] = "application/json"NEWLINE return json.dumps(res)NEWLINENEWLINENEWLINE# @auth.requires_login()NEWLINE# This function is deprecated as of June 2019NEWLINE# We need to keep it in place as long as we continue to serve booksNEWLINE# from runestone/static/ When that period is over we can eliminateNEWLINEdef getuser():NEWLINE response.headers["content-type"] = "application/json"NEWLINENEWLINE if auth.user:NEWLINE try:NEWLINE # return the list of courses that auth.user is registered for to keep them fromNEWLINE # accidentally wandering into courses they are not registered for.NEWLINE cres = db(NEWLINE (db.user_courses.user_id == auth.user.id)NEWLINE & (db.user_courses.course_id == db.courses.id)NEWLINE ).select(db.courses.course_name)NEWLINE clist = []NEWLINE for row in cres:NEWLINE clist.append(row.course_name)NEWLINE res = {NEWLINE "email": auth.user.email,NEWLINE "nick": auth.user.username,NEWLINE "donated": auth.user.donated,NEWLINE "isInstructor": verifyInstructorStatus( # noqa: F405NEWLINE auth.user.course_name, auth.user.idNEWLINE ),NEWLINE "course_list": clist,NEWLINE }NEWLINE session.timezoneoffset = request.vars.timezoneoffsetNEWLINE logger.debug(NEWLINE "setting timezone offset in session %s hours" % session.timezoneoffsetNEWLINE )NEWLINE except Exception:NEWLINE res = dict(redirect=auth.settings.login_url) # ?_next=....NEWLINE else:NEWLINE res = dict(redirect=auth.settings.login_url) # ?_next=....NEWLINE if session.readings:NEWLINE res["readings"] = session.readingsNEWLINE logger.debug("returning login info: %s" % res)NEWLINE return json.dumps([res])NEWLINENEWLINENEWLINEdef set_tz_offset():NEWLINE session.timezoneoffset = request.vars.timezoneoffsetNEWLINE logger.debug("setting timezone offset in session %s hours" % session.timezoneoffset)NEWLINE return "done"NEWLINENEWLINENEWLINE#NEWLINE# Ajax Handlers to update and retrieve the last position of the user in the courseNEWLINE#NEWLINEdef updatelastpage():NEWLINE lastPageUrl = request.vars.lastPageUrlNEWLINE lastPageScrollLocation = request.vars.lastPageScrollLocationNEWLINE if lastPageUrl is None:NEWLINE return # todo: log request.vars, request.args and request.env.path_infoNEWLINE course = request.vars.courseNEWLINE completionFlag = request.vars.completionFlagNEWLINE lastPageChapter = lastPageUrl.split("/")[-2]NEWLINE lastPageSubchapter = ".".join(lastPageUrl.split("/")[-1].split(".")[:-1])NEWLINE if auth.user:NEWLINE done = FalseNEWLINE num_tries = 3NEWLINE while not done and num_tries > 0:NEWLINE try:NEWLINE db(NEWLINE (db.user_state.user_id == auth.user.id)NEWLINE & (db.user_state.course_id == course)NEWLINE ).update(NEWLINE last_page_url=lastPageUrl,NEWLINE last_page_chapter=lastPageChapter,NEWLINE last_page_subchapter=lastPageSubchapter,NEWLINE last_page_scroll_location=lastPageScrollLocation,NEWLINE last_page_accessed_on=datetime.datetime.utcnow(),NEWLINE )NEWLINE done = TrueNEWLINE except Exception:NEWLINE num_tries -= 1NEWLINE if num_tries == 0:NEWLINE raise Exception("Failed to save the user state in update_last_page")NEWLINENEWLINE done = FalseNEWLINE num_tries = 3NEWLINE while not done and num_tries > 0:NEWLINE try:NEWLINE db(NEWLINE (db.user_sub_chapter_progress.user_id == auth.user.id)NEWLINE & (db.user_sub_chapter_progress.chapter_id == lastPageChapter)NEWLINE & (NEWLINE db.user_sub_chapter_progress.sub_chapter_idNEWLINE == lastPageSubchapterNEWLINE )NEWLINE & (NEWLINE (db.user_sub_chapter_progress.course_name == course)NEWLINE | (NEWLINE db.user_sub_chapter_progress.course_name == NoneNEWLINE ) # Back fill for old entries without courseNEWLINE )NEWLINE ).update(NEWLINE status=completionFlag,NEWLINE end_date=datetime.datetime.utcnow(),NEWLINE course_name=course,NEWLINE )NEWLINE done = TrueNEWLINE except Exception:NEWLINE num_tries -= 1NEWLINE if num_tries == 0:NEWLINE raise Exception("Failed to save sub chapter progress in update_last_page")NEWLINENEWLINE practice_settings = db(db.course_practice.course_name == auth.user.course_name)NEWLINE if (NEWLINE practice_settings.count() != 0NEWLINE and practice_settings.select().first().flashcard_creation_method == 0NEWLINE ):NEWLINE # Since each authenticated user has only one active course, we retrieve the course this way.NEWLINE course = (NEWLINE db(db.courses.id == auth.user.course_id).select(**SELECT_CACHE).first()NEWLINE )NEWLINENEWLINE # We only retrieve questions to be used in flashcards if they are marked for practice purpose.NEWLINE questions = _get_qualified_questions(NEWLINE course.base_course, lastPageChapter, lastPageSubchapter, dbNEWLINE )NEWLINE if len(questions) > 0:NEWLINE now = datetime.datetime.utcnow()NEWLINE now_local = now - datetime.timedelta(NEWLINE hours=float(session.timezoneoffset)NEWLINE if "timezoneoffset" in sessionNEWLINE else 0NEWLINE )NEWLINE existing_flashcards = db(NEWLINE (db.user_topic_practice.user_id == auth.user.id)NEWLINE & (db.user_topic_practice.course_name == auth.user.course_name)NEWLINE & (db.user_topic_practice.chapter_label == lastPageChapter)NEWLINE & (db.user_topic_practice.sub_chapter_label == lastPageSubchapter)NEWLINE & (db.user_topic_practice.question_name == questions[0].name)NEWLINE )NEWLINE # There is at least one qualified question in this subchapter, so insert a flashcard for the subchapter.NEWLINE if completionFlag == "1" and existing_flashcards.isempty():NEWLINE db.user_topic_practice.insert(NEWLINE user_id=auth.user.id,NEWLINE course_name=auth.user.course_name,NEWLINE chapter_label=lastPageChapter,NEWLINE sub_chapter_label=lastPageSubchapter,NEWLINE question_name=questions[0].name,NEWLINE # Treat it as if the first eligible question is the last one asked.NEWLINE i_interval=0,NEWLINE e_factor=2.5,NEWLINE next_eligible_date=now_local.date(),NEWLINE # add as if yesterday, so can practice right awayNEWLINE last_presented=now - datetime.timedelta(1),NEWLINE last_completed=now - datetime.timedelta(1),NEWLINE creation_time=now,NEWLINE timezoneoffset=float(session.timezoneoffset)NEWLINE if "timezoneoffset" in sessionNEWLINE else 0,NEWLINE )NEWLINE if completionFlag == "0" and not existing_flashcards.isempty():NEWLINE existing_flashcards.delete()NEWLINENEWLINENEWLINEdef getCompletionStatus():NEWLINE if auth.user:NEWLINE lastPageUrl = request.vars.lastPageUrlNEWLINE lastPageChapter = lastPageUrl.split("/")[-2]NEWLINE lastPageSubchapter = ".".join(lastPageUrl.split("/")[-1].split(".")[:-1])NEWLINE result = db(NEWLINE (db.user_sub_chapter_progress.user_id == auth.user.id)NEWLINE & (db.user_sub_chapter_progress.chapter_id == lastPageChapter)NEWLINE & (db.user_sub_chapter_progress.sub_chapter_id == lastPageSubchapter)NEWLINE & (NEWLINE (db.user_sub_chapter_progress.course_name == auth.user.course_name)NEWLINE | (NEWLINE db.user_sub_chapter_progress.course_name == NoneNEWLINE ) # for backward compatibilityNEWLINE )NEWLINE ).select(db.user_sub_chapter_progress.status)NEWLINE rowarray_list = []NEWLINE if result:NEWLINE for row in result:NEWLINE res = {"completionStatus": row.status}NEWLINE rowarray_list.append(res)NEWLINE # question: since the javascript in user-highlights.js is going to look only at the first row, shouldn'tNEWLINE # we be returning just the *last* status? Or is there no history of status kept anyway?NEWLINE return json.dumps(rowarray_list)NEWLINE else:NEWLINE # haven't seen this Chapter/Subchapter beforeNEWLINE # make the insertions into the DB as necessaryNEWLINENEWLINE # we know the subchapter doesn't existNEWLINE db.user_sub_chapter_progress.insert(NEWLINE user_id=auth.user.id,NEWLINE chapter_id=lastPageChapter,NEWLINE sub_chapter_id=lastPageSubchapter,NEWLINE status=-1,NEWLINE start_date=datetime.datetime.utcnow(),NEWLINE course_name=auth.user.course_name,NEWLINE )NEWLINE # the chapter might exist without the subchapterNEWLINE result = db(NEWLINE (db.user_chapter_progress.user_id == auth.user.id)NEWLINE & (db.user_chapter_progress.chapter_id == lastPageChapter)NEWLINE ).select()NEWLINE if not result:NEWLINE db.user_chapter_progress.insert(NEWLINE user_id=auth.user.id, chapter_id=lastPageChapter, status=-1NEWLINE )NEWLINE return json.dumps([{"completionStatus": -1}])NEWLINENEWLINENEWLINEdef getAllCompletionStatus():NEWLINE if auth.user:NEWLINE result = db(NEWLINE (db.user_sub_chapter_progress.user_id == auth.user.id)NEWLINE & (db.user_sub_chapter_progress.course_name == auth.user.course_name)NEWLINE ).select(NEWLINE db.user_sub_chapter_progress.chapter_id,NEWLINE db.user_sub_chapter_progress.sub_chapter_id,NEWLINE db.user_sub_chapter_progress.status,NEWLINE db.user_sub_chapter_progress.status,NEWLINE db.user_sub_chapter_progress.end_date,NEWLINE )NEWLINE rowarray_list = []NEWLINE if result:NEWLINE for row in result:NEWLINE if row.end_date is None:NEWLINE endDate = 0NEWLINE else:NEWLINE endDate = row.end_date.strftime("%d %b, %Y")NEWLINE res = {NEWLINE "chapterName": row.chapter_id,NEWLINE "subChapterName": row.sub_chapter_id,NEWLINE "completionStatus": row.status,NEWLINE "endDate": endDate,NEWLINE }NEWLINE rowarray_list.append(res)NEWLINE return json.dumps(rowarray_list)NEWLINENEWLINENEWLINE@auth.requires_login()NEWLINEdef getlastpage():NEWLINE course = request.vars.courseNEWLINE course = db(db.courses.course_name == course).select(**SELECT_CACHE).first()NEWLINENEWLINE result = db(NEWLINE (db.user_state.user_id == auth.user.id)NEWLINE & (db.user_state.course_id == course.course_name)NEWLINE & (db.chapters.course_id == course.base_course)NEWLINE & (db.user_state.last_page_chapter == db.chapters.chapter_label)NEWLINE & (db.sub_chapters.chapter_id == db.chapters.id)NEWLINE & (db.user_state.last_page_subchapter == db.sub_chapters.sub_chapter_label)NEWLINE ).select(NEWLINE db.user_state.last_page_url,NEWLINE db.user_state.last_page_hash,NEWLINE db.chapters.chapter_name,NEWLINE db.user_state.last_page_scroll_location,NEWLINE db.sub_chapters.sub_chapter_name,NEWLINE )NEWLINE rowarray_list = []NEWLINE if result:NEWLINE for row in result:NEWLINE res = {NEWLINE "lastPageUrl": row.user_state.last_page_url,NEWLINE "lastPageHash": row.user_state.last_page_hash,NEWLINE "lastPageChapter": row.chapters.chapter_name,NEWLINE "lastPageSubchapter": row.sub_chapters.sub_chapter_name,NEWLINE "lastPageScrollLocation": row.user_state.last_page_scroll_location,NEWLINE }NEWLINE rowarray_list.append(res)NEWLINE return json.dumps(rowarray_list)NEWLINE else:NEWLINE db.user_state.insert(user_id=auth.user.id, course_id=course.course_name)NEWLINENEWLINENEWLINEdef _getCorrectStats(miscdata, event):NEWLINE # TODO: update this to use the xxx_answer tableNEWLINE # select and count grouping by the correct columnNEWLINE # this version can suffer from division by zero errorNEWLINE sid = NoneNEWLINE dbtable = EVENT_TABLE[event] # translate event to correct tableNEWLINENEWLINE if auth.user:NEWLINE sid = auth.user.usernameNEWLINE else:NEWLINE if "ipuser" in request.cookies:NEWLINE sid = request.cookies["ipuser"].valueNEWLINENEWLINE if sid:NEWLINE course = (NEWLINE db(db.courses.course_name == miscdata["course"])NEWLINE .select(**SELECT_CACHE)NEWLINE .first()NEWLINE )NEWLINE tbl = db[dbtable]NEWLINENEWLINE count_expr = tbl.correct.count()NEWLINE rows = db((tbl.sid == sid) & (tbl.timestamp > course.term_start_date)).select(NEWLINE tbl.correct, count_expr, groupby=tbl.correctNEWLINE )NEWLINE total = 0NEWLINE correct = 0NEWLINE for row in rows:NEWLINE count = row[count_expr]NEWLINE total += countNEWLINE if row[dbtable].correct:NEWLINE correct = countNEWLINE if total > 0:NEWLINE pctcorr = round(float(correct) / total * 100)NEWLINE else:NEWLINE pctcorr = "unavailable"NEWLINE else:NEWLINE pctcorr = "unavailable"NEWLINENEWLINE miscdata["yourpct"] = pctcorrNEWLINENEWLINENEWLINEdef _getStudentResults(question: str):NEWLINE """NEWLINE Internal function to collect student answersNEWLINE """NEWLINE cc = db(db.courses.id == auth.user.course_id).select().first()NEWLINE qst = (NEWLINE db(NEWLINE (db.questions.name == question)NEWLINE & (db.questions.base_course == cc.base_course)NEWLINE )NEWLINE .select()NEWLINE .first()NEWLINE )NEWLINE tbl_name = EVENT_TABLE[qst.question_type]NEWLINE tbl = db[tbl_name]NEWLINENEWLINE res = db(NEWLINE (tbl.div_id == question)NEWLINE & (tbl.course_name == cc.course_name)NEWLINE & (tbl.timestamp >= cc.term_start_date)NEWLINE ).select(tbl.sid, tbl.answer, orderby=tbl.sid)NEWLINENEWLINE resultList = []NEWLINE if len(res) > 0:NEWLINE currentSid = res[0].sidNEWLINE currentAnswers = []NEWLINENEWLINE for row in res:NEWLINE if row.answer:NEWLINE answer = clean(row.answer)NEWLINE else:NEWLINE answer = NoneNEWLINENEWLINE if row.sid == currentSid:NEWLINE if answer is not None:NEWLINE currentAnswers.append(answer)NEWLINE else:NEWLINE currentAnswers.sort()NEWLINE resultList.append((currentSid, currentAnswers))NEWLINE currentAnswers = [answer] if answer is not None else []NEWLINE currentSid = row.sidNEWLINENEWLINE currentAnswers.sort()NEWLINE resultList.append((currentSid, currentAnswers))NEWLINENEWLINE return resultListNEWLINENEWLINENEWLINEdef getaggregateresults():NEWLINE course = request.vars.courseNEWLINE question = request.vars.div_idNEWLINE # select act, count(*) from useinfo where div_id = 'question4_2_1' group by act;NEWLINE response.headers["content-type"] = "application/json"NEWLINENEWLINE if not auth.user:NEWLINE return json.dumps([dict(answerDict={}, misc={}, emess="You must be logged in")])NEWLINENEWLINE is_instructor = verifyInstructorStatus(course, auth.user.id) # noqa: F405NEWLINE # Yes, these two things could be done as a join. but this **may** be better for performanceNEWLINE if course in (NEWLINE "thinkcspy",NEWLINE "pythonds",NEWLINE "fopp",NEWLINE "csawesome",NEWLINE "apcsareview",NEWLINE "StudentCSP",NEWLINE ):NEWLINE start_date = datetime.datetime.utcnow() - datetime.timedelta(days=90)NEWLINE else:NEWLINE start_date = (NEWLINE db(db.courses.course_name == course)NEWLINE .select(db.courses.term_start_date)NEWLINE .first()NEWLINE .term_start_dateNEWLINE )NEWLINE count = db.useinfo.id.count()NEWLINE try:NEWLINE result = db(NEWLINE (db.useinfo.div_id == question)NEWLINE & (db.useinfo.course_id == course)NEWLINE & (db.useinfo.timestamp >= start_date)NEWLINE ).select(db.useinfo.act, count, groupby=db.useinfo.act)NEWLINE except Exception:NEWLINE return json.dumps(NEWLINE [dict(answerDict={}, misc={}, emess="Sorry, the request timed out")]NEWLINE )NEWLINENEWLINE tdata = {}NEWLINE tot = 0NEWLINE for row in result:NEWLINE tdata[clean(row.useinfo.act)] = row[count]NEWLINE tot += row[count]NEWLINENEWLINE tot = float(tot)NEWLINE rdata = {}NEWLINE miscdata = {}NEWLINE correct = ""NEWLINE if tot > 0:NEWLINE for key in tdata:NEWLINE all_a = key.split(":")NEWLINE try:NEWLINE answer = all_a[1]NEWLINE if "correct" in key:NEWLINE correct = answerNEWLINE count = int(tdata[key])NEWLINE if answer in rdata:NEWLINE count += rdata[answer] / 100.0 * totNEWLINE pct = round(count / tot * 100.0)NEWLINENEWLINE if answer != "undefined" and answer != "":NEWLINE rdata[answer] = pctNEWLINE except Exception as e:NEWLINE logger.error("Bad data for %s data is %s -- %s" % (question, key, e))NEWLINENEWLINE miscdata["correct"] = correctNEWLINE miscdata["course"] = courseNEWLINENEWLINE _getCorrectStats(miscdata, "mChoice")NEWLINENEWLINE returnDict = dict(answerDict=rdata, misc=miscdata)NEWLINENEWLINE if auth.user and is_instructor:NEWLINE resultList = _getStudentResults(question)NEWLINE returnDict["reslist"] = resultListNEWLINENEWLINE return json.dumps([returnDict])NEWLINENEWLINENEWLINEdef getpollresults():NEWLINE course = request.vars.courseNEWLINE div_id = request.vars.div_idNEWLINENEWLINE response.headers["content-type"] = "application/json"NEWLINENEWLINE query = """select act from useinfoNEWLINE join (select sid, max(id) midNEWLINE from useinfo where event='poll' and div_id = %s and course_id = %s group by sid) as TNEWLINE on id = T.mid"""NEWLINENEWLINE rows = db.executesql(query, (div_id, course))NEWLINENEWLINE result_list = []NEWLINE for row in rows:NEWLINE val = row[0].split(":")[0]NEWLINE result_list.append(int(val))NEWLINENEWLINE # maps option : countNEWLINE opt_counts = Counter(result_list)NEWLINENEWLINE if result_list:NEWLINE for i in range(max(result_list)):NEWLINE if i not in opt_counts:NEWLINE opt_counts[i] = 0NEWLINE # opt_list holds the option numbers from smallest to largestNEWLINE # count_list[i] holds the count of responses that chose option iNEWLINE opt_list = sorted(opt_counts.keys())NEWLINE count_list = []NEWLINE for i in opt_list:NEWLINE count_list.append(opt_counts[i])NEWLINENEWLINE user_res = NoneNEWLINE if auth.user:NEWLINE user_res = (NEWLINE db(NEWLINE (db.useinfo.sid == auth.user.username)NEWLINE & (db.useinfo.course_id == course)NEWLINE & (db.useinfo.div_id == div_id)NEWLINE )NEWLINE .select(db.useinfo.act, orderby=~db.useinfo.id)NEWLINE .first()NEWLINE )NEWLINENEWLINE if user_res:NEWLINE my_vote = user_res.actNEWLINE else:NEWLINE my_vote = -1NEWLINENEWLINE return json.dumps([len(result_list), opt_list, count_list, div_id, my_vote])NEWLINENEWLINENEWLINEdef gettop10Answers():NEWLINE course = request.vars.courseNEWLINE question = request.vars.div_idNEWLINE response.headers["content-type"] = "application/json"NEWLINE rows = []NEWLINENEWLINE try:NEWLINE dbcourse = db(db.courses.course_name == course).select(**SELECT_CACHE).first()NEWLINE count_expr = db.fitb_answers.answer.count()NEWLINE rows = db(NEWLINE (db.fitb_answers.div_id == question)NEWLINE & (db.fitb_answers.course_name == course)NEWLINE & (db.fitb_answers.timestamp > dbcourse.term_start_date)NEWLINE ).select(NEWLINE db.fitb_answers.answer,NEWLINE count_expr,NEWLINE groupby=db.fitb_answers.answer,NEWLINE orderby=~count_expr,NEWLINE limitby=(0, 10),NEWLINE )NEWLINE res = [NEWLINE {"answer": clean(row.fitb_answers.answer), "count": row[count_expr]}NEWLINE for row in rowsNEWLINE ]NEWLINE except Exception as e:NEWLINE logger.debug(e)NEWLINE res = "error in query"NEWLINENEWLINE miscdata = {"course": course}NEWLINE _getCorrectStats(NEWLINE miscdata, "fillb"NEWLINE ) # TODO: rewrite _getCorrectStats to use xxx_answersNEWLINENEWLINE if auth.user and verifyInstructorStatus(course, auth.user.id): # noqa: F405NEWLINE resultList = _getStudentResults(question)NEWLINE miscdata["reslist"] = resultListNEWLINENEWLINE return json.dumps([res, miscdata])NEWLINENEWLINENEWLINEdef getassignmentgrade():NEWLINE response.headers["content-type"] = "application/json"NEWLINE if not auth.user:NEWLINE return json.dumps([dict(message="not logged in")])NEWLINENEWLINE divid = request.vars.div_idNEWLINENEWLINE ret = {NEWLINE "grade": "Not graded yet",NEWLINE "comment": "No Comments",NEWLINE "avg": "None",NEWLINE "count": "None",NEWLINE "released": False,NEWLINE }NEWLINENEWLINE # check that the assignment is releasedNEWLINE #NEWLINE a_q = (NEWLINE db(NEWLINE (db.assignments.course == auth.user.course_id)NEWLINE & (db.assignment_questions.assignment_id == db.assignments.id)NEWLINE & (db.assignment_questions.question_id == db.questions.id)NEWLINE & (db.questions.name == divid)NEWLINE )NEWLINE .select(NEWLINE db.assignments.released, db.assignments.id, db.assignment_questions.pointsNEWLINE )NEWLINE .first()NEWLINE )NEWLINENEWLINE # if there is no assignment_questionNEWLINE # try new way that we store scores and commentsNEWLINE # divid is a question; find question_grades rowNEWLINE result = (NEWLINE db(NEWLINE (db.question_grades.sid == auth.user.username)NEWLINE & (db.question_grades.course_name == auth.user.course_name)NEWLINE & (db.question_grades.div_id == divid)NEWLINE )NEWLINE .select(db.question_grades.score, db.question_grades.comment)NEWLINE .first()NEWLINE )NEWLINE logger.debug(result)NEWLINE if result:NEWLINE # say that we're sending back result styles in new version, so they can be processed differently without affecting old way during transition.NEWLINE ret["version"] = 2NEWLINE ret["released"] = a_q.assignments.released if a_q else FalseNEWLINE if a_q and not a_q.assignments.released:NEWLINE ret["grade"] = "Not graded yet"NEWLINE elif a_q and a_q.assignments.released:NEWLINE ret["grade"] = result.score or "Written Feedback Only"NEWLINENEWLINE if a_q and a_q.assignments.released == True:NEWLINE ret["max"] = a_q.assignment_questions.pointsNEWLINE else:NEWLINE ret["max"] = ""NEWLINENEWLINE if result.comment:NEWLINE ret["comment"] = result.commentNEWLINENEWLINE return json.dumps([ret])NEWLINENEWLINENEWLINEdef _canonicalize_tz(tstring):NEWLINE x = re.search(r"\((.*)\)", tstring)NEWLINE x = x.group(1)NEWLINE y = x.split()NEWLINE if len(y) == 1:NEWLINE return tstringNEWLINE else:NEWLINE zstring = "".join([i[0] for i in y])NEWLINE return re.sub(r"(.*)\((.*)\)", r"\1({})".format(zstring), tstring)NEWLINENEWLINENEWLINE# .. _getAssessResults:NEWLINE#NEWLINE# getAssessResultsNEWLINE# ----------------NEWLINEdef getAssessResults():NEWLINE if not auth.user:NEWLINE # can't query for user's answers if we don't know who the user is, so just load from local storageNEWLINE return ""NEWLINENEWLINE course = request.vars.courseNEWLINE div_id = request.vars.div_idNEWLINE event = request.vars.eventNEWLINE if (NEWLINE verifyInstructorStatus(auth.user.course_name, auth.user) and request.vars.sidNEWLINE ): # retrieving results for graderNEWLINE sid = request.vars.sidNEWLINE else:NEWLINE sid = auth.user.usernameNEWLINENEWLINE # TODO This whole thing is messy - get the deadline from the assignment in the dbNEWLINE if request.vars.deadline:NEWLINE try:NEWLINE deadline = parse(_canonicalize_tz(request.vars.deadline))NEWLINE tzoff = session.timezoneoffset if session.timezoneoffset else 0NEWLINE deadline = deadline + datetime.timedelta(hours=float(tzoff))NEWLINE deadline = deadline.replace(tzinfo=None)NEWLINE except Exception:NEWLINE logger.error("Bad Timezone - {}".format(request.vars.deadline))NEWLINE deadline = datetime.datetime.utcnow()NEWLINE else:NEWLINE deadline = datetime.datetime.utcnow()NEWLINENEWLINE response.headers["content-type"] = "application/json"NEWLINENEWLINE # Identify the correct event and query the database so we can load it from the serverNEWLINE if event == "fillb":NEWLINE rows = (NEWLINE db(NEWLINE (db.fitb_answers.div_id == div_id)NEWLINE & (db.fitb_answers.course_name == course)NEWLINE & (db.fitb_answers.sid == sid)NEWLINE )NEWLINE .select(NEWLINE db.fitb_answers.answer,NEWLINE db.fitb_answers.timestamp,NEWLINE orderby=~db.fitb_answers.id,NEWLINE )NEWLINE .first()NEWLINE )NEWLINE if not rows:NEWLINE return "" # server doesn't have it so we load from local storage insteadNEWLINE #NEWLINE res = {"answer": rows.answer, "timestamp": str(rows.timestamp)}NEWLINE do_server_feedback, feedback = is_server_feedback(div_id, course)NEWLINE if do_server_feedback:NEWLINE correct, res_update = fitb_feedback(rows.answer, feedback)NEWLINE res.update(res_update)NEWLINE return json.dumps(res)NEWLINE elif event == "mChoice":NEWLINE rows = (NEWLINE db(NEWLINE (db.mchoice_answers.div_id == div_id)NEWLINE & (db.mchoice_answers.course_name == course)NEWLINE & (db.mchoice_answers.sid == sid)NEWLINE )NEWLINE .select(NEWLINE db.mchoice_answers.answer,NEWLINE db.mchoice_answers.timestamp,NEWLINE db.mchoice_answers.correct,NEWLINE orderby=~db.mchoice_answers.id,NEWLINE )NEWLINE .first()NEWLINE )NEWLINE if not rows:NEWLINE return ""NEWLINE res = {NEWLINE "answer": rows.answer,NEWLINE "timestamp": str(rows.timestamp),NEWLINE "correct": rows.correct,NEWLINE }NEWLINE return json.dumps(res)NEWLINE elif event == "dragNdrop":NEWLINE rows = (NEWLINE db(NEWLINE (db.dragndrop_answers.div_id == div_id)NEWLINE & (db.dragndrop_answers.course_name == course)NEWLINE & (db.dragndrop_answers.sid == sid)NEWLINE )NEWLINE .select(NEWLINE db.dragndrop_answers.answer,NEWLINE db.dragndrop_answers.timestamp,NEWLINE db.dragndrop_answers.correct,NEWLINE db.dragndrop_answers.min_height,NEWLINE orderby=~db.dragndrop_answers.id,NEWLINE )NEWLINE .first()NEWLINE )NEWLINE if not rows:NEWLINE return ""NEWLINE res = {NEWLINE "answer": rows.answer,NEWLINE "timestamp": str(rows.timestamp),NEWLINE "correct": rows.correct,NEWLINE "minHeight": str(rows.min_height),NEWLINE }NEWLINE return json.dumps(res)NEWLINE elif event == "clickableArea":NEWLINE rows = (NEWLINE db(NEWLINE (db.clickablearea_answers.div_id == div_id)NEWLINE & (db.clickablearea_answers.course_name == course)NEWLINE & (db.clickablearea_answers.sid == sid)NEWLINE )NEWLINE .select(NEWLINE db.clickablearea_answers.answer,NEWLINE db.clickablearea_answers.timestamp,NEWLINE db.clickablearea_answers.correct,NEWLINE orderby=~db.clickablearea_answers.id,NEWLINE )NEWLINE .first()NEWLINE )NEWLINE if not rows:NEWLINE return ""NEWLINE res = {NEWLINE "answer": rows.answer,NEWLINE "timestamp": str(rows.timestamp),NEWLINE "correct": rows.correct,NEWLINE }NEWLINE return json.dumps(res)NEWLINE elif event == "timedExam":NEWLINE rows = (NEWLINE db(NEWLINE (db.timed_exam.reset == None) # noqa: E711NEWLINE & (db.timed_exam.div_id == div_id)NEWLINE & (db.timed_exam.course_name == course)NEWLINE & (db.timed_exam.sid == sid)NEWLINE )NEWLINE .select(NEWLINE db.timed_exam.correct,NEWLINE db.timed_exam.incorrect,NEWLINE db.timed_exam.skipped,NEWLINE db.timed_exam.time_taken,NEWLINE db.timed_exam.timestamp,NEWLINE db.timed_exam.reset,NEWLINE orderby=~db.timed_exam.id,NEWLINE )NEWLINE .first()NEWLINE )NEWLINE if not rows:NEWLINE return ""NEWLINE res = {NEWLINE "correct": rows.correct,NEWLINE "incorrect": rows.incorrect,NEWLINE "skipped": str(rows.skipped),NEWLINE "timeTaken": str(rows.time_taken),NEWLINE "timestamp": str(rows.timestamp),NEWLINE "reset": str(rows.reset),NEWLINE }NEWLINE return json.dumps(res)NEWLINE elif event == "parsons":NEWLINE rows = (NEWLINE db(NEWLINE (db.parsons_answers.div_id == div_id)NEWLINE & (db.parsons_answers.course_name == course)NEWLINE & (db.parsons_answers.sid == sid)NEWLINE )NEWLINE .select(NEWLINE db.parsons_answers.answer,NEWLINE db.parsons_answers.source,NEWLINE db.parsons_answers.timestamp,NEWLINE orderby=~db.parsons_answers.id,NEWLINE )NEWLINE .first()NEWLINE )NEWLINE if not rows:NEWLINE return ""NEWLINE res = {NEWLINE "answer": rows.answer,NEWLINE "source": rows.source,NEWLINE "timestamp": str(rows.timestamp),NEWLINE }NEWLINE return json.dumps(res)NEWLINE elif event == "shortanswer":NEWLINE logger.debug(f"Getting shortanswer: deadline is {deadline} ")NEWLINE rows = db(NEWLINE (db.shortanswer_answers.sid == sid)NEWLINE & (db.shortanswer_answers.div_id == div_id)NEWLINE & (db.shortanswer_answers.course_name == course)NEWLINE ).select(orderby=~db.shortanswer_answers.id)NEWLINE if not rows:NEWLINE return ""NEWLINE last_answer = NoneNEWLINE if not request.vars.deadline:NEWLINE row = rows[0]NEWLINE else:NEWLINE last_answer = rows[0]NEWLINE for row in rows:NEWLINE if row.timestamp <= deadline:NEWLINE breakNEWLINE if row.timestamp > deadline:NEWLINE row = NoneNEWLINENEWLINE if row and row == last_answer:NEWLINE res = {"answer": row.answer, "timestamp": row.timestamp.isoformat()}NEWLINE else:NEWLINE if row and row.timestamp <= deadline:NEWLINE res = {"answer": row.answer, "timestamp": row.timestamp.isoformat()}NEWLINE else:NEWLINE res = {NEWLINE "answer": "",NEWLINE "timestamp": None,NEWLINE "last_answer": last_answer.answer,NEWLINE "last_timestamp": last_answer.timestamp.isoformat(),NEWLINE }NEWLINE srow = (NEWLINE db(NEWLINE (db.question_grades.sid == sid)NEWLINE & (db.question_grades.div_id == div_id)NEWLINE & (db.question_grades.course_name == course)NEWLINE )NEWLINE .select()NEWLINE .first()NEWLINE )NEWLINE if srow:NEWLINE res["score"] = srow.scoreNEWLINE res["comment"] = srow.commentNEWLINENEWLINE return json.dumps(res)NEWLINE elif event == "lp_build":NEWLINE rows = (NEWLINE db(NEWLINE (db.lp_answers.div_id == div_id)NEWLINE & (db.lp_answers.course_name == course)NEWLINE & (db.lp_answers.sid == sid)NEWLINE )NEWLINE .select(NEWLINE db.lp_answers.answer,NEWLINE db.lp_answers.timestamp,NEWLINE db.lp_answers.correct,NEWLINE orderby=~db.lp_answers.id,NEWLINE )NEWLINE .first()NEWLINE )NEWLINE if not rows:NEWLINE return "" # server doesn't have it so we load from local storage insteadNEWLINE answer = json.loads(rows.answer)NEWLINE correct = rows.correctNEWLINE return json.dumps(NEWLINE {"answer": answer, "timestamp": str(rows.timestamp), "correct": correct}NEWLINE )NEWLINENEWLINENEWLINEdef tookTimedAssessment():NEWLINE if auth.user:NEWLINE sid = auth.user.usernameNEWLINE else:NEWLINE return json.dumps({"tookAssessment": False})NEWLINENEWLINE exam_id = request.vars.div_idNEWLINE course = request.vars.course_nameNEWLINE rows = (NEWLINE db(NEWLINE (db.timed_exam.div_id == exam_id)NEWLINE & (db.timed_exam.sid == sid)NEWLINE & (db.timed_exam.course_name == course)NEWLINE )NEWLINE .select(orderby=~db.timed_exam.id)NEWLINE .first()NEWLINE )NEWLINE logger.debug(f"checking {exam_id} {sid} {course} {rows}")NEWLINE if rows:NEWLINE return json.dumps({"tookAssessment": True})NEWLINE else:NEWLINE return json.dumps({"tookAssessment": False})NEWLINENEWLINENEWLINE# The request variable ``code`` must contain JSON-encoded RST to be rendered by Runestone. Only the HTML containing the actual Runestone component will be returned.NEWLINEdef preview_question():NEWLINENEWLINE begin = """NEWLINE.. raw:: htmlNEWLINENEWLINE NEWLINENEWLINE"""NEWLINE end = """NEWLINENEWLINE.. raw:: htmlNEWLINENEWLINE NEWLINENEWLINE"""NEWLINENEWLINE try:NEWLINE code = begin + dedent(json.loads(request.vars.code)) + endNEWLINE with open(NEWLINE "applications/{}/build/preview/_sources/index.rst".format(NEWLINE request.applicationNEWLINE ),NEWLINE "w",NEWLINE encoding="utf-8",NEWLINE ) as ixf:NEWLINE ixf.write(code)NEWLINENEWLINE # Note that ``os.environ`` isn't a dict, it's an object whose setter modifies environment variables. So, modifications of a copy/deepcopy still `modify the original environment `_. Therefore, convert it to a dict, where modifications will not affect the environment.NEWLINE env = dict(os.environ)NEWLINE # Prevent any changes to the database when building a preview question.NEWLINE env.pop("DBURL", None)NEWLINE # Run a runestone build.NEWLINE # We would like to use sys.executable But when we run web2pyNEWLINE # in uwsgi then sys.executable is uwsgi which doesn't work.NEWLINE # Why not just run runestone?NEWLINE if "python" not in settings.python_interpreter:NEWLINE logger.error(f"Error {settings.python_interpreter} is not a valid python")NEWLINE return json.dumps(NEWLINE f"Error: settings.python_interpreter must be set to a valid interpreter not {settings.python_interpreter}"NEWLINE )NEWLINE popen_obj = subprocess.Popen(NEWLINE [settings.python_interpreter, "-m", "runestone", "build"],NEWLINE # The build must be run from the directory containing a ``conf.py`` and all the needed support files.NEWLINE cwd="applications/{}/build/preview".format(request.application),NEWLINE # Capture the build output as text in case of an error.NEWLINE stdout=subprocess.PIPE,NEWLINE stderr=subprocess.PIPE,NEWLINE universal_newlines=True,NEWLINE # Pass the modified environment which doesn't contain ``DBURL``.NEWLINE env=env,NEWLINE )NEWLINE stdout, stderr = popen_obj.communicate()NEWLINE # If there was an error, return stdout and stderr from the build.NEWLINE if popen_obj.returncode != 0:NEWLINE return json.dumps(NEWLINE "Error: Runestone build failed:\n\n" + stdout + "\n" + stderrNEWLINE )NEWLINENEWLINE with open(NEWLINE "applications/{}/build/preview/build/preview/index.html".format(NEWLINE request.applicationNEWLINE ),NEWLINE "r",NEWLINE encoding="utf-8",NEWLINE ) as ixf:NEWLINE src = ixf.read()NEWLINE tree = html.fromstring(src)NEWLINE if len(tree.cssselect(".runestone")) == 0:NEWLINE src = ""NEWLINE result = re.search(NEWLINE "(.*)", src, flags=re.DOTALLNEWLINE )NEWLINE if result:NEWLINE ctext = result.group(1)NEWLINE else:NEWLINE component = tree.cssselect(".system-message")NEWLINE if len(component) > 0:NEWLINE ctext = html.tostring(component[0]).decode("utf-8")NEWLINE logger.debug("error - ", ctext)NEWLINE else:NEWLINE ctext = "Error: Runestone content missing."NEWLINE return json.dumps(ctext)NEWLINE except Exception as ex:NEWLINE return json.dumps("Error: {}".format(ex))NEWLINENEWLINENEWLINEdef save_donate():NEWLINE if auth.user:NEWLINE db(db.auth_user.id == auth.user.id).update(donated=True)NEWLINENEWLINENEWLINEdef did_donate():NEWLINE if auth.user:NEWLINE d_status = (NEWLINE db(db.auth_user.id == auth.user.id).select(db.auth_user.donated).first()NEWLINE )NEWLINENEWLINE return json.dumps(dict(donate=d_status.donated))NEWLINE return json.dumps(dict(donate=False))NEWLINENEWLINENEWLINEdef get_datafile():NEWLINE """NEWLINE course_id - string, the name of the courseNEWLINE acid - the acid of this datafileNEWLINE """NEWLINE course = request.vars.course_id # the course nameNEWLINE the_course = db(db.courses.course_name == course).select(**SELECT_CACHE).first()NEWLINE acid = request.vars.acidNEWLINE file_contents = (NEWLINE db(NEWLINE (db.source_code.acid == acid)NEWLINE & (NEWLINE (db.source_code.course_id == the_course.base_course)NEWLINE | (db.source_code.course_id == course)NEWLINE )NEWLINE )NEWLINE .select(db.source_code.main_code)NEWLINE .first()NEWLINE )NEWLINENEWLINE if file_contents:NEWLINE file_contents = file_contents.main_codeNEWLINE else:NEWLINE file_contents = NoneNEWLINENEWLINE return json.dumps(dict(data=file_contents))NEWLINENEWLINENEWLINE@auth.requires(NEWLINE lambda: verifyInstructorStatus(auth.user.course_name, auth.user),NEWLINE requires_login=True,NEWLINE)NEWLINEdef broadcast_code():NEWLINE """NEWLINE Callable by an instructor to send the code in their scratch activecodeNEWLINE to all students in the class.NEWLINE """NEWLINE the_course = (NEWLINE db(db.courses.course_name == auth.user.course_name)NEWLINE .select(**SELECT_CACHE)NEWLINE .first()NEWLINE )NEWLINE cid = the_course.idNEWLINE student_list = db(NEWLINE (db.user_courses.course_id == cid)NEWLINE & (db.auth_user.id == db.user_courses.user_id)NEWLINE ).select()NEWLINE shared_code = (NEWLINE "{} Instructor shared code on {}\n".format(NEWLINE COMMENT_MAP.get(request.vars.lang, "#"), datetime.datetime.utcnow().date()NEWLINE )NEWLINE + request.vars.codeNEWLINE )NEWLINE counter = 0NEWLINE for student in student_list:NEWLINE if student.auth_user.id == auth.user.id:NEWLINE continueNEWLINE sid = student.auth_user.usernameNEWLINE try:NEWLINE db.code.insert(NEWLINE sid=sid,NEWLINE acid=request.vars.divid,NEWLINE code=shared_code,NEWLINE emessage="",NEWLINE timestamp=datetime.datetime.utcnow(),NEWLINE course_id=cid,NEWLINE language=request.vars.lang,NEWLINE comment="Instructor shared code",NEWLINE )NEWLINE except Exception as e:NEWLINE logger.error("Failed to insert instructor code! details: {}".format(e))NEWLINE return json.dumps(dict(mess="failed"))NEWLINENEWLINE counter += 1NEWLINENEWLINE return json.dumps(dict(mess="success", share_count=counter))NEWLINENEWLINENEWLINEdef _same_class(user1: str, user2: str) -> bool:NEWLINE user1_course = (NEWLINE db(db.auth_user.username == user1).select(db.auth_user.course_id).first()NEWLINE )NEWLINE user2_course = (NEWLINE db(db.auth_user.username == user2).select(db.auth_user.course_id).first()NEWLINE )NEWLINENEWLINE return user1_course == user2_courseNEWLINENEWLINENEWLINEdef login_status():NEWLINE if auth.user:NEWLINE return json.dumps(dict(status="loggedin", course_name=auth.user.course_name))NEWLINE else:NEWLINE return json.dumps(dict(status="loggedout", course_name=auth.user.course_name))NEWLINENEWLINENEWLINEauto_gradable_q = [NEWLINE "clickablearea",NEWLINE "mchoice",NEWLINE "parsonsprob",NEWLINE "dragndrop",NEWLINE "fillintheblank",NEWLINE]NEWLINENEWLINENEWLINE@auth.requires_login()NEWLINEdef get_question_source():NEWLINE """Called from the selectquestion directiveNEWLINE There are 4 cases:NEWLINENEWLINE 1. If there is only 1 question in the question list then return the html source for it.NEWLINE 2. If there are multiple questions then choose a question at randomNEWLINE 3. If a proficiency is selected then select a random question that tests that proficiencyNEWLINE 4. If the question is an AB question then see if this student is an A or a B or assign them to one randomly.NEWLINENEWLINE In the last two cases, first check to see if there is a question for this student for thisNEWLINE component that was previously selected.NEWLINENEWLINE Returns:NEWLINE json: html source for this questionNEWLINE """NEWLINE prof = FalseNEWLINE points = request.vars.pointsNEWLINE logger.debug(f"POINTS = {points}")NEWLINE min_difficulty = request.vars.min_difficultyNEWLINE max_difficulty = request.vars.max_difficultyNEWLINE not_seen_ever = request.vars.not_seen_everNEWLINE autogradable = request.vars.autogradableNEWLINE is_primary = request.vars.primaryNEWLINE is_ab = request.vars.ABNEWLINE selector_id = request.vars["selector_id"]NEWLINE assignment_name = request.vars["timedWrapper"]NEWLINE toggle = request.vars["toggle"]NEWLINENEWLINE # If the question has a :points: option then those points are the defaultNEWLINE # however sometimes questions are entered in the web ui without the :points:NEWLINE # and points are assigned in the UI instead. If this is part of anNEWLINE # assignment or timed exam AND the points are set in the web UI we willNEWLINE # use the points from the UI over the :points: If this is an assignmentNEWLINE # or exam that is totally written in RST then the points in the UI will matchNEWLINE # the points from the assignment anyway.NEWLINE if assignment_name:NEWLINE ui_points = (NEWLINE db(NEWLINE (db.assignments.name == assignment_name)NEWLINE & (db.assignments.id == db.assignment_questions.assignment_id)NEWLINE & (db.assignment_questions.question_id == db.questions.id)NEWLINE & (db.questions.name == selector_id)NEWLINE )NEWLINE .select(db.assignment_questions.points)NEWLINE .first()NEWLINE )NEWLINE logger.debug(NEWLINE f"Assignment Points for {assignment_name}, {selector_id} = {ui_points}"NEWLINE )NEWLINE points = ui_points.pointsNEWLINENEWLINE if request.vars["questions"]:NEWLINE questionlist = request.vars["questions"].split(",")NEWLINE questionlist = [q.strip() for q in questionlist]NEWLINE elif request.vars["proficiency"]:NEWLINE prof = request.vars["proficiency"]NEWLINENEWLINE query = (db.competency.competency == prof) & (NEWLINE db.competency.question == db.questions.idNEWLINE )NEWLINE if is_primary:NEWLINE query = query & (db.competency.is_primary == True)NEWLINE if min_difficulty:NEWLINE query = query & (db.questions.difficulty >= float(min_difficulty))NEWLINE if max_difficulty:NEWLINE query = query & (db.questions.difficulty <= float(max_difficulty))NEWLINE if autogradable:NEWLINE query = query & (NEWLINE (db.questions.autograde == "unittest")NEWLINE | db.questions.question_type.contains(auto_gradable_q, all=False)NEWLINE )NEWLINE res = db(query).select(db.questions.name)NEWLINE logger.debug(f"Query was {db._lastsql}")NEWLINE if res:NEWLINE questionlist = [row.name for row in res]NEWLINE else:NEWLINE questionlist = []NEWLINE logger.error(f"No questions found for proficiency {prof}")NEWLINE return json.dumps(f"

No Questions found for proficiency: {prof}

")NEWLINENEWLINE logger.debug(f"is_ab is {is_ab}")NEWLINE if is_ab:NEWLINENEWLINE res = db(NEWLINE (db.user_experiment.sid == auth.user.username)NEWLINE & (db.user_experiment.experiment_id == is_ab)NEWLINE ).select(orderby=db.user_experiment.id)NEWLINENEWLINE if not res:NEWLINE exp_group = random.randrange(2)NEWLINE db.user_experiment.insert(NEWLINE sid=auth.user.username, experiment_id=is_ab, exp_group=exp_groupNEWLINE )NEWLINE logger.debug(f"added {auth.user.username} to {is_ab} group {exp_group}")NEWLINENEWLINE else:NEWLINE exp_group = res[0].exp_groupNEWLINENEWLINE logger.debug(f"experimental group is {exp_group}")NEWLINENEWLINE prev_selection = (NEWLINE db(NEWLINE (db.selected_questions.sid == auth.user.username)NEWLINE & (db.selected_questions.selector_id == selector_id)NEWLINE )NEWLINE .select()NEWLINE .first()NEWLINE )NEWLINENEWLINE if prev_selection:NEWLINE questionid = prev_selection.selected_idNEWLINE else:NEWLINE questionid = questionlist[exp_group]NEWLINENEWLINE if not is_ab:NEWLINE poss = set()NEWLINE if not_seen_ever:NEWLINE seenq = db(NEWLINE (db.useinfo.sid == auth.user.username)NEWLINE & (db.useinfo.div_id.contains(questionlist, all=False))NEWLINE ).select(db.useinfo.div_id)NEWLINE seen = set([x.div_id for x in seenq])NEWLINE poss = set(questionlist)NEWLINE questionlist = list(poss - seen)NEWLINENEWLINE if len(questionlist) == 0 and len(poss) > 0:NEWLINE questionlist = list(poss)NEWLINENEWLINE htmlsrc = ""NEWLINENEWLINE prev_selection = (NEWLINE db(NEWLINE (db.selected_questions.sid == auth.user.username)NEWLINE & (db.selected_questions.selector_id == selector_id)NEWLINE )NEWLINE .select()NEWLINE .first()NEWLINE )NEWLINENEWLINE if prev_selection:NEWLINE questionid = prev_selection.selected_idNEWLINE else:NEWLINE # Eliminate any previous exam questions for this studentNEWLINE prev_questions = db(db.selected_questions.sid == auth.user.username).select(NEWLINE db.selected_questions.selected_idNEWLINE )NEWLINE prev_questions = set([row.selected_id for row in prev_questions])NEWLINE possible = set(questionlist)NEWLINE questionlist = list(possible - prev_questions)NEWLINE if questionlist:NEWLINE questionid = random.choice(questionlist)NEWLINE else:NEWLINE # If there are no questions left we should still return a random question.NEWLINE questionid = random.choice(list(possible))NEWLINENEWLINE logger.debug(f"toggle is {toggle}")NEWLINE if toggle:NEWLINE prev_selection = (NEWLINE db(NEWLINE (db.selected_questions.sid == auth.user.username)NEWLINE & (db.selected_questions.selector_id == selector_id)NEWLINE )NEWLINE .select()NEWLINE .first()NEWLINE )NEWLINE if prev_selection:NEWLINE questionid = prev_selection.selected_idNEWLINE else:NEWLINE questionid = request.vars["questions"].split(",")[0]NEWLINE # else:NEWLINE # logger.error(NEWLINE # f"Question ID '{questionid}' not found in select question list of '{selector_id}'."NEWLINE # )NEWLINE # return json.dumps(NEWLINE # f"

Question ID '{questionid}' not found in select question list of '{selector_id}'.

"NEWLINE # )NEWLINENEWLINE res = db((db.questions.name == questionid)).select(db.questions.htmlsrc).first()NEWLINENEWLINE if res and not prev_selection:NEWLINE qid = db.selected_questions.insert(NEWLINE selector_id=selector_id,NEWLINE sid=auth.user.username,NEWLINE selected_id=questionid,NEWLINE points=points,NEWLINE )NEWLINE if not qid:NEWLINE logger.error(NEWLINE f"Failed to insert a selected question for {selector_id} and {auth.user.username}"NEWLINE )NEWLINE else:NEWLINE logger.debug(NEWLINE f"Did not insert a record for {selector_id}, {questionid} Conditions are {res} QL: {questionlist} PREV: {prev_selection}"NEWLINE )NEWLINENEWLINE if res and res.htmlsrc:NEWLINE htmlsrc = res.htmlsrcNEWLINE else:NEWLINE logger.error(NEWLINE f"HTML Source not found for {questionid} in course {auth.user.course_name} for {auth.user.username}"NEWLINE )NEWLINE htmlsrc = "

No preview available

"NEWLINE return json.dumps(htmlsrc)NEWLINENEWLINENEWLINE@auth.requires_login()NEWLINEdef update_selected_question():NEWLINE """NEWLINE This endpoint is used by the selectquestion problems that allow theNEWLINE student to select the problem they work on. For example they may haveNEWLINE a programming problem that can be solved with writing code, or theyNEWLINE can switch to a parsons problem if necessary.NEWLINENEWLINE Caller must provide:NEWLINE * ``metaid`` -- the id of the selectquestionNEWLINE * ``selected`` -- the id of the real question chosen by the studentNEWLINE """NEWLINE sid = auth.user.usernameNEWLINE selector_id = request.vars.metaidNEWLINE selected_id = request.vars.selectedNEWLINE logger.debug(f"USQ - {selector_id} --> {selected_id} for {sid}")NEWLINE db.selected_questions.update_or_insert(NEWLINE (db.selected_questions.selector_id == selector_id)NEWLINE & (db.selected_questions.sid == sid),NEWLINE selected_id=selected_id,NEWLINE selector_id=selector_id,NEWLINE sid=sid,NEWLINE )NEWLINE import timeNEWLINEimport typingNEWLINEimport inspectNEWLINEfrom uuid import uuid4NEWLINEfrom broccoli.injector import ASyncInjectorNEWLINEfrom broccoli.components import ReturnValueNEWLINEfrom broccoli.task import create_taskNEWLINEfrom broccoli.result import AsyncResultNEWLINEfrom broccoli.types import App, Broker, Task, Message, Arguments, Fence, TaskLoggerNEWLINEfrom broccoli.traceback import extract_log_tbNEWLINEfrom broccoli.utils import cached_propertyNEWLINEfrom broccoli.graph import GraphNEWLINEfrom broccoli.exceptions import RejectNEWLINEfrom broccoli.router import ROUTER_COMPONENTSNEWLINEfrom broccoli.broker import BROKER_COMPONENTSNEWLINEfrom broccoli.logger import LOGGER_COMPONENTSNEWLINEfrom broccoli.config import CONFIG_COMPONENTSNEWLINEfrom broccoli.arguments import ARGUMENT_COMPONENTSNEWLINENEWLINE__all__ = ('Broccoli',)NEWLINENEWLINENEWLINEclass nullfence:NEWLINENEWLINE def __enter__(self):NEWLINE passNEWLINENEWLINE def __exit__(self, *excinfo):NEWLINE passNEWLINENEWLINENEWLINEclass Broccoli(App):NEWLINE _injector: ASyncInjector = NoneNEWLINE _tasks: typing.Dict[str, Task] = NoneNEWLINE result_factory = AsyncResultNEWLINE graph_factory = GraphNEWLINENEWLINE def __init__(self, components=None, settings=None) -> None:NEWLINE if components:NEWLINE msg = 'components must be a list of instances of Component.'NEWLINE assert all([(not isinstance(component, type) and hasattr(component, 'resolve'))NEWLINE for component in components]), msgNEWLINE if settings is not None:NEWLINE msg = 'settings must be a dict.'NEWLINE assert isinstance(settings, dict), msgNEWLINENEWLINE self.settings = settingsNEWLINE self._init_injector(components or [])NEWLINE self._tasks = {}NEWLINE self._context = {}NEWLINE self._graphs = {}NEWLINENEWLINE def set_context(self, **context):NEWLINE self._context = dict(self._context, **context)NEWLINE self._graphs = {}NEWLINE self._injector.clear_cache()NEWLINENEWLINE def get_context(self):NEWLINE return self._contextNEWLINENEWLINE def set_hooks(self,NEWLINE on_request: typing.Callable = None,NEWLINE on_response: typing.Callable = None):NEWLINE if on_request:NEWLINE if inspect.iscoroutinefunction(on_request):NEWLINE msg = 'Function %r may not be async.'NEWLINE raise TypeError(msg % on_request)NEWLINE self._on_request_hook = on_requestNEWLINE elif '_on_request_hook' in self.__dict__:NEWLINE del self._on_request_hookNEWLINE if on_response:NEWLINE if inspect.iscoroutinefunction(on_response):NEWLINE msg = 'Function %r may not be async.'NEWLINE raise TypeError(msg % on_response)NEWLINE self._on_response_hook = on_responseNEWLINE elif '_on_response_hook' in self.__dict__:NEWLINE del self._on_response_hookNEWLINENEWLINE def _init_injector(self, components):NEWLINE components = components or []NEWLINE components += ROUTER_COMPONENTSNEWLINE components += LOGGER_COMPONENTSNEWLINE components += BROKER_COMPONENTSNEWLINE components += CONFIG_COMPONENTSNEWLINE components += ARGUMENT_COMPONENTSNEWLINENEWLINE initial = {NEWLINE 'app': App,NEWLINE 'message': Message,NEWLINE 'args': Arguments,NEWLINE 'task': Task,NEWLINE 'exc': Exception,NEWLINE 'fence': FenceNEWLINE }NEWLINENEWLINE self._injector = ASyncInjector(components, initial)NEWLINENEWLINE def inject(self, funcs, args=None, cache=True):NEWLINE state = {NEWLINE 'app': self,NEWLINE 'message': None,NEWLINE 'args': args,NEWLINE 'task': None,NEWLINE 'exc': None,NEWLINE 'fence': NoneNEWLINE }NEWLINE return self._injector.run(NEWLINE funcs,NEWLINE state=state,NEWLINE cache=cacheNEWLINE )NEWLINENEWLINE def get_task(self, name: str):NEWLINE try:NEWLINE return self._tasks[name]NEWLINE except KeyError:NEWLINE raise Reject('Task %s not found' % name)NEWLINENEWLINE def task(self, *args, **kwargs):NEWLINE def create_task_wrapper(func):NEWLINE if inspect.iscoroutinefunction(func):NEWLINE msg = 'Function %r may not be async.'NEWLINE raise TypeError(msg % func)NEWLINE task = create_task(self, func, **kwargs)NEWLINE if task.name in self._tasks:NEWLINE msg = 'Task with name %r is already registered.'NEWLINE raise TypeError(msg % task.name)NEWLINE self._tasks[task.name] = taskNEWLINE return taskNEWLINENEWLINE if len(args) == 1:NEWLINE if callable(args[0]):NEWLINE return create_task_wrapper(*args)NEWLINE raise TypeError("Argument 1 to @task() must be a callable")NEWLINENEWLINE if args:NEWLINE raise TypeError("@task() takes exactly 1 argument")NEWLINENEWLINE return create_task_wrapperNEWLINENEWLINE def send_message(self, message: dict):NEWLINE self._broker.send_message(message)NEWLINENEWLINE def result(self, result_key: str):NEWLINE return self.result_factory(self, result_key)NEWLINENEWLINE def serve_message(self, message: dict, fence: Fence = None):NEWLINE if 'id' not in message:NEWLINE raise Reject('no id')NEWLINENEWLINE if 'task' not in message:NEWLINE raise Reject('no task')NEWLINENEWLINE if 'reply_id' in message:NEWLINE if 'graph_id' not in message:NEWLINE raise Reject('no graph_id')NEWLINE graph_id = message['graph_id']NEWLINE if graph_id not in self._graphs:NEWLINE raise Reject('unexpected graph_id')NEWLINE graph = self._graphs[graph_id]NEWLINE if message['reply_id'] not in graph:NEWLINE raise Reject('unexpected reply id')NEWLINE graph.run_reply(message)NEWLINE return graph.get_pending_messages()NEWLINE else:NEWLINE coro = self._run_async(message, fence)NEWLINE try:NEWLINE graph = coro.send(None)NEWLINE graph.set_coroutine(coro)NEWLINE return graph.get_pending_messages()NEWLINE except StopIteration as stop:NEWLINE return [stop.value]NEWLINENEWLINE async def _run_async(self, message, fence):NEWLINE state = {NEWLINE 'app': self,NEWLINE 'message': message,NEWLINE 'fence': fence,NEWLINE 'args': None,NEWLINE 'task': None,NEWLINE 'exc': None,NEWLINE 'return_value': NoneNEWLINE }NEWLINENEWLINE try:NEWLINE __log_tb_start__ = NoneNEWLINE task = self.get_task(message['task'])NEWLINE state['task'] = taskNEWLINE funcs = (NEWLINE self._on_request,NEWLINE self._on_request_hook,NEWLINE self._build_graph,NEWLINE task.handler,NEWLINE self._on_response_hook,NEWLINE self._on_response,NEWLINE )NEWLINE return await self._injector.run_async(funcs, state=state)NEWLINE except Exception as exc:NEWLINE try:NEWLINE state['exc'] = excNEWLINE step = state.get('$step', 0)NEWLINE if 0 < step < 4:NEWLINE funcs = (self._on_response_hook, self._on_response)NEWLINE else:NEWLINE funcs = (self._on_response,)NEWLINE return self._injector.run(funcs, state=state)NEWLINE except Exception as inner_exc:NEWLINE state['exc'] = inner_excNEWLINE return self._injector.run((self._on_response,), state)NEWLINENEWLINE @staticmethodNEWLINE def _on_request(message: Message):NEWLINE expires_at = message.get('expires_at')NEWLINE if expires_at is not None and isinstance(expires_at, (int, float)):NEWLINE if expires_at < time.time():NEWLINE raise Reject('Due to expiration time.')NEWLINENEWLINE @staticmethodNEWLINE def _on_request_hook(ret: ReturnValue):NEWLINE return retNEWLINENEWLINE async def _build_graph(self, task: Task, message: Message) -> Arguments:NEWLINE args = ()NEWLINE if message.get('subtasks'):NEWLINE graph = self.graph_factory(message)NEWLINE self._graphs[graph.id] = graphNEWLINE try:NEWLINE args = await graphNEWLINE finally:NEWLINE graph.close()NEWLINE del self._graphs[graph.id]NEWLINE return task.get_arguments(NEWLINE *((message.get('args') or ()) + tuple(args)),NEWLINE **(message.get('kwargs') or {})NEWLINE )NEWLINENEWLINE @staticmethodNEWLINE def _on_response_hook(ret: ReturnValue):NEWLINE return retNEWLINENEWLINE @staticmethodNEWLINE def _on_response(message: Message,NEWLINE exc: Exception,NEWLINE logger: TaskLogger,NEWLINE return_value: ReturnValue,NEWLINE task: Task):NEWLINE reply = {'id': str(uuid4()), 'task': message['task'], 'reply_id': message['id']}NEWLINE if 'graph_id' in message:NEWLINE reply['graph_id'] = message['graph_id']NEWLINE if 'reply_to' in message:NEWLINE reply['reply_to'] = message['reply_to']NEWLINE if 'result_key' in message:NEWLINE if message.get('ignore_result', task.ignore_result):NEWLINE reply['result_key'] = NoneNEWLINE else:NEWLINE reply['result_key'] = message['result_key']NEWLINE if '_context' in message:NEWLINE reply['_context'] = message['_context']NEWLINE if exc is not None:NEWLINE reply['exc'] = excNEWLINE if isinstance(exc, task.throws) or isinstance(exc, Reject):NEWLINE logger.error("Task {'id': %r, 'task': %r} raised exception %s: %s",NEWLINE message['id'], message['task'], exc.__class__.__name__, exc)NEWLINE return replyNEWLINE else:NEWLINE traceback = extract_log_tb(exc)NEWLINE if traceback:NEWLINE reply['traceback'] = tracebackNEWLINE logger.error("Task {'id': %r, 'task': %r} raised exception %s: %s\n%s",NEWLINE message['id'], message['task'], exc.__class__.__name__, exc, traceback)NEWLINE return replyNEWLINE reply['value'] = return_valueNEWLINE return replyNEWLINENEWLINE @cached_propertyNEWLINE def _broker(self) -> Broker:NEWLINE def get(obj: Broker):NEWLINE return objNEWLINENEWLINE return self.inject([get], cache=False)NEWLINE import boto3NEWLINEimport sysNEWLINEfrom st2actions.runners.pythonrunner import ActionNEWLINENEWLINEclass GetStackBuildStatus(Action):NEWLINE def run(self, stack_name_or_id):NEWLINE region = self.config['region']NEWLINENEWLINE stack_states = ['CREATE_COMPLETE', 'CREATE_FAILED', 'ROLLBACK_COMPLETE']NEWLINENEWLINE client = boto3.client('cloudformation', region_name=region)NEWLINENEWLINE try:NEWLINE stack_status = client.describe_stacks(StackName=stack_name_or_id)['Stacks'][0]['StackStatus']NEWLINENEWLINE except Exception as err:NEWLINE sys.stderr.write('ERROR: %s\n' % str(err))NEWLINE raiseNEWLINENEWLINE if stack_status not in stack_states:NEWLINE sys.stderr.write('Current state: %s\n' % stack_status)NEWLINE sys.exit(2)NEWLINENEWLINE return TrueNEWLINE #!/usr/bin/env pythonNEWLINE# -*- coding: utf8 -*-NEWLINENEWLINE"""Initialize userNEWLINE"""NEWLINENEWLINEimport sysNEWLINEsys.path.insert(0, '../')NEWLINENEWLINEfrom app.models import UserNEWLINEfrom app.models import dbNEWLINENEWLINE_admin0 = {'name': 'uadmin', 'hash': '$6$rounds=656000$BGPNku.GTxUFp5/m$z2VoGUbOzZfjEq2TnQjyK4Ho47MYCEHEK5N/TjpgzNuLWOJHwoeIA3AUbbDSMEvQBdqtEv1Vez1OXAYtYc4r80'}NEWLINENEWLINEuser0 = User(nickname=_admin0['name'], password_hash=_admin0['hash'], NEWLINE email='admin@localhost', id=1)NEWLINENEWLINE# default admin accountNEWLINEdb.session.add(user0)NEWLINEdb.session.commit()NEWLINE from django.apps import AppConfigNEWLINENEWLINENEWLINEclass GiftConfig(AppConfig):NEWLINE name = 'gift'NEWLINE #NEWLINE# Copyright (c) 2021 Citrix Systems, Inc.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License")NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE#NEWLINENEWLINEfrom nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resourceNEWLINEfrom nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_responseNEWLINEfrom nssrc.com.citrix.netscaler.nitro.service.options import optionsNEWLINEfrom nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exceptionNEWLINENEWLINEfrom nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_utilNEWLINENEWLINEclass rdpclientprofile(base_resource) :NEWLINE """ Configuration for RDP clientprofile resource. """NEWLINE def __init__(self) :NEWLINE self._name = NoneNEWLINE self._rdpurloverride = NoneNEWLINE self._redirectclipboard = NoneNEWLINE self._redirectdrives = NoneNEWLINE self._redirectprinters = NoneNEWLINE self._redirectcomports = NoneNEWLINE self._redirectpnpdevices = NoneNEWLINE self._keyboardhook = NoneNEWLINE self._audiocapturemode = NoneNEWLINE self._videoplaybackmode = NoneNEWLINE self._multimonitorsupport = NoneNEWLINE self._rdpcookievalidity = NoneNEWLINE self._addusernameinrdpfile = NoneNEWLINE self._rdpfilename = NoneNEWLINE self._rdphost = NoneNEWLINE self._rdplistener = NoneNEWLINE self._rdpcustomparams = NoneNEWLINE self._psk = NoneNEWLINE self._randomizerdpfilename = NoneNEWLINE self._rdplinkattribute = NoneNEWLINE self._builtin = NoneNEWLINE self._feature = NoneNEWLINE self.___count = NoneNEWLINENEWLINE @propertyNEWLINE def name(self) :NEWLINE r"""The name of the rdp profile.
Minimum length = 1.NEWLINE """NEWLINE try :NEWLINE return self._nameNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @name.setterNEWLINE def name(self, name) :NEWLINE r"""The name of the rdp profile.
Minimum length = 1NEWLINE """NEWLINE try :NEWLINE self._name = nameNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def rdpurloverride(self) :NEWLINE r"""This setting determines whether the RDP parameters supplied in the vpn url override those specified in the RDP profile.
Default value: ENABLE
Possible values = ENABLE, DISABLE.NEWLINE """NEWLINE try :NEWLINE return self._rdpurloverrideNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @rdpurloverride.setterNEWLINE def rdpurloverride(self, rdpurloverride) :NEWLINE r"""This setting determines whether the RDP parameters supplied in the vpn url override those specified in the RDP profile.
Default value: ENABLE
Possible values = ENABLE, DISABLENEWLINE """NEWLINE try :NEWLINE self._rdpurloverride = rdpurloverrideNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def redirectclipboard(self) :NEWLINE r"""This setting corresponds to the Clipboard check box on the Local Resources tab under Options in RDC.
Default value: ENABLE
Possible values = ENABLE, DISABLE.NEWLINE """NEWLINE try :NEWLINE return self._redirectclipboardNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @redirectclipboard.setterNEWLINE def redirectclipboard(self, redirectclipboard) :NEWLINE r"""This setting corresponds to the Clipboard check box on the Local Resources tab under Options in RDC.
Default value: ENABLE
Possible values = ENABLE, DISABLENEWLINE """NEWLINE try :NEWLINE self._redirectclipboard = redirectclipboardNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def redirectdrives(self) :NEWLINE r"""This setting corresponds to the selections for Drives under More on the Local Resources tab under Options in RDC.
Default value: DISABLE
Possible values = ENABLE, DISABLE.NEWLINE """NEWLINE try :NEWLINE return self._redirectdrivesNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @redirectdrives.setterNEWLINE def redirectdrives(self, redirectdrives) :NEWLINE r"""This setting corresponds to the selections for Drives under More on the Local Resources tab under Options in RDC.
Default value: DISABLE
Possible values = ENABLE, DISABLENEWLINE """NEWLINE try :NEWLINE self._redirectdrives = redirectdrivesNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def redirectprinters(self) :NEWLINE r"""This setting corresponds to the selection in the Printers check box on the Local Resources tab under Options in RDC.
Default value: ENABLE
Possible values = ENABLE, DISABLE.NEWLINE """NEWLINE try :NEWLINE return self._redirectprintersNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @redirectprinters.setterNEWLINE def redirectprinters(self, redirectprinters) :NEWLINE r"""This setting corresponds to the selection in the Printers check box on the Local Resources tab under Options in RDC.
Default value: ENABLE
Possible values = ENABLE, DISABLENEWLINE """NEWLINE try :NEWLINE self._redirectprinters = redirectprintersNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def redirectcomports(self) :NEWLINE r"""This setting corresponds to the selections for comports under More on the Local Resources tab under Options in RDC.
Default value: DISABLE
Possible values = ENABLE, DISABLE.NEWLINE """NEWLINE try :NEWLINE return self._redirectcomportsNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @redirectcomports.setterNEWLINE def redirectcomports(self, redirectcomports) :NEWLINE r"""This setting corresponds to the selections for comports under More on the Local Resources tab under Options in RDC.
Default value: DISABLE
Possible values = ENABLE, DISABLENEWLINE """NEWLINE try :NEWLINE self._redirectcomports = redirectcomportsNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def redirectpnpdevices(self) :NEWLINE r"""This setting corresponds to the selections for pnpdevices under More on the Local Resources tab under Options in RDC.
Default value: DISABLE
Possible values = ENABLE, DISABLE.NEWLINE """NEWLINE try :NEWLINE return self._redirectpnpdevicesNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @redirectpnpdevices.setterNEWLINE def redirectpnpdevices(self, redirectpnpdevices) :NEWLINE r"""This setting corresponds to the selections for pnpdevices under More on the Local Resources tab under Options in RDC.
Default value: DISABLE
Possible values = ENABLE, DISABLENEWLINE """NEWLINE try :NEWLINE self._redirectpnpdevices = redirectpnpdevicesNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def keyboardhook(self) :NEWLINE r"""This setting corresponds to the selection in the Keyboard drop-down list on the Local Resources tab under Options in RDC.
Default value: InFullScreenMode
Possible values = OnLocal, OnRemote, InFullScreenMode.NEWLINE """NEWLINE try :NEWLINE return self._keyboardhookNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @keyboardhook.setterNEWLINE def keyboardhook(self, keyboardhook) :NEWLINE r"""This setting corresponds to the selection in the Keyboard drop-down list on the Local Resources tab under Options in RDC.
Default value: InFullScreenMode
Possible values = OnLocal, OnRemote, InFullScreenModeNEWLINE """NEWLINE try :NEWLINE self._keyboardhook = keyboardhookNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def audiocapturemode(self) :NEWLINE r"""This setting corresponds to the selections in the Remote audio area on the Local Resources tab under Options in RDC.
Default value: DISABLE
Possible values = ENABLE, DISABLE.NEWLINE """NEWLINE try :NEWLINE return self._audiocapturemodeNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @audiocapturemode.setterNEWLINE def audiocapturemode(self, audiocapturemode) :NEWLINE r"""This setting corresponds to the selections in the Remote audio area on the Local Resources tab under Options in RDC.
Default value: DISABLE
Possible values = ENABLE, DISABLENEWLINE """NEWLINE try :NEWLINE self._audiocapturemode = audiocapturemodeNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def videoplaybackmode(self) :NEWLINE r"""This setting determines if Remote Desktop Connection (RDC) will use RDP efficient multimedia streaming for video playback.
Default value: ENABLE
Possible values = ENABLE, DISABLE.NEWLINE """NEWLINE try :NEWLINE return self._videoplaybackmodeNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @videoplaybackmode.setterNEWLINE def videoplaybackmode(self, videoplaybackmode) :NEWLINE r"""This setting determines if Remote Desktop Connection (RDC) will use RDP efficient multimedia streaming for video playback.
Default value: ENABLE
Possible values = ENABLE, DISABLENEWLINE """NEWLINE try :NEWLINE self._videoplaybackmode = videoplaybackmodeNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def multimonitorsupport(self) :NEWLINE r"""Enable/Disable Multiple Monitor Support for Remote Desktop Connection (RDC).
Default value: ENABLE
Possible values = ENABLE, DISABLE.NEWLINE """NEWLINE try :NEWLINE return self._multimonitorsupportNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @multimonitorsupport.setterNEWLINE def multimonitorsupport(self, multimonitorsupport) :NEWLINE r"""Enable/Disable Multiple Monitor Support for Remote Desktop Connection (RDC).
Default value: ENABLE
Possible values = ENABLE, DISABLENEWLINE """NEWLINE try :NEWLINE self._multimonitorsupport = multimonitorsupportNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def rdpcookievalidity(self) :NEWLINE r"""RDP cookie validity period. RDP cookie validity time is applicable for new connection and also for any re-connection that might happen, mostly due to network disruption or during fail-over.
Default value: 60
Minimum length = 1
Maximum length = 86400.NEWLINE """NEWLINE try :NEWLINE return self._rdpcookievalidityNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @rdpcookievalidity.setterNEWLINE def rdpcookievalidity(self, rdpcookievalidity) :NEWLINE r"""RDP cookie validity period. RDP cookie validity time is applicable for new connection and also for any re-connection that might happen, mostly due to network disruption or during fail-over.
Default value: 60
Minimum length = 1
Maximum length = 86400NEWLINE """NEWLINE try :NEWLINE self._rdpcookievalidity = rdpcookievalidityNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def addusernameinrdpfile(self) :NEWLINE r"""Add username in rdp file.
Default value: NO
Possible values = YES, NO.NEWLINE """NEWLINE try :NEWLINE return self._addusernameinrdpfileNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @addusernameinrdpfile.setterNEWLINE def addusernameinrdpfile(self, addusernameinrdpfile) :NEWLINE r"""Add username in rdp file.
Default value: NO
Possible values = YES, NONEWLINE """NEWLINE try :NEWLINE self._addusernameinrdpfile = addusernameinrdpfileNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def rdpfilename(self) :NEWLINE r"""RDP file name to be sent to End User.
Minimum length = 1.NEWLINE """NEWLINE try :NEWLINE return self._rdpfilenameNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @rdpfilename.setterNEWLINE def rdpfilename(self, rdpfilename) :NEWLINE r"""RDP file name to be sent to End User.
Minimum length = 1NEWLINE """NEWLINE try :NEWLINE self._rdpfilename = rdpfilenameNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def rdphost(self) :NEWLINE r"""Fully-qualified domain name (FQDN) of the RDP Listener.
Maximum length = 252.NEWLINE """NEWLINE try :NEWLINE return self._rdphostNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @rdphost.setterNEWLINE def rdphost(self, rdphost) :NEWLINE r"""Fully-qualified domain name (FQDN) of the RDP Listener.
Maximum length = 252NEWLINE """NEWLINE try :NEWLINE self._rdphost = rdphostNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def rdplistener(self) :NEWLINE r"""IP address (or) Fully-qualified domain name(FQDN) of the RDP Listener with the port in the format IP:Port (or) FQDN:Port.
Maximum length = 255.NEWLINE """NEWLINE try :NEWLINE return self._rdplistenerNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @rdplistener.setterNEWLINE def rdplistener(self, rdplistener) :NEWLINE r"""IP address (or) Fully-qualified domain name(FQDN) of the RDP Listener with the port in the format IP:Port (or) FQDN:Port.
Maximum length = 255NEWLINE """NEWLINE try :NEWLINE self._rdplistener = rdplistenerNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def rdpcustomparams(self) :NEWLINE r"""Option for RDP custom parameters settings (if any). Custom params needs to be separated by '&'.
Default value: 0
Minimum length = 1.NEWLINE """NEWLINE try :NEWLINE return self._rdpcustomparamsNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @rdpcustomparams.setterNEWLINE def rdpcustomparams(self, rdpcustomparams) :NEWLINE r"""Option for RDP custom parameters settings (if any). Custom params needs to be separated by '&'.
Default value: 0
Minimum length = 1NEWLINE """NEWLINE try :NEWLINE self._rdpcustomparams = rdpcustomparamsNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def psk(self) :NEWLINE r"""Pre shared key value.
Default value: 0.NEWLINE """NEWLINE try :NEWLINE return self._pskNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @psk.setterNEWLINE def psk(self, psk) :NEWLINE r"""Pre shared key value.
Default value: 0NEWLINE """NEWLINE try :NEWLINE self._psk = pskNEWLINE except Exception as e:NEWLINE raise eNEWLINENEWLINE @propertyNEWLINE def randomizerdpfilename(self) :NEWLINE r"""Will generate unique filename everytime rdp file is downloaded by appending output of time() function in the format _