file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
api.ts
import { ProxyMarked } from 'comlink' import { InitData } from '../extensionHost' import { ExtDocumentsAPI } from './documents' import { ExtExtensionsAPI } from './extensions'
import { ExtWorkspaceAPI } from './workspace' import { ExtWindowsAPI } from './windows' import { FlatExtHostAPI } from '../../contract' export type ExtensionHostAPIFactory = (initData: InitData) => ExtensionHostAPI export interface ExtensionHostAPI extends ProxyMarked, FlatExtHostAPI { ping(): 'pong' documents: ExtDocumentsAPI extensions: ExtExtensionsAPI workspace: ExtWorkspaceAPI windows: ExtWindowsAPI }
main.go
/* Package main Copyright 2021 VMware, Inc. SPDX-License-Identifier: BSD-2-Clause */ package main import "github.com/sammcgeown/vra-cli/pkg/cmd" func
() { cmd.Execute() }
main
if-check-fail.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:Number is odd fn even(x: uint) -> bool { if x < 2u { return false; } else if x == 2u { return true; } else { return even(x - 2u); } } fn foo(x: uint) { if even(x) { info!(x); } else { fail!("Number is odd"); } } fn main()
{ foo(3u); }
react-select.browser.esm.js
import '@babel/runtime/helpers/esm/objectWithoutProperties'; import '@babel/runtime/helpers/esm/extends'; import '@babel/runtime/helpers/esm/toConsumableArray'; import '@babel/runtime/helpers/esm/objectSpread'; import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck'; import _createClass from '@babel/runtime/helpers/esm/createClass'; import _possibleConstructorReturn from '@babel/runtime/helpers/esm/possibleConstructorReturn'; import _getPrototypeOf from '@babel/runtime/helpers/esm/getPrototypeOf'; import _inherits from '@babel/runtime/helpers/esm/inherits'; import _assertThisInitialized from '@babel/runtime/helpers/esm/assertThisInitialized'; import _defineProperty from '@babel/runtime/helpers/esm/defineProperty'; import React, { Component } from 'react'; import memoizeOne from 'memoize-one'; import { CacheProvider } from '@emotion/core'; import 'react-dom'; import 'prop-types'; import '@babel/runtime/helpers/esm/typeof'; import './chunk-39d3fda8.browser.esm.js'; export { y as components } from './chunk-80640036.browser.esm.js'; import { S as Select } from './base/dist/react-select-cac0a5ae.browser.esm.js'; export { c as createFilter, a as defaultTheme, m as mergeStyles } from './base/dist/react-select-cac0a5ae.browser.esm.js'; import '@emotion/css'; import '@babel/runtime/helpers/esm/taggedTemplateLiteral'; import 'react-input-autosize'; import { m as manageState } from './chunk-b36baf1a.browser.esm.js'; import createCache from '@emotion/cache'; var NonceProvider = /*#__PURE__*/ function (_Component) { _inherits(NonceProvider, _Component); function
(props) { var _this; _classCallCheck(this, NonceProvider); _this = _possibleConstructorReturn(this, _getPrototypeOf(NonceProvider).call(this, props)); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "createEmotionCache", function (nonce) { return createCache({ nonce: nonce }); }); _this.createEmotionCache = memoizeOne(_this.createEmotionCache); return _this; } _createClass(NonceProvider, [{ key: "render", value: function render() { var emotionCache = this.createEmotionCache(this.props.nonce); return React.createElement(CacheProvider, { value: emotionCache }, this.props.children); } }]); return NonceProvider; }(Component); var index = manageState(Select); export default index; export { NonceProvider };
NonceProvider
right.py
import asyncio class Right(asyncio.Protocol): SEP = b'\n' def __init__(self, logger, loop, left): self.logger = logger self.loop = loop self.left = left self.buffer = bytes() self.transport = None self.w_q = asyncio.Queue() self.peername = (None, None) def connection_made(self, transport): self.transport = transport self.peername = self.transport.get_extra_info('peername') self.logger.info('[%s:%s] Right-side connection to %s:%s establised', *self.left.peername, *self.peername) self.q_consumer = asyncio.ensure_future(self.consume()) @asyncio.coroutine def consume(self): self.logger.debug('[%s:%s] Right-side transport write queue consumer started', *self.left.peername) while not self.transport.is_closing(): try: message = yield from self.w_q.get() self.logger.debug('[%s:%s] -> [%s:%s] %r', *self.left.peername, *self.peername, message) self.transport.write(message + self.SEP) except asyncio.CancelledError: self.logger.warning('[%s:%s] Right-side consume coroutine has been stopped', *self.left.peername) return except Exception as e: self.logger.error('[%s:%s] Right-side had an exception consume coroutine: %s: %s', *self.left.peername, e.__class__.__name__, e) def data_received(self, data): self.buffer += data messages = self.buffer.split(self.SEP) if data.endswith(self.SEP): self.buffer = bytes() else: incomplete = messages.pop() self.logger.warning('[%s:%s] Right-side received incomplete message: %r will be sent later', *self.left.peername, incomplete) self.buffer = incomplete for message in messages: if message: self.left.w_q.put_nowait(message) def eof_received(self): pass def connection_lost(self, exc):
self.logger.error('[%s:%s] Right.side connection lost', *self.left.peername) if hasattr(self, 'q_consumer'): self.q_consumer.cancel() # pylint: disable=no-member # Close the left proxy side as well self.left.transport.close()
builder.d.ts
/** * @module "ui/builder" */ /** */ import { View, Template, KeyedTemplate } from "../core/view";
//@private /** * @private */ export function _loadPage(moduleNamePath: string, fileName: string, moduleExports?: any): Page; //@endprivate export function createViewFromEntry(entry: NavigationEntry): View; export function load(fileName: string, exports?: any): View; export function load(options: LoadOptions): View; export function parse(value: string | Template, exports?: any): View; export function parseMultipleTemplates(value: string, exports?: any): Array<KeyedTemplate>; export interface LoadOptions { path: string; name: string; attributes?: any; exports?: any; page?: Page; }
import { Page } from "../page"; import { NavigationEntry } from "../frame";
test_flux_point.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np from numpy.testing import assert_allclose import astropy.units as u from astropy.table import Table from gammapy.catalog.fermi import SourceCatalog3FGL from gammapy.estimators import FluxPoints from gammapy.modeling.models import SpectralModel from gammapy.utils.scripts import make_path from gammapy.utils.testing import ( assert_quantity_allclose, mpl_plot_check, requires_data, requires_dependency, ) FLUX_POINTS_FILES = [ "diff_flux_points.ecsv", "diff_flux_points.fits", "flux_points.ecsv", "flux_points.fits", ] class LWTestModel(SpectralModel): @staticmethod def evaluate(x): return 1e4 * np.exp(-6 * x) def integral(self, xmin, xmax, **kwargs): return -1.0 / 6 * 1e4 * (np.exp(-6 * xmax) - np.exp(-6 * xmin)) def inverse(self, y): return -1.0 / 6 * np.log(y * 1e-4) class XSqrTestModel(SpectralModel): @staticmethod def evaluate(x): return x ** 2 def integral(self, xmin, xmax, **kwargs): return 1.0 / 3 * (xmax ** 3 - xmin ** 2) def inverse(self, y): return np.sqrt(y) class ExpTestModel(SpectralModel): @staticmethod def evaluate(x): return np.exp(x * u.Unit("1 / TeV")) def integral(self, xmin, xmax, **kwargs): return np.exp(xmax * u.Unit("1 / TeV")) - np.exp(xmin * u.Unit("1 / TeV")) def inverse(self, y): return np.log(y * u.TeV) * u.TeV def test_energy_ref_lafferty(): """ Tests Lafferty & Wyatt x-point method. Using input function g(x) = 10^4 exp(-6x) against check values from paper Lafferty & Wyatt. Nucl. Instr. and Meth. in Phys. Res. A 355 (1995) 541-547, p. 542 Table 1 """ # These are the results from the paper desired = np.array([0.048, 0.190, 0.428, 0.762]) model = LWTestModel() energy_min = np.array([0.0, 0.1, 0.3, 0.6]) energy_max = np.array([0.1, 0.3, 0.6, 1.0]) actual = FluxPoints._energy_ref_lafferty(model, energy_min, energy_max) assert_allclose(actual, desired, atol=1e-3) @pytest.mark.xfail def test_dnde_from_flux(): """Tests y-value normalization adjustment method. """ table = Table() table["e_min"] = np.array([10, 20, 30, 40]) table["e_max"] = np.array([20, 30, 40, 50]) table["flux"] = np.array([42, 52, 62, 72]) # 'True' integral flux in this test bin # Get values model = XSqrTestModel() table["e_ref"] = FluxPoints._energy_ref_lafferty(model, table["e_min"], table["e_max"]) dnde = FluxPoints.from_table(table, reference_model=model) # Set up test case comparison dnde_model = model(table["e_ref"]) # Test comparison result desired = model.integral(table["e_min"], table["e_max"]) # Test output result actual = table["flux"] * (dnde_model / dnde) # Compare assert_allclose(actual, desired, rtol=1e-6) @pytest.mark.xfail @pytest.mark.parametrize("method", ["table", "lafferty", "log_center"]) def test_compute_flux_points_dnde_exp(method): """ Tests against analytical result or result from a powerlaw. """ model = ExpTestModel() energy_min = [1.0, 10.0] * u.TeV energy_max = [10.0, 100.0] * u.TeV table = Table() table.meta["SED_TYPE"] = "flux" table["e_min"] = energy_min table["e_max"] = energy_max flux = model.integral(energy_min, energy_max) table["flux"] = flux if method == "log_center": energy_ref = np.sqrt(energy_min * energy_max) elif method == "table": energy_ref = [2.0, 20.0] * u.TeV elif method == "lafferty": energy_ref = FluxPoints._energy_ref_lafferty(model, energy_min, energy_max) table["e_ref"] = energy_ref result = FluxPoints.from_table(table, reference_model=model) # Test energy actual = result.energy_ref assert_quantity_allclose(actual, energy_ref, rtol=1e-8) # Test flux actual = result.dnde desired = model(energy_ref) assert_quantity_allclose(actual, desired, rtol=1e-8) @requires_data() def test_fermi_to_dnde():
src = catalog_4fgl["FGES J1553.8-5325"] fp = src.flux_points assert_allclose( fp.dnde.quantity[1, 0, 0], 4.567393e-10 * u.Unit("cm-2 s-1 MeV-1"), rtol=1e-5, ) @pytest.fixture(params=FLUX_POINTS_FILES, scope="session") def flux_points(request): path = "$GAMMAPY_DATA/tests/spectrum/flux_points/" + request.param return FluxPoints.read(path) @pytest.fixture(scope="session") def flux_points_likelihood(): path = "$GAMMAPY_DATA/tests/spectrum/flux_points/binlike.fits" return FluxPoints.read(path) @requires_data() class TestFluxPoints: def test_info(self, flux_points): info = str(flux_points) assert "geom" in info assert "axes" in info assert "ref. model" in info assert "quantities" in info def test_energy_ref(self, flux_points): actual = flux_points.energy_ref desired = np.sqrt(flux_points.energy_min * flux_points.energy_max) assert_quantity_allclose(actual, desired) def test_energy_min(self, flux_points): actual = flux_points.energy_min desired = 299530.97 * u.MeV assert_quantity_allclose(actual.sum(), desired) def test_energy_max(self, flux_points): actual = flux_points.energy_max desired = 399430.975 * u.MeV assert_quantity_allclose(actual.sum(), desired) def test_write_fits(self, tmp_path, flux_points): flux_points.write(tmp_path / "tmp.fits", sed_type=flux_points.sed_type_init) actual = FluxPoints.read(tmp_path / "tmp.fits") assert str(flux_points) == str(actual) def test_write_ecsv(self, tmp_path, flux_points): flux_points.write(tmp_path / "flux_points.ecsv", sed_type=flux_points.sed_type_init) actual = FluxPoints.read(tmp_path / "flux_points.ecsv") assert str(flux_points) == str(actual) def test_quantity_access(self, flux_points_likelihood): assert flux_points_likelihood.sqrt_ts assert flux_points_likelihood.ts assert flux_points_likelihood.stat assert_allclose(flux_points_likelihood.n_sigma_ul, 2) assert flux_points_likelihood.sed_type_init == "likelihood" @requires_dependency("matplotlib") def test_plot(self, flux_points): with mpl_plot_check(): flux_points.plot() @requires_dependency("matplotlib") def test_plot_likelihood(self, flux_points_likelihood): with mpl_plot_check(): flux_points_likelihood.plot_ts_profiles() @requires_dependency("matplotlib") def test_plot_likelihood_error(self, flux_points_likelihood): del flux_points_likelihood._data["stat_scan"] with pytest.raises(AttributeError): flux_points_likelihood.plot_ts_profiles() @requires_data() def test_compute_flux_points_dnde_fermi(): """ Test compute_flux_points_dnde on fermi source. """ fermi_3fgl = SourceCatalog3FGL() source = fermi_3fgl["3FGL J0835.3-4510"] flux_points = source.flux_points table = source.flux_points_table for column in ["e2dnde", "e2dnde_errn", "e2dnde_errp", "e2dnde_ul"]: actual = table[column].quantity desired = getattr(flux_points, column).quantity.squeeze() assert_quantity_allclose(actual[:-1], desired[:-1], rtol=0.05) @requires_data() @requires_dependency("matplotlib") def test_plot_fp_no_ul(): path = make_path("$GAMMAPY_DATA/tests/spectrum/flux_points/diff_flux_points.fits") table = Table.read(path) table.remove_column('dnde_ul') fp = FluxPoints.from_table(table, sed_type='dnde') with mpl_plot_check(): fp.plot()
from gammapy.catalog import SourceCatalog4FGL catalog_4fgl = SourceCatalog4FGL("$GAMMAPY_DATA/catalogs/fermi/gll_psc_v20.fit.gz")
deploy.js
const ghpages = require('gh-pages'); const { copyFileSync } = require('fs'); const { copySync } = require('fs-extra'); const { join } = require('path'); const { execSync } = require('child_process'); const basePath = join(process.cwd(), 'dist/app'); const branch = process.env.TRAVIS_BRANCH || execSync(`git branch | sed -n '/\* /s///p'`).toString().trim(); const isStableVersion = branch === 'v5'; // build demo execSync( `rm -rf dist/app && ng build --prod --deploy-url=/ngx-adminify/${branch}/ --base-href=/ngx-adminify/${isStableVersion ? '': branch} --output-path=dist/app/${branch}`, {stdio: 'inherit'} ); copyFileSync(join(basePath, branch, 'index.html'), join(basePath, branch, '404.html')); if (isStableVersion) { copySync(join(basePath, branch, 'assets'), join(basePath, 'assets')); copyFileSync(join(basePath, branch, 'favicon.ico'), join(basePath, 'favicon.ico')); ['404', 'index'].forEach(page => copyFileSync(join(basePath, branch, 'index.html'), join(basePath, `${page}.html`))); }
basePath, { only: branch, repo: 'https://' + process.env.GH_TOKEN + '@github.com/Hatles/ngx-adminify.git', } );
ghpages.publish(
credentials.rs
use crate::errors::{YdbError, YdbResult}; use crate::pub_traits::{Credentials, TokenInfo}; use serde::Deserialize; use std::fmt::Debug; use std::ops::Add; use std::process::Command; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; pub(crate) type CredentialsRef = Arc<Box<dyn Credentials>>; pub(crate) fn credencials_ref<T: 'static + Credentials>(cred: T) -> CredentialsRef { Arc::new(Box::new(cred)) } /// Credentials with static token without renewing /// /// Example: /// ```no_run /// # use ydb::{ClientBuilder, StaticToken, YdbResult}; /// # fn main()->YdbResult<()>{ /// let builder = ClientBuilder::from_str("grpc://localhost:2136?database=/local")?; /// let client = builder.with_credentials(StaticToken::from("asd")).client()?; /// # return Ok(()); /// # } /// ``` #[derive(Debug, Clone)] pub struct StaticToken { pub(crate) token: String, } impl StaticToken { /// Create static token from string /// /// Example: /// ``` /// # use ydb::StaticToken; /// StaticToken::from("asd"); /// ``` pub fn from<T: Into<String>>(token: T) -> Self { return StaticToken { token: token.into(), }; } } impl Credentials for StaticToken { fn create_token(&self) -> YdbResult<TokenInfo> { return Ok(TokenInfo::token(self.token.clone())); } fn debug_string(&self) -> String { let (begin, end) = if self.token.len() > 20 { ( &self.token.as_str()[0..3], &self.token.as_str()[(self.token.len() - 3)..self.token.len()], ) } else { ("xxx", "xxx") }; return format!("static token: {}...{}", begin, end); } } /// Get from stdout of command /// /// Example create token from yandex cloud command line utility: /// ```rust /// use ydb::CommandLineYcToken; /// /// let cred = CommandLineYcToken::from_cmd("yc iam create-token").unwrap(); /// ``` #[derive(Debug)] pub struct CommandLineYcToken { command: Arc<Mutex<Command>>, } impl CommandLineYcToken { /// Command line for create token /// /// The command will be called every time when token needed (token cache by default and will call rare). #[allow(dead_code)] pub fn from_cmd<T: Into<String>>(cmd: T) -> YdbResult<Self> { let cmd = cmd.into(); let cmd_parts: Vec<&str> = cmd.split_whitespace().collect(); if cmd_parts.len() < 1 { return Err(YdbError::Custom( format!("can't split get token command: '{}'", cmd).into(), )); } let mut command = Command::new(cmd_parts[0]); command.args(&cmd_parts.as_slice()[1..]); return Ok(CommandLineYcToken { command: Arc::new(Mutex::new(command)), }); } } impl Credentials for CommandLineYcToken { fn create_token(&self) -> YdbResult<TokenInfo> { let result = self.command.lock()?.output()?; if !result.status.success() { let err = String::from_utf8(result.stderr)?; return Err(YdbError::Custom(format!( "can't execute yc ({}): {}", result.status.code().unwrap(), err ))); } let token = String::from_utf8(result.stdout)?.trim().to_string(); return Ok(TokenInfo::token(token)); } fn debug_string(&self) -> String { let token_describe: String = match self.create_token() { Ok(token_info) => { let token = token_info.token; let desc: String = if token.len() > 20 { format!( "{}..{}", &token.as_str()[0..3], &token.as_str()[(token.len() - 3)..token.len()] ) } else { "short_token".to_string() }; desc } Err(err) => { format!("err: {}", err.to_string()) } }; return token_describe; } } /// Get token of service account of instance /// /// Yandex cloud support GCE token compatible. Use it. /// Example: /// ``` /// use ydb::YandexMetadata; /// let cred = YandexMetadata::new(); /// ``` pub type YandexMetadata = GCEMetadata; /// Get instance service account token from GCE instance /// /// Get token from google cloud engine instance metadata. /// By default from url: http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" /// /// Example: /// ``` /// use ydb::GCEMetadata; /// /// let cred = GCEMetadata::new(); /// ``` pub struct GCEMetadata { uri: String, } impl GCEMetadata { /// Create GCEMetadata with default url for receive token pub fn new() -> Self { return Self::from_url("http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token").unwrap(); } /// Create GCEMetadata with custom url (may need for debug or spec infrastructure with non standard metadata) /// /// Example: /// ``` /// # use ydb::YdbResult; /// # fn main()->YdbResult<()>{ /// use ydb::GCEMetadata; /// let cred = GCEMetadata::from_url("http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token")?; /// # return Ok(()); /// # } /// ``` pub fn from_url<T: Into<String>>(url: T) -> YdbResult<Self> { Ok(Self { uri: url.into().parse()?, }) } } impl Credentials for GCEMetadata { fn create_token(&self) -> YdbResult<TokenInfo> { http::Request::builder() .uri(self.uri.clone()) .header("Metadata-Flavor", "Google"); let mut request = reqwest::blocking::Request::new(reqwest::Method::GET, self.uri.parse().unwrap()); request .headers_mut() .insert("Metadata-Flavor", "Google".parse().unwrap()); #[derive(Deserialize)] struct
{ access_token: String, expires_in: u64, token_type: String, } let client = reqwest::blocking::Client::new(); let res: TokenResponse = client .request(reqwest::Method::GET, self.uri.as_str()) .header("Metadata-Flavor", "Google") .send()? .json()?; return Ok( TokenInfo::token(format!("{} {}", res.token_type, res.access_token)) .with_renew(Instant::now().add(Duration::from_secs(res.expires_in))), ); } fn debug_string(&self) -> String { return format!("GoogleComputeEngineMetadata from {}", self.uri.as_str()); } }
TokenResponse
t_mockiato.rs
// vim: tw=80 /// ``` /// use mockiato::*; /// /// #[mockable] /// pub trait A { /// fn foo(&self, key: i16) -> i32; /// } /// /// let mut mock = AMock::new(); /// mock.expect_foo(|k| k.any()).returns(42); /// assert_eq!(42, mock.foo(-1)); /// ``` fn doctest() {} pub trait ET { fn foo(&self); } struct NonStaticStruct<'a>(&'a i32); #[cfg(test)] mod t { use crate::{TestSuite, UniquelyOwned}; use mockiato::*; use super::{ET, NonStaticStruct}; struct Mockiato {} impl TestSuite for Mockiato { const NAME: &'static str = "mockiato"; fn associated_types() { // Traits are only allowed to contain methods unimplemented!() } fn checkpoint() { unimplemented!() } // Mockiato can't even do match_method or return_call_with_args fn closures() { unimplemented!() } fn reference_parameters() { #[mockable] pub trait A { fn foo(&self, x: &u32); } let mut mock = AMock::new(); mock.expect_foo(|x| x.partial_eq_owned(42)).returns(()); mock.foo(&42); } fn consume_parameters() { // Mockiato can't pass any arguments, by clone or by move, to a return // function, because it doesn't support return functions unimplemented!() } fn consume_self() { #[mockable] pub trait A { fn into_nothing(self); } let mut mock = AMock::new(); mock.expect_into_nothing(); mock.into_nothing(); } fn external_trait() { #[mockable(remote = "super::ET")] trait ET{ fn foo(&self); } let mut mock = ETMock::new(); mock.expect_foo().returns(()); mock.foo(); } fn foreign() { unimplemented!() } fn generic_method() { // Only lifetimes are supported as generic parameters on methods unimplemented!() } // Mockiato can sort-of implement this, but there's no way to match the // function's argument. fn generic_method_with_lifetime() { #[mockable] trait A { fn foo<'a>(&self, x: NonStaticStruct<'a>); } let mut mock = AMock::new(); mock.expect_foo(|t| t.any()).returns(()); let x_inner = -1; let x = NonStaticStruct(&x_inner); mock.foo(x); } fn generic_return() { #[mockable] pub trait A<T> { fn foo(&self) -> T; } let mut mock = AMock::<u32>::new(); mock.expect_foo().returns(42); assert_eq!(42u32, mock.foo()); } fn generic_struct() { // Only traits can be made mockable unimplemented!() } fn generic_trait() { #[mockable] pub trait A<T> { fn foo(&self, t: T) -> u32; } let mut mock: AMock<i16> = AMock::new(); mock.expect_foo(|t| t.any()).returns(42); assert_eq!(42, mock.foo(-1)); } fn impl_trait() { // Only traits can be made mockable , and traits may not // `use -> impl Trait` syntax unimplemented!() } fn inherited_trait() { // According to the README, trait bounds are not supported unimplemented!() } fn match_method() { unimplemented!() } fn mock_struct() { // Only traits can be made mockable unimplemented!() } fn mock_trait() { #[mockable] pub trait A { fn foo(&self, key: i16); } let _mock = AMock::new(); } fn multi_trait() { // Trait bounds are not supported, and custom derive is the only way to // mock a trait, so there's no way for a mock to implement multiple // traits. unimplemented!() } fn return_call_with_args() { unimplemented!() } fn return_reference() { #[mockable] pub trait A { fn foo(&self) -> &u32; } let x = 5u32; let mut mock = AMock::new(); mock.expect_foo() .returns(&x); assert_eq!(5, *mock.foo()); } fn return_mutable_reference() { // Mockiato can sort-of do this, but it's a bit crippled by the fact // that mutable references aren't Clone, so you need to use // returns_once. That's a pretty big limitation, because the code under // test can't call the method more than once. unimplemented!() //#[mockable] //pub trait A { //fn foo(&mut self) -> &mut u32; //} //let mut x = 5u32; //let mut mock = AMock::new(); //mock.expect_foo() //.returns_once(&mut x); //let x = mock.foo(); //assert_eq!(5, *x); //*x = 6; } fn return_owned() { #[mockable] pub trait A { fn foo(&self) -> UniquelyOwned; } let mut mock = AMock::new(); let result = UniquelyOwned(42); mock.expect_foo() .returns_once(result); assert_eq!(mock.foo(), UniquelyOwned(42)); } fn return_parameters() { unimplemented!() } fn send() { #[mockable] pub trait A {} let mock = AMock::new(); let _ = Box::new(mock) as Box<dyn A + Send>; } fn static_method() { // The first parameter of a method must be self, so that the trait is // object-safe unimplemented!() } fn times_range()
fn derive() { #[mockable] pub trait A { fn foo(&self, key: i16); } let _mock = AMock::new(); } fn fallback() { unimplemented!() } fn match_combo() { unimplemented!() } fn match_constant() { #[mockable] pub trait A { fn foo(&self, key: i16); } let mut mock = AMock::new(); mock.expect_foo(|key| key.partial_eq(5)); mock.foo(5); } fn match_operator() { unimplemented!() } fn match_pattern() { unimplemented!() } fn match_range() { unimplemented!() } fn match_wildcard() { #[mockable] pub trait A { fn foo(&self, key: i16); } let mut mock = AMock::new(); mock.expect_foo(|key| key.any()); mock.foo(2); } fn modules() { // Only traits can be mocked unimplemented!() } fn return_constant() { #[mockable] pub trait A { fn foo(&self) -> i16; } let mut mock = AMock::new(); mock.expect_foo().returns(2i16); assert_eq!(mock.foo(), 2); } // Mockiato implemented this feature only for one type: () fn return_default() { unimplemented!() } fn return_panic() { #[mockable] pub trait A { fn foo(&self); } let mut mock = AMock::new(); mock.expect_foo().panics_with_message("Panic"); mock.foo(); } // This is the default behavior fn times_once() { #[mockable] pub trait A { fn foo(&self); } let mut mock = AMock::new(); mock.expect_foo().times(1); mock.foo(); } fn times_any() { #[mockable] pub trait A { fn foo(&self); } let mut mock = AMock::new(); mock.expect_foo().times(..); mock.foo(); mock.foo(); } fn times_n() { #[mockable] pub trait A { fn foo(&self); } let mut mock = AMock::new(); mock.expect_foo().times(2); mock.foo(); mock.foo(); } fn times_never() { #[mockable] pub trait A { fn foo(&self); } let mut mock = AMock::new(); mock.expect_foo().times(0); } fn many_args() { #[mockable] pub trait A { fn foo(&self, a: i8, b: i8, c: i8, d: i8, e: i8, f: i8, g: i8, h: i8, i: i8, j: i8, k: i8, l: i8, m: i8, n: i8, o: i8, p: i8); } let mut mock = AMock::new(); mock.expect_foo(|x| x.any(), |x| x.any(), |x| x.any(), |x| x.any(), |x| x.any(), |x| x.any(), |x| x.any(), |x| x.any(), |x| x.any(), |x| x.any(), |x| x.any(), |x| x.any(), |x| x.any(), |x| x.any(), |x| x.any(), |x| x.any()); mock.foo(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); print!("≥ 16 "); } fn sequence() { #[mockable] pub trait A { fn foo(&self, x: i32); } let mut mock = AMock::new(); mock.expect_foo(|x| x.partial_eq(42)).returns(()); mock.expect_foo(|x| x.partial_eq(5)).returns(()); mock.expect_foo_calls_in_order(); mock.foo(42); mock.foo(5); print!("single method "); } fn version() { let ver = crate::built_info::DEPENDENCIES.iter() .find(|(name, _)| *name == "mockiato") .unwrap() .1; print!("{} ", ver); } fn where_clause() { // I think where clauses work but only for generic traits, not generic // methods. unimplemented!() } } test!{Mockiato} }
{ #[mockable] pub trait A { fn foo(&self); } let mut mock = AMock::new(); mock.expect_foo().times(2..4).returns(()); mock.foo(); mock.foo(); }
Desafio071.py
''' Exercício Python 071: Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. ''' print('=' * 30) print('{:^30}'.format('BANCO CEV')) print('=' * 30) saque = int(input('Que valor você quer sacar? R$ ')) total = saque ced = 50 totalCed = 0 while True:
totalCed += 1 else: if totalCed > 0: print('Total de {} cédulas de R$ {}'.format(totalCed, ced)) if ced == 50: ced = 20 elif ced == 20: ced = 10 elif ced == 10: ced = 1 totalCed = 0 if total == 0: break
if total >= ced: total -= ced
RedisConfig.d.ts
export default class RedisConfig { host: string; port: number;
password: string; constructor(host: string, port: number, db?: number, password?: string); setHost(host: string): RedisConfig; setPort(port: number): RedisConfig; setDb(id: number): RedisConfig; setPassword(password: string): RedisConfig; }
db: number;
softmax_policy.py
import torch from torch import nn from torch.distributions import Categorical class SoftmaxCategoricalHead(nn.Module): def forward(self, logits): return torch.distributions.Categorical(logits=logits) # class MultiSoftmaxCategoricalHead(nn.Module): # def forward(self, logits): # return Independent(Categorical(logits=logits), reinterpreted_batch_ndims=1)
self.dims = dims logits = torch.split(logits, tuple(dims), dim=1) self.dists = [Categorical(logits=logits_dim) for logits_dim in logits] def log_prob(self, actions): actions = torch.unbind(actions, dim=1) logprobs = torch.stack([ dist.log_prob(action) for dist, action in zip(self.dists, actions) ], dim=1) return logprobs.sum(dim=1) def entropy(self): return torch.stack([dist.entropy() for dist in self.dists], dim=1).sum(dim=1) def sample(self): return torch.stack([dist.sample() for dist in self.dists], dim=1) def mode(self): return torch.stack([ torch.argmax(dist.probs, dim=1) for dist in self.dists ], dim=1) class MultiSoftmaxCategoricalHead(nn.Module): def __init__(self, dims=None): self.dims = dims super().__init__() def forward(self, logits): return MultiCategorical(dims=self.dims, logits=logits)
class MultiCategorical(): def __init__(self, dims=None, logits=None):
sync_licenses_request_builder.go
package synclicenses import ( i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f "github.com/microsoft/kiota-abstractions-go"
// SyncLicensesRequestBuilder provides operations to call the syncLicenses method. type SyncLicensesRequestBuilder struct { // Path parameters for the request pathParameters map[string]string // The request adapter to use to execute the requests. requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter // Url template to use to build the URL for the current request builder urlTemplate string } // SyncLicensesRequestBuilderPostRequestConfiguration configuration for the request such as headers, query parameters, and middleware options. type SyncLicensesRequestBuilderPostRequestConfiguration struct { // Request headers Headers map[string]string // Request options Options []i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestOption } // NewSyncLicensesRequestBuilderInternal instantiates a new SyncLicensesRequestBuilder and sets the default values. func NewSyncLicensesRequestBuilderInternal(pathParameters map[string]string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter)(*SyncLicensesRequestBuilder) { m := &SyncLicensesRequestBuilder{ } m.urlTemplate = "{+baseurl}/deviceAppManagement/vppTokens/{vppToken%2Did}/microsoft.graph.syncLicenses"; urlTplParams := make(map[string]string) for idx, item := range pathParameters { urlTplParams[idx] = item } m.pathParameters = urlTplParams; m.requestAdapter = requestAdapter; return m } // NewSyncLicensesRequestBuilder instantiates a new SyncLicensesRequestBuilder and sets the default values. func NewSyncLicensesRequestBuilder(rawUrl string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter)(*SyncLicensesRequestBuilder) { urlParams := make(map[string]string) urlParams["request-raw-url"] = rawUrl return NewSyncLicensesRequestBuilderInternal(urlParams, requestAdapter) } // CreatePostRequestInformation syncs licenses associated with a specific appleVolumePurchaseProgramToken func (m *SyncLicensesRequestBuilder) CreatePostRequestInformation()(*i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestInformation, error) { return m.CreatePostRequestInformationWithRequestConfiguration(nil); } // CreatePostRequestInformationWithRequestConfiguration syncs licenses associated with a specific appleVolumePurchaseProgramToken func (m *SyncLicensesRequestBuilder) CreatePostRequestInformationWithRequestConfiguration(requestConfiguration *SyncLicensesRequestBuilderPostRequestConfiguration)(*i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestInformation, error) { requestInfo := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.NewRequestInformation() requestInfo.UrlTemplate = m.urlTemplate requestInfo.PathParameters = m.pathParameters requestInfo.Method = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.POST if requestConfiguration != nil { requestInfo.AddRequestHeaders(requestConfiguration.Headers) requestInfo.AddRequestOptions(requestConfiguration.Options) } return requestInfo, nil } // Post syncs licenses associated with a specific appleVolumePurchaseProgramToken func (m *SyncLicensesRequestBuilder) Post()(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.VppTokenable, error) { return m.PostWithRequestConfigurationAndResponseHandler(nil, nil); } // PostWithRequestConfigurationAndResponseHandler syncs licenses associated with a specific appleVolumePurchaseProgramToken func (m *SyncLicensesRequestBuilder) PostWithRequestConfigurationAndResponseHandler(requestConfiguration *SyncLicensesRequestBuilderPostRequestConfiguration, responseHandler i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ResponseHandler)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.VppTokenable, error) { requestInfo, err := m.CreatePostRequestInformationWithRequestConfiguration(requestConfiguration); if err != nil { return nil, err } res, err := m.requestAdapter.SendAsync(requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateVppTokenFromDiscriminatorValue, responseHandler, nil) if err != nil { return nil, err } return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.VppTokenable), nil }
iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242 "github.com/microsoftgraph/msgraph-sdk-go/models" )
many_requests_.py
import logging from json import JSONDecodeError from typing import List, Optional, Dict, Union import asks import trio from asks.errors import BadHttpResponse from asks.response_objects import Response from h11 import RemoteProtocolError from .easy_async import EasyAsync, delayed, zip_kw from .common import BadResponse, N_WORKERS_DEFAULT, N_CONNECTIONS_DEFAULT, is_collection class ManyRequests: def __init__( self, n_workers=N_WORKERS_DEFAULT, n_connections=N_CONNECTIONS_DEFAULT, retries=10, retry_sleep=3, ok_codes=(200,), ok_response_func=None, json=False, ):
def __call__( self, method: Union[str, List[str]], url: Union[str, List[str]], params=None, data=None, json=None, headers=None, cookies=None, auth=None, ) -> List[Union[Response, BadResponse]]: """ Process asynchronously many requests, handling bad responses. Return the responses in the same order. If no ok response was obtained after retires a `BadResponse` will be included in the corresponding position of the output. A `BadResponse` will contain the last response and error reason. Arguments mimic `asks.request`_, which in turn mimics `requests.request`_. Each argument could be a single item or a list of items. When they are a single item, that attribute is duplicated for every request. Args: method: HTTP method type `GET`, `OPTIONS`, `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`. url: URL of the Request params: Dictionary, list of tuples or bytes to send in the query string of the Request data: Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request json: A JSON serializable Python object to send in the body of the Request headers: Dictionary of HTTP Headers to send with the Request cookies: Dict or CookieJar object to send with the Request auth: Auth tuple to enable Basic/Digest/Custom HTTP Auth Returns: responses: A list of responses in the same order of the requests. Will include a `BadResponse` in the position of a request where no good response was obtained. .. _asks.request: https://asks.readthedocs.io/en/latest/overview-of-funcs-and-args.html .. _requests.request: https://2.python-requests.org/en/master/api/#requests.request """ length = None for e in (method, url, params, data, json, headers, cookies, auth): if not is_collection(e): continue try: l = len(e) if length is None or l < length: length = l except TypeError: pass self.session = asks.Session(connections=self.n_connections) responses = EasyAsync(n_workers=self.n_workers)( tasks=( delayed(self._runner)(request_kwargs=kwargs) for kwargs in zip_kw( method=method, url=url, params=params, data=data, json=json, headers=headers, cookies=cookies, auth=auth, ) ), length=length, ) return responses async def _runner(self, request_kwargs): """Task which handles completing a HTTP request and errors that arise""" last_error = None for attempt_i in range(0, self.retries+1): try: try: response = await self.session.request(**request_kwargs) except RemoteProtocolError as e: raise BadResponse('RemoteProtocolError', reason='RemoteProtocolError', attempt_num=attempt_i) except BadHttpResponse as e: raise BadResponse('BadHttpResponse', reason='BadHttpResponse', attempt_num=attempt_i) if self.ok_codes != "any" and response.status_code not in self.ok_codes: raise BadResponse(f"Bad response status code: {response.status_code}. Should be in {self.ok_codes}", response=response, reason='bad_status_code', attempt_num=attempt_i) if self.ok_response_func is not None and not self.ok_response_func(response): raise BadResponse('Not OK response determined by `ok_response_func`', response=response, reason='ok_response_func', attempt_num=attempt_i) if self.json: try: response = response.json() except JSONDecodeError as e: raise BadResponse('Cannot decode JSON', response=response, reason='JSONDecodeError', attempt_num=attempt_i) logging.debug(f"OK Response {request_kwargs}") return response except BadResponse as e: try: code, text = response.status_code, response.text except NameError: code, text = None, None logging.info( f"BAD Response {request_kwargs}: Attempt {attempt_i}. Error {type(e).__name__}. Code: {code}. Body: {text}" ) last_error = e await trio.sleep(self.retry_sleep) logging.warning( f"FAILED Request {request_kwargs}: Permanently failed. Last error: {last_error.description}" ) return last_error
""" Dead easy interface for executing many HTTP requests asynchronously. Args: n_workers: Max number of workers to use. Too many workers will use a lot of memory and increase startup time, too few can lead to slower execution. n_connections: Max number of open connections to have open at once. The number of connections is also limited by the OS. For example, by default MacOS has a limit of 256 and Ubuntu has ~66k. These limits can be changed with OS configuration. retries: Number of retries to attempt if a request fails retry_sleep: How long to wait in seconds before retrying a request ok_codes: A sequence of HTTP status codes to accept as ok. If `any`, all responses will be assumed to be ok ok_response_func: A function to apply to the response to determine if ok. Should return True/False. json: Parse response body as json and return instead of full Responce object Examples: Execute 10 GET requests to https://example.org >>> responses = ManyRequests(n_workers=5, n_connections=5)( >>> method='GET', url=[f'https://example.org' for i in range(10)]) """ self.n_workers = n_workers self.n_connections = n_connections self.session = None self.retries = retries self.retry_sleep = retry_sleep self.ok_codes = ok_codes self.ok_response_func = ok_response_func self.json = json self.requests = None self.responses = None
index.js
import useScreenSize from './use-screen-size' import useStyles from './use-styles' export { useScreenSize, useStyles,
}
main.go
package main import ( "github.com/casbin/casbin/v2" "log" ) func
() { e, err := casbin.NewEnforcer("./basic_model.conf", "./basic_policy.csv") if err != nil { log.Fatalf("casbin.NewEnforcer error:%v", err) } sub := "alice" // the user that wants to access a resource. obj := "data1" // the resource that is going to be accessed. act := "read" // the operation that the user performs on the resource. res, err := e.Enforce(sub, obj, act) if err != nil { log.Fatalf("e.Enforce error:%v", err) } if res { log.Println("permit alice to read data1") } else { log.Println("deny the request, show an error") } }
main
test_response_whois_nic_net_ng_status_registered.py
# This file is autogenerated. Do not edit it manually. # If you want change the content of this file, edit # # spec/fixtures/responses/whois.nic.net.ng/status_registered # # and regenerate the tests with the following script # # $ scripts/generate_tests.py # from nose.tools import * from dateutil.parser import parse as time_parse import yawhois class TestWhoisNicNetNgStatusRegistered(object): def setUp(self): fixture_path = "spec/fixtures/responses/whois.nic.net.ng/status_registered.txt" host = "whois.nic.net.ng" part = yawhois.record.Part(open(fixture_path, "r").read(), host) self.record = yawhois.record.Record(None, [part]) def test_status(self): eq_(self.record.status, 'registered') def test_available(self): eq_(self.record.available, False) def test_domain(self): eq_(self.record.domain, "nic.net.ng") def test_nameservers(self): eq_(self.record.nameservers.__class__.__name__, 'list') eq_(len(self.record.nameservers), 4) eq_(self.record.nameservers[0].__class__.__name__, 'Nameserver') eq_(self.record.nameservers[0].name, "rns1.nic.net.ng") eq_(self.record.nameservers[1].__class__.__name__, 'Nameserver') eq_(self.record.nameservers[1].name, "rns2.nic.net.ng") eq_(self.record.nameservers[2].__class__.__name__, 'Nameserver') eq_(self.record.nameservers[2].name, "rns3.nic.net.ng") eq_(self.record.nameservers[3].__class__.__name__, 'Nameserver') eq_(self.record.nameservers[3].name, "rns4.nic.net.ng") def test_registered(self): eq_(self.record.registered, True) def test_created_on(self): eq_(self.record.created_on.__class__.__name__, 'datetime') eq_(self.record.created_on, time_parse('2009-05-13 14:27:27 UTC')) def test_registrar(self):
def test_updated_on(self): eq_(self.record.updated_on.__class__.__name__, 'datetime') eq_(self.record.updated_on, time_parse('2012-08-24 13:46:14 UTC')) def test_domain_id(self): eq_(self.record.domain_id, "6808-NIRA") def test_expires_on(self): eq_(self.record.expires_on.__class__.__name__, 'datetime') eq_(self.record.expires_on, time_parse('2020-07-30 23:00:00 UTC'))
eq_(self.record.registrar.__class__.__name__, 'Registrar') eq_(self.record.registrar.id, None) eq_(self.record.registrar.name, "nira") eq_(self.record.registrar.organization, None) eq_(self.record.registrar.url, None)
jobs-stats.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { JobsStatsComponent } from './jobs-stats.component'; describe('JobsStatsComponent', () => { let component: JobsStatsComponent; let fixture: ComponentFixture<JobsStatsComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ JobsStatsComponent ] }) .compileComponents(); }));
beforeEach(() => { fixture = TestBed.createComponent(JobsStatsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
backbones_factory.py
import copy import efficientnet.model as eff import keras_applications as ka from classification_models.models_factory import ModelsFactory from . import inception_resnet_v2 as irv2 from . import inception_v3 as iv3 from . import vgg19 class
(ModelsFactory): _default_feature_layers = { # List of layers to take features from backbone in the following order: # (x16, x8, x4, x2, x1) - `x4` mean that features has 4 times less spatial # resolution (Height x Width) than input image. # VGG 'vgg16': ('block5_conv3', 'block4_conv3', 'block3_conv3', 'block2_conv2', 'block1_conv2'), 'vgg19': ('block5_conv4', 'block4_conv4', 'block3_conv4', 'block2_conv2', 'block1_conv2'), 'vgg19_drop': ('block5_conv4', 'block4_conv4', 'block3_conv4', 'block2_conv2', 'block1_conv2'), # ResNets 'resnet18': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0'), 'resnet34': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0'), 'resnet50': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0'), 'resnet101': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0'), 'resnet152': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0'), # ResNeXt 'resnext50': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0'), 'resnext101': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0'), # Inception 'inceptionv3': (228, 86, 16, 9), 'inceptionresnetv2': (594, 260, 16, 9), # DenseNet 'densenet121': (311, 139, 51, 4), 'densenet169': (367, 139, 51, 4), 'densenet201': (479, 139, 51, 4), # SE models 'seresnet18': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0'), 'seresnet34': ('stage4_unit1_relu1', 'stage3_unit1_relu1', 'stage2_unit1_relu1', 'relu0'), 'seresnet50': (246, 136, 62, 4), 'seresnet101': (552, 136, 62, 4), 'seresnet152': (858, 208, 62, 4), 'seresnext50': (1078, 584, 254, 4), 'seresnext101': (2472, 584, 254, 4), 'senet154': (6884, 1625, 454, 12), # Mobile Nets 'mobilenet': ('conv_pw_11_relu', 'conv_pw_5_relu', 'conv_pw_3_relu', 'conv_pw_1_relu'), 'mobilenetv2': ('block_13_expand_relu', 'block_6_expand_relu', 'block_3_expand_relu', 'block_1_expand_relu'), # EfficientNets 'efficientnetb0': ('block6a_expand_activation', 'block4a_expand_activation', 'block3a_expand_activation', 'block2a_expand_activation'), 'efficientnetb1': ('block6a_expand_activation', 'block4a_expand_activation', 'block3a_expand_activation', 'block2a_expand_activation'), 'efficientnetb2': ('block6a_expand_activation', 'block4a_expand_activation', 'block3a_expand_activation', 'block2a_expand_activation'), 'efficientnetb3': ('block6a_expand_activation', 'block4a_expand_activation', 'block3a_expand_activation', 'block2a_expand_activation'), 'efficientnetb4': ('block6a_expand_activation', 'block4a_expand_activation', 'block3a_expand_activation', 'block2a_expand_activation'), 'efficientnetb5': ('block6a_expand_activation', 'block4a_expand_activation', 'block3a_expand_activation', 'block2a_expand_activation'), 'efficientnetb6': ('block6a_expand_activation', 'block4a_expand_activation', 'block3a_expand_activation', 'block2a_expand_activation'), 'efficientnetb7': ('block6a_expand_activation', 'block4a_expand_activation', 'block3a_expand_activation', 'block2a_expand_activation'), } _models_update = { 'inceptionresnetv2': [irv2.InceptionResNetV2, irv2.preprocess_input], 'inceptionv3': [iv3.InceptionV3, iv3.preprocess_input], 'efficientnetb0': [eff.EfficientNetB0, eff.preprocess_input], 'efficientnetb1': [eff.EfficientNetB1, eff.preprocess_input], 'efficientnetb2': [eff.EfficientNetB2, eff.preprocess_input], 'efficientnetb3': [eff.EfficientNetB3, eff.preprocess_input], 'efficientnetb4': [eff.EfficientNetB4, eff.preprocess_input], 'efficientnetb5': [eff.EfficientNetB5, eff.preprocess_input], 'efficientnetb6': [eff.EfficientNetB6, eff.preprocess_input], 'efficientnetb7': [eff.EfficientNetB7, eff.preprocess_input], 'vgg19_drop': [vgg19.VGG19, ka.vgg19.preprocess_input], } # currently not supported _models_delete = ['resnet50v2', 'resnet101v2', 'resnet152v2', 'nasnetlarge', 'nasnetmobile', 'xception'] @property def models(self): all_models = copy.copy(self._models) all_models.update(self._models_update) for k in self._models_delete: del all_models[k] return all_models def get_backbone(self, name, *args, **kwargs): model_fn, _ = self.get(name) model = model_fn(*args, **kwargs) return model def get_feature_layers(self, name, n=5): return self._default_feature_layers[name][:n] def get_preprocessing(self, name): return self.get(name)[1] Backbones = BackbonesFactory()
BackbonesFactory
endpoint_queries.go
package service import ( "context" "github.com/fleetdm/fleet/v4/server/fleet" "github.com/go-kit/kit/endpoint" ) //////////////////////////////////////////////////////////////////////////////// // Get Query //////////////////////////////////////////////////////////////////////////////// type getQueryRequest struct { ID uint } type getQueryResponse struct { Query *fleet.Query `json:"query,omitempty"` Err error `json:"error,omitempty"` } func (r getQueryResponse) error() error { return r.Err } func makeGetQueryEndpoint(svc fleet.Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(getQueryRequest) query, err := svc.GetQuery(ctx, req.ID) if err != nil { return getQueryResponse{Err: err}, nil } return getQueryResponse{query, nil}, nil } } //////////////////////////////////////////////////////////////////////////////// // List Queries //////////////////////////////////////////////////////////////////////////////// type listQueriesRequest struct { ListOptions fleet.ListOptions } type listQueriesResponse struct { Queries []fleet.Query `json:"queries"` Err error `json:"error,omitempty"` } func (r listQueriesResponse) error() error { return r.Err } func makeListQueriesEndpoint(svc fleet.Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(listQueriesRequest) queries, err := svc.ListQueries(ctx, req.ListOptions) if err != nil { return listQueriesResponse{Err: err}, nil } resp := listQueriesResponse{Queries: []fleet.Query{}} for _, query := range queries { resp.Queries = append(resp.Queries, *query) } return resp, nil } } //////////////////////////////////////////////////////////////////////////////// // Create Query //////////////////////////////////////////////////////////////////////////////// type createQueryRequest struct { payload fleet.QueryPayload } type createQueryResponse struct { Query *fleet.Query `json:"query,omitempty"` Err error `json:"error,omitempty"` } func (r createQueryResponse) error() error { return r.Err } func makeCreateQueryEndpoint(svc fleet.Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(createQueryRequest) query, err := svc.NewQuery(ctx, req.payload) if err != nil { return createQueryResponse{Err: err}, nil } return createQueryResponse{query, nil}, nil } } //////////////////////////////////////////////////////////////////////////////// // Modify Query //////////////////////////////////////////////////////////////////////////////// type modifyQueryRequest struct { ID uint payload fleet.QueryPayload } type modifyQueryResponse struct { Query *fleet.Query `json:"query,omitempty"` Err error `json:"error,omitempty"` } func (r modifyQueryResponse) error() error { return r.Err } func makeModifyQueryEndpoint(svc fleet.Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(modifyQueryRequest) query, err := svc.ModifyQuery(ctx, req.ID, req.payload) if err != nil { return modifyQueryResponse{Err: err}, nil } return modifyQueryResponse{query, nil}, nil } } //////////////////////////////////////////////////////////////////////////////// // Delete Query //////////////////////////////////////////////////////////////////////////////// type deleteQueryRequest struct { Name string } type deleteQueryResponse struct { Err error `json:"error,omitempty"` } func (r deleteQueryResponse) error() error { return r.Err } func makeDeleteQueryEndpoint(svc fleet.Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(deleteQueryRequest) err := svc.DeleteQuery(ctx, req.Name) if err != nil { return deleteQueryResponse{Err: err}, nil } return deleteQueryResponse{}, nil } } //////////////////////////////////////////////////////////////////////////////// // Delete Query By ID //////////////////////////////////////////////////////////////////////////////// type deleteQueryByIDRequest struct { ID uint } type deleteQueryByIDResponse struct { Err error `json:"error,omitempty"` } func (r deleteQueryByIDResponse) error() error { return r.Err } func makeDeleteQueryByIDEndpoint(svc fleet.Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(deleteQueryByIDRequest) err := svc.DeleteQueryByID(ctx, req.ID) if err != nil { return deleteQueryByIDResponse{Err: err}, nil } return deleteQueryByIDResponse{}, nil } } //////////////////////////////////////////////////////////////////////////////// // Delete Queries //////////////////////////////////////////////////////////////////////////////// type deleteQueriesRequest struct { IDs []uint `json:"ids"` } type deleteQueriesResponse struct { Deleted uint `json:"deleted"` Err error `json:"error,omitempty"` } func (r deleteQueriesResponse) error() error { return r.Err } func makeDeleteQueriesEndpoint(svc fleet.Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(deleteQueriesRequest) deleted, err := svc.DeleteQueries(ctx, req.IDs) if err != nil { return deleteQueriesResponse{Err: err}, nil } return deleteQueriesResponse{Deleted: deleted}, nil } } //////////////////////////////////////////////////////////////////////////////// // Apply Query Spec //////////////////////////////////////////////////////////////////////////////// type applyQuerySpecsRequest struct { Specs []*fleet.QuerySpec `json:"specs"` } type applyQuerySpecsResponse struct { Err error `json:"error,omitempty"` } func (r applyQuerySpecsResponse) error() error { return r.Err } func makeApplyQuerySpecsEndpoint(svc fleet.Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(applyQuerySpecsRequest) err := svc.ApplyQuerySpecs(ctx, req.Specs) if err != nil { return applyQuerySpecsResponse{Err: err}, nil } return applyQuerySpecsResponse{}, nil } } //////////////////////////////////////////////////////////////////////////////// // Get Query Spec ////////////////////////////////////////////////////////////////////////////////
} func (r getQuerySpecsResponse) error() error { return r.Err } func makeGetQuerySpecsEndpoint(svc fleet.Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { specs, err := svc.GetQuerySpecs(ctx) if err != nil { return getQuerySpecsResponse{Err: err}, nil } return getQuerySpecsResponse{Specs: specs}, nil } } //////////////////////////////////////////////////////////////////////////////// // Get Query Spec //////////////////////////////////////////////////////////////////////////////// type getQuerySpecResponse struct { Spec *fleet.QuerySpec `json:"specs,omitempty"` Err error `json:"error,omitempty"` } func (r getQuerySpecResponse) error() error { return r.Err } func makeGetQuerySpecEndpoint(svc fleet.Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(getGenericSpecRequest) spec, err := svc.GetQuerySpec(ctx, req.Name) if err != nil { return getQuerySpecResponse{Err: err}, nil } return getQuerySpecResponse{Spec: spec}, nil } }
type getQuerySpecsResponse struct { Specs []*fleet.QuerySpec `json:"specs"` Err error `json:"error,omitempty"`
imageToArray.ts
import Jimp from 'jimp'; export default (image: Jimp) => { const { width, height } = image.bitmap; let isScanning = true; const pixels = []; let x = 0; let y = 0; while (isScanning) { const { r, g, b, a } = Jimp.intToRGBA(image.getPixelColor(x, y)); pixels.push([r, g, b, x, y, a]);
y += 1; } if (y >= height - 1 && x >= width - 2) { isScanning = false; } x += 1; } return pixels; };
if (x === width - 1) { x = 0;
list.go
package containerserver import ( "encoding/json" "fmt" "github.com/concourse/concourse/atc/types" "net/http" "strconv" "time" "code.cloudfoundry.org/lager" "github.com/concourse/concourse/atc/api/present" "github.com/concourse/concourse/atc/creds" "github.com/concourse/concourse/atc/db" ) func (s *Server) ListContainers(team db.Team) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { params := r.URL.RawQuery hLog := s.logger.Session("list-containers", lager.Data{ "params": params, }) containerLocator, err := createContainerLocatorFromRequest(team, r, s.secretManager, s.varSourcePool) if err != nil { hLog.Error("failed-to-parse-request", err) http.Error(w, err.Error(), http.StatusBadRequest) return } w.Header().Set("Content-Type", "application/json") hLog.Debug("listing-containers") containers, checkContainersExpiresAt, err := containerLocator.Locate(hLog) if err != nil { hLog.Error("failed-to-find-containers", err) w.WriteHeader(http.StatusInternalServerError) return } hLog.Debug("listed", lager.Data{"container-count": len(containers)}) presentedContainers := make([]types.Container, len(containers)) for i := 0; i < len(containers); i++ { container := containers[i] presentedContainers[i] = present.Container(container, checkContainersExpiresAt[container.ID()]) } err = json.NewEncoder(w).Encode(presentedContainers) if err != nil { hLog.Error("failed-to-encode-containers", err) w.WriteHeader(http.StatusInternalServerError) } }) } type containerLocator interface { Locate(lager.Logger) ([]db.Container, map[int]time.Time, error) } func createContainerLocatorFromRequest(team db.Team, r *http.Request, secretManager creds.Secrets, varSourcePool creds.VarSourcePool) (containerLocator, error) { query := r.URL.Query() delete(query, ":team_name") if len(query) == 0 { return &allContainersLocator{ team: team, }, nil } if query.Get("type") == "check" { return &checkContainerLocator{ team: team, pipelineName: query.Get("pipeline_name"), resourceName: query.Get("resource_name"), secretManager: secretManager, varSourcePool: varSourcePool, }, nil } var err error var containerType db.ContainerType if query.Get("type") != "" { containerType, err = db.ContainerTypeFromString(query.Get("type")) if err != nil { return nil, err } } pipelineID, err := parseIntParam(r, "pipeline_id") if err != nil { return nil, err } jobID, err := parseIntParam(r, "job_id") if err != nil { return nil, err } buildID, err := parseIntParam(r, "build_id") if err != nil { return nil, err } return &stepContainerLocator{ team: team, metadata: db.ContainerMetadata{ Type: containerType, StepName: query.Get("step_name"), Attempt: query.Get("attempt"), PipelineID: pipelineID, JobID: jobID, BuildID: buildID, PipelineName: query.Get("pipeline_name"), JobName: query.Get("job_name"), BuildName: query.Get("build_name"), }, }, nil } type allContainersLocator struct { team db.Team } func (l *allContainersLocator) Locate(logger lager.Logger) ([]db.Container, map[int]time.Time, error) { containers, err := l.team.Containers() return containers, nil, err } type checkContainerLocator struct { team db.Team pipelineName string resourceName string secretManager creds.Secrets varSourcePool creds.VarSourcePool } func (l *checkContainerLocator) Locate(logger lager.Logger) ([]db.Container, map[int]time.Time, error) { return l.team.FindCheckContainers(logger, l.pipelineName, l.resourceName, l.secretManager, l.varSourcePool) } type stepContainerLocator struct { team db.Team metadata db.ContainerMetadata } func (l *stepContainerLocator) Locate(logger lager.Logger) ([]db.Container, map[int]time.Time, error) { containers, err := l.team.FindContainersByMetadata(l.metadata) return containers, nil, err } func parseIntParam(r *http.Request, name string) (int, error)
{ var val int param := r.URL.Query().Get(name) if len(param) != 0 { var err error val, err = strconv.Atoi(param) if err != nil { return 0, fmt.Errorf("non-numeric '%s' param (%s): %s", name, param, err) } } return val, nil }
memxattr_state_autogen.go
// automatically generated by stateify. package memxattr import ( "gvisor.dev/gvisor/pkg/state" ) func (x *SimpleExtendedAttributes) StateTypeName() string { return "pkg/sentry/vfs/memxattr.SimpleExtendedAttributes" } func (x *SimpleExtendedAttributes) StateFields() []string { return []string{ "xattrs", } } func (x *SimpleExtendedAttributes) beforeSave() {} // +checklocksignore func (x *SimpleExtendedAttributes) StateSave(stateSinkObject state.Sink) { x.beforeSave() stateSinkObject.Save(0, &x.xattrs) } func (x *SimpleExtendedAttributes) afterLoad() {} // +checklocksignore func (x *SimpleExtendedAttributes) StateLoad(stateSourceObject state.Source) { stateSourceObject.Load(0, &x.xattrs) } func
() { state.Register((*SimpleExtendedAttributes)(nil)) }
init
linear_algebra.py
# global from typing import Union, Optional, Tuple, Literal from collections import namedtuple # local import ivy from ivy.framework_handler import current_framework as _cur_framework inf = float('inf') # Array API Standard # # -------------------# def matrix_transpose(x: Union[ivy.Array, ivy.NativeArray])\ -> ivy.Array: """ Transposes a matrix (or a stack of matrices) ``x``. Parameters ---------- x: array input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Returns ------- out: array an array containing the transpose for each matrix and having shape ``(..., N, M)``. The returned array must have the same data type as ``x``. """ return _cur_framework(x).matrix_transpose(x) # noinspection PyShadowingBuiltins def vector_norm(x: Union[ivy.Array, ivy.NativeArray], axis: Optional[Union[int, Tuple[int]]] = None, keepdims: bool = False, ord: Union[int, float, Literal[inf, -inf]] = 2)\ -> ivy.Array: """ Computes the vector norm of a vector (or batch of vectors) ``x``. Parameters ---------- x: input array. Should have a floating-point data type. axis: If an integer, ``axis`` specifies the axis (dimension) along which to compute vector norms. If an n-tuple, ``axis`` specifies the axes (dimensions) along which to compute batched vector norms. If ``None``, the vector norm must be computed over all array values (i.e., equivalent to computing the vector norm of a flattened array). Negative indices must be supported. Default: ``None``. keepdims: If ``True``, the axes (dimensions) specified by ``axis`` must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the axes (dimensions) specified by ``axis`` must not be included in the result. Default: ``False``. ord: order of the norm. The following mathematical norms must be supported: +------------------+----------------------------+ | ord | description | +==================+============================+ | 1 | L1-norm (Manhattan) | +------------------+----------------------------+ | 2 | L2-norm (Euclidean) | +------------------+----------------------------+ | inf | infinity norm | +------------------+----------------------------+ | (int,float >= 1) | p-norm | +------------------+----------------------------+ The following non-mathematical "norms" must be supported: +------------------+--------------------------------+ | ord | description | +==================+================================+ | 0 | sum(a != 0) | +------------------+--------------------------------+ | -1 | 1./sum(1./abs(a)) | +------------------+--------------------------------+ | -2 | 1./sqrt(sum(1./abs(a)\*\*2)) | +------------------+--------------------------------+ | -inf | min(abs(a)) | +------------------+--------------------------------+ | (int,float < 1) | sum(abs(a)\*\*ord)\*\*(1./ord) | +------------------+--------------------------------+ Default: ``2``. Returns ------- out: an array containing the vector norms. If ``axis`` is ``None``, the returned array must be a zero-dimensional array containing a vector norm. If ``axis`` is a scalar value (``int`` or ``float``), the returned array must have a rank which is one less than the rank of ``x``. If ``axis`` is a ``n``-tuple, the returned array must have a rank which is ``n`` less than the rank of ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. """
return ivy.reduce_max(ivy.abs(x), axis, keepdims) elif ord == 0: return ivy.reduce_sum(ivy.cast(x != 0, 'float32'), axis, keepdims) x_raised = x ** ord return ivy.reduce_sum(x_raised, axis, keepdims) ** (1/ord) def svd(x:Union[ivy.Array,ivy.NativeArray],full_matrices: bool = True)->Union[ivy.Array, Tuple[ivy.Array,...]]: """ Singular Value Decomposition. When x is a 2D array, it is factorized as u @ numpy.diag(s) @ vh = (u * s) @ vh, where u and vh are 2D unitary arrays and s is a 1D array of a’s singular values. When x is higher-dimensional, SVD is applied in batched mode. :param x: Input array with number of dimensions >= 2. :type x: array :return: u -> { (…, M, M), (…, M, K) } array \n Unitary array(s). The first (number of dims - 2) dimensions have the same size as those of the input a. The size of the last two dimensions depends on the value of full_matrices. s -> (…, K) array \n Vector(s) with the singular values, within each vector sorted in descending ord. The first (number of dims - 2) dimensions have the same size as those of the input a. vh -> { (…, N, N), (…, K, N) } array \n Unitary array(s). The first (number of dims - 2) dimensions have the same size as those of the input a. The size of the last two dimensions depends on the value of full_matrices. """ return _cur_framework(x).svd(x,full_matrices) def diagonal(x: ivy.Array, offset: int = 0, axis1: int = -2, axis2: int = -1) -> ivy.Array: """ Returns the specified diagonals of a matrix (or a stack of matrices) ``x``. Parameters ---------- x: input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. offset: offset specifying the off-diagonal relative to the main diagonal. - ``offset = 0``: the main diagonal. - ``offset > 0``: off-diagonal above the main diagonal. - ``offset < 0``: off-diagonal below the main diagonal. Default: `0`. axis1: axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0). axis2: axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis (1). Returns ------- out: an array containing the diagonals and whose shape is determined by removing the last two dimensions and appending a dimension equal to the size of the resulting diagonals. The returned array must have the same data type as ``x``. """ return _cur_framework(x).diagonal(x, offset, axis1=axis1, axis2=axis2) def inv(x): """ Computes the (multiplicative) inverse of x matrix. Given a square matrix x, returns the matrix x_inv satisfying dot(x, x_inv) = dot(x_inv, x) = eye(x.shape[0]). :param x: Matrix to be inverted. :type x: array :return: (Multiplicative) inverse of the matrix x. """ return _cur_framework(x).inv(x) def pinv(x): """ Computes the pseudo inverse of x matrix. :param x: Matrix to be pseudo inverted. :type x: array :return: pseudo inverse of the matrix x. """ return _cur_framework(x).pinv(x) def qr(x: ivy.Array, mode: str = 'reduced') -> namedtuple('qr', ['Q', 'R']): """ Returns the qr decomposition x = QR of a full column rank matrix (or a stack of matrices), where Q is an orthonormal matrix (or a stack of matrices) and R is an upper-triangular matrix (or a stack of matrices). Parameters ---------- x: input array having shape (..., M, N) and whose innermost two dimensions form MxN matrices of rank N. Should have a floating-point data type. mode: decomposition mode. Should be one of the following modes: - 'reduced': compute only the leading K columns of q, such that q and r have dimensions (..., M, K) and (..., K, N), respectively, and where K = min(M, N). - 'complete': compute q and r with dimensions (..., M, M) and (..., M, N), respectively. Default: 'reduced'. Returns ------- out: a namedtuple (Q, R) whose - first element must have the field name Q and must be an array whose shape depends on the value of mode and contain matrices with orthonormal columns. If mode is 'complete', the array must have shape (..., M, M). If mode is 'reduced', the array must have shape (..., M, K), where K = min(M, N). The first x.ndim-2 dimensions must have the same size as those of the input array x. - second element must have the field name R and must be an array whose shape depends on the value of mode and contain upper-triangular matrices. If mode is 'complete', the array must have shape (..., M, N). If mode is 'reduced', the array must have shape (..., K, N), where K = min(M, N). The first x.ndim-2 dimensions must have the same size as those of the input x. """ return _cur_framework(x).qr(x, mode) def matmul(x1: Union[ivy.Array, ivy.NativeArray], x2: Union[ivy.Array, ivy.NativeArray]) -> ivy.Array: """ Computes the matrix product. Parameters ---------- x1: x1 (array) – first input array. Should have a numeric data type. Must have at least one dimension. x2: x2 (array) – second input array. Should have a numeric data type. Must have at least one dimension. Returns ------- out(array): if both x1 and x2 are one-dimensional arrays having shape (N,), a zero-dimensional array containing the inner product as its only element. if x1 is a two-dimensional array having shape (M, K) and x2 is a two-dimensional array having shape (K, N), a two-dimensional array containing the conventional matrix product and having shape (M, N). if x1 is a one-dimensional array having shape (K,) and x2 is an array having shape (..., K, N), an array having shape (..., N) (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the conventional matrix product. if x1 is an array having shape (..., M, K) and x2 is a one-dimensional array having shape (K,), an array having shape (..., M) (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the conventional matrix product. if x1 is a two-dimensional array having shape (M, K) and x2 is an array having shape (..., K, N), an array having shape (..., M, N) and containing the conventional matrix product for each stacked matrix. if x1 is an array having shape (..., M, K) and x2 is a two-dimensional array having shape (K, N), an array having shape (..., M, N) and containing the conventional matrix product for each stacked matrix. if either x1 or x2 has more than two dimensions, an array having a shape determined by Broadcasting shape(x1)[:-2] against shape(x2)[:-2] and containing the conventional matrix product for each stacked matrix. Raises ------ if either x1 or x2 is a zero-dimensional array. if x1 is a one-dimensional array having shape (K,), x2 is a one-dimensional array having shape (L,), and K != L. if x1 is a one-dimensional array having shape (K,), x2 is an array having shape (..., L, N), and K != L. if x1 is an array having shape (..., M, K), x2 is a one-dimensional array having shape (L,), and K != L. if x1 is an array having shape (..., M, K), x2 is an array having shape (..., L, N), and K != L. """ return _cur_framework(x1).matmul(x1, x2) def slodget(x: Union[ivy.Array, ivy.NativeArray],) \ -> ivy.Array: """ Computes the sign and natural logarithm of the determinant of an array. Parameters ---------- x: This is a 2D array, and it has to be square Return ---------- Out: This function returns two values - sign: A number representing the sign of the determinant. logdet: The natural log of the absolute value of the determinant. """ return _cur_framework(x).slodget(x) def svdvals(x: Union[ivy.Array, ivy.NativeArray],) \ -> ivy.Array: """ Returns the singular values of a matrix (or a stack of matrices) ``x``. Parameters ---------- x: input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Return ---------- Out: array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where K = min(M, N). The values are sorted in descending order by magnitude. """ return _cur_framework(x).svdvals(x) def trace(x: ivy.Array, offset: int = 0)\ -> ivy.Array: """ Computes the sum of the diagonal of an array. Parameters ---------- x: This is an array. Return ---------- Out: This function returns two values - sum: The sum of the diagonals along an axis. """ return _cur_framework(x).trace(x, offset) # Extra # # ------#
if ord == -float('inf'): return ivy.reduce_min(ivy.abs(x), axis, keepdims) elif ord == float('inf'):
xobject.rs
// clippy lints when serializing PDF strings, in this case its wrong #![cfg_attr(feature = "cargo-clippy", allow(string_lit_as_bytes))] use lopdf; use std::collections::HashMap; #[cfg(feature = "embedded_images")] use image::{ImageError, ImageDecoder, DynamicImage, GenericImageView}; use time::Tm; use { ColorSpace, ColorBits, CurTransMat, Px }; /* Parent: Resources dictionary of the page */ /// External object that gets reference outside the PDF content stream /// Gets constructed similar to the `ExtGState`, then inserted into the `/XObject` dictionary /// on the page. You can instantiate `XObjects` with the `/Do` operator. The `layer.add_xobject()` /// (or better yet, the `layer.add_image()`, `layer.add_form()`) methods will do this for you. #[derive(Debug, Clone)] pub enum XObject { /* /Subtype /Image */ /// Image XObject, for images Image(ImageXObject), /* /Subtype /Form */ /// Form XObject, for PDF forms Form(Box<FormXObject>), /* /Subtype /PS */ /// Embedded PostScript XObject, for legacy applications /// You can embed PostScript in a PDF, it is not recommended PostScript(PostScriptXObject), } impl XObject { #[cfg(debug_assertions)] #[inline] fn compress_stream(stream: lopdf::Stream) -> lopdf::Stream { stream } #[cfg(not(debug_assertions))] #[inline] fn compress_stream(mut stream: lopdf::Stream) -> lopdf::Stream { stream.compress(); stream } } impl Into<lopdf::Object> for XObject { fn into(self) -> lopdf::Object { match self { XObject::Image(image) => { lopdf::Object::Stream(Self::compress_stream(image.into())) } XObject::Form(form) => { let cur_form: FormXObject = *form; lopdf::Object::Stream(Self::compress_stream(cur_form.into())) } XObject::PostScript(ps) => { lopdf::Object::Stream(Self::compress_stream(ps.into())) } } } } /// List of `XObjects` #[derive(Debug, Default, Clone)] pub struct XObjectList { objects: HashMap<String, XObject>, } impl XObjectList { /// Creates a new XObjectList pub fn new() -> Self { Self::default() } /// Adds a new XObject to the list pub fn add_xobject(&mut self, xobj: XObject) -> XObjectRef { let len = self.objects.len(); let xobj_ref = XObjectRef::new(len); self.objects.insert(xobj_ref.name.clone(), xobj); xobj_ref } /// Same as `Into<lopdf::Dictionary>`, but since the dictionary /// items in an XObject dictionary are streams and must be added to /// the document as __references__, this function needs an additional /// access to the PDF document so that we can add the streams first and /// then track the references to them. #[cfg_attr(feature = "cargo-clippy", allow(needless_return))] pub fn into_with_document(self, doc: &mut lopdf::Document) -> lopdf::Dictionary { self.objects.into_iter().map(|(name, object)| { let obj: lopdf::Object = object.into(); let obj_ref = doc.add_object(obj); (name.to_string(), lopdf::Object::Reference(obj_ref)) }).collect() } } /// Named reference to an `XObject` #[derive(Debug)] pub struct XObjectRef { pub(crate) name: String, } impl XObjectRef { /// Creates a new reference from a number pub fn new(index: usize) -> Self { Self { name: format!("X{}", index), } } } /* todo: inline images? (icons, logos, etc.) */ /* todo: JPXDecode filter */ #[derive(Debug, Clone)] pub struct ImageXObject { /// Width of the image (original width, not scaled width) pub width: Px, /// Height of the image (original height, not scaled height) pub height: Px, /// Color space (Greyscale, RGB, CMYK) pub color_space: ColorSpace, /// Bits per color component (1, 2, 4, 8, 16) - 1 for black/white, 8 Greyscale / RGB, etc. /// If using a JPXDecode filter (for JPEG images), this can be inferred from the image data pub bits_per_component: ColorBits, /// Should the image be interpolated when scaled? pub interpolate: bool, /// The actual data from the image pub image_data: Vec<u8>, /// Compression filter used for this image pub image_filter: Option<ImageFilter>, /* /BBox << dictionary >> */ /* todo: find out if this is really required */ /// Required bounds to clip the image, in unit space /// Default value: Identity matrix (`[1 0 0 1 0 0]`) - used when value is `None` pub clipping_bbox: Option<CurTransMat>, } impl<'a> ImageXObject { /// Creates a new ImageXObject // #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))] #[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))] pub fn new(width: Px, height: Px, color_space: ColorSpace, bits: ColorBits, interpolate: bool, image_filter: Option<ImageFilter>, bbox: Option<CurTransMat>, data: Vec<u8>) -> Self { Self { width: width, height: height, color_space: color_space, bits_per_component: bits, interpolate: interpolate, image_data: data, image_filter: image_filter, clipping_bbox: bbox, } } #[cfg(feature = "embedded_images")] pub fn try_from<T: ImageDecoder<'a>>(image: T) -> Result<Self, ImageError>
#[cfg(feature = "embedded_images")] pub fn from_dynamic_image(image: &DynamicImage) -> Self { let dim = image.dimensions(); let color_type = image.color(); let data = image.raw_pixels(); let color_bits = ColorBits::from(color_type); let color_space = ColorSpace::from(color_type); Self { width: Px(dim.0 as usize), height: Px(dim.1 as usize), color_space: color_space, bits_per_component: color_bits, image_data: data, interpolate: true, image_filter: None, clipping_bbox: None, } } } impl Into<lopdf::Stream> for ImageXObject { fn into(self) -> lopdf::Stream { use lopdf::Object::*; use std::iter::FromIterator; let cs: &'static str = self.color_space.into(); let bbox: lopdf::Object = self.clipping_bbox .unwrap_or(CurTransMat::Identity) .into(); let dict = lopdf::Dictionary::from_iter(vec![ ("Type", Name("XObject".as_bytes().to_vec())), ("Subtype", Name("Image".as_bytes().to_vec())), ("Width", Integer(self.width.0 as i64)), ("Height", Integer(self.height.0 as i64)), ("Interpolate", self.interpolate.into()), ("BitsPerComponent", Integer(self.bits_per_component.into())), ("ColorSpace", Name(cs.as_bytes().to_vec())), ("BBox", bbox), ]); if self.image_filter.is_some() { /* todo: add filter */ } lopdf::Stream::new(dict, self.image_data) } } /// Named reference to an image #[derive(Debug)] pub struct ImageXObjectRef { name: String, } /// todo: they don't work yet #[derive(Debug, Copy, Clone)] pub enum ImageFilter { Ascii85Decode, LzwDecode, JPXDecode, } /// __THIS IS NOT A PDF FORM!__ A form `XObject` can be nearly everything. /// PDF allows you to reuse content for the graphics stream in a `FormXObject`. /// A `FormXObject` is basically a layer-like content stream and can contain anything /// as long as it's a valid strem. A `FormXObject` is intended to be used for reapeated /// content on one page. #[derive(Debug, Clone)] pub struct FormXObject { /* /Type /XObject */ /* /Subtype /Form */ /* /FormType Integer */ /// Form type (currently only Type1) pub form_type: FormType, /// The actual content of this FormXObject pub bytes: Vec<u8>, /* /Matrix [Integer , 6] */ /// Optional matrix, maps the form into user space pub matrix: Option<CurTransMat>, /* /Resources << dictionary >> */ /// (Optional but strongly recommended; PDF 1.2) A dictionary specifying /// any resources (such as fonts and images) required by the form XObject /// (see Section 3.7, “Content Streams and Resources”). /// /// In PDF 1.1 and earlier, all named resources used in the form XObject must be /// included in the resource dictionary of each page object on which the form /// XObject appears, regardless of whether they also appear in the resource /// dictionary of the form XObject. It can be useful to specify these resources /// in the form XObject’s resource dictionary as well, to determine which resources /// are used inside the form XObject. If a resource is included in both dictionaries, /// it should have the same name in both locations. /// /// In PDF 1.2 and later versions, form XObjects can be independent of the content /// streams in which they appear, and this is strongly recommended although not /// required. In an independent form XObject, the resource dictionary of the form /// XObject is required and contains all named resources used by the form XObject. /// These resources are not promoted to the outer content stream’s resource /// dictionary, although that stream’s resource dictionary refers to the form XObject. pub resources: Option<lopdf::Dictionary>, /* /Group << dictionary >> */ /// (Optional; PDF 1.4) A group attributes dictionary indicating that the contents of the /// form XObject are to be treated as a group and specifying the attributes of that group /// (see Section 4.9.2, “Group XObjects”). /// /// Note: If a Ref entry (see below) is present, the group attributes also apply to the /// external page imported by that entry, which allows such an imported page to be treated /// as a group without further modification. pub group: Option<GroupXObject>, /* /Ref << dictionary >> */ /// (Optional; PDF 1.4) A reference dictionary identifying a page to be imported from another /// PDF file, and for which the form XObject serves as a proxy (see Section 4.9.3, “Reference XObjects”). pub ref_dict: Option<lopdf::Dictionary>, /* /Metadata [stream] */ /// (Optional; PDF 1.4) A metadata stream containing metadata for the form XObject /// (see Section 10.2.2, “Metadata Streams”). pub metadata: Option<lopdf::Stream>, /* /PieceInfo << dictionary >> */ /// (Optional; PDF 1.3) A page-piece dictionary associated with the form XObject /// (see Section 10.4, “Page-Piece Dictionaries”). pub piece_info: Option<lopdf::Dictionary>, /* /LastModified (date) */ /// (Required if PieceInfo is present; optional otherwise; PDF 1.3) The date and time /// (see Section 3.8.3, “Dates”) when the form XObject’s contents were most recently /// modified. If a page-piece dictionary (PieceInfo) is present, the modification date /// is used to ascertain which of the application data dictionaries it contains correspond /// to the current content of the form (see Section 10.4, “Page-Piece Dictionaries”). pub last_modified: Option<Tm>, /* /StructParent integer */ /// (Required if the form XObject is a structural content item; PDF 1.3) The integer key of /// the form XObject’s entry in the structural parent tree (see “Finding Structure Elements /// from Content Items” on page 868). pub struct_parent: Option<i64>, /* /StructParents integer */ /// __(Required if the form XObject contains marked-content sequences that are structural content /// items; PDF 1.3)__ The integer key of the form XObject’s entry in the structural parent tree /// (see “Finding Structure Elements from Content Items” on page 868). /// /// __Note:__ At most one of the entries StructParent or StructParents may be present. A form /// XObject can be either a content item in its entirety or a container for marked-content sequences /// that are content items, but not both. pub struct_parents: Option<i64>, /* /OPI << dictionary >> */ /// (Optional; PDF 1.2) An OPI version dictionary for the form XObject /// (see Section 10.10.6, “Open Prepress Interface (OPI)”). pub opi: Option<lopdf::Dictionary>, /// (Optional; PDF 1.5) An optional content group or optional content membership dictionary /// (see Section 4.10, “Optional Content”) specifying the optional content properties for /// the form XObject. Before the form is processed, its visibility is determined based on /// this entry. If it is determined to be invisible, the entire form is skipped, as if there /// were no Do operator to invoke it. pub oc: Option<lopdf::Dictionary>, /* /Name /MyName */ /// __(Required in PDF 1.0; optional otherwise)__ The name by which this form XObject is referenced /// in the XObject subdictionary of the current resource dictionary /// (see Section 3.7.2, “Resource Dictionaries”). /// __Note:__ This entry is obsolescent and its use is no longer recommended. /// (See implementation note 55 in Appendix H.) pub name: Option<String>, } impl Into<lopdf::Stream> for FormXObject { fn into(self) -> lopdf::Stream { use std::iter::FromIterator; use lopdf::Object::*; let dict = lopdf::Dictionary::from_iter(vec![ ("Type", Name("XObject".as_bytes().to_vec())), ("Subtype", Name("Form".as_bytes().to_vec())), ("FormType", Integer(self.form_type.into())), ]); lopdf::Stream::new(dict, self.bytes) } } /* << /Type /XObject /Subtype /Form /FormType 1 /BBox [ 0 0 1000 1000 ] /Matrix [ 1 0 0 1 0 0 ] /Resources << /ProcSet [ /PDF ] >> /Length 58 >> */ #[derive(Debug, Clone)] pub struct FormXObjectRef { name: String, } #[derive(Debug, Copy, Clone)] pub enum FormType { /// The only form type ever declared by Adobe /* Integer(1) */ Type1, } impl Into<i64> for FormType { fn into(self) -> i64 { match self { FormType::Type1 => 1, } } } /* see page 341 /Type /Image1 /Subtype /Image /Width 350 /Height 200 /ColorSpace /DeviceRGB % required, except for JPXDecode, not allowed for image masks /BitsPerComponent 8 % if ImageMask is true, optional or 1. % Optional stuff below /Intent /RelativeColormetric /ImageMask false % Mask and ColorSpace should not be specified /Mask << >> % Stream or array of colors to be masked /Decode [0 1] % weird /Interpolate true /Alternate [] % array of alternative images /SMask << >> % (Optional; PDF 1.4) A subsidiary image XObject defining a soft-mask image % (see “Soft-Mask Images” on page 553) to be used as a source of mask shape % or mask opacity values in the transparent imaging model. The alpha source % parameter in the graphics state determines whether the mask values are % interpreted as shape or opacity. % If present, this entry overrides the current soft mask in the graphics state, % as well as the image’s Mask entry, if any. (However, the other % transparency-related graphics state parameters—blend mode and alpha % constant—remain in effect.) If SMask is absent, the image has no associated % soft mask (although the current soft mask in the graphics state may still apply). /SMaskInData % 0, 1, 2 /Matte % if present, the SMask must have the same w / h as the picture. */ /* Parent: XObject with /Subtype /Image */ /// `SMask` dictionary. A soft mask (or `SMask`) is a greyscale image /// that is used to mask another image #[derive(Debug)] pub struct SMask { /* /Type /XObject */ /* /Subtype /Image */ /* /ColorSpace /DeviceGray */ /* /Intent (is ignored, don't set) */ /* /ImageMask (fals or not set, is ignored, don't set) */ /* /Mask (must be absent) */ /* /SMask (must be absent) */ /* /Decode (must be [0 1]) */ /* /Alternates (ignored, don't set) */ /* /Name (ignored, don't set) */ /* /StructParent (ignored, don't set) */ /* /ID (ignored, don't set) */ /* /OPI (ignored, don't set) */ /// If `self.matte` is set to true, this entry must be the same /// width as the parent image. If not, the `SMask` is resampled to the parent unit square pub width: i64, /// See width pub height: i64, /* /Interpolate (optional, set to true)*/ pub interpolate: bool, /// Bits per component, required (warning: this is a grayscale image) pub bits_per_component: i64, /// Vec of component values pub matte: Vec<i64>, } // in the PDF content stream, reference an XObject like this /* q % Save graphics state 1 0 0 1 100 200 cm % Translate 0. 7071 0. 7071 −0. 7071 0. 7071 0 0 cm % Rotate 150 0 0 80 0 0 cm % Scale /Image1 Do % Paint image Q % Restore graphics state */ #[derive(Debug, Copy, Clone)] pub struct GroupXObject { /* /Type /Group */ /* /S /Transparency */ /* currently the only valid GroupXObject */ } #[derive(Debug, Copy, Clone)] pub enum GroupXObjectType { /// Transparency group XObject TransparencyGroup, } /// PDF 1.4 and higher /// Contains a PDF file to be embedded in the current PDF #[derive(Debug)] pub struct ReferenceXObject { /// (Required) The file containing the target document. (?) pub file: Vec<u8>, /// Page number to embed pub page: i64, /// Optional, should be the document ID and version ID from the metadata pub id: [i64; 2], } /* parent: Catalog dictionary, I think, not sure */ /// Optional content group, for PDF layers. Only available in PDF 1.4 /// but (I think) lower versions of PDF allow this, too. Used to create /// Adobe Illustrator-like layers in PDF #[derive(Debug)] pub struct OptionalContentGroup { /* /Type /OCG */ /* /Name (Layer 1) */ /// (Required) The name of the optional content group, suitable for /// presentation in a viewer application’s user interface. pub name: String, /* /Intent [/View /Design] */ /// (Optional) A single intent name or an array containing any /// combination of names. PDF 1.5 defines two names, View and Design, /// that indicate the intended use of the graphics in the group. /// Future versions may define others. A processing application can choose /// to use only groups that have a specific intent and ignore others. /// Default value: View. See “Intent” on page 368 for more information. pub intent: Vec<OCGIntent>, /* /Usage << dictionary >> */ /// (Optional) A usage dictionary describing the nature of the content controlled /// by the group. It may be used by features that automatically control the state /// of the group based on outside factors. See “Usage and Usage Application /// Dictionaries” on page 380 for more information. pub usage: Option<lopdf::Dictionary>, } /// Intent to use for the optional content groups #[derive(Debug, Copy, Clone)] pub enum OCGIntent { View, Design, } /// TODO, very low priority #[derive(Debug, Clone)] pub struct PostScriptXObject { /// __(Optional)__ A stream whose contents are to be used in /// place of the PostScript XObject’s stream when the target /// PostScript interpreter is known to support only LanguageLevel 1 level1: Option<Vec<u8>>, } impl Into<lopdf::Stream> for PostScriptXObject { fn into(self) -> lopdf::Stream { // todo! lopdf::Stream::new(lopdf::Dictionary::new(), Vec::new()) } }
{ let dim = image.dimensions(); let color_type = image.colortype(); let image_data = image.read_image()?; let color_bits = ColorBits::from(color_type); let color_space = ColorSpace::from(color_type); Ok(Self { width: Px(dim.0 as usize), height: Px(dim.1 as usize), color_space: color_space, bits_per_component: color_bits, image_data: image_data, interpolate: true, image_filter: None, clipping_bbox: None, }) }
main.go
package main import ( "fmt" "github.com/c-bata/go-prompt" ) func
(in string) { fmt.Println("Your input: " + in) } func completer(in prompt.Document) []prompt.Suggest { s := []prompt.Suggest{ {Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"}, {Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."}, {Text: "您好", Description: "'您好' means 'Hello' in Chinese."}, {Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."}, } return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true) } func main() { p := prompt.New( executor, completer, prompt.OptionPrefix(">>> "), prompt.OptionTitle("sql-prompt for multi width characters"), ) p.Run() }
executor
preallocated_test.go
package storages import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestPreAllocatedBuffer_allocate(t *testing.T) { allocateSz := 16 now := time.Now() expiration := now.Add(1 * time.Minute) data := make([]byte, 128) preAllocated := newPreAllocatedBuffer(data) buf, ok := preAllocated.allocate(allocateSz, expiration) require.True(t, ok) assert.Len(t, buf.Bytes(), allocateSz) assert.False(t, preAllocated.isExpired(now)) } func TestPreAllocatedBuffer_allocateExpired(t *testing.T) { allocateSz := 16 now := time.Now() expiration := now data := make([]byte, 128) preAllocated := newPreAllocatedBuffer(data) buf, ok := preAllocated.allocate(allocateSz, expiration) require.True(t, ok) assert.Len(t, buf.Bytes(), allocateSz) assert.True(t, preAllocated.isExpired(now)) } func TestPreAllocatedBuffer_allocateOutOfLimit(t *testing.T) { allocateSz := 16 now := time.Now() expiration := now.Add(1 * time.Minute) data := make([]byte, 129) preAllocated := newPreAllocatedBuffer(data) bufCap := len(data) / allocateSz for i := 0; i < bufCap; i++ { buf, ok := preAllocated.allocate(allocateSz, expiration) require.True(t, ok) assert.Len(t, buf.Bytes(), allocateSz) } _, ok := preAllocated.allocate(allocateSz, expiration) require.False(t, ok) assert.False(t, preAllocated.isExpired(now)) } func TestPreAllocatedBuffer_allocateNotExpired(t *testing.T) { allocateSz := 16 now := time.Now() expiration := now data := make([]byte, 129) preAllocated := newPreAllocatedBuffer(data) bufCap := len(data) / allocateSz for i := 0; i < bufCap-1; i++ { buf, ok := preAllocated.allocate(allocateSz, expiration) require.True(t, ok) assert.Len(t, buf.Bytes(), allocateSz) } _, ok := preAllocated.allocate(allocateSz, expiration.Add(1*time.Minute)) require.True(t, ok) assert.False(t, preAllocated.isExpired(now)) } func TestPreAllocatedBuffer_allocateNotExpiredInUse(t *testing.T) { allocateSz := 16 now := time.Now() expiration := now data := make([]byte, 129) preAllocated := newPreAllocatedBuffer(data) bufCap := len(data) / allocateSz for i := 0; i < bufCap-1; i++ { buf, ok := preAllocated.allocate(allocateSz, expiration) require.True(t, ok) assert.Len(t, buf.Bytes(), allocateSz) } buf, ok := preAllocated.allocate(allocateSz, expiration) require.True(t, ok) buf.inUse() assert.False(t, preAllocated.isExpired(now)) buf.Free() assert.True(t, preAllocated.isExpired(now)) } func TestQueue_push(t *testing.T) { count := 2 queue := &queueAllocations{} for i := 0; i < count; i++ { queue.push(&preAllocatedBuffer{}) } assert.Equal(t, count, queue.len()) } func
(t *testing.T) { count := 4 expiredCount := 3 expired := make([]*preAllocatedBuffer, expiredCount) queue := &queueAllocations{} // Add expired 1 expired[0] = newPreAllocatedBuffer(make([]byte, 128)) _, ok := expired[0].allocate(16, time.Now()) require.True(t, ok) queue.push(expired[0]) // Add in use 1 for i := 0; i < count/2; i++ { buf := newPreAllocatedBuffer(make([]byte, 128)) _, ok := buf.allocate(16, time.Now().Add(1*time.Minute)) require.True(t, ok) queue.push(buf) } // Add expired 2 expired[1] = newPreAllocatedBuffer(make([]byte, 128)) _, ok = expired[1].allocate(16, time.Now()) require.True(t, ok) queue.push(expired[1]) // Add in use 2 for i := 0; i < count/2; i++ { buf := newPreAllocatedBuffer(make([]byte, 128)) _, ok := buf.allocate(16, time.Now().Add(1*time.Minute)) require.True(t, ok) queue.push(buf) } // Add expired 3 expired[2] = newPreAllocatedBuffer(make([]byte, 128)) _, ok = expired[2].allocate(16, time.Now()) require.True(t, ok) queue.push(expired[2]) assert.Equal(t, count+expiredCount, queue.len()) // Pop for i := 0; i < expiredCount; i++ { popExpired, ok := queue.pop(time.Now()) require.True(t, ok) assert.Equal(t, expired[i], popExpired) } assert.Equal(t, count, queue.len()) // Another are in use _, ok = queue.pop(time.Now()) require.False(t, ok) }
TestQueue_pop
test_visualization.py
import pyabc import tempfile import pytest import os import numpy as np import pandas as pd import matplotlib.pyplot as plt # create and run some model def model(p): return {'ss0': p['p0'] + 0.1 * np.random.uniform(), 'ss1': p['p1'] + 0.1 * np.random.uniform()} p_true = {'p0': 3, 'p1': 4} observation = {'ss0': p_true['p0'], 'ss1': p_true['p1']} limits = {'p0': (0, 5), 'p1': (1, 8)} prior = pyabc.Distribution(**{ key: pyabc.RV('uniform', limits[key][0], limits[key][1] - limits[key][0]) for key in p_true.keys()}) db_path = "sqlite:///" \ + os.path.join(tempfile.gettempdir(), "test_visualize.db") distance = pyabc.PNormDistance(p=2) n_history = 2 sampler = pyabc.sampler.MulticoreEvalParallelSampler(n_procs=2) for _ in range(n_history): abc = pyabc.ABCSMC(model, prior, distance, 20, sampler=sampler) abc.new(db_path, observation) abc.run(minimum_epsilon=.1, max_nr_populations=3) histories = [] labels = [] for j in range(n_history): history = pyabc.History(db_path) history.id = j + 1 histories.append(history) labels.append("Some run " + str(j)) def test_epsilons(): pyabc.visualization.plot_epsilons(histories, labels) plt.close() def test_sample_numbers(): pyabc.visualization.plot_sample_numbers( histories, rotation=43, size=(5, 5)) _, ax = plt.subplots() pyabc.visualization.plot_sample_numbers(histories, labels, ax=ax) with pytest.raises(ValueError): pyabc.visualization.plot_sample_numbers(histories, [labels[0]]) plt.close() def test_sample_numbers_trajectory(): pyabc.visualization.plot_sample_numbers_trajectory( histories, labels, yscale='log', rotation=90) _, ax = plt.subplots() pyabc.visualization.plot_sample_numbers_trajectory( histories, labels, yscale='log10', size=(8, 8), ax=ax) plt.close() def
(): pyabc.visualization.plot_acceptance_rates_trajectory( histories, labels, yscale='log', rotation=76) _, ax = plt.subplots() pyabc.visualization.plot_acceptance_rates_trajectory( histories, labels, yscale='log10', rotation=76, size=(10, 5), ax=ax) plt.close() def test_total_sample_numbers(): pyabc.visualization.plot_total_sample_numbers(histories) pyabc.visualization.plot_total_sample_numbers( histories, labels, yscale='log', size=(10, 5)) _, ax = plt.subplots() pyabc.visualization.plot_total_sample_numbers( histories, rotation=75, yscale='log10', ax=ax) plt.close() def test_effective_sample_sizes(): pyabc.visualization.plot_effective_sample_sizes( histories, labels, rotation=45, relative=True) plt.close() def test_histograms(): # 1d pyabc.visualization.plot_histogram_1d( histories[0], 'p0', bins=20, xmin=limits['p0'][0], xmax=limits['p0'][1], size=(5, 5), refval=p_true) # 2d pyabc.visualization.plot_histogram_2d(histories[0], 'p0', 'p1') pyabc.visualization.plot_histogram_2d( histories[0], 'p0', 'p1', xmin=limits['p0'][0], xmax=limits['p0'][1], ymin=limits['p1'][0], ymax=limits['p1'][1], size=(5, 6), refval=p_true) # matrix pyabc.visualization.plot_histogram_matrix( histories[0], bins=1000, size=(6, 7), refval=p_true) plt.close() def test_kdes(): history = histories[0] df, w = history.get_distribution(m=0, t=None) pyabc.visualization.plot_kde_1d( df, w, x='p0', xmin=limits['p0'][0], xmax=limits['p0'][1], label="PDF") pyabc.visualization.plot_kde_2d(df, w, x='p0', y='p1') pyabc.visualization.plot_kde_matrix(df, w) # also use the highlevel interfaces pyabc.visualization.plot_kde_1d_highlevel(history, x='p0', size=(4, 5), refval=p_true) pyabc.visualization.plot_kde_2d_highlevel(history, x='p0', y='p1', size=(7, 5), refval=p_true) pyabc.visualization.plot_kde_matrix_highlevel(history, height=27.43, refval=p_true) plt.close() def test_credible_intervals(): pyabc.visualization.plot_credible_intervals(histories[0]) pyabc.visualization.plot_credible_intervals( histories[0], levels=[0.2, 0.5, 0.9], show_kde_max_1d=True, show_kde_max=True, show_mean=True, refval=p_true) pyabc.visualization.plot_credible_intervals_for_time( histories, levels=[0.5, 0.99], show_kde_max_1d=True, show_kde_max=True, show_mean=True, refvals=p_true) plt.close() def test_model_probabilities(): pyabc.visualization.plot_model_probabilities(histories[0]) plt.close() def test_data_callback(): def plot_data(sum_stat, weight, ax, **kwargs): ax.plot(sum_stat['ss0'], alpha=weight, **kwargs) def plot_data_aggregated(sum_stats, weights, ax, **kwargs): data = np.array([sum_stat['ss0'] for sum_stat in sum_stats]) weights = np.array(weights).reshape((-1, 1)) mean = (data * weights).sum(axis=0) plot_data({'ss0': mean}, 1.0, ax) pyabc.visualization.plot_data_callback( histories[0], plot_data, plot_data_aggregated) def test_data_default(): obs_dict = {1: 0.7, 2: np.array([43, 423, 5.5]), 3: pd.DataFrame({'a': [1, 2], 'b': [4, 6]})} sim_dict = {1: 6.5, 2: np.array([32, 5, 6]), 3: pd.DataFrame({'a': [1.55, -0.1], 'b': [54, 6]})} pyabc.visualization.plot_data_default(obs_dict, sim_dict) for i in range(5): obs_dict[i] = i + 1 sim_dict[i] = i + 2 pyabc.visualization.plot_data_default(obs_dict, sim_dict) plt.close()
test_acceptance_rates_trajectory
cvnumpy.py
import numpy as np import cv2 def rodrigues2matrix_cv(params): rvec = np.array(params,dtype=np.float64) rvec.shape = (1,3) Rmat, jacobian = cv2.Rodrigues(rvec) return Rmat def rodrigues2matrix(params): # Written after the docs at # http://opencv.itseez.com/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#rodrigues try: rvec = np.array(params,dtype=np.float) rvec.shape = (1,3) except: print('bad rvec',rvec) raise theta = np.sqrt(np.sum(rvec**2))
r = rvec[0] # drop dim s = np.sin(theta) c = np.cos(theta) R = c*np.eye(3) + (1-c)*rvec*rvec.T + s*np.array([[0, -r[2], r[1]], [r[2], 0, -r[0]], [-r[1], r[0], 0]]) # -R.T might also be considered a valid rotation matrix, but it # -does not have an eigenvector of 1. return R def matrix2rodrigues(R): Rmat = np.array(R,dtype=np.float64) assert Rmat.shape == (3,3) rvec, jacobian = cv2.Rodrigues(Rmat) return rvec def rodrigues2angle_axis(params): rvec = np.array(params) rvec.shape = (1,3) theta = np.sqrt(np.sum(rvec**2)) if theta==0: rvec = rvec else: rvec = rvec/theta r = rvec[0] # drop dim return theta, r
if theta==0: rvec = rvec else: rvec = rvec/theta
config.go
package objets import ( "io/ioutil" "gopkg.in/yaml.v2" ) var ( DefautRootPath = "./objets_data" ) type Config struct { // Where objects will be stored UserDataDir string `yaml:"data_dir"` // Server listen UserListen string `yaml:"listen"` // TLS related config AutoTLS bool `yaml:"tls_auto"` Domains []string `yaml:"tls_domains"` // Auth AccessKeyID string `yaml:"access_key_id"` SecretAccessKey string `yaml:"secret_access_key"` } func (c *Config) DataDir() string { if c.UserDataDir == "" { return DefautRootPath } return c.UserDataDir } func (c *Config) Listen() string { if c.UserListen != ""
if c.AutoTLS { return ":443" } return ":8060" } func newConfig(path string) (*Config, error) { data, err := ioutil.ReadFile(path) if err != nil { return nil, err } conf := &Config{} if err := yaml.Unmarshal([]byte(data), &conf); err != nil { return nil, err } return conf, nil }
{ return c.UserListen }
network.py
# Copyright (c) 2017 Sony Corporation. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from nnabla.logger import logger import nnabla.function as F def print_network_traceback(funcs): logger.critical('Network traceback:') for i, func in enumerate(funcs): logger.critical('{}{}'.format( '->' if i == len(funcs) - 1 else ' ', func.name)) class Network: def setup_function(self, func): try: func.function_instance.setup( func.variable_inputs, func.variable_outputs) except: logger.critical('An error occurred while setup of function {} (nn.{}) in network {}'.format( func.name, func.function_instance.name, self.name)) logger.critical('Input variables:') for v in func.inputs: logger.critical(' {} (shape: {}, design_shape: {})'.format( v.name, str(v.variable_instance.shape), str(v.shape))) logger.critical('Output variables:') for v in func.outputs: logger.critical(' {} (shape: {}, design_shape: {})'.format( v.name, str(v.variable_instance.shape), str(v.shape))) raise # logger.debug('Setup: {} {}'.format(func.name, func.function_instance.name)) def get_forward_sequence(self, loss_variables): forward_sequence = [] for func in self.functions.values(): func.forward_complete = False for loss in loss_variables: self.__forward_recursive(forward_sequence, variable=loss) return forward_sequence def __forward_recursive(self, forward_sequence, variable=None, function=None): if not function and variable not in self.variable_inputs: return for func in [function] if function else self.variable_inputs[variable]: if func.forward_complete: continue for input_function in func.input_functions: self.__forward_recursive( forward_sequence, function=input_function) forward_sequence.append(func) func.forward_complete = True def forward(self, forward_sequence): for func in forward_sequence: try: self.forward_function(func) except: index = forward_sequence.index(func) print_network_traceback( forward_sequence[max(0, index - 4):index + 1]) raise def forward_function(self, func): try: # Uncomment when debugging expand_recurrent # print(func.name) # print(func.function_instance) # for n, inp in enumerate(func.variable_inputs): # print(' IN:', n, inp.shape, inp.d.flatten()[0]) func.function_instance.forward( func.variable_inputs, func.variable_outputs) # Uncomment when debugging expand_recurrent # for n, out in enumerate(func.variable_outputs): # print(' OUT:', n, out.shape, out.d.flatten()[0]) except: logger.critical('An error occurred while executing forward of function {} (nn.{}) in network {}'.format( func.name, func.function_instance.name, self.name)) raise def get_backward_sequence(self, loss_variables, parameter_variables_and_locallr): class BackwardSequence: loss_variables = [] variables = [] grad_variables = [] unused_variables = [] parameters = [] sequence = [] backward_sequence = BackwardSequence() backward_sequence.loss_variables = [ v.variable_instance for v in loss_variables] for p, lr in parameter_variables_and_locallr.items(): if lr > 0.0: backward_sequence.parameters.append(p.variable_instance) for func in self.functions.values(): func.backward_complete = False for p, local_lr in parameter_variables_and_locallr.items(): if local_lr > 0.0: self.__backward_recursive( backward_sequence, loss_variables, variable=p) for seq in backward_sequence.sequence: backward_sequence.variables.extend(seq.func.variable_outputs) for v in self.variables.values(): vi = v.variable_instance if vi not in backward_sequence.variables and vi not in backward_sequence.parameters: backward_sequence.unused_variables.append(vi) return backward_sequence def __backward_recursive(self, backward_sequence, loss_variables, variable=None, function=None): # logger.debug('bwcall: {}'.format(function.name if function else '')) if not function and variable not in self.variable_outputs: # terminal variable return variable in self.loss_variables diff_exists = False for func in [function] if function else self.variable_outputs[variable]: if func.backward_complete: diff_exists = True continue func.backward_complete = True for output_function in func.output_functions: if func.output_functions: diff = self.__backward_recursive( backward_sequence, loss_variables, function=output_function) diff_exists = diff_exists or diff else: # terminal function for v in loss_variables: diff_exists = diff_exists or (v in func.outputs) if diff_exists: if backward_sequence is not None: class BackwardSequenceItem: func = None accum_grad = [] seq = BackwardSequenceItem() seq.func = func for i, v in enumerate(func.variable_inputs): accum = ( v in backward_sequence.grad_variables or v in backward_sequence.parameters) and not func.function_instance.inplace_grad(i) seq.accum_grad.append(accum) if not v in backward_sequence.grad_variables: backward_sequence.grad_variables.append(v) backward_sequence.sequence.append(seq) return diff_exists def prepare_backward(self, backward_sequence, parameter_zero_grad=True): for v in backward_sequence.unused_variables: v.need_grad = False for p in backward_sequence.parameters: p.need_grad = True if parameter_zero_grad: p.grad.zero() for v in backward_sequence.variables: v.need_grad = True for l in backward_sequence.loss_variables: l.grad.fill(1.0 / l.size) def backward(self, backward_sequence, parameter_zero_grad=True):
except: index = backward_sequence.sequence.index(seq) print_network_traceback( [seq.func for seq in backward_sequence.sequence[max(0, index - 4):index + 1]]) raise def backward_function(self, seq): try: seq.func.function_instance.backward( seq.func.variable_inputs, seq.func.variable_outputs, seq.accum_grad) except: logger.critical('An error occurred while executing backward of function {} (nn.{}) in network {}'.format( seq.func.name, seq.func.function_instance.name, self.name)) raise # logger.debug('Backward: {} {}'.format(func.name, func.function_instance.name)) def setup(self, optimize=False): if optimize: for func in list(self.functions.values()): # remove identity layer if func.function_instance.name[0:8] == "Identity": assert(len(func.inputs) == 1) assert(len(func.outputs) == 1) # if the identity function is not terminal (keep terminal # identity function) if func.outputs[0] in self.variable_outputs: next_functions = self.variable_outputs[func.outputs[0]] self.variable_outputs[func.inputs[0]].remove(func) self.variable_outputs[ func.inputs[0]].extend(next_functions) for next_function in next_functions: next_function.inputs = [func.inputs[0] if v == func.outputs[ 0] else v for v in next_function.inputs] del self.functions[func.name] del self.variables[func.outputs[0].name] # create variable instances for variable in self.variables.values(): if variable.variable_instance.shape != variable.shape: if hasattr(variable.variable_instance, 'reset_shape'): variable.variable_instance.reset_shape( variable.shape, force=True) else: variable.variable_instance.reshape( variable.shape, force=True) # setup functions for i, func in enumerate(self.functions.values()): func.variable_inputs = [v.variable_instance for v in func.inputs] func.variable_outputs = [v.variable_instance for v in func.outputs] try: self.setup_function(func) except: print_network_traceback(list(self.functions.values())[ max(0, i - 4):i + 1]) raise # set link structure to each layer from itertools import chain for func in self.functions.values(): func.input_functions = list(chain.from_iterable( [self.variable_inputs[v] for v in func.inputs if v in self.variable_inputs])) func.output_functions = list(chain.from_iterable( [self.variable_outputs[v] for v in func.outputs if v in self.variable_outputs])) logger.debug(func.name) logger.debug(' in: {}'.format( [f.name for f in func.input_functions])) logger.debug(' out: {}'.format( [f.name for f in func.output_functions]))
self.prepare_backward(backward_sequence, parameter_zero_grad) for seq in backward_sequence.sequence: try: self.backward_function(seq)
engine.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Pradeep Jairamani , github.com/pradeepjairamani import socket import socks import time import json import threading import string import random import sys import struct import re import os from OpenSSL import crypto import ssl from core.alert import * from core.targets import target_type from core.targets import target_to_host from core.load_modules import load_file_path from lib.socks_resolver.engine import getaddrinfo from core._time import now from core.log import __log_into_file import requests def extra_requirements_dict(): return { "clickjacking_vuln_ports": [80, 443] } def conn(targ, port, timeout_sec, socks_proxy): try: if socks_proxy is not None: socks_version = socks.SOCKS5 if socks_proxy.startswith( 'socks5://') else socks.SOCKS4 socks_proxy = socks_proxy.rsplit('://')[1] if '@' in socks_proxy: socks_username = socks_proxy.rsplit(':')[0] socks_password = socks_proxy.rsplit(':')[1].rsplit('@')[0] socks.set_default_proxy(socks_version, str(socks_proxy.rsplit('@')[1].rsplit(':')[0]), int(socks_proxy.rsplit(':')[-1]), username=socks_username, password=socks_password) socket.socket = socks.socksocket socket.getaddrinfo = getaddrinfo else: socks.set_default_proxy(socks_version, str(socks_proxy.rsplit(':')[0]), int(socks_proxy.rsplit(':')[1])) socket.socket = socks.socksocket socket.getaddrinfo = getaddrinfo() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sys.stdout.flush() s.settimeout(timeout_sec) s.connect((targ, port)) return s except: return None def clickjacking(target, port, timeout_sec, log_in_file, language, time_sleep, thread_tmp_filename, socks_proxy, scan_id, scan_cmd): try: s = conn(target, port, timeout_sec, socks_proxy) if not s: return False else: if target_type(target) != "HTTP" and port == 443: target = 'https://' + target if target_type(target) != "HTTP" and port == 80: target = 'http://' + target req = requests.get(target) if req.headers['x-frame-options']: return False req = requests.get(target) if "frame-ancestors" in req.headers["content-security-policy"]: return False else: return True except: # some error warning return False def __clickjacking(target, port, timeout_sec, log_in_file, language, time_sleep, thread_tmp_filename, socks_proxy, scan_id, scan_cmd): if clickjacking(target, port, timeout_sec, log_in_file, language, time_sleep, thread_tmp_filename, socks_proxy, scan_id, scan_cmd): info(messages(language, "target_vulnerable").format(target, port, 'Header x-frame-options or frame-ancestors directive not set, ClickJacking attack is possible. Clickjacking, also known as a "UI redress attack", is when an attacker uses multiple transparent or opaque layers to trick a user into clicking on a button or link on another page when they were intending to click on the the top level page. ')) __log_into_file(thread_tmp_filename, 'w', '0', language) data = json.dumps({'HOST': target, 'USERNAME': '', 'PASSWORD': '', 'PORT': port, 'TYPE': 'clickjacking_vuln', 'DESCRIPTION': messages(language, "vulnerable").format('Header x-frame-options or frame-ancestors directive not set, ClickJacking attack is possible. Clickjacking, also known as a "UI redress attack", is when an attacker uses multiple transparent or opaque layers to trick a user into clicking on a button or link on another page when they were intending to click on the the top level page. '), 'TIME': now(), 'CATEGORY': "vuln", 'SCAN_ID': scan_id, 'SCAN_CMD': scan_cmd}) __log_into_file(log_in_file, 'a', data, language) return True else: return False def
(target, users, passwds, ports, timeout_sec, thread_number, num, total, log_in_file, time_sleep, language, verbose_level, socks_proxy, retries, methods_args, scan_id, scan_cmd): # Main function if target_type(target) != 'SINGLE_IPv4' or target_type(target) != 'DOMAIN' or target_type(target) != 'HTTP': # requirements check new_extra_requirements = extra_requirements_dict() if methods_args is not None: for extra_requirement in extra_requirements_dict(): if extra_requirement in methods_args: new_extra_requirements[ extra_requirement] = methods_args[extra_requirement] extra_requirements = new_extra_requirements if ports is None: ports = extra_requirements["clickjacking_vuln_ports"] if target_type(target) == 'HTTP': target = target_to_host(target) threads = [] total_req = len(ports) thread_tmp_filename = '{}/tmp/thread_tmp_'.format(load_file_path()) + ''.join( random.choice(string.ascii_letters + string.digits) for _ in range(20)) __log_into_file(thread_tmp_filename, 'w', '1', language) trying = 0 keyboard_interrupt_flag = False for port in ports: port = int(port) t = threading.Thread(target=__clickjacking, args=(target, int(port), timeout_sec, log_in_file, language, time_sleep, thread_tmp_filename, socks_proxy, scan_id, scan_cmd)) threads.append(t) t.start() trying += 1 if verbose_level > 3: info( messages(language, "trying_message").format(trying, total_req, num, total, target, port, 'clickjacking_vuln')) while 1: try: if threading.activeCount() >= thread_number: time.sleep(0.01) else: break except KeyboardInterrupt: keyboard_interrupt_flag = True break if keyboard_interrupt_flag: break # wait for threads kill_switch = 0 kill_time = int( timeout_sec / 0.1) if int(timeout_sec / 0.1) is not 0 else 1 while 1: time.sleep(0.1) kill_switch += 1 try: if threading.activeCount() is 1 or kill_switch is kill_time: break except KeyboardInterrupt: break thread_write = int(open(thread_tmp_filename).read().rsplit()[0]) if thread_write is 1 and verbose_level is not 0: info(messages(language, "no_vulnerability_found").format( 'ClickJacking')) data = json.dumps({'HOST': target, 'USERNAME': '', 'PASSWORD': '', 'PORT': '', 'TYPE': 'clickjacking_vuln', 'DESCRIPTION': messages(language, "no_vulnerability_found").format('ClickJacking'), 'TIME': now(), 'CATEGORY': "scan", 'SCAN_ID': scan_id, 'SCAN_CMD': scan_cmd}) __log_into_file(log_in_file, 'a', data, language) os.remove(thread_tmp_filename) else: warn(messages(language, "input_target_error").format( 'clickjacking_vuln', target))
start
book.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var BookSchema = new Schema({ title: {type: String, required: true}, author: {type: Schema.ObjectId, ref: 'Author', required: true}, summary: {type: String, required: true}, isbn: {type: String, required: true}, genre: [{type: Schema.ObjectId, ref: 'Genre'}] }); // Virtual for book's URL BookSchema .virtual('url')
return '/catalog/book/' + this._id; }); //Export model module.exports = mongoose.model('Book', BookSchema);
.get(function () {
completer.rs
use crate::completion::command::CommandCompleter; use crate::completion::flag::FlagCompleter; use crate::completion::matchers; use crate::completion::matchers::Matcher; use crate::completion::path::{PathCompleter, PathSuggestion}; use crate::completion::{self, Completer, Suggestion}; use nu_engine::EvaluationContext; use nu_parser::ParserScope; use nu_source::{Span, Tag}; use std::borrow::Cow; pub(crate) struct NuCompleter {} impl NuCompleter {} impl NuCompleter { pub fn complete( &self, line: &str, pos: usize, context: &completion::CompletionContext, ) -> (usize, Vec<Suggestion>)
} fn select_directory_suggestions(completed_paths: Vec<PathSuggestion>) -> Vec<PathSuggestion> { completed_paths .into_iter() .filter(|suggestion| { suggestion .path .metadata() .map(|md| md.is_dir()) .unwrap_or(false) }) .collect() } fn requote(orig_value: String, previously_quoted: bool) -> String { let value: Cow<str> = rustyline::completion::unescape(&orig_value, Some('\\')); let mut quotes = vec!['"', '\'']; let mut should_quote = false; for c in value.chars() { if c.is_whitespace() || c == '#' { should_quote = true; } else if let Some(index) = quotes.iter().position(|q| *q == c) { should_quote = true; quotes.swap_remove(index); } } if should_quote { if quotes.is_empty() { // TODO we don't really have an escape character, so there isn't a great option right // now. One possibility is `{{(char backtick)}}` value.to_string() } else { let quote = quotes[0]; if previously_quoted { format!("{}{}", quote, value) } else { format!("{}{}{}", quote, value, quote) } } } else { value.to_string() } }
{ use completion::engine::LocationType; let nu_context: &EvaluationContext = context.as_ref(); nu_context.scope.enter_scope(); let (block, _) = nu_parser::parse(line, 0, &nu_context.scope); nu_context.scope.exit_scope(); let locations = completion::engine::completion_location(line, &block, pos); let matcher = nu_data::config::config(Tag::unknown()) .ok() .and_then(|cfg| cfg.get("line_editor").cloned()) .and_then(|le| { le.row_entries() .find(|(idx, _value)| idx.as_str() == "completion_match_method") .and_then(|(_idx, value)| value.as_string().ok()) }) .unwrap_or_else(String::new); let matcher = matcher.as_str(); let matcher: &dyn Matcher = match matcher { "case-insensitive" => &matchers::case_insensitive::Matcher, "case-sensitive" => &matchers::case_sensitive::Matcher, #[cfg(target_os = "windows")] _ => &matchers::case_insensitive::Matcher, #[cfg(not(target_os = "windows"))] _ => &matchers::case_sensitive::Matcher, }; if locations.is_empty() { (pos, Vec::new()) } else { let mut pos = locations[0].span.start(); for location in &locations { if location.span.start() < pos { pos = location.span.start(); } } let suggestions = locations .into_iter() .flat_map(|location| { let partial = location.span.slice(line).to_string(); match location.item { LocationType::Command => { let command_completer = CommandCompleter; command_completer.complete(context, &partial, matcher.to_owned()) } LocationType::Flag(cmd) => { let flag_completer = FlagCompleter { cmd }; flag_completer.complete(context, &partial, matcher.to_owned()) } LocationType::Argument(cmd, _arg_name) => { let path_completer = PathCompleter; let prepend = Span::new(pos, location.span.start()).slice(line); const QUOTE_CHARS: &[char] = &['\'', '"']; // TODO Find a better way to deal with quote chars. Can the completion // engine relay this back to us? Maybe have two spans: inner and // outer. The former is what we want to complete, the latter what // we'd need to replace. let (quote_char, partial) = if partial.starts_with(QUOTE_CHARS) { let (head, tail) = partial.split_at(1); (Some(head), tail.to_string()) } else { (None, partial) }; let (mut partial, quoted) = if let Some(quote_char) = quote_char { if partial.ends_with(quote_char) { (partial[..partial.len() - 1].to_string(), true) } else { (partial, false) } } else { (partial, false) }; partial = partial.split('"').collect::<Vec<_>>().join(""); let completed_paths = path_completer.path_suggestions(&partial, matcher); match cmd.as_deref().unwrap_or("") { "cd" => select_directory_suggestions(completed_paths), _ => completed_paths, } .into_iter() .map(|s| Suggestion { replacement: format!( "{}{}", prepend, requote(s.suggestion.replacement, quoted) ), display: s.suggestion.display, }) .collect() } LocationType::Variable => Vec::new(), } }) .collect(); (pos, suggestions) } }
test_hive_to_dynamodb_operator.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import json import unittest from unittest import mock import datetime import pandas as pd from airflow import DAG from airflow.contrib.hooks.aws_dynamodb_hook import AwsDynamoDBHook import airflow.contrib.operators.hive_to_dynamodb DEFAULT_DATE = datetime.datetime(2015, 1, 1) DEFAULT_DATE_ISO = DEFAULT_DATE.isoformat() DEFAULT_DATE_DS = DEFAULT_DATE_ISO[:10] try: from moto import mock_dynamodb2 except ImportError: mock_dynamodb2 = None class HiveToDynamoDBTransferOperatorTest(unittest.TestCase): def setUp(self): args = {'owner': 'airflow', 'start_date': DEFAULT_DATE} dag = DAG('test_dag_id', default_args=args) self.dag = dag self.sql = 'SELECT 1' self.hook = AwsDynamoDBHook( aws_conn_id='aws_default', region_name='us-east-1') @staticmethod def process_data(data, *args, **kwargs):
@unittest.skipIf(mock_dynamodb2 is None, 'mock_dynamodb2 package not present') @mock_dynamodb2 def test_get_conn_returns_a_boto3_connection(self): hook = AwsDynamoDBHook(aws_conn_id='aws_default') self.assertIsNotNone(hook.get_conn()) @mock.patch('airflow.hooks.hive_hooks.HiveServer2Hook.get_pandas_df', return_value=pd.DataFrame(data=[('1', 'sid')], columns=['id', 'name'])) @unittest.skipIf(mock_dynamodb2 is None, 'mock_dynamodb2 package not present') @mock_dynamodb2 def test_get_records_with_schema(self, get_results_mock): # this table needs to be created in production self.hook.get_conn().create_table( TableName='test_airflow', KeySchema=[ { 'AttributeName': 'id', 'KeyType': 'HASH' }, ], AttributeDefinitions=[ { 'AttributeName': 'name', 'AttributeType': 'S' } ], ProvisionedThroughput={ 'ReadCapacityUnits': 10, 'WriteCapacityUnits': 10 } ) operator = airflow.contrib.operators.hive_to_dynamodb.HiveToDynamoDBTransferOperator( sql=self.sql, table_name="test_airflow", task_id='hive_to_dynamodb_check', table_keys=['id'], dag=self.dag) operator.execute(None) table = self.hook.get_conn().Table('test_airflow') table.meta.client.get_waiter( 'table_exists').wait(TableName='test_airflow') self.assertEqual(table.item_count, 1) @mock.patch('airflow.hooks.hive_hooks.HiveServer2Hook.get_pandas_df', return_value=pd.DataFrame(data=[('1', 'sid'), ('1', 'gupta')], columns=['id', 'name'])) @unittest.skipIf(mock_dynamodb2 is None, 'mock_dynamodb2 package not present') @mock_dynamodb2 def test_pre_process_records_with_schema(self, get_results_mock): # this table needs to be created in production self.hook.get_conn().create_table( TableName='test_airflow', KeySchema=[ { 'AttributeName': 'id', 'KeyType': 'HASH' }, ], AttributeDefinitions=[ { 'AttributeName': 'name', 'AttributeType': 'S' } ], ProvisionedThroughput={ 'ReadCapacityUnits': 10, 'WriteCapacityUnits': 10 } ) operator = airflow.contrib.operators.hive_to_dynamodb.HiveToDynamoDBTransferOperator( sql=self.sql, table_name='test_airflow', task_id='hive_to_dynamodb_check', table_keys=['id'], pre_process=self.process_data, dag=self.dag) operator.execute(None) table = self.hook.get_conn().Table('test_airflow') table.meta.client.get_waiter('table_exists').wait(TableName='test_airflow') self.assertEqual(table.item_count, 1) if __name__ == '__main__': unittest.main()
return json.loads(data.to_json(orient='records'))
prototype.rs
#[cfg(test)] #[path = "../../../tests/unit/extensions/generate/prototype_test.rs"] mod prototype_test; use super::*; use vrp_pragmatic::format::problem::Problem; use vrp_pragmatic::format::Location; /// Generates meaningful problem from the prototype. /// There is another problem generation implementation in `vrp-pragmatic` crate, used by tests. /// Its main goal is to discover problem space by generating many, potentially unrealistic, problems /// using property based approach. This implementation, in contrast, focuses on generating realistic /// problems. pub(crate) fn
( problem: &Problem, locations: Option<Vec<Location>>, jobs_size: usize, vehicle_types_size: usize, area_size: Option<f64>, ) -> Result<Problem, String> { if problem.plan.jobs.len() < 3 { return Err("at least three jobs should be defined".to_string()); } Ok(Problem { plan: generate_plan(&problem, locations, jobs_size, area_size)?, fleet: generate_fleet(&problem, vehicle_types_size), objectives: problem.objectives.clone(), }) }
generate_from_prototype
courses.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map, shareReplay } from 'rxjs/operators'; import { Course } from '../model/course'; import { Lesson } from '../model/lesson'; @Injectable({ providedIn: 'root' }) export class
{ constructor(private http:HttpClient) { } loadCourseById(courseId: number) { return this.http.get<Course>(`/api/courses/${courseId}`) .pipe( shareReplay() ); } loadAllCourseLessons(courseId: number): Observable<Lesson[]> { return this.http.get<Lesson[]>('/api/lessons', { params: { pageSize: "100000", courseId: courseId.toString() } }) .pipe( map(res => res["payload"]), shareReplay() ); } loadAllCourses(): Observable<Course[]> { return this.http.get<Course[]>("/api/courses") .pipe( map(res => res["payload"]), shareReplay() ); } saveCourse(courseId: string, changes: Partial<Course>): Observable<any> { return this.http.put(`/api/courses/${courseId}`, changes) .pipe( shareReplay() ) } searchLessons(search: string): Observable<Lesson[]> { return this.http.get<Lesson[]>('/api/lessons', { params: { filter: search, pageSize: "100" } }) .pipe( map(res => res["payload"]), shareReplay() ); } }
CoursesService
item.ts
import type { RequestHandler } from "express"; import * as configFns from "../helpers/configFns"; import * as itemData from "../helpers/itemDataCache"; export const handler: RequestHandler = (req, res) => { const itemKey = req.params.itemKey; if (itemKey === "") {
return res.redirect(configFns.getProperty("reverseProxy.urlPrefix") + "/search"); } const item = itemData.getItemByItemKey(itemKey); if (!item) { return res.redirect(configFns.getProperty("reverseProxy.urlPrefix") + "/search"); } const itemReuses = itemData.getItemReusesByItemKey(itemKey) || []; const itemLocations = itemData.getItemLocationsByItemKey(itemKey) || []; const relatedItems = itemData.getRelatedItemsByItemKey(itemKey) || []; return res.render("item", { item, itemReuses, itemLocations, relatedItems }); };
linked_list_test.go
package collection import ( "fmt" "testing" ) func
(t *testing.T) { linkedList := LinkedList{} linkedList.Add(1) linkedList.Add(2) linkedList.Add(3) linkedList.AddFirst(4) err, item := linkedList.GetLast() fmt.Println(item) err, item1 := linkedList.RemoveLast() fmt.Println(item1) err, item2 := linkedList.GetLast() fmt.Println(item2) contain := linkedList.Contains(1) fmt.Println(contain) contain2 := linkedList.Contains(3) fmt.Println(contain2) err, item3 := linkedList.Get(4) fmt.Printf("Size %d \n", linkedList.Size()) fmt.Printf("%s 节点值:%v", err, item3) }
TestLinkedList
main.js
var app = require('app'); // Module to control application life. var BrowserWindow = require('browser-window'); // Module to create native browser window. // Report crashes to our server. require('crash-reporter').start(); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. var mainWindow = null; // Quit when all windows are closed. app.on('window-all-closed', function() { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform != 'darwin') { app.quit(); } });
app.on('ready', function() { // Create the browser window. mainWindow = new BrowserWindow({width: 800, height: 600}); // and load the index.html of the app. mainWindow.loadUrl('file://' + __dirname + '/html/index.html'); // Open the DevTools. mainWindow.openDevTools(); // Emitted when the window is closed. mainWindow.on('closed', function() { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); });
// This method will be called when Electron has finished // initialization and is ready to create browser windows.
paginacontrollers.js
import { Viajes } from '../Models/Viajes.js' import { Testimoniales } from '../Models/testimoniales.js' const paginaInicio = async (req, res) => { //Consideraciones de conceptos. Para mejora de performance, es recomendable que ambas consultas se hagan al mismo tiempo. Por talmotivo se crea un objeto de Promise donde se agregan ambas consultas y se ejecutan al mismo tiempo en una unica acción. Eso hace que la vista sea renderizada con otdas las informaciones const promiseDB = []; promiseDB.push( Viajes.findAll( {limit: 3})); promiseDB.push( Testimoniales.findAll( {limit: 3 })); //Consultar 3 viajes del modelo viaje try { const resultado = await Promise.all( promiseDB );
pagina: 'inicio', clase: 'home', viajes: resultado[0], testimonios: resultado[1] }) } catch(error) { console.log(error) } }; const paginaNosotros = (req, res) => { res.render('nosotros', { pagina: 'Nosotros' } )}; const paginaTestimoniales = async (req, res) => { try { const testimonios = await Testimoniales.findAll(); res.render('testimoniales', { pagina: 'Testimoniales', testimonios }) }catch(error) { console.log(error); } }; const paginaViajes = async (req, res) => { //Consultar BD const viajes = await Viajes.findAll(); console.log(viajes); res.render('viajes', { pagina: 'Viajes', viajes }) }; //Muestra un viaje por su slug const paginaDetalleViaje = async (req, res) => { const { viaje } = req.params; try { const resultado = await Viajes.findOne( {where: { slug: viaje }}); res.render('viaje', { pagina: 'Informacion Viaje', resultado }) } catch(error) { console.log(error); } } export { paginaInicio, paginaNosotros, paginaTestimoniales, paginaViajes, paginaDetalleViaje }
res.render('inicio', {
read.py
""" Module for reading data from 'q4x.csv' and 'q4y.csv' """ import numpy as np def loadData (x_file="../ass1_data/q4x.dat", y_file="../ass1_data/q4y.dat"): """ Loads the X, Y matrices. """ X = np.genfromtxt(x_file, delimiter=' ', dtype=int) labels = np.genfromtxt(y_file, dtype=str) Y = [] for label in labels: if (label == "Alaska"): Y.append(0) else:
return (X, Y)
Y.append(1)
messaging.go
package hybsterx import ( "github.com/gogo/protobuf/proto" "github.com/ibalajiarun/go-consensus/peer/peerpb" pb "github.com/ibalajiarun/go-consensus/protocols/hybsterx/hybsterxpb" ) func (p *hybsterx) wrapAndMarshal(m proto.Message) []byte { hMsg := pb.WrapHybsterxMessage(m) mBytes, err := proto.Marshal(hMsg) if err != nil { p.logger.Panic("unable to marshal") } return mBytes } func (p *hybsterx) sendTo(to peerpb.PeerID, mm, cert []byte) { cm := peerpb.Message{ Content: mm, Certificate: cert, To: to, From: p.id, } p.msgs = append(p.msgs, cm) } func (p *hybsterx) broadcastNormal(m *pb.NormalMessage) { mBytes := p.wrapAndMarshal(m) counter := uint64(uint64(m.View<<48)|uint64(m.InstanceID.Index)) + 1 ctrIdx := int(m.InstanceID.PeerID) p.signDispatcher.Exec(func() []byte { return p.certifier.CreateIndependentCounterCertificateVector(mBytes, counter, ctrIdx) }, func(cert []byte) { for _, node := range p.nodes { if node != p.id
} }, int(m.InstanceID.PeerID)%p.signWorkerCount) } func (p *hybsterx) broadcastONormal(m *pb.ONormalMessage) { mBytes := p.wrapAndMarshal(m) counter := uint64(uint64(m.View<<48)|uint64(m.Index)) + 1 ctrIdx := len(p.nodes) p.signDispatcher.Exec(func() []byte { return p.certifier.CreateIndependentCounterCertificateVector(mBytes, counter, ctrIdx) }, func(cert []byte) { for _, node := range p.nodes { if node != p.id { idx := node * 32 p.sendTo(node, mBytes, cert[idx:idx+32]) } } }, len(p.nodes)%p.signWorkerCount) } func (p *hybsterx) ClearMsgs() { p.msgs = nil }
{ idx := node * 32 p.sendTo(node, mBytes, cert[idx:idx+32]) }
load.js
const Article = require('../../db/article'); export default function load(req) { const currentPage = parseInt(req.query.currentPage) || 1; const perPage = 20; const user = req.session.user;
const city = user ? user.city : 'jinzhou'; return new Promise((resolve, reject) => { let options = { currentPage, perPage, criteria: { city } }; Article.list(options, function (err, articles) { if (err) { reject(err); } else { Article.count({}, (err, count) => { const total = Math.ceil(count / perPage); resolve({ articles, total, ...options }); }) } }); }) }
settings.py
WIDTH = 1024 HEIGHT = 768 #colours
WHITE = (255,255,255) RED = (255,0,0)
check.d.ts
import { flags } from "@oclif/command"; import { ClientCommand } from "../../Command"; import { graphqlTypes } from "apollo-language-server"; declare type ValidationResult = graphqlTypes.ValidateOperations_service_validateOperations_validationResults; interface Operation { body: string; name: string; relativePath: string; locationOffset: LocationOffset; } interface LocationOffset { column: number; line: number; } export default class ClientCheck extends ClientCommand { static description: string; static flags: { clientReferenceId: flags.IOptionFlag<string | undefined>; clientName: flags.IOptionFlag<string | undefined>; clientVersion: flags.IOptionFlag<string | undefined>; tag: flags.IOptionFlag<string | undefined>; queries: flags.IOptionFlag<string | undefined>; includes: flags.IOptionFlag<string | undefined>; excludes: flags.IOptionFlag<string | undefined>; tagName: flags.IOptionFlag<string | undefined>; config: flags.IOptionFlag<string | undefined>; header: flags.IOptionFlag<string[]>; endpoint: flags.IOptionFlag<string | undefined>; key: flags.IOptionFlag<string | undefined>; engine: flags.IOptionFlag<string | undefined>; frontend: flags.IOptionFlag<string | undefined>;
getMessagesByOperationName(validationResults: ValidationResult[], operations: Operation[]): { [operationName: string]: { operation: Operation; validationResults: graphqlTypes.ValidateOperations_service_validateOperations_validationResults[]; }; }; logMessagesForOperation: ({ validationResults, operation }: { validationResults: graphqlTypes.ValidateOperations_service_validateOperations_validationResults[]; operation: Operation; }) => void; formatValidation({ type, description }: ValidationResult): string; printStats: (validationResults: graphqlTypes.ValidateOperations_service_validateOperations_validationResults[], operations: Operation[]) => void; } export {}; //# sourceMappingURL=check.d.ts.map
}; run(): Promise<void>;
test_util.go
package binance import ( "io/ioutil" "net/http" "net/http/httptest" "os" "path/filepath" "testing" ) func readTestData(t *testing.T) ([]byte, error) { path := filepath.Join("testdata", filepath.FromSlash(t.Name()+".json")) if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { return nil, nil } return nil, err } b, err := ioutil.ReadFile(path) if err != nil { return nil, err }
func createTestServer(t *testing.T, statusCode int) (*httptest.Server, error) { response, err := readTestData(t) if err != nil { return nil, err } h := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(statusCode) w.Write(response) } srv := httptest.NewServer(http.HandlerFunc(h)) return srv, nil }
return b, nil }
ways.go
package cache import ( "github.com/jmhodges/levigo" osm "github.com/omniscale/go-osm" "github.com/nextgis/imposm3/cache/binary" ) type WaysCache struct { cache } func newWaysCache(path string) (*WaysCache, error)
func (c *WaysCache) PutWay(way *osm.Way) error { if way.ID == SKIP { return nil } keyBuf := idToKeyBuf(way.ID) data, err := binary.MarshalWay(way) if err != nil { return err } return c.db.Put(c.wo, keyBuf, data) } func (c *WaysCache) PutWays(ways []osm.Way) error { batch := levigo.NewWriteBatch() defer batch.Close() for _, way := range ways { if way.ID == SKIP { continue } keyBuf := idToKeyBuf(way.ID) data, err := binary.MarshalWay(&way) if err != nil { return err } batch.Put(keyBuf, data) } return c.db.Write(c.wo, batch) } func (c *WaysCache) GetWay(id int64) (*osm.Way, error) { keyBuf := idToKeyBuf(id) data, err := c.db.Get(c.ro, keyBuf) if err != nil { return nil, err } if data == nil { return nil, NotFound } way, err := binary.UnmarshalWay(data) if err != nil { return nil, err } way.ID = id return way, nil } func (c *WaysCache) DeleteWay(id int64) error { keyBuf := idToKeyBuf(id) return c.db.Delete(c.wo, keyBuf) } func (c *WaysCache) Iter() chan *osm.Way { ways := make(chan *osm.Way, 1024) go func() { ro := levigo.NewReadOptions() ro.SetFillCache(false) it := c.db.NewIterator(ro) // we need to Close the iter before closing the // chan (and thus signaling that we are done) // to avoid race where db is closed before the iterator defer close(ways) defer it.Close() it.SeekToFirst() for ; it.Valid(); it.Next() { way, err := binary.UnmarshalWay(it.Value()) if err != nil { panic(err) } way.ID = idFromKeyBuf(it.Key()) ways <- way } }() return ways } func (c *WaysCache) FillMembers(members []osm.Member) error { if members == nil || len(members) == 0 { return nil } for i, member := range members { if member.Type != osm.WayMember { continue } way, err := c.GetWay(member.ID) if err != nil { return err } members[i].Way = way } return nil }
{ cache := WaysCache{} cache.options = &globalCacheOptions.Ways err := cache.open(path) if err != nil { return nil, err } return &cache, err }
setup.py
#! /usr/bin/env python from os.path import dirname, realpath, join from setuptools import setup, find_packages import sys #### # Basic project info. #### project_name = 'short-con' package_name = project_name.replace('-', '_') repo_name = project_name description = 'Constants collections without boilerplate' url = 'https://github.com/hindman/' + repo_name author = 'Monty Hindman' author_email = '[email protected]' license = 'MIT' src_subdir = 'src' project_dir = dirname(realpath(__file__)) #### # Requirements. #### reqs = [ 'attrs', 'six', ] extras = { 'test' : [ 'pytest', 'pytest-cov', 'tox', ], 'dev' : [ 'invoke', 'ipython' if sys.version_info.major > 2 else 'ipython<6.0', 'pycodestyle', 'twine', 'virtualenv', 'virtualenvwrapper', ], } #### # Set __version__, long description, and classifiers. #### version_file = join(project_dir, src_subdir, package_name, 'version.py') exec(open(version_file).read()) readme_file = join(project_dir, 'README.md') long_desc = open(readme_file).read() long_desc_type = 'text/markdown' classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Software Development',
#### packages = find_packages(where = src_subdir) package_data = { package_name: [], } #### # Install. #### setup( name = project_name, version = __version__, author = author, author_email = author_email, url = url, description = description, zip_safe = False, packages = packages, package_dir = {'': src_subdir}, package_data = package_data, install_requires = reqs, tests_require = extras['test'], extras_require = extras, license = license, long_description = long_desc, long_description_content_type = long_desc_type, classifiers = classifiers, )
] #### # Packages and scripts.
utils.py
import os import glob import torch import pandas as pd import seaborn as sn import torch.nn as nn import torch.optim as optim import matplotlib.pyplot as plt from torch.optim.lr_scheduler import _LRScheduler from sklearn.metrics import confusion_matrix from PIL import Image def set_lr(optimizer, lrs): if(len(lrs) == 1): for param in optimizer.param_groups: param['lr'] = lrs[0] else: for i, param in enumerate(optimizer.param_groups): param['lr'] = lrs[i] def set_base_lr(optimizer, lrs): if(len(lrs) == 1): for param in optimizer.param_groups: param['initial_lr'] = lrs[0] else: for i, param in enumerate(optimizer.param_groups): param['initial_lr'] = lrs[i] def get_lr(optimizer): optim_param_groups = optimizer.param_groups if(len(optim_param_groups) == 1): return optim_param_groups[0]['lr'] else: lrs = [] for param in optim_param_groups: lrs.append(param['lr']) return lrs def get_children_groups(model_children, param_places): cur_place = 0 children_groups = [] for param_place in param_places: children_groups.append(model_children[cur_place:param_place]) cur_place = param_place return children_groups def
(children): params_use_grad = [] for child in children: for param in child.parameters(): if(param.requires_grad == True): params_use_grad.append(param) return params_use_grad def get_optimizer(model, lrs, param_places): model_children = list(model.children()) # only 1 learning rate if(len(lrs) == 1): # from the model's childrens, only get the parameters that use grad param_use_grad = get_params(model_children) # set an Adam optimizer with the params that use grad, and the lr optimizer = optim.Adam(param_use_grad, lrs[0]) # multiple learning rates else: # from the param_places, get chunks of children from model_children # children_groups is a list, and each item will be a list of children children_groups = get_children_groups(model_children, param_places) # from children_groups, get each of its children group's grad using params # param_groups_use_grad is a list, and each item will be a list of params that use grad param_groups_use_grad = [] for children_group in children_groups: param_group_use_grad = get_params(children_group) param_groups_use_grad.append(param_group_use_grad) # zip param_groups_use_grad together with lrs # in order to feed in the corresponding lr to a given param_group param_groups_use_grad_with_lrs = zip(param_groups_use_grad, lrs) optimizer = optim.Adam([{'params' : p, 'lr' : l} for p, l in param_groups_use_grad_with_lrs]) return optimizer def freeze_until(model, idx): for i, child in enumerate(model.children()): if(i <= idx): for param in child.parameters(): param.requires_grad = False else: for param in child.parameters(): param.requires_grad = True def histogram_sizes(img_dir, h_lim = None, w_lim = None): hs, ws = [], [] for file in glob.iglob(os.path.join(img_dir, '**/*.*')): try: with Image.open(file) as im: h, w = im.size hs.append(h) ws.append(w) except: print('Not an Image file') if(h_lim is not None and w_lim is not None): hs = [h for h in hs if h<h_lim] ws = [w for w in ws if w<w_lim] plt.figure('Height') plt.hist(hs) plt.figure('Width') plt.hist(ws) plt.show() return hs, ws def plot_confusion_matrix(model, dl, names, classes_count, device, figsize): true_label = [] predicted_label = [] for batch in dl: (images, labels) = batch y_real = list(labels.data.cpu().numpy()) y_pred = list(torch.argmax(model(images.to(device)), dim=1).data.cpu().numpy()) true_label.extend(y_real) predicted_label.extend(y_pred) cm = confusion_matrix(true_label, predicted_label) names_with_cnt = [str(name) + ' : ' + str(cnt) for name, cnt in zip(names, classes_count)] df = pd.DataFrame(cm, index = names_with_cnt, columns = names_with_cnt) plt.figure(figsize = figsize) ax = plt.subplot(111) sn.heatmap(df, annot = True, ax = ax, fmt='g') plt.show() def freeze_cur_bn(module): classname = module.__class__.__name__ if(classname.find('BatchNorm') != -1): module.eval() def freeze_bn(model): model.apply(freeze_cur_bn) class Normalize(nn.Module): def __init__(self, mean, variance): super(Normalize, self).__init__() self.mean = mean.view(-1, 1, 1) self.variance = variance.view(-1, 1, 1) def forward(self, x): return (x - mean) / variance
get_params
config.py
import os from os.path import join, dirname from dotenv import load_dotenv from urllib.parse import urlparse # loading .env file env_path = join(dirname(__file__), '.env') load_dotenv(env_path) # use function def url_path_check(path):
def number_check(num=None): if isinstance(int(num), int): return int(num) return None # Register Env Param try: API_AUTH_FEATURE = os.environ.get('API_AUTH_FEATURE', 'False').lower() in ('true') or False DEFAULT_LANGUAGE = os.environ.get('DEFAULT_LANGUAGE') or 'ja' VERSION = os.environ.get('VERSION') or '1.0.0' SHOW_SWAGGER_PATH = url_path_check(os.environ.get('SHOW_SWAGGER_PATH') or "") or None SHOW_REDOC_PATH = url_path_check(os.environ.get('SHOW_REDOC_PATH') or "") or None SHOW_OPENAPI_PATH = url_path_check(os.environ.get('SHOW_OPENAPI_PATH')) or None DB_HOST = os.environ.get('DB_HOST') or 'pgsql' DB_PORT = number_check(os.environ.get('DB_PORT')) or 5432 DB_USER = os.environ.get('DB_USER') or 'postgres' DB_PASSWORD = os.environ.get('DB_PASSWORD') or 'postgres' DATABASE = os.environ.get('DATABASE') or 'postgres' except Exception: print("defined param error: check .env file") raise
sample_host = 'http://localhost' sample_url = sample_host + path if urlparse(sample_url) and urlparse(sample_url).path == path: return path return None
lib.rs
// Copyright 2021 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 //! In-memory Bee storage backend. #![deny(missing_docs)] #![deny(warnings)] mod table; pub mod access;
pub mod storage;
.prettierrc.js
module.exports = { bracketSpacing: true, jsxBracketSameLine: true, singleQuote: true, trailingComma: 'none', arrowParens: 'avoid'
};
gpio.rs
//! General Purpose Input Output (GPIO) //! //! For details see p.987 in the cc2650 technical reference manual. //! //! Configures the GPIO pins, and interfaces with the HIL for gpio. use core::cell::Cell; use core::ops::{Index, IndexMut}; use kernel::common::cells::OptionalCell; use kernel::common::registers::{ReadWrite, WriteOnly}; use kernel::common::StaticRef; use kernel::hil; use kernel::hil::gpio::PinCtl; const NUM_PINS: usize = 32; const GPIO_BASE: StaticRef<GpioRegisters> = unsafe { StaticRef::new(0x40022000 as *const GpioRegisters) }; const IOC_BASE: StaticRef<IocRegisters> = unsafe { StaticRef::new(0x40081000 as *const IocRegisters) }; #[repr(C)] struct GpioRegisters { _reserved0: [u8; 0x90], pub dout_set: WriteOnly<u32>, _reserved1: [u8; 0xC], pub dout_clr: WriteOnly<u32>, _reserved2: [u8; 0xC], pub dout_tgl: WriteOnly<u32>, _reserved3: [u8; 0xC], pub din: ReadWrite<u32>, _reserved4: [u8; 0xC], pub doe: ReadWrite<u32>, _reserved5: [u8; 0xC], pub evflags: ReadWrite<u32>, } pub struct GPIOPin { registers: StaticRef<GpioRegisters>, ioc_registers: StaticRef<IocRegisters>, pin: usize, pin_mask: u32, client_data: Cell<usize>, client: OptionalCell<&'static hil::gpio::Client>, } impl GPIOPin { const fn new(pin: usize) -> GPIOPin { GPIOPin { registers: GPIO_BASE, ioc_registers: IOC_BASE, pin: pin, pin_mask: 1 << pin, client_data: Cell::new(0), client: OptionalCell::empty(), } } pub fn set_client<C: hil::gpio::Client>(&self, client: &'static C) { self.client.set(client); } pub fn handle_interrupt(&self) { self.client.map(|client| { client.fired(self.client_data.get()); }); } } #[repr(C)] struct IocRegisters { iocfg: [ReadWrite<u32, IoConfiguration::Register>; 32], } register_bitfields![ u32, IoConfiguration [ IE OFFSET(29) NUMBITS(1) [], // Input Enable IO_MODE OFFSET(24) NUMBITS(3) [], EDGE_IRQ_EN OFFSET(18) NUMBITS(1) [], // Interrupt enable EDGE_DET OFFSET(16) NUMBITS(2) [ None = 0b00, NegativeEdge = 0b01, PositiveEdge = 0b10, EitherEdge = 0b11 ], PULL_CTL OFFSET(13) NUMBITS(2) [ PullDown = 0b01, PullUp = 0b10, PullNone = 0b11 ], PORT_ID OFFSET(0) NUMBITS(6) [ // From p.1072 GPIO = 0, AON_CLK32K = 7, AUX_DOMAIN_IO = 8, SSI0_RX = 9, SSI0_TX = 10, SSI0_FSS = 11, SSI0_CLK = 12, I2C_MSSDA = 13, I2C_MSSCL = 14, UART0_RX = 15, UART0_TX = 16, UART0_CTS = 17, UART0_RTS = 18, UART1_RX = 19, UART1_TX = 20, UART1_CTS = 21, UART1_RTS = 22, PORT_EVENT0 = 23, PORT_EVENT1 = 24, PORT_EVENT2 = 25, PORT_EVENT3 = 26, PORT_EVENT4 = 27, PORT_EVENT5 = 28, PORT_EVENT6 = 29, PORT_EVENT7 = 30, CPU_SWV = 32, SSI1_RX = 33, SSI1_TX = 34, SSI1_FSS = 35, SSI1_CLK = 36, I2S_AD0 = 37, I2S_AD1 = 38, I2S_WCLK = 39, I2S_BCLK = 40, I2S_MCLK = 41, RFC_GPO0 = 47, RFC_GPO1 = 48, RFC_GPO2 = 49, RFC_GPO3 = 50 ] ] ]; /// Pinmux implementation (IOC) impl GPIOPin { pub fn enable_gpio(&self) { let pin_ioc = &self.ioc_registers.iocfg[self.pin]; // In order to configure the pin for GPIO we need to clear // the lower 6 bits. pin_ioc.write(IoConfiguration::PORT_ID::GPIO); } pub fn enable_output(&self) { // Enable by disabling input let pin_ioc = &self.ioc_registers.iocfg[self.pin]; pin_ioc.modify(IoConfiguration::IE::CLEAR); } pub fn enable_input(&self) { // Set IE (Input Enable) bit let pin_ioc = &self.ioc_registers.iocfg[self.pin]; pin_ioc.modify(IoConfiguration::IE::SET); } pub fn enable_interrupt(&self, mode: hil::gpio::InterruptMode) { let pin_ioc = &self.ioc_registers.iocfg[self.pin]; let ioc_edge_mode = match mode { hil::gpio::InterruptMode::FallingEdge => IoConfiguration::EDGE_DET::NegativeEdge, hil::gpio::InterruptMode::RisingEdge => IoConfiguration::EDGE_DET::PositiveEdge, hil::gpio::InterruptMode::EitherEdge => IoConfiguration::EDGE_DET::EitherEdge, }; pin_ioc.modify(ioc_edge_mode + IoConfiguration::EDGE_IRQ_EN::SET); } pub fn disable_interrupt(&self) { let pin_ioc = &self.ioc_registers.iocfg[self.pin]; pin_ioc.modify(IoConfiguration::EDGE_IRQ_EN::CLEAR); } /// Configures pin for I2C SDA pub fn enable_i2c_sda(&self) { let pin_ioc = &self.ioc_registers.iocfg[self.pin]; pin_ioc.modify( IoConfiguration::PORT_ID::I2C_MSSDA + IoConfiguration::IO_MODE.val(0x4) + IoConfiguration::PULL_CTL::PullUp, ); self.enable_input(); } /// Configures pin for I2C SDA pub fn enable_i2c_scl(&self) { let pin_ioc = &self.ioc_registers.iocfg[self.pin];
pin_ioc.modify( IoConfiguration::PORT_ID::I2C_MSSCL + IoConfiguration::IO_MODE.val(0x4) + IoConfiguration::PULL_CTL::PullUp, ); // TODO(alevy): I couldn't find any justification for enabling input mode in the datasheet, // but I2C master seems not to work without it. Maybe it's important for multi-master mode, // or for allowing a slave to stretch the clock, but in any case, I2C master won't actually // output anything without this line. self.enable_input(); } /// Configures pin for UART0 receive (RX). pub fn enable_uart0_rx(&self) { let pin_ioc = &self.ioc_registers.iocfg[self.pin]; pin_ioc.modify(IoConfiguration::PORT_ID::UART0_RX); self.set_input_mode(hil::gpio::InputMode::PullNone); self.enable_input(); } // Configures pin for UART0 transmit (TX). pub fn enable_uart0_tx(&self) { let pin_ioc = &self.ioc_registers.iocfg[self.pin]; pin_ioc.modify(IoConfiguration::PORT_ID::UART0_TX); self.set_input_mode(hil::gpio::InputMode::PullNone); self.enable_output(); } // Configures pin for UART1 receive (RX). pub fn enable_uart1_rx(&self) { let pin_ioc = &self.ioc_registers.iocfg[self.pin]; pin_ioc.modify(IoConfiguration::PORT_ID::UART1_RX); self.set_input_mode(hil::gpio::InputMode::PullNone); self.enable_input(); } // Configures pin for UART1 transmit (TX). pub fn enable_uart1_tx(&self) { let pin_ioc = &self.ioc_registers.iocfg[self.pin]; pin_ioc.modify(IoConfiguration::PORT_ID::UART1_TX); self.set_input_mode(hil::gpio::InputMode::PullNone); self.enable_output(); } } impl hil::gpio::PinCtl for GPIOPin { fn set_input_mode(&self, mode: hil::gpio::InputMode) { let pin_ioc = &self.ioc_registers.iocfg[self.pin]; let field = match mode { hil::gpio::InputMode::PullDown => IoConfiguration::PULL_CTL::PullDown, hil::gpio::InputMode::PullUp => IoConfiguration::PULL_CTL::PullUp, hil::gpio::InputMode::PullNone => IoConfiguration::PULL_CTL::PullNone, }; pin_ioc.modify(field); } } impl hil::gpio::Pin for GPIOPin { fn make_output(&self) { self.enable_gpio(); // Disable input in the io configuration self.enable_output(); // Enable data output let regs = &*self.registers; regs.doe.set(regs.doe.get() | self.pin_mask); } fn make_input(&self) { self.enable_gpio(); self.enable_input(); } fn disable(&self) { hil::gpio::PinCtl::set_input_mode(self, hil::gpio::InputMode::PullNone); } fn set(&self) { let regs = &*self.registers; regs.dout_set.set(self.pin_mask); } fn clear(&self) { let regs = &*self.registers; regs.dout_clr.set(self.pin_mask); } fn toggle(&self) { let regs = &*self.registers; regs.dout_tgl.set(self.pin_mask); } fn read(&self) -> bool { let regs = &*self.registers; regs.din.get() & self.pin_mask != 0 } fn enable_interrupt(&self, client_data: usize, mode: hil::gpio::InterruptMode) { self.client_data.set(client_data); self.enable_interrupt(mode); } fn disable_interrupt(&self) { self.disable_interrupt(); } } pub struct Port { pins: [GPIOPin; NUM_PINS], } impl Index<usize> for Port { type Output = GPIOPin; fn index(&self, index: usize) -> &GPIOPin { &self.pins[index] } } impl IndexMut<usize> for Port { fn index_mut(&mut self, index: usize) -> &mut GPIOPin { &mut self.pins[index] } } impl Port { pub fn handle_interrupt(&self) { let regs = GPIO_BASE; let evflags = regs.evflags.get(); // Clear all interrupts by setting their bits to 1 in evflags regs.evflags.set(evflags); // evflags indicate which pins has triggered an interrupt, // we need to call the respective handler for positive bit in evflags. let mut pin: usize = usize::max_value(); while pin < self.pins.len() { pin = evflags.trailing_zeros() as usize; if pin >= self.pins.len() { break; } self.pins[pin].handle_interrupt(); } } } pub static mut PORT: Port = Port { pins: [ GPIOPin::new(0), GPIOPin::new(1), GPIOPin::new(2), GPIOPin::new(3), GPIOPin::new(4), GPIOPin::new(5), GPIOPin::new(6), GPIOPin::new(7), GPIOPin::new(8), GPIOPin::new(9), GPIOPin::new(10), GPIOPin::new(11), GPIOPin::new(12), GPIOPin::new(13), GPIOPin::new(14), GPIOPin::new(15), GPIOPin::new(16), GPIOPin::new(17), GPIOPin::new(18), GPIOPin::new(19), GPIOPin::new(20), GPIOPin::new(21), GPIOPin::new(22), GPIOPin::new(23), GPIOPin::new(24), GPIOPin::new(25), GPIOPin::new(26), GPIOPin::new(27), GPIOPin::new(28), GPIOPin::new(29), GPIOPin::new(30), GPIOPin::new(31), ], };
test_unicode.py
""" Test script for the Unicode implementation. Written by Marc-Andre Lemburg ([email protected]). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import _string import codecs import itertools import operator import struct import string import sys import unittest import warnings from test import support, string_tests # Error handling (bad decoder return) def search_function(encoding): def decode1(input, errors="strict"): return 42 # not a tuple def encode1(input, errors="strict"): return 42 # not a tuple def encode2(input, errors="strict"): return (42, 42) # no unicode def decode2(input, errors="strict"): return (42, 42) # no unicode if encoding=="test.unicode1": return (encode1, decode1, None, None) elif encoding=="test.unicode2": return (encode2, decode2, None, None) else: return None codecs.register(search_function) def duplicate_string(text): """ Try to get a fresh clone of the specified text: new object with a reference count of 1. This is a best-effort: latin1 single letters and the empty string ('') are singletons and cannot be cloned. """ return text.encode().decode() class StrSubclass(str): pass class UnicodeTest(string_tests.CommonTest, string_tests.MixinStrUnicodeUserStringTest, string_tests.MixinStrUnicodeTest, unittest.TestCase): type2test = str def checkequalnofix(self, result, object, methodname, *args): method = getattr(object, methodname) realresult = method(*args) self.assertEqual(realresult, result) self.assertTrue(type(realresult) is type(result)) # if the original is returned make sure that # this doesn't happen with subclasses if realresult is object: class usub(str): def __repr__(self): return 'usub(%r)' % str.__repr__(self) object = usub(object) method = getattr(object, methodname) realresult = method(*args) self.assertEqual(realresult, result) self.assertTrue(object is not realresult) def test_literals(self): self.assertEqual('\xff', '\u00ff') self.assertEqual('\uffff', '\U0000ffff') self.assertRaises(SyntaxError, eval, '\'\\Ufffffffe\'') self.assertRaises(SyntaxError, eval, '\'\\Uffffffff\'') self.assertRaises(SyntaxError, eval, '\'\\U%08x\'' % 0x110000) # raw strings should not have unicode escapes self.assertNotEqual(r"\u0020", " ") def test_ascii(self): if not sys.platform.startswith('java'): # Test basic sanity of repr() self.assertEqual(ascii('abc'), "'abc'") self.assertEqual(ascii('ab\\c'), "'ab\\\\c'") self.assertEqual(ascii('ab\\'), "'ab\\\\'") self.assertEqual(ascii('\\c'), "'\\\\c'") self.assertEqual(ascii('\\'), "'\\\\'") self.assertEqual(ascii('\n'), "'\\n'") self.assertEqual(ascii('\r'), "'\\r'") self.assertEqual(ascii('\t'), "'\\t'") self.assertEqual(ascii('\b'), "'\\x08'") self.assertEqual(ascii("'\""), """'\\'"'""") self.assertEqual(ascii("'\""), """'\\'"'""") self.assertEqual(ascii("'"), '''"'"''') self.assertEqual(ascii('"'), """'"'""") latin1repr = ( "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r" "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a" "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI" "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f" "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d" "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b" "\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9" "\\xaa\\xab\\xac\\xad\\xae\\xaf\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7" "\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5" "\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3" "\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1" "\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef" "\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd" "\\xfe\\xff'") testrepr = ascii(''.join(map(chr, range(256)))) self.assertEqual(testrepr, latin1repr) # Test ascii works on wide unicode escapes without overflow. self.assertEqual(ascii("\U00010000" * 39 + "\uffff" * 4096), ascii("\U00010000" * 39 + "\uffff" * 4096)) class WrongRepr: def __repr__(self): return b'byte-repr' self.assertRaises(TypeError, ascii, WrongRepr()) def test_repr(self): if not sys.platform.startswith('java'): # Test basic sanity of repr() self.assertEqual(repr('abc'), "'abc'") self.assertEqual(repr('ab\\c'), "'ab\\\\c'") self.assertEqual(repr('ab\\'), "'ab\\\\'") self.assertEqual(repr('\\c'), "'\\\\c'") self.assertEqual(repr('\\'), "'\\\\'") self.assertEqual(repr('\n'), "'\\n'") self.assertEqual(repr('\r'), "'\\r'") self.assertEqual(repr('\t'), "'\\t'") self.assertEqual(repr('\b'), "'\\x08'") self.assertEqual(repr("'\""), """'\\'"'""") self.assertEqual(repr("'\""), """'\\'"'""") self.assertEqual(repr("'"), '''"'"''') self.assertEqual(repr('"'), """'"'""") latin1repr = ( "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r" "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a" "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI" "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f" "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d" "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b" "\\x9c\\x9d\\x9e\\x9f\\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9" "\xaa\xab\xac\\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7" "\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5" "\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3" "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1" "\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef" "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd" "\xfe\xff'") testrepr = repr(''.join(map(chr, range(256)))) self.assertEqual(testrepr, latin1repr) # Test repr works on wide unicode escapes without overflow. self.assertEqual(repr("\U00010000" * 39 + "\uffff" * 4096), repr("\U00010000" * 39 + "\uffff" * 4096)) class WrongRepr: def __repr__(self): return b'byte-repr' self.assertRaises(TypeError, repr, WrongRepr()) def test_iterators(self): # Make sure unicode objects have an __iter__ method it = "\u1111\u2222\u3333".__iter__() self.assertEqual(next(it), "\u1111") self.assertEqual(next(it), "\u2222") self.assertEqual(next(it), "\u3333") self.assertRaises(StopIteration, next, it) def test_count(self): string_tests.CommonTest.test_count(self) # check mixed argument types self.checkequalnofix(3, 'aaa', 'count', 'a') self.checkequalnofix(0, 'aaa', 'count', 'b') self.checkequalnofix(3, 'aaa', 'count', 'a') self.checkequalnofix(0, 'aaa', 'count', 'b') self.checkequalnofix(0, 'aaa', 'count', 'b') self.checkequalnofix(1, 'aaa', 'count', 'a', -1) self.checkequalnofix(3, 'aaa', 'count', 'a', -10) self.checkequalnofix(2, 'aaa', 'count', 'a', 0, -1) self.checkequalnofix(0, 'aaa', 'count', 'a', 0, -10) # test mixed kinds self.checkequal(10, '\u0102' + 'a' * 10, 'count', 'a') self.checkequal(10, '\U00100304' + 'a' * 10, 'count', 'a') self.checkequal(10, '\U00100304' + '\u0102' * 10, 'count', '\u0102') self.checkequal(0, 'a' * 10, 'count', '\u0102') self.checkequal(0, 'a' * 10, 'count', '\U00100304') self.checkequal(0, '\u0102' * 10, 'count', '\U00100304') self.checkequal(10, '\u0102' + 'a_' * 10, 'count', 'a_') self.checkequal(10, '\U00100304' + 'a_' * 10, 'count', 'a_') self.checkequal(10, '\U00100304' + '\u0102_' * 10, 'count', '\u0102_') self.checkequal(0, 'a' * 10, 'count', 'a\u0102') self.checkequal(0, 'a' * 10, 'count', 'a\U00100304') self.checkequal(0, '\u0102' * 10, 'count', '\u0102\U00100304') def test_find(self): string_tests.CommonTest.test_find(self) # test implementation details of the memchr fast path self.checkequal(100, 'a' * 100 + '\u0102', 'find', '\u0102') self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0201') self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0120') self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0220') self.checkequal(100, 'a' * 100 + '\U00100304', 'find', '\U00100304') self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00100204') self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00102004') # check mixed argument types self.checkequalnofix(0, 'abcdefghiabc', 'find', 'abc') self.checkequalnofix(9, 'abcdefghiabc', 'find', 'abc', 1) self.checkequalnofix(-1, 'abcdefghiabc', 'find', 'def', 4) self.assertRaises(TypeError, 'hello'.find) self.assertRaises(TypeError, 'hello'.find, 42) # test mixed kinds self.checkequal(100, '\u0102' * 100 + 'a', 'find', 'a') self.checkequal(100, '\U00100304' * 100 + 'a', 'find', 'a') self.checkequal(100, '\U00100304' * 100 + '\u0102', 'find', '\u0102') self.checkequal(-1, 'a' * 100, 'find', '\u0102') self.checkequal(-1, 'a' * 100, 'find', '\U00100304') self.checkequal(-1, '\u0102' * 100, 'find', '\U00100304') self.checkequal(100, '\u0102' * 100 + 'a_', 'find', 'a_') self.checkequal(100, '\U00100304' * 100 + 'a_', 'find', 'a_') self.checkequal(100, '\U00100304' * 100 + '\u0102_', 'find', '\u0102_') self.checkequal(-1, 'a' * 100, 'find', 'a\u0102') self.checkequal(-1, 'a' * 100, 'find', 'a\U00100304') self.checkequal(-1, '\u0102' * 100, 'find', '\u0102\U00100304') def test_rfind(self): string_tests.CommonTest.test_rfind(self) # test implementation details of the memrchr fast path self.checkequal(0, '\u0102' + 'a' * 100 , 'rfind', '\u0102') self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0201') self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0120') self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0220') self.checkequal(0, '\U00100304' + 'a' * 100, 'rfind', '\U00100304') self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00100204') self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00102004') # check mixed argument types self.checkequalnofix(9, 'abcdefghiabc', 'rfind', 'abc') self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '') self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '') # test mixed kinds self.checkequal(0, 'a' + '\u0102' * 100, 'rfind', 'a') self.checkequal(0, 'a' + '\U00100304' * 100, 'rfind', 'a') self.checkequal(0, '\u0102' + '\U00100304' * 100, 'rfind', '\u0102') self.checkequal(-1, 'a' * 100, 'rfind', '\u0102') self.checkequal(-1, 'a' * 100, 'rfind', '\U00100304') self.checkequal(-1, '\u0102' * 100, 'rfind', '\U00100304') self.checkequal(0, '_a' + '\u0102' * 100, 'rfind', '_a') self.checkequal(0, '_a' + '\U00100304' * 100, 'rfind', '_a') self.checkequal(0, '_\u0102' + '\U00100304' * 100, 'rfind', '_\u0102') self.checkequal(-1, 'a' * 100, 'rfind', '\u0102a') self.checkequal(-1, 'a' * 100, 'rfind', '\U00100304a') self.checkequal(-1, '\u0102' * 100, 'rfind', '\U00100304\u0102') def test_index(self): string_tests.CommonTest.test_index(self) self.checkequalnofix(0, 'abcdefghiabc', 'index', '') self.checkequalnofix(3, 'abcdefghiabc', 'index', 'def') self.checkequalnofix(0, 'abcdefghiabc', 'index', 'abc') self.checkequalnofix(9, 'abcdefghiabc', 'index', 'abc', 1) self.assertRaises(ValueError, 'abcdefghiabc'.index, 'hib') self.assertRaises(ValueError, 'abcdefghiab'.index, 'abc', 1) self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', 8) self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', -1) # test mixed kinds self.checkequal(100, '\u0102' * 100 + 'a', 'index', 'a') self.checkequal(100, '\U00100304' * 100 + 'a', 'index', 'a') self.checkequal(100, '\U00100304' * 100 + '\u0102', 'index', '\u0102') self.assertRaises(ValueError, ('a' * 100).index, '\u0102') self.assertRaises(ValueError, ('a' * 100).index, '\U00100304') self.assertRaises(ValueError, ('\u0102' * 100).index, '\U00100304') self.checkequal(100, '\u0102' * 100 + 'a_', 'index', 'a_') self.checkequal(100, '\U00100304' * 100 + 'a_', 'index', 'a_') self.checkequal(100, '\U00100304' * 100 + '\u0102_', 'index', '\u0102_') self.assertRaises(ValueError, ('a' * 100).index, 'a\u0102') self.assertRaises(ValueError, ('a' * 100).index, 'a\U00100304') self.assertRaises(ValueError, ('\u0102' * 100).index, '\u0102\U00100304') def test_rindex(self): string_tests.CommonTest.test_rindex(self) self.checkequalnofix(12, 'abcdefghiabc', 'rindex', '') self.checkequalnofix(3, 'abcdefghiabc', 'rindex', 'def') self.checkequalnofix(9, 'abcdefghiabc', 'rindex', 'abc') self.checkequalnofix(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1) self.assertRaises(ValueError, 'abcdefghiabc'.rindex, 'hib') self.assertRaises(ValueError, 'defghiabc'.rindex, 'def', 1) self.assertRaises(ValueError, 'defghiabc'.rindex, 'abc', 0, -1) self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, 8) self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, -1) # test mixed kinds self.checkequal(0, 'a' + '\u0102' * 100, 'rindex', 'a') self.checkequal(0, 'a' + '\U00100304' * 100, 'rindex', 'a') self.checkequal(0, '\u0102' + '\U00100304' * 100, 'rindex', '\u0102') self.assertRaises(ValueError, ('a' * 100).rindex, '\u0102') self.assertRaises(ValueError, ('a' * 100).rindex, '\U00100304') self.assertRaises(ValueError, ('\u0102' * 100).rindex, '\U00100304') self.checkequal(0, '_a' + '\u0102' * 100, 'rindex', '_a') self.checkequal(0, '_a' + '\U00100304' * 100, 'rindex', '_a') self.checkequal(0, '_\u0102' + '\U00100304' * 100, 'rindex', '_\u0102') self.assertRaises(ValueError, ('a' * 100).rindex, '\u0102a') self.assertRaises(ValueError, ('a' * 100).rindex, '\U00100304a') self.assertRaises(ValueError, ('\u0102' * 100).rindex, '\U00100304\u0102') def test_maketrans_translate(self): # these work with plain translate() self.checkequalnofix('bbbc', 'abababc', 'translate', {ord('a'): None}) self.checkequalnofix('iiic', 'abababc', 'translate', {ord('a'): None, ord('b'): ord('i')}) self.checkequalnofix('iiix', 'abababc', 'translate', {ord('a'): None, ord('b'): ord('i'), ord('c'): 'x'}) self.checkequalnofix('c', 'abababc', 'translate', {ord('a'): None, ord('b'): ''}) self.checkequalnofix('xyyx', 'xzx', 'translate', {ord('z'): 'yy'}) # this needs maketrans() self.checkequalnofix('abababc', 'abababc', 'translate', {'b': '<i>'}) tbl = self.type2test.maketrans({'a': None, 'b': '<i>'}) self.checkequalnofix('<i><i><i>c', 'abababc', 'translate', tbl) # test alternative way of calling maketrans() tbl = self.type2test.maketrans('abc', 'xyz', 'd') self.checkequalnofix('xyzzy', 'abdcdcbdddd', 'translate', tbl) # various tests switching from ASCII to latin1 or the opposite; # same length, remove a letter, or replace with a longer string. self.assertEqual("[a]".translate(str.maketrans('a', 'X')), "[X]") self.assertEqual("[a]".translate(str.maketrans({'a': 'X'})), "[X]") self.assertEqual("[a]".translate(str.maketrans({'a': None})), "[]") self.assertEqual("[a]".translate(str.maketrans({'a': 'XXX'})), "[XXX]") self.assertEqual("[a]".translate(str.maketrans({'a': '\xe9'})), "[\xe9]") self.assertEqual('axb'.translate(str.maketrans({'a': None, 'b': '123'})), "x123") self.assertEqual('axb'.translate(str.maketrans({'a': None, 'b': '\xe9'})), "x\xe9") # test non-ASCII (don't take the fast-path) self.assertEqual("[a]".translate(str.maketrans({'a': '<\xe9>'})), "[<\xe9>]") self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': 'a'})), "[a]") self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': None})), "[]") self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': '123'})), "[123]") self.assertEqual("[a\xe9]".translate(str.maketrans({'a': '<\u20ac>'})), "[<\u20ac>\xe9]") # invalid Unicode characters invalid_char = 0x10ffff+1 for before in "a\xe9\u20ac\U0010ffff": mapping = str.maketrans({before: invalid_char}) text = "[%s]" % before self.assertRaises(ValueError, text.translate, mapping) # errors self.assertRaises(TypeError, self.type2test.maketrans) self.assertRaises(ValueError, self.type2test.maketrans, 'abc', 'defg') self.assertRaises(TypeError, self.type2test.maketrans, 2, 'def') self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 2) self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 'def', 2) self.assertRaises(ValueError, self.type2test.maketrans, {'xy': 2}) self.assertRaises(TypeError, self.type2test.maketrans, {(1,): 2}) self.assertRaises(TypeError, 'hello'.translate) self.assertRaises(TypeError, 'abababc'.translate, 'abc', 'xyz') def test_split(self): string_tests.CommonTest.test_split(self) # test mixed kinds for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'): left *= 9 right *= 9 for delim in ('c', '\u0102', '\U00010302'): self.checkequal([left + right], left + right, 'split', delim) self.checkequal([left, right], left + delim + right, 'split', delim) self.checkequal([left + right], left + right, 'split', delim * 2) self.checkequal([left, right], left + delim * 2 + right, 'split', delim *2) def test_rsplit(self): string_tests.CommonTest.test_rsplit(self) # test mixed kinds for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'): left *= 9 right *= 9 for delim in ('c', '\u0102', '\U00010302'): self.checkequal([left + right], left + right, 'rsplit', delim) self.checkequal([left, right], left + delim + right, 'rsplit', delim) self.checkequal([left + right], left + right, 'rsplit', delim * 2) self.checkequal([left, right], left + delim * 2 + right, 'rsplit', delim *2) def test_partition(self): string_tests.MixinStrUnicodeUserStringTest.test_partition(self) # test mixed kinds self.checkequal(('ABCDEFGH', '', ''), 'ABCDEFGH', 'partition', '\u4200') for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'): left *= 9 right *= 9 for delim in ('c', '\u0102', '\U00010302'): self.checkequal((left + right, '', ''), left + right, 'partition', delim) self.checkequal((left, delim, right), left + delim + right, 'partition', delim) self.checkequal((left + right, '', ''), left + right, 'partition', delim * 2) self.checkequal((left, delim * 2, right), left + delim * 2 + right, 'partition', delim * 2) def test_rpartition(self): string_tests.MixinStrUnicodeUserStringTest.test_rpartition(self) # test mixed kinds self.checkequal(('', '', 'ABCDEFGH'), 'ABCDEFGH', 'rpartition', '\u4200') for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'): left *= 9 right *= 9 for delim in ('c', '\u0102', '\U00010302'): self.checkequal(('', '', left + right), left + right, 'rpartition', delim) self.checkequal((left, delim, right), left + delim + right, 'rpartition', delim) self.checkequal(('', '', left + right), left + right, 'rpartition', delim * 2) self.checkequal((left, delim * 2, right), left + delim * 2 + right, 'rpartition', delim * 2) def test_join(self): string_tests.MixinStrUnicodeUserStringTest.test_join(self) class MyWrapper: def __init__(self, sval): self.sval = sval def __str__(self): return self.sval # mixed arguments self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd']) self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd')) self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz')) self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd']) self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd']) self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd')) self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz')) self.checkraises(TypeError, ' ', 'join', ['1', '2', MyWrapper('foo')]) self.checkraises(TypeError, ' ', 'join', ['1', '2', '3', bytes()]) self.checkraises(TypeError, ' ', 'join', [1, 2, 3]) self.checkraises(TypeError, ' ', 'join', ['1', '2', 3]) @unittest.skipIf(sys.maxsize > 2**32, 'needs too much memory on a 64-bit platform') def test_join_overflow(self): size = int(sys.maxsize**0.5) + 1 seq = ('A' * size,) * size self.assertRaises(OverflowError, ''.join, seq) def test_replace(self): string_tests.CommonTest.test_replace(self) # method call forwarded from str implementation because of unicode argument self.checkequalnofix('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1) self.assertRaises(TypeError, 'replace'.replace, "r", 42) # test mixed kinds for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'): left *= 9 right *= 9 for delim in ('c', '\u0102', '\U00010302'): for repl in ('d', '\u0103', '\U00010303'): self.checkequal(left + right, left + right, 'replace', delim, repl) self.checkequal(left + repl + right, left + delim + right, 'replace', delim, repl) self.checkequal(left + right, left + right, 'replace', delim * 2, repl) self.checkequal(left + repl + right, left + delim * 2 + right, 'replace', delim * 2, repl) @support.cpython_only def test_replace_id(self): pattern = 'abc' text = 'abc def' self.assertIs(text.replace(pattern, pattern), text) def test_bytes_comparison(self): with support.check_warnings(): warnings.simplefilter('ignore', BytesWarning) self.assertEqual('abc' == b'abc', False) self.assertEqual('abc' != b'abc', True) self.assertEqual('abc' == bytearray(b'abc'), False) self.assertEqual('abc' != bytearray(b'abc'), True) def test_comparison(self): # Comparisons: self.assertEqual('abc', 'abc') self.assertTrue('abcd' > 'abc') self.assertTrue('abc' < 'abcd') if 0: # Move these tests to a Unicode collation module test... # Testing UTF-16 code point order comparisons... # No surrogates, no fixup required. self.assertTrue('\u0061' < '\u20ac') # Non surrogate below surrogate value, no fixup required self.assertTrue('\u0061' < '\ud800\udc02') # Non surrogate above surrogate value, fixup required def test_lecmp(s, s2): self.assertTrue(s < s2) def test_fixup(s): s2 = '\ud800\udc01' test_lecmp(s, s2) s2 = '\ud900\udc01' test_lecmp(s, s2) s2 = '\uda00\udc01' test_lecmp(s, s2) s2 = '\udb00\udc01' test_lecmp(s, s2) s2 = '\ud800\udd01' test_lecmp(s, s2) s2 = '\ud900\udd01' test_lecmp(s, s2) s2 = '\uda00\udd01' test_lecmp(s, s2) s2 = '\udb00\udd01' test_lecmp(s, s2) s2 = '\ud800\ude01' test_lecmp(s, s2) s2 = '\ud900\ude01' test_lecmp(s, s2) s2 = '\uda00\ude01' test_lecmp(s, s2) s2 = '\udb00\ude01' test_lecmp(s, s2) s2 = '\ud800\udfff' test_lecmp(s, s2) s2 = '\ud900\udfff' test_lecmp(s, s2) s2 = '\uda00\udfff' test_lecmp(s, s2) s2 = '\udb00\udfff' test_lecmp(s, s2) test_fixup('\ue000') test_fixup('\uff61') # Surrogates on both sides, no fixup required self.assertTrue('\ud800\udc02' < '\ud84d\udc56') def test_islower(self): super().test_islower() self.checkequalnofix(False, '\u1FFc', 'islower') self.assertFalse('\u2167'.islower()) self.assertTrue('\u2177'.islower()) # non-BMP, uppercase self.assertFalse('\U00010401'.islower()) self.assertFalse('\U00010427'.islower()) # non-BMP, lowercase self.assertTrue('\U00010429'.islower()) self.assertTrue('\U0001044E'.islower()) # non-BMP, non-cased self.assertFalse('\U0001F40D'.islower()) self.assertFalse('\U0001F46F'.islower()) def test_isupper(self): super().test_isupper() if not sys.platform.startswith('java'): self.checkequalnofix(False, '\u1FFc', 'isupper') self.assertTrue('\u2167'.isupper()) self.assertFalse('\u2177'.isupper()) # non-BMP, uppercase self.assertTrue('\U00010401'.isupper()) self.assertTrue('\U00010427'.isupper()) # non-BMP, lowercase self.assertFalse('\U00010429'.isupper()) self.assertFalse('\U0001044E'.isupper()) # non-BMP, non-cased self.assertFalse('\U0001F40D'.isupper()) self.assertFalse('\U0001F46F'.isupper()) def test_istitle(self): super().test_istitle() self.checkequalnofix(True, '\u1FFc', 'istitle') self.checkequalnofix(True, 'Greek \u1FFcitlecases ...', 'istitle') # non-BMP, uppercase + lowercase self.assertTrue('\U00010401\U00010429'.istitle()) self.assertTrue('\U00010427\U0001044E'.istitle()) # apparently there are no titlecased (Lt) non-BMP chars in Unicode 6 for ch in ['\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F']: self.assertFalse(ch.istitle(), '{!a} is not title'.format(ch)) def test_isspace(self): super().test_isspace() self.checkequalnofix(True, '\u2000', 'isspace') self.checkequalnofix(True, '\u200a', 'isspace') self.checkequalnofix(False, '\u2014', 'isspace') # apparently there are no non-BMP spaces chars in Unicode 6 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F']: self.assertFalse(ch.isspace(), '{!a} is not space.'.format(ch)) def test_isalnum(self): super().test_isalnum() for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E', '\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']: self.assertTrue(ch.isalnum(), '{!a} is alnum.'.format(ch)) def test_isalpha(self): super().test_isalpha() self.checkequalnofix(True, '\u1FFc', 'isalpha') # non-BMP, cased self.assertTrue('\U00010401'.isalpha()) self.assertTrue('\U00010427'.isalpha()) self.assertTrue('\U00010429'.isalpha()) self.assertTrue('\U0001044E'.isalpha()) # non-BMP, non-cased self.assertFalse('\U0001F40D'.isalpha()) self.assertFalse('\U0001F46F'.isalpha()) def test_isdecimal(self): self.checkequalnofix(False, '', 'isdecimal') self.checkequalnofix(False, 'a', 'isdecimal') self.checkequalnofix(True, '0', 'isdecimal') self.checkequalnofix(False, '\u2460', 'isdecimal') # CIRCLED DIGIT ONE self.checkequalnofix(False, '\xbc', 'isdecimal') # VULGAR FRACTION ONE QUARTER self.checkequalnofix(True, '\u0660', 'isdecimal') # ARABIC-INDIC DIGIT ZERO self.checkequalnofix(True, '0123456789', 'isdecimal') self.checkequalnofix(False, '0123456789a', 'isdecimal') self.checkraises(TypeError, 'abc', 'isdecimal', 42) for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F', '\U00011065', '\U0001F107']: self.assertFalse(ch.isdecimal(), '{!a} is not decimal.'.format(ch)) for ch in ['\U0001D7F6', '\U00011066', '\U000104A0']: self.assertTrue(ch.isdecimal(), '{!a} is decimal.'.format(ch)) def test_isdigit(self): super().test_isdigit() self.checkequalnofix(True, '\u2460', 'isdigit') self.checkequalnofix(False, '\xbc', 'isdigit') self.checkequalnofix(True, '\u0660', 'isdigit') for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F', '\U00011065']: self.assertFalse(ch.isdigit(), '{!a} is not a digit.'.format(ch)) for ch in ['\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']: self.assertTrue(ch.isdigit(), '{!a} is a digit.'.format(ch)) def test_isnumeric(self): self.checkequalnofix(False, '', 'isnumeric') self.checkequalnofix(False, 'a', 'isnumeric') self.checkequalnofix(True, '0', 'isnumeric') self.checkequalnofix(True, '\u2460', 'isnumeric') self.checkequalnofix(True, '\xbc', 'isnumeric') self.checkequalnofix(True, '\u0660', 'isnumeric') self.checkequalnofix(True, '0123456789', 'isnumeric') self.checkequalnofix(False, '0123456789a', 'isnumeric') self.assertRaises(TypeError, "abc".isnumeric, 42) for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F']: self.assertFalse(ch.isnumeric(), '{!a} is not numeric.'.format(ch)) for ch in ['\U00011065', '\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']: self.assertTrue(ch.isnumeric(), '{!a} is numeric.'.format(ch)) def test_isidentifier(self): self.assertTrue("a".isidentifier()) self.assertTrue("Z".isidentifier()) self.assertTrue("_".isidentifier()) self.assertTrue("b0".isidentifier()) self.assertTrue("bc".isidentifier()) self.assertTrue("b_".isidentifier()) self.assertTrue("µ".isidentifier()) self.assertTrue("𝔘𝔫𝔦𝔠𝔬𝔡𝔢".isidentifier()) self.assertFalse(" ".isidentifier()) self.assertFalse("[".isidentifier()) self.assertFalse("©".isidentifier()) self.assertFalse("0".isidentifier()) def test_isprintable(self): self.assertTrue("".isprintable()) self.assertTrue(" ".isprintable()) self.assertTrue("abcdefg".isprintable()) self.assertFalse("abcdefg\n".isprintable()) # some defined Unicode character self.assertTrue("\u0374".isprintable()) # undefined character self.assertFalse("\u0378".isprintable()) # single surrogate character self.assertFalse("\ud800".isprintable()) self.assertTrue('\U0001F46F'.isprintable()) self.assertFalse('\U000E0020'.isprintable()) def test_surrogates(self): for s in ('a\uD800b\uDFFF', 'a\uDFFFb\uD800', 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'): self.assertTrue(s.islower()) self.assertFalse(s.isupper()) self.assertFalse(s.istitle()) for s in ('A\uD800B\uDFFF', 'A\uDFFFB\uD800', 'A\uD800B\uDFFFA', 'A\uDFFFB\uD800A'): self.assertFalse(s.islower()) self.assertTrue(s.isupper()) self.assertTrue(s.istitle()) for meth_name in ('islower', 'isupper', 'istitle'): meth = getattr(str, meth_name) for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF'): self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name)) for meth_name in ('isalpha', 'isalnum', 'isdigit', 'isspace', 'isdecimal', 'isnumeric', 'isidentifier', 'isprintable'): meth = getattr(str, meth_name) for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF', 'a\uD800b\uDFFF', 'a\uDFFFb\uD800', 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'): self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name)) def test_lower(self): string_tests.CommonTest.test_lower(self) self.assertEqual('\U00010427'.lower(), '\U0001044F') self.assertEqual('\U00010427\U00010427'.lower(), '\U0001044F\U0001044F') self.assertEqual('\U00010427\U0001044F'.lower(), '\U0001044F\U0001044F') self.assertEqual('X\U00010427x\U0001044F'.lower(), 'x\U0001044Fx\U0001044F') self.assertEqual('fi'.lower(), 'fi') self.assertEqual('\u0130'.lower(), '\u0069\u0307') # Special case for GREEK CAPITAL LETTER SIGMA U+03A3 self.assertEqual('\u03a3'.lower(), '\u03c3') self.assertEqual('\u0345\u03a3'.lower(), '\u0345\u03c3') self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2') self.assertEqual('A\u0345\u03a3a'.lower(), 'a\u0345\u03c3a') self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2') self.assertEqual('A\u03a3\u0345'.lower(), 'a\u03c2\u0345') self.assertEqual('\u03a3\u0345 '.lower(), '\u03c3\u0345 ') self.assertEqual('\U0008fffe'.lower(), '\U0008fffe') self.assertEqual('\u2177'.lower(), '\u2177') def test_casefold(self): self.assertEqual('hello'.casefold(), 'hello') self.assertEqual('hELlo'.casefold(), 'hello') self.assertEqual('ß'.casefold(), 'ss') self.assertEqual('fi'.casefold(), 'fi') self.assertEqual('\u03a3'.casefold(), '\u03c3') self.assertEqual('A\u0345\u03a3'.casefold(), 'a\u03b9\u03c3') self.assertEqual('\u00b5'.casefold(), '\u03bc') def test_upper(self): string_tests.CommonTest.test_upper(self) self.assertEqual('\U0001044F'.upper(), '\U00010427') self.assertEqual('\U0001044F\U0001044F'.upper(), '\U00010427\U00010427') self.assertEqual('\U00010427\U0001044F'.upper(), '\U00010427\U00010427') self.assertEqual('X\U00010427x\U0001044F'.upper(), 'X\U00010427X\U00010427') self.assertEqual('fi'.upper(), 'FI') self.assertEqual('\u0130'.upper(), '\u0130') self.assertEqual('\u03a3'.upper(), '\u03a3') self.assertEqual('ß'.upper(), 'SS') self.assertEqual('\u1fd2'.upper(), '\u0399\u0308\u0300') self.assertEqual('\U0008fffe'.upper(), '\U0008fffe') self.assertEqual('\u2177'.upper(), '\u2167') def test_capitalize(self): string_tests.CommonTest.test_capitalize(self) self.assertEqual('\U0001044F'.capitalize(), '\U00010427') self.assertEqual('\U0001044F\U0001044F'.capitalize(), '\U00010427\U0001044F') self.assertEqual('\U00010427\U0001044F'.capitalize(), '\U00010427\U0001044F') self.assertEqual('\U0001044F\U00010427'.capitalize(), '\U00010427\U0001044F') self.assertEqual('X\U00010427x\U0001044F'.capitalize(), 'X\U0001044Fx\U0001044F') self.assertEqual('h\u0130'.capitalize(), 'H\u0069\u0307') exp = '\u0399\u0308\u0300\u0069\u0307' self.assertEqual('\u1fd2\u0130'.capitalize(), exp) self.assertEqual('finnish'.capitalize(), 'FInnish') self.assertEqual('A\u0345\u03a3'.capitalize(), 'A\u0345\u03c2') def test_title(self): super().test_title() self.assertEqual('\U0001044F'.title(), '\U00010427') self.assertEqual('\U0001044F\U0001044F'.title(), '\U00010427\U0001044F') self.assertEqual('\U0001044F\U0001044F \U0001044F\U0001044F'.title(), '\U00010427\U0001044F \U00010427\U0001044F') self.assertEqual('\U00010427\U0001044F \U00010427\U0001044F'.title(), '\U00010427\U0001044F \U00010427\U0001044F') self.assertEqual('\U0001044F\U00010427 \U0001044F\U00010427'.title(), '\U00010427\U0001044F \U00010427\U0001044F') self.assertEqual('X\U00010427x\U0001044F X\U00010427x\U0001044F'.title(), 'X\U0001044Fx\U0001044F X\U0001044Fx\U0001044F') self.assertEqual('fiNNISH'.title(), 'Finnish') self.assertEqual('A\u03a3 \u1fa1xy'.title(), 'A\u03c2 \u1fa9xy') self.assertEqual('A\u03a3A'.title(), 'A\u03c3a') def test_swapcase(self): string_tests.CommonTest.test_swapcase(self) self.assertEqual('\U0001044F'.swapcase(), '\U00010427') self.assertEqual('\U00010427'.swapcase(), '\U0001044F') self.assertEqual('\U0001044F\U0001044F'.swapcase(), '\U00010427\U00010427') self.assertEqual('\U00010427\U0001044F'.swapcase(), '\U0001044F\U00010427') self.assertEqual('\U0001044F\U00010427'.swapcase(), '\U00010427\U0001044F') self.assertEqual('X\U00010427x\U0001044F'.swapcase(), 'x\U0001044FX\U00010427') self.assertEqual('fi'.swapcase(), 'FI') self.assertEqual('\u0130'.swapcase(), '\u0069\u0307') # Special case for GREEK CAPITAL LETTER SIGMA U+03A3 self.assertEqual('\u03a3'.swapcase(), '\u03c3') self.assertEqual('\u0345\u03a3'.swapcase(), '\u0399\u03c3') self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2') self.assertEqual('A\u0345\u03a3a'.swapcase(), 'a\u0399\u03c3A') self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2') self.assertEqual('A\u03a3\u0345'.swapcase(), 'a\u03c2\u0399') self.assertEqual('\u03a3\u0345 '.swapcase(), '\u03c3\u0399 ') self.assertEqual('\u03a3'.swapcase(), '\u03c3') self.assertEqual('ß'.swapcase(), 'SS') self.assertEqual('\u1fd2'.swapcase(), '\u0399\u0308\u0300') def test_center(self): string_tests.CommonTest.test_center(self) self.assertEqual('x'.center(2, '\U0010FFFF'), 'x\U0010FFFF') self.assertEqual('x'.center(3, '\U0010FFFF'), '\U0010FFFFx\U0010FFFF') self.assertEqual('x'.center(4, '\U0010FFFF'), '\U0010FFFFx\U0010FFFF\U0010FFFF') @unittest.skipUnless(sys.maxsize == 2**31 - 1, "requires 32-bit system") @support.cpython_only def test_case_operation_overflow(self): # Issue #22643 size = 2**32//12 + 1 try: s = "ü" * size except MemoryError: self.skipTest('no enough memory (%.0f MiB required)' % (size / 2**20)) try: self.assertRaises(OverflowError, s.upper) finally: del s def test_contains(self): # Testing Unicode contains method self.assertIn('a', 'abdb') self.assertIn('a', 'bdab') self.assertIn('a', 'bdaba') self.assertIn('a', 'bdba') self.assertNotIn('a', 'bdb') self.assertIn('a', 'bdba') self.assertIn('a', ('a',1,None)) self.assertIn('a', (1,None,'a')) self.assertIn('a', ('a',1,None)) self.assertIn('a', (1,None,'a')) self.assertNotIn('a', ('x',1,'y')) self.assertNotIn('a', ('x',1,None)) self.assertNotIn('abcd', 'abcxxxx') self.assertIn('ab', 'abcd') self.assertIn('ab', 'abc') self.assertIn('ab', (1,None,'ab')) self.assertIn('', 'abc') self.assertIn('', '') self.assertIn('', 'abc') self.assertNotIn('\0', 'abc') self.assertIn('\0', '\0abc') self.assertIn('\0', 'abc\0') self.assertIn('a', '\0abc') self.assertIn('asdf', 'asdf') self.assertNotIn('asdf', 'asd') self.assertNotIn('asdf', '') self.assertRaises(TypeError, "abc".__contains__) # test mixed kinds for fill in ('a', '\u0100', '\U00010300'): fill *= 9 for delim in ('c', '\u0102', '\U00010302'): self.assertNotIn(delim, fill) self.assertIn(delim, fill + delim) self.assertNotIn(delim * 2, fill) self.assertIn(delim * 2, fill + delim * 2) def test_issue18183(self): '\U00010000\U00100000'.lower() '\U00010000\U00100000'.casefold() '\U00010000\U00100000'.upper() '\U00010000\U00100000'.capitalize() '\U00010000\U00100000'.title() '\U00010000\U00100000'.swapcase() '\U00100000'.center(3, '\U00010000') '\U00100000'.ljust(3, '\U00010000') '\U00100000'.rjust(3, '\U00010000') def test_format(self): self.assertEqual(''.format(), '') self.assertEqual('a'.format(), 'a') self.assertEqual('ab'.format(), 'ab') self.assertEqual('a{{'.format(), 'a{') self.assertEqual('a}}'.format(), 'a}') self.assertEqual('{{b'.format(), '{b') self.assertEqual('}}b'.format(), '}b') self.assertEqual('a{{b'.format(), 'a{b') # examples from the PEP: import datetime self.assertEqual("My name is {0}".format('Fred'), "My name is Fred") self.assertEqual("My name is {0[name]}".format(dict(name='Fred')), "My name is Fred") self.assertEqual("My name is {0} :-{{}}".format('Fred'), "My name is Fred :-{}") d = datetime.date(2007, 8, 18) self.assertEqual("The year is {0.year}".format(d), "The year is 2007") # classes we'll use for testing class C: def __init__(self, x=100): self._x = x def __format__(self, spec): return spec class D: def __init__(self, x): self.x = x def __format__(self, spec): return str(self.x) # class with __str__, but no __format__ class E: def __init__(self, x): self.x = x def __str__(self): return 'E(' + self.x + ')' # class with __repr__, but no __format__ or __str__ class F: def __init__(self, x): self.x = x def __repr__(self): return 'F(' + self.x + ')' # class with __format__ that forwards to string, for some format_spec's class G: def __init__(self, x): self.x = x def __str__(self): return "string is " + self.x def __format__(self, format_spec): if format_spec == 'd': return 'G(' + self.x + ')' return object.__format__(self, format_spec) class I(datetime.date): def __format__(self, format_spec): return self.strftime(format_spec) class J(int): def __format__(self, format_spec): return int.__format__(self * 2, format_spec) class M: def __init__(self, x): self.x = x def __repr__(self): return 'M(' + self.x + ')' __str__ = None class N: def __init__(self, x): self.x = x def __repr__(self): return 'N(' + self.x + ')' __format__ = None self.assertEqual(''.format(), '') self.assertEqual('abc'.format(), 'abc') self.assertEqual('{0}'.format('abc'), 'abc') self.assertEqual('{0:}'.format('abc'), 'abc') # self.assertEqual('{ 0 }'.format('abc'), 'abc') self.assertEqual('X{0}'.format('abc'), 'Xabc') self.assertEqual('{0}X'.format('abc'), 'abcX') self.assertEqual('X{0}Y'.format('abc'), 'XabcY') self.assertEqual('{1}'.format(1, 'abc'), 'abc') self.assertEqual('X{1}'.format(1, 'abc'), 'Xabc') self.assertEqual('{1}X'.format(1, 'abc'), 'abcX') self.assertEqual('X{1}Y'.format(1, 'abc'), 'XabcY') self.assertEqual('{0}'.format(-15), '-15') self.assertEqual('{0}{1}'.format(-15, 'abc'), '-15abc') self.assertEqual('{0}X{1}'.format(-15, 'abc'), '-15Xabc') self.assertEqual('{{'.format(), '{') self.assertEqual('}}'.format(), '}') self.assertEqual('{{}}'.format(), '{}') self.assertEqual('{{x}}'.format(), '{x}') self.assertEqual('{{{0}}}'.format(123), '{123}') self.assertEqual('{{{{0}}}}'.format(), '{{0}}') self.assertEqual('}}{{'.format(), '}{') self.assertEqual('}}x{{'.format(), '}x{') # weird field names self.assertEqual("{0[foo-bar]}".format({'foo-bar':'baz'}), 'baz') self.assertEqual("{0[foo bar]}".format({'foo bar':'baz'}), 'baz') self.assertEqual("{0[ ]}".format({' ':3}), '3') self.assertEqual('{foo._x}'.format(foo=C(20)), '20') self.assertEqual('{1}{0}'.format(D(10), D(20)), '2010') self.assertEqual('{0._x.x}'.format(C(D('abc'))), 'abc') self.assertEqual('{0[0]}'.format(['abc', 'def']), 'abc') self.assertEqual('{0[1]}'.format(['abc', 'def']), 'def') self.assertEqual('{0[1][0]}'.format(['abc', ['def']]), 'def') self.assertEqual('{0[1][0].x}'.format(['abc', [D('def')]]), 'def') # strings self.assertEqual('{0:.3s}'.format('abc'), 'abc') self.assertEqual('{0:.3s}'.format('ab'), 'ab') self.assertEqual('{0:.3s}'.format('abcdef'), 'abc') self.assertEqual('{0:.0s}'.format('abcdef'), '') self.assertEqual('{0:3.3s}'.format('abc'), 'abc') self.assertEqual('{0:2.3s}'.format('abc'), 'abc') self.assertEqual('{0:2.2s}'.format('abc'), 'ab') self.assertEqual('{0:3.2s}'.format('abc'), 'ab ') self.assertEqual('{0:x<0s}'.format('result'), 'result') self.assertEqual('{0:x<5s}'.format('result'), 'result') self.assertEqual('{0:x<6s}'.format('result'), 'result') self.assertEqual('{0:x<7s}'.format('result'), 'resultx') self.assertEqual('{0:x<8s}'.format('result'), 'resultxx') self.assertEqual('{0: <7s}'.format('result'), 'result ') self.assertEqual('{0:<7s}'.format('result'), 'result ') self.assertEqual('{0:>7s}'.format('result'), ' result') self.assertEqual('{0:>8s}'.format('result'), ' result') self.assertEqual('{0:^8s}'.format('result'), ' result ') self.assertEqual('{0:^9s}'.format('result'), ' result ') self.assertEqual('{0:^10s}'.format('result'), ' result ') self.assertEqual('{0:10000}'.format('a'), 'a' + ' ' * 9999) self.assertEqual('{0:10000}'.format(''), ' ' * 10000) self.assertEqual('{0:10000000}'.format(''), ' ' * 10000000) # issue 12546: use \x00 as a fill character self.assertEqual('{0:\x00<6s}'.format('foo'), 'foo\x00\x00\x00') self.assertEqual('{0:\x01<6s}'.format('foo'), 'foo\x01\x01\x01') self.assertEqual('{0:\x00^6s}'.format('foo'), '\x00foo\x00\x00') self.assertEqual('{0:^6s}'.format('foo'), ' foo ') self.assertEqual('{0:\x00<6}'.format(3), '3\x00\x00\x00\x00\x00') self.assertEqual('{0:\x01<6}'.format(3), '3\x01\x01\x01\x01\x01') self.assertEqual('{0:\x00^6}'.format(3), '\x00\x003\x00\x00\x00') self.assertEqual('{0:<6}'.format(3), '3 ') self.assertEqual('{0:\x00<6}'.format(3.14), '3.14\x00\x00') self.assertEqual('{0:\x01<6}'.format(3.14), '3.14\x01\x01') self.assertEqual('{0:\x00^6}'.format(3.14), '\x003.14\x00') self.assertEqual('{0:^6}'.format(3.14), ' 3.14 ') self.assertEqual('{0:\x00<12}'.format(3+2.0j), '(3+2j)\x00\x00\x00\x00\x00\x00') self.assertEqual('{0:\x01<12}'.format(3+2.0j), '(3+2j)\x01\x01\x01\x01\x01\x01') self.assertEqual('{0:\x00^12}'.format(3+2.0j), '\x00\x00\x00(3+2j)\x00\x00\x00') self.assertEqual('{0:^12}'.format(3+2.0j), ' (3+2j) ') # format specifiers for user defined type self.assertEqual('{0:abc}'.format(C()), 'abc') # !r, !s and !a coercions self.assertEqual('{0!s}'.format('Hello'), 'Hello') self.assertEqual('{0!s:}'.format('Hello'), 'Hello') self.assertEqual('{0!s:15}'.format('Hello'), 'Hello ') self.assertEqual('{0!s:15s}'.format('Hello'), 'Hello ') self.assertEqual('{0!r}'.format('Hello'), "'Hello'") self.assertEqual('{0!r:}'.format('Hello'), "'Hello'") self.assertEqual('{0!r}'.format(F('Hello')), 'F(Hello)') self.assertEqual('{0!r}'.format('\u0378'), "'\\u0378'") # nonprintable self.assertEqual('{0!r}'.format('\u0374'), "'\u0374'") # printable self.assertEqual('{0!r}'.format(F('\u0374')), 'F(\u0374)') self.assertEqual('{0!a}'.format('Hello'), "'Hello'") self.assertEqual('{0!a}'.format('\u0378'), "'\\u0378'") # nonprintable self.assertEqual('{0!a}'.format('\u0374'), "'\\u0374'") # printable self.assertEqual('{0!a:}'.format('Hello'), "'Hello'") self.assertEqual('{0!a}'.format(F('Hello')), 'F(Hello)') self.assertEqual('{0!a}'.format(F('\u0374')), 'F(\\u0374)') # test fallback to object.__format__ self.assertEqual('{0}'.format({}), '{}') self.assertEqual('{0}'.format([]), '[]') self.assertEqual('{0}'.format([1]), '[1]') self.assertEqual('{0:d}'.format(G('data')), 'G(data)') self.assertEqual('{0!s}'.format(G('data')), 'string is data') self.assertRaises(TypeError, '{0:^10}'.format, E('data')) self.assertRaises(TypeError, '{0:^10s}'.format, E('data')) self.assertRaises(TypeError, '{0:>15s}'.format, G('data')) self.assertEqual("{0:date: %Y-%m-%d}".format(I(year=2007, month=8, day=27)), "date: 2007-08-27") # test deriving from a builtin type and overriding __format__ self.assertEqual("{0}".format(J(10)), "20") # string format specifiers self.assertEqual('{0:}'.format('a'), 'a') # computed format specifiers self.assertEqual("{0:.{1}}".format('hello world', 5), 'hello') self.assertEqual("{0:.{1}s}".format('hello world', 5), 'hello') self.assertEqual("{0:.{precision}s}".format('hello world', precision=5), 'hello') self.assertEqual("{0:{width}.{precision}s}".format('hello world', width=10, precision=5), 'hello ') self.assertEqual("{0:{width}.{precision}s}".format('hello world', width='10', precision='5'), 'hello ') # test various errors self.assertRaises(ValueError, '{'.format) self.assertRaises(ValueError, '}'.format) self.assertRaises(ValueError, 'a{'.format) self.assertRaises(ValueError, 'a}'.format) self.assertRaises(ValueError, '{a'.format) self.assertRaises(ValueError, '}a'.format) self.assertRaises(IndexError, '{0}'.format) self.assertRaises(IndexError, '{1}'.format, 'abc') self.assertRaises(KeyError, '{x}'.format) self.assertRaises(ValueError, "}{".format) self.assertRaises(ValueError, "abc{0:{}".format) self.assertRaises(ValueError, "{0".format) self.assertRaises(IndexError, "{0.}".format) self.assertRaises(ValueError, "{0.}".format, 0) self.assertRaises(ValueError, "{0[}".format) self.assertRaises(ValueError, "{0[}".format, []) self.assertRaises(KeyError, "{0]}".format) self.assertRaises(ValueError, "{0.[]}".format, 0) self.assertRaises(ValueError, "{0..foo}".format, 0) self.assertRaises(ValueError, "{0[0}".format, 0) self.assertRaises(ValueError, "{0[0:foo}".format, 0) self.assertRaises(KeyError, "{c]}".format) self.assertRaises(ValueError, "{{ {{{0}}".format, 0) self.assertRaises(ValueError, "{0}}".format, 0) self.assertRaises(KeyError, "{foo}".format, bar=3) self.assertRaises(ValueError, "{0!x}".format, 3) self.assertRaises(ValueError, "{0!}".format, 0) self.assertRaises(ValueError, "{0!rs}".format, 0) self.assertRaises(ValueError, "{!}".format) self.assertRaises(IndexError, "{:}".format) self.assertRaises(IndexError, "{:s}".format) self.assertRaises(IndexError, "{}".format) big = "23098475029384702983476098230754973209482573" self.assertRaises(ValueError, ("{" + big + "}").format) self.assertRaises(ValueError, ("{[" + big + "]}").format, [0]) # issue 6089 self.assertRaises(ValueError, "{0[0]x}".format, [None]) self.assertRaises(ValueError, "{0[0](10)}".format, [None]) # can't have a replacement on the field name portion self.assertRaises(TypeError, '{0[{1}]}'.format, 'abcdefg', 4) # exceed maximum recursion depth self.assertRaises(ValueError, "{0:{1:{2}}}".format, 'abc', 's', '') self.assertRaises(ValueError, "{0:{1:{2:{3:{4:{5:{6}}}}}}}".format, 0, 1, 2, 3, 4, 5, 6, 7) # string format spec errors self.assertRaises(ValueError, "{0:-s}".format, '') self.assertRaises(ValueError, format, "", "-") self.assertRaises(ValueError, "{0:=s}".format, '') # Alternate formatting is not supported self.assertRaises(ValueError, format, '', '#') self.assertRaises(ValueError, format, '', '#20') # Non-ASCII self.assertEqual("{0:s}{1:s}".format("ABC", "\u0410\u0411\u0412"), 'ABC\u0410\u0411\u0412') self.assertEqual("{0:.3s}".format("ABC\u0410\u0411\u0412"), 'ABC') self.assertEqual("{0:.0s}".format("ABC\u0410\u0411\u0412"), '') self.assertEqual("{[{}]}".format({"{}": 5}), "5") self.assertEqual("{[{}]}".format({"{}" : "a"}), "a") self.assertEqual("{[{]}".format({"{" : "a"}), "a") self.assertEqual("{[}]}".format({"}" : "a"}), "a") self.assertEqual("{[[]}".format({"[" : "a"}), "a") self.assertEqual("{[!]}".format({"!" : "a"}), "a") self.assertRaises(ValueError, "{a{}b}".format, 42) self.assertRaises(ValueError, "{a{b}".format, 42) self.assertRaises(ValueError, "{[}".format, 42) self.assertEqual("0x{:0{:d}X}".format(0x0,16), "0x0000000000000000") # Blocking fallback m = M('data') self.assertEqual("{!r}".format(m), 'M(data)') self.assertRaises(TypeError, "{!s}".format, m) self.assertRaises(TypeError, "{}".format, m) n = N('data') self.assertEqual("{!r}".format(n), 'N(data)') self.assertEqual("{!s}".format(n), 'N(data)') self.assertRaises(TypeError, "{}".format, n) def test_format_map(self): self.assertEqual(''.format_map({}), '') self.assertEqual('a'.format_map({}), 'a') self.assertEqual('ab'.format_map({}), 'ab') self.assertEqual('a{{'.format_map({}), 'a{') self.assertEqual('a}}'.format_map({}), 'a}') self.assertEqual('{{b'.format_map({}), '{b') self.assertEqual('}}b'.format_map({}), '}b') self.assertEqual('a{{b'.format_map({}), 'a{b') # using mappings class Mapping(dict): def __missing__(self, key): return key self.assertEqual('{hello}'.format_map(Mapping()), 'hello') self.assertEqual('{a} {world}'.format_map(Mapping(a='hello')), 'hello world') class InternalMapping: def __init__(self): self.mapping = {'a': 'hello'} def __getitem__(self, key): return self.mapping[key] self.assertEqual('{a}'.format_map(InternalMapping()), 'hello') class C: def __init__(self, x=100): self._x = x def __format__(self, spec): return spec self.assertEqual('{foo._x}'.format_map({'foo': C(20)}), '20') # test various errors self.assertRaises(TypeError, ''.format_map) self.assertRaises(TypeError, 'a'.format_map) self.assertRaises(ValueError, '{'.format_map, {}) self.assertRaises(ValueError, '}'.format_map, {}) self.assertRaises(ValueError, 'a{'.format_map, {}) self.assertRaises(ValueError, 'a}'.format_map, {}) self.assertRaises(ValueError, '{a'.format_map, {}) self.assertRaises(ValueError, '}a'.format_map, {}) # issue #12579: can't supply positional params to format_map self.assertRaises(ValueError, '{}'.format_map, {'a' : 2}) self.assertRaises(ValueError, '{}'.format_map, 'a') self.assertRaises(ValueError, '{a} {}'.format_map, {"a" : 2, "b" : 1}) def test_format_huge_precision(self): format_string = ".{}f".format(sys.maxsize + 1) with self.assertRaises(ValueError): result = format(2.34, format_string) def test_format_huge_width(self): format_string = "{}f".format(sys.maxsize + 1) with self.assertRaises(ValueError): result = format(2.34, format_string) def test_format_huge_item_number(self): format_string = "{{{}:.6f}}".format(sys.maxsize + 1) with self.assertRaises(ValueError): result = format_string.format(2.34) def test_format_auto_numbering(self): class C: def __init__(self, x=100): self._x = x def __format__(self, spec): return spec self.assertEqual('{}'.format(10), '10') self.assertEqual('{:5}'.format('s'), 's ') self.assertEqual('{!r}'.format('s'), "'s'") self.assertEqual('{._x}'.format(C(10)), '10') self.assertEqual('{[1]}'.format([1, 2]), '2') self.assertEqual('{[a]}'.format({'a':4, 'b':2}), '4') self.assertEqual('a{}b{}c'.format(0, 1), 'a0b1c') self.assertEqual('a{:{}}b'.format('x', '^10'), 'a x b') self.assertEqual('a{:{}x}b'.format(20, '#'), 'a0x14b') # can't mix and match numbering and auto-numbering self.assertRaises(ValueError, '{}{1}'.format, 1, 2) self.assertRaises(ValueError, '{1}{}'.format, 1, 2) self.assertRaises(ValueError, '{:{1}}'.format, 1, 2) self.assertRaises(ValueError, '{0:{}}'.format, 1, 2) # can mix and match auto-numbering and named self.assertEqual('{f}{}'.format(4, f='test'), 'test4') self.assertEqual('{}{f}'.format(4, f='test'), '4test') self.assertEqual('{:{f}}{g}{}'.format(1, 3, g='g', f=2), ' 1g3') self.assertEqual('{f:{}}{}{g}'.format(2, 4, f=1, g='g'), ' 14g') def test_formatting(self): string_tests.MixinStrUnicodeUserStringTest.test_formatting(self) # Testing Unicode formatting strings... self.assertEqual("%s, %s" % ("abc", "abc"), 'abc, abc') self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, 2, 3), 'abc, abc, 1, 2.000000, 3.00') self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, -2, 3), 'abc, abc, 1, -2.000000, 3.00') self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.5), 'abc, abc, -1, -2.000000, 3.50') self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.57), 'abc, abc, -1, -2.000000, 3.57') self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 1003.57), 'abc, abc, -1, -2.000000, 1003.57') if not sys.platform.startswith('java'): self.assertEqual("%r, %r" % (b"abc", "abc"), "b'abc', 'abc'") self.assertEqual("%r" % ("\u1234",), "'\u1234'") self.assertEqual("%a" % ("\u1234",), "'\\u1234'") self.assertEqual("%(x)s, %(y)s" % {'x':"abc", 'y':"def"}, 'abc, def') self.assertEqual("%(x)s, %(\xfc)s" % {'x':"abc", '\xfc':"def"}, 'abc, def') self.assertEqual('%c' % 0x1234, '\u1234') self.assertEqual('%c' % 0x21483, '\U00021483') self.assertRaises(OverflowError, "%c".__mod__, (0x110000,)) self.assertEqual('%c' % '\U00021483', '\U00021483') self.assertRaises(TypeError, "%c".__mod__, "aa") self.assertRaises(ValueError, "%.1\u1032f".__mod__, (1.0/3)) self.assertRaises(TypeError, "%i".__mod__, "aa") # formatting jobs delegated from the string implementation: self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...') self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...') self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...') self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...') self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...') self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...') self.assertEqual('...%s...%s...%s...%s...' % (1,2,3,"abc"), '...1...2...3...abc...') self.assertEqual('...%%...%%s...%s...%s...%s...%s...' % (1,2,3,"abc"), '...%...%s...1...2...3...abc...') self.assertEqual('...%s...' % "abc", '...abc...') self.assertEqual('%*s' % (5,'abc',), ' abc') self.assertEqual('%*s' % (-5,'abc',), 'abc ') self.assertEqual('%*.*s' % (5,2,'abc',), ' ab') self.assertEqual('%*.*s' % (5,3,'abc',), ' abc') self.assertEqual('%i %*.*s' % (10, 5,3,'abc',), '10 abc') self.assertEqual('%i%s %*.*s' % (10, 3, 5, 3, 'abc',), '103 abc') self.assertEqual('%c' % 'a', 'a') class Wrapper: def __str__(self): return '\u1234' self.assertEqual('%s' % Wrapper(), '\u1234') # issue 3382 NAN = float('nan') INF = float('inf') self.assertEqual('%f' % NAN, 'nan') self.assertEqual('%F' % NAN, 'NAN') self.assertEqual('%f' % INF, 'inf') self.assertEqual('%F' % INF, 'INF') # PEP 393 self.assertEqual('%.1s' % "a\xe9\u20ac", 'a') self.assertEqual('%.2s' % "a\xe9\u20ac", 'a\xe9') #issue 19995 class PseudoInt: def __init__(self, value): self.value = int(value) def __int__(self): return self.value def __index__(self): return self.value class PseudoFloat: def __init__(self, value): self.value = float(value) def __int__(self): return int(self.value) pi = PseudoFloat(3.1415) letter_m = PseudoInt(109) self.assertEqual('%x' % 42, '2a') self.assertEqual('%X' % 15, 'F') self.assertEqual('%o' % 9, '11') self.assertEqual('%c' % 109, 'm') self.assertEqual('%x' % letter_m, '6d') self.assertEqual('%X' % letter_m, '6D') self.assertEqual('%o' % letter_m, '155') self.assertEqual('%c' % letter_m, 'm') self.assertRaisesRegex(TypeError, '%x format: an integer is required, not float', operator.mod, '%x', 3.14), self.assertRaisesRegex(TypeError, '%X format: an integer is required, not float', operator.mod, '%X', 2.11), self.assertRaisesRegex(TypeError, '%o format: an integer is required, not float', operator.mod, '%o', 1.79), self.assertRaisesRegex(TypeError, '%x format: an integer is required, not PseudoFloat', operator.mod, '%x', pi), self.assertRaises(TypeError, operator.mod, '%c', pi), def test_formatting_with_enum(self): # issue18780 import enum class Float(float, enum.Enum): PI = 3.1415926 class Int(enum.IntEnum): IDES = 15 class Str(str, enum.Enum): ABC = 'abc' # Testing Unicode formatting strings... self.assertEqual("%s, %s" % (Str.ABC, Str.ABC), 'Str.ABC, Str.ABC') self.assertEqual("%s, %s, %d, %i, %u, %f, %5.2f" % (Str.ABC, Str.ABC, Int.IDES, Int.IDES, Int.IDES, Float.PI, Float.PI), 'Str.ABC, Str.ABC, 15, 15, 15, 3.141593, 3.14') # formatting jobs delegated from the string implementation: self.assertEqual('...%(foo)s...' % {'foo':Str.ABC}, '...Str.ABC...') self.assertEqual('...%(foo)s...' % {'foo':Int.IDES}, '...Int.IDES...') self.assertEqual('...%(foo)i...' % {'foo':Int.IDES}, '...15...') self.assertEqual('...%(foo)d...' % {'foo':Int.IDES}, '...15...') self.assertEqual('...%(foo)u...' % {'foo':Int.IDES, 'def':Float.PI}, '...15...') self.assertEqual('...%(foo)f...' % {'foo':Float.PI,'def':123}, '...3.141593...') def test_formatting_huge_precision(self): format_string = "%.{}f".format(sys.maxsize + 1) with self.assertRaises(ValueError): result = format_string % 2.34 def test_issue28598_strsubclass_rhs(self): # A subclass of str with an __rmod__ method should be able to hook # into the % operator class SubclassedStr(str): def __rmod__(self, other): return 'Success, self.__rmod__({!r}) was called'.format(other) self.assertEqual('lhs %% %r' % SubclassedStr('rhs'), "Success, self.__rmod__('lhs %% %r') was called") @support.cpython_only def test_formatting_huge_precision_c_limits(self): from _testcapi import INT_MAX format_string = "%.{}f".format(INT_MAX + 1) with self.assertRaises(ValueError): result = format_string % 2.34 def test_formatting_huge_width(self): format_string = "%{}f".format(sys.maxsize + 1) with self.assertRaises(ValueError): result = format_string % 2.34 def test_startswith_endswith_errors(self): for meth in ('foo'.startswith, 'foo'.endswith): with self.assertRaises(TypeError) as cm: meth(['f']) exc = str(cm.exception) self.assertIn('str', exc) self.assertIn('tuple', exc) @support.run_with_locale('LC_ALL', 'de_DE', 'fr_FR') def test_format_float(self): # should not format with a comma, but always with C locale self.assertEqual('1.0', '%.1f' % 1.0) def test_constructor(self): # unicode(obj) tests (this maps to PyObject_Unicode() at C level) self.assertEqual( str('unicode remains unicode'), 'unicode remains unicode' ) for text in ('ascii', '\xe9', '\u20ac', '\U0010FFFF'): subclass = StrSubclass(text) self.assertEqual(str(subclass), text) self.assertEqual(len(subclass), len(text)) if text == 'ascii': self.assertEqual(subclass.encode('ascii'), b'ascii') self.assertEqual(subclass.encode('utf-8'), b'ascii') self.assertEqual( str('strings are converted to unicode'), 'strings are converted to unicode' ) class StringCompat: def __init__(self, x): self.x = x def __str__(self): return self.x self.assertEqual( str(StringCompat('__str__ compatible objects are recognized')), '__str__ compatible objects are recognized' ) # unicode(obj) is compatible to str(): o = StringCompat('unicode(obj) is compatible to str()') self.assertEqual(str(o), 'unicode(obj) is compatible to str()') self.assertEqual(str(o), 'unicode(obj) is compatible to str()') for obj in (123, 123.45, 123): self.assertEqual(str(obj), str(str(obj))) # unicode(obj, encoding, error) tests (this maps to # PyUnicode_FromEncodedObject() at C level) if not sys.platform.startswith('java'): self.assertRaises( TypeError, str, 'decoding unicode is not supported', 'utf-8', 'strict' ) self.assertEqual( str(b'strings are decoded to unicode', 'utf-8', 'strict'), 'strings are decoded to unicode' ) if not sys.platform.startswith('java'): self.assertEqual( str( memoryview(b'character buffers are decoded to unicode'), 'utf-8', 'strict' ), 'character buffers are decoded to unicode' ) self.assertRaises(TypeError, str, 42, 42, 42) def test_constructor_keyword_args(self): """Pass various keyword argument combinations to the constructor.""" # The object argument can be passed as a keyword. self.assertEqual(str(object='foo'), 'foo') self.assertEqual(str(object=b'foo', encoding='utf-8'), 'foo') # The errors argument without encoding triggers "decode" mode. self.assertEqual(str(b'foo', errors='strict'), 'foo') # not "b'foo'" self.assertEqual(str(object=b'foo', errors='strict'), 'foo') def test_constructor_defaults(self): """Check the constructor argument defaults.""" # The object argument defaults to '' or b''. self.assertEqual(str(), '') self.assertEqual(str(errors='strict'), '') utf8_cent = '¢'.encode('utf-8') # The encoding argument defaults to utf-8. self.assertEqual(str(utf8_cent, errors='strict'), '¢') # The errors argument defaults to strict. self.assertRaises(UnicodeDecodeError, str, utf8_cent, encoding='ascii') def test_codecs_utf7(self): utfTests = [ ('A\u2262\u0391.', b'A+ImIDkQ.'), # RFC2152 example ('Hi Mom -\u263a-!', b'Hi Mom -+Jjo--!'), # RFC2152 example ('\u65E5\u672C\u8A9E', b'+ZeVnLIqe-'), # RFC2152 example ('Item 3 is \u00a31.', b'Item 3 is +AKM-1.'), # RFC2152 example ('+', b'+-'), ('+-', b'+--'), ('+?', b'+-?'), (r'\?', b'+AFw?'), ('+?', b'+-?'), (r'\\?', b'+AFwAXA?'), (r'\\\?', b'+AFwAXABc?'), (r'++--', b'+-+---'), ('\U000abcde', b'+2m/c3g-'), # surrogate pairs ('/', b'/'), ] for (x, y) in utfTests: self.assertEqual(x.encode('utf-7'), y) # Unpaired surrogates are passed through self.assertEqual('\uD801'.encode('utf-7'), b'+2AE-') self.assertEqual('\uD801x'.encode('utf-7'), b'+2AE-x') self.assertEqual('\uDC01'.encode('utf-7'), b'+3AE-') self.assertEqual('\uDC01x'.encode('utf-7'), b'+3AE-x') self.assertEqual(b'+2AE-'.decode('utf-7'), '\uD801') self.assertEqual(b'+2AE-x'.decode('utf-7'), '\uD801x') self.assertEqual(b'+3AE-'.decode('utf-7'), '\uDC01') self.assertEqual(b'+3AE-x'.decode('utf-7'), '\uDC01x') self.assertEqual('\uD801\U000abcde'.encode('utf-7'), b'+2AHab9ze-') self.assertEqual(b'+2AHab9ze-'.decode('utf-7'), '\uD801\U000abcde') # Issue #2242: crash on some Windows/MSVC versions self.assertEqual(b'+\xc1'.decode('utf-7', 'ignore'), '') # Direct encoded characters set_d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'(),-./:?" # Optional direct characters set_o = '!"#$%&*;<=>@[]^_`{|}' for c in set_d: self.assertEqual(c.encode('utf7'), c.encode('ascii')) self.assertEqual(c.encode('ascii').decode('utf7'), c) for c in set_o: self.assertEqual(c.encode('ascii').decode('utf7'), c) def test_codecs_utf8(self): self.assertEqual(''.encode('utf-8'), b'') self.assertEqual('\u20ac'.encode('utf-8'), b'\xe2\x82\xac') self.assertEqual('\U00010002'.encode('utf-8'), b'\xf0\x90\x80\x82') self.assertEqual('\U00023456'.encode('utf-8'), b'\xf0\xa3\x91\x96') self.assertEqual('\ud800'.encode('utf-8', 'surrogatepass'), b'\xed\xa0\x80') self.assertEqual('\udc00'.encode('utf-8', 'surrogatepass'), b'\xed\xb0\x80') self.assertEqual(('\U00010002'*10).encode('utf-8'), b'\xf0\x90\x80\x82'*10) self.assertEqual( '\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f' '\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00' '\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c' '\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067' '\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das' ' Nunstuck git und'.encode('utf-8'), b'\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81' b'\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3' b'\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe' b'\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83' b'\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8' b'\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81' b'\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81' b'\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3' b'\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf' b'\xe3\x80\x8cWenn ist das Nunstuck git und' ) # UTF-8 specific decoding tests self.assertEqual(str(b'\xf0\xa3\x91\x96', 'utf-8'), '\U00023456' ) self.assertEqual(str(b'\xf0\x90\x80\x82', 'utf-8'), '\U00010002' ) self.assertEqual(str(b'\xe2\x82\xac', 'utf-8'), '\u20ac' ) # Other possible utf-8 test cases: # * strict decoding testing for all of the # UTF8_ERROR cases in PyUnicode_DecodeUTF8 def test_utf8_decode_valid_sequences(self): sequences = [ # single byte (b'\x00', '\x00'), (b'a', 'a'), (b'\x7f', '\x7f'), # 2 bytes (b'\xc2\x80', '\x80'), (b'\xdf\xbf', '\u07ff'), # 3 bytes (b'\xe0\xa0\x80', '\u0800'), (b'\xed\x9f\xbf', '\ud7ff'), (b'\xee\x80\x80', '\uE000'), (b'\xef\xbf\xbf', '\uffff'), # 4 bytes (b'\xF0\x90\x80\x80', '\U00010000'), (b'\xf4\x8f\xbf\xbf', '\U0010FFFF') ] for seq, res in sequences: self.assertEqual(seq.decode('utf-8'), res) def test_utf8_decode_invalid_sequences(self): # continuation bytes in a sequence of 2, 3, or 4 bytes continuation_bytes = [bytes([x]) for x in range(0x80, 0xC0)] # start bytes of a 2-byte sequence equivalent to code points < 0x7F invalid_2B_seq_start_bytes = [bytes([x]) for x in range(0xC0, 0xC2)] # start bytes of a 4-byte sequence equivalent to code points > 0x10FFFF invalid_4B_seq_start_bytes = [bytes([x]) for x in range(0xF5, 0xF8)] invalid_start_bytes = ( continuation_bytes + invalid_2B_seq_start_bytes + invalid_4B_seq_start_bytes + [bytes([x]) for x in range(0xF7, 0x100)] ) for byte in invalid_start_bytes: self.assertRaises(UnicodeDecodeError, byte.decode, 'utf-8') for sb in invalid_2B_seq_start_bytes: for cb in continuation_bytes: self.assertRaises(UnicodeDecodeError, (sb+cb).decode, 'utf-8') for sb in invalid_4B_seq_start_bytes: for cb1 in continuation_bytes[:3]: for cb3 in continuation_bytes[:3]: self.assertRaises(UnicodeDecodeError, (sb+cb1+b'\x80'+cb3).decode, 'utf-8') for cb in [bytes([x]) for x in range(0x80, 0xA0)]: self.assertRaises(UnicodeDecodeError, (b'\xE0'+cb+b'\x80').decode, 'utf-8') self.assertRaises(UnicodeDecodeError, (b'\xE0'+cb+b'\xBF').decode, 'utf-8') # surrogates for cb in [bytes([x]) for x in range(0xA0, 0xC0)]: self.assertRaises(UnicodeDecodeError, (b'\xED'+cb+b'\x80').decode, 'utf-8') self.assertRaises(UnicodeDecodeError, (b'\xED'+cb+b'\xBF').decode, 'utf-8') for cb in [bytes([x]) for x in range(0x80, 0x90)]: self.assertRaises(UnicodeDecodeError, (b'\xF0'+cb+b'\x80\x80').decode, 'utf-8') self.assertRaises(UnicodeDecodeError, (b'\xF0'+cb+b'\xBF\xBF').decode, 'utf-8') for cb in [bytes([x]) for x in range(0x90, 0xC0)]: self.assertRaises(UnicodeDecodeError, (b'\xF4'+cb+b'\x80\x80').decode, 'utf-8') self.assertRaises(UnicodeDecodeError, (b'\xF4'+cb+b'\xBF\xBF').decode, 'utf-8') def test_issue8271(self): # Issue #8271: during the decoding of an invalid UTF-8 byte sequence, # only the start byte and the continuation byte(s) are now considered # invalid, instead of the number of bytes specified by the start byte. # See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf (page 95, # table 3-8, Row 2) for more information about the algorithm used. FFFD = '\ufffd' sequences = [ # invalid start bytes (b'\x80', FFFD), # continuation byte (b'\x80\x80', FFFD*2), # 2 continuation bytes (b'\xc0', FFFD), (b'\xc0\xc0', FFFD*2), (b'\xc1', FFFD), (b'\xc1\xc0', FFFD*2), (b'\xc0\xc1', FFFD*2), # with start byte of a 2-byte sequence (b'\xc2', FFFD), # only the start byte (b'\xc2\xc2', FFFD*2), # 2 start bytes (b'\xc2\xc2\xc2', FFFD*3), # 3 start bytes (b'\xc2\x41', FFFD+'A'), # invalid continuation byte # with start byte of a 3-byte sequence (b'\xe1', FFFD), # only the start byte (b'\xe1\xe1', FFFD*2), # 2 start bytes (b'\xe1\xe1\xe1', FFFD*3), # 3 start bytes (b'\xe1\xe1\xe1\xe1', FFFD*4), # 4 start bytes (b'\xe1\x80', FFFD), # only 1 continuation byte (b'\xe1\x41', FFFD+'A'), # invalid continuation byte (b'\xe1\x41\x80', FFFD+'A'+FFFD), # invalid cb followed by valid cb (b'\xe1\x41\x41', FFFD+'AA'), # 2 invalid continuation bytes (b'\xe1\x80\x41', FFFD+'A'), # only 1 valid continuation byte (b'\xe1\x80\xe1\x41', FFFD*2+'A'), # 1 valid and the other invalid (b'\xe1\x41\xe1\x80', FFFD+'A'+FFFD), # 1 invalid and the other valid # with start byte of a 4-byte sequence (b'\xf1', FFFD), # only the start byte (b'\xf1\xf1', FFFD*2), # 2 start bytes (b'\xf1\xf1\xf1', FFFD*3), # 3 start bytes (b'\xf1\xf1\xf1\xf1', FFFD*4), # 4 start bytes (b'\xf1\xf1\xf1\xf1\xf1', FFFD*5), # 5 start bytes (b'\xf1\x80', FFFD), # only 1 continuation bytes (b'\xf1\x80\x80', FFFD), # only 2 continuation bytes (b'\xf1\x80\x41', FFFD+'A'), # 1 valid cb and 1 invalid (b'\xf1\x80\x41\x41', FFFD+'AA'), # 1 valid cb and 1 invalid (b'\xf1\x80\x80\x41', FFFD+'A'), # 2 valid cb and 1 invalid (b'\xf1\x41\x80', FFFD+'A'+FFFD), # 1 invalid cv and 1 valid (b'\xf1\x41\x80\x80', FFFD+'A'+FFFD*2), # 1 invalid cb and 2 invalid (b'\xf1\x41\x80\x41', FFFD+'A'+FFFD+'A'), # 2 invalid cb and 1 invalid (b'\xf1\x41\x41\x80', FFFD+'AA'+FFFD), # 1 valid cb and 1 invalid (b'\xf1\x41\xf1\x80', FFFD+'A'+FFFD), (b'\xf1\x41\x80\xf1', FFFD+'A'+FFFD*2), (b'\xf1\xf1\x80\x41', FFFD*2+'A'), (b'\xf1\x41\xf1\xf1', FFFD+'A'+FFFD*2), # with invalid start byte of a 4-byte sequence (rfc2279) (b'\xf5', FFFD), # only the start byte (b'\xf5\xf5', FFFD*2), # 2 start bytes (b'\xf5\x80', FFFD*2), # only 1 continuation byte (b'\xf5\x80\x80', FFFD*3), # only 2 continuation byte (b'\xf5\x80\x80\x80', FFFD*4), # 3 continuation bytes (b'\xf5\x80\x41', FFFD*2+'A'), # 1 valid cb and 1 invalid (b'\xf5\x80\x41\xf5', FFFD*2+'A'+FFFD), (b'\xf5\x41\x80\x80\x41', FFFD+'A'+FFFD*2+'A'), # with invalid start byte of a 5-byte sequence (rfc2279) (b'\xf8', FFFD), # only the start byte (b'\xf8\xf8', FFFD*2), # 2 start bytes (b'\xf8\x80', FFFD*2), # only one continuation byte (b'\xf8\x80\x41', FFFD*2 + 'A'), # 1 valid cb and 1 invalid (b'\xf8\x80\x80\x80\x80', FFFD*5), # invalid 5 bytes seq with 5 bytes # with invalid start byte of a 6-byte sequence (rfc2279) (b'\xfc', FFFD), # only the start byte (b'\xfc\xfc', FFFD*2), # 2 start bytes (b'\xfc\x80\x80', FFFD*3), # only 2 continuation bytes (b'\xfc\x80\x80\x80\x80\x80', FFFD*6), # 6 continuation bytes # invalid start byte (b'\xfe', FFFD), (b'\xfe\x80\x80', FFFD*3), # other sequences (b'\xf1\x80\x41\x42\x43', '\ufffd\x41\x42\x43'), (b'\xf1\x80\xff\x42\x43', '\ufffd\ufffd\x42\x43'), (b'\xf1\x80\xc2\x81\x43', '\ufffd\x81\x43'), (b'\x61\xF1\x80\x80\xE1\x80\xC2\x62\x80\x63\x80\xBF\x64', '\x61\uFFFD\uFFFD\uFFFD\x62\uFFFD\x63\uFFFD\uFFFD\x64'), ] for n, (seq, res) in enumerate(sequences): self.assertRaises(UnicodeDecodeError, seq.decode, 'utf-8', 'strict') self.assertEqual(seq.decode('utf-8', 'replace'), res) self.assertEqual((seq+b'b').decode('utf-8', 'replace'), res+'b') self.assertEqual(seq.decode('utf-8', 'ignore'), res.replace('\uFFFD', '')) def assertCorrectUTF8Decoding(self, seq, res, err): """ Check that an invalid UTF-8 sequence raises a UnicodeDecodeError when 'strict' is used, returns res when 'replace' is used, and that doesn't return anything when 'ignore' is used. """ with self.assertRaises(UnicodeDecodeError) as cm: seq.decode('utf-8') exc = cm.exception self.assertIn(err, str(exc)) self.assertEqual(seq.decode('utf-8', 'replace'), res) self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'replace'), 'aaaa' + res + 'bbbb') res = res.replace('\ufffd', '') self.assertEqual(seq.decode('utf-8', 'ignore'), res) self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'ignore'), 'aaaa' + res + 'bbbb') def test_invalid_start_byte(self): """ Test that an 'invalid start byte' error is raised when the first byte is not in the ASCII range or is not a valid start byte of a 2-, 3-, or 4-bytes sequence. The invalid start byte is replaced with a single U+FFFD when errors='replace'. E.g. <80> is a continuation byte and can appear only after a start byte. """ FFFD = '\ufffd' for byte in b'\x80\xA0\x9F\xBF\xC0\xC1\xF5\xFF': self.assertCorrectUTF8Decoding(bytes([byte]), '\ufffd', 'invalid start byte') def test_unexpected_end_of_data(self): """ Test that an 'unexpected end of data' error is raised when the string ends after a start byte of a 2-, 3-, or 4-bytes sequence without having enough continuation bytes. The incomplete sequence is replaced with a single U+FFFD when errors='replace'. E.g. in the sequence <F3 80 80>, F3 is the start byte of a 4-bytes sequence, but it's followed by only 2 valid continuation bytes and the last continuation bytes is missing. Note: the continuation bytes must be all valid, if one of them is invalid another error will be raised. """ sequences = [ 'C2', 'DF', 'E0 A0', 'E0 BF', 'E1 80', 'E1 BF', 'EC 80', 'EC BF', 'ED 80', 'ED 9F', 'EE 80', 'EE BF', 'EF 80', 'EF BF', 'F0 90', 'F0 BF', 'F0 90 80', 'F0 90 BF', 'F0 BF 80', 'F0 BF BF', 'F1 80', 'F1 BF', 'F1 80 80', 'F1 80 BF', 'F1 BF 80', 'F1 BF BF', 'F3 80', 'F3 BF', 'F3 80 80', 'F3 80 BF', 'F3 BF 80', 'F3 BF BF', 'F4 80', 'F4 8F', 'F4 80 80', 'F4 80 BF', 'F4 8F 80', 'F4 8F BF' ] FFFD = '\ufffd' for seq in sequences: self.assertCorrectUTF8Decoding(bytes.fromhex(seq), '\ufffd', 'unexpected end of data') def test_invalid_cb_for_2bytes_seq(self): """ Test that an 'invalid continuation byte' error is raised when the continuation byte of a 2-bytes sequence is invalid. The start byte is replaced by a single U+FFFD and the second byte is handled separately when errors='replace'. E.g. in the sequence <C2 41>, C2 is the start byte of a 2-bytes sequence, but 41 is not a valid continuation byte because it's the ASCII letter 'A'. """ FFFD = '\ufffd' FFFDx2 = FFFD * 2 sequences = [ ('C2 00', FFFD+'\x00'), ('C2 7F', FFFD+'\x7f'), ('C2 C0', FFFDx2), ('C2 FF', FFFDx2), ('DF 00', FFFD+'\x00'), ('DF 7F', FFFD+'\x7f'), ('DF C0', FFFDx2), ('DF FF', FFFDx2), ] for seq, res in sequences: self.assertCorrectUTF8Decoding(bytes.fromhex(seq), res, 'invalid continuation byte') def test_invalid_cb_for_3bytes_seq(self): """ Test that an 'invalid continuation byte' error is raised when the continuation byte(s) of a 3-bytes sequence are invalid. When errors='replace', if the first continuation byte is valid, the first two bytes (start byte + 1st cb) are replaced by a single U+FFFD and the third byte is handled separately, otherwise only the start byte is replaced with a U+FFFD and the other continuation bytes are handled separately. E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes sequence, 80 is a valid continuation byte, but 41 is not a valid cb because it's the ASCII letter 'A'. Note: when the start byte is E0 or ED, the valid ranges for the first continuation byte are limited to A0..BF and 80..9F respectively. Python 2 used to consider all the bytes in range 80..BF valid when the start byte was ED. This is fixed in Python 3. """ FFFD = '\ufffd' FFFDx2 = FFFD * 2 sequences = [ ('E0 00', FFFD+'\x00'), ('E0 7F', FFFD+'\x7f'), ('E0 80', FFFDx2), ('E0 9F', FFFDx2), ('E0 C0', FFFDx2), ('E0 FF', FFFDx2), ('E0 A0 00', FFFD+'\x00'), ('E0 A0 7F', FFFD+'\x7f'), ('E0 A0 C0', FFFDx2), ('E0 A0 FF', FFFDx2), ('E0 BF 00', FFFD+'\x00'), ('E0 BF 7F', FFFD+'\x7f'), ('E0 BF C0', FFFDx2), ('E0 BF FF', FFFDx2), ('E1 00', FFFD+'\x00'), ('E1 7F', FFFD+'\x7f'), ('E1 C0', FFFDx2), ('E1 FF', FFFDx2), ('E1 80 00', FFFD+'\x00'), ('E1 80 7F', FFFD+'\x7f'), ('E1 80 C0', FFFDx2), ('E1 80 FF', FFFDx2), ('E1 BF 00', FFFD+'\x00'), ('E1 BF 7F', FFFD+'\x7f'), ('E1 BF C0', FFFDx2), ('E1 BF FF', FFFDx2), ('EC 00', FFFD+'\x00'), ('EC 7F', FFFD+'\x7f'), ('EC C0', FFFDx2), ('EC FF', FFFDx2), ('EC 80 00', FFFD+'\x00'), ('EC 80 7F', FFFD+'\x7f'), ('EC 80 C0', FFFDx2), ('EC 80 FF', FFFDx2), ('EC BF 00', FFFD+'\x00'), ('EC BF 7F', FFFD+'\x7f'), ('EC BF C0', FFFDx2), ('EC BF FF', FFFDx2), ('ED 00', FFFD+'\x00'), ('ED 7F', FFFD+'\x7f'), ('ED A0', FFFDx2), ('ED BF', FFFDx2), # see note ^ ('ED C0', FFFDx2), ('ED FF', FFFDx2), ('ED 80 00', FFFD+'\x00'), ('ED 80 7F', FFFD+'\x7f'), ('ED 80 C0', FFFDx2), ('ED 80 FF', FFFDx2), ('ED 9F 00', FFFD+'\x00'), ('ED 9F 7F', FFFD+'\x7f'), ('ED 9F C0', FFFDx2), ('ED 9F FF', FFFDx2), ('EE 00', FFFD+'\x00'), ('EE 7F', FFFD+'\x7f'), ('EE C0', FFFDx2), ('EE FF', FFFDx2), ('EE 80 00', FFFD+'\x00'), ('EE 80 7F', FFFD+'\x7f'), ('EE 80 C0', FFFDx2), ('EE 80 FF', FFFDx2), ('EE BF 00', FFFD+'\x00'), ('EE BF 7F', FFFD+'\x7f'), ('EE BF C0', FFFDx2), ('EE BF FF', FFFDx2), ('EF 00', FFFD+'\x00'), ('EF 7F', FFFD+'\x7f'), ('EF C0', FFFDx2), ('EF FF', FFFDx2), ('EF 80 00', FFFD+'\x00'), ('EF 80 7F', FFFD+'\x7f'), ('EF 80 C0', FFFDx2), ('EF 80 FF', FFFDx2), ('EF BF 00', FFFD+'\x00'), ('EF BF 7F', FFFD+'\x7f'), ('EF BF C0', FFFDx2), ('EF BF FF', FFFDx2), ] for seq, res in sequences: self.assertCorrectUTF8Decoding(bytes.fromhex(seq), res, 'invalid continuation byte') def test_invalid_cb_for_4bytes_seq(self): """ Test that an 'invalid continuation byte' error is raised when the continuation byte(s) of a 4-bytes sequence are invalid. When errors='replace',the start byte and all the following valid continuation bytes are replaced with a single U+FFFD, and all the bytes starting from the first invalid continuation bytes (included) are handled separately. E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes sequence, 80 is a valid continuation byte, but 41 is not a valid cb because it's the ASCII letter 'A'. Note: when the start byte is E0 or ED, the valid ranges for the first continuation byte are limited to A0..BF and 80..9F respectively. However, when the start byte is ED, Python 2 considers all the bytes in range 80..BF valid. This is fixed in Python 3. """ FFFD = '\ufffd' FFFDx2 = FFFD * 2 sequences = [ ('F0 00', FFFD+'\x00'), ('F0 7F', FFFD+'\x7f'), ('F0 80', FFFDx2), ('F0 8F', FFFDx2), ('F0 C0', FFFDx2), ('F0 FF', FFFDx2), ('F0 90 00', FFFD+'\x00'), ('F0 90 7F', FFFD+'\x7f'), ('F0 90 C0', FFFDx2), ('F0 90 FF', FFFDx2), ('F0 BF 00', FFFD+'\x00'), ('F0 BF 7F', FFFD+'\x7f'), ('F0 BF C0', FFFDx2), ('F0 BF FF', FFFDx2), ('F0 90 80 00', FFFD+'\x00'), ('F0 90 80 7F', FFFD+'\x7f'), ('F0 90 80 C0', FFFDx2), ('F0 90 80 FF', FFFDx2), ('F0 90 BF 00', FFFD+'\x00'), ('F0 90 BF 7F', FFFD+'\x7f'), ('F0 90 BF C0', FFFDx2), ('F0 90 BF FF', FFFDx2), ('F0 BF 80 00', FFFD+'\x00'), ('F0 BF 80 7F', FFFD+'\x7f'), ('F0 BF 80 C0', FFFDx2), ('F0 BF 80 FF', FFFDx2), ('F0 BF BF 00', FFFD+'\x00'), ('F0 BF BF 7F', FFFD+'\x7f'), ('F0 BF BF C0', FFFDx2), ('F0 BF BF FF', FFFDx2), ('F1 00', FFFD+'\x00'), ('F1 7F', FFFD+'\x7f'), ('F1 C0', FFFDx2), ('F1 FF', FFFDx2), ('F1 80 00', FFFD+'\x00'), ('F1 80 7F', FFFD+'\x7f'), ('F1 80 C0', FFFDx2), ('F1 80 FF', FFFDx2), ('F1 BF 00', FFFD+'\x00'), ('F1 BF 7F', FFFD+'\x7f'), ('F1 BF C0', FFFDx2), ('F1 BF FF', FFFDx2), ('F1 80 80 00', FFFD+'\x00'), ('F1 80 80 7F', FFFD+'\x7f'), ('F1 80 80 C0', FFFDx2), ('F1 80 80 FF', FFFDx2), ('F1 80 BF 00', FFFD+'\x00'), ('F1 80 BF 7F', FFFD+'\x7f'), ('F1 80 BF C0', FFFDx2), ('F1 80 BF FF', FFFDx2), ('F1 BF 80 00', FFFD+'\x00'), ('F1 BF 80 7F', FFFD+'\x7f'), ('F1 BF 80 C0', FFFDx2), ('F1 BF 80 FF', FFFDx2), ('F1 BF BF 00', FFFD+'\x00'), ('F1 BF BF 7F', FFFD+'\x7f'), ('F1 BF BF C0', FFFDx2), ('F1 BF BF FF', FFFDx2), ('F3 00', FFFD+'\x00'), ('F3 7F', FFFD+'\x7f'), ('F3 C0', FFFDx2), ('F3 FF', FFFDx2), ('F3 80 00', FFFD+'\x00'), ('F3 80 7F', FFFD+'\x7f'), ('F3 80 C0', FFFDx2), ('F3 80 FF', FFFDx2), ('F3 BF 00', FFFD+'\x00'), ('F3 BF 7F', FFFD+'\x7f'), ('F3 BF C0', FFFDx2), ('F3 BF FF', FFFDx2), ('F3 80 80 00', FFFD+'\x00'), ('F3 80 80 7F', FFFD+'\x7f'), ('F3 80 80 C0', FFFDx2), ('F3 80 80 FF', FFFDx2), ('F3 80 BF 00', FFFD+'\x00'), ('F3 80 BF 7F', FFFD+'\x7f'), ('F3 80 BF C0', FFFDx2), ('F3 80 BF FF', FFFDx2), ('F3 BF 80 00', FFFD+'\x00'), ('F3 BF 80 7F', FFFD+'\x7f'), ('F3 BF 80 C0', FFFDx2), ('F3 BF 80 FF', FFFDx2), ('F3 BF BF 00', FFFD+'\x00'), ('F3 BF BF 7F', FFFD+'\x7f'), ('F3 BF BF C0', FFFDx2), ('F3 BF BF FF', FFFDx2), ('F4 00', FFFD+'\x00'), ('F4 7F', FFFD+'\x7f'), ('F4 90', FFFDx2), ('F4 BF', FFFDx2), ('F4 C0', FFFDx2), ('F4 FF', FFFDx2), ('F4 80 00', FFFD+'\x00'), ('F4 80 7F', FFFD+'\x7f'), ('F4 80 C0', FFFDx2), ('F4 80 FF', FFFDx2), ('F4 8F 00', FFFD+'\x00'), ('F4 8F 7F', FFFD+'\x7f'), ('F4 8F C0', FFFDx2), ('F4 8F FF', FFFDx2), ('F4 80 80 00', FFFD+'\x00'), ('F4 80 80 7F', FFFD+'\x7f'), ('F4 80 80 C0', FFFDx2), ('F4 80 80 FF', FFFDx2), ('F4 80 BF 00', FFFD+'\x00'), ('F4 80 BF 7F', FFFD+'\x7f'), ('F4 80 BF C0', FFFDx2), ('F4 80 BF FF', FFFDx2), ('F4 8F 80 00', FFFD+'\x00'), ('F4 8F 80 7F', FFFD+'\x7f'), ('F4 8F 80 C0', FFFDx2), ('F4 8F 80 FF', FFFDx2), ('F4 8F BF 00', FFFD+'\x00'), ('F4 8F BF 7F', FFFD+'\x7f'), ('F4 8F BF C0', FFFDx2), ('F4 8F BF FF', FFFDx2) ] for seq, res in sequences: self.assertCorrectUTF8Decoding(bytes.fromhex(seq), res, 'invalid continuation byte') def test_codecs_idna(self): # Test whether trailing dot is preserved self.assertEqual("www.python.org.".encode("idna"), b"www.python.org.") def test_codecs_errors(self): # Error handling (encoding) self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii') self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii','strict') self.assertEqual('Andr\202 x'.encode('ascii','ignore'), b"Andr x") self.assertEqual('Andr\202 x'.encode('ascii','replace'), b"Andr? x") self.assertEqual('Andr\202 x'.encode('ascii', 'replace'), 'Andr\202 x'.encode('ascii', errors='replace')) self.assertEqual('Andr\202 x'.encode('ascii', 'ignore'), 'Andr\202 x'.encode(encoding='ascii', errors='ignore')) # Error handling (decoding) self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii') self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii', 'strict') self.assertEqual(str(b'Andr\202 x', 'ascii', 'ignore'), "Andr x") self.assertEqual(str(b'Andr\202 x', 'ascii', 'replace'), 'Andr\uFFFD x') self.assertEqual(str(b'\202 x', 'ascii', 'replace'), '\uFFFD x') # Error handling (unknown character names) self.assertEqual(b"\\N{foo}xx".decode("unicode-escape", "ignore"), "xx") # Error handling (truncated escape sequence) self.assertRaises(UnicodeError, b"\\".decode, "unicode-escape") self.assertRaises(TypeError, b"hello".decode, "test.unicode1") self.assertRaises(TypeError, str, b"hello", "test.unicode2") self.assertRaises(TypeError, "hello".encode, "test.unicode1") self.assertRaises(TypeError, "hello".encode, "test.unicode2") # Error handling (wrong arguments) self.assertRaises(TypeError, "hello".encode, 42, 42, 42) # Error handling (lone surrogate in PyUnicode_TransformDecimalToASCII()) self.assertRaises(UnicodeError, float, "\ud800") self.assertRaises(UnicodeError, float, "\udf00") self.assertRaises(UnicodeError, complex, "\ud800") self.assertRaises(UnicodeError, complex, "\udf00") def test_codecs(self): # Encoding self.assertEqual('hello'.encode('ascii'), b'hello') self.assertEqual('hello'.encode('utf-7'), b'hello') self.assertEqual('hello'.encode('utf-8'), b'hello') self.assertEqual('hello'.encode('utf-8'), b'hello') self.assertEqual('hello'.encode('utf-16-le'), b'h\000e\000l\000l\000o\000') self.assertEqual('hello'.encode('utf-16-be'), b'\000h\000e\000l\000l\000o') self.assertEqual('hello'.encode('latin-1'), b'hello') # Default encoding is utf-8 self.assertEqual('\u2603'.encode(), b'\xe2\x98\x83') # Roundtrip safety for BMP (just the first 1024 chars) for c in range(1024): u = chr(c) for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le', 'utf-16-be', 'raw_unicode_escape', 'unicode_escape', 'unicode_internal'): with warnings.catch_warnings(): # unicode-internal has been deprecated warnings.simplefilter("ignore", DeprecationWarning) self.assertEqual(str(u.encode(encoding),encoding), u) # Roundtrip safety for BMP (just the first 256 chars) for c in range(256): u = chr(c) for encoding in ('latin-1',): self.assertEqual(str(u.encode(encoding),encoding), u) # Roundtrip safety for BMP (just the first 128 chars) for c in range(128): u = chr(c) for encoding in ('ascii',): self.assertEqual(str(u.encode(encoding),encoding), u) # Roundtrip safety for non-BMP (just a few chars) with warnings.catch_warnings(): # unicode-internal has been deprecated warnings.simplefilter("ignore", DeprecationWarning) u = '\U00010001\U00020002\U00030003\U00040004\U00050005' for encoding in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be', 'raw_unicode_escape', 'unicode_escape', 'unicode_internal'): self.assertEqual(str(u.encode(encoding),encoding), u) # UTF-8 must be roundtrip safe for all code points # (except surrogates, which are forbidden). u = ''.join(map(chr, list(range(0, 0xd800)) + list(range(0xe000, 0x110000)))) for encoding in ('utf-8',): self.assertEqual(str(u.encode(encoding),encoding), u) def test_codecs_charmap(self): # 0-127 s = bytes(range(128)) for encoding in ( 'cp037', 'cp1026', 'cp273', 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp865', 'cp866', 'cp1125', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_9', 'koi8_r', 'koi8_t', 'koi8_u', 'kz1048', 'latin_1', 'mac_cyrillic', 'mac_latin2', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874', 'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish', 'cp1006', 'iso8859_8', ### These have undefined mappings: #'cp424', ### These fail the round-trip: #'cp875' ): self.assertEqual(str(s, encoding).encode(encoding), s) # 128-255 s = bytes(range(128, 256)) for encoding in ( 'cp037', 'cp1026', 'cp273', 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp865', 'cp866', 'cp1125', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_2', 'iso8859_4', 'iso8859_5', 'iso8859_9', 'koi8_r', 'koi8_u', 'latin_1', 'mac_cyrillic', 'mac_latin2', ### These have undefined mappings: #'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', #'cp1256', 'cp1257', 'cp1258', #'cp424', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874', #'iso8859_3', 'iso8859_6', 'iso8859_7', 'koi8_t', 'kz1048', #'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish', ### These fail the round-trip: #'cp1006', 'cp875', 'iso8859_8', ): self.assertEqual(str(s, encoding).encode(encoding), s) def test_concatenation(self): self.assertEqual(("abc" "def"), "abcdef") self.assertEqual(("abc" "def"), "abcdef") self.assertEqual(("abc" "def"), "abcdef") self.assertEqual(("abc" "def" "ghi"), "abcdefghi") self.assertEqual(("abc" "def" "ghi"), "abcdefghi") def test_printing(self): class BitBucket: def write(self, text): pass out = BitBucket() print('abc', file=out) print('abc', 'def', file=out) print('abc', 'def', file=out) print('abc', 'def', file=out) print('abc\n', file=out) print('abc\n', end=' ', file=out) print('abc\n', end=' ', file=out) print('def\n', file=out) print('def\n', file=out) def test_ucs4(self): x = '\U00100000' y = x.encode("raw-unicode-escape").decode("raw-unicode-escape") self.assertEqual(x, y) y = br'\U00100000' x = y.decode("raw-unicode-escape").encode("raw-unicode-escape") self.assertEqual(x, y) y = br'\U00010000' x = y.decode("raw-unicode-escape").encode("raw-unicode-escape") self.assertEqual(x, y) try: br'\U11111111'.decode("raw-unicode-escape") except UnicodeDecodeError as e: self.assertEqual(e.start, 0) self.assertEqual(e.end, 10) else: self.fail("Should have raised UnicodeDecodeError") def test_conversion(self): # Make sure __str__() works properly class ObjectToStr: def __str__(self): return "foo" class StrSubclassToStr(str): def __str__(self): return "foo" class StrSubclassToStrSubclass(str): def __new__(cls, content=""): return str.__new__(cls, 2*content) def __str__(self): return self self.assertEqual(str(ObjectToStr()), "foo") self.assertEqual(str(StrSubclassToStr("bar")), "foo") s = str(StrSubclassToStrSubclass("foo")) self.assertEqual(s, "foofoo") self.assertIs(type(s), StrSubclassToStrSubclass) s = StrSubclass(StrSubclassToStrSubclass("foo")) self.assertEqual(s, "foofoo") self.assertIs(type(s), StrSubclass) def test_unicode_repr(self): class s1: def __repr__(self): return '\\n' class s2: def __repr__(self): return '\\n' self.assertEqual(repr(s1()), '\\n') self.assertEqual(repr(s2()), '\\n') def test_printable_repr(self): self.assertEqual(repr('\U00010000'), "'%c'" % (0x10000,)) # printable self.assertEqual(repr('\U00014000'), "'\\U00014000'") # nonprintable # This test only affects 32-bit platforms because expandtabs can only take # an int as the max value, not a 64-bit C long. If expandtabs is changed # to take a 64-bit long, this test should apply to all platforms. @unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4, 'only applies to 32-bit platforms') def test_expandtabs_overflows_gracefully(self): self.assertRaises(OverflowError, 't\tt\t'.expandtabs, sys.maxsize) @support.cpython_only def test_expandtabs_optimization(self): s = 'abc' self.assertIs(s.expandtabs(), s) def test_raiseMemError(self): if struct.calcsize('P') == 8: # 64 bits pointers ascii_struct_size = 48 compact_struct_size = 72 else: # 32 bits pointers ascii_struct_size = 24 compact_struct_size = 36 for char in ('a', '\xe9', '\u20ac', '\U0010ffff'): code = ord(char) if code < 0x100: char_size = 1 # sizeof(Py_UCS1) struct_size = ascii_struct_size elif code < 0x10000: char_size = 2 # sizeof(Py_UCS2) struct_size = compact_struct_size else: char_size = 4 # sizeof(Py_UCS4) struct_size = compact_struct_size # Note: sys.maxsize is half of the actual max allocation because of # the signedness of Py_ssize_t. Strings of maxlen-1 should in principle # be allocatable, given enough memory. maxlen = ((sys.maxsize - struct_size) // char_size) alloc = lambda: char * maxlen self.assertRaises(MemoryError, alloc) self.assertRaises(MemoryError, alloc) def test_format_subclass(self): class S(str): def __str__(self): return '__str__ overridden' s = S('xxx') self.assertEqual("%s" % s, '__str__ overridden') self.assertEqual("{}".format(s), '__str__ overridden') def test_subclass_add(self): class S(str): def __add__(self, o): return "3" self.assertEqual(S("4") + S("5"), "3") class S(str): def __iadd__(self, o): return "3" s = S("1") s += "4" self.assertEqual(s, "3") def test_getnewargs(self): text = 'abc' args = text.__getnewargs__() self.assertIsNot(args[0], text) self.assertEqual(args[0], text) self.assertEqual(len(args), 1) def test_resize(self): for length in range(1, 100, 7): # generate a fresh string (refcount=1) text = 'a' * length + 'b' with support.check_warnings(('unicode_internal codec has been ' 'deprecated', DeprecationWarning)): # fill wstr internal field abc = text.encode('unicode_internal') self.assertEqual(abc.decode('unicode_internal'), text) # resize text: wstr field must be cleared and then recomputed text += 'c' abcdef = text.encode('unicode_internal') self.assertNotEqual(abc, abcdef) self.assertEqual(abcdef.decode('unicode_internal'), text) def test_compare(self): # Issue #17615 N = 10 ascii = 'a' * N ascii2 = 'z' * N latin = '\x80' * N latin2 = '\xff' * N bmp = '\u0100' * N bmp2 = '\uffff' * N astral = '\U00100000' * N astral2 = '\U0010ffff' * N strings = ( ascii, ascii2, latin, latin2, bmp, bmp2, astral, astral2) for text1, text2 in itertools.combinations(strings, 2): equal = (text1 is text2) self.assertEqual(text1 == text2, equal) self.assertEqual(text1 != text2, not equal) if equal: self.assertTrue(text1 <= text2) self.assertTrue(text1 >= text2) # text1 is text2: duplicate strings to skip the "str1 == str2" # optimization in unicode_compare_eq() and really compare # character per character copy1 = duplicate_string(text1) copy2 = duplicate_string(text2) self.assertIsNot(copy1, copy2) self.assertTrue(copy1 == copy2) self.assertFalse(copy1 != copy2) self.assertTrue(copy1 <= copy2) self.assertTrue(copy2 >= copy2) self.assertTrue(ascii < ascii2) self.assertTrue(ascii < latin) self.assertTrue(ascii < bmp) self.assertTrue(ascii < astral) self.assertFalse(ascii >= ascii2) self.assertFalse(ascii >= latin) self.assertFalse(ascii >= bmp) self.assertFalse(ascii >= astral) self.assertFalse(latin < ascii) self.assertTrue(latin < latin2) self.assertTrue(latin < bmp) self.assertTrue(latin < astral) self.assertTrue(latin >= ascii) self.assertFalse(latin >= latin2) self.assertFalse(latin >= bmp) self.assertFalse(latin >= astral) self.assertFalse(bmp < ascii) self.assertFalse(bmp < latin) self.assertTrue(bmp < bmp2) self.assertTrue(bmp < astral) self.assertTrue(bmp >= ascii) self.assertTrue(bmp >= latin) self.assertFalse(bmp >= bmp2) self.assertFalse(bmp >= astral) self.assertFalse(astral < ascii) self.assertFalse(astral < latin) self.assertFalse(astral < bmp2) self.assertTrue(astral < astral2) self.assertTrue(astral >= ascii) self.assertTrue(astral >= latin) self.assertTrue(astral >= bmp2) self.assertFalse(astral >= astral2) def test_free_after_iterating(self): support.check_free_after_iterating(self, iter, str) support.check_free_after_iterating(self, reversed, str) class CAPITest(unittest.TestCase): # Test PyUnicode_FromFormat() def test_from_format(self): support.import_module('ctypes') from ctypes import ( pythonapi, py_object, sizeof, c_int, c_long, c_longlong, c_ssize_t, c_uint, c_ulong, c_ulonglong, c_size_t, c_void_p) name = "PyUnicode_FromFormat" _PyUnicode_FromFormat = getattr(pythonapi, name) _PyUnicode_FromFormat.restype = py_object def PyUnicode_FromFormat(format, *args): cargs = tuple( py_object(arg) if isinstance(arg, str) else arg for arg in args) return _PyUnicode_FromFormat(format, *cargs) def check_format(expected, format, *args): text = PyUnicode_FromFormat(format, *args) self.assertEqual(expected, text) # ascii format, non-ascii argument check_format('ascii\x7f=unicode\xe9', b'ascii\x7f=%U', 'unicode\xe9') # non-ascii format, ascii argument: ensure that PyUnicode_FromFormatV() # raises an error self.assertRaisesRegex(ValueError, r'^PyUnicode_FromFormatV\(\) expects an ASCII-encoded format ' 'string, got a non-ASCII byte: 0xe9$', PyUnicode_FromFormat, b'unicode\xe9=%s', 'ascii') # test "%c" check_format('\uabcd', b'%c', c_int(0xabcd)) check_format('\U0010ffff', b'%c', c_int(0x10ffff)) with self.assertRaises(OverflowError): PyUnicode_FromFormat(b'%c', c_int(0x110000)) # Issue #18183 check_format('\U00010000\U00100000', b'%c%c', c_int(0x10000), c_int(0x100000)) # test "%" check_format('%', b'%') check_format('%', b'%%') check_format('%s', b'%%s') check_format('[%]', b'[%%]') check_format('%abc', b'%%%s', b'abc') # truncated string check_format('abc', b'%.3s', b'abcdef') check_format('abc[\ufffd', b'%.5s', 'abc[\u20ac]'.encode('utf8')) check_format("'\\u20acABC'", b'%A', '\u20acABC') check_format("'\\u20", b'%.5A', '\u20acABCDEF') check_format("'\u20acABC'", b'%R', '\u20acABC') check_format("'\u20acA", b'%.3R', '\u20acABCDEF') check_format('\u20acAB', b'%.3S', '\u20acABCDEF') check_format('\u20acAB', b'%.3U', '\u20acABCDEF') check_format('\u20acAB', b'%.3V', '\u20acABCDEF', None) check_format('abc[\ufffd', b'%.5V', None, 'abc[\u20ac]'.encode('utf8')) # following tests comes from #7330 # test width modifier and precision modifier with %S check_format("repr= abc", b'repr=%5S', 'abc') check_format("repr=ab", b'repr=%.2S', 'abc') check_format("repr= ab", b'repr=%5.2S', 'abc') # test width modifier and precision modifier with %R check_format("repr= 'abc'", b'repr=%8R', 'abc') check_format("repr='ab", b'repr=%.3R', 'abc') check_format("repr= 'ab", b'repr=%5.3R', 'abc') # test width modifier and precision modifier with %A check_format("repr= 'abc'", b'repr=%8A', 'abc') check_format("repr='ab", b'repr=%.3A', 'abc') check_format("repr= 'ab", b'repr=%5.3A', 'abc') # test width modifier and precision modifier with %s check_format("repr= abc", b'repr=%5s', b'abc') check_format("repr=ab", b'repr=%.2s', b'abc') check_format("repr= ab", b'repr=%5.2s', b'abc') # test width modifier and precision modifier with %U check_format("repr= abc", b'repr=%5U', 'abc') check_format("repr=ab", b'repr=%.2U', 'abc') check_format("repr= ab", b'repr=%5.2U', 'abc') # test width modifier and precision modifier with %V check_format("repr= abc", b'repr=%5V', 'abc', b'123') check_format("repr=ab", b'repr=%.2V', 'abc', b'123') check_format("repr= ab", b'repr=%5.2V', 'abc', b'123') check_format("repr= 123", b'repr=%5V', None, b'123') check_format("repr=12", b'repr=%.2V', None, b'123') check_format("repr= 12", b'repr=%5.2V', None, b'123') # test integer formats (%i, %d, %u) check_format('010', b'%03i', c_int(10)) check_format('0010', b'%0.4i', c_int(10)) check_format('-123', b'%i', c_int(-123)) check_format('-123', b'%li', c_long(-123)) check_format('-123', b'%lli', c_longlong(-123)) check_format('-123', b'%zi', c_ssize_t(-123)) check_format('-123', b'%d', c_int(-123)) check_format('-123', b'%ld', c_long(-123)) check_format('-123', b'%lld', c_longlong(-123)) check_format('-123', b'%zd', c_ssize_t(-123)) check_format('123', b'%u', c_uint(123)) check_format('123', b'%lu', c_ulong(123)) check_format('123', b'%llu', c_ulonglong(123)) check_format('123', b'%zu', c_size_t(123)) # test long output min_longlong = -(2 ** (8 * sizeof(c_longlong) - 1)) max_longlong = -min_longlong - 1 check_format(str(min_longlong), b'%lld', c_longlong(min_longlong)) check_format(str(max_longlong), b'%lld', c_longlong(max_longlong)) max_ulonglong = 2 ** (8 * sizeof(c_ulonglong)) - 1 check_format(str(max_ulonglong), b'%llu', c_ulonglong(max_ulonglong)) PyUnicode_FromFormat(b'%p', c_void_p(-1)) # test padding (width and/or precision) check_format('123'.rjust(10, '0'), b'%010i', c_int(123)) check_format('123'.rjust(100), b'%100i', c_int(123)) check_format('123'.rjust(100, '0'), b'%.100i', c_int(123)) check_format('123'.rjust(80, '0').rjust(100), b'%100.80i', c_int(123)) check_format('123'.rjust(10, '0'), b'%010u', c_uint(123)) check_format('123'.rjust(100), b'%100u', c_uint(123)) check_format('123'.rjust(100, '0'), b'%.100u', c_uint(123)) check_format('123'.rjust(80, '0').rjust(100), b'%100.80u', c_uint(123)) check_format('123'.rjust(10, '0'), b'%010x', c_int(0x123)) check_format('123'.rjust(100), b'%100x', c_int(0x123)) check_format('123'.rjust(100, '0'), b'%.100x', c_int(0x123)) check_format('123'.rjust(80, '0').rjust(100), b'%100.80x', c_int(0x123)) # test %A check_format(r"%A:'abc\xe9\uabcd\U0010ffff'", b'%%A:%A', 'abc\xe9\uabcd\U0010ffff') # test %V check_format('repr=abc', b'repr=%V', 'abc', b'xyz') # Test string decode from parameter of %s using utf-8. # b'\xe4\xba\xba\xe6\xb0\x91' is utf-8 encoded byte sequence of # '\u4eba\u6c11' check_format('repr=\u4eba\u6c11', b'repr=%V', None, b'\xe4\xba\xba\xe6\xb0\x91') #Test replace error handler. check_format('repr=abc\ufffd', b'repr=%V', None, b'abc\xff') # not supported: copy the raw format string. these tests are just here # to check for crashes and should not be considered as specifications check_format('%s', b'%1%s', b'abc') check_format('%1abc', b'%1abc') check_format('%+i', b'%+i', c_int(10)) check_format('%.%s', b'%.%s', b'abc') # Test PyUnicode_AsWideChar() @support.cpython_only def test_aswidechar(self): from _testcapi import unicode_aswidechar support.import_module('ctypes') from ctypes import c_wchar, sizeof wchar, size = unicode_aswidechar('abcdef', 2) self.assertEqual(size, 2) self.assertEqual(wchar, 'ab') wchar, size = unicode_aswidechar('abc', 3) self.assertEqual(size, 3) self.assertEqual(wchar, 'abc') wchar, size = unicode_aswidechar('abc', 4) self.assertEqual(size, 3) self.assertEqual(wchar, 'abc\0') wchar, size = unicode_aswidechar('abc', 10) self.assertEqual(size, 3) self.assertEqual(wchar, 'abc\0') wchar, size = unicode_aswidechar('abc\0def', 20) self.assertEqual(size, 7) self.assertEqual(wchar, 'abc\0def\0') nonbmp = chr(0x10ffff) if sizeof(c_wchar) == 2: buflen = 3 nchar = 2 else: # sizeof(c_wchar) == 4 buflen = 2 nchar = 1 wchar, size = unicode_aswidechar(nonbmp, buflen) self.assertEqual(size, nchar) self.assertEqual(wchar, nonbmp + '\0') # Test PyUnicode_AsWideCharString() @support.cpython_only def test_aswidecharstring(self): from _testcapi import unicode_aswidecharstring support.import_module('ctypes') from ctypes import c_wchar, sizeof wchar, size = unicode_aswidecharstring('abc') self.assertEqual(size, 3) self.assertEqual(wchar, 'abc\0') wchar, size = unicode_aswidecharstring('abc\0def') self.assertEqual(size, 7) self.assertEqual(wchar, 'abc\0def\0') nonbmp = chr(0x10ffff) if sizeof(c_wchar) == 2: nchar = 2 else: # sizeof(c_wchar) == 4 nchar = 1 wchar, size = unicode_aswidecharstring(nonbmp) self.assertEqual(size, nchar) self.assertEqual(wchar, nonbmp + '\0') # Test PyUnicode_AsUCS4() @support.cpython_only def test_asucs4(self): from _testcapi import unicode_asucs4 for s in ['abc', '\xa1\xa2', '\u4f60\u597d', 'a\U0001f600', 'a\ud800b\udfffc', '\ud834\udd1e']: l = len(s) self.assertEqual(unicode_asucs4(s, l, 1), s+'\0') self.assertEqual(unicode_asucs4(s, l, 0), s+'\uffff') self.assertEqual(unicode_asucs4(s, l+1, 1), s+'\0\uffff') self.assertEqual(unicode_asucs4(s, l+1, 0), s+'\0\uffff') self.assertRaises(SystemError, unicode_asucs4, s, l-1, 1) self.assertRaises(SystemError, unicode_asucs4, s, l-2, 0) s = '\0'.join([s, s]) self.assertEqual(unicode_asucs4(s, len(s), 1), s+'\0') self.assertEqual(unicode_asucs4(s, len(s), 0), s+'\uffff') # Test PyUnicode_FindChar() @support.cpython_only def test_findchar(self): from _testcapi import unicode_findchar for str in "\xa1", "\u8000\u8080", "\ud800\udc02", "\U0001f100\U0001f1f1": for i, ch in enumerate(str): self.assertEqual(unicode_findchar(str, ord(ch), 0, len(str), 1), i) self.assertEqual(unicode_findchar(str, ord(ch), 0, len(str), -1), i) str = "!>_<!" self.assertEqual(unicode_findchar(str, 0x110000, 0, len(str), 1), -1) self.assertEqual(unicode_findchar(str, 0x110000, 0, len(str), -1), -1) # start < end self.assertEqual(unicode_findchar(str, ord('!'), 1, len(str)+1, 1), 4) self.assertEqual(unicode_findchar(str, ord('!'), 1, len(str)+1, -1), 4) # start >= end self.assertEqual(unicode_findchar(str, ord('!'), 0, 0, 1), -1) self.assertEqual(unicode_findchar(str, ord('!'), len(str), 0, 1), -1) # negative self.assertEqual(unicode_findchar(str, ord('!'), -len(str), -1, 1), 0) self.assertEqual(unicode_findchar(str, ord('!'), -len(str), -1, -1), 0) # Test PyUnicode_CopyCharacters() @support.cpython_only def test_copycharacters(self): from _testcapi import unicode_copycharacters strings = [ 'abcde', '\xa1\xa2\xa3\xa4\xa5', '\u4f60\u597d\u4e16\u754c\uff01', '\U0001f600\U0001f601\U0001f602\U0001f603\U0001f604' ] for idx, from_ in enumerate(strings): # wide -> narrow: exceed maxchar limitation for to in strings[:idx]: self.assertRaises( SystemError, unicode_copycharacters, to, 0, from_, 0, 5 ) # same kind for from_start in range(5): self.assertEqual( unicode_copycharacters(from_, 0, from_, from_start, 5), (from_[from_start:from_start+5].ljust(5, '\0'), 5-from_start) ) for to_start in range(5): self.assertEqual( unicode_copycharacters(from_, to_start, from_, to_start, 5), (from_[to_start:to_start+5].rjust(5, '\0'), 5-to_start) ) # narrow -> wide # Tests omitted since this creates invalid strings. s = strings[0] self.assertRaises(IndexError, unicode_copycharacters, s, 6, s, 0, 5) self.assertRaises(IndexError, unicode_copycharacters, s, -1, s, 0, 5) self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, 6, 5) self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, -1, 5) self.assertRaises(SystemError, unicode_copycharacters, s, 1, s, 0, 5) self.assertRaises(SystemError, unicode_copycharacters, s, 0, s, 0, -1) self.assertRaises(SystemError, unicode_copycharacters, s, 0, b'', 0, 0) @support.cpython_only def test_encode_decimal(self): from _testcapi import unicode_encodedecimal
ansform_decimal(self): from _testcapi import unicode_transformdecimaltoascii as transform_decimal self.assertEqual(transform_decimal('123'), '123') self.assertEqual(transform_decimal('\u0663.\u0661\u0664'), '3.14') self.assertEqual(transform_decimal("\N{EM SPACE}3.14\N{EN SPACE}"), "\N{EM SPACE}3.14\N{EN SPACE}") self.assertEqual(transform_decimal('123\u20ac'), '123\u20ac') @support.cpython_only def test_pep393_utf8_caching_bug(self): # Issue #25709: Problem with string concatenation and utf-8 cache from _testcapi import getargs_s_hash for k in 0x24, 0xa4, 0x20ac, 0x1f40d: s = '' for i in range(5): # Due to CPython specific optimization the 's' string can be # resized in-place. s += chr(k) # Parsing with the "s#" format code calls indirectly # PyUnicode_AsUTF8AndSize() which creates the UTF-8 # encoded string cached in the Unicode object. self.assertEqual(getargs_s_hash(s), chr(k).encode() * (i + 1)) # Check that the second call returns the same result self.assertEqual(getargs_s_hash(s), chr(k).encode() * (i + 1)) class StringModuleTest(unittest.TestCase): def test_formatter_parser(self): def parse(format): return list(_string.formatter_parser(format)) formatter = parse("prefix {2!s}xxx{0:^+10.3f}{obj.attr!s} {z[0]!s:10}") self.assertEqual(formatter, [ ('prefix ', '2', '', 's'), ('xxx', '0', '^+10.3f', None), ('', 'obj.attr', '', 's'), (' ', 'z[0]', '10', 's'), ]) formatter = parse("prefix {} suffix") self.assertEqual(formatter, [ ('prefix ', '', '', None), (' suffix', None, None, None), ]) formatter = parse("str") self.assertEqual(formatter, [ ('str', None, None, None), ]) formatter = parse("") self.assertEqual(formatter, []) formatter = parse("{0}") self.assertEqual(formatter, [ ('', '0', '', None), ]) self.assertRaises(TypeError, _string.formatter_parser, 1) def test_formatter_field_name_split(self): def split(name): items = list(_string.formatter_field_name_split(name)) items[1] = list(items[1]) return items self.assertEqual(split("obj"), ["obj", []]) self.assertEqual(split("obj.arg"), ["obj", [(True, 'arg')]]) self.assertEqual(split("obj[key]"), ["obj", [(False, 'key')]]) self.assertEqual(split("obj.arg[key1][key2]"), [ "obj", [(True, 'arg'), (False, 'key1'), (False, 'key2'), ]]) self.assertRaises(TypeError, _string.formatter_field_name_split, 1) if __name__ == "__main__": unittest.main()
self.assertEqual(unicode_encodedecimal('123'), b'123') self.assertEqual(unicode_encodedecimal('\u0663.\u0661\u0664'), b'3.14') self.assertEqual(unicode_encodedecimal("\N{EM SPACE}3.14\N{EN SPACE}"), b' 3.14 ') self.assertRaises(UnicodeEncodeError, unicode_encodedecimal, "123\u20ac", "strict") self.assertRaisesRegex( ValueError, "^'decimal' codec can't encode character", unicode_encodedecimal, "123\u20ac", "replace") @support.cpython_only def test_tr
c_dual_list_selector__list_item_row_BackgroundColor.d.ts
export const c_dual_list_selector__list_item_row_BackgroundColor: { "name": "--pf-c-dual-list-selector__list-item-row--BackgroundColor", "value": "#fff", "var": "var(--pf-c-dual-list-selector__list-item-row--BackgroundColor)" };
export default c_dual_list_selector__list_item_row_BackgroundColor;
OrphanagesMap.tsx
import React, { useEffect, useState } from 'react'; import { StyleSheet, Text, View, Dimensions, TouchableOpacity } from 'react-native'; import MapView, { Marker, Callout, PROVIDER_GOOGLE } from 'react-native-maps'; import { useNavigation, useFocusEffect } from '@react-navigation/native'; import { Feather } from '@expo/vector-icons'; import mapMarker from '../images/map-marker.png'; import { RectButton } from 'react-native-gesture-handler'; import api from '../services/api'; interface Orphanage { id: number; name: string; latitude: number; longitude: number; } export default function OrphanagesMap() { const navigation = useNavigation() const [orphanages, setOrphanages] = useState<Orphanage[]>([]); // aqui voce esta dizendo que esse estado vai armazenar um array de objetos no formato Orphanage useFocusEffect( () => { api.get('orphanages').then(response => { setOrphanages(response.data); }); }); function handleNavigateToOrphanageDetails(id: number){ navigation.navigate('OrphanageDetails', { id }); // redireciona para essa pagina } function handleNavigateToCreateOrphanage(){ navigation.navigate('SelectMapPosition'); } return ( <View style={styles.container}> <MapView provider = {PROVIDER_GOOGLE} style={styles.map} initialRegion= {{ latitude: -21.5959093, longitude: -48.3489365, latitudeDelta: 0.008, longitudeDelta: 0.008, }} > {orphanages.map(orphanage => { return ( <Marker key={orphanage.id} icon= {mapMarker} calloutAnchor = {{ x: 2.7, y: 0.8, }} coordinate= {{ latitude: orphanage.latitude, longitude: orphanage.longitude, }} > <Callout tooltip={true} onPress={() => handleNavigateToOrphanageDetails(orphanage.id)}>
<Text style={styles.calloutText}>{orphanage.name}</Text> </View> </Callout> </Marker> ); }) } </MapView> <View style={styles.footer}> <Text style={styles.footerText}>{orphanages.length} orfanatos encontrados</Text> <RectButton style={styles.createOrphanagesButton} onPress={handleNavigateToCreateOrphanage}> <Feather name="plus" size={20} color="#FFF" /> </RectButton> </View> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, }, map: { width: Dimensions.get('window').width, height: Dimensions.get('window').height, }, calloutContainer:{ width: 160, height: 46, paddingHorizontal: 16, backgroundColor: 'rgba(255, 255, 255, 0.8)', borderRadius: 16, justifyContent: 'center', }, calloutText: { color: "#0089a5", fontSize: 14, fontFamily: 'Nunito_700Bold', }, footer: { position: 'absolute', left: 24, right: 24, bottom: 32, backgroundColor: "#FFF", borderRadius: 20, height: 56, paddingLeft: 24, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', elevation: 3, }, footerText: { fontFamily: 'Nunito_700Bold', color:'#8fa7b3', }, createOrphanagesButton: { width: 56, height: 56, backgroundColor: '#15c3d6', borderRadius: 20, justifyContent: 'center', alignItems: 'center', }, });
<View style={styles.calloutContainer}>
aoc2021-19.js
const fs = require('fs') const lines = fs.readFileSync(__dirname + '/aoc2021-19.txt', 'utf-8').split(/\r?\n/); const scanners = []; let currentScanner = null; lines.forEach(l => { if (l.length <= 1); else if (l.startsWith('---')) { currentScanner = []; scanners.push(currentScanner); } else currentScanner.push(l.split(',').map(x => +x)); }) const matrixIdentity = (dimension) => { return Array(dimension).fill(0).map((_, i) => { const l = Array(dimension).fill(0); l[i] = 1; return l; }); } const matrixMultiply = (m1, m2) => { // m1 size (y1, x1) x m2 size (y2, x2) => size (y3=y1, x3=x2) - x1 must be equal y2 const result = []; for (let yTarget = 0; yTarget < m1.length; yTarget++) { const line = []; result.push(line); for (let xTarget = 0; xTarget < m2[0].length; xTarget++) { let cell = 0; for (let i = 0; i < m2.length; i++) { cell += m1[yTarget][i] * m2[i][xTarget]; } line.push(cell); } } return result; } const matrixPow = (matrix, n) => { let result = matrixIdentity(matrix.length); for (let i = 0; i < n; i++) result = matrixMultiply(result, matrix); return result; } const matrixSerialize = (m) => m.map(x => x.join(',')).join('|'); // 24 uniques rotation matrices with quarter turn in X, Y, Z const combinations = ['', 'X', 'Y', 'XX', 'XY', 'YX', 'YY', 'XXX', 'XXY', 'XYX', 'XYY', 'YXX', 'YYX', 'YYY', 'XXXY', 'XXYX', 'XXYY', 'XYXX', 'XYYY', 'YXXX', 'YYYX', 'XXXYX', 'XYXXX', 'XYYYX']; const inverseCombinations = ['', 'XXX', 'YYY', 'XX', 'YYYXXX', 'XXXYYY', 'YY', 'X', 'YYYXX', 'XYX', 'XYY', 'YXX', 'YYX', 'Y', 'YYYX', 'XXXYYYXX', 'YYXX', 'XXYYYXXX', 'YXXX', 'XYYY', 'XXXY', 'XXXYYYX', 'XYYYXXX', 'XYYYX']; const getRotationMatrices = () => { const matrixX = [ [1, 0, 0], [0, Math.round(Math.cos(Math.PI / 2)), Math.round(Math.sin(Math.PI / 2))], [0, Math.round(-Math.sin(Math.PI / 2)), Math.round(Math.cos(Math.PI / 2))] ]; const matrixY = [ [Math.round(Math.cos(Math.PI / 2)), 0, Math.round(-Math.sin(Math.PI / 2))], [0, 1, 0], [Math.round(Math.sin(Math.PI / 2)), 0, Math.round(Math.cos(Math.PI / 2))] ]; const matrixZ = [ [Math.round(Math.cos(Math.PI / 2)), Math.round(Math.sin(Math.PI / 2)), 0], [Math.round(-Math.sin(Math.PI / 2)), Math.round(Math.cos(Math.PI / 2)), 0], [0, 0, 1] ]; /* const rotationsMatrices = []; for (let x = 0; x < 4; x++) { const X = matrixPow(matrixX, x); for (let y = 0; y < 4; y++) { const Y = matrixPow(matrixY, y); const XY = matrixMultiply(X, Y); for (let z = 0; z < 4; z++) { const Z = matrixPow(matrixZ, z); const XYZ = matrixMultiply(XY, Z); rotationsMatrices.push(XYZ); } } } const hashes = rotationsMatrices.map(matrixSerialize); const hashesToIndex = Object.fromEntries(Object.entries(hashes).map(([k, v]) => [v, k])); const indexes = Object.values(hashesToIndex).map(a => +a).sort((a, b) => a - b); return indexes.map(i => rotationsMatrices[i]); */ const genMatrix = combinations => combinations.map(c => { let m = matrixIdentity(3); for (const axis of Array.from(c)) { if (axis === 'X') m = matrixMultiply(m, matrixX); if (axis === 'Y') m = matrixMultiply(m, matrixY); if (axis === 'Z') m = matrixMultiply(m, matrixZ); } return m; }); const result1 = genMatrix(combinations); const result2 = genMatrix(inverseCombinations); const rotationMatrixToIndex = {}; for (let i = 0; i < result1.length; i++) { const m = matrixMultiply(result1[i], result2[i]); if (matrixSerialize(m) !== '1,0,0|0,1,0|0,0,1') throw new Error(`Error rotation matrix ${i}: ${combinations[i]} is not inverse of ${inverseCombinations[i]}`); rotationMatrixToIndex[matrixSerialize(result1[i])] = i; } return [result1, result2, rotationMatrixToIndex]; }; const [rotationMatrices, inverseRotationMatrices, rotationMatrixToIndex] = getRotationMatrices(); const vectorDiff = (pt1, pt2) => pt1.map((x, i) => x - pt2[i]); const vectorAdd = (pt1, pt2) => pt1.map((x, i) => x + pt2[i]); const vectorDistManhattan = (pt1, pt2) => pt1.reduce((agg, x, i) => agg + Math.abs(x - pt2[i]), 0); const getPointsBestMatch = (scan1, scan2) => { const pointCounts0 = {}; for (const pt of scan1) { const key = pt.join(','); pointCounts0[key] = (pointCounts0[key] ?? 0) + 1; } for (let i = 0; i < rotationMatrices.length; i++) { const rotationMatrix = rotationMatrices[i]; const rotatedPoints = scan2.map(pt => matrixMultiply([pt], rotationMatrix)[0]); for (const pt1 of scan1) { for (const pt2 of rotatedPoints) { const translation = vectorDiff(pt1, pt2); const translatedPts = rotatedPoints.map(pt => vectorAdd(pt, translation)); const pointCounts = {...pointCounts0}; for (const pt of translatedPts) { const key = pt.join(','); pointCounts[key] = (pointCounts[key] ?? 0) + 1; } const nbCommon = Object.values(pointCounts).filter(x => x === 2).length; if (nbCommon >= 12) { return { rotationIndex: i, translation }; } } } } return null; } function getInverseRelation(match, from, to) { const inverseMatrix = inverseRotationMatrices[match.rotationIndex]; const inverseMatrixIndex = rotationMatrixToIndex[matrixSerialize(inverseMatrix)]; const inverseRotationMatrix = rotationMatrices[inverseMatrixIndex]; const inverseTranslation = matrixMultiply([match.translation], inverseRotationMatrix)[0].map(x => -x); return { from: to, to: from, added: false, rotationIndex: inverseMatrixIndex, translation: inverseTranslation }; } const getPointsInScanner0Coordinate = (index, tree, points) => { const findPath = (index, tree, currentTransformation) => { if (tree.links[index]) return [...currentTransformation, tree.links[index].transformation]; for (const link of Object.values(tree.links)) { const result = findPath(index, link, [...currentTransformation, link.transformation]); if (result) return result; } return null; } const transformations = findPath(index, tree, []); let translation = [0, 0, 0]; let pts = points; for (const t of transformations.reverse()) { translation = vectorAdd(matrixMultiply([translation], rotationMatrices[t.rotationIndex])[0], t.translation); pts = pts.map(pt => vectorAdd(matrixMultiply([pt], rotationMatrices[t.rotationIndex])[0], t.translation)); } return [translation, pts]; }; function
() { const relativePositions = []; for (let to = 0; to < scanners.length - 1; to++) { for (let from = to + 1; from < scanners.length; from++) { const match = getPointsBestMatch(scanners[to], scanners[from]); if (match) { console.log(`Found transformation from ${from} to ${to} with rotation ${combinations[match.rotationIndex]} and translation [${match.translation.join(',')}]`); relativePositions.push({ from, to, added: false, ...match }); relativePositions.push(getInverseRelation(match, from, to)); } } } return relativePositions; } function computeTranslationTree(transformations) { const translationTree = {links: {}}; const indexToTree = [translationTree]; while (!transformations.every(x => x.added)) { for (const r of transformations) { if (r.added) continue; const toNode = indexToTree[r.to]; if (toNode) { toNode.links[r.from] = {transformation: r, links: {}}; r.added = true; if (!indexToTree[r.from]) { indexToTree[r.from] = toNode.links[r.from]; } } } } return translationTree; } const part = () => { const transformations = computeTransformations(); const translationTree = computeTranslationTree(transformations); const positions = [[0, 0, 0]]; const points = scanners[0].slice(); for (let index = 1; index < scanners.length; index++) { const [translation, pts] = getPointsInScanner0Coordinate(index, translationTree, scanners[index]); points.push(...pts); positions.push(translation); } const hashes = points.map(x => x.join(',')); const hashesToIndex = Object.fromEntries(Object.entries(hashes).map(([k, v]) => [v, k])); const indexes = Object.values(hashesToIndex).map(a => +a).sort((a, b) => a - b); const nbDistinctPoints = indexes.length; let maxDist = 0; for (let i = 0; i < positions.length - 1; i++) { for (let j = i + 1; j < positions.length; j++) { const d = vectorDistManhattan(positions[i], positions[j]); maxDist = Math.max(maxDist, d); } } return [nbDistinctPoints, maxDist]; }; console.log(part());
computeTransformations
drm_client.ts
/* eslint-disable @typescript-eslint/no-unused-vars */ /* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { AbstractClient } from "../../../common/abstract_client" import { ClientConfig } from "../../../common/interface" import { CreateLicenseResponse, KeyParam, FairPlayPemDigestInfo, CreateEncryptKeysResponse, CreateLicenseRequest, DescribeAllKeysRequest, DrmSourceObject, CreateEncryptKeysRequest, ModifyFairPlayPemResponse, DescribeFairPlayPemResponse, Key, PlaybackPolicy, AddFairPlayPemResponse, AddFairPlayPemRequest,
DeleteFairPlayPemRequest, DescribeKeysResponse, DescribeAllKeysResponse, StartEncryptionRequest, ModifyFairPlayPemRequest, DeleteFairPlayPemResponse, DrmOutputPara, StartEncryptionResponse, DescribeFairPlayPemRequest, DescribeKeysRequest, DrmOutputObject, } from "./drm_models" /** * drm client * @class */ export class Client extends AbstractClient { constructor(clientConfig: ClientConfig) { super("drm.tencentcloudapi.com", "2018-11-15", clientConfig) } /** * 开发者调用该接口,启动一次内容文件的DRM加密工作流 */ async StartEncryption( req: StartEncryptionRequest, cb?: (error: string, rep: StartEncryptionResponse) => void ): Promise<StartEncryptionResponse> { return this.request("StartEncryption", req, cb) } /** * 本接口用来设置fairplay方案所需的私钥、私钥密钥、ask等信息。 如需使用fairplay方案,请务必先设置私钥。 */ async AddFairPlayPem( req: AddFairPlayPemRequest, cb?: (error: string, rep: AddFairPlayPemResponse) => void ): Promise<AddFairPlayPemResponse> { return this.request("AddFairPlayPem", req, cb) } /** * 该接口用来设置加密的密钥。注意,同一个content id,只能设置一次! */ async CreateEncryptKeys( req: CreateEncryptKeysRequest, cb?: (error: string, rep: CreateEncryptKeysResponse) => void ): Promise<CreateEncryptKeysResponse> { return this.request("CreateEncryptKeys", req, cb) } /** * 本接口用来生成DRM方案对应的播放许可证,开发者需提供DRM方案类型、内容类型参数,后台将生成许可证后返回许可证数据 开发者需要转发终端设备发出的许可证请求信息。 */ async CreateLicense( req: CreateLicenseRequest, cb?: (error: string, rep: CreateLicenseResponse) => void ): Promise<CreateLicenseResponse> { return this.request("CreateLicense", req, cb) } /** * 本接口用来设置fairplay方案所需的私钥、私钥密钥、ask等信息。 如需使用fairplay方案,请务必先设置私钥。 */ async ModifyFairPlayPem( req: ModifyFairPlayPemRequest, cb?: (error: string, rep: ModifyFairPlayPemResponse) => void ): Promise<ModifyFairPlayPemResponse> { return this.request("ModifyFairPlayPem", req, cb) } /** * 开发者需要指定使用的DRM类型、和需要加密的Track类型,后台返回加密使用的密钥 如果加密使用的ContentID没有关联的密钥信息,后台会自动生成新的密钥返回 */ async DescribeKeys( req: DescribeKeysRequest, cb?: (error: string, rep: DescribeKeysResponse) => void ): Promise<DescribeKeysResponse> { return this.request("DescribeKeys", req, cb) } /** * 本接口用来查询指定DRM类型、ContentType的所有加密密钥 */ async DescribeAllKeys( req: DescribeAllKeysRequest, cb?: (error: string, rep: DescribeAllKeysResponse) => void ): Promise<DescribeAllKeysResponse> { return this.request("DescribeAllKeys", req, cb) } /** * 本接口用来删除fairplay方案的私钥、ask等信息 注:高风险操作,删除后,您将无法使用腾讯云DRM提供的fairplay服务。 由于缓存,删除操作需要约半小时生效 */ async DeleteFairPlayPem( req: DeleteFairPlayPemRequest, cb?: (error: string, rep: DeleteFairPlayPemResponse) => void ): Promise<DeleteFairPlayPemResponse> { return this.request("DeleteFairPlayPem", req, cb) } /** * 该接口用来查询设置的FairPlay私钥校验信息。可用该接口校验设置的私钥与本身的私钥是否一致。 */ async DescribeFairPlayPem( req: DescribeFairPlayPemRequest, cb?: (error: string, rep: DescribeFairPlayPemResponse) => void ): Promise<DescribeFairPlayPemResponse> { return this.request("DescribeFairPlayPem", req, cb) } }
preprocess_google_dataset_main.py
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Preprocess the Google text summarization dataset. """ import argparse import csv import os import subprocess import preprocess_utils TEMP_FOLDER_NAME = "temp_preprocess_google_dataset" TEMP_FOLDER_DIR = "~/" + TEMP_FOLDER_NAME DATASET_NAME = "sentence-compression" DATASET_DIR = "~/" + DATASET_NAME + "/data" PREPROCESSED_FILE_PATH = "~/preprocessed_google_dataset.tsv" TRAIN_FILE_PATH = "~/train_google_dataset.tsv" TUNE_FILE_PATH = "~/tune_google_dataset.tsv" VALID_FILE_PATH = "~/valid_google_dataset.tsv" def __clean_up(): """ Clean up temporary intermediate files.""" subprocess.call(['rm', '-rf', TEMP_FOLDER_NAME], cwd=os.path.expanduser('~')) def
(): """ Download Google dataset from Github.""" if not os.path.isdir(os.path.expanduser("~/" + DATASET_NAME)): print("-------Downloading dataset-------") subprocess.call( "git clone https://github.com/google-research-datasets/sentence-compression.git " .split(), cwd=os.path.expanduser('~')) __unzip_data(DATASET_DIR) else: print("-------Updating dataset-------") output = subprocess.check_output("git pull".split(), cwd=os.path.expanduser("~/" + DATASET_NAME)) if output != b"Already up-to-date.\n": __unzip_data(DATASET_DIR) print("-------Dataset up to date-------") def __unzip_data(dataset_dir): """Unzip files in the Google dataset. Args: dataset_dir: the directory where the Google dataset is in. """ print("-------Unzipping dataset-------") for i in range(1, 11): subprocess.call( ["gunzip", "sent-comp.train" + str(i).zfill(2) + ".json.gz"], cwd=os.path.expanduser(dataset_dir)) subprocess.call("gunzip comp-data.eval.json.gz".split(), cwd=os.path.expanduser(dataset_dir)) def __format_data(): """ Format the dataset and clean up special characters. Returns: cleaned_sentences: a list of cleaned input sentences cleaned_summaries: a list of cleaned summaries corresponding to the input sentences """ print("-------Processing original sentences-------") for i in range(1, 11): subprocess.call('cat sent-comp.train' + str(i).zfill(2) + '.json | grep \'"sentence":\' > ~/' + TEMP_FOLDER_NAME + '/train' + str(i) + '.txt', shell=True, cwd=os.path.expanduser(DATASET_DIR)) subprocess.call('cat comp-data.eval.json | grep \'"sentence":\' > ~/' + TEMP_FOLDER_NAME + '/train11.txt', shell=True, cwd=os.path.expanduser(DATASET_DIR)) sentences = [] for i in range(1, 12): file_name = os.path.expanduser(TEMP_FOLDER_NAME) + '/train' + str( i) + '.txt' f = open(file_name, "r") odd_line = True for line in f: if odd_line: sentences.append(line[17:-3]) odd_line = not odd_line f.close() cleaned_sentences = preprocess_utils.text_strip(sentences) print("-------Processing summaries-------") for i in range(1, 11): subprocess.call('cat sent-comp.train' + str(i).zfill(2) + '.json | grep \'"headline":\' > ~/' + TEMP_FOLDER_NAME + '/train' + str(i) + '.txt', shell=True, cwd=os.path.expanduser(DATASET_DIR)) subprocess.call('cat comp-data.eval.json | grep \'"headline":\' > ~/' + TEMP_FOLDER_NAME + '/train11.txt', shell=True, cwd=os.path.expanduser(DATASET_DIR)) summaries = [] for i in range(1, 12): file_name = os.path.expanduser(TEMP_FOLDER_NAME) + '/train' + str( i) + '.txt' f = open(file_name, "r") for line in f: summaries.append(line[15:-3]) f.close() cleaned_summaries = preprocess_utils.text_strip(summaries) cleaned_sentences, cleaned_summaries = preprocess_utils.delete_empty_entry( cleaned_sentences, cleaned_summaries) preprocess_utils.validate_dataset(cleaned_sentences, cleaned_summaries) print("Number of samples is", len(cleaned_sentences)) return cleaned_sentences, cleaned_summaries def main(args): """Preprocess the Google dataset. Args: args: command line arguments. """ num_of_tuning_sam = args.num_of_tuning num_of_valid_sam = args.num_of_validation if num_of_valid_sam < 0 or num_of_tuning_sam < 0: raise Exception("Number of samples must be non-negative integers") if not os.path.isfile(os.path.expanduser(PREPROCESSED_FILE_PATH)): __clean_up() subprocess.call(['mkdir', TEMP_FOLDER_NAME], cwd=os.path.expanduser('~')) __download_data() cleaned_sentences, cleaned_summaries = __format_data() preprocess_utils.calculate_stats(cleaned_sentences, cleaned_summaries) spaced_sentences = preprocess_utils.tokenize_with_space(cleaned_sentences) spaced_summaries = preprocess_utils.tokenize_with_space(cleaned_summaries) __clean_up() with open(os.path.expanduser(PREPROCESSED_FILE_PATH), 'wt') as out_file: tsv_writer = csv.writer(out_file, delimiter='\t') for i in range(len(spaced_sentences)): tsv_writer.writerow([spaced_sentences[i], spaced_summaries[i]]) print("-------Preprocessed data saved to", PREPROCESSED_FILE_PATH, "-------") print("-------Now splitting dataset.-------") else: print("-------Preprocessed data exists. Now splitting dataset.-------") preprocess_utils.split_dataset(TRAIN_FILE_PATH, TUNE_FILE_PATH, VALID_FILE_PATH, PREPROCESSED_FILE_PATH, num_of_tuning_sam, num_of_valid_sam, whether_shuffle_entire_set=True, whether_shuffle_individual_file=True) if __name__ == "__main__": """ Preprocess the Google research text summarization dataset. See dataset at https://github.com/google-research-datasets/sentence-compression.git Dataset is split into training, tuning, and validation sets, with the number of samples in the tuning and validation set being specified in the command line argument. The three sets are saved in three separate tsv files, and all the preprocessed data are saved in another tsv file. usage: preprocess_google_dataset.py [-h] num_of_tuning num_of_validation positional arguments: num_of_tuning Number of tuning samples num_of_validation Number of validation samples optional arguments: -h, --help show this help message and exit """ parser = argparse.ArgumentParser() parser.add_argument("num_of_tuning", help="Number of tuning samples", type=int) parser.add_argument("num_of_validation", help="Number of validation samples", type=int) arguments = parser.parse_args() main(arguments)
__download_data
enterprise.go
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved. // See License.txt for license information. package app import ( "github.com/mattermost/mattermost-server/einterfaces" ejobs "github.com/mattermost/mattermost-server/einterfaces/jobs" tjobs "github.com/mattermost/mattermost-server/jobs/interfaces" "github.com/mattermost/mattermost-server/mlog" "github.com/mattermost/mattermost-server/model" ) var accountMigrationInterface func(*App) einterfaces.AccountMigrationInterface func RegisterAccountMigrationInterface(f func(*App) einterfaces.AccountMigrationInterface) { accountMigrationInterface = f } var clusterInterface func(*Server) einterfaces.ClusterInterface func RegisterClusterInterface(f func(*Server) einterfaces.ClusterInterface) { clusterInterface = f } var complianceInterface func(*App) einterfaces.ComplianceInterface func RegisterComplianceInterface(f func(*App) einterfaces.ComplianceInterface) { complianceInterface = f } var dataRetentionInterface func(*App) einterfaces.DataRetentionInterface func RegisterDataRetentionInterface(f func(*App) einterfaces.DataRetentionInterface) { dataRetentionInterface = f } var elasticsearchInterface func(*App) einterfaces.ElasticsearchInterface func RegisterElasticsearchInterface(f func(*App) einterfaces.ElasticsearchInterface) { elasticsearchInterface = f } var jobsDataRetentionJobInterface func(*App) ejobs.DataRetentionJobInterface func RegisterJobsDataRetentionJobInterface(f func(*App) ejobs.DataRetentionJobInterface) { jobsDataRetentionJobInterface = f } var jobsMessageExportJobInterface func(*App) ejobs.MessageExportJobInterface func RegisterJobsMessageExportJobInterface(f func(*App) ejobs.MessageExportJobInterface) { jobsMessageExportJobInterface = f } var jobsElasticsearchAggregatorInterface func(*App) ejobs.ElasticsearchAggregatorInterface func RegisterJobsElasticsearchAggregatorInterface(f func(*App) ejobs.ElasticsearchAggregatorInterface) { jobsElasticsearchAggregatorInterface = f } var jobsElasticsearchIndexerInterface func(*App) ejobs.ElasticsearchIndexerInterface func RegisterJobsElasticsearchIndexerInterface(f func(*App) ejobs.ElasticsearchIndexerInterface) { jobsElasticsearchIndexerInterface = f } var jobsLdapSyncInterface func(*App) ejobs.LdapSyncInterface func RegisterJobsLdapSyncInterface(f func(*App) ejobs.LdapSyncInterface) { jobsLdapSyncInterface = f } var jobsMigrationsInterface func(*App) tjobs.MigrationsJobInterface func RegisterJobsMigrationsJobInterface(f func(*App) tjobs.MigrationsJobInterface) { jobsMigrationsInterface = f } var jobsPluginsInterface func(*App) tjobs.PluginsJobInterface func RegisterJobsPluginsJobInterface(f func(*App) tjobs.PluginsJobInterface) { jobsPluginsInterface = f } var ldapInterface func(*App) einterfaces.LdapInterface func RegisterLdapInterface(f func(*App) einterfaces.LdapInterface) { ldapInterface = f } var messageExportInterface func(*App) einterfaces.MessageExportInterface func RegisterMessageExportInterface(f func(*App) einterfaces.MessageExportInterface) { messageExportInterface = f } var metricsInterface func(*App) einterfaces.MetricsInterface func RegisterMetricsInterface(f func(*App) einterfaces.MetricsInterface) { metricsInterface = f } var samlInterface func(*App) einterfaces.SamlInterface func RegisterSamlInterface(f func(*App) einterfaces.SamlInterface) { samlInterface = f } func (s *Server) initEnterprise() { if accountMigrationInterface != nil
if complianceInterface != nil { s.Compliance = complianceInterface(s.FakeApp()) } if elasticsearchInterface != nil { s.Elasticsearch = elasticsearchInterface(s.FakeApp()) } if ldapInterface != nil { s.Ldap = ldapInterface(s.FakeApp()) } if messageExportInterface != nil { s.MessageExport = messageExportInterface(s.FakeApp()) } if metricsInterface != nil { s.Metrics = metricsInterface(s.FakeApp()) } if samlInterface != nil { s.Saml = samlInterface(s.FakeApp()) s.AddConfigListener(func(_, cfg *model.Config) { if err := s.Saml.ConfigureSP(); err != nil { mlog.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err)) } }) } if dataRetentionInterface != nil { s.DataRetention = dataRetentionInterface(s.FakeApp()) } if clusterInterface != nil { s.Cluster = clusterInterface(s) } }
{ s.AccountMigration = accountMigrationInterface(s.FakeApp()) }
dm_flags.go
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package gen_tasks_logic import ( "fmt" "log" "sort" "strconv" "strings" "github.com/golang/glog" "go.skia.org/infra/task_scheduler/go/specs" ) // keyParams generates the key used by DM for Gold results. func
(parts map[string]string) []string { // Don't bother to include role, which is always Test. ignored := []string{"role", "test_filter"} keys := make([]string, 0, len(parts)) for key := range parts { found := false for _, b := range ignored { if key == b { found = true break } } if !found { keys = append(keys, key) } } sort.Strings(keys) rv := make([]string, 0, 2*len(keys)) for _, key := range keys { rv = append(rv, key, parts[key]) } return rv } // dmFlags generates flags to DM based on the given task properties. func (b *taskBuilder) dmFlags(internalHardwareLabel string) { properties := map[string]string{ "gitHash": specs.PLACEHOLDER_REVISION, "builder": b.Name, "buildbucket_build_id": specs.PLACEHOLDER_BUILDBUCKET_BUILD_ID, "task_id": specs.PLACEHOLDER_TASK_ID, "issue": specs.PLACEHOLDER_ISSUE, "patchset": specs.PLACEHOLDER_PATCHSET, "patch_storage": specs.PLACEHOLDER_PATCH_STORAGE, "swarming_bot_id": "${SWARMING_BOT_ID}", "swarming_task_id": "${SWARMING_TASK_ID}", } args := []string{ "dm", "--nameByHash", } configs := []string{} skipped := []string{} hasConfig := func(cfg string) bool { for _, c := range configs { if c == cfg { return true } } return false } filter := func(slice []string, elems ...string) []string { m := make(map[string]bool, len(elems)) for _, e := range elems { m[e] = true } rv := make([]string, 0, len(slice)) for _, e := range slice { if m[e] { rv = append(rv, e) } } return rv } remove := func(slice []string, elem string) []string { rv := make([]string, 0, len(slice)) for _, e := range slice { if e != elem { rv = append(rv, e) } } return rv } removeContains := func(slice []string, elem string) []string { rv := make([]string, 0, len(slice)) for _, e := range slice { if !strings.Contains(e, elem) { rv = append(rv, e) } } return rv } suffix := func(slice []string, sfx string) []string { rv := make([]string, 0, len(slice)) for _, e := range slice { rv = append(rv, e+sfx) } return rv } skip := func(quad ...string) { if len(quad) == 1 { quad = strings.Fields(quad[0]) } if len(quad) != 4 { log.Fatalf("Invalid value for --skip: %+v", quad) } config := quad[0] src := quad[1] options := quad[2] name := quad[3] if config == "_" || hasConfig(config) || (config[0] == '~' && hasConfig(config[1:])) { skipped = append(skipped, config, src, options, name) } } // Keys. keys := keyParams(b.parts) if b.extraConfig("Lottie") { keys = append(keys, "renderer", "skottie") } if b.matchExtraConfig("DDL") { // 'DDL' style means "--skpViewportSize 2048" keys = append(keys, "style", "DDL") } else { keys = append(keys, "style", "default") } args = append(args, "--key") args = append(args, keys...) // This enables non-deterministic random seeding of the GPU FP optimization // test. // Not Android due to: // - https://skia.googlesource.com/skia/+/5910ed347a638ded8cd4c06dbfda086695df1112/BUILD.gn#160 // - https://skia.googlesource.com/skia/+/ce06e261e68848ae21cac1052abc16bc07b961bf/tests/ProcessorTest.cpp#307 // Not MSAN due to: // - https://skia.googlesource.com/skia/+/0ac06e47269a40c177747310a613d213c95d1d6d/infra/bots/recipe_modules/flavor/gn_flavor.py#80 if !b.os("Android") && !b.extraConfig("MSAN") { args = append(args, "--randomProcessorTest") } threadLimit := -1 const MAIN_THREAD_ONLY = 0 // 32-bit desktop bots tend to run out of memory, because they have relatively // far more cores than RAM (e.g. 32 cores, 3G RAM). Hold them back a bit. if b.arch("x86") { threadLimit = 4 } // These bots run out of memory easily. if b.model("MotoG4", "Nexus7") { threadLimit = MAIN_THREAD_ONLY } // Avoid issues with dynamically exceeding resource cache limits. if b.matchExtraConfig("DISCARDABLE") { threadLimit = MAIN_THREAD_ONLY } if threadLimit >= 0 { args = append(args, "--threads", strconv.Itoa(threadLimit)) } sampleCount := 0 glPrefix := "" if b.extraConfig("SwiftShader") { configs = append(configs, "gles", "glesdft", "glesdmsaa") } else if b.cpu() { args = append(args, "--nogpu") configs = append(configs, "8888") if b.extraConfig("SkVM") { args = append(args, "--skvm") } if b.extraConfig("BonusConfigs") { configs = []string{ "g8", "565", "pic-8888", "serialize-8888", "linear-f16", "srgb-rgba", "srgb-f16", "narrow-rgba", "narrow-f16", "p3-rgba", "p3-f16", "rec2020-rgba", "rec2020-f16"} } if b.extraConfig("PDF") { configs = []string{"pdf"} args = append(args, "--rasterize_pdf") // Works only on Mac. // Take ~forever to rasterize: skip("pdf gm _ lattice2") skip("pdf gm _ hairmodes") skip("pdf gm _ longpathdash") } } else if b.gpu() { args = append(args, "--nocpu") // Add in either gles or gl configs to the canonical set based on OS glPrefix = "gl" // Use 4x MSAA for all our testing. It's more consistent and 8x MSAA is nondeterministic (by // design) on NVIDIA hardware. The problem is especially bad on ANGLE. skia:6813 skia:6545 sampleCount = 4 if b.os("Android", "iOS") { glPrefix = "gles" // MSAA is disabled on Pixel3a (https://b.corp.google.com/issues/143074513). // MSAA is disabled on Pixel5 (https://skbug.com/11152). if b.model("Pixel3a", "Pixel5") { sampleCount = 0 } } else if b.matchGpu("Intel") { // MSAA doesn't work well on Intel GPUs chromium:527565, chromium:983926 sampleCount = 0 } else if b.os("ChromeOS") { glPrefix = "gles" } if b.extraConfig("NativeFonts") { configs = append(configs, glPrefix) } else { configs = append(configs, glPrefix, glPrefix+"dft", "srgb-"+glPrefix) if sampleCount > 0 { configs = append(configs, fmt.Sprintf("%smsaa%d", glPrefix, sampleCount)) // Temporarily limit the bots we test dynamic MSAA on. if b.gpu("QuadroP400", "MaliG77") || b.matchOs("Mac") { configs = append(configs, fmt.Sprintf("%sdmsaa", glPrefix)) } } } // The Tegra3 doesn't support MSAA if b.gpu("Tegra3") || // We aren't interested in fixing msaa bugs on current iOS devices. b.model("iPad4", "iPadPro", "iPhone6", "iPhone7") || // skia:5792 b.gpu("IntelHD530", "IntelIris540") { configs = removeContains(configs, "msaa") } // We want to test both the OpenGL config and the GLES config on Linux Intel: // GL is used by Chrome, GLES is used by ChromeOS. // Also do the Ganesh threading verification test (render with and without // worker threads, using only the SW path renderer, and compare the results). if b.matchGpu("Intel") && b.isLinux() { configs = append(configs, "gles", "glesdft", "srgb-gles", "gltestthreading") // skbug.com/6333, skbug.com/6419, skbug.com/6702 skip("gltestthreading gm _ lcdblendmodes") skip("gltestthreading gm _ lcdoverlap") skip("gltestthreading gm _ textbloblooper") // All of these GMs are flaky, too: skip("gltestthreading gm _ savelayer_with_backdrop") skip("gltestthreading gm _ persp_shaders_bw") skip("gltestthreading gm _ dftext_blob_persp") skip("gltestthreading gm _ dftext") skip("gltestthreading gm _ gpu_blur_utils") skip("gltestthreading gm _ gpu_blur_utils_ref") skip("gltestthreading gm _ gpu_blur_utils_subset_rect") skip("gltestthreading gm _ gpu_blur_utils_subset_rect_ref") // skbug.com/7523 - Flaky on various GPUs skip("gltestthreading gm _ orientation") // These GMs only differ in the low bits skip("gltestthreading gm _ stroketext") skip("gltestthreading gm _ draw_image_set") } // CommandBuffer bot *only* runs the cmdbuffer_es2 configs. if b.extraConfig("CommandBuffer") { configs = []string{"cmdbuffer_es2"} if sampleCount > 0 { configs = append(configs, "cmdbuffer_es2_dmsaa") } } // Dawn bot *only* runs the dawn config if b.extraConfig("Dawn") { // tint:1045: Tint doesn't implement MatrixInverse yet. skip("_", "gm", "_", "runtime_intrinsics_matrix") configs = []string{"dawn"} } // Graphite bot *only* runs the grmtl config if b.extraConfig("Graphite") { args = append(args, "--nogpu") // disable non-Graphite tests // TODO: re-enable - currently fails with "Failed to make lazy image" skip("_", "gm", "_", "image_subset") if b.extraConfig("ASAN") { // skbug.com/12507 (Neon UB during JPEG compression on M1 ASAN Graphite bot) skip("_", "gm", "_", "yuv420_odd_dim") // Oddly enough yuv420_odd_dim_repeat doesn't crash skip("_", "gm", "_", "encode-alpha-jpeg") skip("_", "gm", "_", "encode") skip("_", "gm", "_", "jpg-color-cube") } configs = []string{"grmtl"} } // ANGLE bot *only* runs the angle configs if b.extraConfig("ANGLE") { configs = []string{"angle_d3d11_es2", "angle_gl_es2", "angle_d3d11_es3"} if sampleCount > 0 { configs = append(configs, fmt.Sprintf("angle_d3d11_es2_msaa%d", sampleCount)) configs = append(configs, fmt.Sprintf("angle_d3d11_es2_dmsaa")) configs = append(configs, fmt.Sprintf("angle_gl_es2_dmsaa")) configs = append(configs, fmt.Sprintf("angle_d3d11_es3_msaa%d", sampleCount)) configs = append(configs, fmt.Sprintf("angle_d3d11_es3_dmsaa")) configs = append(configs, fmt.Sprintf("angle_gl_es3_dmsaa")) } if b.matchGpu("GTX", "Quadro") { // See skia:7823 and chromium:693090. configs = append(configs, "angle_gl_es3") if sampleCount > 0 { configs = append(configs, fmt.Sprintf("angle_gl_es2_msaa%d", sampleCount)) configs = append(configs, fmt.Sprintf("angle_gl_es2_dmsaa")) configs = append(configs, fmt.Sprintf("angle_gl_es3_msaa%d", sampleCount)) configs = append(configs, fmt.Sprintf("angle_gl_es3_dmsaa")) } } if !b.matchGpu("GTX", "Quadro", "GT610") { // See skia:10149 configs = append(configs, "angle_d3d9_es2") } if b.model("NUC5i7RYH") { // skbug.com/7376 skip("_ test _ ProcessorCloneTest") } } if b.model("AndroidOne", "Nexus5", "Nexus7") { // skbug.com/9019 skip("_ test _ ProcessorCloneTest") skip("_ test _ Programs") skip("_ test _ ProcessorOptimizationValidationTest") } if b.model("GalaxyS20") { // skbug.com/10595 skip("_ test _ ProcessorCloneTest") } if b.extraConfig("CommandBuffer") && b.model("MacBook10.1") { // skbug.com/9235 skip("_ test _ Programs") } if b.model("Spin513") { // skbug.com/11876 skip("_ test _ Programs") // skbug.com/12486 skip("_ test _ TestMockContext") skip("_ test _ TestGpuRenderingContexts") skip("_ test _ TestGpuAllContexts") skip("_ test _ OverdrawSurface_Gpu") skip("_ test _ ReplaceSurfaceBackendTexture") skip("_ test _ SurfaceAttachStencil_Gpu") skip("_ test _ SurfaceWrappedWithRelease_Gpu") } if b.extraConfig("CommandBuffer") { // skbug.com/10412 skip("_ test _ GLBackendAllocationTest") skip("_ test _ InitialTextureClear") // skbug.com/12437 skip("_ test _ GrDDLImage_MakeSubset") skip("_ test _ GrContext_oomed") } // skbug.com/9043 - these devices render this test incorrectly // when opList splitting reduction is enabled if b.gpu() && b.extraConfig("Vulkan") && (b.gpu("RadeonR9M470X", "RadeonHD7770")) { skip("_", "tests", "_", "VkDrawableImportTest") } if b.extraConfig("Vulkan") { configs = []string{"vk"} // MSAA doesn't work well on Intel GPUs chromium:527565, chromium:983926, skia:9023 if !b.matchGpu("Intel") { configs = append(configs, "vkmsaa4") } // Temporarily limit the bots we test dynamic MSAA on. if b.gpu("QuadroP400", "MaliG77") && !b.extraConfig("TSAN") { configs = append(configs, "vkdmsaa") } } if b.extraConfig("Metal") { configs = []string{"mtl"} // MSAA doesn't work well on Intel GPUs chromium:527565, chromium:983926 if !b.matchGpu("Intel") { configs = append(configs, "mtlmsaa4") } } if b.extraConfig("Direct3D") { configs = []string{"d3d"} } // Test 1010102 on our Linux/NVIDIA bots and the persistent cache config // on the GL bots. if b.gpu("QuadroP400") && !b.extraConfig("PreAbandonGpuContext") && !b.extraConfig("TSAN") && b.isLinux() { if b.extraConfig("Vulkan") { configs = append(configs, "vk1010102") // Decoding transparent images to 1010102 just looks bad skip("vk1010102 image _ _") } else { configs = append(configs, "gl1010102", "gltestpersistentcache", "gltestglslcache", "gltestprecompile") // Decoding transparent images to 1010102 just looks bad skip("gl1010102 image _ _") // These tests produce slightly different pixels run to run on NV. skip("gltestpersistentcache gm _ atlastext") skip("gltestpersistentcache gm _ dftext") skip("gltestpersistentcache gm _ glyph_pos_h_b") skip("gltestpersistentcache gm _ glyph_pos_h_f") skip("gltestpersistentcache gm _ glyph_pos_n_f") skip("gltestglslcache gm _ atlastext") skip("gltestglslcache gm _ dftext") skip("gltestglslcache gm _ glyph_pos_h_b") skip("gltestglslcache gm _ glyph_pos_h_f") skip("gltestglslcache gm _ glyph_pos_n_f") skip("gltestprecompile gm _ atlastext") skip("gltestprecompile gm _ dftext") skip("gltestprecompile gm _ glyph_pos_h_b") skip("gltestprecompile gm _ glyph_pos_h_f") skip("gltestprecompile gm _ glyph_pos_n_f") // Tessellation shaders do not yet participate in the persistent cache. skip("gltestpersistentcache gm _ tessellation") skip("gltestglslcache gm _ tessellation") skip("gltestprecompile gm _ tessellation") } } // We also test the SkSL precompile config on Pixel2XL as a representative // Android device - this feature is primarily used by Flutter. if b.model("Pixel2XL") && !b.extraConfig("Vulkan") { configs = append(configs, "glestestprecompile") } // Test SkSL precompile on iPhone 8 as representative iOS device if b.model("iPhone8") && b.extraConfig("Metal") { configs = append(configs, "mtltestprecompile") // avoid tests that can generate slightly different pixels per run skip("mtltestprecompile gm _ atlastext") skip("mtltestprecompile gm _ circular_arcs_hairline") skip("mtltestprecompile gm _ dashcircle") skip("mtltestprecompile gm _ dftext") skip("mtltestprecompile gm _ fontmgr_bounds") skip("mtltestprecompile gm _ fontmgr_bounds_1_-0.25") skip("mtltestprecompile gm _ glyph_pos_h_b") skip("mtltestprecompile gm _ glyph_pos_h_f") skip("mtltestprecompile gm _ glyph_pos_n_f") skip("mtltestprecompile gm _ persp_images") skip("mtltestprecompile gm _ ovals") skip("mtltestprecompile gm _ roundrects") skip("mtltestprecompile gm _ shadow_utils_occl") skip("mtltestprecompile gm _ strokedlines") skip("mtltestprecompile gm _ strokerect") skip("mtltestprecompile gm _ strokes3") skip("mtltestprecompile gm _ texel_subset_linear_mipmap_nearest_down") skip("mtltestprecompile gm _ texel_subset_linear_mipmap_linear_down") skip("mtltestprecompile gm _ textblobmixedsizes_df") skip("mtltestprecompile gm _ yuv420_odd_dim_repeat") skip("mtltestprecompile svg _ A_large_blank_world_map_with_oceans_marked_in_blue.svg") skip("mtltestprecompile svg _ Chalkboard.svg") skip("mtltestprecompile svg _ Ghostscript_Tiger.svg") skip("mtltestprecompile svg _ Seal_of_American_Samoa.svg") skip("mtltestprecompile svg _ Seal_of_Illinois.svg") skip("mtltestprecompile svg _ desk_motionmark_paths.svg") skip("mtltestprecompile svg _ rg1024_green_grapes.svg") skip("mtltestprecompile svg _ shapes-intro-02-f.svg") skip("mtltestprecompile svg _ tiger-8.svg") } // Test reduced shader mode on iPhone 11 as representative iOS device if b.model("iPhone11") && b.extraConfig("Metal") { configs = append(configs, "mtlreducedshaders") } if b.gpu("AppleM1") && !b.extraConfig("Metal") { skip("_ test _ TransferPixelsFromTextureTest") // skia:11814 } if b.model(DONT_REDUCE_OPS_TASK_SPLITTING_MODELS...) { args = append(args, "--dontReduceOpsTaskSplitting", "true") } // Test reduceOpsTaskSplitting fallback when over budget. if b.model("NUC7i5BNK") && b.extraConfig("ASAN") { args = append(args, "--gpuResourceCacheLimit", "16777216") } // Test rendering to wrapped dsts on a few bots // Also test "narrow-glf16", which hits F16 surfaces and F16 vertex colors. if b.extraConfig("BonusConfigs") { configs = []string{"glbetex", "glbert", "narrow-glf16", "glreducedshaders"} } if b.os("ChromeOS") { // Just run GLES for now - maybe add gles_msaa4 in the future configs = []string{"gles"} } // Test GPU tessellation path renderer. if b.extraConfig("GpuTess") { configs = []string{glPrefix + "msaa4"} // Use hardware tessellation as much as possible for testing. Use 16 segments max to // verify the chopping logic. args = append(args, "--pr", "atlas", "tess", "--hwtess", "--alwaysHwTess", "--maxTessellationSegments", "16") } // DDL is a GPU-only feature if b.extraConfig("DDL1") { // This bot generates comparison images for the large skps and the gms configs = filter(configs, "gl", "vk", "mtl") args = append(args, "--skpViewportSize", "2048") } if b.extraConfig("DDL3") { // This bot generates the real ddl images for the large skps and the gms configs = suffix(filter(configs, "gl", "vk", "mtl"), "ddl") args = append(args, "--skpViewportSize", "2048") args = append(args, "--gpuThreads", "0") } if b.extraConfig("OOPRDDL") { // This bot generates the real oopr/DDL images for the large skps and the GMs configs = suffix(filter(configs, "gl", "vk", "mtl"), "ooprddl") args = append(args, "--skpViewportSize", "2048") args = append(args, "--gpuThreads", "0") } } // Sharding. tf := b.parts["test_filter"] if tf != "" && tf != "All" { // Expected format: shard_XX_YY split := strings.Split(tf, "_") if len(split) == 3 { args = append(args, "--shard", split[1]) args = append(args, "--shards", split[2]) } else { glog.Fatalf("Invalid task name - bad shards: %s", tf) } } args = append(args, "--config") args = append(args, configs...) removeFromArgs := func(arg string) { args = remove(args, arg) } // Run tests, gms, and image decoding tests everywhere. args = append(args, "--src", "tests", "gm", "image", "lottie", "colorImage", "svg", "skp") if b.gpu() { // Don't run the "svgparse_*" svgs on GPU. skip("_ svg _ svgparse_") } else if b.Name == "Test-Debian10-Clang-GCE-CPU-AVX2-x86_64-Debug-All-ASAN" { // Only run the CPU SVGs on 8888. skip("~8888 svg _ _") } else { // On CPU SVGs we only care about parsing. Only run them on the above bot. removeFromArgs("svg") } // Eventually I'd like these to pass, but for now just skip 'em. if b.extraConfig("SK_FORCE_RASTER_PIPELINE_BLITTER") { removeFromArgs("tests") } if b.extraConfig("NativeFonts") { // images won't exercise native font integration :) removeFromArgs("image") removeFromArgs("colorImage") } if b.matchExtraConfig("Graphite") { // The Graphite bots run the skps, gms and tests removeFromArgs("image") removeFromArgs("colorImage") removeFromArgs("svg") } else if b.matchExtraConfig("DDL", "PDF") { // The DDL and PDF bots just render the large skps and the gms removeFromArgs("tests") removeFromArgs("image") removeFromArgs("colorImage") removeFromArgs("svg") } else { // No other bots render the .skps. removeFromArgs("skp") } if b.extraConfig("Lottie") { // Only run the lotties on Lottie bots. removeFromArgs("tests") removeFromArgs("gm") removeFromArgs("image") removeFromArgs("colorImage") removeFromArgs("svg") removeFromArgs("skp") } else { removeFromArgs("lottie") } if b.extraConfig("TSAN") { // skbug.com/10848 removeFromArgs("svg") } // TODO: ??? skip("f16 _ _ dstreadshuffle") skip("srgb-gl image _ _") skip("srgb-gles image _ _") // --src image --config g8 means "decode into Gray8", which isn't supported. skip("g8 image _ _") skip("g8 colorImage _ _") if b.extraConfig("Valgrind") { // These take 18+ hours to run. skip("pdf gm _ fontmgr_iter") skip("pdf _ _ PANO_20121023_214540.jpg") skip("pdf skp _ worldjournal") skip("pdf skp _ desk_baidu.skp") skip("pdf skp _ desk_wikipedia.skp") skip("_ svg _ _") // skbug.com/9171 and 8847 skip("_ test _ InitialTextureClear") } if b.model("Pixel3") { // skbug.com/10546 skip("vkddl gm _ compressed_textures_nmof") skip("vkddl gm _ compressed_textures_npot") skip("vkddl gm _ compressed_textures") } if b.model("TecnoSpark3Pro", "Wembley") { // skbug.com/9421 skip("_ test _ InitialTextureClear") } if b.model("Wembley") { // These tests run forever on the Wembley. skip("_ gm _ async_rescale_and_read") } if b.os("iOS") { skip(glPrefix + " skp _ _") } if b.matchOs("Mac", "iOS") { // CG fails on questionable bmps skip("_ image gen_platf rgba32abf.bmp") skip("_ image gen_platf rgb24prof.bmp") skip("_ image gen_platf rgb24lprof.bmp") skip("_ image gen_platf 8bpp-pixeldata-cropped.bmp") skip("_ image gen_platf 4bpp-pixeldata-cropped.bmp") skip("_ image gen_platf 32bpp-pixeldata-cropped.bmp") skip("_ image gen_platf 24bpp-pixeldata-cropped.bmp") // CG has unpredictable behavior on this questionable gif // It's probably using uninitialized memory skip("_ image gen_platf frame_larger_than_image.gif") // CG has unpredictable behavior on incomplete pngs // skbug.com/5774 skip("_ image gen_platf inc0.png") skip("_ image gen_platf inc1.png") skip("_ image gen_platf inc2.png") skip("_ image gen_platf inc3.png") skip("_ image gen_platf inc4.png") skip("_ image gen_platf inc5.png") skip("_ image gen_platf inc6.png") skip("_ image gen_platf inc7.png") skip("_ image gen_platf inc8.png") skip("_ image gen_platf inc9.png") skip("_ image gen_platf inc10.png") skip("_ image gen_platf inc11.png") skip("_ image gen_platf inc12.png") skip("_ image gen_platf inc13.png") skip("_ image gen_platf inc14.png") skip("_ image gen_platf incInterlaced.png") // These images fail after Mac 10.13.1 upgrade. skip("_ image gen_platf incInterlaced.gif") skip("_ image gen_platf inc1.gif") skip("_ image gen_platf inc0.gif") skip("_ image gen_platf butterfly.gif") } // WIC fails on questionable bmps if b.matchOs("Win") { skip("_ image gen_platf pal8os2v2.bmp") skip("_ image gen_platf pal8os2v2-16.bmp") skip("_ image gen_platf rgba32abf.bmp") skip("_ image gen_platf rgb24prof.bmp") skip("_ image gen_platf rgb24lprof.bmp") skip("_ image gen_platf 8bpp-pixeldata-cropped.bmp") skip("_ image gen_platf 4bpp-pixeldata-cropped.bmp") skip("_ image gen_platf 32bpp-pixeldata-cropped.bmp") skip("_ image gen_platf 24bpp-pixeldata-cropped.bmp") if b.arch("x86_64") && b.cpu() { // This GM triggers a SkSmallAllocator assert. skip("_ gm _ composeshader_bitmap") } } if b.matchOs("Win", "Mac") { // WIC and CG fail on arithmetic jpegs skip("_ image gen_platf testimgari.jpg") // More questionable bmps that fail on Mac, too. skbug.com/6984 skip("_ image gen_platf rle8-height-negative.bmp") skip("_ image gen_platf rle4-height-negative.bmp") } // These PNGs have CRC errors. The platform generators seem to draw // uninitialized memory without reporting an error, so skip them to // avoid lots of images on Gold. skip("_ image gen_platf error") if b.os("Android", "iOS") { // This test crashes the N9 (perhaps because of large malloc/frees). It also // is fairly slow and not platform-specific. So we just disable it on all of // Android and iOS. skia:5438 skip("_ test _ GrStyledShape") } if internalHardwareLabel == "5" { // http://b/118312149#comment9 skip("_ test _ SRGBReadWritePixels") } // skia:4095 badSerializeGMs := []string{ "strict_constraint_batch_no_red_allowed", // https://crbug.com/skia/10278 "strict_constraint_no_red_allowed", // https://crbug.com/skia/10278 "fast_constraint_red_is_allowed", // https://crbug.com/skia/10278 "c_gms", "colortype", "colortype_xfermodes", "drawfilter", "fontmgr_bounds_0.75_0", "fontmgr_bounds_1_-0.25", "fontmgr_bounds", "fontmgr_match", "fontmgr_iter", "imagemasksubset", "wacky_yuv_formats_domain", "imagemakewithfilter", "imagemakewithfilter_crop", "imagemakewithfilter_crop_ref", "imagemakewithfilter_ref", } // skia:5589 badSerializeGMs = append(badSerializeGMs, "bitmapfilters", "bitmapshaders", "convex_poly_clip", "extractalpha", "filterbitmap_checkerboard_32_32_g8", "filterbitmap_image_mandrill_64", "shadows", "simpleaaclip_aaclip", ) // skia:5595 badSerializeGMs = append(badSerializeGMs, "composeshader_bitmap", "scaled_tilemodes_npot", "scaled_tilemodes", ) // skia:5778 badSerializeGMs = append(badSerializeGMs, "typefacerendering_pfaMac") // skia:5942 badSerializeGMs = append(badSerializeGMs, "parsedpaths") // these use a custom image generator which doesn't serialize badSerializeGMs = append(badSerializeGMs, "ImageGeneratorExternal_rect") badSerializeGMs = append(badSerializeGMs, "ImageGeneratorExternal_shader") // skia:6189 badSerializeGMs = append(badSerializeGMs, "shadow_utils") // skia:7938 badSerializeGMs = append(badSerializeGMs, "persp_images") // Not expected to round trip encoding/decoding. badSerializeGMs = append(badSerializeGMs, "all_bitmap_configs") badSerializeGMs = append(badSerializeGMs, "makecolorspace") badSerializeGMs = append(badSerializeGMs, "readpixels") badSerializeGMs = append(badSerializeGMs, "draw_image_set_rect_to_rect") badSerializeGMs = append(badSerializeGMs, "draw_image_set_alpha_only") badSerializeGMs = append(badSerializeGMs, "compositor_quads_shader") badSerializeGMs = append(badSerializeGMs, "wacky_yuv_formats_qtr") badSerializeGMs = append(badSerializeGMs, "runtime_effect_image") badSerializeGMs = append(badSerializeGMs, "ctmpatheffect") // This GM forces a path to be convex. That property doesn't survive // serialization. badSerializeGMs = append(badSerializeGMs, "analytic_antialias_convex") for _, test := range badSerializeGMs { skip("serialize-8888", "gm", "_", test) } // We skip these to avoid out-of-memory failures. if b.matchOs("Win", "Android") { for _, test := range []string{"verylargebitmap", "verylarge_picture_image"} { skip("serialize-8888", "gm", "_", test) } } if b.model("iPhone6") { skip("_", "gm", "_", "verylargebitmap") skip("_", "gm", "_", "verylarge_picture_image") skip("_", "svg", "_", "A_large_blank_world_map_with_oceans_marked_in_blue.svg") skip("_", "tests", "_", "ImageFilterBlurLargeImage_Gpu") skip("_", "gm", "_", "wacky_yuv") } if b.matchOs("Mac") && b.cpu() { // skia:6992 skip("pic-8888", "gm", "_", "encode-platform") skip("serialize-8888", "gm", "_", "encode-platform") } // skia:4769 skip("pic-8888", "gm", "_", "drawfilter") // skia:4703 for _, test := range []string{"image-cacherator-from-picture", "image-cacherator-from-raster", "image-cacherator-from-ctable"} { skip("pic-8888", "gm", "_", test) skip("serialize-8888", "gm", "_", test) } // GM that requires raster-backed canvas for _, test := range []string{"complexclip4_bw", "complexclip4_aa", "p3", "async_rescale_and_read_text_up_large", "async_rescale_and_read_text_up", "async_rescale_and_read_text_down", "async_rescale_and_read_dog_up", "async_rescale_and_read_dog_down", "async_rescale_and_read_rose", "async_rescale_and_read_no_bleed", "async_rescale_and_read_alpha_type"} { skip("pic-8888", "gm", "_", test) skip("serialize-8888", "gm", "_", test) // GM requires canvas->makeSurface() to return a valid surface. // TODO(borenet): These should be just outside of this block but are // left here to match the recipe which has an indentation bug. skip("pic-8888", "gm", "_", "blurrect_compare") skip("serialize-8888", "gm", "_", "blurrect_compare") } // Extensions for RAW images r := []string{ "arw", "cr2", "dng", "nef", "nrw", "orf", "raf", "rw2", "pef", "srw", "ARW", "CR2", "DNG", "NEF", "NRW", "ORF", "RAF", "RW2", "PEF", "SRW", } // skbug.com/4888 // Skip RAW images (and a few large PNGs) on GPU bots // until we can resolve failures. if b.gpu() { skip("_ image _ interlaced1.png") skip("_ image _ interlaced2.png") skip("_ image _ interlaced3.png") for _, rawExt := range r { skip(fmt.Sprintf("_ image _ .%s", rawExt)) } } // Skip memory intensive tests on 32-bit bots. if b.os("Win8") && b.arch("x86") { skip("_ image f16 _") skip("_ image _ abnormal.wbmp") skip("_ image _ interlaced1.png") skip("_ image _ interlaced2.png") skip("_ image _ interlaced3.png") for _, rawExt := range r { skip(fmt.Sprintf("_ image _ .%s", rawExt)) } } if b.model("Nexus5", "Nexus5x") && b.gpu() { // skia:5876 skip("_", "gm", "_", "encode-platform") } if b.model("AndroidOne") && b.gpu() { // skia:4697, skia:4704, skia:4694, skia:4705, skia:11133 skip("_", "gm", "_", "bigblurs") skip("_", "gm", "_", "strict_constraint_no_red_allowed") skip("_", "gm", "_", "fast_constraint_red_is_allowed") skip("_", "gm", "_", "dropshadowimagefilter") skip("_", "gm", "_", "filterfastbounds") skip(glPrefix, "gm", "_", "imageblurtiled") skip("_", "gm", "_", "imagefiltersclipped") skip("_", "gm", "_", "imagefiltersscaled") skip("_", "gm", "_", "imageresizetiled") skip("_", "gm", "_", "matrixconvolution") skip("_", "gm", "_", "strokedlines") skip("_", "gm", "_", "runtime_intrinsics_matrix") if sampleCount > 0 { glMsaaConfig := fmt.Sprintf("%smsaa%d", glPrefix, sampleCount) skip(glMsaaConfig, "gm", "_", "imageblurtiled") skip(glMsaaConfig, "gm", "_", "imagefiltersbase") } } if b.matchGpu("Adreno[3456]") { // disable broken tests on Adreno 3/4/5/6xx skip("_", "tests", "_", "SkSLArrayCast_GPU") // skia:12332 skip("_", "tests", "_", "SkSLArrayComparison_GPU") // skia:12332 } if b.matchGpu("Adreno[345]") && !b.extraConfig("Vulkan") { // disable broken tests on Adreno 3/4/5xx GLSL skip("_", "tests", "_", "DSLFPTest_SwitchStatement") // skia:11891 skip("_", "tests", "_", "SkSLMatrixToVectorCast_GPU") // skia:12192 skip("_", "tests", "_", "SkSLStructsInFunctions_GPU") // skia:11929 } if b.matchGpu("Adreno6") && !b.extraConfig("Vulkan") { // disable broken tests on Adreno 6xx GLSL skip("_", "tests", "_", "SkSLIntrinsicIsInf_GPU") // skia:12377 } if (b.matchGpu("Adreno3") || b.matchGpu("Mali400")) && !b.extraConfig("Vulkan") { skip("_", "tests", "_", "SkSLMatrices") // skia:12456 } if b.gpu("IntelIris6100", "IntelHD4400") && b.matchOs("Win") && !b.extraConfig("Vulkan") { skip("_", "tests", "_", "SkSLVectorToMatrixCast_GPU") // skia:12179 } if b.matchGpu("Intel") && b.matchOs("Win") && !b.extraConfig("Vulkan") { skip("_", "tests", "_", "SkSLReturnsValueOnEveryPathES3_GPU") // skia:12465 } if (b.extraConfig("Vulkan") && b.isLinux() && b.matchGpu("Intel")) || (b.extraConfig("ANGLE") && b.matchOs("Win") && b.matchGpu("IntelIris(540|655)")) { skip("_", "tests", "_", "SkSLSwitchDefaultOnly_GPU") // skia:12465 } if b.gpu("Tegra3") { // Tegra3 fails to compile break stmts inside a for loop (skia:12477) skip("_", "tests", "_", "SkSLSwitch_GPU") skip("_", "tests", "_", "SkSLSwitchDefaultOnly_GPU") skip("_", "tests", "_", "SkSLSwitchWithFallthrough_GPU") skip("_", "tests", "_", "SkSLSwitchWithLoops_GPU") skip("_", "tests", "_", "SkSLLoopFloat_GPU") skip("_", "tests", "_", "SkSLLoopInt_GPU") } if !b.extraConfig("Vulkan") && (b.gpu("QuadroP400") || b.gpu("GTX660") || b.gpu("GTX960") || b.gpu("Tegra3")) { // Various Nvidia GPUs crash or generate errors when assembling weird matrices (skia:12443) skip("_", "tests", "_", "SkSLMatrixConstructorsES2_GPU") skip("_", "tests", "_", "SkSLMatrixConstructorsES3_GPU") } if !b.extraConfig("Vulkan") && (b.gpu("RadeonR9M470X") || b.gpu("RadeonHD7770")) { // Some AMD GPUs can get the wrong result when assembling non-square matrices (skia:12443) skip("_", "tests", "_", "SkSLMatrixConstructorsES3_GPU") } if b.matchGpu("Intel") { // some Intel GPUs don't return zero for the derivative of a uniform skip("_", "tests", "_", "SkSLIntrinsicDFdy_GPU") skip("_", "tests", "_", "SkSLIntrinsicDFdx_GPU") skip("_", "tests", "_", "SkSLIntrinsicFwidth_GPU") } if b.matchOs("Mac") && b.matchGpu("Intel(Iris5100|HD6000)") { skip("_", "tests", "_", "SkSLLoopFloat_GPU") // skia:12426 } match := []string{} if b.extraConfig("Valgrind") { // skia:3021 match = append(match, "~Threaded") } if b.extraConfig("Valgrind") && b.extraConfig("PreAbandonGpuContext") { // skia:6575 match = append(match, "~multipicturedraw_") } if b.model("AndroidOne") { match = append(match, "~WritePixels") // skia:4711 match = append(match, "~PremulAlphaRoundTrip_Gpu") // skia:7501 match = append(match, "~ReimportImageTextureWithMipLevels") // skia:8090 match = append(match, "~MorphologyFilterRadiusWithMirrorCTM_Gpu") // skia:10383 } if b.extraConfig("MSAN") { match = append(match, "~Once", "~Shared") // Not sure what's up with these tests. } // By default, we test with GPU threading enabled, unless specifically // disabled. if b.extraConfig("NoGPUThreads") { args = append(args, "--gpuThreads", "0") } if b.extraConfig("Vulkan") && b.gpu("Adreno530") { // skia:5777 match = append(match, "~CopySurface") } if b.extraConfig("Vulkan") && b.matchGpu("Adreno") { // skia:7663 match = append(match, "~WritePixelsNonTextureMSAA_Gpu") match = append(match, "~WritePixelsMSAA_Gpu") } if b.extraConfig("Vulkan") && b.isLinux() && b.gpu("IntelIris640") { match = append(match, "~VkHeapTests") // skia:6245 } if b.isLinux() && b.gpu("IntelIris640") { match = append(match, "~Programs") // skia:7849 } if b.model("TecnoSpark3Pro", "Wembley") { // skia:9814 match = append(match, "~Programs") match = append(match, "~ProcessorCloneTest") match = append(match, "~ProcessorOptimizationValidationTest") } if b.gpu("IntelIris640", "IntelHD615", "IntelHDGraphics615") { match = append(match, "~^SRGBReadWritePixels$") // skia:9225 } if b.extraConfig("Vulkan") && b.isLinux() && b.gpu("IntelHD405") { // skia:7322 skip("vk", "gm", "_", "skbug_257") skip("vk", "gm", "_", "filltypespersp") match = append(match, "~^ClearOp$") match = append(match, "~^CopySurface$") match = append(match, "~^ImageNewShader_GPU$") match = append(match, "~^InitialTextureClear$") match = append(match, "~^PinnedImageTest$") match = append(match, "~^ReadPixels_Gpu$") match = append(match, "~^ReadPixels_Texture$") match = append(match, "~^SRGBReadWritePixels$") match = append(match, "~^VkUploadPixelsTests$") match = append(match, "~^WritePixelsNonTexture_Gpu$") match = append(match, "~^WritePixelsNonTextureMSAA_Gpu$") match = append(match, "~^WritePixels_Gpu$") match = append(match, "~^WritePixelsMSAA_Gpu$") } if b.extraConfig("Vulkan") && b.gpu("GTX660") && b.matchOs("Win") { // skbug.com/8047 match = append(match, "~FloatingPointTextureTest$") } if b.extraConfig("Metal") && b.gpu("RadeonHD8870M") && b.matchOs("Mac") { // skia:9255 match = append(match, "~WritePixelsNonTextureMSAA_Gpu") // skbug.com/11366 match = append(match, "~SurfacePartialDraw_Gpu") } if b.extraConfig("Metal") && b.gpu("PowerVRGX6450") && b.matchOs("iOS") { // skbug.com/11885 match = append(match, "~flight_animated_image") } if b.extraConfig("ANGLE") { // skia:7835 match = append(match, "~BlurMaskBiggerThanDest") } if b.gpu("IntelIris6100") && b.extraConfig("ANGLE") && !b.debug() { // skia:7376 match = append(match, "~^ProcessorOptimizationValidationTest$") } if b.gpu("IntelIris6100", "IntelHD4400") && b.extraConfig("ANGLE") { // skia:6857 skip("angle_d3d9_es2", "gm", "_", "lighting") } if b.gpu("PowerVRGX6250") { match = append(match, "~gradients_view_perspective_nodither") //skia:6972 } if b.arch("arm") && b.extraConfig("ASAN") { // TODO: can we run with env allocator_may_return_null=1 instead? match = append(match, "~BadImage") } if b.matchOs("Mac") && b.gpu("IntelHD6000") { // skia:7574 match = append(match, "~^ProcessorCloneTest$") match = append(match, "~^GrMeshTest$") } if b.matchOs("Mac") && b.gpu("IntelHD615") { // skia:7603 match = append(match, "~^GrMeshTest$") } if b.extraConfig("Vulkan") && b.model("GalaxyS20") { // skia:10247 match = append(match, "~VkPrepareForExternalIOQueueTransitionTest") } if len(skipped) > 0 { args = append(args, "--skip") args = append(args, skipped...) } if len(match) > 0 { args = append(args, "--match") args = append(args, match...) } // These bots run out of memory running RAW codec tests. Do not run them in // parallel // TODO(borenet): Previously this was `'Nexus5' in bot or 'Nexus9' in bot` // which also matched 'Nexus5x'. I added That here to maintain the // existing behavior, but we should verify that it's needed. if b.model("Nexus5", "Nexus5x", "Nexus9") { args = append(args, "--noRAW_threading") } if b.extraConfig("FSAA") { args = append(args, "--analyticAA", "false") } if b.extraConfig("FAAA") { args = append(args, "--forceAnalyticAA") } if !b.extraConfig("NativeFonts") { args = append(args, "--nonativeFonts") } if b.extraConfig("GDI") { args = append(args, "--gdi") } // Let's make all bots produce verbose output by default. args = append(args, "--verbose") // See skia:2789. if b.extraConfig("AbandonGpuContext") { args = append(args, "--abandonGpuContext") } if b.extraConfig("PreAbandonGpuContext") { args = append(args, "--preAbandonGpuContext") } if b.extraConfig("ReleaseAndAbandonGpuContext") { args = append(args, "--releaseAndAbandonGpuContext") } // Finalize the DM flags and properties. b.recipeProp("dm_flags", marshalJson(args)) b.recipeProp("dm_properties", marshalJson(properties)) // Add properties indicating which assets the task should use. if b.matchExtraConfig("Lottie") { b.asset("lottie-samples") b.recipeProp("lotties", "true") } else { b.asset("skimage") b.recipeProp("images", "true") b.asset("skp") b.recipeProp("skps", "true") b.asset("svg") b.recipeProp("svgs", "true") } b.recipeProp("do_upload", fmt.Sprintf("%t", b.doUpload())) b.recipeProp("resources", "true") }
keyParams
signage_point.py
from typing import Optional from cactus.types.blockchain_format.vdf import VDFInfo, VDFProof from cactus.util.streamable import Streamable, streamable @dataclass(frozen=True) @streamable class SignagePoint(Streamable): cc_vdf: Optional[VDFInfo] cc_proof: Optional[VDFProof] rc_vdf: Optional[VDFInfo] rc_proof: Optional[VDFProof]
from dataclasses import dataclass
excelquery_test.go
// // excelquery - a package for quering Caltech library API (and others) and integrating results into an Excel Workbook. // // @author R. S. Doiel, <[email protected]> // // Copyright (c) 2016, Caltech // All rights not granted herein are expressly reserved by Caltech. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // package excelquery import ( "net/url" "path" "testing" // Caltech packages "github.com/caltechlibrary/excelquery" "github.com/caltechlibrary/rss2" // 3rd Party packages "github.com/tealeg/xlsx" ) func TestColumnNameToIndex(t *testing.T) { testVals := map[string]int{ "A": 0, "R": 17, "Z": 25, "AA": 26, "AB": 27, "AM": 38, "AS": 44, "AX": 49, "AZ": 51, "BA": 52, "BE": 56, "BY": 76,
"CL": 89, "DO": 118, "EG": 136, "EZ": 155, "FX": 179, "GZ": 207, "IE": 238, "IT": 253, "LS": 330, "MA": 338, "MT": 357, "OK": 400, "PQ": 432, "RD": 471, "TJ": 529, "ZZ": 701, "AAA": 702, "AAB": 703, "AAZ": 727, "ABA": 728, "ADQ": 796, "ARC": 1146, "ARG": 1150, "ARM": 1156, "ASK": 1180, "ASM": 1182, "ATM": 1208, "AUX": 1245, "AVE": 1252, "AVI": 1256, "AWE": 1278, "AWK": 1284, "AZZ": 1377, "BAA": 1378, "BAD": 1381, "BAM": 1390, "BAT": 1397, "BBC": 1406, "BED": 1485, } for s, i := range testVals { r, err := excelquery.ColumnNameToIndex(s) if err != nil { t.Errorf("Couldn't convert %s to int, %s", s, err) } if r != i { t.Errorf("ColumnNameToIndex(%q) != %d, returned %d", s, i, r) } } } func TestSheetHandling(t *testing.T) { xldoc := xlsx.NewFile() sheet, err := xldoc.AddSheet("Sheet1") if err != nil { t.Errorf("Can't add sheet: %s", err) t.FailNow() } row := sheet.AddRow() A := row.AddCell() A.Value = "Query" B := row.AddCell() B.Value = "Result" queryTerms := map[string]string{ "flood characteristics of alluvial": "Flood Characteristics of Alluvial Streams Important to Pipeline Crossings.", "gravitational waves in a": "Gravitational Waves in a Shallow Compressible Liquid", "experimental design of low": "", } for query, val := range queryTerms { row = sheet.AddRow() A = row.AddCell() A.Value = query B = row.AddCell() B.Value = val } // Make our test directory if needed fname := path.Join("testdata", "test-0.xlsx") err = xldoc.Save(fname) if err != nil { t.Errorf("Can't save %s, %s", fname, err) } xldocTest, err := xlsx.OpenFile(fname) if err != nil { t.Errorf("Can't open %s, %s", fname, err) t.FailNow() } for _, sheet := range xldocTest.Sheets { for j, _ := range sheet.Rows { q := sheet.Cell(j, 0) r := sheet.Cell(j, 2) qTest := excelquery.GetCell(sheet, j, 0) if q.Value != qTest { t.Errorf("GetCell(sheet, %d, 0) expected %q, got %q", j, q.Value, qTest) } if r.Value != "" { err := excelquery.UpdateCell(sheet, j, 2, "This is a test", false) if err != nil { t.Errorf("Expected an err on update to cell %d:2", j) } } err := excelquery.UpdateCell(sheet, j, 2, "This is a test 2", true) if err != nil { t.Errorf("Expected err to be nil on update to cell %d:2, %q", j, err) } r2 := sheet.Cell(j, 2) if r2.Value != "This is a test 2" { t.Errorf("Expected %q, got %q", "This is a test 2", r2.Value) } } } } func TestQuerySupport(t *testing.T) { eprintsAPI, err := url.Parse("http://authors.library.caltech.edu/cgi/search/advanced/") if err != nil { t.Error(err) t.FailNow() } eprintsAPI = excelquery.UpdateParameters(eprintsAPI, map[string]string{ "title": "Molecules in solution", "output": "RSS2", }) if eprintsAPI == nil { t.Errorf("Something went wrong updating eprintsAPI query") t.FailNow() } buf, err := excelquery.Request(eprintsAPI, map[string]string{}) if err != nil { t.Errorf("Failed to run %s, %s", eprintsAPI.String(), err) t.FailNow() } r, err := rss2.Parse(buf) if err != nil { t.Errorf("Failed to parse response, buf[0:24] %q, err %q", buf[0:24], err) t.FailNow() } _, err = r.Filter([]string{".item[].title"}) if err != nil { t.Errorf("Failed to filter for titles, %s", err) t.FailNow() } }
"CA": 78,
modff.rs
#[inline] #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub extern "C" fn modff(x: f32) -> (f32, f32)
{ let rv2: f32; let mut u: u32 = x.to_bits(); let mask: u32; let e = ((u >> 23 & 0xff) as i32) - 0x7f; /* no fractional part */ if e >= 23 { rv2 = x; if e == 0x80 && (u << 9) != 0 { /* nan */ return (x, rv2); } u &= 0x80000000; return (f32::from_bits(u), rv2); } /* no integral part */ if e < 0 { u &= 0x80000000; rv2 = f32::from_bits(u); return (x, rv2); } mask = 0x007fffff >> e; if (u & mask) == 0 { rv2 = x; u &= 0x80000000; return (f32::from_bits(u), rv2); } u &= !mask; rv2 = f32::from_bits(u); return (x - rv2, rv2); }
model-editor.module.ts
/*! * @license * Copyright 2019 Alfresco, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { ModuleWithProviders, NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ModelEditorType, MODEL_EDITORS_TOKEN } from './components/model-editor/model-editors.token'; import { ModelEditorComponent } from './components/model-editor/model-editor.component'; import { DynamicComponentDirective } from './components/model-editor/dynamic-component.directive'; import { ModelLoaderGuard } from './router/guards/model-loader.guard'; import { ModelEditorProxyComponent } from './components/model-editor-proxy/model-editor-proxy.component'; import { UnsavedPageGuard } from './router/guards/unsaved-page.guard'; import { ModelHeaderComponent } from './components/model-header/model-header.component'; import { SharedModule } from '../helpers/shared.module'; import { MaterialModule, ToolbarModule } from '@alfresco/adf-core'; import { TranslateModule } from '@ngx-translate/core'; import { ModelHeaderBreadcrumbProxyComponent } from './components/model-header-breadcrumb/model-header-breadcrumb-proxy.component'; @NgModule({ imports: [ CommonModule, SharedModule, MaterialModule, ToolbarModule, TranslateModule.forRoot() ], declarations: [ DynamicComponentDirective, ModelEditorComponent, ModelEditorProxyComponent, ModelHeaderComponent, ModelHeaderBreadcrumbProxyComponent ], exports: [ CommonModule, ModelEditorComponent, ModelEditorProxyComponent, ModelHeaderComponent, ModelHeaderBreadcrumbProxyComponent ], providers: [ UnsavedPageGuard, ModelLoaderGuard ] }) export class
{ public static forChild(modelEditorType: ModelEditorType): ModuleWithProviders<ModelEditorModule> { return { ngModule: ModelEditorModule, providers: [ { provide: MODEL_EDITORS_TOKEN, useValue: modelEditorType, multi: true } ] }; } }
ModelEditorModule
shiori.go
package main /* #define UNICODE #include <windows.h> #include <stdlib.h> #include <string.h> */ import "C" import ( "bytes" "fmt" "github.com/Narazaka/shiorigo" "github.com/kurousada/gohst/internal/readerstream" "github.com/kurousada/gohst/internal/requesthandlers" "github.com/kurousada/gohst/internal/win32file" "log" "os" "unsafe" ) // 空だけどコンパイルするのに必要です。 func main() {} var ( logFile *win32file
e ) /* main パッケージは以下の関数をエクスポートしています。 * * extern "C" __declspec(dllexport) BOOL __cdecl load(HGLOBAL h, long len); * extern "C" __declspec(dllexport) BOOL __cdecl unload(void); * extern "C" __declspec(dllexport) HGLOBAL __cdecl request(HGLOBAL h, long *len); * * それぞれの関数では、ログファイルの扱いと internal/requesthandlers パッケージで定義されているリクエストハンドラの呼び出しを行っています。 * */ /* extern "C" __declspec(dllexport) BOOL __cdecl load(HGLOBAL h, long len); * * h = DLL のパス(文字列) * length = h のサイズ * * h は GlobalAlloc(GPTR, length) で確保されたメモリ領域へのポインタで、DLL 側で GlobalFree(h) する必要があります。 * * あと、「//export 〜」は「// export 〜」だとダメです。空行もダメ。 */ //export load func load(h C.HGLOBAL, length C.long) C.BOOL { var err error // せっかくサイズ情報があるので C.GoStringN() を使います。 // ここは C.GoString() でも大丈夫なはず。 // あ、HGLOBAL は void* なので、char* に相当する *C.char にキャストしています。 curDir := C.GoStringN((*C.char)(h), (C.int)(length)) // DLL のパスが入っているメモリを開放します。 C.GlobalFree(h) // Logger の設定をします。 // // log パッケージを使って、"shiori.log" というファイルに書き込みます。 // ログファイルの場所は DLL と同じ位置(ベースウェアのゴーストフォルダ内「/gohst/ghost/master/shiori.log」)です。 // ファイルをオープンできなければ標準出力にエラーメッセージを出します。 // // ただ、出力先のファイルの読み書きに os パッケージで開いたファイルを使うと「書き込み権限がない」というエラーが出ます。 // これはおそらく FAT32 にパーミッションという概念がないことと、私が Wine を使っているせいです。 // そのため、Win32 API を cgo で直接叩いています(その部分は internal/win32file パッケージにまとめてあります)。 // // それから、Write() するときに Shift_JIS に変換するようにフックを書いています。 // このフックを登録できる機能は win32file パッケージ独自のもので、os パッケージにはありません(たぶん)。 // log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile) log.SetOutput(os.Stdout) path := "shiori.log" logFile, err = win32file.OpenFile(path, win32file.O_WRONLY) if err != nil { fmt.Println(err.Error()) } else if err == nil && logFile != nil { logFile.OnWrite(func(p []byte) ([]byte, error) { // Write()時にShift_JISに変換する return readerstream.New(bytes.NewReader(p)).ToShiftJIS().ToBytes() }) log.SetOutput(logFile) } log.Printf("[info] load(\"%s\", %d)\n", curDir, (int)(length)) // リクエストハンドラを呼びます。 err = requesthandlers.OnLoad(curDir) if err != nil { log.Printf("[info] OnLoad() failed\n%s\n", err.Error()) } return C.TRUE } /* extern "C" __declspec(dllexport) BOOL __cdecl unload(); * * リクエストハンドラを呼んでログファイルをクローズするだけです。 */ //export unload func unload() C.BOOL { log.Println("[info] unload()") // リクエストハンドラを呼びます err := requesthandlers.OnUnload() if err != nil { log.Printf("[info] OnUnload() failed\n%s\n", err.Error()) } // ログファイルを使っていたら、クローズします。 if logFile != nil { logFile.Close() } return C.TRUE } /* extern "C" __declspec(dllexport) HGLOBAL __cdecl request(HGLOBAL h, long *length); * * h = リクエスト(文字列) * length = h のサイズ(load() と違ってポインタなので注意) * * h は GlobalAlloc(GPTR, length) で確保されたメモリ領域へのポインタで、DLL 側で GlobalFree(h) する必要があります。 * * リクエストの文字コードは Charset ヘッダを見るまでわかりませんが、ここでは簡便のため UTF-8 で来ると仮定しています。 * 伺かベースウェアのデファクトスタンダードである SSP は UTF-8 で送ってくれるので、とりあえず、です。 * そこら辺もちゃんと処理したいなら Charset ヘッダを見ればリクエストの文字コードがわかります。 * Shift_JIS から UTF-8 に変換したければ、strings パッケージをインポートして以下を追加します。 * * req_str = readerstream.New(strings.NewReader(req_str)).FromShiftJIS().String() * * レスポンスは h とは別に GlobalAlloc(GPTR, n) し、そこに書き込みます。 * そして書き込んだ長さ n を length に書き込み、レスポンスが入ったメモリ領域へのポインタを返します。 * こっちの GlobalFree() はベースウェアがしてくれます。 * * レスポンスも簡便のため一律に UTF-8 で返しています。 * Shift_JIS で返したければ、strings パッケージをインポートして以下を追加します。 * * res.Headers["Charset"] = "Shift_JIS" * res_str = readerstream.New(strings.NewReader(res_str)).ToShiftJIS().String() */ //export request func request(h C.HGLOBAL, length *C.long) C.HGLOBAL { var err error var req shiori.Request var res shiori.Response // リクエストが入っているメモリのサイズを取得します。 // load() と違い、ポインタなので注意してください。 req_size := (*length) // せっかくサイズ情報があるので C.GoStringN() を使います。 // ここは C.GoString() でも大丈夫なはず。 req_str := C.GoStringN((*C.char)(h), (C.int)(req_size)) // レスポンスが入っているメモリを開放します。 C.GlobalFree(h) log.Printf("[info] request content [%s]\n%s\n", req.Charset(), req_str) // リクエストである Go string をパースして shiori.Request にします。 req, err = shiori.ParseRequest(req_str) if err != nil { // パースできなかったらダメなリクエスト送ってきてんじゃねえ!と文句を返します(文学的な表現です)。 log.Printf("[error] shiori.ParseRequest() failed: %s\n", err.Error()) res = requesthandlers.ResponseBadRequest() } else { // パースできたら、リクエストハンドラを呼びます。 res, err = requesthandlers.OnRequest(req) if err != nil { // ハンドラ内でエラーが起きたら Internal Server Error を返します。 log.Printf("[info] OnRequest() failed\n%s\n", err.Error()) res = requesthandlers.ResponseInternalServerError() } } // レスポンスである shiori.Response をGo string にします。 // 前述の通り、レスポンスの文字コードは UTF-8 に決め打ちです。 var res_str string res.Headers["Charset"] = "UTF-8" res_str = res.String() log.Printf("[info] response content [%s]\n%s", res.Charset(), res) // Go string の res_str を C で扱えるように、char の配列にします。 // C.CString() は malloc() してメモリを確保し、そこに Go string の内容をコピーする関数です。 res_buf := C.CString(res_str) // C.CString() で確保したメモリは自前で free() してやる必要があります。 // この時、res_buf の型は *C.char なので unsafe.Pointer (つまり void*) にキャストします。 defer C.free((unsafe.Pointer)(res_buf)) // バッファのサイズを調べます。 // len(res_str) でもいいんですが、後でキャストの手間が少しだけ省けるので strlen() を呼んでいます。 res_size := C.strlen(res_buf) // 調べたサイズを基に、レスポンス用のメモリを確保します。 // SIZE_T は Win32 API での size_t です。 ret := C.GlobalAlloc(C.GPTR, (C.SIZE_T)(res_size)) // 確保したメモリにレスポンスをコピーします。 // ret の型は C.HGLOBAL (つまり void*) なのですが、明示的に unsafe.Pointer にキャストしてやらねばなりません。 // 逆に res_size は strlen() を使ったために型が C.size_t となり、キャストする必要がありません。 C.memcpy((unsafe.Pointer)(ret), (unsafe.Pointer)(res_buf), res_size) // レスポンスのサイズを request() の第 2引数である length ポインタが指す先にキャストして書き込んでやります。 *length = (C.long)(res_size) // レスポンスが入ったメモリ領域へのポインタ(HGLOBAL = void* です)を返して終了! return ret }
.Fil
node_status.rs
// Generated from definition io.k8s.api.core.v1.NodeStatus /// NodeStatus is information about the current status of a node. #[derive(Clone, Debug, Default, PartialEq)] pub struct NodeStatus { /// List of addresses reachable to the node. Queried from cloud provider, if available. More info: https://kubernetes.io/docs/concepts/nodes/node/#addresses pub addresses: Option<Vec<crate::v1_13::api::core::v1::NodeAddress>>, /// Allocatable represents the resources of a node that are available for scheduling. Defaults to Capacity. pub allocatable: Option<std::collections::BTreeMap<String, crate::v1_13::apimachinery::pkg::api::resource::Quantity>>, /// Capacity represents the total resources of a node. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#capacity pub capacity: Option<std::collections::BTreeMap<String, crate::v1_13::apimachinery::pkg::api::resource::Quantity>>, /// Conditions is an array of current observed node conditions. More info: https://kubernetes.io/docs/concepts/nodes/node/#condition pub conditions: Option<Vec<crate::v1_13::api::core::v1::NodeCondition>>, /// Status of the config assigned to the node via the dynamic Kubelet config feature. pub config: Option<crate::v1_13::api::core::v1::NodeConfigStatus>, /// Endpoints of daemons running on the Node. pub daemon_endpoints: Option<crate::v1_13::api::core::v1::NodeDaemonEndpoints>, /// List of container images on this node pub images: Option<Vec<crate::v1_13::api::core::v1::ContainerImage>>, /// Set of ids/uuids to uniquely identify the node. More info: https://kubernetes.io/docs/concepts/nodes/node/#info pub node_info: Option<crate::v1_13::api::core::v1::NodeSystemInfo>, /// NodePhase is the recently observed lifecycle phase of the node. More info: https://kubernetes.io/docs/concepts/nodes/node/#phase The field is never populated, and now is deprecated. pub phase: Option<String>, /// List of volumes that are attached to the node. pub volumes_attached: Option<Vec<crate::v1_13::api::core::v1::AttachedVolume>>, /// List of attachable volumes in use (mounted) by the node. pub volumes_in_use: Option<Vec<String>>, } impl<'de> serde::Deserialize<'de> for NodeStatus { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { #[allow(non_camel_case_types)] enum Field { Key_addresses, Key_allocatable, Key_capacity, Key_conditions, Key_config, Key_daemon_endpoints, Key_images, Key_node_info, Key_phase, Key_volumes_attached, Key_volumes_in_use, Other, } impl<'de> serde::Deserialize<'de> for Field { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = Field; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "field identifier") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error { Ok(match v { "addresses" => Field::Key_addresses, "allocatable" => Field::Key_allocatable, "capacity" => Field::Key_capacity, "conditions" => Field::Key_conditions, "config" => Field::Key_config, "daemonEndpoints" => Field::Key_daemon_endpoints, "images" => Field::Key_images, "nodeInfo" => Field::Key_node_info, "phase" => Field::Key_phase, "volumesAttached" => Field::Key_volumes_attached, "volumesInUse" => Field::Key_volumes_in_use, _ => Field::Other, }) } } deserializer.deserialize_identifier(Visitor) } } struct
; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = NodeStatus; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "struct NodeStatus") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> { let mut value_addresses: Option<Vec<crate::v1_13::api::core::v1::NodeAddress>> = None; let mut value_allocatable: Option<std::collections::BTreeMap<String, crate::v1_13::apimachinery::pkg::api::resource::Quantity>> = None; let mut value_capacity: Option<std::collections::BTreeMap<String, crate::v1_13::apimachinery::pkg::api::resource::Quantity>> = None; let mut value_conditions: Option<Vec<crate::v1_13::api::core::v1::NodeCondition>> = None; let mut value_config: Option<crate::v1_13::api::core::v1::NodeConfigStatus> = None; let mut value_daemon_endpoints: Option<crate::v1_13::api::core::v1::NodeDaemonEndpoints> = None; let mut value_images: Option<Vec<crate::v1_13::api::core::v1::ContainerImage>> = None; let mut value_node_info: Option<crate::v1_13::api::core::v1::NodeSystemInfo> = None; let mut value_phase: Option<String> = None; let mut value_volumes_attached: Option<Vec<crate::v1_13::api::core::v1::AttachedVolume>> = None; let mut value_volumes_in_use: Option<Vec<String>> = None; while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? { match key { Field::Key_addresses => value_addresses = serde::de::MapAccess::next_value(&mut map)?, Field::Key_allocatable => value_allocatable = serde::de::MapAccess::next_value(&mut map)?, Field::Key_capacity => value_capacity = serde::de::MapAccess::next_value(&mut map)?, Field::Key_conditions => value_conditions = serde::de::MapAccess::next_value(&mut map)?, Field::Key_config => value_config = serde::de::MapAccess::next_value(&mut map)?, Field::Key_daemon_endpoints => value_daemon_endpoints = serde::de::MapAccess::next_value(&mut map)?, Field::Key_images => value_images = serde::de::MapAccess::next_value(&mut map)?, Field::Key_node_info => value_node_info = serde::de::MapAccess::next_value(&mut map)?, Field::Key_phase => value_phase = serde::de::MapAccess::next_value(&mut map)?, Field::Key_volumes_attached => value_volumes_attached = serde::de::MapAccess::next_value(&mut map)?, Field::Key_volumes_in_use => value_volumes_in_use = serde::de::MapAccess::next_value(&mut map)?, Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; }, } } Ok(NodeStatus { addresses: value_addresses, allocatable: value_allocatable, capacity: value_capacity, conditions: value_conditions, config: value_config, daemon_endpoints: value_daemon_endpoints, images: value_images, node_info: value_node_info, phase: value_phase, volumes_attached: value_volumes_attached, volumes_in_use: value_volumes_in_use, }) } } deserializer.deserialize_struct( "NodeStatus", &[ "addresses", "allocatable", "capacity", "conditions", "config", "daemonEndpoints", "images", "nodeInfo", "phase", "volumesAttached", "volumesInUse", ], Visitor, ) } } impl serde::Serialize for NodeStatus { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer { let mut state = serializer.serialize_struct( "NodeStatus", self.addresses.as_ref().map_or(0, |_| 1) + self.allocatable.as_ref().map_or(0, |_| 1) + self.capacity.as_ref().map_or(0, |_| 1) + self.conditions.as_ref().map_or(0, |_| 1) + self.config.as_ref().map_or(0, |_| 1) + self.daemon_endpoints.as_ref().map_or(0, |_| 1) + self.images.as_ref().map_or(0, |_| 1) + self.node_info.as_ref().map_or(0, |_| 1) + self.phase.as_ref().map_or(0, |_| 1) + self.volumes_attached.as_ref().map_or(0, |_| 1) + self.volumes_in_use.as_ref().map_or(0, |_| 1), )?; if let Some(value) = &self.addresses { serde::ser::SerializeStruct::serialize_field(&mut state, "addresses", value)?; } if let Some(value) = &self.allocatable { serde::ser::SerializeStruct::serialize_field(&mut state, "allocatable", value)?; } if let Some(value) = &self.capacity { serde::ser::SerializeStruct::serialize_field(&mut state, "capacity", value)?; } if let Some(value) = &self.conditions { serde::ser::SerializeStruct::serialize_field(&mut state, "conditions", value)?; } if let Some(value) = &self.config { serde::ser::SerializeStruct::serialize_field(&mut state, "config", value)?; } if let Some(value) = &self.daemon_endpoints { serde::ser::SerializeStruct::serialize_field(&mut state, "daemonEndpoints", value)?; } if let Some(value) = &self.images { serde::ser::SerializeStruct::serialize_field(&mut state, "images", value)?; } if let Some(value) = &self.node_info { serde::ser::SerializeStruct::serialize_field(&mut state, "nodeInfo", value)?; } if let Some(value) = &self.phase { serde::ser::SerializeStruct::serialize_field(&mut state, "phase", value)?; } if let Some(value) = &self.volumes_attached { serde::ser::SerializeStruct::serialize_field(&mut state, "volumesAttached", value)?; } if let Some(value) = &self.volumes_in_use { serde::ser::SerializeStruct::serialize_field(&mut state, "volumesInUse", value)?; } serde::ser::SerializeStruct::end(state) } }
Visitor
count-number-of-maximum-bitwise-or-subsets.go
package solution2044 func countMaxOrSubsets(nums []int) (ans int) { maxOr := 0 for i := 1; i < 1<<len(nums); i++ { or := 0 for j, num := range nums { if i>>j&1 == 1 { or |= num } } if or > maxOr { maxOr = or ans = 1 } else if or == maxOr
} return }
{ ans++ }
index.js
module.exports = {handler: require('@ohoareau/lambda-api-event').default()}
PersonNameInfo.js
/** * Pipedrive API v1 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
import ApiClient from '../ApiClient'; /** * The PersonNameInfo model module. * @module model/PersonNameInfo * @version 1.0.0 */ class PersonNameInfo { /** * Constructs a new <code>PersonNameInfo</code>. * @alias module:model/PersonNameInfo */ constructor() { PersonNameInfo.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>PersonNameInfo</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/PersonNameInfo} obj Optional instance to populate. * @return {module:model/PersonNameInfo} The populated <code>PersonNameInfo</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new PersonNameInfo(); if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); delete data['name']; } if (data.hasOwnProperty('first_name')) { obj['first_name'] = ApiClient.convertToType(data['first_name'], 'String'); delete data['first_name']; } if (data.hasOwnProperty('last_name')) { obj['last_name'] = ApiClient.convertToType(data['last_name'], 'String'); delete data['last_name']; } if (Object.keys(data).length > 0) { Object.assign(obj, data); } } return obj; } } /** * The name of the person * @member {String} name */ PersonNameInfo.prototype['name'] = undefined; /** * The first name of the person * @member {String} first_name */ PersonNameInfo.prototype['first_name'] = undefined; /** * The last name of the person * @member {String} last_name */ PersonNameInfo.prototype['last_name'] = undefined; export default PersonNameInfo;
* https://openapi-generator.tech * Do not edit the class manually. * */
app.js
'use strict'; let imgArr = []; function Image (imgObject) { this.image_url = imgObject.image_url; this.title = imgObject.title; this.description = imgObject.description; this.keyword = imgObject.keyword; this.horns = imgObject.horns; } // render function Image.prototype.render = function() { $('main').append('<div class="clone"></div>'); let imageClone = $('div[class="clone"]'); let imageHtml = $('#photo-template').html(); imageClone.html(imageHtml); imageClone.find('h2').text(this.title);
imageClone.find('p').text(this.description); imageClone.removeClass('clone'); imageClone.attr('class' , this.keyword); }; //generate images from page-1 Image.readJson = () => { $.ajax('../data/page-1.json','json') .then(imgData => { imgData.forEach(imageItem => { imgArr.push(new Image(imageItem)); }); }) .then(Image.loadImage); }; Image.loadImage = () => { imgArr.forEach(imgObject => imgObject.render()); renderList(); }; $(() => Image.readJson()); //generate keyword list let keywordFilter = []; function renderList () { imgArr.forEach((keywordCheck) => { if(!keywordFilter.includes(keywordCheck.keyword)) { console.log(keywordCheck.keyword); keywordFilter.push(keywordCheck.keyword); $('select').append(`<option>${keywordCheck.keyword}</option>`); } }); } Image.prototype.renderList = function() { //select the parent & creating an option imgArr.forEach(); $('option').append('<p></p>'); let $listClone = $('option[class="clone"]'); //fill the option $listClone.find('option').text(this.keyword); $listClone.removeClass('clone'); $listClone.attr('class', this.keyword); //find the option $listClone.find('p').text(this.keyword); }; //filter by keyword keywordFilter.forEach(function(value) { $('select') .append(`<option id="option_${value}">${value}</option>`);}); $('select').on('change', (event) => { let option = event.target.value; $('div').hide(); $(`.${option}`).show(); });
imageClone.find('img').attr('src', this.image_url); imageClone.find('img').attr('alt', this.title);
identity_credentials.rs
use crate::credential::Verifier; use crate::IdentityCredentialRequest::*; use crate::IdentityError::IdentityApiFailed; use crate::{ BbsCredential, Credential, CredentialAcquisitionResultMessage, CredentialAttribute, CredentialFragment1, CredentialFragment2, CredentialOffer, CredentialPresentation, CredentialProof, CredentialProtocol, CredentialPublicKey, CredentialRequest, CredentialRequestFragment, CredentialSchema, CredentialVerificationResultMessage, Holder, HolderWorker, Identity, Identity, IdentityCredential, IdentityCredentialResponse, IdentityIdentifier, IdentityRequest, IdentityResponse, IdentityTrait, Issuer, ListenerWorker, OfferId, PresentationFinishedMessage, PresentationManifest, PresenterWorker, ProofRequestId, SigningPublicKey, TrustPolicy, TrustPolicyImpl, VerifierWorker, }; use core::convert::TryInto; use ockam_core::{async_trait, compat::boxed::Box}; use ockam_core::{Address, Result, Route}; use signature_bls::SecretKey; use IdentityRequest::*; use IdentityResponse as Res; fn err<T>() -> Result<T> { Err(IdentityApiFailed.into()) } #[async_trait] impl Issuer for Identity { async fn get_signing_key(&mut self) -> Result<SecretKey> { // FIXME: Clone on every call let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(GetSigningKey( identity .identifier() .await .expect("couldn't get identity id"), ))) .await? { if let IdentityCredentialResponse::GetSigningKey(signing_key) = res { Ok(signing_key) } else { err() } } else { err() } } async fn get_signing_public_key(&mut self) -> Result<SigningPublicKey> { // FIXME: Why clone? let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(GetIssuerPublicKey( identity .identifier() .await .expect("couldn't get identity id"), ))) .await? { if let IdentityCredentialResponse::GetIssuerPublicKey(issuer_public_key) = res { Ok(issuer_public_key.0) } else { err() } } else { err() } } async fn create_offer(&self, schema: &CredentialSchema) -> Result<CredentialOffer> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(CreateOffer( identity .identifier() .await .expect("couldn't get identity id"), schema.clone(), ))) .await? { if let IdentityCredentialResponse::CreateOffer(offer) = res { Ok(offer) } else { err() } } else { err() } } async fn create_proof_of_possession(&self) -> Result<CredentialProof> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(CreateProofOfPossession( identity .identifier() .await .expect("couldn't get identity id"), ))) .await? { if let IdentityCredentialResponse::CreateProofOfPossession(proof) = res { Ok(proof) } else { err() } } else { err() } } async fn sign_credential( &self, schema: &CredentialSchema, attributes: &[CredentialAttribute], ) -> Result<BbsCredential> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(SignCredential( identity .identifier() .await .expect("couldn't get identity id"), schema.clone(), attributes.as_ref().to_vec(), ))) .await? { if let IdentityCredentialResponse::SignCredential(credential) = res { Ok(credential) } else { err() } } else { err() } } async fn sign_credential_request( &self, request: &CredentialRequest, schema: &CredentialSchema, attributes: &[(String, CredentialAttribute)], offer_id: OfferId, ) -> Result<CredentialFragment2> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(SignCredentialRequest( identity .identifier() .await .expect("couldn't get identity id"), request.clone(), schema.clone(), attributes.as_ref().to_vec(), offer_id, ))) .await? { if let IdentityCredentialResponse::SignCredentialRequest(frag) = res { Ok(frag) } else { err() } } else { err() } } } #[async_trait] impl Holder for Identity { async fn accept_credential_offer( &self, offer: &CredentialOffer, issuer_public_key: SigningPublicKey, ) -> Result<CredentialRequestFragment> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(AcceptCredentialOffer( identity .identifier() .await .expect("couldn't get identity id"), offer.clone(), CredentialPublicKey(issuer_public_key), ))) .await? { if let IdentityCredentialResponse::AcceptCredentialOffer(request_fragment) = res { Ok(request_fragment) } else { err() } } else { err() } } async fn combine_credential_fragments( &self, credential_fragment1: CredentialFragment1, credential_fragment2: CredentialFragment2, ) -> Result<BbsCredential> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(CombineCredentialFragments( identity .identifier() .await .expect("couldn't get identity id"), credential_fragment1, credential_fragment2, ))) .await? { if let IdentityCredentialResponse::CombineCredentialFragments(credential) = res { Ok(credential) } else { err() } } else { err() } } async fn is_valid_credential( &self, credential: &BbsCredential, verifier_key: SigningPublicKey, ) -> Result<bool> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(IsValidCredential( identity .identifier() .await .expect("couldn't get identity id"), credential.clone(), CredentialPublicKey(verifier_key), ))) .await? { if let IdentityCredentialResponse::IsValidCredential(valid) = res { Ok(valid) } else {
} else { err() } } async fn create_credential_presentation( &self, credential: &BbsCredential, presentation_manifests: &PresentationManifest, proof_request_id: ProofRequestId, ) -> Result<CredentialPresentation> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(PresentCredential( identity .identifier() .await .expect("couldn't get identity id"), credential.clone(), presentation_manifests.clone(), proof_request_id, ))) .await? { if let IdentityCredentialResponse::PresentCredential(presentation) = res { Ok(presentation) } else { err() } } else { err() } } async fn add_credential(&mut self, credential: IdentityCredential) -> Result<()> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(AddCredential( identity .identifier() .await .expect("couldn't get identity id"), credential, ))) .await? { if let IdentityCredentialResponse::AddCredential = res { Ok(()) } else { err() } } else { err() } } async fn get_credential(&mut self, credential: &Credential) -> Result<IdentityCredential> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(GetCredential( identity .identifier() .await .expect("couldn't get identity id"), credential.clone(), ))) .await? { if let IdentityCredentialResponse::GetCredential(c) = res { Ok(c) } else { err() } } else { err() } } } #[async_trait] impl Verifier for Identity { async fn create_proof_request_id(&self) -> Result<ProofRequestId> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(CreateProofRequestId( identity .identifier() .await .expect("couldn't get identity id"), ))) .await? { if let IdentityCredentialResponse::CreateProofRequestId(request_id) = res { Ok(request_id) } else { err() } } else { err() } } async fn verify_proof_of_possession( &self, signing_public_key: CredentialPublicKey, proof: CredentialProof, ) -> Result<bool> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(VerifyProofOfPossession( identity .identifier() .await .expect("couldn't get identity id"), signing_public_key, proof, ))) .await? { if let IdentityCredentialResponse::VerifyProofOfPossession(verified) = res { Ok(verified) } else { err() } } else { err() } } async fn verify_credential_presentation( &self, presentation: &CredentialPresentation, presentation_manifest: &PresentationManifest, proof_request_id: ProofRequestId, ) -> Result<bool> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); if let Res::CredentialResponse(res) = identity .call(CredentialRequest(VerifyCredentialPresentation( identity .identifier() .await .expect("couldn't get identity id"), presentation.clone(), presentation_manifest.clone(), proof_request_id, ))) .await? { if let IdentityCredentialResponse::VerifyCredentialPresentation(verified) = res { Ok(verified) } else { err() } } else { err() } } } #[async_trait] impl CredentialProtocol for Identity { async fn create_credential_issuance_listener( &mut self, address: Address, schema: CredentialSchema, trust_policy: impl TrustPolicy, ) -> Result<()> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); let trust_policy = TrustPolicyImpl::create_using_impl(&self.handle.ctx(), trust_policy).await?; let worker = ListenerWorker::new(identity, schema, trust_policy); self.handle.ctx().start_worker(address, worker).await?; Ok(()) } async fn acquire_credential( &mut self, issuer_route: Route, issuer_id: &IdentityIdentifier, schema: CredentialSchema, values: Vec<CredentialAttribute>, ) -> Result<Credential> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); let mut ctx = self.handle.ctx().new_context(Address::random(0)).await?; let worker = HolderWorker::new( identity, issuer_id.clone(), issuer_route, schema, values, ctx.address(), ); ctx.start_worker(Address::random(0), worker).await?; let res = ctx .receive_timeout::<CredentialAcquisitionResultMessage>(120 /* FIXME */) .await? .take() .body(); Ok(res.credential) } async fn present_credential( &mut self, verifier_route: Route, credential: Credential, reveal_attributes: Vec<String>, ) -> Result<()> { let identity = self .current_identity() .await .unwrap() .expect("no current identity"); let credential = self.get_credential(&credential).await?; let mut ctx = self.handle.ctx().new_context(Address::random(0)).await?; let worker = PresenterWorker::new( identity, verifier_route, credential, reveal_attributes, ctx.address(), ); ctx.start_worker(Address::random(0), worker).await?; let _ = ctx .receive_timeout::<PresentationFinishedMessage>(120 /* FIXME */) .await? .take() .body(); Ok(()) } async fn verify_credential( &mut self, address: Address, issuer_id: &IdentityIdentifier, schema: CredentialSchema, attributes_values: Vec<CredentialAttribute>, ) -> Result<bool> { let mut identity = self .current_identity() .await .unwrap() .expect("no current identity"); let issuer = identity.get_contact(issuer_id).await?.unwrap(); let pubkey = issuer.get_signing_public_key()?; let mut ctx = self.handle.ctx().new_context(Address::random(0)).await?; let worker = VerifierWorker::new( identity, pubkey.as_ref().try_into().unwrap(), // FIXME schema, attributes_values, ctx.address(), ); ctx.start_worker(address, worker).await?; let res = ctx .receive_timeout::<CredentialVerificationResultMessage>(120 /* FIXME */) .await? .take() .body(); Ok(res.is_valid) } }
err() }
KnxManufacturer.go
// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // package model import ( "github.com/apache/plc4x/plc4go/internal/plc4go/spi/utils" "github.com/pkg/errors" ) // Code generated by code-generation. DO NOT EDIT. type KnxManufacturer uint16 type IKnxManufacturer interface { Number() uint16 Name() string Serialize(writeBuffer utils.WriteBuffer) error } const ( KnxManufacturer_M_UNKNOWN KnxManufacturer = 0 KnxManufacturer_M_SIEMENS KnxManufacturer = 1 KnxManufacturer_M_ABB KnxManufacturer = 2 KnxManufacturer_M_ALBRECHT_JUNG KnxManufacturer = 3 KnxManufacturer_M_BTICINO KnxManufacturer = 4 KnxManufacturer_M_BERKER KnxManufacturer = 5 KnxManufacturer_M_BUSCH_JAEGER_ELEKTRO KnxManufacturer = 6 KnxManufacturer_M_GIRA_GIERSIEPEN KnxManufacturer = 7 KnxManufacturer_M_HAGER_ELECTRO KnxManufacturer = 8 KnxManufacturer_M_INSTA_GMBH KnxManufacturer = 9 KnxManufacturer_M_LEGRAND_APPAREILLAGE_ELECTRIQUE KnxManufacturer = 10 KnxManufacturer_M_MERTEN KnxManufacturer = 11 KnxManufacturer_M_ABB_SPA_SACE_DIVISION KnxManufacturer = 12 KnxManufacturer_M_SIEDLE_AND_SOEHNE KnxManufacturer = 13 KnxManufacturer_M_EBERLE KnxManufacturer = 14 KnxManufacturer_M_GEWISS KnxManufacturer = 15 KnxManufacturer_M_ALBERT_ACKERMANN KnxManufacturer = 16 KnxManufacturer_M_SCHUPA_GMBH KnxManufacturer = 17 KnxManufacturer_M_ABB_SCHWEIZ KnxManufacturer = 18 KnxManufacturer_M_FELLER KnxManufacturer = 19 KnxManufacturer_M_GLAMOX_AS KnxManufacturer = 20 KnxManufacturer_M_DEHN_AND_SOEHNE KnxManufacturer = 21 KnxManufacturer_M_CRABTREE KnxManufacturer = 22 KnxManufacturer_M_EVOKNX KnxManufacturer = 23 KnxManufacturer_M_PAUL_HOCHKOEPPER KnxManufacturer = 24 KnxManufacturer_M_ALTENBURGER_ELECTRONIC KnxManufacturer = 25 KnxManufacturer_M_GRAESSLIN KnxManufacturer = 26 KnxManufacturer_M_SIMON_42 KnxManufacturer = 27 KnxManufacturer_M_VIMAR KnxManufacturer = 28 KnxManufacturer_M_MOELLER_GEBAEUDEAUTOMATION_KG KnxManufacturer = 29 KnxManufacturer_M_ELTAKO KnxManufacturer = 30 KnxManufacturer_M_BOSCH_SIEMENS_HAUSHALTSGERAETE KnxManufacturer = 31 KnxManufacturer_M_RITTO_GMBHANDCO_KG KnxManufacturer = 32 KnxManufacturer_M_POWER_CONTROLS KnxManufacturer = 33 KnxManufacturer_M_ZUMTOBEL KnxManufacturer = 34 KnxManufacturer_M_PHOENIX_CONTACT KnxManufacturer = 35 KnxManufacturer_M_WAGO_KONTAKTTECHNIK KnxManufacturer = 36 KnxManufacturer_M_KNXPRESSO KnxManufacturer = 37 KnxManufacturer_M_WIELAND_ELECTRIC KnxManufacturer = 38 KnxManufacturer_M_HERMANN_KLEINHUIS KnxManufacturer = 39 KnxManufacturer_M_STIEBEL_ELTRON KnxManufacturer = 40 KnxManufacturer_M_TEHALIT KnxManufacturer = 41 KnxManufacturer_M_THEBEN_AG KnxManufacturer = 42 KnxManufacturer_M_WILHELM_RUTENBECK KnxManufacturer = 43 KnxManufacturer_M_WINKHAUS KnxManufacturer = 44 KnxManufacturer_M_ROBERT_BOSCH KnxManufacturer = 45 KnxManufacturer_M_SOMFY KnxManufacturer = 46 KnxManufacturer_M_WOERTZ KnxManufacturer = 47 KnxManufacturer_M_VIESSMANN_WERKE KnxManufacturer = 48 KnxManufacturer_M_IMI_HYDRONIC_ENGINEERING KnxManufacturer = 49 KnxManufacturer_M_JOH__VAILLANT KnxManufacturer = 50 KnxManufacturer_M_AMP_DEUTSCHLAND KnxManufacturer = 51 KnxManufacturer_M_BOSCH_THERMOTECHNIK_GMBH KnxManufacturer = 52 KnxManufacturer_M_SEF___ECOTEC KnxManufacturer = 53 KnxManufacturer_M_DORMA_GMBH_Plus_CO__KG KnxManufacturer = 54 KnxManufacturer_M_WINDOWMASTER_AS KnxManufacturer = 55 KnxManufacturer_M_WALTHER_WERKE KnxManufacturer = 56 KnxManufacturer_M_ORAS KnxManufacturer = 57 KnxManufacturer_M_DAETWYLER KnxManufacturer = 58 KnxManufacturer_M_ELECTRAK KnxManufacturer = 59 KnxManufacturer_M_TECHEM KnxManufacturer = 60 KnxManufacturer_M_SCHNEIDER_ELECTRIC_INDUSTRIES_SAS KnxManufacturer = 61 KnxManufacturer_M_WHD_WILHELM_HUBER_Plus_SOEHNE KnxManufacturer = 62 KnxManufacturer_M_BISCHOFF_ELEKTRONIK KnxManufacturer = 63 KnxManufacturer_M_JEPAZ KnxManufacturer = 64 KnxManufacturer_M_RTS_AUTOMATION KnxManufacturer = 65 KnxManufacturer_M_EIBMARKT_GMBH KnxManufacturer = 66 KnxManufacturer_M_WAREMA_RENKHOFF_SE KnxManufacturer = 67 KnxManufacturer_M_EELECTRON KnxManufacturer = 68 KnxManufacturer_M_BELDEN_WIRE_AND_CABLE_B_V_ KnxManufacturer = 69 KnxManufacturer_M_BECKER_ANTRIEBE_GMBH KnxManufacturer = 70 KnxManufacturer_M_J_STEHLEPlusSOEHNE_GMBH KnxManufacturer = 71 KnxManufacturer_M_AGFEO KnxManufacturer = 72 KnxManufacturer_M_ZENNIO KnxManufacturer = 73 KnxManufacturer_M_TAPKO_TECHNOLOGIES KnxManufacturer = 74 KnxManufacturer_M_HDL KnxManufacturer = 75 KnxManufacturer_M_UPONOR KnxManufacturer = 76 KnxManufacturer_M_SE_LIGHTMANAGEMENT_AG KnxManufacturer = 77 KnxManufacturer_M_ARCUS_EDS KnxManufacturer = 78 KnxManufacturer_M_INTESIS KnxManufacturer = 79 KnxManufacturer_M_HERHOLDT_CONTROLS_SRL KnxManufacturer = 80 KnxManufacturer_M_NIKO_ZUBLIN KnxManufacturer = 81 KnxManufacturer_M_DURABLE_TECHNOLOGIES KnxManufacturer = 82 KnxManufacturer_M_INNOTEAM KnxManufacturer = 83 KnxManufacturer_M_ISE_GMBH KnxManufacturer = 84 KnxManufacturer_M_TEAM_FOR_TRONICS KnxManufacturer = 85 KnxManufacturer_M_CIAT KnxManufacturer = 86 KnxManufacturer_M_REMEHA_BV KnxManufacturer = 87 KnxManufacturer_M_ESYLUX KnxManufacturer = 88 KnxManufacturer_M_BASALTE KnxManufacturer = 89 KnxManufacturer_M_VESTAMATIC KnxManufacturer = 90 KnxManufacturer_M_MDT_TECHNOLOGIES KnxManufacturer = 91 KnxManufacturer_M_WARENDORFER_KUECHEN_GMBH KnxManufacturer = 92 KnxManufacturer_M_VIDEO_STAR KnxManufacturer = 93 KnxManufacturer_M_SITEK KnxManufacturer = 94 KnxManufacturer_M_CONTROLTRONIC KnxManufacturer = 95 KnxManufacturer_M_FUNCTION_TECHNOLOGY KnxManufacturer = 96 KnxManufacturer_M_AMX KnxManufacturer = 97 KnxManufacturer_M_ELDAT KnxManufacturer = 98 KnxManufacturer_M_PANASONIC KnxManufacturer = 99 KnxManufacturer_M_PULSE_TECHNOLOGIES KnxManufacturer = 100 KnxManufacturer_M_CRESTRON KnxManufacturer = 101 KnxManufacturer_M_STEINEL_PROFESSIONAL KnxManufacturer = 102 KnxManufacturer_M_BILTON_LED_LIGHTING KnxManufacturer = 103 KnxManufacturer_M_DENRO_AG KnxManufacturer = 104 KnxManufacturer_M_GEPRO KnxManufacturer = 105 KnxManufacturer_M_PREUSSEN_AUTOMATION KnxManufacturer = 106 KnxManufacturer_M_ZOPPAS_INDUSTRIES KnxManufacturer = 107 KnxManufacturer_M_MACTECH KnxManufacturer = 108 KnxManufacturer_M_TECHNO_TREND KnxManufacturer = 109 KnxManufacturer_M_FS_CABLES KnxManufacturer = 110 KnxManufacturer_M_DELTA_DORE KnxManufacturer = 111 KnxManufacturer_M_EISSOUND KnxManufacturer = 112 KnxManufacturer_M_CISCO KnxManufacturer = 113 KnxManufacturer_M_DINUY KnxManufacturer = 114 KnxManufacturer_M_IKNIX KnxManufacturer = 115 KnxManufacturer_M_RADEMACHER_GERAETE_ELEKTRONIK_GMBH KnxManufacturer = 116 KnxManufacturer_M_EGI_ELECTROACUSTICA_GENERAL_IBERICA KnxManufacturer = 117 KnxManufacturer_M_BES___INGENIUM KnxManufacturer = 118 KnxManufacturer_M_ELABNET KnxManufacturer = 119 KnxManufacturer_M_BLUMOTIX KnxManufacturer = 120 KnxManufacturer_M_HUNTER_DOUGLAS KnxManufacturer = 121 KnxManufacturer_M_APRICUM KnxManufacturer = 122 KnxManufacturer_M_TIANSU_AUTOMATION KnxManufacturer = 123 KnxManufacturer_M_BUBENDORFF KnxManufacturer = 124 KnxManufacturer_M_MBS_GMBH KnxManufacturer = 125 KnxManufacturer_M_ENERTEX_BAYERN_GMBH KnxManufacturer = 126 KnxManufacturer_M_BMS KnxManufacturer = 127 KnxManufacturer_M_SINAPSI KnxManufacturer = 128 KnxManufacturer_M_EMBEDDED_SYSTEMS_SIA KnxManufacturer = 129 KnxManufacturer_M_KNX1 KnxManufacturer = 130 KnxManufacturer_M_TOKKA KnxManufacturer = 131 KnxManufacturer_M_NANOSENSE KnxManufacturer = 132 KnxManufacturer_M_PEAR_AUTOMATION_GMBH KnxManufacturer = 133 KnxManufacturer_M_DGA KnxManufacturer = 134 KnxManufacturer_M_LUTRON KnxManufacturer = 135 KnxManufacturer_M_AIRZONE___ALTRA KnxManufacturer = 136 KnxManufacturer_M_LITHOSS_DESIGN_SWITCHES KnxManufacturer = 137 KnxManufacturer_M_THREEATEL KnxManufacturer = 138 KnxManufacturer_M_PHILIPS_CONTROLS KnxManufacturer = 139 KnxManufacturer_M_VELUX_AS KnxManufacturer = 140 KnxManufacturer_M_LOYTEC KnxManufacturer = 141 KnxManufacturer_M_EKINEX_S_P_A_ KnxManufacturer = 142 KnxManufacturer_M_SIRLAN_TECHNOLOGIES KnxManufacturer = 143 KnxManufacturer_M_PROKNX_SAS KnxManufacturer = 144 KnxManufacturer_M_IT_GMBH KnxManufacturer = 145 KnxManufacturer_M_RENSON KnxManufacturer = 146 KnxManufacturer_M_HEP_GROUP KnxManufacturer = 147 KnxManufacturer_M_BALMART KnxManufacturer = 148 KnxManufacturer_M_GFS_GMBH KnxManufacturer = 149 KnxManufacturer_M_SCHENKER_STOREN_AG KnxManufacturer = 150 KnxManufacturer_M_ALGODUE_ELETTRONICA_S_R_L_ KnxManufacturer = 151 KnxManufacturer_M_ABB_FRANCE KnxManufacturer = 152 KnxManufacturer_M_MAINTRONIC KnxManufacturer = 153 KnxManufacturer_M_VANTAGE KnxManufacturer = 154 KnxManufacturer_M_FORESIS KnxManufacturer = 155 KnxManufacturer_M_RESEARCH_AND_PRODUCTION_ASSOCIATION_SEM KnxManufacturer = 156 KnxManufacturer_M_WEINZIERL_ENGINEERING_GMBH KnxManufacturer = 157 KnxManufacturer_M_MOEHLENHOFF_WAERMETECHNIK_GMBH KnxManufacturer = 158 KnxManufacturer_M_PKC_GROUP_OYJ KnxManufacturer = 159 KnxManufacturer_M_B_E_G_ KnxManufacturer = 160 KnxManufacturer_M_ELSNER_ELEKTRONIK_GMBH KnxManufacturer = 161 KnxManufacturer_M_SIEMENS_BUILDING_TECHNOLOGIES_HKCHINA_LTD_ KnxManufacturer = 162 KnxManufacturer_M_EUTRAC KnxManufacturer = 163 KnxManufacturer_M_GUSTAV_HENSEL_GMBH_AND_CO__KG KnxManufacturer = 164 KnxManufacturer_M_GARO_AB KnxManufacturer = 165 KnxManufacturer_M_WALDMANN_LICHTTECHNIK KnxManufacturer = 166 KnxManufacturer_M_SCHUECO KnxManufacturer = 167 KnxManufacturer_M_EMU KnxManufacturer = 168 KnxManufacturer_M_JNET_SYSTEMS_AG KnxManufacturer = 169 KnxManufacturer_M_TOTAL_SOLUTION_GMBH KnxManufacturer = 170 KnxManufacturer_M_O_Y_L__ELECTRONICS KnxManufacturer = 171 KnxManufacturer_M_GALAX_SYSTEM KnxManufacturer = 172 KnxManufacturer_M_DISCH KnxManufacturer = 173 KnxManufacturer_M_AUCOTEAM KnxManufacturer = 174 KnxManufacturer_M_LUXMATE_CONTROLS KnxManufacturer = 175 KnxManufacturer_M_DANFOSS KnxManufacturer = 176 KnxManufacturer_M_AST_GMBH KnxManufacturer = 177 KnxManufacturer_M_WILA_LEUCHTEN KnxManufacturer = 178 KnxManufacturer_M_BPlusB_AUTOMATIONS__UND_STEUERUNGSTECHNIK KnxManufacturer = 179 KnxManufacturer_M_LINGG_AND_JANKE KnxManufacturer = 180 KnxManufacturer_M_SAUTER KnxManufacturer = 181 KnxManufacturer_M_SIMU KnxManufacturer = 182 KnxManufacturer_M_THEBEN_HTS_AG KnxManufacturer = 183 KnxManufacturer_M_AMANN_GMBH KnxManufacturer = 184 KnxManufacturer_M_BERG_ENERGIEKONTROLLSYSTEME_GMBH KnxManufacturer = 185 KnxManufacturer_M_HUEPPE_FORM_SONNENSCHUTZSYSTEME_GMBH KnxManufacturer = 186 KnxManufacturer_M_OVENTROP_KG KnxManufacturer = 187 KnxManufacturer_M_GRIESSER_AG KnxManufacturer = 188 KnxManufacturer_M_IPAS_GMBH KnxManufacturer = 189 KnxManufacturer_M_ELERO_GMBH KnxManufacturer = 190 KnxManufacturer_M_ARDAN_PRODUCTION_AND_INDUSTRIAL_CONTROLS_LTD_ KnxManufacturer = 191 KnxManufacturer_M_METEC_MESSTECHNIK_GMBH KnxManufacturer = 192 KnxManufacturer_M_ELKA_ELEKTRONIK_GMBH KnxManufacturer = 193 KnxManufacturer_M_ELEKTROANLAGEN_D__NAGEL KnxManufacturer = 194 KnxManufacturer_M_TRIDONIC_BAUELEMENTE_GMBH KnxManufacturer = 195 KnxManufacturer_M_STENGLER_GESELLSCHAFT KnxManufacturer = 196 KnxManufacturer_M_SCHNEIDER_ELECTRIC_MG KnxManufacturer = 197 KnxManufacturer_M_KNX_ASSOCIATION KnxManufacturer = 198 KnxManufacturer_M_VIVO KnxManufacturer = 199 KnxManufacturer_M_HUGO_MUELLER_GMBH_AND_CO_KG KnxManufacturer = 200 KnxManufacturer_M_SIEMENS_HVAC KnxManufacturer = 201 KnxManufacturer_M_APT KnxManufacturer = 202 KnxManufacturer_M_HIGHDOM KnxManufacturer = 203 KnxManufacturer_M_TOP_SERVICES KnxManufacturer = 204 KnxManufacturer_M_AMBIHOME KnxManufacturer = 205 KnxManufacturer_M_DATEC_ELECTRONIC_AG KnxManufacturer = 206 KnxManufacturer_M_ABUS_SECURITY_CENTER KnxManufacturer = 207 KnxManufacturer_M_LITE_PUTER KnxManufacturer = 208 KnxManufacturer_M_TANTRON_ELECTRONIC KnxManufacturer = 209 KnxManufacturer_M_INTERRA KnxManufacturer = 210 KnxManufacturer_M_DKX_TECH KnxManufacturer = 211 KnxManufacturer_M_VIATRON KnxManufacturer = 212 KnxManufacturer_M_NAUTIBUS KnxManufacturer = 213 KnxManufacturer_M_ON_SEMICONDUCTOR KnxManufacturer = 214 KnxManufacturer_M_LONGCHUANG KnxManufacturer = 215 KnxManufacturer_M_AIR_ON_AG KnxManufacturer = 216 KnxManufacturer_M_IB_COMPANY_GMBH KnxManufacturer = 217 KnxManufacturer_M_SATION_FACTORY KnxManufacturer = 218 KnxManufacturer_M_AGENTILO_GMBH KnxManufacturer = 219 KnxManufacturer_M_MAKEL_ELEKTRIK KnxManufacturer = 220 KnxManufacturer_M_HELIOS_VENTILATOREN KnxManufacturer = 221 KnxManufacturer_M_OTTO_SOLUTIONS_PTE_LTD KnxManufacturer = 222 KnxManufacturer_M_AIRMASTER KnxManufacturer = 223 KnxManufacturer_M_VALLOX_GMBH KnxManufacturer = 224 KnxManufacturer_M_DALITEK KnxManufacturer = 225 KnxManufacturer_M_ASIN KnxManufacturer = 226 KnxManufacturer_M_BRIDGES_INTELLIGENCE_TECHNOLOGY_INC_ KnxManufacturer = 227 KnxManufacturer_M_ARBONIA KnxManufacturer = 228 KnxManufacturer_M_KERMI KnxManufacturer = 229 KnxManufacturer_M_PROLUX KnxManufacturer = 230 KnxManufacturer_M_CLICHOME KnxManufacturer = 231 KnxManufacturer_M_COMMAX KnxManufacturer = 232 KnxManufacturer_M_EAE KnxManufacturer = 233 KnxManufacturer_M_TENSE KnxManufacturer = 234 KnxManufacturer_M_SEYOUNG_ELECTRONICS KnxManufacturer = 235 KnxManufacturer_M_LIFEDOMUS KnxManufacturer = 236 KnxManufacturer_M_EUROTRONIC_TECHNOLOGY_GMBH KnxManufacturer = 237 KnxManufacturer_M_TCI KnxManufacturer = 238 KnxManufacturer_M_RISHUN_ELECTRONIC KnxManufacturer = 239 KnxManufacturer_M_ZIPATO KnxManufacturer = 240 KnxManufacturer_M_CM_SECURITY_GMBH_AND_CO_KG KnxManufacturer = 241 KnxManufacturer_M_QING_CABLES KnxManufacturer = 242 KnxManufacturer_M_LABIO KnxManufacturer = 243 KnxManufacturer_M_COSTER_TECNOLOGIE_ELETTRONICHE_S_P_A_ KnxManufacturer = 244 KnxManufacturer_M_E_G_E KnxManufacturer = 245 KnxManufacturer_M_NETXAUTOMATION KnxManufacturer = 246 KnxManufacturer_M_TECALOR KnxManufacturer = 247 KnxManufacturer_M_URMET_ELECTRONICS_HUIZHOU_LTD_ KnxManufacturer = 248 KnxManufacturer_M_PEIYING_BUILDING_CONTROL KnxManufacturer = 249 KnxManufacturer_M_BPT_S_P_A__A_SOCIO_UNICO KnxManufacturer = 250 KnxManufacturer_M_KANONTEC___KANONBUS KnxManufacturer = 251 KnxManufacturer_M_ISER_TECH KnxManufacturer = 252 KnxManufacturer_M_FINELINE KnxManufacturer = 253 KnxManufacturer_M_CP_ELECTRONICS_LTD KnxManufacturer = 254 KnxManufacturer_M_NIKO_SERVODAN_AS KnxManufacturer = 255 KnxManufacturer_M_SIMON_309 KnxManufacturer = 256 KnxManufacturer_M_GM_MODULAR_PVT__LTD_ KnxManufacturer = 257 KnxManufacturer_M_FU_CHENG_INTELLIGENCE KnxManufacturer = 258 KnxManufacturer_M_NEXKON KnxManufacturer = 259 KnxManufacturer_M_FEEL_S_R_L KnxManufacturer = 260 KnxManufacturer_M_NOT_ASSIGNED_314 KnxManufacturer = 261 KnxManufacturer_M_SHENZHEN_FANHAI_SANJIANG_ELECTRONICS_CO___LTD_ KnxManufacturer = 262 KnxManufacturer_M_JIUZHOU_GREEBLE KnxManufacturer = 263 KnxManufacturer_M_AUMUELLER_AUMATIC_GMBH KnxManufacturer = 264 KnxManufacturer_M_ETMAN_ELECTRIC KnxManufacturer = 265 KnxManufacturer_M_BLACK_NOVA KnxManufacturer = 266 KnxManufacturer_M_ZIDATECH_AG KnxManufacturer = 267 KnxManufacturer_M_IDGS_BVBA KnxManufacturer = 268 KnxManufacturer_M_DAKANIMO KnxManufacturer = 269 KnxManufacturer_M_TREBOR_AUTOMATION_AB KnxManufacturer = 270 KnxManufacturer_M_SATEL_SP__Z_O_O_ KnxManufacturer = 271 KnxManufacturer_M_RUSSOUND__INC_ KnxManufacturer = 272 KnxManufacturer_M_MIDEA_HEATING_AND_VENTILATING_EQUIPMENT_CO_LTD KnxManufacturer = 273 KnxManufacturer_M_CONSORZIO_TERRANUOVA KnxManufacturer = 274 KnxManufacturer_M_WOLF_HEIZTECHNIK_GMBH KnxManufacturer = 275 KnxManufacturer_M_SONTEC KnxManufacturer = 276 KnxManufacturer_M_BELCOM_CABLES_LTD_ KnxManufacturer = 277 KnxManufacturer_M_GUANGZHOU_SEAWIN_ELECTRICAL_TECHNOLOGIES_CO___LTD_ KnxManufacturer = 278 KnxManufacturer_M_ACREL KnxManufacturer = 279 KnxManufacturer_M_FRANKE_AQUAROTTER_GMBH KnxManufacturer = 280 KnxManufacturer_M_ORION_SYSTEMS KnxManufacturer = 281 KnxManufacturer_M_SCHRACK_TECHNIK_GMBH KnxManufacturer = 282 KnxManufacturer_M_INSPRID KnxManufacturer = 283 KnxManufacturer_M_SUNRICHER KnxManufacturer = 284 KnxManufacturer_M_MENRED_AUTOMATION_SYSTEMSHANGHAI_CO__LTD_ KnxManufacturer = 285 KnxManufacturer_M_AUREX KnxManufacturer = 286 KnxManufacturer_M_JOSEF_BARTHELME_GMBH_AND_CO__KG KnxManufacturer = 287 KnxManufacturer_M_ARCHITECTURE_NUMERIQUE KnxManufacturer = 288 KnxManufacturer_M_UP_GROUP KnxManufacturer = 289 KnxManufacturer_M_TEKNOS_AVINNO KnxManufacturer = 290 KnxManufacturer_M_NINGBO_DOOYA_MECHANIC_AND_ELECTRONIC_TECHNOLOGY KnxManufacturer = 291 KnxManufacturer_M_THERMOKON_SENSORTECHNIK_GMBH KnxManufacturer = 292 KnxManufacturer_M_BELIMO_AUTOMATION_AG KnxManufacturer = 293 KnxManufacturer_M_ZEHNDER_GROUP_INTERNATIONAL_AG KnxManufacturer = 294 KnxManufacturer_M_SKS_KINKEL_ELEKTRONIK KnxManufacturer = 295 KnxManufacturer_M_ECE_WURMITZER_GMBH KnxManufacturer = 296 KnxManufacturer_M_LARS KnxManufacturer = 297 KnxManufacturer_M_URC KnxManufacturer = 298 KnxManufacturer_M_LIGHTCONTROL KnxManufacturer = 299 KnxManufacturer_M_SHENZHEN_YM KnxManufacturer = 300 KnxManufacturer_M_MEAN_WELL_ENTERPRISES_CO__LTD_ KnxManufacturer = 301 KnxManufacturer_M_OSIX KnxManufacturer = 302 KnxManufacturer_M_AYPRO_TECHNOLOGY KnxManufacturer = 303 KnxManufacturer_M_HEFEI_ECOLITE_SOFTWARE KnxManufacturer = 304 KnxManufacturer_M_ENNO KnxManufacturer = 305 KnxManufacturer_M_OHOSURE KnxManufacturer = 306 KnxManufacturer_M_GAREFOWL KnxManufacturer = 307 KnxManufacturer_M_GEZE KnxManufacturer = 308 KnxManufacturer_M_LG_ELECTRONICS_INC_ KnxManufacturer = 309 KnxManufacturer_M_SMC_INTERIORS KnxManufacturer = 310 KnxManufacturer_M_NOT_ASSIGNED_364 KnxManufacturer = 311 KnxManufacturer_M_SCS_CABLE KnxManufacturer = 312 KnxManufacturer_M_HOVAL KnxManufacturer = 313 KnxManufacturer_M_CANST KnxManufacturer = 314 KnxManufacturer_M_HANGZHOU_BERLIN KnxManufacturer = 315 KnxManufacturer_M_EVN_LICHTTECHNIK KnxManufacturer = 316 KnxManufacturer_M_RUTEC KnxManufacturer = 317 KnxManufacturer_M_FINDER KnxManufacturer = 318 KnxManufacturer_M_FUJITSU_GENERAL_LIMITED KnxManufacturer = 319 KnxManufacturer_M_ZF_FRIEDRICHSHAFEN_AG KnxManufacturer = 320 KnxManufacturer_M_CREALED KnxManufacturer = 321 KnxManufacturer_M_MILES_MAGIC_AUTOMATION_PRIVATE_LIMITED KnxManufacturer = 322 KnxManufacturer_M_EPlus KnxManufacturer = 323 KnxManufacturer_M_ITALCOND KnxManufacturer = 324 KnxManufacturer_M_SATION KnxManufacturer = 325 KnxManufacturer_M_NEWBEST KnxManufacturer = 326 KnxManufacturer_M_GDS_DIGITAL_SYSTEMS KnxManufacturer = 327 KnxManufacturer_M_IDDERO KnxManufacturer = 328 KnxManufacturer_M_MBNLED KnxManufacturer = 329 KnxManufacturer_M_VITRUM KnxManufacturer = 330 KnxManufacturer_M_EKEY_BIOMETRIC_SYSTEMS_GMBH KnxManufacturer = 331 KnxManufacturer_M_AMC KnxManufacturer = 332 KnxManufacturer_M_TRILUX_GMBH_AND_CO__KG KnxManufacturer = 333 KnxManufacturer_M_WEXCEDO KnxManufacturer = 334 KnxManufacturer_M_VEMER_SPA KnxManufacturer = 335 KnxManufacturer_M_ALEXANDER_BUERKLE_GMBH_AND_CO_KG KnxManufacturer = 336 KnxManufacturer_M_CITRON KnxManufacturer = 337 KnxManufacturer_M_SHENZHEN_HEGUANG KnxManufacturer = 338 KnxManufacturer_M_NOT_ASSIGNED_392 KnxManufacturer = 339 KnxManufacturer_M_TRANE_B_V_B_A KnxManufacturer = 340 KnxManufacturer_M_CAREL KnxManufacturer = 341 KnxManufacturer_M_PROLITE_CONTROLS KnxManufacturer = 342 KnxManufacturer_M_BOSMER KnxManufacturer = 343 KnxManufacturer_M_EUCHIPS KnxManufacturer = 344 KnxManufacturer_M_CONNECT_THINKA_CONNECT KnxManufacturer = 345 KnxManufacturer_M_PEAKNX_A_DOGAWIST_COMPANY KnxManufacturer = 346 KnxManufacturer_M_ACEMATIC KnxManufacturer = 347 KnxManufacturer_M_ELAUSYS KnxManufacturer = 348 KnxManufacturer_M_ITK_ENGINEERING_AG KnxManufacturer = 349 KnxManufacturer_M_INTEGRA_METERING_AG KnxManufacturer = 350 KnxManufacturer_M_FMS_HOSPITALITY_PTE_LTD KnxManufacturer = 351 KnxManufacturer_M_NUVO KnxManufacturer = 352 KnxManufacturer_M_U__LUX_GMBH KnxManufacturer = 353 KnxManufacturer_M_BRUMBERG_LEUCHTEN KnxManufacturer = 354 KnxManufacturer_M_LIME KnxManufacturer = 355 KnxManufacturer_M_GREAT_EMPIRE_INTERNATIONAL_GROUP_CO___LTD_ KnxManufacturer = 356 KnxManufacturer_M_KAVOSHPISHRO_ASIA KnxManufacturer = 357 KnxManufacturer_M_V2_SPA KnxManufacturer = 358 KnxManufacturer_M_JOHNSON_CONTROLS KnxManufacturer = 359 KnxManufacturer_M_ARKUD KnxManufacturer = 360 KnxManufacturer_M_IRIDIUM_LTD_ KnxManufacturer = 361 KnxManufacturer_M_BSMART KnxManufacturer = 362 KnxManufacturer_M_BAB_TECHNOLOGIE_GMBH KnxManufacturer = 363 KnxManufacturer_M_NICE_SPA KnxManufacturer = 364 KnxManufacturer_M_REDFISH_GROUP_PTY_LTD KnxManufacturer = 365 KnxManufacturer_M_SABIANA_SPA KnxManufacturer = 366 KnxManufacturer_M_UBEE_INTERACTIVE_EUROPE KnxManufacturer = 367 KnxManufacturer_M_REXEL KnxManufacturer = 368 KnxManufacturer_M_GES_TEKNIK_A_S_ KnxManufacturer = 369 KnxManufacturer_M_AVE_S_P_A_ KnxManufacturer = 370 KnxManufacturer_M_ZHUHAI_LTECH_TECHNOLOGY_CO___LTD_ KnxManufacturer = 371 KnxManufacturer_M_ARCOM KnxManufacturer = 372 KnxManufacturer_M_VIA_TECHNOLOGIES__INC_ KnxManufacturer = 373 KnxManufacturer_M_FEELSMART_ KnxManufacturer = 374 KnxManufacturer_M_SUPCON KnxManufacturer = 375 KnxManufacturer_M_MANIC KnxManufacturer = 376 KnxManufacturer_M_TDE_GMBH KnxManufacturer = 377 KnxManufacturer_M_NANJING_SHUFAN_INFORMATION_TECHNOLOGY_CO__LTD_ KnxManufacturer = 378 KnxManufacturer_M_EWTECH KnxManufacturer = 379 KnxManufacturer_M_KLUGER_AUTOMATION_GMBH KnxManufacturer = 380 KnxManufacturer_M_JOONGANG_CONTROL KnxManufacturer = 381 KnxManufacturer_M_GREENCONTROLS_TECHNOLOGY_SDN__BHD_ KnxManufacturer = 382 KnxManufacturer_M_IME_S_P_A_ KnxManufacturer = 383 KnxManufacturer_M_SICHUAN_HAODING KnxManufacturer = 384 KnxManufacturer_M_MINDJAGA_LTD_ KnxManufacturer = 385 KnxManufacturer_M_RUILI_SMART_CONTROL KnxManufacturer = 386 KnxManufacturer_M_CODESYS_GMBH KnxManufacturer = 387 KnxManufacturer_M_MOORGEN_DEUTSCHLAND_GMBH KnxManufacturer = 388 KnxManufacturer_M_CULLMANN_TECH KnxManufacturer = 389 KnxManufacturer_M_MERCK_WINDOW_TECHNOLOGIES_B_V_ KnxManufacturer = 390 KnxManufacturer_M_ABEGO KnxManufacturer = 391 KnxManufacturer_M_MYGEKKO KnxManufacturer = 392 KnxManufacturer_M_ERGO3_SARL KnxManufacturer = 393 KnxManufacturer_M_STMICROELECTRONICS_INTERNATIONAL_N_V_ KnxManufacturer = 394 KnxManufacturer_M_CJC_SYSTEMS KnxManufacturer = 395 KnxManufacturer_M_SUDOKU KnxManufacturer = 396 KnxManufacturer_M_AZ_E_LITE_PTE_LTD KnxManufacturer = 397 KnxManufacturer_M_ARLIGHT KnxManufacturer = 398 KnxManufacturer_M_GRUENBECK_WASSERAUFBEREITUNG_GMBH KnxManufacturer = 399 KnxManufacturer_M_MODULE_ELECTRONIC KnxManufacturer = 400 KnxManufacturer_M_KOPLAT KnxManufacturer = 401 KnxManufacturer_M_GUANGZHOU_LETOUR_LIFE_TECHNOLOGY_CO___LTD KnxManufacturer = 402 KnxManufacturer_M_ILEVIA KnxManufacturer = 403 KnxManufacturer_M_LN_SYSTEMTEQ KnxManufacturer = 404 KnxManufacturer_M_HISENSE_SMARTHOME KnxManufacturer = 405 KnxManufacturer_M_FLINK_AUTOMATION_SYSTEM KnxManufacturer = 406 KnxManufacturer_M_XXTER_BV KnxManufacturer = 407 KnxManufacturer_M_LYNXUS_TECHNOLOGY KnxManufacturer = 408 KnxManufacturer_M_ROBOT_S_A_ KnxManufacturer = 409 KnxManufacturer_M_SHENZHEN_ATTE_SMART_LIFE_CO__LTD_ KnxManufacturer = 410 KnxManufacturer_M_NOBLESSE KnxManufacturer = 411 KnxManufacturer_M_ADVANCED_DEVICES KnxManufacturer = 412 KnxManufacturer_M_ATRINA_BUILDING_AUTOMATION_CO__LTD KnxManufacturer = 413 KnxManufacturer_M_GUANGDONG_DAMING_LAFFEY_ELECTRIC_CO___LTD_ KnxManufacturer = 414 KnxManufacturer_M_WESTERSTRAND_URFABRIK_AB KnxManufacturer = 415 KnxManufacturer_M_CONTROL4_CORPORATE KnxManufacturer = 416 KnxManufacturer_M_ONTROL KnxManufacturer = 417 KnxManufacturer_M_STARNET KnxManufacturer = 418 KnxManufacturer_M_BETA_CAVI KnxManufacturer = 419 KnxManufacturer_M_EASEMORE KnxManufacturer = 420 KnxManufacturer_M_VIVALDI_SRL KnxManufacturer = 421 KnxManufacturer_M_GREE_ELECTRIC_APPLIANCES_INC__OF_ZHUHAI KnxManufacturer = 422 KnxManufacturer_M_HWISCON KnxManufacturer = 423 KnxManufacturer_M_SHANGHAI_ELECON_INTELLIGENT_TECHNOLOGY_CO___LTD_ KnxManufacturer = 424 KnxManufacturer_M_KAMPMANN KnxManufacturer = 425 KnxManufacturer_M_IMPOLUX_GMBH_LEDIMAX KnxManufacturer = 426 KnxManufacturer_M_EVAUX KnxManufacturer = 427 KnxManufacturer_M_WEBRO_CABLES_AND_CONNECTORS_LIMITED KnxManufacturer = 428 KnxManufacturer_M_SHANGHAI_E_TECH_SOLUTION KnxManufacturer = 429 KnxManufacturer_M_GUANGZHOU_HOKO_ELECTRIC_CO__LTD_ KnxManufacturer = 430 KnxManufacturer_M_LAMMIN_HIGH_TECH_CO__LTD KnxManufacturer = 431 KnxManufacturer_M_SHENZHEN_MERRYTEK_TECHNOLOGY_CO___LTD KnxManufacturer = 432 KnxManufacturer_M_I_LUXUS KnxManufacturer = 433 KnxManufacturer_M_ELMOS_SEMICONDUCTOR_AG KnxManufacturer = 434 KnxManufacturer_M_EMCOM_TECHNOLOGY_INC KnxManufacturer = 435 KnxManufacturer_M_PROJECT_INNOVATIONS_GMBH KnxManufacturer = 436 KnxManufacturer_M_ITC KnxManufacturer = 437 KnxManufacturer_M_ABB_LV_INSTALLATION_MATERIALS_COMPANY_LTD__BEIJING KnxManufacturer = 438 KnxManufacturer_M_MAICO KnxManufacturer = 439 KnxManufacturer_M_ELAN_SRL KnxManufacturer = 440 KnxManufacturer_M_MINHHA_TECHNOLOGY_CO__LTD KnxManufacturer = 441 KnxManufacturer_M_ZHEJIANG_TIANJIE_INDUSTRIAL_CORP_ KnxManufacturer = 442 KnxManufacturer_M_IAUTOMATION_PTY_LIMITED KnxManufacturer = 443 KnxManufacturer_M_EXTRON KnxManufacturer = 444 KnxManufacturer_M_FREEDOMPRO KnxManufacturer = 445 KnxManufacturer_M_ONEHOME KnxManufacturer = 446 KnxManufacturer_M_EOS_SAUNATECHNIK_GMBH KnxManufacturer = 447 KnxManufacturer_M_KUSATEK_GMBH KnxManufacturer = 448 KnxManufacturer_M_EISBAER_SCADA KnxManufacturer = 449 KnxManufacturer_M_AUTOMATISMI_BENINCA_S_P_A_ KnxManufacturer = 450 KnxManufacturer_M_BLENDOM KnxManufacturer = 451 KnxManufacturer_M_MADEL_AIR_TECHNICAL_DIFFUSION KnxManufacturer = 452 KnxManufacturer_M_NIKO KnxManufacturer = 453 KnxManufacturer_M_BOSCH_REXROTH_AG KnxManufacturer = 454 KnxManufacturer_M_CANDM_PRODUCTS KnxManufacturer = 455 KnxManufacturer_M_HOERMANN_KG_VERKAUFSGESELLSCHAFT KnxManufacturer = 456 KnxManufacturer_M_SHANGHAI_RAJAYASA_CO__LTD KnxManufacturer = 457 KnxManufacturer_M_SUZUKI KnxManufacturer = 458 KnxManufacturer_M_SILENT_GLISS_INTERNATIONAL_LTD_ KnxManufacturer = 459 KnxManufacturer_M_BEE_CONTROLS_ADGSC_GROUP KnxManufacturer = 460 KnxManufacturer_M_XDTECGMBH KnxManufacturer = 461 KnxManufacturer_M_OSRAM KnxManufacturer = 462 KnxManufacturer_M_LEBENOR KnxManufacturer = 463 KnxManufacturer_M_AUTOMANENG KnxManufacturer = 464 KnxManufacturer_M_HONEYWELL_AUTOMATION_SOLUTION_CONTROLCHINA KnxManufacturer = 465 KnxManufacturer_M_HANGZHOU_BINTHEN_INTELLIGENCE_TECHNOLOGY_CO__LTD KnxManufacturer = 466 KnxManufacturer_M_ETA_HEIZTECHNIK KnxManufacturer = 467 KnxManufacturer_M_DIVUS_GMBH KnxManufacturer = 468 KnxManufacturer_M_NANJING_TAIJIESAI_INTELLIGENT_TECHNOLOGY_CO__LTD_ KnxManufacturer = 469 KnxManufacturer_M_LUNATONE KnxManufacturer = 470 KnxManufacturer_M_ZHEJIANG_SCTECH_BUILDING_INTELLIGENT KnxManufacturer = 471 KnxManufacturer_M_FOSHAN_QITE_TECHNOLOGY_CO___LTD_ KnxManufacturer = 472 KnxManufacturer_M_NOKE KnxManufacturer = 473 KnxManufacturer_M_LANDCOM KnxManufacturer = 474 KnxManufacturer_M_STORK_AS KnxManufacturer = 475 KnxManufacturer_M_HANGZHOU_SHENDU_TECHNOLOGY_CO___LTD_ KnxManufacturer = 476 KnxManufacturer_M_COOLAUTOMATION KnxManufacturer = 477 KnxManufacturer_M_APRSTERN KnxManufacturer = 478 KnxManufacturer_M_SONNEN KnxManufacturer = 479 KnxManufacturer_M_DNAKE KnxManufacturer = 480 KnxManufacturer_M_NEUBERGER_GEBAEUDEAUTOMATION_GMBH KnxManufacturer = 481 KnxManufacturer_M_STILIGER KnxManufacturer = 482 KnxManufacturer_M_BERGHOF_AUTOMATION_GMBH KnxManufacturer = 483 KnxManufacturer_M_TOTAL_AUTOMATION_AND_CONTROLS_GMBH KnxManufacturer = 484 KnxManufacturer_M_DOVIT KnxManufacturer = 485 KnxManufacturer_M_INSTALIGHTING_GMBH KnxManufacturer = 486 KnxManufacturer_M_UNI_TEC KnxManufacturer = 487 KnxManufacturer_M_CASATUNES KnxManufacturer = 488 KnxManufacturer_M_EMT KnxManufacturer = 489 KnxManufacturer_M_SENFFICIENT KnxManufacturer = 490 KnxManufacturer_M_AUROLITE_ELECTRICAL_PANYU_GUANGZHOU_LIMITED KnxManufacturer = 491 KnxManufacturer_M_ABB_XIAMEN_SMART_TECHNOLOGY_CO___LTD_ KnxManufacturer = 492 KnxManufacturer_M_SAMSON_ELECTRIC_WIRE KnxManufacturer = 493 KnxManufacturer_M_T_TOUCHING KnxManufacturer = 494 KnxManufacturer_M_CORE_SMART_HOME KnxManufacturer = 495 KnxManufacturer_M_GREENCONNECT_SOLUTIONS_SA KnxManufacturer = 496 KnxManufacturer_M_ELETTRONICA_CONDUTTORI KnxManufacturer = 497 KnxManufacturer_M_MKFC KnxManufacturer = 498 KnxManufacturer_M_AUTOMATIONPlus KnxManufacturer = 499 KnxManufacturer_M_BLUE_AND_RED KnxManufacturer = 500 KnxManufacturer_M_FROGBLUE KnxManufacturer = 501 KnxManufacturer_M_SAVESOR KnxManufacturer = 502 KnxManufacturer_M_APP_TECH KnxManufacturer = 503 KnxManufacturer_M_SENSORTEC_AG KnxManufacturer = 504 KnxManufacturer_M_NYSA_TECHNOLOGY_AND_SOLUTIONS KnxManufacturer = 505 KnxManufacturer_M_FARADITE KnxManufacturer = 506 KnxManufacturer_M_OPTIMUS KnxManufacturer = 507 KnxManufacturer_M_KTS_S_R_L_ KnxManufacturer = 508 KnxManufacturer_M_RAMCRO_SPA KnxManufacturer = 509 KnxManufacturer_M_WUHAN_WISECREATE_UNIVERSE_TECHNOLOGY_CO___LTD KnxManufacturer = 510 KnxManufacturer_M_BEMI_SMART_HOME_LTD KnxManufacturer = 511 KnxManufacturer_M_ARDOMUS KnxManufacturer = 512 KnxManufacturer_M_CHANGXING KnxManufacturer = 513 KnxManufacturer_M_E_CONTROLS KnxManufacturer = 514 KnxManufacturer_M_AIB_TECHNOLOGY KnxManufacturer = 515 KnxManufacturer_M_NVC KnxManufacturer = 516 KnxManufacturer_M_KBOX KnxManufacturer = 517 KnxManufacturer_M_CNS KnxManufacturer = 518 KnxManufacturer_M_TYBA KnxManufacturer = 519 KnxManufacturer_M_ATREL KnxManufacturer = 520 KnxManufacturer_M_SIMON_ELECTRIC_CHINA_CO___LTD KnxManufacturer = 521 KnxManufacturer_M_KORDZ_GROUP KnxManufacturer = 522 KnxManufacturer_M_ND_ELECTRIC KnxManufacturer = 523 KnxManufacturer_M_CONTROLIUM KnxManufacturer = 524 KnxManufacturer_M_FAMO_GMBH_AND_CO__KG KnxManufacturer = 525 KnxManufacturer_M_CDN_SMART KnxManufacturer = 526 KnxManufacturer_M_HESTON KnxManufacturer = 527 KnxManufacturer_M_ESLA_CONEXIONES_S_L_ KnxManufacturer = 528 KnxManufacturer_M_WEISHAUPT KnxManufacturer = 529 KnxManufacturer_M_ASTRUM_TECHNOLOGY KnxManufacturer = 530 KnxManufacturer_M_WUERTH_ELEKTRONIK_STELVIO_KONTEK_S_P_A_ KnxManufacturer = 531 KnxManufacturer_M_NANOTECO_CORPORATION KnxManufacturer = 532 KnxManufacturer_M_NIETIAN KnxManufacturer = 533 KnxManufacturer_M_SUMSIR KnxManufacturer = 534 KnxManufacturer_M_ORBIS_TECNOLOGIA_ELECTRICA_SA KnxManufacturer = 535 KnxManufacturer_M_NANJING_ZHONGYI_IOT_TECHNOLOGY_CO___LTD_ KnxManufacturer = 536 KnxManufacturer_M_ANLIPS KnxManufacturer = 537 KnxManufacturer_M_GUANGDONG_PAK_CORPORATION_CO___LTD KnxManufacturer = 538 KnxManufacturer_M_BVK_TECHNOLOGY KnxManufacturer = 539 KnxManufacturer_M_SOLOMIO_SRL KnxManufacturer = 540 KnxManufacturer_M_DOMOTICA_LABS KnxManufacturer = 541 KnxManufacturer_M_NVC_INTERNATIONAL KnxManufacturer = 542 KnxManufacturer_M_BA KnxManufacturer = 543 KnxManufacturer_M_IRIS_CERAMICA_GROUP KnxManufacturer = 544 KnxManufacturer_M_WIREEO KnxManufacturer = 545 KnxManufacturer_M_NVCLIGHTING KnxManufacturer = 546 KnxManufacturer_M_JINAN_TIAN_DA_SHENG_INFORMATION_TECHNOLOGY_CO_ KnxManufacturer = 547 KnxManufacturer_M_ARMITI_TRADING KnxManufacturer = 548 KnxManufacturer_M_ELEK KnxManufacturer = 549 KnxManufacturer_M_ACCORDIA_SA KnxManufacturer = 550 KnxManufacturer_M_OURICAN KnxManufacturer = 551 KnxManufacturer_M_INLIWOSE KnxManufacturer = 552 KnxManufacturer_M_BOSCH_SHANGHAI_SMART_LIFE_TECHNOLOGY_LTD_ KnxManufacturer = 553 KnxManufacturer_M_SHK_KNX KnxManufacturer = 554 KnxManufacturer_M_AMPIO KnxManufacturer = 555 KnxManufacturer_M_MINGXING_WISDOM KnxManufacturer = 556 KnxManufacturer_M_ALTEN_SW_GMBH KnxManufacturer = 557 KnxManufacturer_M_ABB___RESERVED KnxManufacturer = 558 KnxManufacturer_M_BUSCH_JAEGER_ELEKTRO___RESERVED KnxManufacturer = 559 ) var KnxManufacturerValues []KnxManufacturer func init() { _ = errors.New KnxManufacturerValues = []KnxManufacturer{ KnxManufacturer_M_UNKNOWN, KnxManufacturer_M_SIEMENS, KnxManufacturer_M_ABB, KnxManufacturer_M_ALBRECHT_JUNG, KnxManufacturer_M_BTICINO, KnxManufacturer_M_BERKER, KnxManufacturer_M_BUSCH_JAEGER_ELEKTRO, KnxManufacturer_M_GIRA_GIERSIEPEN, KnxManufacturer_M_HAGER_ELECTRO, KnxManufacturer_M_INSTA_GMBH, KnxManufacturer_M_LEGRAND_APPAREILLAGE_ELECTRIQUE, KnxManufacturer_M_MERTEN, KnxManufacturer_M_ABB_SPA_SACE_DIVISION, KnxManufacturer_M_SIEDLE_AND_SOEHNE, KnxManufacturer_M_EBERLE, KnxManufacturer_M_GEWISS, KnxManufacturer_M_ALBERT_ACKERMANN, KnxManufacturer_M_SCHUPA_GMBH, KnxManufacturer_M_ABB_SCHWEIZ, KnxManufacturer_M_FELLER, KnxManufacturer_M_GLAMOX_AS, KnxManufacturer_M_DEHN_AND_SOEHNE, KnxManufacturer_M_CRABTREE, KnxManufacturer_M_EVOKNX, KnxManufacturer_M_PAUL_HOCHKOEPPER, KnxManufacturer_M_ALTENBURGER_ELECTRONIC, KnxManufacturer_M_GRAESSLIN, KnxManufacturer_M_SIMON_42, KnxManufacturer_M_VIMAR, KnxManufacturer_M_MOELLER_GEBAEUDEAUTOMATION_KG, KnxManufacturer_M_ELTAKO, KnxManufacturer_M_BOSCH_SIEMENS_HAUSHALTSGERAETE, KnxManufacturer_M_RITTO_GMBHANDCO_KG, KnxManufacturer_M_POWER_CONTROLS, KnxManufacturer_M_ZUMTOBEL, KnxManufacturer_M_PHOENIX_CONTACT, KnxManufacturer_M_WAGO_KONTAKTTECHNIK, KnxManufacturer_M_KNXPRESSO, KnxManufacturer_M_WIELAND_ELECTRIC, KnxManufacturer_M_HERMANN_KLEINHUIS, KnxManufacturer_M_STIEBEL_ELTRON, KnxManufacturer_M_TEHALIT, KnxManufacturer_M_THEBEN_AG, KnxManufacturer_M_WILHELM_RUTENBECK, KnxManufacturer_M_WINKHAUS, KnxManufacturer_M_ROBERT_BOSCH, KnxManufacturer_M_SOMFY, KnxManufacturer_M_WOERTZ, KnxManufacturer_M_VIESSMANN_WERKE, KnxManufacturer_M_IMI_HYDRONIC_ENGINEERING, KnxManufacturer_M_JOH__VAILLANT, KnxManufacturer_M_AMP_DEUTSCHLAND, KnxManufacturer_M_BOSCH_THERMOTECHNIK_GMBH, KnxManufacturer_M_SEF___ECOTEC, KnxManufacturer_M_DORMA_GMBH_Plus_CO__KG, KnxManufacturer_M_WINDOWMASTER_AS, KnxManufacturer_M_WALTHER_WERKE, KnxManufacturer_M_ORAS, KnxManufacturer_M_DAETWYLER, KnxManufacturer_M_ELECTRAK, KnxManufacturer_M_TECHEM, KnxManufacturer_M_SCHNEIDER_ELECTRIC_INDUSTRIES_SAS, KnxManufacturer_M_WHD_WILHELM_HUBER_Plus_SOEHNE, KnxManufacturer_M_BISCHOFF_ELEKTRONIK, KnxManufacturer_M_JEPAZ, KnxManufacturer_M_RTS_AUTOMATION, KnxManufacturer_M_EIBMARKT_GMBH, KnxManufacturer_M_WAREMA_RENKHOFF_SE, KnxManufacturer_M_EELECTRON, KnxManufacturer_M_BELDEN_WIRE_AND_CABLE_B_V_, KnxManufacturer_M_BECKER_ANTRIEBE_GMBH, KnxManufacturer_M_J_STEHLEPlusSOEHNE_GMBH, KnxManufacturer_M_AGFEO, KnxManufacturer_M_ZENNIO, KnxManufacturer_M_TAPKO_TECHNOLOGIES, KnxManufacturer_M_HDL, KnxManufacturer_M_UPONOR, KnxManufacturer_M_SE_LIGHTMANAGEMENT_AG, KnxManufacturer_M_ARCUS_EDS, KnxManufacturer_M_INTESIS, KnxManufacturer_M_HERHOLDT_CONTROLS_SRL, KnxManufacturer_M_NIKO_ZUBLIN, KnxManufacturer_M_DURABLE_TECHNOLOGIES, KnxManufacturer_M_INNOTEAM, KnxManufacturer_M_ISE_GMBH, KnxManufacturer_M_TEAM_FOR_TRONICS, KnxManufacturer_M_CIAT, KnxManufacturer_M_REMEHA_BV, KnxManufacturer_M_ESYLUX, KnxManufacturer_M_BASALTE, KnxManufacturer_M_VESTAMATIC, KnxManufacturer_M_MDT_TECHNOLOGIES, KnxManufacturer_M_WARENDORFER_KUECHEN_GMBH, KnxManufacturer_M_VIDEO_STAR, KnxManufacturer_M_SITEK, KnxManufacturer_M_CONTROLTRONIC, KnxManufacturer_M_FUNCTION_TECHNOLOGY, KnxManufacturer_M_AMX, KnxManufacturer_M_ELDAT, KnxManufacturer_M_PANASONIC, KnxManufacturer_M_PULSE_TECHNOLOGIES, KnxManufacturer_M_CRESTRON, KnxManufacturer_M_STEINEL_PROFESSIONAL, KnxManufacturer_M_BILTON_LED_LIGHTING, KnxManufacturer_M_DENRO_AG, KnxManufacturer_M_GEPRO, KnxManufacturer_M_PREUSSEN_AUTOMATION, KnxManufacturer_M_ZOPPAS_INDUSTRIES, KnxManufacturer_M_MACTECH, KnxManufacturer_M_TECHNO_TREND, KnxManufacturer_M_FS_CABLES, KnxManufacturer_M_DELTA_DORE, KnxManufacturer_M_EISSOUND, KnxManufacturer_M_CISCO, KnxManufacturer_M_DINUY, KnxManufacturer_M_IKNIX, KnxManufacturer_M_RADEMACHER_GERAETE_ELEKTRONIK_GMBH, KnxManufacturer_M_EGI_ELECTROACUSTICA_GENERAL_IBERICA, KnxManufacturer_M_BES___INGENIUM, KnxManufacturer_M_ELABNET, KnxManufacturer_M_BLUMOTIX, KnxManufacturer_M_HUNTER_DOUGLAS, KnxManufacturer_M_APRICUM, KnxManufacturer_M_TIANSU_AUTOMATION, KnxManufacturer_M_BUBENDORFF, KnxManufacturer_M_MBS_GMBH, KnxManufacturer_M_ENERTEX_BAYERN_GMBH, KnxManufacturer_M_BMS, KnxManufacturer_M_SINAPSI, KnxManufacturer_M_EMBEDDED_SYSTEMS_SIA, KnxManufacturer_M_KNX1, KnxManufacturer_M_TOKKA, KnxManufacturer_M_NANOSENSE, KnxManufacturer_M_PEAR_AUTOMATION_GMBH, KnxManufacturer_M_DGA, KnxManufacturer_M_LUTRON, KnxManufacturer_M_AIRZONE___ALTRA, KnxManufacturer_M_LITHOSS_DESIGN_SWITCHES, KnxManufacturer_M_THREEATEL, KnxManufacturer_M_PHILIPS_CONTROLS, KnxManufacturer_M_VELUX_AS, KnxManufacturer_M_LOYTEC, KnxManufacturer_M_EKINEX_S_P_A_, KnxManufacturer_M_SIRLAN_TECHNOLOGIES, KnxManufacturer_M_PROKNX_SAS, KnxManufacturer_M_IT_GMBH, KnxManufacturer_M_RENSON, KnxManufacturer_M_HEP_GROUP, KnxManufacturer_M_BALMART, KnxManufacturer_M_GFS_GMBH, KnxManufacturer_M_SCHENKER_STOREN_AG, KnxManufacturer_M_ALGODUE_ELETTRONICA_S_R_L_, KnxManufacturer_M_ABB_FRANCE, KnxManufacturer_M_MAINTRONIC, KnxManufacturer_M_VANTAGE, KnxManufacturer_M_FORESIS, KnxManufacturer_M_RESEARCH_AND_PRODUCTION_ASSOCIATION_SEM, KnxManufacturer_M_WEINZIERL_ENGINEERING_GMBH, KnxManufacturer_M_MOEHLENHOFF_WAERMETECHNIK_GMBH, KnxManufacturer_M_PKC_GROUP_OYJ, KnxManufacturer_M_B_E_G_, KnxManufacturer_M_ELSNER_ELEKTRONIK_GMBH, KnxManufacturer_M_SIEMENS_BUILDING_TECHNOLOGIES_HKCHINA_LTD_, KnxManufacturer_M_EUTRAC, KnxManufacturer_M_GUSTAV_HENSEL_GMBH_AND_CO__KG, KnxManufacturer_M_GARO_AB, KnxManufacturer_M_WALDMANN_LICHTTECHNIK, KnxManufacturer_M_SCHUECO, KnxManufacturer_M_EMU, KnxManufacturer_M_JNET_SYSTEMS_AG, KnxManufacturer_M_TOTAL_SOLUTION_GMBH, KnxManufacturer_M_O_Y_L__ELECTRONICS, KnxManufacturer_M_GALAX_SYSTEM, KnxManufacturer_M_DISCH, KnxManufacturer_M_AUCOTEAM, KnxManufacturer_M_LUXMATE_CONTROLS, KnxManufacturer_M_DANFOSS, KnxManufacturer_M_AST_GMBH, KnxManufacturer_M_WILA_LEUCHTEN, KnxManufacturer_M_BPlusB_AUTOMATIONS__UND_STEUERUNGSTECHNIK, KnxManufacturer_M_LINGG_AND_JANKE, KnxManufacturer_M_SAUTER, KnxManufacturer_M_SIMU, KnxManufacturer_M_THEBEN_HTS_AG, KnxManufacturer_M_AMANN_GMBH, KnxManufacturer_M_BERG_ENERGIEKONTROLLSYSTEME_GMBH, KnxManufacturer_M_HUEPPE_FORM_SONNENSCHUTZSYSTEME_GMBH, KnxManufacturer_M_OVENTROP_KG, KnxManufacturer_M_GRIESSER_AG, KnxManufacturer_M_IPAS_GMBH, KnxManufacturer_M_ELERO_GMBH, KnxManufacturer_M_ARDAN_PRODUCTION_AND_INDUSTRIAL_CONTROLS_LTD_, KnxManufacturer_M_METEC_MESSTECHNIK_GMBH, KnxManufacturer_M_ELKA_ELEKTRONIK_GMBH, KnxManufacturer_M_ELEKTROANLAGEN_D__NAGEL, KnxManufacturer_M_TRIDONIC_BAUELEMENTE_GMBH, KnxManufacturer_M_STENGLER_GESELLSCHAFT, KnxManufacturer_M_SCHNEIDER_ELECTRIC_MG, KnxManufacturer_M_KNX_ASSOCIATION, KnxManufacturer_M_VIVO, KnxManufacturer_M_HUGO_MUELLER_GMBH_AND_CO_KG, KnxManufacturer_M_SIEMENS_HVAC, KnxManufacturer_M_APT, KnxManufacturer_M_HIGHDOM, KnxManufacturer_M_TOP_SERVICES, KnxManufacturer_M_AMBIHOME, KnxManufacturer_M_DATEC_ELECTRONIC_AG, KnxManufacturer_M_ABUS_SECURITY_CENTER, KnxManufacturer_M_LITE_PUTER, KnxManufacturer_M_TANTRON_ELECTRONIC, KnxManufacturer_M_INTERRA, KnxManufacturer_M_DKX_TECH, KnxManufacturer_M_VIATRON, KnxManufacturer_M_NAUTIBUS, KnxManufacturer_M_ON_SEMICONDUCTOR, KnxManufacturer_M_LONGCHUANG, KnxManufacturer_M_AIR_ON_AG, KnxManufacturer_M_IB_COMPANY_GMBH, KnxManufacturer_M_SATION_FACTORY, KnxManufacturer_M_AGENTILO_GMBH, KnxManufacturer_M_MAKEL_ELEKTRIK, KnxManufacturer_M_HELIOS_VENTILATOREN, KnxManufacturer_M_OTTO_SOLUTIONS_PTE_LTD, KnxManufacturer_M_AIRMASTER, KnxManufacturer_M_VALLOX_GMBH, KnxManufacturer_M_DALITEK, KnxManufacturer_M_ASIN, KnxManufacturer_M_BRIDGES_INTELLIGENCE_TECHNOLOGY_INC_, KnxManufacturer_M_ARBONIA, KnxManufacturer_M_KERMI, KnxManufacturer_M_PROLUX, KnxManufacturer_M_CLICHOME, KnxManufacturer_M_COMMAX, KnxManufacturer_M_EAE, KnxManufacturer_M_TENSE, KnxManufacturer_M_SEYOUNG_ELECTRONICS, KnxManufacturer_M_LIFEDOMUS, KnxManufacturer_M_EUROTRONIC_TECHNOLOGY_GMBH, KnxManufacturer_M_TCI, KnxManufacturer_M_RISHUN_ELECTRONIC, KnxManufacturer_M_ZIPATO, KnxManufacturer_M_CM_SECURITY_GMBH_AND_CO_KG, KnxManufacturer_M_QING_CABLES, KnxManufacturer_M_LABIO, KnxManufacturer_M_COSTER_TECNOLOGIE_ELETTRONICHE_S_P_A_, KnxManufacturer_M_E_G_E, KnxManufacturer_M_NETXAUTOMATION, KnxManufacturer_M_TECALOR, KnxManufacturer_M_URMET_ELECTRONICS_HUIZHOU_LTD_, KnxManufacturer_M_PEIYING_BUILDING_CONTROL, KnxManufacturer_M_BPT_S_P_A__A_SOCIO_UNICO, KnxManufacturer_M_KANONTEC___KANONBUS, KnxManufacturer_M_ISER_TECH, KnxManufacturer_M_FINELINE, KnxManufacturer_M_CP_ELECTRONICS_LTD, KnxManufacturer_M_NIKO_SERVODAN_AS, KnxManufacturer_M_SIMON_309, KnxManufacturer_M_GM_MODULAR_PVT__LTD_, KnxManufacturer_M_FU_CHENG_INTELLIGENCE, KnxManufacturer_M_NEXKON, KnxManufacturer_M_FEEL_S_R_L, KnxManufacturer_M_NOT_ASSIGNED_314, KnxManufacturer_M_SHENZHEN_FANHAI_SANJIANG_ELECTRONICS_CO___LTD_, KnxManufacturer_M_JIUZHOU_GREEBLE, KnxManufacturer_M_AUMUELLER_AUMATIC_GMBH, KnxManufacturer_M_ETMAN_ELECTRIC, KnxManufacturer_M_BLACK_NOVA, KnxManufacturer_M_ZIDATECH_AG, KnxManufacturer_M_IDGS_BVBA, KnxManufacturer_M_DAKANIMO, KnxManufacturer_M_TREBOR_AUTOMATION_AB, KnxManufacturer_M_SATEL_SP__Z_O_O_, KnxManufacturer_M_RUSSOUND__INC_, KnxManufacturer_M_MIDEA_HEATING_AND_VENTILATING_EQUIPMENT_CO_LTD, KnxManufacturer_M_CONSORZIO_TERRANUOVA, KnxManufacturer_M_WOLF_HEIZTECHNIK_GMBH, KnxManufacturer_M_SONTEC, KnxManufacturer_M_BELCOM_CABLES_LTD_, KnxManufacturer_M_GUANGZHOU_SEAWIN_ELECTRICAL_TECHNOLOGIES_CO___LTD_, KnxManufacturer_M_ACREL, KnxManufacturer_M_FRANKE_AQUAROTTER_GMBH, KnxManufacturer_M_ORION_SYSTEMS, KnxManufacturer_M_SCHRACK_TECHNIK_GMBH, KnxManufacturer_M_INSPRID, KnxManufacturer_M_SUNRICHER, KnxManufacturer_M_MENRED_AUTOMATION_SYSTEMSHANGHAI_CO__LTD_, KnxManufacturer_M_AUREX, KnxManufacturer_M_JOSEF_BARTHELME_GMBH_AND_CO__KG, KnxManufacturer_M_ARCHITECTURE_NUMERIQUE, KnxManufacturer_M_UP_GROUP, KnxManufacturer_M_TEKNOS_AVINNO, KnxManufacturer_M_NINGBO_DOOYA_MECHANIC_AND_ELECTRONIC_TECHNOLOGY, KnxManufacturer_M_THERMOKON_SENSORTECHNIK_GMBH, KnxManufacturer_M_BELIMO_AUTOMATION_AG, KnxManufacturer_M_ZEHNDER_GROUP_INTERNATIONAL_AG, KnxManufacturer_M_SKS_KINKEL_ELEKTRONIK, KnxManufacturer_M_ECE_WURMITZER_GMBH, KnxManufacturer_M_LARS, KnxManufacturer_M_URC, KnxManufacturer_M_LIGHTCONTROL, KnxManufacturer_M_SHENZHEN_YM, KnxManufacturer_M_MEAN_WELL_ENTERPRISES_CO__LTD_, KnxManufacturer_M_OSIX, KnxManufacturer_M_AYPRO_TECHNOLOGY, KnxManufacturer_M_HEFEI_ECOLITE_SOFTWARE, KnxManufacturer_M_ENNO, KnxManufacturer_M_OHOSURE, KnxManufacturer_M_GAREFOWL, KnxManufacturer_M_GEZE, KnxManufacturer_M_LG_ELECTRONICS_INC_, KnxManufacturer_M_SMC_INTERIORS, KnxManufacturer_M_NOT_ASSIGNED_364, KnxManufacturer_M_SCS_CABLE, KnxManufacturer_M_HOVAL, KnxManufacturer_M_CANST, KnxManufacturer_M_HANGZHOU_BERLIN, KnxManufacturer_M_EVN_LICHTTECHNIK, KnxManufacturer_M_RUTEC, KnxManufacturer_M_FINDER, KnxManufacturer_M_FUJITSU_GENERAL_LIMITED, KnxManufacturer_M_ZF_FRIEDRICHSHAFEN_AG, KnxManufacturer_M_CREALED, KnxManufacturer_M_MILES_MAGIC_AUTOMATION_PRIVATE_LIMITED, KnxManufacturer_M_EPlus, KnxManufacturer_M_ITALCOND, KnxManufacturer_M_SATION, KnxManufacturer_M_NEWBEST, KnxManufacturer_M_GDS_DIGITAL_SYSTEMS, KnxManufacturer_M_IDDERO, KnxManufacturer_M_MBNLED, KnxManufacturer_M_VITRUM, KnxManufacturer_M_EKEY_BIOMETRIC_SYSTEMS_GMBH, KnxManufacturer_M_AMC, KnxManufacturer_M_TRILUX_GMBH_AND_CO__KG, KnxManufacturer_M_WEXCEDO, KnxManufacturer_M_VEMER_SPA, KnxManufacturer_M_ALEXANDER_BUERKLE_GMBH_AND_CO_KG, KnxManufacturer_M_CITRON, KnxManufacturer_M_SHENZHEN_HEGUANG, KnxManufacturer_M_NOT_ASSIGNED_392, KnxManufacturer_M_TRANE_B_V_B_A, KnxManufacturer_M_CAREL, KnxManufacturer_M_PROLITE_CONTROLS, KnxManufacturer_M_BOSMER, KnxManufacturer_M_EUCHIPS, KnxManufacturer_M_CONNECT_THINKA_CONNECT, KnxManufacturer_M_PEAKNX_A_DOGAWIST_COMPANY, KnxManufacturer_M_ACEMATIC, KnxManufacturer_M_ELAUSYS, KnxManufacturer_M_ITK_ENGINEERING_AG, KnxManufacturer_M_INTEGRA_METERING_AG, KnxManufacturer_M_FMS_HOSPITALITY_PTE_LTD, KnxManufacturer_M_NUVO, KnxManufacturer_M_U__LUX_GMBH, KnxManufacturer_M_BRUMBERG_LEUCHTEN, KnxManufacturer_M_LIME, KnxManufacturer_M_GREAT_EMPIRE_INTERNATIONAL_GROUP_CO___LTD_, KnxManufacturer_M_KAVOSHPISHRO_ASIA, KnxManufacturer_M_V2_SPA, KnxManufacturer_M_JOHNSON_CONTROLS, KnxManufacturer_M_ARKUD, KnxManufacturer_M_IRIDIUM_LTD_, KnxManufacturer_M_BSMART, KnxManufacturer_M_BAB_TECHNOLOGIE_GMBH, KnxManufacturer_M_NICE_SPA, KnxManufacturer_M_REDFISH_GROUP_PTY_LTD, KnxManufacturer_M_SABIANA_SPA, KnxManufacturer_M_UBEE_INTERACTIVE_EUROPE, KnxManufacturer_M_REXEL, KnxManufacturer_M_GES_TEKNIK_A_S_, KnxManufacturer_M_AVE_S_P_A_, KnxManufacturer_M_ZHUHAI_LTECH_TECHNOLOGY_CO___LTD_, KnxManufacturer_M_ARCOM, KnxManufacturer_M_VIA_TECHNOLOGIES__INC_, KnxManufacturer_M_FEELSMART_, KnxManufacturer_M_SUPCON, KnxManufacturer_M_MANIC, KnxManufacturer_M_TDE_GMBH, KnxManufacturer_M_NANJING_SHUFAN_INFORMATION_TECHNOLOGY_CO__LTD_, KnxManufacturer_M_EWTECH, KnxManufacturer_M_KLUGER_AUTOMATION_GMBH, KnxManufacturer_M_JOONGANG_CONTROL, KnxManufacturer_M_GREENCONTROLS_TECHNOLOGY_SDN__BHD_, KnxManufacturer_M_IME_S_P_A_, KnxManufacturer_M_SICHUAN_HAODING, KnxManufacturer_M_MINDJAGA_LTD_, KnxManufacturer_M_RUILI_SMART_CONTROL, KnxManufacturer_M_CODESYS_GMBH, KnxManufacturer_M_MOORGEN_DEUTSCHLAND_GMBH, KnxManufacturer_M_CULLMANN_TECH, KnxManufacturer_M_MERCK_WINDOW_TECHNOLOGIES_B_V_, KnxManufacturer_M_ABEGO, KnxManufacturer_M_MYGEKKO, KnxManufacturer_M_ERGO3_SARL, KnxManufacturer_M_STMICROELECTRONICS_INTERNATIONAL_N_V_, KnxManufacturer_M_CJC_SYSTEMS, KnxManufacturer_M_SUDOKU, KnxManufacturer_M_AZ_E_LITE_PTE_LTD, KnxManufacturer_M_ARLIGHT, KnxManufacturer_M_GRUENBECK_WASSERAUFBEREITUNG_GMBH, KnxManufacturer_M_MODULE_ELECTRONIC, KnxManufacturer_M_KOPLAT, KnxManufacturer_M_GUANGZHOU_LETOUR_LIFE_TECHNOLOGY_CO___LTD, KnxManufacturer_M_ILEVIA, KnxManufacturer_M_LN_SYSTEMTEQ, KnxManufacturer_M_HISENSE_SMARTHOME, KnxManufacturer_M_FLINK_AUTOMATION_SYSTEM, KnxManufacturer_M_XXTER_BV, KnxManufacturer_M_LYNXUS_TECHNOLOGY, KnxManufacturer_M_ROBOT_S_A_, KnxManufacturer_M_SHENZHEN_ATTE_SMART_LIFE_CO__LTD_, KnxManufacturer_M_NOBLESSE, KnxManufacturer_M_ADVANCED_DEVICES, KnxManufacturer_M_ATRINA_BUILDING_AUTOMATION_CO__LTD, KnxManufacturer_M_GUANGDONG_DAMING_LAFFEY_ELECTRIC_CO___LTD_, KnxManufacturer_M_WESTERSTRAND_URFABRIK_AB, KnxManufacturer_M_CONTROL4_CORPORATE, KnxManufacturer_M_ONTROL, KnxManufacturer_M_STARNET, KnxManufacturer_M_BETA_CAVI, KnxManufacturer_M_EASEMORE, KnxManufacturer_M_VIVALDI_SRL, KnxManufacturer_M_GREE_ELECTRIC_APPLIANCES_INC__OF_ZHUHAI, KnxManufacturer_M_HWISCON, KnxManufacturer_M_SHANGHAI_ELECON_INTELLIGENT_TECHNOLOGY_CO___LTD_, KnxManufacturer_M_KAMPMANN, KnxManufacturer_M_IMPOLUX_GMBH_LEDIMAX, KnxManufacturer_M_EVAUX, KnxManufacturer_M_WEBRO_CABLES_AND_CONNECTORS_LIMITED, KnxManufacturer_M_SHANGHAI_E_TECH_SOLUTION, KnxManufacturer_M_GUANGZHOU_HOKO_ELECTRIC_CO__LTD_, KnxManufacturer_M_LAMMIN_HIGH_TECH_CO__LTD, KnxManufacturer_M_SHENZHEN_MERRYTEK_TECHNOLOGY_CO___LTD, KnxManufacturer_M_I_LUXUS, KnxManufacturer_M_ELMOS_SEMICONDUCTOR_AG, KnxManufacturer_M_EMCOM_TECHNOLOGY_INC, KnxManufacturer_M_PROJECT_INNOVATIONS_GMBH, KnxManufacturer_M_ITC, KnxManufacturer_M_ABB_LV_INSTALLATION_MATERIALS_COMPANY_LTD__BEIJING, KnxManufacturer_M_MAICO, KnxManufacturer_M_ELAN_SRL, KnxManufacturer_M_MINHHA_TECHNOLOGY_CO__LTD, KnxManufacturer_M_ZHEJIANG_TIANJIE_INDUSTRIAL_CORP_, KnxManufacturer_M_IAUTOMATION_PTY_LIMITED, KnxManufacturer_M_EXTRON, KnxManufacturer_M_FREEDOMPRO, KnxManufacturer_M_ONEHOME, KnxManufacturer_M_EOS_SAUNATECHNIK_GMBH, KnxManufacturer_M_KUSATEK_GMBH, KnxManufacturer_M_EISBAER_SCADA, KnxManufacturer_M_AUTOMATISMI_BENINCA_S_P_A_, KnxManufacturer_M_BLENDOM, KnxManufacturer_M_MADEL_AIR_TECHNICAL_DIFFUSION, KnxManufacturer_M_NIKO, KnxManufacturer_M_BOSCH_REXROTH_AG, KnxManufacturer_M_CANDM_PRODUCTS, KnxManufacturer_M_HOERMANN_KG_VERKAUFSGESELLSCHAFT, KnxManufacturer_M_SHANGHAI_RAJAYASA_CO__LTD, KnxManufacturer_M_SUZUKI, KnxManufacturer_M_SILENT_GLISS_INTERNATIONAL_LTD_, KnxManufacturer_M_BEE_CONTROLS_ADGSC_GROUP, KnxManufacturer_M_XDTECGMBH, KnxManufacturer_M_OSRAM, KnxManufacturer_M_LEBENOR, KnxManufacturer_M_AUTOMANENG, KnxManufacturer_M_HONEYWELL_AUTOMATION_SOLUTION_CONTROLCHINA, KnxManufacturer_M_HANGZHOU_BINTHEN_INTELLIGENCE_TECHNOLOGY_CO__LTD, KnxManufacturer_M_ETA_HEIZTECHNIK, KnxManufacturer_M_DIVUS_GMBH, KnxManufacturer_M_NANJING_TAIJIESAI_INTELLIGENT_TECHNOLOGY_CO__LTD_, KnxManufacturer_M_LUNATONE, KnxManufacturer_M_ZHEJIANG_SCTECH_BUILDING_INTELLIGENT, KnxManufacturer_M_FOSHAN_QITE_TECHNOLOGY_CO___LTD_, KnxManufacturer_M_NOKE, KnxManufacturer_M_LANDCOM, KnxManufacturer_M_STORK_AS, KnxManufacturer_M_HANGZHOU_SHENDU_TECHNOLOGY_CO___LTD_, KnxManufacturer_M_COOLAUTOMATION, KnxManufacturer_M_APRSTERN, KnxManufacturer_M_SONNEN, KnxManufacturer_M_DNAKE, KnxManufacturer_M_NEUBERGER_GEBAEUDEAUTOMATION_GMBH, KnxManufacturer_M_STILIGER, KnxManufacturer_M_BERGHOF_AUTOMATION_GMBH, KnxManufacturer_M_TOTAL_AUTOMATION_AND_CONTROLS_GMBH, KnxManufacturer_M_DOVIT, KnxManufacturer_M_INSTALIGHTING_GMBH, KnxManufacturer_M_UNI_TEC, KnxManufacturer_M_CASATUNES, KnxManufacturer_M_EMT, KnxManufacturer_M_SENFFICIENT, KnxManufacturer_M_AUROLITE_ELECTRICAL_PANYU_GUANGZHOU_LIMITED, KnxManufacturer_M_ABB_XIAMEN_SMART_TECHNOLOGY_CO___LTD_, KnxManufacturer_M_SAMSON_ELECTRIC_WIRE, KnxManufacturer_M_T_TOUCHING, KnxManufacturer_M_CORE_SMART_HOME, KnxManufacturer_M_GREENCONNECT_SOLUTIONS_SA, KnxManufacturer_M_ELETTRONICA_CONDUTTORI, KnxManufacturer_M_MKFC, KnxManufacturer_M_AUTOMATIONPlus, KnxManufacturer_M_BLUE_AND_RED, KnxManufacturer_M_FROGBLUE, KnxManufacturer_M_SAVESOR, KnxManufacturer_M_APP_TECH, KnxManufacturer_M_SENSORTEC_AG, KnxManufacturer_M_NYSA_TECHNOLOGY_AND_SOLUTIONS, KnxManufacturer_M_FARADITE, KnxManufacturer_M_OPTIMUS, KnxManufacturer_M_KTS_S_R_L_, KnxManufacturer_M_RAMCRO_SPA, KnxManufacturer_M_WUHAN_WISECREATE_UNIVERSE_TECHNOLOGY_CO___LTD, KnxManufacturer_M_BEMI_SMART_HOME_LTD, KnxManufacturer_M_ARDOMUS, KnxManufacturer_M_CHANGXING, KnxManufacturer_M_E_CONTROLS, KnxManufacturer_M_AIB_TECHNOLOGY, KnxManufacturer_M_NVC, KnxManufacturer_M_KBOX, KnxManufacturer_M_CNS, KnxManufacturer_M_TYBA, KnxManufacturer_M_ATREL, KnxManufacturer_M_SIMON_ELECTRIC_CHINA_CO___LTD, KnxManufacturer_M_KORDZ_GROUP, KnxManufacturer_M_ND_ELECTRIC, KnxManufacturer_M_CONTROLIUM, KnxManufacturer_M_FAMO_GMBH_AND_CO__KG, KnxManufacturer_M_CDN_SMART, KnxManufacturer_M_HESTON, KnxManufacturer_M_ESLA_CONEXIONES_S_L_, KnxManufacturer_M_WEISHAUPT, KnxManufacturer_M_ASTRUM_TECHNOLOGY, KnxManufacturer_M_WUERTH_ELEKTRONIK_STELVIO_KONTEK_S_P_A_, KnxManufacturer_M_NANOTECO_CORPORATION, KnxManufacturer_M_NIETIAN, KnxManufacturer_M_SUMSIR, KnxManufacturer_M_ORBIS_TECNOLOGIA_ELECTRICA_SA, KnxManufacturer_M_NANJING_ZHONGYI_IOT_TECHNOLOGY_CO___LTD_, KnxManufacturer_M_ANLIPS, KnxManufacturer_M_GUANGDONG_PAK_CORPORATION_CO___LTD, KnxManufacturer_M_BVK_TECHNOLOGY, KnxManufacturer_M_SOLOMIO_SRL, KnxManufacturer_M_DOMOTICA_LABS, KnxManufacturer_M_NVC_INTERNATIONAL, KnxManufacturer_M_BA, KnxManufacturer_M_IRIS_CERAMICA_GROUP, KnxManufacturer_M_WIREEO, KnxManufacturer_M_NVCLIGHTING, KnxManufacturer_M_JINAN_TIAN_DA_SHENG_INFORMATION_TECHNOLOGY_CO_, KnxManufacturer_M_ARMITI_TRADING, KnxManufacturer_M_ELEK, KnxManufacturer_M_ACCORDIA_SA, KnxManufacturer_M_OURICAN, KnxManufacturer_M_INLIWOSE, KnxManufacturer_M_BOSCH_SHANGHAI_SMART_LIFE_TECHNOLOGY_LTD_, KnxManufacturer_M_SHK_KNX, KnxManufacturer_M_AMPIO, KnxManufacturer_M_MINGXING_WISDOM, KnxManufacturer_M_ALTEN_SW_GMBH, KnxManufacturer_M_ABB___RESERVED, KnxManufacturer_M_BUSCH_JAEGER_ELEKTRO___RESERVED, } } func (e KnxManufacturer) Number() uint16 { switch e { case 0: { /* '0' */ return 0 } case 1: { /* '1' */ return 1 } case 10: { /* '10' */ return 11 } case 100: { /* '100' */ return 140 } case 101: { /* '101' */ return 141 } case 102: { /* '102' */ return 142 } case 103: { /* '103' */ return 143 } case 104: { /* '104' */ return 144 } case 105: { /* '105' */ return 145 } case 106: { /* '106' */ return 146 } case 107: { /* '107' */ return 147 } case 108: { /* '108' */ return 148 } case 109: { /* '109' */ return 149 } case 11: { /* '11' */ return 12 } case 110: { /* '110' */ return 150 } case 111: { /* '111' */ return 151 } case 112: { /* '112' */ return 152 } case 113: { /* '113' */ return 153 } case 114: { /* '114' */ return 154 } case 115: { /* '115' */ return 155 } case 116: { /* '116' */ return 156 } case 117: { /* '117' */ return 157 } case 118: { /* '118' */ return 158 } case 119: { /* '119' */ return 159 } case 12: { /* '12' */ return 14 } case 120: { /* '120' */ return 160 } case 121: { /* '121' */ return 161 } case 122: { /* '122' */ return 162 } case 123: { /* '123' */ return 163 } case 124: { /* '124' */ return 164 } case 125: { /* '125' */ return 165 } case 126: { /* '126' */ return 166 } case 127: { /* '127' */ return 167 } case 128: { /* '128' */ return 168 } case 129: { /* '129' */ return 169 } case 13: { /* '13' */ return 22 } case 130: { /* '130' */ return 170 } case 131: { /* '131' */ return 171 } case 132: { /* '132' */ return 172 } case 133: { /* '133' */ return 173 } case 134: { /* '134' */ return 174 } case 135: { /* '135' */ return 175 } case 136: { /* '136' */ return 176 } case 137: { /* '137' */ return 177 } case 138: { /* '138' */ return 178 } case 139: { /* '139' */ return 179 } case 14: { /* '14' */ return 24 } case 140: { /* '140' */ return 180 } case 141: { /* '141' */ return 181 } case 142: { /* '142' */ return 182 } case 143: { /* '143' */ return 183 } case 144: { /* '144' */ return 184 } case 145: { /* '145' */ return 185 } case 146: { /* '146' */ return 186 } case 147: { /* '147' */ return 187 } case 148: { /* '148' */ return 188 } case 149: { /* '149' */ return 189 } case 15: { /* '15' */ return 25 } case 150: { /* '150' */ return 190 } case 151: { /* '151' */ return 191 } case 152: { /* '152' */ return 192 } case 153: { /* '153' */ return 193 } case 154: { /* '154' */ return 194 } case 155: { /* '155' */ return 195 } case 156: { /* '156' */ return 196 } case 157: { /* '157' */ return 197 } case 158: { /* '158' */ return 198 } case 159: { /* '159' */ return 199 } case 16: { /* '16' */ return 27 } case 160: { /* '160' */ return 200 } case 161: { /* '161' */ return 201 } case 162: { /* '162' */ return 202 } case 163: { /* '163' */ return 204 } case 164: { /* '164' */ return 205 } case 165: { /* '165' */ return 206 } case 166: { /* '166' */ return 207 } case 167: { /* '167' */ return 208 } case 168: { /* '168' */ return 209 } case 169: { /* '169' */ return 210 } case 17: { /* '17' */ return 28 } case 170: { /* '170' */ return 211 } case 171: { /* '171' */ return 214 } case 172: { /* '172' */ return 215 } case 173: { /* '173' */ return 216 } case 174: { /* '174' */ return 217 } case 175: { /* '175' */ return 218 } case 176: { /* '176' */ return 219 } case 177: { /* '177' */ return 220 } case 178: { /* '178' */ return 222 } case 179: { /* '179' */ return 223 } case 18: { /* '18' */ return 29 } case 180: { /* '180' */ return 225 } case 181: { /* '181' */ return 227 } case 182: { /* '182' */ return 228 } case 183: { /* '183' */ return 232 } case 184: { /* '184' */ return 233 } case 185: { /* '185' */ return 234 } case 186: { /* '186' */ return 235 } case 187: { /* '187' */ return 237 } case 188: { /* '188' */ return 238 } case 189: { /* '189' */ return 239 } case 19: { /* '19' */ return 30 } case 190: { /* '190' */ return 240 } case 191: { /* '191' */ return 241 } case 192: { /* '192' */ return 242 } case 193: { /* '193' */ return 244 } case 194: { /* '194' */ return 245 } case 195: { /* '195' */ return 246 } case 196: { /* '196' */ return 248 } case 197: { /* '197' */ return 249 } case 198: { /* '198' */ return 250 } case 199: { /* '199' */ return 251 } case 2: { /* '2' */ return 2 } case 20: { /* '20' */ return 31 } case 200: { /* '200' */ return 252 } case 201: { /* '201' */ return 253 } case 202: { /* '202' */ return 254 } case 203: { /* '203' */ return 256 } case 204: { /* '204' */ return 257 } case 205: { /* '205' */ return 258 } case 206: { /* '206' */ return 259 } case 207: { /* '207' */ return 260 } case 208: { /* '208' */ return 261 } case 209: { /* '209' */ return 262 } case 21: { /* '21' */ return 32 } case 210: { /* '210' */ return 263 } case 211: { /* '211' */ return 264 } case 212: { /* '212' */ return 265 } case 213: { /* '213' */ return 266 } case 214: { /* '214' */ return 267 } case 215: { /* '215' */ return 268 } case 216: { /* '216' */ return 269 } case 217: { /* '217' */ return 270 } case 218: { /* '218' */ return 271 } case 219: { /* '219' */ return 272 } case 22: { /* '22' */ return 33 } case 220: { /* '220' */ return 273 } case 221: { /* '221' */ return 274 } case 222: { /* '222' */ return 275 } case 223: { /* '223' */ return 276 } case 224: { /* '224' */ return 277 } case 225: { /* '225' */ return 278 } case 226: { /* '226' */ return 279 } case 227: { /* '227' */ return 280 } case 228: { /* '228' */ return 281 } case 229: { /* '229' */ return 282 } case 23: { /* '23' */ return 34 } case 230: { /* '230' */ return 283 } case 231: { /* '231' */ return 284 } case 232: { /* '232' */ return 285 } case 233: { /* '233' */ return 286 } case 234: { /* '234' */ return 287 } case 235: { /* '235' */ return 288 } case 236: { /* '236' */ return 289 } case 237: { /* '237' */ return 290 } case 238: { /* '238' */ return 291 } case 239: { /* '239' */ return 292 } case 24: { /* '24' */ return 36 } case 240: { /* '240' */ return 293 } case 241: { /* '241' */ return 294 } case 242: { /* '242' */ return 295 } case 243: { /* '243' */ return 296 } case 244: { /* '244' */ return 297 } case 245: { /* '245' */ return 298 } case 246: { /* '246' */ return 299 } case 247: { /* '247' */ return 300 } case 248: { /* '248' */ return 301 } case 249: { /* '249' */ return 302 } case 25: { /* '25' */ return 37 } case 250: { /* '250' */ return 303 } case 251: { /* '251' */ return 304 } case 252: { /* '252' */ return 305 } case 253: { /* '253' */ return 306 } case 254: { /* '254' */ return 307 } case 255: { /* '255' */ return 308 } case 256: { /* '256' */ return 309 } case 257: { /* '257' */ return 310 } case 258: { /* '258' */ return 311 } case 259: { /* '259' */ return 312 } case 26: { /* '26' */ return 41 } case 260: { /* '260' */ return 313 } case 261: { /* '261' */ return 314 } case 262: { /* '262' */ return 315 } case 263: { /* '263' */ return 316 } case 264: { /* '264' */ return 317 } case 265: { /* '265' */ return 318 } case 266: { /* '266' */ return 319 } case 267: { /* '267' */ return 320 } case 268: { /* '268' */ return 321 } case 269: { /* '269' */ return 322 } case 27: { /* '27' */ return 42 } case 270: { /* '270' */ return 323 } case 271: { /* '271' */ return 324 } case 272: { /* '272' */ return 325 } case 273: { /* '273' */ return 326 } case 274: { /* '274' */ return 327 } case 275: { /* '275' */ return 328 } case 276: { /* '276' */ return 329 } case 277: { /* '277' */ return 330 } case 278: { /* '278' */ return 331 } case 279: { /* '279' */ return 332 } case 28: { /* '28' */ return 44 } case 280: { /* '280' */ return 333 } case 281: { /* '281' */ return 334 } case 282: { /* '282' */ return 335 } case 283: { /* '283' */ return 336 } case 284: { /* '284' */ return 337 } case 285: { /* '285' */ return 338 } case 286: { /* '286' */ return 339 } case 287: { /* '287' */ return 340 } case 288: { /* '288' */ return 341 } case 289: { /* '289' */ return 342 } case 29: { /* '29' */ return 45 } case 290: { /* '290' */ return 343 } case 291: { /* '291' */ return 344 } case 292: { /* '292' */ return 345 } case 293: { /* '293' */ return 346 } case 294: { /* '294' */ return 347 } case 295: { /* '295' */ return 348 } case 296: { /* '296' */ return 349 } case 297: { /* '297' */ return 350 } case 298: { /* '298' */ return 351 } case 299: { /* '299' */ return 352 } case 3: { /* '3' */ return 4 } case 30: { /* '30' */ return 46 } case 300: { /* '300' */ return 353 } case 301: { /* '301' */ return 354 } case 302: { /* '302' */ return 355 } case 303: { /* '303' */ return 356 } case 304: { /* '304' */ return 357 } case 305: { /* '305' */ return 358 } case 306: { /* '306' */ return 359 } case 307: { /* '307' */ return 360 } case 308: { /* '308' */ return 361 } case 309: { /* '309' */ return 362 } case 31: { /* '31' */ return 49 } case 310: { /* '310' */ return 363 } case 311: { /* '311' */ return 364 } case 312: { /* '312' */ return 365 } case 313: { /* '313' */ return 366 } case 314: { /* '314' */ return 367 } case 315: { /* '315' */ return 368 } case 316: { /* '316' */ return 369 } case 317: { /* '317' */ return 370 } case 318: { /* '318' */ return 371 } case 319: { /* '319' */ return 372 } case 32: { /* '32' */ return 52 } case 320: { /* '320' */ return 373 } case 321: { /* '321' */ return 374 } case 322: { /* '322' */ return 375 } case 323: { /* '323' */ return 376 } case 324: { /* '324' */ return 377 } case 325: { /* '325' */ return 378 } case 326: { /* '326' */ return 379 } case 327: { /* '327' */ return 380 } case 328: { /* '328' */ return 381 } case 329: { /* '329' */ return 382 } case 33: { /* '33' */ return 53 } case 330: { /* '330' */ return 383 } case 331: { /* '331' */ return 384 } case 332: { /* '332' */ return 385 } case 333: { /* '333' */ return 386 } case 334: { /* '334' */ return 387 } case 335: { /* '335' */ return 388 } case 336: { /* '336' */ return 389 } case 337: { /* '337' */ return 390 } case 338: { /* '338' */ return 391 } case 339: { /* '339' */ return 392 } case 34: { /* '34' */ return 55 } case 340: { /* '340' */ return 393 } case 341: { /* '341' */ return 394 } case 342: { /* '342' */ return 395 } case 343: { /* '343' */ return 396 } case 344: { /* '344' */ return 397 } case 345: { /* '345' */ return 398 } case 346: { /* '346' */ return 399 } case 347: { /* '347' */ return 400 } case 348: { /* '348' */ return 401 } case 349: { /* '349' */ return 402 } case 35: { /* '35' */ return 57 } case 350: { /* '350' */ return 403 } case 351: { /* '351' */ return 404 } case 352: { /* '352' */ return 405 } case 353: { /* '353' */ return 406 } case 354: { /* '354' */ return 407 } case 355: { /* '355' */ return 408 } case 356: { /* '356' */ return 409 } case 357: { /* '357' */ return 410 } case 358: { /* '358' */ return 411 } case 359: { /* '359' */ return 412 } case 36: { /* '36' */ return 61 } case 360: { /* '360' */ return 413 } case 361: { /* '361' */ return 414 } case 362: { /* '362' */ return 415 } case 363: { /* '363' */ return 416 } case 364: { /* '364' */ return 417 } case 365: { /* '365' */ return 418 } case 366: { /* '366' */ return 419 } case 367: { /* '367' */ return 420 } case 368: { /* '368' */ return 421 } case 369: { /* '369' */ return 422 } case 37: { /* '37' */ return 62 } case 370: { /* '370' */ return 423 } case 371: { /* '371' */ return 424 } case 372: { /* '372' */ return 425 } case 373: { /* '373' */ return 426 } case 374: { /* '374' */ return 427 } case 375: { /* '375' */ return 428 } case 376: { /* '376' */ return 429 } case 377: { /* '377' */ return 430 } case 378: { /* '378' */ return 431 } case 379: { /* '379' */ return 432 } case 38: { /* '38' */ return 66 } case 380: { /* '380' */ return 433 } case 381: { /* '381' */ return 434 } case 382: { /* '382' */ return 435 } case 383: { /* '383' */ return 436 } case 384: { /* '384' */ return 437 } case 385: { /* '385' */ return 438 } case 386: { /* '386' */ return 439 } case 387: { /* '387' */ return 440 } case 388: { /* '388' */ return 441 } case 389: { /* '389' */ return 442 } case 39: { /* '39' */ return 67 } case 390: { /* '390' */ return 443 } case 391: { /* '391' */ return 444 } case 392: { /* '392' */ return 445 } case 393: { /* '393' */ return 446 } case 394: { /* '394' */ return 447 } case 395: { /* '395' */ return 448 } case 396: { /* '396' */ return 449 } case 397: { /* '397' */ return 451 } case 398: { /* '398' */ return 452 } case 399: { /* '399' */ return 453 } case 4: { /* '4' */ return 5 } case 40: { /* '40' */ return 69 } case 400: { /* '400' */ return 454 } case 401: { /* '401' */ return 455 } case 402: { /* '402' */ return 456 } case 403: { /* '403' */ return 457 } case 404: { /* '404' */ return 458 } case 405: { /* '405' */ return 459 } case 406: { /* '406' */ return 460 } case 407: { /* '407' */ return 461 } case 408: { /* '408' */ return 462 } case 409: { /* '409' */ return 463 } case 41: { /* '41' */ return 71 } case 410: { /* '410' */ return 464 } case 411: { /* '411' */ return 465 } case 412: { /* '412' */ return 466 } case 413: { /* '413' */ return 467 } case 414: { /* '414' */ return 468 } case 415: { /* '415' */ return 469 } case 416: { /* '416' */ return 470 } case 417: { /* '417' */ return 471 } case 418: { /* '418' */ return 472 } case 419: { /* '419' */ return 473 } case 42: { /* '42' */ return 72 } case 420: { /* '420' */ return 474 } case 421: { /* '421' */ return 475 } case 422: { /* '422' */ return 476 } case 423: { /* '423' */ return 477 } case 424: { /* '424' */ return 478 } case 425: { /* '425' */ return 479 } case 426: { /* '426' */ return 480 } case 427: { /* '427' */ return 481 } case 428: { /* '428' */ return 482 } case 429: { /* '429' */ return 483 } case 43: { /* '43' */ return 73 } case 430: { /* '430' */ return 484 } case 431: { /* '431' */ return 485 } case 432: { /* '432' */ return 486 } case 433: { /* '433' */ return 487 } case 434: { /* '434' */ return 488 } case 435: { /* '435' */ return 489 } case 436: { /* '436' */ return 490 } case 437: { /* '437' */ return 491 } case 438: { /* '438' */ return 492 } case 439: { /* '439' */ return 493 } case 44: { /* '44' */ return 75 } case 440: { /* '440' */ return 495 } case 441: { /* '441' */ return 496 } case 442: { /* '442' */ return 497 } case 443: { /* '443' */ return 498 } case 444: { /* '444' */ return 499 } case 445: { /* '445' */ return 500 } case 446: { /* '446' */ return 501 } case 447: { /* '447' */ return 502 } case 448: { /* '448' */ return 503 } case 449: { /* '449' */ return 504 } case 45: { /* '45' */ return 76 } case 450: { /* '450' */ return 505 } case 451: { /* '451' */ return 506 } case 452: { /* '452' */ return 507 } case 453: { /* '453' */ return 508 } case 454: { /* '454' */ return 509 } case 455: { /* '455' */ return 512 } case 456: { /* '456' */ return 513 } case 457: { /* '457' */ return 514 } case 458: { /* '458' */ return 515 } case 459: { /* '459' */ return 516 } case 46: { /* '46' */ return 78 } case 460: { /* '460' */ return 517 } case 461: { /* '461' */ return 518 } case 462: { /* '462' */ return 519 } case 463: { /* '463' */ return 520 } case 464: { /* '464' */ return 521 } case 465: { /* '465' */ return 522 } case 466: { /* '466' */ return 523 } case 467: { /* '467' */ return 524 } case 468: { /* '468' */ return 525 } case 469: { /* '469' */ return 526 } case 47: { /* '47' */ return 80 } case 470: { /* '470' */ return 527 } case 471: { /* '471' */ return 528 } case 472: { /* '472' */ return 529 } case 473: { /* '473' */ return 530 } case 474: { /* '474' */ return 531 } case 475: { /* '475' */ return 532 } case 476: { /* '476' */ return 533 } case 477: { /* '477' */ return 534 } case 478: { /* '478' */ return 535 } case 479: { /* '479' */ return 536 } case 48: { /* '48' */ return 81 } case 480: { /* '480' */ return 537 } case 481: { /* '481' */ return 538 } case 482: { /* '482' */ return 539 } case 483: { /* '483' */ return 540 } case 484: { /* '484' */ return 541 } case 485: { /* '485' */ return 542 } case 486: { /* '486' */ return 543 } case 487: { /* '487' */ return 544 } case 488: { /* '488' */ return 545 } case 489: { /* '489' */ return 546 } case 49: { /* '49' */ return 82 } case 490: { /* '490' */ return 547 } case 491: { /* '491' */ return 548 } case 492: { /* '492' */ return 549 } case 493: { /* '493' */ return 550 } case 494: { /* '494' */ return 551 } case 495: { /* '495' */ return 552 } case 496: { /* '496' */ return 553 } case 497: { /* '497' */ return 554 } case 498: { /* '498' */ return 555 } case 499: { /* '499' */ return 556 } case 5: { /* '5' */ return 6 } case 50: { /* '50' */ return 83 } case 500: { /* '500' */ return 557 } case 501: { /* '501' */ return 558 } case 502: { /* '502' */ return 559 } case 503: { /* '503' */ return 560 } case 504: { /* '504' */ return 561 } case 505: { /* '505' */ return 562 } case 506: { /* '506' */ return 563 } case 507: { /* '507' */ return 564 } case 508: { /* '508' */ return 565 } case 509: { /* '509' */ return 566 } case 51: { /* '51' */ return 85 } case 510: { /* '510' */ return 567 } case 511: { /* '511' */ return 568 } case 512: { /* '512' */ return 569 } case 513: { /* '513' */ return 570 } case 514: { /* '514' */ return 571 } case 515: { /* '515' */ return 572 } case 516: { /* '516' */ return 573 } case 517: { /* '517' */ return 574 } case 518: { /* '518' */ return 575 } case 519: { /* '519' */ return 576 } case 52: { /* '52' */ return 89 } case 520: { /* '520' */ return 577 } case 521: { /* '521' */ return 578 } case 522: { /* '522' */ return 579 } case 523: { /* '523' */ return 580 } case 524: { /* '524' */ return 581 } case 525: { /* '525' */ return 582 } case 526: { /* '526' */ return 583 } case 527: { /* '527' */ return 584 } case 528: { /* '528' */ return 585 } case 529: { /* '529' */ return 586 } case 53: { /* '53' */ return 90 } case 530: { /* '530' */ return 587 } case 531: { /* '531' */ return 588 } case 532: { /* '532' */ return 589 } case 533: { /* '533' */ return 590 } case 534: { /* '534' */ return 591 } case 535: { /* '535' */ return 592 } case 536: { /* '536' */ return 593 } case 537: { /* '537' */ return 594 } case 538: { /* '538' */ return 595 } case 539: { /* '539' */ return 596 } case 54: { /* '54' */ return 92 } case 540: { /* '540' */ return 597 } case 541: { /* '541' */ return 598 } case 542: { /* '542' */ return 599 } case 543: { /* '543' */ return 600 } case 544: { /* '544' */ return 601 } case 545: { /* '545' */ return 602 } case 546: { /* '546' */ return 603 } case 547: { /* '547' */ return 604 } case 548: { /* '548' */ return 605 } case 549: { /* '549' */ return 606 } case 55: { /* '55' */ return 93 } case 550: { /* '550' */ return 607 } case 551: { /* '551' */ return 608 } case 552: { /* '552' */ return 609 } case 553: { /* '553' */ return 610 } case 554: { /* '554' */ return 611 } case 555: { /* '555' */ return 612 } case 556: { /* '556' */ return 613 } case 557: { /* '557' */ return 614 } case 558: { /* '558' */ return 43954 } case 559: { /* '559' */ return 43959 } case 56: { /* '56' */ return 94 } case 57: { /* '57' */ return 95 } case 58: { /* '58' */ return 97 } case 59: { /* '59' */ return 98 } case 6: { /* '6' */ return 7 } case 60: { /* '60' */ return 99 } case 61: { /* '61' */ return 100 } case 62: { /* '62' */ return 101 } case 63: { /* '63' */ return 102 } case 64: { /* '64' */ return 104 } case 65: { /* '65' */ return 105 } case 66: { /* '66' */ return 106 } case 67: { /* '67' */ return 107 } case 68: { /* '68' */ return 108 } case 69: { /* '69' */ return 109 } case 7: { /* '7' */ return 8 } case 70: { /* '70' */ return 110 } case 71: { /* '71' */ return 111 } case 72: { /* '72' */ return 112 } case 73: { /* '73' */ return 113 } case 74: { /* '74' */ return 114 } case 75: { /* '75' */ return 115 } case 76: { /* '76' */ return 116 } case 77: { /* '77' */ return 117 } case 78: { /* '78' */ return 118 } case 79: { /* '79' */ return 119 } case 8: { /* '8' */ return 9 } case 80: { /* '80' */ return 120 } case 81: { /* '81' */ return 121 } case 82: { /* '82' */ return 122 } case 83: { /* '83' */ return 123 } case 84: { /* '84' */ return 124 } case 85: { /* '85' */ return 125 } case 86: { /* '86' */ return 126 } case 87: { /* '87' */ return 127 } case 88: { /* '88' */ return 128 } case 89: { /* '89' */ return 129 } case 9: { /* '9' */ return 10 } case 90: { /* '90' */ return 130 } case 91: { /* '91' */ return 131 } case 92: { /* '92' */ return 132 } case 93: { /* '93' */ return 133 } case 94: { /* '94' */ return 134 } case 95: { /* '95' */ return 135 } case 96: { /* '96' */ return 136 } case 97: { /* '97' */ return 137 } case 98: { /* '98' */ return 138 } case 99: { /* '99' */ return 139 } default: { return 0 } } } func KnxManufacturerFirstEnumForFieldNumber(value uint16) (KnxManufacturer, error) { for _, sizeValue := range KnxManufacturerValues { if sizeValue.Number() == value { return sizeValue, nil } } return 0, errors.Errorf("enum for %v describing Number not found", value) } func (e KnxManufacturer) Name() string { switch e { case 0: { /* '0' */ return "Unknown Manufacturer" } case 1: { /* '1' */ return "Siemens" } case 10: { /* '10' */ return "LEGRAND Appareillage électrique" } case 100: { /* '100' */ return "Pulse Technologies" } case 101: { /* '101' */ return "Crestron" } case 102: { /* '102' */ return "STEINEL professional" } case 103: { /* '103' */ return "BILTON LED Lighting" } case 104: { /* '104' */ return "denro AG" } case 105: { /* '105' */ return "GePro" } case 106: { /* '106' */ return "preussen automation" } case 107: { /* '107' */ return "Zoppas Industries" } case 108: { /* '108' */ return "MACTECH" } case 109: { /* '109' */ return "TECHNO-TREND" } case 11: { /* '11' */ return "Merten" } case 110: { /* '110' */ return "FS Cables" } case 111: { /* '111' */ return "Delta Dore" } case 112: { /* '112' */ return "Eissound" } case 113: { /* '113' */ return "Cisco" } case 114: { /* '114' */ return "Dinuy" } case 115: { /* '115' */ return "iKNiX" } case 116: { /* '116' */ return "Rademacher Geräte-Elektronik GmbH" } case 117: { /* '117' */ return "EGi Electroacustica General Iberica" } case 118: { /* '118' */ return "Bes – Ingenium" } case 119: { /* '119' */ return "ElabNET" } case 12: { /* '12' */ return "ABB SpA-SACE Division" } case 120: { /* '120' */ return "Blumotix" } case 121: { /* '121' */ return "Hunter Douglas" } case 122: { /* '122' */ return "APRICUM" } case 123: { /* '123' */ return "TIANSU Automation" } case 124: { /* '124' */ return "Bubendorff" } case 125: { /* '125' */ return "MBS GmbH" } case 126: { /* '126' */ return "Enertex Bayern GmbH" } case 127: { /* '127' */ return "BMS" } case 128: { /* '128' */ return "Sinapsi" } case 129: { /* '129' */ return "Embedded Systems SIA" } case 13: { /* '13' */ return "Siedle & Söhne" } case 130: { /* '130' */ return "KNX1" } case 131: { /* '131' */ return "Tokka" } case 132: { /* '132' */ return "NanoSense" } case 133: { /* '133' */ return "PEAR Automation GmbH" } case 134: { /* '134' */ return "DGA" } case 135: { /* '135' */ return "Lutron" } case 136: { /* '136' */ return "AIRZONE – ALTRA" } case 137: { /* '137' */ return "Lithoss Design Switches" } case 138: { /* '138' */ return "3ATEL" } case 139: { /* '139' */ return "Philips Controls" } case 14: { /* '14' */ return "Eberle" } case 140: { /* '140' */ return "VELUX A/S" } case 141: { /* '141' */ return "LOYTEC" } case 142: { /* '142' */ return "Ekinex S.p.A." } case 143: { /* '143' */ return "SIRLAN Technologies" } case 144: { /* '144' */ return "ProKNX SAS" } case 145: { /* '145' */ return "IT GmbH" } case 146: { /* '146' */ return "RENSON" } case 147: { /* '147' */ return "HEP Group" } case 148: { /* '148' */ return "Balmart" } case 149: { /* '149' */ return "GFS GmbH" } case 15: { /* '15' */ return "GEWISS" } case 150: { /* '150' */ return "Schenker Storen AG" } case 151: { /* '151' */ return "Algodue Elettronica S.r.L." } case 152: { /* '152' */ return "ABB France" } case 153: { /* '153' */ return "maintronic" } case 154: { /* '154' */ return "Vantage" } case 155: { /* '155' */ return "Foresis" } case 156: { /* '156' */ return "Research & Production Association SEM" } case 157: { /* '157' */ return "Weinzierl Engineering GmbH" } case 158: { /* '158' */ return "Möhlenhoff Wärmetechnik GmbH" } case 159: { /* '159' */ return "PKC-GROUP Oyj" } case 16: { /* '16' */ return "Albert Ackermann" } case 160: { /* '160' */ return "B.E.G." } case 161: { /* '161' */ return "Elsner Elektronik GmbH" } case 162: { /* '162' */ return "Siemens Building Technologies (HK/China) Ltd." } case 163: { /* '163' */ return "Eutrac" } case 164: { /* '164' */ return "Gustav Hensel GmbH & Co. KG" } case 165: { /* '165' */ return "GARO AB" } case 166: { /* '166' */ return "Waldmann Lichttechnik" } case 167: { /* '167' */ return "SCHÜCO" } case 168: { /* '168' */ return "EMU" } case 169: { /* '169' */ return "JNet Systems AG" } case 17: { /* '17' */ return "Schupa GmbH" } case 170: { /* '170' */ return "Total Solution GmbH" } case 171: { /* '171' */ return "O.Y.L. Electronics" } case 172: { /* '172' */ return "Galax System" } case 173: { /* '173' */ return "Disch" } case 174: { /* '174' */ return "Aucoteam" } case 175: { /* '175' */ return "Luxmate Controls" } case 176: { /* '176' */ return "Danfoss" } case 177: { /* '177' */ return "AST GmbH" } case 178: { /* '178' */ return "WILA Leuchten" } case 179: { /* '179' */ return "b+b Automations- und Steuerungstechnik" } case 18: { /* '18' */ return "ABB SCHWEIZ" } case 180: { /* '180' */ return "Lingg & Janke" } case 181: { /* '181' */ return "Sauter" } case 182: { /* '182' */ return "SIMU" } case 183: { /* '183' */ return "Theben HTS AG" } case 184: { /* '184' */ return "Amann GmbH" } case 185: { /* '185' */ return "BERG Energiekontrollsysteme GmbH" } case 186: { /* '186' */ return "Hüppe Form Sonnenschutzsysteme GmbH" } case 187: { /* '187' */ return "Oventrop KG" } case 188: { /* '188' */ return "Griesser AG" } case 189: { /* '189' */ return "IPAS GmbH" } case 19: { /* '19' */ return "Feller" } case 190: { /* '190' */ return "elero GmbH" } case 191: { /* '191' */ return "Ardan Production and Industrial Controls Ltd." } case 192: { /* '192' */ return "Metec Meßtechnik GmbH" } case 193: { /* '193' */ return "ELKA-Elektronik GmbH" } case 194: { /* '194' */ return "ELEKTROANLAGEN D. NAGEL" } case 195: { /* '195' */ return "Tridonic Bauelemente GmbH" } case 196: { /* '196' */ return "Stengler Gesellschaft" } case 197: { /* '197' */ return "Schneider Electric (MG)" } case 198: { /* '198' */ return "KNX Association" } case 199: { /* '199' */ return "VIVO" } case 2: { /* '2' */ return "ABB" } case 20: { /* '20' */ return "Glamox AS" } case 200: { /* '200' */ return "Hugo Müller GmbH & Co KG" } case 201: { /* '201' */ return "Siemens HVAC" } case 202: { /* '202' */ return "APT" } case 203: { /* '203' */ return "HighDom" } case 204: { /* '204' */ return "Top Services" } case 205: { /* '205' */ return "ambiHome" } case 206: { /* '206' */ return "DATEC electronic AG" } case 207: { /* '207' */ return "ABUS Security-Center" } case 208: { /* '208' */ return "Lite-Puter" } case 209: { /* '209' */ return "Tantron Electronic" } case 21: { /* '21' */ return "DEHN & SÖHNE" } case 210: { /* '210' */ return "Interra" } case 211: { /* '211' */ return "DKX Tech" } case 212: { /* '212' */ return "Viatron" } case 213: { /* '213' */ return "Nautibus" } case 214: { /* '214' */ return "ON Semiconductor" } case 215: { /* '215' */ return "Longchuang" } case 216: { /* '216' */ return "Air-On AG" } case 217: { /* '217' */ return "ib-company GmbH" } case 218: { /* '218' */ return "Sation Factory" } case 219: { /* '219' */ return "Agentilo GmbH" } case 22: { /* '22' */ return "CRABTREE" } case 220: { /* '220' */ return "Makel Elektrik" } case 221: { /* '221' */ return "Helios Ventilatoren" } case 222: { /* '222' */ return "Otto Solutions Pte Ltd" } case 223: { /* '223' */ return "Airmaster" } case 224: { /* '224' */ return "Vallox GmbH" } case 225: { /* '225' */ return "Dalitek" } case 226: { /* '226' */ return "ASIN" } case 227: { /* '227' */ return "Bridges Intelligence Technology Inc." } case 228: { /* '228' */ return "ARBONIA" } case 229: { /* '229' */ return "KERMI" } case 23: { /* '23' */ return "eVoKNX" } case 230: { /* '230' */ return "PROLUX" } case 231: { /* '231' */ return "ClicHome" } case 232: { /* '232' */ return "COMMAX" } case 233: { /* '233' */ return "EAE" } case 234: { /* '234' */ return "Tense" } case 235: { /* '235' */ return "Seyoung Electronics" } case 236: { /* '236' */ return "Lifedomus" } case 237: { /* '237' */ return "EUROtronic Technology GmbH" } case 238: { /* '238' */ return "tci" } case 239: { /* '239' */ return "Rishun Electronic" } case 24: { /* '24' */ return "Paul Hochköpper" } case 240: { /* '240' */ return "Zipato" } case 241: { /* '241' */ return "cm-security GmbH & Co KG" } case 242: { /* '242' */ return "Qing Cables" } case 243: { /* '243' */ return "LABIO" } case 244: { /* '244' */ return "Coster Tecnologie Elettroniche S.p.A." } case 245: { /* '245' */ return "E.G.E" } case 246: { /* '246' */ return "NETxAutomation" } case 247: { /* '247' */ return "tecalor" } case 248: { /* '248' */ return "Urmet Electronics (Huizhou) Ltd." } case 249: { /* '249' */ return "Peiying Building Control" } case 25: { /* '25' */ return "Altenburger Electronic" } case 250: { /* '250' */ return "BPT S.p.A. a Socio Unico" } case 251: { /* '251' */ return "Kanontec - KanonBUS" } case 252: { /* '252' */ return "ISER Tech" } case 253: { /* '253' */ return "Fineline" } case 254: { /* '254' */ return "CP Electronics Ltd" } case 255: { /* '255' */ return "Niko-Servodan A/S" } case 256: { /* '256' */ return "Simon" } case 257: { /* '257' */ return "GM modular pvt. Ltd." } case 258: { /* '258' */ return "FU CHENG Intelligence" } case 259: { /* '259' */ return "NexKon" } case 26: { /* '26' */ return "Grässlin" } case 260: { /* '260' */ return "FEEL s.r.l" } case 261: { /* '261' */ return "Not Assigned" } case 262: { /* '262' */ return "Shenzhen Fanhai Sanjiang Electronics Co., Ltd." } case 263: { /* '263' */ return "Jiuzhou Greeble" } case 264: { /* '264' */ return "Aumüller Aumatic GmbH" } case 265: { /* '265' */ return "Etman Electric" } case 266: { /* '266' */ return "Black Nova" } case 267: { /* '267' */ return "ZidaTech AG" } case 268: { /* '268' */ return "IDGS bvba" } case 269: { /* '269' */ return "dakanimo" } case 27: { /* '27' */ return "Simon" } case 270: { /* '270' */ return "Trebor Automation AB" } case 271: { /* '271' */ return "Satel sp. z o.o." } case 272: { /* '272' */ return "Russound, Inc." } case 273: { /* '273' */ return "Midea Heating & Ventilating Equipment CO LTD" } case 274: { /* '274' */ return "Consorzio Terranuova" } case 275: { /* '275' */ return "Wolf Heiztechnik GmbH" } case 276: { /* '276' */ return "SONTEC" } case 277: { /* '277' */ return "Belcom Cables Ltd." } case 278: { /* '278' */ return "Guangzhou SeaWin Electrical Technologies Co., Ltd." } case 279: { /* '279' */ return "Acrel" } case 28: { /* '28' */ return "VIMAR" } case 280: { /* '280' */ return "Franke Aquarotter GmbH" } case 281: { /* '281' */ return "Orion Systems" } case 282: { /* '282' */ return "Schrack Technik GmbH" } case 283: { /* '283' */ return "INSPRID" } case 284: { /* '284' */ return "Sunricher" } case 285: { /* '285' */ return "Menred automation system(shanghai) Co.,Ltd." } case 286: { /* '286' */ return "Aurex" } case 287: { /* '287' */ return "Josef Barthelme GmbH & Co. KG" } case 288: { /* '288' */ return "Architecture Numerique" } case 289: { /* '289' */ return "UP GROUP" } case 29: { /* '29' */ return "Moeller Gebäudeautomation KG" } case 290: { /* '290' */ return "Teknos-Avinno" } case 291: { /* '291' */ return "Ningbo Dooya Mechanic & Electronic Technology" } case 292: { /* '292' */ return "Thermokon Sensortechnik GmbH" } case 293: { /* '293' */ return "BELIMO Automation AG" } case 294: { /* '294' */ return "Zehnder Group International AG" } case 295: { /* '295' */ return "sks Kinkel Elektronik" } case 296: { /* '296' */ return "ECE Wurmitzer GmbH" } case 297: { /* '297' */ return "LARS" } case 298: { /* '298' */ return "URC" } case 299: { /* '299' */ return "LightControl" } case 3: { /* '3' */ return "Albrecht Jung" } case 30: { /* '30' */ return "Eltako" } case 300: { /* '300' */ return "ShenZhen YM" } case 301: { /* '301' */ return "MEAN WELL Enterprises Co. Ltd." } case 302: { /* '302' */ return "OSix" } case 303: { /* '303' */ return "AYPRO Technology" } case 304: { /* '304' */ return "Hefei Ecolite Software" } case 305: { /* '305' */ return "Enno" } case 306: { /* '306' */ return "OHOSURE" } case 307: { /* '307' */ return "Garefowl" } case 308: { /* '308' */ return "GEZE" } case 309: { /* '309' */ return "LG Electronics Inc." } case 31: { /* '31' */ return "Bosch-Siemens Haushaltsgeräte" } case 310: { /* '310' */ return "SMC interiors" } case 311: { /* '311' */ return "Not Assigned" } case 312: { /* '312' */ return "SCS Cable" } case 313: { /* '313' */ return "Hoval" } case 314: { /* '314' */ return "CANST" } case 315: { /* '315' */ return "HangZhou Berlin" } case 316: { /* '316' */ return "EVN-Lichttechnik" } case 317: { /* '317' */ return "rutec" } case 318: { /* '318' */ return "Finder" } case 319: { /* '319' */ return "Fujitsu General Limited" } case 32: { /* '32' */ return "RITTO GmbH&Co.KG" } case 320: { /* '320' */ return "ZF Friedrichshafen AG" } case 321: { /* '321' */ return "Crealed" } case 322: { /* '322' */ return "Miles Magic Automation Private Limited" } case 323: { /* '323' */ return "E+" } case 324: { /* '324' */ return "Italcond" } case 325: { /* '325' */ return "SATION" } case 326: { /* '326' */ return "NewBest" } case 327: { /* '327' */ return "GDS DIGITAL SYSTEMS" } case 328: { /* '328' */ return "Iddero" } case 329: { /* '329' */ return "MBNLED" } case 33: { /* '33' */ return "Power Controls" } case 330: { /* '330' */ return "VITRUM" } case 331: { /* '331' */ return "ekey biometric systems GmbH" } case 332: { /* '332' */ return "AMC" } case 333: { /* '333' */ return "TRILUX GmbH & Co. KG" } case 334: { /* '334' */ return "WExcedo" } case 335: { /* '335' */ return "VEMER SPA" } case 336: { /* '336' */ return "Alexander Bürkle GmbH & Co KG" } case 337: { /* '337' */ return "Citron" } case 338: { /* '338' */ return "Shenzhen HeGuang" } case 339: { /* '339' */ return "Not Assigned" } case 34: { /* '34' */ return "ZUMTOBEL" } case 340: { /* '340' */ return "TRANE B.V.B.A" } case 341: { /* '341' */ return "CAREL" } case 342: { /* '342' */ return "Prolite Controls" } case 343: { /* '343' */ return "BOSMER" } case 344: { /* '344' */ return "EUCHIPS" } case 345: { /* '345' */ return "connect (Thinka connect)" } case 346: { /* '346' */ return "PEAKnx a DOGAWIST company" } case 347: { /* '347' */ return "ACEMATIC" } case 348: { /* '348' */ return "ELAUSYS" } case 349: { /* '349' */ return "ITK Engineering AG" } case 35: { /* '35' */ return "Phoenix Contact" } case 350: { /* '350' */ return "INTEGRA METERING AG" } case 351: { /* '351' */ return "FMS Hospitality Pte Ltd" } case 352: { /* '352' */ return "Nuvo" } case 353: { /* '353' */ return "u::Lux GmbH" } case 354: { /* '354' */ return "Brumberg Leuchten" } case 355: { /* '355' */ return "Lime" } case 356: { /* '356' */ return "Great Empire International Group Co., Ltd." } case 357: { /* '357' */ return "Kavoshpishro Asia" } case 358: { /* '358' */ return "V2 SpA" } case 359: { /* '359' */ return "Johnson Controls" } case 36: { /* '36' */ return "WAGO Kontakttechnik" } case 360: { /* '360' */ return "Arkud" } case 361: { /* '361' */ return "Iridium Ltd." } case 362: { /* '362' */ return "bsmart" } case 363: { /* '363' */ return "BAB TECHNOLOGIE GmbH" } case 364: { /* '364' */ return "NICE Spa" } case 365: { /* '365' */ return "Redfish Group Pty Ltd" } case 366: { /* '366' */ return "SABIANA spa" } case 367: { /* '367' */ return "Ubee Interactive Europe" } case 368: { /* '368' */ return "Rexel" } case 369: { /* '369' */ return "Ges Teknik A.S." } case 37: { /* '37' */ return "knXpresso" } case 370: { /* '370' */ return "Ave S.p.A." } case 371: { /* '371' */ return "Zhuhai Ltech Technology Co., Ltd." } case 372: { /* '372' */ return "ARCOM" } case 373: { /* '373' */ return "VIA Technologies, Inc." } case 374: { /* '374' */ return "FEELSMART." } case 375: { /* '375' */ return "SUPCON" } case 376: { /* '376' */ return "MANIC" } case 377: { /* '377' */ return "TDE GmbH" } case 378: { /* '378' */ return "Nanjing Shufan Information technology Co.,Ltd." } case 379: { /* '379' */ return "EWTech" } case 38: { /* '38' */ return "Wieland Electric" } case 380: { /* '380' */ return "Kluger Automation GmbH" } case 381: { /* '381' */ return "JoongAng Control" } case 382: { /* '382' */ return "GreenControls Technology Sdn. Bhd." } case 383: { /* '383' */ return "IME S.p.a." } case 384: { /* '384' */ return "SiChuan HaoDing" } case 385: { /* '385' */ return "Mindjaga Ltd." } case 386: { /* '386' */ return "RuiLi Smart Control" } case 387: { /* '387' */ return "CODESYS GmbH" } case 388: { /* '388' */ return "Moorgen Deutschland GmbH" } case 389: { /* '389' */ return "CULLMANN TECH" } case 39: { /* '39' */ return "Hermann Kleinhuis" } case 390: { /* '390' */ return "Merck Window Technologies B.V." } case 391: { /* '391' */ return "ABEGO" } case 392: { /* '392' */ return "myGEKKO" } case 393: { /* '393' */ return "Ergo3 Sarl" } case 394: { /* '394' */ return "STmicroelectronics International N.V." } case 395: { /* '395' */ return "cjc systems" } case 396: { /* '396' */ return "Sudoku" } case 397: { /* '397' */ return "AZ e-lite Pte Ltd" } case 398: { /* '398' */ return "Arlight" } case 399: { /* '399' */ return "Grünbeck Wasseraufbereitung GmbH" } case 4: { /* '4' */ return "Bticino" } case 40: { /* '40' */ return "Stiebel Eltron" } case 400: { /* '400' */ return "Module Electronic" } case 401: { /* '401' */ return "KOPLAT" } case 402: { /* '402' */ return "Guangzhou Letour Life Technology Co., Ltd" } case 403: { /* '403' */ return "ILEVIA" } case 404: { /* '404' */ return "LN SYSTEMTEQ" } case 405: { /* '405' */ return "Hisense SmartHome" } case 406: { /* '406' */ return "Flink Automation System" } case 407: { /* '407' */ return "xxter bv" } case 408: { /* '408' */ return "lynxus technology" } case 409: { /* '409' */ return "ROBOT S.A." } case 41: { /* '41' */ return "Tehalit" } case 410: { /* '410' */ return "Shenzhen Atte Smart Life Co.,Ltd." } case 411: { /* '411' */ return "Noblesse" } case 412: { /* '412' */ return "Advanced Devices" } case 413: { /* '413' */ return "Atrina Building Automation Co. Ltd" } case 414: { /* '414' */ return "Guangdong Daming Laffey electric Co., Ltd." } case 415: { /* '415' */ return "Westerstrand Urfabrik AB" } case 416: { /* '416' */ return "Control4 Corporate" } case 417: { /* '417' */ return "Ontrol" } case 418: { /* '418' */ return "Starnet" } case 419: { /* '419' */ return "BETA CAVI" } case 42: { /* '42' */ return "Theben AG" } case 420: { /* '420' */ return "EaseMore" } case 421: { /* '421' */ return "Vivaldi srl" } case 422: { /* '422' */ return "Gree Electric Appliances,Inc. of Zhuhai" } case 423: { /* '423' */ return "HWISCON" } case 424: { /* '424' */ return "Shanghai ELECON Intelligent Technology Co., Ltd." } case 425: { /* '425' */ return "Kampmann" } case 426: { /* '426' */ return "Impolux GmbH / LEDIMAX" } case 427: { /* '427' */ return "Evaux" } case 428: { /* '428' */ return "Webro Cables & Connectors Limited" } case 429: { /* '429' */ return "Shanghai E-tech Solution" } case 43: { /* '43' */ return "Wilhelm Rutenbeck" } case 430: { /* '430' */ return "Guangzhou HOKO Electric Co.,Ltd." } case 431: { /* '431' */ return "LAMMIN HIGH TECH CO.,LTD" } case 432: { /* '432' */ return "Shenzhen Merrytek Technology Co., Ltd" } case 433: { /* '433' */ return "I-Luxus" } case 434: { /* '434' */ return "Elmos Semiconductor AG" } case 435: { /* '435' */ return "EmCom Technology Inc" } case 436: { /* '436' */ return "project innovations GmbH" } case 437: { /* '437' */ return "Itc" } case 438: { /* '438' */ return "ABB LV Installation Materials Company Ltd, Beijing" } case 439: { /* '439' */ return "Maico" } case 44: { /* '44' */ return "Winkhaus" } case 440: { /* '440' */ return "ELAN SRL" } case 441: { /* '441' */ return "MinhHa Technology co.,Ltd" } case 442: { /* '442' */ return "Zhejiang Tianjie Industrial CORP." } case 443: { /* '443' */ return "iAutomation Pty Limited" } case 444: { /* '444' */ return "Extron" } case 445: { /* '445' */ return "Freedompro" } case 446: { /* '446' */ return "1Home" } case 447: { /* '447' */ return "EOS Saunatechnik GmbH" } case 448: { /* '448' */ return "KUSATEK GmbH" } case 449: { /* '449' */ return "EisBär Scada" } case 45: { /* '45' */ return "Robert Bosch" } case 450: { /* '450' */ return "AUTOMATISMI BENINCA S.P.A." } case 451: { /* '451' */ return "Blendom" } case 452: { /* '452' */ return "Madel Air Technical diffusion" } case 453: { /* '453' */ return "NIKO" } case 454: { /* '454' */ return "Bosch Rexroth AG" } case 455: { /* '455' */ return "C&M Products" } case 456: { /* '456' */ return "Hörmann KG Verkaufsgesellschaft" } case 457: { /* '457' */ return "Shanghai Rajayasa co.,LTD" } case 458: { /* '458' */ return "SUZUKI" } case 459: { /* '459' */ return "Silent Gliss International Ltd." } case 46: { /* '46' */ return "Somfy" } case 460: { /* '460' */ return "BEE Controls (ADGSC Group)" } case 461: { /* '461' */ return "xDTecGmbH" } case 462: { /* '462' */ return "OSRAM" } case 463: { /* '463' */ return "Lebenor" } case 464: { /* '464' */ return "automaneng" } case 465: { /* '465' */ return "Honeywell Automation Solution control(China)" } case 466: { /* '466' */ return "Hangzhou binthen Intelligence Technology Co.,Ltd" } case 467: { /* '467' */ return "ETA Heiztechnik" } case 468: { /* '468' */ return "DIVUS GmbH" } case 469: { /* '469' */ return "Nanjing Taijiesai Intelligent Technology Co. Ltd." } case 47: { /* '47' */ return "Woertz" } case 470: { /* '470' */ return "Lunatone" } case 471: { /* '471' */ return "ZHEJIANG SCTECH BUILDING INTELLIGENT" } case 472: { /* '472' */ return "Foshan Qite Technology Co., Ltd." } case 473: { /* '473' */ return "NOKE" } case 474: { /* '474' */ return "LANDCOM" } case 475: { /* '475' */ return "Stork AS" } case 476: { /* '476' */ return "Hangzhou Shendu Technology Co., Ltd." } case 477: { /* '477' */ return "CoolAutomation" } case 478: { /* '478' */ return "Aprstern" } case 479: { /* '479' */ return "sonnen" } case 48: { /* '48' */ return "Viessmann Werke" } case 480: { /* '480' */ return "DNAKE" } case 481: { /* '481' */ return "Neuberger Gebäudeautomation GmbH" } case 482: { /* '482' */ return "Stiliger" } case 483: { /* '483' */ return "Berghof Automation GmbH" } case 484: { /* '484' */ return "Total Automation and controls GmbH" } case 485: { /* '485' */ return "dovit" } case 486: { /* '486' */ return "Instalighting GmbH" } case 487: { /* '487' */ return "UNI-TEC" } case 488: { /* '488' */ return "CasaTunes" } case 489: { /* '489' */ return "EMT" } case 49: { /* '49' */ return "IMI Hydronic Engineering" } case 490: { /* '490' */ return "Senfficient" } case 491: { /* '491' */ return "Aurolite electrical panyu guangzhou limited" } case 492: { /* '492' */ return "ABB Xiamen Smart Technology Co., Ltd." } case 493: { /* '493' */ return "Samson Electric Wire" } case 494: { /* '494' */ return "T-Touching" } case 495: { /* '495' */ return "Core Smart Home" } case 496: { /* '496' */ return "GreenConnect Solutions SA" } case 497: { /* '497' */ return "ELETTRONICA CONDUTTORI" } case 498: { /* '498' */ return "MKFC" } case 499: { /* '499' */ return "Automation+" } case 5: { /* '5' */ return "Berker" } case 50: { /* '50' */ return "Joh. Vaillant" } case 500: { /* '500' */ return "blue and red" } case 501: { /* '501' */ return "frogblue" } case 502: { /* '502' */ return "SAVESOR" } case 503: { /* '503' */ return "App Tech" } case 504: { /* '504' */ return "sensortec AG" } case 505: { /* '505' */ return "nysa technology & solutions" } case 506: { /* '506' */ return "FARADITE" } case 507: { /* '507' */ return "Optimus" } case 508: { /* '508' */ return "KTS s.r.l." } case 509: { /* '509' */ return "Ramcro SPA" } case 51: { /* '51' */ return "AMP Deutschland" } case 510: { /* '510' */ return "Wuhan WiseCreate Universe Technology Co., Ltd" } case 511: { /* '511' */ return "BEMI Smart Home Ltd" } case 512: { /* '512' */ return "Ardomus" } case 513: { /* '513' */ return "ChangXing" } case 514: { /* '514' */ return "E-Controls" } case 515: { /* '515' */ return "AIB Technology" } case 516: { /* '516' */ return "NVC" } case 517: { /* '517' */ return "Kbox" } case 518: { /* '518' */ return "CNS" } case 519: { /* '519' */ return "Tyba" } case 52: { /* '52' */ return "Bosch Thermotechnik GmbH" } case 520: { /* '520' */ return "Atrel" } case 521: { /* '521' */ return "Simon Electric (China) Co., LTD" } case 522: { /* '522' */ return "Kordz Group" } case 523: { /* '523' */ return "ND Electric" } case 524: { /* '524' */ return "Controlium" } case 525: { /* '525' */ return "FAMO GmbH & Co. KG" } case 526: { /* '526' */ return "CDN Smart" } case 527: { /* '527' */ return "Heston" } case 528: { /* '528' */ return "ESLA CONEXIONES S.L." } case 529: { /* '529' */ return "Weishaupt" } case 53: { /* '53' */ return "SEF - ECOTEC" } case 530: { /* '530' */ return "ASTRUM TECHNOLOGY" } case 531: { /* '531' */ return "WUERTH ELEKTRONIK STELVIO KONTEK S.p.A." } case 532: { /* '532' */ return "NANOTECO corporation" } case 533: { /* '533' */ return "Nietian" } case 534: { /* '534' */ return "Sumsir" } case 535: { /* '535' */ return "ORBIS TECNOLOGIA ELECTRICA SA" } case 536: { /* '536' */ return "Nanjing Zhongyi IoT Technology Co., Ltd." } case 537: { /* '537' */ return "Anlips" } case 538: { /* '538' */ return "GUANGDONG PAK CORPORATION CO., LTD" } case 539: { /* '539' */ return "BVK Technology" } case 54: { /* '54' */ return "DORMA GmbH + Co. KG" } case 540: { /* '540' */ return "Solomio srl" } case 541: { /* '541' */ return "Domotica Labs" } case 542: { /* '542' */ return "NVC International" } case 543: { /* '543' */ return "BA" } case 544: { /* '544' */ return "Iris Ceramica Group" } case 545: { /* '545' */ return "Wireeo" } case 546: { /* '546' */ return "nvclighting" } case 547: { /* '547' */ return "Jinan Tian Da Sheng Information Technology Co." } case 548: { /* '548' */ return "Armiti trading" } case 549: { /* '549' */ return "ELEK" } case 55: { /* '55' */ return "WindowMaster A/S" } case 550: { /* '550' */ return "Accordia sa" } case 551: { /* '551' */ return "OURICAN" } case 552: { /* '552' */ return "INLIWOSE" } case 553: { /* '553' */ return "Bosch (Shanghai) Smart Life Technology Ltd." } case 554: { /* '554' */ return "SHK KNX" } case 555: { /* '555' */ return "Ampio" } case 556: { /* '556' */ return "Mingxing Wisdom" } case 557: { /* '557' */ return "ALTEN SW GmbH" } case 558: { /* '558' */ return "ABB - reserved" } case 559: { /* '559' */ return "Busch-Jaeger Elektro - reserved" } case 56: { /* '56' */ return "Walther Werke" } case 57: { /* '57' */ return "ORAS" } case 58: { /* '58' */ return "Dätwyler" } case 59: { /* '59' */ return "Electrak" } case 6: { /* '6' */ return "Busch-Jaeger Elektro" } case 60: { /* '60' */ return "Techem" } case 61: { /* '61' */ return "Schneider Electric Industries SAS" } case 62: { /* '62' */ return "WHD Wilhelm Huber + Söhne" } case 63: { /* '63' */ return "Bischoff Elektronik" } case 64: { /* '64' */ return "JEPAZ" } case 65: { /* '65' */ return "RTS Automation" } case 66: { /* '66' */ return "EIBMARKT GmbH" } case 67: { /* '67' */ return "WAREMA Renkhoff SE" } case 68: { /* '68' */ return "Eelectron" } case 69: { /* '69' */ return "Belden Wire & Cable B.V." } case 7: { /* '7' */ return "GIRA Giersiepen" } case 70: { /* '70' */ return "Becker-Antriebe GmbH" } case 71: { /* '71' */ return "J.Stehle+Söhne GmbH" } case 72: { /* '72' */ return "AGFEO" } case 73: { /* '73' */ return "Zennio" } case 74: { /* '74' */ return "TAPKO Technologies" } case 75: { /* '75' */ return "HDL" } case 76: { /* '76' */ return "Uponor" } case 77: { /* '77' */ return "se Lightmanagement AG" } case 78: { /* '78' */ return "Arcus-eds" } case 79: { /* '79' */ return "Intesis" } case 8: { /* '8' */ return "Hager Electro" } case 80: { /* '80' */ return "Herholdt Controls srl" } case 81: { /* '81' */ return "Niko-Zublin" } case 82: { /* '82' */ return "Durable Technologies" } case 83: { /* '83' */ return "Innoteam" } case 84: { /* '84' */ return "ise GmbH" } case 85: { /* '85' */ return "TEAM FOR TRONICS" } case 86: { /* '86' */ return "CIAT" } case 87: { /* '87' */ return "Remeha BV" } case 88: { /* '88' */ return "ESYLUX" } case 89: { /* '89' */ return "BASALTE" } case 9: { /* '9' */ return "Insta GmbH" } case 90: { /* '90' */ return "Vestamatic" } case 91: { /* '91' */ return "MDT technologies" } case 92: { /* '92' */ return "Warendorfer Küchen GmbH" } case 93: { /* '93' */ return "Video-Star" } case 94: { /* '94' */ return "Sitek" } case 95: { /* '95' */ return "CONTROLtronic" } case 96: { /* '96' */ return "function Technology" } case 97: { /* '97' */ return "AMX" } case 98: { /* '98' */ return "ELDAT" } case 99: { /* '99' */ return "Panasonic" } default: { return "" } } } func KnxManufacturerFirstEnumForFieldName(value string) (KnxManufacturer, error) { for _, sizeValue := range KnxManufacturerValues { if sizeValue.Name() == value { return sizeValue, nil } } return 0, errors.Errorf("enum for %v describing Name not found", value) } func KnxManufacturerByValue(value uint16) KnxManufacturer { switch value { case 0: return KnxManufacturer_M_UNKNOWN case 1: return KnxManufacturer_M_SIEMENS case 10: return KnxManufacturer_M_LEGRAND_APPAREILLAGE_ELECTRIQUE case 100: return KnxManufacturer_M_PULSE_TECHNOLOGIES case 101: return KnxManufacturer_M_CRESTRON case 102: return KnxManufacturer_M_STEINEL_PROFESSIONAL case 103: return KnxManufacturer_M_BILTON_LED_LIGHTING case 104: return KnxManufacturer_M_DENRO_AG case 105: return KnxManufacturer_M_GEPRO case 106: return KnxManufacturer_M_PREUSSEN_AUTOMATION case 107: return KnxManufacturer_M_ZOPPAS_INDUSTRIES case 108: return KnxManufacturer_M_MACTECH case 109: return KnxManufacturer_M_TECHNO_TREND case 11: return KnxManufacturer_M_MERTEN case 110: return KnxManufacturer_M_FS_CABLES case 111: return KnxManufacturer_M_DELTA_DORE case 112: return KnxManufacturer_M_EISSOUND case 113: return KnxManufacturer_M_CISCO case 114: return KnxManufacturer_M_DINUY case 115: return KnxManufacturer_M_IKNIX case 116: return KnxManufacturer_M_RADEMACHER_GERAETE_ELEKTRONIK_GMBH case 117: return KnxManufacturer_M_EGI_ELECTROACUSTICA_GENERAL_IBERICA case 118: return KnxManufacturer_M_BES___INGENIUM case 119: return KnxManufacturer_M_ELABNET case 12: return KnxManufacturer_M_ABB_SPA_SACE_DIVISION case 120: return KnxManufacturer_M_BLUMOTIX case 121: return KnxManufacturer_M_HUNTER_DOUGLAS case 122: return KnxManufacturer_M_APRICUM case 123: return KnxManufacturer_M_TIANSU_AUTOMATION case 124: return KnxManufacturer_M_BUBENDORFF case 125: return KnxManufacturer_M_MBS_GMBH case 126: return KnxManufacturer_M_ENERTEX_BAYERN_GMBH case 127: return KnxManufacturer_M_BMS case 128: return KnxManufacturer_M_SINAPSI case 129: return KnxManufacturer_M_EMBEDDED_SYSTEMS_SIA case 13: return KnxManufacturer_M_SIEDLE_AND_SOEHNE case 130: return KnxManufacturer_M_KNX1 case 131: return KnxManufacturer_M_TOKKA case 132: return KnxManufacturer_M_NANOSENSE case 133: return KnxManufacturer_M_PEAR_AUTOMATION_GMBH case 134: return KnxManufacturer_M_DGA case 135: return KnxManufacturer_M_LUTRON case 136: return KnxManufacturer_M_AIRZONE___ALTRA case 137: return KnxManufacturer_M_LITHOSS_DESIGN_SWITCHES case 138: return KnxManufacturer_M_THREEATEL case 139: return KnxManufacturer_M_PHILIPS_CONTROLS case 14: return KnxManufacturer_M_EBERLE case 140: return KnxManufacturer_M_VELUX_AS case 141: return KnxManufacturer_M_LOYTEC case 142: return KnxManufacturer_M_EKINEX_S_P_A_ case 143: return KnxManufacturer_M_SIRLAN_TECHNOLOGIES case 144: return KnxManufacturer_M_PROKNX_SAS case 145: return KnxManufacturer_M_IT_GMBH case 146: return KnxManufacturer_M_RENSON case 147: return KnxManufacturer_M_HEP_GROUP case 148: return KnxManufacturer_M_BALMART case 149: return KnxManufacturer_M_GFS_GMBH case 15: return KnxManufacturer_M_GEWISS case 150: return KnxManufacturer_M_SCHENKER_STOREN_AG case 151: return KnxManufacturer_M_ALGODUE_ELETTRONICA_S_R_L_ case 152: return KnxManufacturer_M_ABB_FRANCE case 153: return KnxManufacturer_M_MAINTRONIC case 154: return KnxManufacturer_M_VANTAGE case 155: return KnxManufacturer_M_FORESIS case 156: return KnxManufacturer_M_RESEARCH_AND_PRODUCTION_ASSOCIATION_SEM case 157: return KnxManufacturer_M_WEINZIERL_ENGINEERING_GMBH case 158: return KnxManufacturer_M_MOEHLENHOFF_WAERMETECHNIK_GMBH case 159: return KnxManufacturer_M_PKC_GROUP_OYJ case 16: return KnxManufacturer_M_ALBERT_ACKERMANN case 160: return KnxManufacturer_M_B_E_G_ case 161: return KnxManufacturer_M_ELSNER_ELEKTRONIK_GMBH case 162: return KnxManufacturer_M_SIEMENS_BUILDING_TECHNOLOGIES_HKCHINA_LTD_ case 163: return KnxManufacturer_M_EUTRAC case 164: return KnxManufacturer_M_GUSTAV_HENSEL_GMBH_AND_CO__KG case 165: return KnxManufacturer_M_GARO_AB case 166: return KnxManufacturer_M_WALDMANN_LICHTTECHNIK case 167: return KnxManufacturer_M_SCHUECO case 168: return KnxManufacturer_M_EMU case 169: return KnxManufacturer_M_JNET_SYSTEMS_AG case 17: return KnxManufacturer_M_SCHUPA_GMBH case 170: return KnxManufacturer_M_TOTAL_SOLUTION_GMBH case 171: return KnxManufacturer_M_O_Y_L__ELECTRONICS case 172: return KnxManufacturer_M_GALAX_SYSTEM case 173: return KnxManufacturer_M_DISCH case 174: return KnxManufacturer_M_AUCOTEAM case 175: return KnxManufacturer_M_LUXMATE_CONTROLS case 176: return KnxManufacturer_M_DANFOSS case 177: return KnxManufacturer_M_AST_GMBH case 178: return KnxManufacturer_M_WILA_LEUCHTEN case 179: return KnxManufacturer_M_BPlusB_AUTOMATIONS__UND_STEUERUNGSTECHNIK case 18: return KnxManufacturer_M_ABB_SCHWEIZ case 180: return KnxManufacturer_M_LINGG_AND_JANKE case 181: return KnxManufacturer_M_SAUTER case 182: return KnxManufacturer_M_SIMU case 183: return KnxManufacturer_M_THEBEN_HTS_AG case 184: return KnxManufacturer_M_AMANN_GMBH case 185: return KnxManufacturer_M_BERG_ENERGIEKONTROLLSYSTEME_GMBH case 186: return KnxManufacturer_M_HUEPPE_FORM_SONNENSCHUTZSYSTEME_GMBH case 187: return KnxManufacturer_M_OVENTROP_KG case 188: return KnxManufacturer_M_GRIESSER_AG case 189: return KnxManufacturer_M_IPAS_GMBH case 19: return KnxManufacturer_M_FELLER case 190: return KnxManufacturer_M_ELERO_GMBH case 191: return KnxManufacturer_M_ARDAN_PRODUCTION_AND_INDUSTRIAL_CONTROLS_LTD_ case 192: return KnxManufacturer_M_METEC_MESSTECHNIK_GMBH case 193: return KnxManufacturer_M_ELKA_ELEKTRONIK_GMBH case 194: return KnxManufacturer_M_ELEKTROANLAGEN_D__NAGEL case 195: return KnxManufacturer_M_TRIDONIC_BAUELEMENTE_GMBH case 196: return KnxManufacturer_M_STENGLER_GESELLSCHAFT case 197: return KnxManufacturer_M_SCHNEIDER_ELECTRIC_MG case 198: return KnxManufacturer_M_KNX_ASSOCIATION case 199: return KnxManufacturer_M_VIVO case 2: return KnxManufacturer_M_ABB case 20: return KnxManufacturer_M_GLAMOX_AS case 200: return KnxManufacturer_M_HUGO_MUELLER_GMBH_AND_CO_KG case 201: return KnxManufacturer_M_SIEMENS_HVAC case 202: return KnxManufacturer_M_APT case 203: return KnxManufacturer_M_HIGHDOM case 204: return KnxManufacturer_M_TOP_SERVICES case 205: return KnxManufacturer_M_AMBIHOME case 206: return KnxManufacturer_M_DATEC_ELECTRONIC_AG case 207: return KnxManufacturer_M_ABUS_SECURITY_CENTER case 208: return KnxManufacturer_M_LITE_PUTER case 209: return KnxManufacturer_M_TANTRON_ELECTRONIC case 21: return KnxManufacturer_M_DEHN_AND_SOEHNE case 210: return KnxManufacturer_M_INTERRA case 211: return KnxManufacturer_M_DKX_TECH case 212: return KnxManufacturer_M_VIATRON case 213: return KnxManufacturer_M_NAUTIBUS case 214: return KnxManufacturer_M_ON_SEMICONDUCTOR case 215: return KnxManufacturer_M_LONGCHUANG case 216: return KnxManufacturer_M_AIR_ON_AG case 217: return KnxManufacturer_M_IB_COMPANY_GMBH case 218: return KnxManufacturer_M_SATION_FACTORY case 219: return KnxManufacturer_M_AGENTILO_GMBH case 22: return KnxManufacturer_M_CRABTREE case 220: return KnxManufacturer_M_MAKEL_ELEKTRIK case 221: return KnxManufacturer_M_HELIOS_VENTILATOREN case 222: return KnxManufacturer_M_OTTO_SOLUTIONS_PTE_LTD case 223: return KnxManufacturer_M_AIRMASTER case 224: return KnxManufacturer_M_VALLOX_GMBH case 225: return KnxManufacturer_M_DALITEK case 226: return KnxManufacturer_M_ASIN case 227: return KnxManufacturer_M_BRIDGES_INTELLIGENCE_TECHNOLOGY_INC_ case 228: return KnxManufacturer_M_ARBONIA case 229: return KnxManufacturer_M_KERMI case 23: return KnxManufacturer_M_EVOKNX case 230: return KnxManufacturer_M_PROLUX case 231: return KnxManufacturer_M_CLICHOME case 232: return KnxManufacturer_M_COMMAX case 233: return KnxManufacturer_M_EAE case 234: return KnxManufacturer_M_TENSE case 235: return KnxManufacturer_M_SEYOUNG_ELECTRONICS case 236: return KnxManufacturer_M_LIFEDOMUS case 237: return KnxManufacturer_M_EUROTRONIC_TECHNOLOGY_GMBH case 238: return KnxManufacturer_M_TCI case 239: return KnxManufacturer_M_RISHUN_ELECTRONIC case 24: return KnxManufacturer_M_PAUL_HOCHKOEPPER case 240: return KnxManufacturer_M_ZIPATO case 241: return KnxManufacturer_M_CM_SECURITY_GMBH_AND_CO_KG case 242: return KnxManufacturer_M_QING_CABLES case 243: return KnxManufacturer_M_LABIO case 244: return KnxManufacturer_M_COSTER_TECNOLOGIE_ELETTRONICHE_S_P_A_ case 245: return KnxManufacturer_M_E_G_E case 246: return KnxManufacturer_M_NETXAUTOMATION case 247: return KnxManufacturer_M_TECALOR case 248: return KnxManufacturer_M_URMET_ELECTRONICS_HUIZHOU_LTD_ case 249: return KnxManufacturer_M_PEIYING_BUILDING_CONTROL case 25: return KnxManufacturer_M_ALTENBURGER_ELECTRONIC case 250: return KnxManufacturer_M_BPT_S_P_A__A_SOCIO_UNICO case 251: return KnxManufacturer_M_KANONTEC___KANONBUS case 252: return KnxManufacturer_M_ISER_TECH case 253: return KnxManufacturer_M_FINELINE case 254: return KnxManufacturer_M_CP_ELECTRONICS_LTD case 255: return KnxManufacturer_M_NIKO_SERVODAN_AS case 256: return KnxManufacturer_M_SIMON_309 case 257: return KnxManufacturer_M_GM_MODULAR_PVT__LTD_ case 258: return KnxManufacturer_M_FU_CHENG_INTELLIGENCE case 259: return KnxManufacturer_M_NEXKON case 26: return KnxManufacturer_M_GRAESSLIN case 260: return KnxManufacturer_M_FEEL_S_R_L case 261: return KnxManufacturer_M_NOT_ASSIGNED_314 case 262: return KnxManufacturer_M_SHENZHEN_FANHAI_SANJIANG_ELECTRONICS_CO___LTD_ case 263: return KnxManufacturer_M_JIUZHOU_GREEBLE case 264: return KnxManufacturer_M_AUMUELLER_AUMATIC_GMBH case 265: return KnxManufacturer_M_ETMAN_ELECTRIC case 266: return KnxManufacturer_M_BLACK_NOVA case 267: return KnxManufacturer_M_ZIDATECH_AG case 268: return KnxManufacturer_M_IDGS_BVBA case 269: return KnxManufacturer_M_DAKANIMO case 27: return KnxManufacturer_M_SIMON_42 case 270: return KnxManufacturer_M_TREBOR_AUTOMATION_AB case 271: return KnxManufacturer_M_SATEL_SP__Z_O_O_ case 272: return KnxManufacturer_M_RUSSOUND__INC_ case 273: return KnxManufacturer_M_MIDEA_HEATING_AND_VENTILATING_EQUIPMENT_CO_LTD case 274: return KnxManufacturer_M_CONSORZIO_TERRANUOVA case 275: return KnxManufacturer_M_WOLF_HEIZTECHNIK_GMBH case 276: return KnxManufacturer_M_SONTEC case 277: return KnxManufacturer_M_BELCOM_CABLES_LTD_ case 278: return KnxManufacturer_M_GUANGZHOU_SEAWIN_ELECTRICAL_TECHNOLOGIES_CO___LTD_ case 279: return KnxManufacturer_M_ACREL case 28: return KnxManufacturer_M_VIMAR case 280: return KnxManufacturer_M_FRANKE_AQUAROTTER_GMBH case 281: return KnxManufacturer_M_ORION_SYSTEMS case 282: return KnxManufacturer_M_SCHRACK_TECHNIK_GMBH case 283: return KnxManufacturer_M_INSPRID case 284: return KnxManufacturer_M_SUNRICHER case 285: return KnxManufacturer_M_MENRED_AUTOMATION_SYSTEMSHANGHAI_CO__LTD_ case 286: return KnxManufacturer_M_AUREX case 287: return KnxManufacturer_M_JOSEF_BARTHELME_GMBH_AND_CO__KG case 288: return KnxManufacturer_M_ARCHITECTURE_NUMERIQUE case 289: return KnxManufacturer_M_UP_GROUP case 29: return KnxManufacturer_M_MOELLER_GEBAEUDEAUTOMATION_KG case 290: return KnxManufacturer_M_TEKNOS_AVINNO case 291: return KnxManufacturer_M_NINGBO_DOOYA_MECHANIC_AND_ELECTRONIC_TECHNOLOGY case 292: return KnxManufacturer_M_THERMOKON_SENSORTECHNIK_GMBH case 293: return KnxManufacturer_M_BELIMO_AUTOMATION_AG case 294: return KnxManufacturer_M_ZEHNDER_GROUP_INTERNATIONAL_AG case 295: return KnxManufacturer_M_SKS_KINKEL_ELEKTRONIK case 296: return KnxManufacturer_M_ECE_WURMITZER_GMBH case 297: return KnxManufacturer_M_LARS case 298: return KnxManufacturer_M_URC case 299: return KnxManufacturer_M_LIGHTCONTROL case 3: return KnxManufacturer_M_ALBRECHT_JUNG case 30: return KnxManufacturer_M_ELTAKO case 300: return KnxManufacturer_M_SHENZHEN_YM case 301: return KnxManufacturer_M_MEAN_WELL_ENTERPRISES_CO__LTD_ case 302: return KnxManufacturer_M_OSIX case 303: return KnxManufacturer_M_AYPRO_TECHNOLOGY case 304: return KnxManufacturer_M_HEFEI_ECOLITE_SOFTWARE case 305: return KnxManufacturer_M_ENNO case 306: return KnxManufacturer_M_OHOSURE case 307: return KnxManufacturer_M_GAREFOWL case 308: return KnxManufacturer_M_GEZE case 309: return KnxManufacturer_M_LG_ELECTRONICS_INC_ case 31: return KnxManufacturer_M_BOSCH_SIEMENS_HAUSHALTSGERAETE case 310: return KnxManufacturer_M_SMC_INTERIORS case 311: return KnxManufacturer_M_NOT_ASSIGNED_364 case 312: return KnxManufacturer_M_SCS_CABLE case 313: return KnxManufacturer_M_HOVAL case 314: return KnxManufacturer_M_CANST case 315: return KnxManufacturer_M_HANGZHOU_BERLIN case 316: return KnxManufacturer_M_EVN_LICHTTECHNIK case 317: return KnxManufacturer_M_RUTEC case 318: return KnxManufacturer_M_FINDER case 319: return KnxManufacturer_M_FUJITSU_GENERAL_LIMITED case 32: return KnxManufacturer_M_RITTO_GMBHANDCO_KG case 320: return KnxManufacturer_M_ZF_FRIEDRICHSHAFEN_AG case 321: return KnxManufacturer_M_CREALED case 322: return KnxManufacturer_M_MILES_MAGIC_AUTOMATION_PRIVATE_LIMITED case 323: return KnxManufacturer_M_EPlus case 324: return KnxManufacturer_M_ITALCOND case 325: return KnxManufacturer_M_SATION case 326: return KnxManufacturer_M_NEWBEST case 327: return KnxManufacturer_M_GDS_DIGITAL_SYSTEMS case 328: return KnxManufacturer_M_IDDERO case 329: return KnxManufacturer_M_MBNLED case 33: return KnxManufacturer_M_POWER_CONTROLS case 330: return KnxManufacturer_M_VITRUM case 331: return KnxManufacturer_M_EKEY_BIOMETRIC_SYSTEMS_GMBH case 332: return KnxManufacturer_M_AMC case 333: return KnxManufacturer_M_TRILUX_GMBH_AND_CO__KG case 334: return KnxManufacturer_M_WEXCEDO case 335: return KnxManufacturer_M_VEMER_SPA case 336: return KnxManufacturer_M_ALEXANDER_BUERKLE_GMBH_AND_CO_KG case 337: return KnxManufacturer_M_CITRON case 338: return KnxManufacturer_M_SHENZHEN_HEGUANG case 339: return KnxManufacturer_M_NOT_ASSIGNED_392 case 34: return KnxManufacturer_M_ZUMTOBEL case 340: return KnxManufacturer_M_TRANE_B_V_B_A case 341: return KnxManufacturer_M_CAREL case 342: return KnxManufacturer_M_PROLITE_CONTROLS case 343: return KnxManufacturer_M_BOSMER case 344: return KnxManufacturer_M_EUCHIPS case 345: return KnxManufacturer_M_CONNECT_THINKA_CONNECT case 346: return KnxManufacturer_M_PEAKNX_A_DOGAWIST_COMPANY case 347: return KnxManufacturer_M_ACEMATIC case 348: return KnxManufacturer_M_ELAUSYS case 349: return KnxManufacturer_M_ITK_ENGINEERING_AG case 35: return KnxManufacturer_M_PHOENIX_CONTACT case 350: return KnxManufacturer_M_INTEGRA_METERING_AG case 351: return KnxManufacturer_M_FMS_HOSPITALITY_PTE_LTD case 352: return KnxManufacturer_M_NUVO case 353: return KnxManufacturer_M_U__LUX_GMBH case 354: return KnxManufacturer_M_BRUMBERG_LEUCHTEN case 355: return KnxManufacturer_M_LIME case 356: return KnxManufacturer_M_GREAT_EMPIRE_INTERNATIONAL_GROUP_CO___LTD_ case 357: return KnxManufacturer_M_KAVOSHPISHRO_ASIA case 358: return KnxManufacturer_M_V2_SPA case 359: return KnxManufacturer_M_JOHNSON_CONTROLS case 36: return KnxManufacturer_M_WAGO_KONTAKTTECHNIK case 360: return KnxManufacturer_M_ARKUD case 361: return KnxManufacturer_M_IRIDIUM_LTD_ case 362: return KnxManufacturer_M_BSMART case 363: return KnxManufacturer_M_BAB_TECHNOLOGIE_GMBH case 364: return KnxManufacturer_M_NICE_SPA case 365: return KnxManufacturer_M_REDFISH_GROUP_PTY_LTD case 366: return KnxManufacturer_M_SABIANA_SPA case 367: return KnxManufacturer_M_UBEE_INTERACTIVE_EUROPE case 368: return KnxManufacturer_M_REXEL case 369: return KnxManufacturer_M_GES_TEKNIK_A_S_ case 37: return KnxManufacturer_M_KNXPRESSO case 370: return KnxManufacturer_M_AVE_S_P_A_ case 371: return KnxManufacturer_M_ZHUHAI_LTECH_TECHNOLOGY_CO___LTD_ case 372: return KnxManufacturer_M_ARCOM case 373: return KnxManufacturer_M_VIA_TECHNOLOGIES__INC_ case 374: return KnxManufacturer_M_FEELSMART_ case 375: return KnxManufacturer_M_SUPCON case 376: return KnxManufacturer_M_MANIC case 377: return KnxManufacturer_M_TDE_GMBH case 378: return KnxManufacturer_M_NANJING_SHUFAN_INFORMATION_TECHNOLOGY_CO__LTD_ case 379: return KnxManufacturer_M_EWTECH case 38: return KnxManufacturer_M_WIELAND_ELECTRIC case 380: return KnxManufacturer_M_KLUGER_AUTOMATION_GMBH case 381: return KnxManufacturer_M_JOONGANG_CONTROL case 382: return KnxManufacturer_M_GREENCONTROLS_TECHNOLOGY_SDN__BHD_ case 383: return KnxManufacturer_M_IME_S_P_A_ case 384: return KnxManufacturer_M_SICHUAN_HAODING case 385: return KnxManufacturer_M_MINDJAGA_LTD_ case 386: return KnxManufacturer_M_RUILI_SMART_CONTROL case 387: return KnxManufacturer_M_CODESYS_GMBH case 388: return KnxManufacturer_M_MOORGEN_DEUTSCHLAND_GMBH case 389: return KnxManufacturer_M_CULLMANN_TECH case 39: return KnxManufacturer_M_HERMANN_KLEINHUIS case 390: return KnxManufacturer_M_MERCK_WINDOW_TECHNOLOGIES_B_V_ case 391: return KnxManufacturer_M_ABEGO case 392: return KnxManufacturer_M_MYGEKKO case 393: return KnxManufacturer_M_ERGO3_SARL case 394: return KnxManufacturer_M_STMICROELECTRONICS_INTERNATIONAL_N_V_ case 395: return KnxManufacturer_M_CJC_SYSTEMS case 396: return KnxManufacturer_M_SUDOKU case 397: return KnxManufacturer_M_AZ_E_LITE_PTE_LTD case 398: return KnxManufacturer_M_ARLIGHT case 399: return KnxManufacturer_M_GRUENBECK_WASSERAUFBEREITUNG_GMBH case 4: return KnxManufacturer_M_BTICINO case 40: return KnxManufacturer_M_STIEBEL_ELTRON case 400: return KnxManufacturer_M_MODULE_ELECTRONIC case 401: return KnxManufacturer_M_KOPLAT case 402: return KnxManufacturer_M_GUANGZHOU_LETOUR_LIFE_TECHNOLOGY_CO___LTD case 403: return KnxManufacturer_M_ILEVIA case 404: return KnxManufacturer_M_LN_SYSTEMTEQ case 405: return KnxManufacturer_M_HISENSE_SMARTHOME case 406: return KnxManufacturer_M_FLINK_AUTOMATION_SYSTEM case 407: return KnxManufacturer_M_XXTER_BV case 408: return KnxManufacturer_M_LYNXUS_TECHNOLOGY case 409: return KnxManufacturer_M_ROBOT_S_A_ case 41: return KnxManufacturer_M_TEHALIT case 410: return KnxManufacturer_M_SHENZHEN_ATTE_SMART_LIFE_CO__LTD_ case 411: return KnxManufacturer_M_NOBLESSE case 412: return KnxManufacturer_M_ADVANCED_DEVICES case 413: return KnxManufacturer_M_ATRINA_BUILDING_AUTOMATION_CO__LTD case 414: return KnxManufacturer_M_GUANGDONG_DAMING_LAFFEY_ELECTRIC_CO___LTD_ case 415: return KnxManufacturer_M_WESTERSTRAND_URFABRIK_AB case 416: return KnxManufacturer_M_CONTROL4_CORPORATE case 417: return KnxManufacturer_M_ONTROL case 418: return KnxManufacturer_M_STARNET case 419: return KnxManufacturer_M_BETA_CAVI case 42: return KnxManufacturer_M_THEBEN_AG case 420: return KnxManufacturer_M_EASEMORE case 421: return KnxManufacturer_M_VIVALDI_SRL case 422: return KnxManufacturer_M_GREE_ELECTRIC_APPLIANCES_INC__OF_ZHUHAI case 423: return KnxManufacturer_M_HWISCON case 424: return KnxManufacturer_M_SHANGHAI_ELECON_INTELLIGENT_TECHNOLOGY_CO___LTD_ case 425: return KnxManufacturer_M_KAMPMANN case 426: return KnxManufacturer_M_IMPOLUX_GMBH_LEDIMAX case 427: return KnxManufacturer_M_EVAUX case 428: return KnxManufacturer_M_WEBRO_CABLES_AND_CONNECTORS_LIMITED case 429: return KnxManufacturer_M_SHANGHAI_E_TECH_SOLUTION case 43: return KnxManufacturer_M_WILHELM_RUTENBECK case 430: return KnxManufacturer_M_GUANGZHOU_HOKO_ELECTRIC_CO__LTD_ case 431: return KnxManufacturer_M_LAMMIN_HIGH_TECH_CO__LTD case 432: return KnxManufacturer_M_SHENZHEN_MERRYTEK_TECHNOLOGY_CO___LTD case 433: return KnxManufacturer_M_I_LUXUS case 434: return KnxManufacturer_M_ELMOS_SEMICONDUCTOR_AG case 435: return KnxManufacturer_M_EMCOM_TECHNOLOGY_INC case 436: return KnxManufacturer_M_PROJECT_INNOVATIONS_GMBH case 437: return KnxManufacturer_M_ITC case 438: return KnxManufacturer_M_ABB_LV_INSTALLATION_MATERIALS_COMPANY_LTD__BEIJING case 439: return KnxManufacturer_M_MAICO case 44: return KnxManufacturer_M_WINKHAUS case 440: return KnxManufacturer_M_ELAN_SRL case 441: return KnxManufacturer_M_MINHHA_TECHNOLOGY_CO__LTD case 442: return KnxManufacturer_M_ZHEJIANG_TIANJIE_INDUSTRIAL_CORP_ case 443: return KnxManufacturer_M_IAUTOMATION_PTY_LIMITED case 444: return KnxManufacturer_M_EXTRON case 445: return KnxManufacturer_M_FREEDOMPRO case 446: return KnxManufacturer_M_ONEHOME case 447: return KnxManufacturer_M_EOS_SAUNATECHNIK_GMBH case 448: return KnxManufacturer_M_KUSATEK_GMBH case 449: return KnxManufacturer_M_EISBAER_SCADA case 45: return KnxManufacturer_M_ROBERT_BOSCH case 450: return KnxManufacturer_M_AUTOMATISMI_BENINCA_S_P_A_ case 451: return KnxManufacturer_M_BLENDOM case 452: return KnxManufacturer_M_MADEL_AIR_TECHNICAL_DIFFUSION case 453: return KnxManufacturer_M_NIKO case 454: return KnxManufacturer_M_BOSCH_REXROTH_AG case 455: return KnxManufacturer_M_CANDM_PRODUCTS case 456: return KnxManufacturer_M_HOERMANN_KG_VERKAUFSGESELLSCHAFT case 457: return KnxManufacturer_M_SHANGHAI_RAJAYASA_CO__LTD case 458: return KnxManufacturer_M_SUZUKI case 459: return KnxManufacturer_M_SILENT_GLISS_INTERNATIONAL_LTD_ case 46: return KnxManufacturer_M_SOMFY case 460: return KnxManufacturer_M_BEE_CONTROLS_ADGSC_GROUP case 461: return KnxManufacturer_M_XDTECGMBH case 462: return KnxManufacturer_M_OSRAM case 463: return KnxManufacturer_M_LEBENOR case 464: return KnxManufacturer_M_AUTOMANENG case 465: return KnxManufacturer_M_HONEYWELL_AUTOMATION_SOLUTION_CONTROLCHINA case 466: return KnxManufacturer_M_HANGZHOU_BINTHEN_INTELLIGENCE_TECHNOLOGY_CO__LTD case 467: return KnxManufacturer_M_ETA_HEIZTECHNIK case 468: return KnxManufacturer_M_DIVUS_GMBH case 469: return KnxManufacturer_M_NANJING_TAIJIESAI_INTELLIGENT_TECHNOLOGY_CO__LTD_ case 47: return KnxManufacturer_M_WOERTZ case 470: return KnxManufacturer_M_LUNATONE case 471: return KnxManufacturer_M_ZHEJIANG_SCTECH_BUILDING_INTELLIGENT case 472: return KnxManufacturer_M_FOSHAN_QITE_TECHNOLOGY_CO___LTD_ case 473: return KnxManufacturer_M_NOKE case 474: return KnxManufacturer_M_LANDCOM case 475: return KnxManufacturer_M_STORK_AS case 476: return KnxManufacturer_M_HANGZHOU_SHENDU_TECHNOLOGY_CO___LTD_ case 477: return KnxManufacturer_M_COOLAUTOMATION case 478: return KnxManufacturer_M_APRSTERN case 479: return KnxManufacturer_M_SONNEN case 48: return KnxManufacturer_M_VIESSMANN_WERKE case 480: return KnxManufacturer_M_DNAKE case 481: return KnxManufacturer_M_NEUBERGER_GEBAEUDEAUTOMATION_GMBH case 482: return KnxManufacturer_M_STILIGER case 483: return KnxManufacturer_M_BERGHOF_AUTOMATION_GMBH case 484: return KnxManufacturer_M_TOTAL_AUTOMATION_AND_CONTROLS_GMBH case 485: return KnxManufacturer_M_DOVIT case 486: return KnxManufacturer_M_INSTALIGHTING_GMBH case 487: return KnxManufacturer_M_UNI_TEC case 488: return KnxManufacturer_M_CASATUNES case 489: return KnxManufacturer_M_EMT case 49: return KnxManufacturer_M_IMI_HYDRONIC_ENGINEERING case 490: return KnxManufacturer_M_SENFFICIENT case 491: return KnxManufacturer_M_AUROLITE_ELECTRICAL_PANYU_GUANGZHOU_LIMITED case 492: return KnxManufacturer_M_ABB_XIAMEN_SMART_TECHNOLOGY_CO___LTD_ case 493: return KnxManufacturer_M_SAMSON_ELECTRIC_WIRE case 494: return KnxManufacturer_M_T_TOUCHING case 495: return KnxManufacturer_M_CORE_SMART_HOME case 496: return KnxManufacturer_M_GREENCONNECT_SOLUTIONS_SA case 497: return KnxManufacturer_M_ELETTRONICA_CONDUTTORI case 498: return KnxManufacturer_M_MKFC case 499: return KnxManufacturer_M_AUTOMATIONPlus case 5: return KnxManufacturer_M_BERKER case 50: return KnxManufacturer_M_JOH__VAILLANT case 500: return KnxManufacturer_M_BLUE_AND_RED case 501: return KnxManufacturer_M_FROGBLUE case 502: return KnxManufacturer_M_SAVESOR case 503: return KnxManufacturer_M_APP_TECH case 504: return KnxManufacturer_M_SENSORTEC_AG case 505: return KnxManufacturer_M_NYSA_TECHNOLOGY_AND_SOLUTIONS case 506: return KnxManufacturer_M_FARADITE case 507: return KnxManufacturer_M_OPTIMUS case 508: return KnxManufacturer_M_KTS_S_R_L_ case 509: return KnxManufacturer_M_RAMCRO_SPA case 51: return KnxManufacturer_M_AMP_DEUTSCHLAND case 510: return KnxManufacturer_M_WUHAN_WISECREATE_UNIVERSE_TECHNOLOGY_CO___LTD case 511: return KnxManufacturer_M_BEMI_SMART_HOME_LTD case 512: return KnxManufacturer_M_ARDOMUS case 513: return KnxManufacturer_M_CHANGXING case 514: return KnxManufacturer_M_E_CONTROLS case 515: return KnxManufacturer_M_AIB_TECHNOLOGY case 516: return KnxManufacturer_M_NVC case 517: return KnxManufacturer_M_KBOX case 518: return KnxManufacturer_M_CNS case 519: return KnxManufacturer_M_TYBA case 52: return KnxManufacturer_M_BOSCH_THERMOTECHNIK_GMBH case 520: return KnxManufacturer_M_ATREL case 521: return KnxManufacturer_M_SIMON_ELECTRIC_CHINA_CO___LTD case 522: return KnxManufacturer_M_KORDZ_GROUP case 523: return KnxManufacturer_M_ND_ELECTRIC case 524: return KnxManufacturer_M_CONTROLIUM case 525: return KnxManufacturer_M_FAMO_GMBH_AND_CO__KG case 526: return KnxManufacturer_M_CDN_SMART case 527: return KnxManufacturer_M_HESTON case 528: return KnxManufacturer_M_ESLA_CONEXIONES_S_L_ case 529: return KnxManufacturer_M_WEISHAUPT case 53: return KnxManufacturer_M_SEF___ECOTEC case 530: return KnxManufacturer_M_ASTRUM_TECHNOLOGY case 531: return KnxManufacturer_M_WUERTH_ELEKTRONIK_STELVIO_KONTEK_S_P_A_ case 532: return KnxManufacturer_M_NANOTECO_CORPORATION case 533: return KnxManufacturer_M_NIETIAN case 534: return KnxManufacturer_M_SUMSIR case 535: return KnxManufacturer_M_ORBIS_TECNOLOGIA_ELECTRICA_SA case 536: return KnxManufacturer_M_NANJING_ZHONGYI_IOT_TECHNOLOGY_CO___LTD_ case 537: return KnxManufacturer_M_ANLIPS case 538: return KnxManufacturer_M_GUANGDONG_PAK_CORPORATION_CO___LTD case 539: return KnxManufacturer_M_BVK_TECHNOLOGY case 54: return KnxManufacturer_M_DORMA_GMBH_Plus_CO__KG case 540: return KnxManufacturer_M_SOLOMIO_SRL case 541: return KnxManufacturer_M_DOMOTICA_LABS case 542: return KnxManufacturer_M_NVC_INTERNATIONAL case 543: return KnxManufacturer_M_BA case 544: return KnxManufacturer_M_IRIS_CERAMICA_GROUP case 545: return KnxManufacturer_M_WIREEO case 546: return KnxManufacturer_M_NVCLIGHTING case 547: return KnxManufacturer_M_JINAN_TIAN_DA_SHENG_INFORMATION_TECHNOLOGY_CO_ case 548: return KnxManufacturer_M_ARMITI_TRADING case 549: return KnxManufacturer_M_ELEK case 55: return KnxManufacturer_M_WINDOWMASTER_AS case 550: return KnxManufacturer_M_ACCORDIA_SA case 551: return KnxManufacturer_M_OURICAN case 552: return KnxManufacturer_M_INLIWOSE case 553: return KnxManufacturer_M_BOSCH_SHANGHAI_SMART_LIFE_TECHNOLOGY_LTD_ case 554: return KnxManufacturer_M_SHK_KNX case 555: return KnxManufacturer_M_AMPIO case 556: return KnxManufacturer_M_MINGXING_WISDOM case 557: return KnxManufacturer_M_ALTEN_SW_GMBH case 558: return KnxManufacturer_M_ABB___RESERVED case 559: return KnxManufacturer_M_BUSCH_JAEGER_ELEKTRO___RESERVED case 56: return KnxManufacturer_M_WALTHER_WERKE case 57: return KnxManufacturer_M_ORAS case 58: return KnxManufacturer_M_DAETWYLER case 59: return KnxManufacturer_M_ELECTRAK case 6: return KnxManufacturer_M_BUSCH_JAEGER_ELEKTRO case 60: return KnxManufacturer_M_TECHEM case 61: return KnxManufacturer_M_SCHNEIDER_ELECTRIC_INDUSTRIES_SAS case 62: return KnxManufacturer_M_WHD_WILHELM_HUBER_Plus_SOEHNE case 63: return KnxManufacturer_M_BISCHOFF_ELEKTRONIK case 64: return KnxManufacturer_M_JEPAZ case 65: return KnxManufacturer_M_RTS_AUTOMATION case 66: return KnxManufacturer_M_EIBMARKT_GMBH case 67: return KnxManufacturer_M_WAREMA_RENKHOFF_SE case 68: return KnxManufacturer_M_EELECTRON case 69: return KnxManufacturer_M_BELDEN_WIRE_AND_CABLE_B_V_ case 7: return KnxManufacturer_M_GIRA_GIERSIEPEN case 70: return KnxManufacturer_M_BECKER_ANTRIEBE_GMBH case 71: return KnxManufacturer_M_J_STEHLEPlusSOEHNE_GMBH case 72: return KnxManufacturer_M_AGFEO case 73: return KnxManufacturer_M_ZENNIO case 74: return KnxManufacturer_M_TAPKO_TECHNOLOGIES case 75: return KnxManufacturer_M_HDL case 76: return KnxManufacturer_M_UPONOR case 77: return KnxManufacturer_M_SE_LIGHTMANAGEMENT_AG case 78: return KnxManufacturer_M_ARCUS_EDS case 79: return KnxManufacturer_M_INTESIS case 8: return KnxManufacturer_M_HAGER_ELECTRO case 80: return KnxManufacturer_M_HERHOLDT_CONTROLS_SRL case 81: return KnxManufacturer_M_NIKO_ZUBLIN case 82: return KnxManufacturer_M_DURABLE_TECHNOLOGIES case 83: return KnxManufacturer_M_INNOTEAM case 84: return KnxManufacturer_M_ISE_GMBH case 85: return KnxManufacturer_M_TEAM_FOR_TRONICS case 86: return KnxManufacturer_M_CIAT case 87: return KnxManufacturer_M_REMEHA_BV case 88: return KnxManufacturer_M_ESYLUX case 89: return KnxManufacturer_M_BASALTE case 9: return KnxManufacturer_M_INSTA_GMBH case 90: return KnxManufacturer_M_VESTAMATIC case 91: return KnxManufacturer_M_MDT_TECHNOLOGIES case 92: return KnxManufacturer_M_WARENDORFER_KUECHEN_GMBH case 93: return KnxManufacturer_M_VIDEO_STAR case 94: return KnxManufacturer_M_SITEK case 95: return KnxManufacturer_M_CONTROLTRONIC case 96: return KnxManufacturer_M_FUNCTION_TECHNOLOGY case 97: return KnxManufacturer_M_AMX case 98: return KnxManufacturer_M_ELDAT case 99: return KnxManufacturer_M_PANASONIC } return 0 } func KnxManufacturerByName(value string) KnxManufacturer { switch value { case "M_UNKNOWN": return KnxManufacturer_M_UNKNOWN case "M_SIEMENS": return KnxManufacturer_M_SIEMENS case "M_LEGRAND_APPAREILLAGE_ELECTRIQUE": return KnxManufacturer_M_LEGRAND_APPAREILLAGE_ELECTRIQUE case "M_PULSE_TECHNOLOGIES": return KnxManufacturer_M_PULSE_TECHNOLOGIES case "M_CRESTRON": return KnxManufacturer_M_CRESTRON case "M_STEINEL_PROFESSIONAL": return KnxManufacturer_M_STEINEL_PROFESSIONAL case "M_BILTON_LED_LIGHTING": return KnxManufacturer_M_BILTON_LED_LIGHTING case "M_DENRO_AG": return KnxManufacturer_M_DENRO_AG case "M_GEPRO": return KnxManufacturer_M_GEPRO case "M_PREUSSEN_AUTOMATION": return KnxManufacturer_M_PREUSSEN_AUTOMATION case "M_ZOPPAS_INDUSTRIES": return KnxManufacturer_M_ZOPPAS_INDUSTRIES case "M_MACTECH": return KnxManufacturer_M_MACTECH case "M_TECHNO_TREND": return KnxManufacturer_M_TECHNO_TREND case "M_MERTEN": return KnxManufacturer_M_MERTEN case "M_FS_CABLES": return KnxManufacturer_M_FS_CABLES case "M_DELTA_DORE": return KnxManufacturer_M_DELTA_DORE case "M_EISSOUND": return KnxManufacturer_M_EISSOUND case "M_CISCO": return KnxManufacturer_M_CISCO case "M_DINUY": return KnxManufacturer_M_DINUY case "M_IKNIX": return KnxManufacturer_M_IKNIX case "M_RADEMACHER_GERAETE_ELEKTRONIK_GMBH": return KnxManufacturer_M_RADEMACHER_GERAETE_ELEKTRONIK_GMBH case "M_EGI_ELECTROACUSTICA_GENERAL_IBERICA": return KnxManufacturer_M_EGI_ELECTROACUSTICA_GENERAL_IBERICA case "M_BES___INGENIUM": return KnxManufacturer_M_BES___INGENIUM case "M_ELABNET": return KnxManufacturer_M_ELABNET case "M_ABB_SPA_SACE_DIVISION": return KnxManufacturer_M_ABB_SPA_SACE_DIVISION case "M_BLUMOTIX": return KnxManufacturer_M_BLUMOTIX case "M_HUNTER_DOUGLAS": return KnxManufacturer_M_HUNTER_DOUGLAS case "M_APRICUM": return KnxManufacturer_M_APRICUM case "M_TIANSU_AUTOMATION": return KnxManufacturer_M_TIANSU_AUTOMATION case "M_BUBENDORFF": return KnxManufacturer_M_BUBENDORFF case "M_MBS_GMBH": return KnxManufacturer_M_MBS_GMBH case "M_ENERTEX_BAYERN_GMBH": return KnxManufacturer_M_ENERTEX_BAYERN_GMBH case "M_BMS": return KnxManufacturer_M_BMS case "M_SINAPSI": return KnxManufacturer_M_SINAPSI case "M_EMBEDDED_SYSTEMS_SIA": return KnxManufacturer_M_EMBEDDED_SYSTEMS_SIA case "M_SIEDLE_AND_SOEHNE": return KnxManufacturer_M_SIEDLE_AND_SOEHNE case "M_KNX1": return KnxManufacturer_M_KNX1 case "M_TOKKA": return KnxManufacturer_M_TOKKA case "M_NANOSENSE": return KnxManufacturer_M_NANOSENSE case "M_PEAR_AUTOMATION_GMBH": return KnxManufacturer_M_PEAR_AUTOMATION_GMBH case "M_DGA": return KnxManufacturer_M_DGA case "M_LUTRON": return KnxManufacturer_M_LUTRON case "M_AIRZONE___ALTRA": return KnxManufacturer_M_AIRZONE___ALTRA case "M_LITHOSS_DESIGN_SWITCHES": return KnxManufacturer_M_LITHOSS_DESIGN_SWITCHES case "M_THREEATEL": return KnxManufacturer_M_THREEATEL case "M_PHILIPS_CONTROLS": return KnxManufacturer_M_PHILIPS_CONTROLS case "M_EBERLE": return KnxManufacturer_M_EBERLE case "M_VELUX_AS": return KnxManufacturer_M_VELUX_AS case "M_LOYTEC": return KnxManufacturer_M_LOYTEC case "M_EKINEX_S_P_A_": return KnxManufacturer_M_EKINEX_S_P_A_ case "M_SIRLAN_TECHNOLOGIES": return KnxManufacturer_M_SIRLAN_TECHNOLOGIES case "M_PROKNX_SAS": return KnxManufacturer_M_PROKNX_SAS case "M_IT_GMBH": return KnxManufacturer_M_IT_GMBH case "M_RENSON": return KnxManufacturer_M_RENSON case "M_HEP_GROUP": return KnxManufacturer_M_HEP_GROUP case "M_BALMART":
return KnxManufacturer_M_GEWISS case "M_SCHENKER_STOREN_AG": return KnxManufacturer_M_SCHENKER_STOREN_AG case "M_ALGODUE_ELETTRONICA_S_R_L_": return KnxManufacturer_M_ALGODUE_ELETTRONICA_S_R_L_ case "M_ABB_FRANCE": return KnxManufacturer_M_ABB_FRANCE case "M_MAINTRONIC": return KnxManufacturer_M_MAINTRONIC case "M_VANTAGE": return KnxManufacturer_M_VANTAGE case "M_FORESIS": return KnxManufacturer_M_FORESIS case "M_RESEARCH_AND_PRODUCTION_ASSOCIATION_SEM": return KnxManufacturer_M_RESEARCH_AND_PRODUCTION_ASSOCIATION_SEM case "M_WEINZIERL_ENGINEERING_GMBH": return KnxManufacturer_M_WEINZIERL_ENGINEERING_GMBH case "M_MOEHLENHOFF_WAERMETECHNIK_GMBH": return KnxManufacturer_M_MOEHLENHOFF_WAERMETECHNIK_GMBH case "M_PKC_GROUP_OYJ": return KnxManufacturer_M_PKC_GROUP_OYJ case "M_ALBERT_ACKERMANN": return KnxManufacturer_M_ALBERT_ACKERMANN case "M_B_E_G_": return KnxManufacturer_M_B_E_G_ case "M_ELSNER_ELEKTRONIK_GMBH": return KnxManufacturer_M_ELSNER_ELEKTRONIK_GMBH case "M_SIEMENS_BUILDING_TECHNOLOGIES_HKCHINA_LTD_": return KnxManufacturer_M_SIEMENS_BUILDING_TECHNOLOGIES_HKCHINA_LTD_ case "M_EUTRAC": return KnxManufacturer_M_EUTRAC case "M_GUSTAV_HENSEL_GMBH_AND_CO__KG": return KnxManufacturer_M_GUSTAV_HENSEL_GMBH_AND_CO__KG case "M_GARO_AB": return KnxManufacturer_M_GARO_AB case "M_WALDMANN_LICHTTECHNIK": return KnxManufacturer_M_WALDMANN_LICHTTECHNIK case "M_SCHUECO": return KnxManufacturer_M_SCHUECO case "M_EMU": return KnxManufacturer_M_EMU case "M_JNET_SYSTEMS_AG": return KnxManufacturer_M_JNET_SYSTEMS_AG case "M_SCHUPA_GMBH": return KnxManufacturer_M_SCHUPA_GMBH case "M_TOTAL_SOLUTION_GMBH": return KnxManufacturer_M_TOTAL_SOLUTION_GMBH case "M_O_Y_L__ELECTRONICS": return KnxManufacturer_M_O_Y_L__ELECTRONICS case "M_GALAX_SYSTEM": return KnxManufacturer_M_GALAX_SYSTEM case "M_DISCH": return KnxManufacturer_M_DISCH case "M_AUCOTEAM": return KnxManufacturer_M_AUCOTEAM case "M_LUXMATE_CONTROLS": return KnxManufacturer_M_LUXMATE_CONTROLS case "M_DANFOSS": return KnxManufacturer_M_DANFOSS case "M_AST_GMBH": return KnxManufacturer_M_AST_GMBH case "M_WILA_LEUCHTEN": return KnxManufacturer_M_WILA_LEUCHTEN case "M_BPlusB_AUTOMATIONS__UND_STEUERUNGSTECHNIK": return KnxManufacturer_M_BPlusB_AUTOMATIONS__UND_STEUERUNGSTECHNIK case "M_ABB_SCHWEIZ": return KnxManufacturer_M_ABB_SCHWEIZ case "M_LINGG_AND_JANKE": return KnxManufacturer_M_LINGG_AND_JANKE case "M_SAUTER": return KnxManufacturer_M_SAUTER case "M_SIMU": return KnxManufacturer_M_SIMU case "M_THEBEN_HTS_AG": return KnxManufacturer_M_THEBEN_HTS_AG case "M_AMANN_GMBH": return KnxManufacturer_M_AMANN_GMBH case "M_BERG_ENERGIEKONTROLLSYSTEME_GMBH": return KnxManufacturer_M_BERG_ENERGIEKONTROLLSYSTEME_GMBH case "M_HUEPPE_FORM_SONNENSCHUTZSYSTEME_GMBH": return KnxManufacturer_M_HUEPPE_FORM_SONNENSCHUTZSYSTEME_GMBH case "M_OVENTROP_KG": return KnxManufacturer_M_OVENTROP_KG case "M_GRIESSER_AG": return KnxManufacturer_M_GRIESSER_AG case "M_IPAS_GMBH": return KnxManufacturer_M_IPAS_GMBH case "M_FELLER": return KnxManufacturer_M_FELLER case "M_ELERO_GMBH": return KnxManufacturer_M_ELERO_GMBH case "M_ARDAN_PRODUCTION_AND_INDUSTRIAL_CONTROLS_LTD_": return KnxManufacturer_M_ARDAN_PRODUCTION_AND_INDUSTRIAL_CONTROLS_LTD_ case "M_METEC_MESSTECHNIK_GMBH": return KnxManufacturer_M_METEC_MESSTECHNIK_GMBH case "M_ELKA_ELEKTRONIK_GMBH": return KnxManufacturer_M_ELKA_ELEKTRONIK_GMBH case "M_ELEKTROANLAGEN_D__NAGEL": return KnxManufacturer_M_ELEKTROANLAGEN_D__NAGEL case "M_TRIDONIC_BAUELEMENTE_GMBH": return KnxManufacturer_M_TRIDONIC_BAUELEMENTE_GMBH case "M_STENGLER_GESELLSCHAFT": return KnxManufacturer_M_STENGLER_GESELLSCHAFT case "M_SCHNEIDER_ELECTRIC_MG": return KnxManufacturer_M_SCHNEIDER_ELECTRIC_MG case "M_KNX_ASSOCIATION": return KnxManufacturer_M_KNX_ASSOCIATION case "M_VIVO": return KnxManufacturer_M_VIVO case "M_ABB": return KnxManufacturer_M_ABB case "M_GLAMOX_AS": return KnxManufacturer_M_GLAMOX_AS case "M_HUGO_MUELLER_GMBH_AND_CO_KG": return KnxManufacturer_M_HUGO_MUELLER_GMBH_AND_CO_KG case "M_SIEMENS_HVAC": return KnxManufacturer_M_SIEMENS_HVAC case "M_APT": return KnxManufacturer_M_APT case "M_HIGHDOM": return KnxManufacturer_M_HIGHDOM case "M_TOP_SERVICES": return KnxManufacturer_M_TOP_SERVICES case "M_AMBIHOME": return KnxManufacturer_M_AMBIHOME case "M_DATEC_ELECTRONIC_AG": return KnxManufacturer_M_DATEC_ELECTRONIC_AG case "M_ABUS_SECURITY_CENTER": return KnxManufacturer_M_ABUS_SECURITY_CENTER case "M_LITE_PUTER": return KnxManufacturer_M_LITE_PUTER case "M_TANTRON_ELECTRONIC": return KnxManufacturer_M_TANTRON_ELECTRONIC case "M_DEHN_AND_SOEHNE": return KnxManufacturer_M_DEHN_AND_SOEHNE case "M_INTERRA": return KnxManufacturer_M_INTERRA case "M_DKX_TECH": return KnxManufacturer_M_DKX_TECH case "M_VIATRON": return KnxManufacturer_M_VIATRON case "M_NAUTIBUS": return KnxManufacturer_M_NAUTIBUS case "M_ON_SEMICONDUCTOR": return KnxManufacturer_M_ON_SEMICONDUCTOR case "M_LONGCHUANG": return KnxManufacturer_M_LONGCHUANG case "M_AIR_ON_AG": return KnxManufacturer_M_AIR_ON_AG case "M_IB_COMPANY_GMBH": return KnxManufacturer_M_IB_COMPANY_GMBH case "M_SATION_FACTORY": return KnxManufacturer_M_SATION_FACTORY case "M_AGENTILO_GMBH": return KnxManufacturer_M_AGENTILO_GMBH case "M_CRABTREE": return KnxManufacturer_M_CRABTREE case "M_MAKEL_ELEKTRIK": return KnxManufacturer_M_MAKEL_ELEKTRIK case "M_HELIOS_VENTILATOREN": return KnxManufacturer_M_HELIOS_VENTILATOREN case "M_OTTO_SOLUTIONS_PTE_LTD": return KnxManufacturer_M_OTTO_SOLUTIONS_PTE_LTD case "M_AIRMASTER": return KnxManufacturer_M_AIRMASTER case "M_VALLOX_GMBH": return KnxManufacturer_M_VALLOX_GMBH case "M_DALITEK": return KnxManufacturer_M_DALITEK case "M_ASIN": return KnxManufacturer_M_ASIN case "M_BRIDGES_INTELLIGENCE_TECHNOLOGY_INC_": return KnxManufacturer_M_BRIDGES_INTELLIGENCE_TECHNOLOGY_INC_ case "M_ARBONIA": return KnxManufacturer_M_ARBONIA case "M_KERMI": return KnxManufacturer_M_KERMI case "M_EVOKNX": return KnxManufacturer_M_EVOKNX case "M_PROLUX": return KnxManufacturer_M_PROLUX case "M_CLICHOME": return KnxManufacturer_M_CLICHOME case "M_COMMAX": return KnxManufacturer_M_COMMAX case "M_EAE": return KnxManufacturer_M_EAE case "M_TENSE": return KnxManufacturer_M_TENSE case "M_SEYOUNG_ELECTRONICS": return KnxManufacturer_M_SEYOUNG_ELECTRONICS case "M_LIFEDOMUS": return KnxManufacturer_M_LIFEDOMUS case "M_EUROTRONIC_TECHNOLOGY_GMBH": return KnxManufacturer_M_EUROTRONIC_TECHNOLOGY_GMBH case "M_TCI": return KnxManufacturer_M_TCI case "M_RISHUN_ELECTRONIC": return KnxManufacturer_M_RISHUN_ELECTRONIC case "M_PAUL_HOCHKOEPPER": return KnxManufacturer_M_PAUL_HOCHKOEPPER case "M_ZIPATO": return KnxManufacturer_M_ZIPATO case "M_CM_SECURITY_GMBH_AND_CO_KG": return KnxManufacturer_M_CM_SECURITY_GMBH_AND_CO_KG case "M_QING_CABLES": return KnxManufacturer_M_QING_CABLES case "M_LABIO": return KnxManufacturer_M_LABIO case "M_COSTER_TECNOLOGIE_ELETTRONICHE_S_P_A_": return KnxManufacturer_M_COSTER_TECNOLOGIE_ELETTRONICHE_S_P_A_ case "M_E_G_E": return KnxManufacturer_M_E_G_E case "M_NETXAUTOMATION": return KnxManufacturer_M_NETXAUTOMATION case "M_TECALOR": return KnxManufacturer_M_TECALOR case "M_URMET_ELECTRONICS_HUIZHOU_LTD_": return KnxManufacturer_M_URMET_ELECTRONICS_HUIZHOU_LTD_ case "M_PEIYING_BUILDING_CONTROL": return KnxManufacturer_M_PEIYING_BUILDING_CONTROL case "M_ALTENBURGER_ELECTRONIC": return KnxManufacturer_M_ALTENBURGER_ELECTRONIC case "M_BPT_S_P_A__A_SOCIO_UNICO": return KnxManufacturer_M_BPT_S_P_A__A_SOCIO_UNICO case "M_KANONTEC___KANONBUS": return KnxManufacturer_M_KANONTEC___KANONBUS case "M_ISER_TECH": return KnxManufacturer_M_ISER_TECH case "M_FINELINE": return KnxManufacturer_M_FINELINE case "M_CP_ELECTRONICS_LTD": return KnxManufacturer_M_CP_ELECTRONICS_LTD case "M_NIKO_SERVODAN_AS": return KnxManufacturer_M_NIKO_SERVODAN_AS case "M_SIMON_309": return KnxManufacturer_M_SIMON_309 case "M_GM_MODULAR_PVT__LTD_": return KnxManufacturer_M_GM_MODULAR_PVT__LTD_ case "M_FU_CHENG_INTELLIGENCE": return KnxManufacturer_M_FU_CHENG_INTELLIGENCE case "M_NEXKON": return KnxManufacturer_M_NEXKON case "M_GRAESSLIN": return KnxManufacturer_M_GRAESSLIN case "M_FEEL_S_R_L": return KnxManufacturer_M_FEEL_S_R_L case "M_NOT_ASSIGNED_314": return KnxManufacturer_M_NOT_ASSIGNED_314 case "M_SHENZHEN_FANHAI_SANJIANG_ELECTRONICS_CO___LTD_": return KnxManufacturer_M_SHENZHEN_FANHAI_SANJIANG_ELECTRONICS_CO___LTD_ case "M_JIUZHOU_GREEBLE": return KnxManufacturer_M_JIUZHOU_GREEBLE case "M_AUMUELLER_AUMATIC_GMBH": return KnxManufacturer_M_AUMUELLER_AUMATIC_GMBH case "M_ETMAN_ELECTRIC": return KnxManufacturer_M_ETMAN_ELECTRIC case "M_BLACK_NOVA": return KnxManufacturer_M_BLACK_NOVA case "M_ZIDATECH_AG": return KnxManufacturer_M_ZIDATECH_AG case "M_IDGS_BVBA": return KnxManufacturer_M_IDGS_BVBA case "M_DAKANIMO": return KnxManufacturer_M_DAKANIMO case "M_SIMON_42": return KnxManufacturer_M_SIMON_42 case "M_TREBOR_AUTOMATION_AB": return KnxManufacturer_M_TREBOR_AUTOMATION_AB case "M_SATEL_SP__Z_O_O_": return KnxManufacturer_M_SATEL_SP__Z_O_O_ case "M_RUSSOUND__INC_": return KnxManufacturer_M_RUSSOUND__INC_ case "M_MIDEA_HEATING_AND_VENTILATING_EQUIPMENT_CO_LTD": return KnxManufacturer_M_MIDEA_HEATING_AND_VENTILATING_EQUIPMENT_CO_LTD case "M_CONSORZIO_TERRANUOVA": return KnxManufacturer_M_CONSORZIO_TERRANUOVA case "M_WOLF_HEIZTECHNIK_GMBH": return KnxManufacturer_M_WOLF_HEIZTECHNIK_GMBH case "M_SONTEC": return KnxManufacturer_M_SONTEC case "M_BELCOM_CABLES_LTD_": return KnxManufacturer_M_BELCOM_CABLES_LTD_ case "M_GUANGZHOU_SEAWIN_ELECTRICAL_TECHNOLOGIES_CO___LTD_": return KnxManufacturer_M_GUANGZHOU_SEAWIN_ELECTRICAL_TECHNOLOGIES_CO___LTD_ case "M_ACREL": return KnxManufacturer_M_ACREL case "M_VIMAR": return KnxManufacturer_M_VIMAR case "M_FRANKE_AQUAROTTER_GMBH": return KnxManufacturer_M_FRANKE_AQUAROTTER_GMBH case "M_ORION_SYSTEMS": return KnxManufacturer_M_ORION_SYSTEMS case "M_SCHRACK_TECHNIK_GMBH": return KnxManufacturer_M_SCHRACK_TECHNIK_GMBH case "M_INSPRID": return KnxManufacturer_M_INSPRID case "M_SUNRICHER": return KnxManufacturer_M_SUNRICHER case "M_MENRED_AUTOMATION_SYSTEMSHANGHAI_CO__LTD_": return KnxManufacturer_M_MENRED_AUTOMATION_SYSTEMSHANGHAI_CO__LTD_ case "M_AUREX": return KnxManufacturer_M_AUREX case "M_JOSEF_BARTHELME_GMBH_AND_CO__KG": return KnxManufacturer_M_JOSEF_BARTHELME_GMBH_AND_CO__KG case "M_ARCHITECTURE_NUMERIQUE": return KnxManufacturer_M_ARCHITECTURE_NUMERIQUE case "M_UP_GROUP": return KnxManufacturer_M_UP_GROUP case "M_MOELLER_GEBAEUDEAUTOMATION_KG": return KnxManufacturer_M_MOELLER_GEBAEUDEAUTOMATION_KG case "M_TEKNOS_AVINNO": return KnxManufacturer_M_TEKNOS_AVINNO case "M_NINGBO_DOOYA_MECHANIC_AND_ELECTRONIC_TECHNOLOGY": return KnxManufacturer_M_NINGBO_DOOYA_MECHANIC_AND_ELECTRONIC_TECHNOLOGY case "M_THERMOKON_SENSORTECHNIK_GMBH": return KnxManufacturer_M_THERMOKON_SENSORTECHNIK_GMBH case "M_BELIMO_AUTOMATION_AG": return KnxManufacturer_M_BELIMO_AUTOMATION_AG case "M_ZEHNDER_GROUP_INTERNATIONAL_AG": return KnxManufacturer_M_ZEHNDER_GROUP_INTERNATIONAL_AG case "M_SKS_KINKEL_ELEKTRONIK": return KnxManufacturer_M_SKS_KINKEL_ELEKTRONIK case "M_ECE_WURMITZER_GMBH": return KnxManufacturer_M_ECE_WURMITZER_GMBH case "M_LARS": return KnxManufacturer_M_LARS case "M_URC": return KnxManufacturer_M_URC case "M_LIGHTCONTROL": return KnxManufacturer_M_LIGHTCONTROL case "M_ALBRECHT_JUNG": return KnxManufacturer_M_ALBRECHT_JUNG case "M_ELTAKO": return KnxManufacturer_M_ELTAKO case "M_SHENZHEN_YM": return KnxManufacturer_M_SHENZHEN_YM case "M_MEAN_WELL_ENTERPRISES_CO__LTD_": return KnxManufacturer_M_MEAN_WELL_ENTERPRISES_CO__LTD_ case "M_OSIX": return KnxManufacturer_M_OSIX case "M_AYPRO_TECHNOLOGY": return KnxManufacturer_M_AYPRO_TECHNOLOGY case "M_HEFEI_ECOLITE_SOFTWARE": return KnxManufacturer_M_HEFEI_ECOLITE_SOFTWARE case "M_ENNO": return KnxManufacturer_M_ENNO case "M_OHOSURE": return KnxManufacturer_M_OHOSURE case "M_GAREFOWL": return KnxManufacturer_M_GAREFOWL case "M_GEZE": return KnxManufacturer_M_GEZE case "M_LG_ELECTRONICS_INC_": return KnxManufacturer_M_LG_ELECTRONICS_INC_ case "M_BOSCH_SIEMENS_HAUSHALTSGERAETE": return KnxManufacturer_M_BOSCH_SIEMENS_HAUSHALTSGERAETE case "M_SMC_INTERIORS": return KnxManufacturer_M_SMC_INTERIORS case "M_NOT_ASSIGNED_364": return KnxManufacturer_M_NOT_ASSIGNED_364 case "M_SCS_CABLE": return KnxManufacturer_M_SCS_CABLE case "M_HOVAL": return KnxManufacturer_M_HOVAL case "M_CANST": return KnxManufacturer_M_CANST case "M_HANGZHOU_BERLIN": return KnxManufacturer_M_HANGZHOU_BERLIN case "M_EVN_LICHTTECHNIK": return KnxManufacturer_M_EVN_LICHTTECHNIK case "M_RUTEC": return KnxManufacturer_M_RUTEC case "M_FINDER": return KnxManufacturer_M_FINDER case "M_FUJITSU_GENERAL_LIMITED": return KnxManufacturer_M_FUJITSU_GENERAL_LIMITED case "M_RITTO_GMBHANDCO_KG": return KnxManufacturer_M_RITTO_GMBHANDCO_KG case "M_ZF_FRIEDRICHSHAFEN_AG": return KnxManufacturer_M_ZF_FRIEDRICHSHAFEN_AG case "M_CREALED": return KnxManufacturer_M_CREALED case "M_MILES_MAGIC_AUTOMATION_PRIVATE_LIMITED": return KnxManufacturer_M_MILES_MAGIC_AUTOMATION_PRIVATE_LIMITED case "M_EPlus": return KnxManufacturer_M_EPlus case "M_ITALCOND": return KnxManufacturer_M_ITALCOND case "M_SATION": return KnxManufacturer_M_SATION case "M_NEWBEST": return KnxManufacturer_M_NEWBEST case "M_GDS_DIGITAL_SYSTEMS": return KnxManufacturer_M_GDS_DIGITAL_SYSTEMS case "M_IDDERO": return KnxManufacturer_M_IDDERO case "M_MBNLED": return KnxManufacturer_M_MBNLED case "M_POWER_CONTROLS": return KnxManufacturer_M_POWER_CONTROLS case "M_VITRUM": return KnxManufacturer_M_VITRUM case "M_EKEY_BIOMETRIC_SYSTEMS_GMBH": return KnxManufacturer_M_EKEY_BIOMETRIC_SYSTEMS_GMBH case "M_AMC": return KnxManufacturer_M_AMC case "M_TRILUX_GMBH_AND_CO__KG": return KnxManufacturer_M_TRILUX_GMBH_AND_CO__KG case "M_WEXCEDO": return KnxManufacturer_M_WEXCEDO case "M_VEMER_SPA": return KnxManufacturer_M_VEMER_SPA case "M_ALEXANDER_BUERKLE_GMBH_AND_CO_KG": return KnxManufacturer_M_ALEXANDER_BUERKLE_GMBH_AND_CO_KG case "M_CITRON": return KnxManufacturer_M_CITRON case "M_SHENZHEN_HEGUANG": return KnxManufacturer_M_SHENZHEN_HEGUANG case "M_NOT_ASSIGNED_392": return KnxManufacturer_M_NOT_ASSIGNED_392 case "M_ZUMTOBEL": return KnxManufacturer_M_ZUMTOBEL case "M_TRANE_B_V_B_A": return KnxManufacturer_M_TRANE_B_V_B_A case "M_CAREL": return KnxManufacturer_M_CAREL case "M_PROLITE_CONTROLS": return KnxManufacturer_M_PROLITE_CONTROLS case "M_BOSMER": return KnxManufacturer_M_BOSMER case "M_EUCHIPS": return KnxManufacturer_M_EUCHIPS case "M_CONNECT_THINKA_CONNECT": return KnxManufacturer_M_CONNECT_THINKA_CONNECT case "M_PEAKNX_A_DOGAWIST_COMPANY": return KnxManufacturer_M_PEAKNX_A_DOGAWIST_COMPANY case "M_ACEMATIC": return KnxManufacturer_M_ACEMATIC case "M_ELAUSYS": return KnxManufacturer_M_ELAUSYS case "M_ITK_ENGINEERING_AG": return KnxManufacturer_M_ITK_ENGINEERING_AG case "M_PHOENIX_CONTACT": return KnxManufacturer_M_PHOENIX_CONTACT case "M_INTEGRA_METERING_AG": return KnxManufacturer_M_INTEGRA_METERING_AG case "M_FMS_HOSPITALITY_PTE_LTD": return KnxManufacturer_M_FMS_HOSPITALITY_PTE_LTD case "M_NUVO": return KnxManufacturer_M_NUVO case "M_U__LUX_GMBH": return KnxManufacturer_M_U__LUX_GMBH case "M_BRUMBERG_LEUCHTEN": return KnxManufacturer_M_BRUMBERG_LEUCHTEN case "M_LIME": return KnxManufacturer_M_LIME case "M_GREAT_EMPIRE_INTERNATIONAL_GROUP_CO___LTD_": return KnxManufacturer_M_GREAT_EMPIRE_INTERNATIONAL_GROUP_CO___LTD_ case "M_KAVOSHPISHRO_ASIA": return KnxManufacturer_M_KAVOSHPISHRO_ASIA case "M_V2_SPA": return KnxManufacturer_M_V2_SPA case "M_JOHNSON_CONTROLS": return KnxManufacturer_M_JOHNSON_CONTROLS case "M_WAGO_KONTAKTTECHNIK": return KnxManufacturer_M_WAGO_KONTAKTTECHNIK case "M_ARKUD": return KnxManufacturer_M_ARKUD case "M_IRIDIUM_LTD_": return KnxManufacturer_M_IRIDIUM_LTD_ case "M_BSMART": return KnxManufacturer_M_BSMART case "M_BAB_TECHNOLOGIE_GMBH": return KnxManufacturer_M_BAB_TECHNOLOGIE_GMBH case "M_NICE_SPA": return KnxManufacturer_M_NICE_SPA case "M_REDFISH_GROUP_PTY_LTD": return KnxManufacturer_M_REDFISH_GROUP_PTY_LTD case "M_SABIANA_SPA": return KnxManufacturer_M_SABIANA_SPA case "M_UBEE_INTERACTIVE_EUROPE": return KnxManufacturer_M_UBEE_INTERACTIVE_EUROPE case "M_REXEL": return KnxManufacturer_M_REXEL case "M_GES_TEKNIK_A_S_": return KnxManufacturer_M_GES_TEKNIK_A_S_ case "M_KNXPRESSO": return KnxManufacturer_M_KNXPRESSO case "M_AVE_S_P_A_": return KnxManufacturer_M_AVE_S_P_A_ case "M_ZHUHAI_LTECH_TECHNOLOGY_CO___LTD_": return KnxManufacturer_M_ZHUHAI_LTECH_TECHNOLOGY_CO___LTD_ case "M_ARCOM": return KnxManufacturer_M_ARCOM case "M_VIA_TECHNOLOGIES__INC_": return KnxManufacturer_M_VIA_TECHNOLOGIES__INC_ case "M_FEELSMART_": return KnxManufacturer_M_FEELSMART_ case "M_SUPCON": return KnxManufacturer_M_SUPCON case "M_MANIC": return KnxManufacturer_M_MANIC case "M_TDE_GMBH": return KnxManufacturer_M_TDE_GMBH case "M_NANJING_SHUFAN_INFORMATION_TECHNOLOGY_CO__LTD_": return KnxManufacturer_M_NANJING_SHUFAN_INFORMATION_TECHNOLOGY_CO__LTD_ case "M_EWTECH": return KnxManufacturer_M_EWTECH case "M_WIELAND_ELECTRIC": return KnxManufacturer_M_WIELAND_ELECTRIC case "M_KLUGER_AUTOMATION_GMBH": return KnxManufacturer_M_KLUGER_AUTOMATION_GMBH case "M_JOONGANG_CONTROL": return KnxManufacturer_M_JOONGANG_CONTROL case "M_GREENCONTROLS_TECHNOLOGY_SDN__BHD_": return KnxManufacturer_M_GREENCONTROLS_TECHNOLOGY_SDN__BHD_ case "M_IME_S_P_A_": return KnxManufacturer_M_IME_S_P_A_ case "M_SICHUAN_HAODING": return KnxManufacturer_M_SICHUAN_HAODING case "M_MINDJAGA_LTD_": return KnxManufacturer_M_MINDJAGA_LTD_ case "M_RUILI_SMART_CONTROL": return KnxManufacturer_M_RUILI_SMART_CONTROL case "M_CODESYS_GMBH": return KnxManufacturer_M_CODESYS_GMBH case "M_MOORGEN_DEUTSCHLAND_GMBH": return KnxManufacturer_M_MOORGEN_DEUTSCHLAND_GMBH case "M_CULLMANN_TECH": return KnxManufacturer_M_CULLMANN_TECH case "M_HERMANN_KLEINHUIS": return KnxManufacturer_M_HERMANN_KLEINHUIS case "M_MERCK_WINDOW_TECHNOLOGIES_B_V_": return KnxManufacturer_M_MERCK_WINDOW_TECHNOLOGIES_B_V_ case "M_ABEGO": return KnxManufacturer_M_ABEGO case "M_MYGEKKO": return KnxManufacturer_M_MYGEKKO case "M_ERGO3_SARL": return KnxManufacturer_M_ERGO3_SARL case "M_STMICROELECTRONICS_INTERNATIONAL_N_V_": return KnxManufacturer_M_STMICROELECTRONICS_INTERNATIONAL_N_V_ case "M_CJC_SYSTEMS": return KnxManufacturer_M_CJC_SYSTEMS case "M_SUDOKU": return KnxManufacturer_M_SUDOKU case "M_AZ_E_LITE_PTE_LTD": return KnxManufacturer_M_AZ_E_LITE_PTE_LTD case "M_ARLIGHT": return KnxManufacturer_M_ARLIGHT case "M_GRUENBECK_WASSERAUFBEREITUNG_GMBH": return KnxManufacturer_M_GRUENBECK_WASSERAUFBEREITUNG_GMBH case "M_BTICINO": return KnxManufacturer_M_BTICINO case "M_STIEBEL_ELTRON": return KnxManufacturer_M_STIEBEL_ELTRON case "M_MODULE_ELECTRONIC": return KnxManufacturer_M_MODULE_ELECTRONIC case "M_KOPLAT": return KnxManufacturer_M_KOPLAT case "M_GUANGZHOU_LETOUR_LIFE_TECHNOLOGY_CO___LTD": return KnxManufacturer_M_GUANGZHOU_LETOUR_LIFE_TECHNOLOGY_CO___LTD case "M_ILEVIA": return KnxManufacturer_M_ILEVIA case "M_LN_SYSTEMTEQ": return KnxManufacturer_M_LN_SYSTEMTEQ case "M_HISENSE_SMARTHOME": return KnxManufacturer_M_HISENSE_SMARTHOME case "M_FLINK_AUTOMATION_SYSTEM": return KnxManufacturer_M_FLINK_AUTOMATION_SYSTEM case "M_XXTER_BV": return KnxManufacturer_M_XXTER_BV case "M_LYNXUS_TECHNOLOGY": return KnxManufacturer_M_LYNXUS_TECHNOLOGY case "M_ROBOT_S_A_": return KnxManufacturer_M_ROBOT_S_A_ case "M_TEHALIT": return KnxManufacturer_M_TEHALIT case "M_SHENZHEN_ATTE_SMART_LIFE_CO__LTD_": return KnxManufacturer_M_SHENZHEN_ATTE_SMART_LIFE_CO__LTD_ case "M_NOBLESSE": return KnxManufacturer_M_NOBLESSE case "M_ADVANCED_DEVICES": return KnxManufacturer_M_ADVANCED_DEVICES case "M_ATRINA_BUILDING_AUTOMATION_CO__LTD": return KnxManufacturer_M_ATRINA_BUILDING_AUTOMATION_CO__LTD case "M_GUANGDONG_DAMING_LAFFEY_ELECTRIC_CO___LTD_": return KnxManufacturer_M_GUANGDONG_DAMING_LAFFEY_ELECTRIC_CO___LTD_ case "M_WESTERSTRAND_URFABRIK_AB": return KnxManufacturer_M_WESTERSTRAND_URFABRIK_AB case "M_CONTROL4_CORPORATE": return KnxManufacturer_M_CONTROL4_CORPORATE case "M_ONTROL": return KnxManufacturer_M_ONTROL case "M_STARNET": return KnxManufacturer_M_STARNET case "M_BETA_CAVI": return KnxManufacturer_M_BETA_CAVI case "M_THEBEN_AG": return KnxManufacturer_M_THEBEN_AG case "M_EASEMORE": return KnxManufacturer_M_EASEMORE case "M_VIVALDI_SRL": return KnxManufacturer_M_VIVALDI_SRL case "M_GREE_ELECTRIC_APPLIANCES_INC__OF_ZHUHAI": return KnxManufacturer_M_GREE_ELECTRIC_APPLIANCES_INC__OF_ZHUHAI case "M_HWISCON": return KnxManufacturer_M_HWISCON case "M_SHANGHAI_ELECON_INTELLIGENT_TECHNOLOGY_CO___LTD_": return KnxManufacturer_M_SHANGHAI_ELECON_INTELLIGENT_TECHNOLOGY_CO___LTD_ case "M_KAMPMANN": return KnxManufacturer_M_KAMPMANN case "M_IMPOLUX_GMBH_LEDIMAX": return KnxManufacturer_M_IMPOLUX_GMBH_LEDIMAX case "M_EVAUX": return KnxManufacturer_M_EVAUX case "M_WEBRO_CABLES_AND_CONNECTORS_LIMITED": return KnxManufacturer_M_WEBRO_CABLES_AND_CONNECTORS_LIMITED case "M_SHANGHAI_E_TECH_SOLUTION": return KnxManufacturer_M_SHANGHAI_E_TECH_SOLUTION case "M_WILHELM_RUTENBECK": return KnxManufacturer_M_WILHELM_RUTENBECK case "M_GUANGZHOU_HOKO_ELECTRIC_CO__LTD_": return KnxManufacturer_M_GUANGZHOU_HOKO_ELECTRIC_CO__LTD_ case "M_LAMMIN_HIGH_TECH_CO__LTD": return KnxManufacturer_M_LAMMIN_HIGH_TECH_CO__LTD case "M_SHENZHEN_MERRYTEK_TECHNOLOGY_CO___LTD": return KnxManufacturer_M_SHENZHEN_MERRYTEK_TECHNOLOGY_CO___LTD case "M_I_LUXUS": return KnxManufacturer_M_I_LUXUS case "M_ELMOS_SEMICONDUCTOR_AG": return KnxManufacturer_M_ELMOS_SEMICONDUCTOR_AG case "M_EMCOM_TECHNOLOGY_INC": return KnxManufacturer_M_EMCOM_TECHNOLOGY_INC case "M_PROJECT_INNOVATIONS_GMBH": return KnxManufacturer_M_PROJECT_INNOVATIONS_GMBH case "M_ITC": return KnxManufacturer_M_ITC case "M_ABB_LV_INSTALLATION_MATERIALS_COMPANY_LTD__BEIJING": return KnxManufacturer_M_ABB_LV_INSTALLATION_MATERIALS_COMPANY_LTD__BEIJING case "M_MAICO": return KnxManufacturer_M_MAICO case "M_WINKHAUS": return KnxManufacturer_M_WINKHAUS case "M_ELAN_SRL": return KnxManufacturer_M_ELAN_SRL case "M_MINHHA_TECHNOLOGY_CO__LTD": return KnxManufacturer_M_MINHHA_TECHNOLOGY_CO__LTD case "M_ZHEJIANG_TIANJIE_INDUSTRIAL_CORP_": return KnxManufacturer_M_ZHEJIANG_TIANJIE_INDUSTRIAL_CORP_ case "M_IAUTOMATION_PTY_LIMITED": return KnxManufacturer_M_IAUTOMATION_PTY_LIMITED case "M_EXTRON": return KnxManufacturer_M_EXTRON case "M_FREEDOMPRO": return KnxManufacturer_M_FREEDOMPRO case "M_ONEHOME": return KnxManufacturer_M_ONEHOME case "M_EOS_SAUNATECHNIK_GMBH": return KnxManufacturer_M_EOS_SAUNATECHNIK_GMBH case "M_KUSATEK_GMBH": return KnxManufacturer_M_KUSATEK_GMBH case "M_EISBAER_SCADA": return KnxManufacturer_M_EISBAER_SCADA case "M_ROBERT_BOSCH": return KnxManufacturer_M_ROBERT_BOSCH case "M_AUTOMATISMI_BENINCA_S_P_A_": return KnxManufacturer_M_AUTOMATISMI_BENINCA_S_P_A_ case "M_BLENDOM": return KnxManufacturer_M_BLENDOM case "M_MADEL_AIR_TECHNICAL_DIFFUSION": return KnxManufacturer_M_MADEL_AIR_TECHNICAL_DIFFUSION case "M_NIKO": return KnxManufacturer_M_NIKO case "M_BOSCH_REXROTH_AG": return KnxManufacturer_M_BOSCH_REXROTH_AG case "M_CANDM_PRODUCTS": return KnxManufacturer_M_CANDM_PRODUCTS case "M_HOERMANN_KG_VERKAUFSGESELLSCHAFT": return KnxManufacturer_M_HOERMANN_KG_VERKAUFSGESELLSCHAFT case "M_SHANGHAI_RAJAYASA_CO__LTD": return KnxManufacturer_M_SHANGHAI_RAJAYASA_CO__LTD case "M_SUZUKI": return KnxManufacturer_M_SUZUKI case "M_SILENT_GLISS_INTERNATIONAL_LTD_": return KnxManufacturer_M_SILENT_GLISS_INTERNATIONAL_LTD_ case "M_SOMFY": return KnxManufacturer_M_SOMFY case "M_BEE_CONTROLS_ADGSC_GROUP": return KnxManufacturer_M_BEE_CONTROLS_ADGSC_GROUP case "M_XDTECGMBH": return KnxManufacturer_M_XDTECGMBH case "M_OSRAM": return KnxManufacturer_M_OSRAM case "M_LEBENOR": return KnxManufacturer_M_LEBENOR case "M_AUTOMANENG": return KnxManufacturer_M_AUTOMANENG case "M_HONEYWELL_AUTOMATION_SOLUTION_CONTROLCHINA": return KnxManufacturer_M_HONEYWELL_AUTOMATION_SOLUTION_CONTROLCHINA case "M_HANGZHOU_BINTHEN_INTELLIGENCE_TECHNOLOGY_CO__LTD": return KnxManufacturer_M_HANGZHOU_BINTHEN_INTELLIGENCE_TECHNOLOGY_CO__LTD case "M_ETA_HEIZTECHNIK": return KnxManufacturer_M_ETA_HEIZTECHNIK case "M_DIVUS_GMBH": return KnxManufacturer_M_DIVUS_GMBH case "M_NANJING_TAIJIESAI_INTELLIGENT_TECHNOLOGY_CO__LTD_": return KnxManufacturer_M_NANJING_TAIJIESAI_INTELLIGENT_TECHNOLOGY_CO__LTD_ case "M_WOERTZ": return KnxManufacturer_M_WOERTZ case "M_LUNATONE": return KnxManufacturer_M_LUNATONE case "M_ZHEJIANG_SCTECH_BUILDING_INTELLIGENT": return KnxManufacturer_M_ZHEJIANG_SCTECH_BUILDING_INTELLIGENT case "M_FOSHAN_QITE_TECHNOLOGY_CO___LTD_": return KnxManufacturer_M_FOSHAN_QITE_TECHNOLOGY_CO___LTD_ case "M_NOKE": return KnxManufacturer_M_NOKE case "M_LANDCOM": return KnxManufacturer_M_LANDCOM case "M_STORK_AS": return KnxManufacturer_M_STORK_AS case "M_HANGZHOU_SHENDU_TECHNOLOGY_CO___LTD_": return KnxManufacturer_M_HANGZHOU_SHENDU_TECHNOLOGY_CO___LTD_ case "M_COOLAUTOMATION": return KnxManufacturer_M_COOLAUTOMATION case "M_APRSTERN": return KnxManufacturer_M_APRSTERN case "M_SONNEN": return KnxManufacturer_M_SONNEN case "M_VIESSMANN_WERKE": return KnxManufacturer_M_VIESSMANN_WERKE case "M_DNAKE": return KnxManufacturer_M_DNAKE case "M_NEUBERGER_GEBAEUDEAUTOMATION_GMBH": return KnxManufacturer_M_NEUBERGER_GEBAEUDEAUTOMATION_GMBH case "M_STILIGER": return KnxManufacturer_M_STILIGER case "M_BERGHOF_AUTOMATION_GMBH": return KnxManufacturer_M_BERGHOF_AUTOMATION_GMBH case "M_TOTAL_AUTOMATION_AND_CONTROLS_GMBH": return KnxManufacturer_M_TOTAL_AUTOMATION_AND_CONTROLS_GMBH case "M_DOVIT": return KnxManufacturer_M_DOVIT case "M_INSTALIGHTING_GMBH": return KnxManufacturer_M_INSTALIGHTING_GMBH case "M_UNI_TEC": return KnxManufacturer_M_UNI_TEC case "M_CASATUNES": return KnxManufacturer_M_CASATUNES case "M_EMT": return KnxManufacturer_M_EMT case "M_IMI_HYDRONIC_ENGINEERING": return KnxManufacturer_M_IMI_HYDRONIC_ENGINEERING case "M_SENFFICIENT": return KnxManufacturer_M_SENFFICIENT case "M_AUROLITE_ELECTRICAL_PANYU_GUANGZHOU_LIMITED": return KnxManufacturer_M_AUROLITE_ELECTRICAL_PANYU_GUANGZHOU_LIMITED case "M_ABB_XIAMEN_SMART_TECHNOLOGY_CO___LTD_": return KnxManufacturer_M_ABB_XIAMEN_SMART_TECHNOLOGY_CO___LTD_ case "M_SAMSON_ELECTRIC_WIRE": return KnxManufacturer_M_SAMSON_ELECTRIC_WIRE case "M_T_TOUCHING": return KnxManufacturer_M_T_TOUCHING case "M_CORE_SMART_HOME": return KnxManufacturer_M_CORE_SMART_HOME case "M_GREENCONNECT_SOLUTIONS_SA": return KnxManufacturer_M_GREENCONNECT_SOLUTIONS_SA case "M_ELETTRONICA_CONDUTTORI": return KnxManufacturer_M_ELETTRONICA_CONDUTTORI case "M_MKFC": return KnxManufacturer_M_MKFC case "M_AUTOMATIONPlus": return KnxManufacturer_M_AUTOMATIONPlus case "M_BERKER": return KnxManufacturer_M_BERKER case "M_JOH__VAILLANT": return KnxManufacturer_M_JOH__VAILLANT case "M_BLUE_AND_RED": return KnxManufacturer_M_BLUE_AND_RED case "M_FROGBLUE": return KnxManufacturer_M_FROGBLUE case "M_SAVESOR": return KnxManufacturer_M_SAVESOR case "M_APP_TECH": return KnxManufacturer_M_APP_TECH case "M_SENSORTEC_AG": return KnxManufacturer_M_SENSORTEC_AG case "M_NYSA_TECHNOLOGY_AND_SOLUTIONS": return KnxManufacturer_M_NYSA_TECHNOLOGY_AND_SOLUTIONS case "M_FARADITE": return KnxManufacturer_M_FARADITE case "M_OPTIMUS": return KnxManufacturer_M_OPTIMUS case "M_KTS_S_R_L_": return KnxManufacturer_M_KTS_S_R_L_ case "M_RAMCRO_SPA": return KnxManufacturer_M_RAMCRO_SPA case "M_AMP_DEUTSCHLAND": return KnxManufacturer_M_AMP_DEUTSCHLAND case "M_WUHAN_WISECREATE_UNIVERSE_TECHNOLOGY_CO___LTD": return KnxManufacturer_M_WUHAN_WISECREATE_UNIVERSE_TECHNOLOGY_CO___LTD case "M_BEMI_SMART_HOME_LTD": return KnxManufacturer_M_BEMI_SMART_HOME_LTD case "M_ARDOMUS": return KnxManufacturer_M_ARDOMUS case "M_CHANGXING": return KnxManufacturer_M_CHANGXING case "M_E_CONTROLS": return KnxManufacturer_M_E_CONTROLS case "M_AIB_TECHNOLOGY": return KnxManufacturer_M_AIB_TECHNOLOGY case "M_NVC": return KnxManufacturer_M_NVC case "M_KBOX": return KnxManufacturer_M_KBOX case "M_CNS": return KnxManufacturer_M_CNS case "M_TYBA": return KnxManufacturer_M_TYBA case "M_BOSCH_THERMOTECHNIK_GMBH": return KnxManufacturer_M_BOSCH_THERMOTECHNIK_GMBH case "M_ATREL": return KnxManufacturer_M_ATREL case "M_SIMON_ELECTRIC_CHINA_CO___LTD": return KnxManufacturer_M_SIMON_ELECTRIC_CHINA_CO___LTD case "M_KORDZ_GROUP": return KnxManufacturer_M_KORDZ_GROUP case "M_ND_ELECTRIC": return KnxManufacturer_M_ND_ELECTRIC case "M_CONTROLIUM": return KnxManufacturer_M_CONTROLIUM case "M_FAMO_GMBH_AND_CO__KG": return KnxManufacturer_M_FAMO_GMBH_AND_CO__KG case "M_CDN_SMART": return KnxManufacturer_M_CDN_SMART case "M_HESTON": return KnxManufacturer_M_HESTON case "M_ESLA_CONEXIONES_S_L_": return KnxManufacturer_M_ESLA_CONEXIONES_S_L_ case "M_WEISHAUPT": return KnxManufacturer_M_WEISHAUPT case "M_SEF___ECOTEC": return KnxManufacturer_M_SEF___ECOTEC case "M_ASTRUM_TECHNOLOGY": return KnxManufacturer_M_ASTRUM_TECHNOLOGY case "M_WUERTH_ELEKTRONIK_STELVIO_KONTEK_S_P_A_": return KnxManufacturer_M_WUERTH_ELEKTRONIK_STELVIO_KONTEK_S_P_A_ case "M_NANOTECO_CORPORATION": return KnxManufacturer_M_NANOTECO_CORPORATION case "M_NIETIAN": return KnxManufacturer_M_NIETIAN case "M_SUMSIR": return KnxManufacturer_M_SUMSIR case "M_ORBIS_TECNOLOGIA_ELECTRICA_SA": return KnxManufacturer_M_ORBIS_TECNOLOGIA_ELECTRICA_SA case "M_NANJING_ZHONGYI_IOT_TECHNOLOGY_CO___LTD_": return KnxManufacturer_M_NANJING_ZHONGYI_IOT_TECHNOLOGY_CO___LTD_ case "M_ANLIPS": return KnxManufacturer_M_ANLIPS case "M_GUANGDONG_PAK_CORPORATION_CO___LTD": return KnxManufacturer_M_GUANGDONG_PAK_CORPORATION_CO___LTD case "M_BVK_TECHNOLOGY": return KnxManufacturer_M_BVK_TECHNOLOGY case "M_DORMA_GMBH_Plus_CO__KG": return KnxManufacturer_M_DORMA_GMBH_Plus_CO__KG case "M_SOLOMIO_SRL": return KnxManufacturer_M_SOLOMIO_SRL case "M_DOMOTICA_LABS": return KnxManufacturer_M_DOMOTICA_LABS case "M_NVC_INTERNATIONAL": return KnxManufacturer_M_NVC_INTERNATIONAL case "M_BA": return KnxManufacturer_M_BA case "M_IRIS_CERAMICA_GROUP": return KnxManufacturer_M_IRIS_CERAMICA_GROUP case "M_WIREEO": return KnxManufacturer_M_WIREEO case "M_NVCLIGHTING": return KnxManufacturer_M_NVCLIGHTING case "M_JINAN_TIAN_DA_SHENG_INFORMATION_TECHNOLOGY_CO_": return KnxManufacturer_M_JINAN_TIAN_DA_SHENG_INFORMATION_TECHNOLOGY_CO_ case "M_ARMITI_TRADING": return KnxManufacturer_M_ARMITI_TRADING case "M_ELEK": return KnxManufacturer_M_ELEK case "M_WINDOWMASTER_AS": return KnxManufacturer_M_WINDOWMASTER_AS case "M_ACCORDIA_SA": return KnxManufacturer_M_ACCORDIA_SA case "M_OURICAN": return KnxManufacturer_M_OURICAN case "M_INLIWOSE": return KnxManufacturer_M_INLIWOSE case "M_BOSCH_SHANGHAI_SMART_LIFE_TECHNOLOGY_LTD_": return KnxManufacturer_M_BOSCH_SHANGHAI_SMART_LIFE_TECHNOLOGY_LTD_ case "M_SHK_KNX": return KnxManufacturer_M_SHK_KNX case "M_AMPIO": return KnxManufacturer_M_AMPIO case "M_MINGXING_WISDOM": return KnxManufacturer_M_MINGXING_WISDOM case "M_ALTEN_SW_GMBH": return KnxManufacturer_M_ALTEN_SW_GMBH case "M_ABB___RESERVED": return KnxManufacturer_M_ABB___RESERVED case "M_BUSCH_JAEGER_ELEKTRO___RESERVED": return KnxManufacturer_M_BUSCH_JAEGER_ELEKTRO___RESERVED case "M_WALTHER_WERKE": return KnxManufacturer_M_WALTHER_WERKE case "M_ORAS": return KnxManufacturer_M_ORAS case "M_DAETWYLER": return KnxManufacturer_M_DAETWYLER case "M_ELECTRAK": return KnxManufacturer_M_ELECTRAK case "M_BUSCH_JAEGER_ELEKTRO": return KnxManufacturer_M_BUSCH_JAEGER_ELEKTRO case "M_TECHEM": return KnxManufacturer_M_TECHEM case "M_SCHNEIDER_ELECTRIC_INDUSTRIES_SAS": return KnxManufacturer_M_SCHNEIDER_ELECTRIC_INDUSTRIES_SAS case "M_WHD_WILHELM_HUBER_Plus_SOEHNE": return KnxManufacturer_M_WHD_WILHELM_HUBER_Plus_SOEHNE case "M_BISCHOFF_ELEKTRONIK": return KnxManufacturer_M_BISCHOFF_ELEKTRONIK case "M_JEPAZ": return KnxManufacturer_M_JEPAZ case "M_RTS_AUTOMATION": return KnxManufacturer_M_RTS_AUTOMATION case "M_EIBMARKT_GMBH": return KnxManufacturer_M_EIBMARKT_GMBH case "M_WAREMA_RENKHOFF_SE": return KnxManufacturer_M_WAREMA_RENKHOFF_SE case "M_EELECTRON": return KnxManufacturer_M_EELECTRON case "M_BELDEN_WIRE_AND_CABLE_B_V_": return KnxManufacturer_M_BELDEN_WIRE_AND_CABLE_B_V_ case "M_GIRA_GIERSIEPEN": return KnxManufacturer_M_GIRA_GIERSIEPEN case "M_BECKER_ANTRIEBE_GMBH": return KnxManufacturer_M_BECKER_ANTRIEBE_GMBH case "M_J_STEHLEPlusSOEHNE_GMBH": return KnxManufacturer_M_J_STEHLEPlusSOEHNE_GMBH case "M_AGFEO": return KnxManufacturer_M_AGFEO case "M_ZENNIO": return KnxManufacturer_M_ZENNIO case "M_TAPKO_TECHNOLOGIES": return KnxManufacturer_M_TAPKO_TECHNOLOGIES case "M_HDL": return KnxManufacturer_M_HDL case "M_UPONOR": return KnxManufacturer_M_UPONOR case "M_SE_LIGHTMANAGEMENT_AG": return KnxManufacturer_M_SE_LIGHTMANAGEMENT_AG case "M_ARCUS_EDS": return KnxManufacturer_M_ARCUS_EDS case "M_INTESIS": return KnxManufacturer_M_INTESIS case "M_HAGER_ELECTRO": return KnxManufacturer_M_HAGER_ELECTRO case "M_HERHOLDT_CONTROLS_SRL": return KnxManufacturer_M_HERHOLDT_CONTROLS_SRL case "M_NIKO_ZUBLIN": return KnxManufacturer_M_NIKO_ZUBLIN case "M_DURABLE_TECHNOLOGIES": return KnxManufacturer_M_DURABLE_TECHNOLOGIES case "M_INNOTEAM": return KnxManufacturer_M_INNOTEAM case "M_ISE_GMBH": return KnxManufacturer_M_ISE_GMBH case "M_TEAM_FOR_TRONICS": return KnxManufacturer_M_TEAM_FOR_TRONICS case "M_CIAT": return KnxManufacturer_M_CIAT case "M_REMEHA_BV": return KnxManufacturer_M_REMEHA_BV case "M_ESYLUX": return KnxManufacturer_M_ESYLUX case "M_BASALTE": return KnxManufacturer_M_BASALTE case "M_INSTA_GMBH": return KnxManufacturer_M_INSTA_GMBH case "M_VESTAMATIC": return KnxManufacturer_M_VESTAMATIC case "M_MDT_TECHNOLOGIES": return KnxManufacturer_M_MDT_TECHNOLOGIES case "M_WARENDORFER_KUECHEN_GMBH": return KnxManufacturer_M_WARENDORFER_KUECHEN_GMBH case "M_VIDEO_STAR": return KnxManufacturer_M_VIDEO_STAR case "M_SITEK": return KnxManufacturer_M_SITEK case "M_CONTROLTRONIC": return KnxManufacturer_M_CONTROLTRONIC case "M_FUNCTION_TECHNOLOGY": return KnxManufacturer_M_FUNCTION_TECHNOLOGY case "M_AMX": return KnxManufacturer_M_AMX case "M_ELDAT": return KnxManufacturer_M_ELDAT case "M_PANASONIC": return KnxManufacturer_M_PANASONIC } return 0 } func CastKnxManufacturer(structType interface{}) KnxManufacturer { castFunc := func(typ interface{}) KnxManufacturer { if sKnxManufacturer, ok := typ.(KnxManufacturer); ok { return sKnxManufacturer } return 0 } return castFunc(structType) } func (m KnxManufacturer) LengthInBits() uint16 { return 16 } func (m KnxManufacturer) LengthInBytes() uint16 { return m.LengthInBits() / 8 } func KnxManufacturerParse(readBuffer utils.ReadBuffer) (KnxManufacturer, error) { val, err := readBuffer.ReadUint16("KnxManufacturer", 16) if err != nil { return 0, nil } return KnxManufacturerByValue(val), nil } func (e KnxManufacturer) Serialize(writeBuffer utils.WriteBuffer) error { return writeBuffer.WriteUint16("KnxManufacturer", 16, uint16(e), utils.WithAdditionalStringRepresentation(e.name())) } func (e KnxManufacturer) name() string { switch e { case KnxManufacturer_M_UNKNOWN: return "M_UNKNOWN" case KnxManufacturer_M_SIEMENS: return "M_SIEMENS" case KnxManufacturer_M_LEGRAND_APPAREILLAGE_ELECTRIQUE: return "M_LEGRAND_APPAREILLAGE_ELECTRIQUE" case KnxManufacturer_M_PULSE_TECHNOLOGIES: return "M_PULSE_TECHNOLOGIES" case KnxManufacturer_M_CRESTRON: return "M_CRESTRON" case KnxManufacturer_M_STEINEL_PROFESSIONAL: return "M_STEINEL_PROFESSIONAL" case KnxManufacturer_M_BILTON_LED_LIGHTING: return "M_BILTON_LED_LIGHTING" case KnxManufacturer_M_DENRO_AG: return "M_DENRO_AG" case KnxManufacturer_M_GEPRO: return "M_GEPRO" case KnxManufacturer_M_PREUSSEN_AUTOMATION: return "M_PREUSSEN_AUTOMATION" case KnxManufacturer_M_ZOPPAS_INDUSTRIES: return "M_ZOPPAS_INDUSTRIES" case KnxManufacturer_M_MACTECH: return "M_MACTECH" case KnxManufacturer_M_TECHNO_TREND: return "M_TECHNO_TREND" case KnxManufacturer_M_MERTEN: return "M_MERTEN" case KnxManufacturer_M_FS_CABLES: return "M_FS_CABLES" case KnxManufacturer_M_DELTA_DORE: return "M_DELTA_DORE" case KnxManufacturer_M_EISSOUND: return "M_EISSOUND" case KnxManufacturer_M_CISCO: return "M_CISCO" case KnxManufacturer_M_DINUY: return "M_DINUY" case KnxManufacturer_M_IKNIX: return "M_IKNIX" case KnxManufacturer_M_RADEMACHER_GERAETE_ELEKTRONIK_GMBH: return "M_RADEMACHER_GERAETE_ELEKTRONIK_GMBH" case KnxManufacturer_M_EGI_ELECTROACUSTICA_GENERAL_IBERICA: return "M_EGI_ELECTROACUSTICA_GENERAL_IBERICA" case KnxManufacturer_M_BES___INGENIUM: return "M_BES___INGENIUM" case KnxManufacturer_M_ELABNET: return "M_ELABNET" case KnxManufacturer_M_ABB_SPA_SACE_DIVISION: return "M_ABB_SPA_SACE_DIVISION" case KnxManufacturer_M_BLUMOTIX: return "M_BLUMOTIX" case KnxManufacturer_M_HUNTER_DOUGLAS: return "M_HUNTER_DOUGLAS" case KnxManufacturer_M_APRICUM: return "M_APRICUM" case KnxManufacturer_M_TIANSU_AUTOMATION: return "M_TIANSU_AUTOMATION" case KnxManufacturer_M_BUBENDORFF: return "M_BUBENDORFF" case KnxManufacturer_M_MBS_GMBH: return "M_MBS_GMBH" case KnxManufacturer_M_ENERTEX_BAYERN_GMBH: return "M_ENERTEX_BAYERN_GMBH" case KnxManufacturer_M_BMS: return "M_BMS" case KnxManufacturer_M_SINAPSI: return "M_SINAPSI" case KnxManufacturer_M_EMBEDDED_SYSTEMS_SIA: return "M_EMBEDDED_SYSTEMS_SIA" case KnxManufacturer_M_SIEDLE_AND_SOEHNE: return "M_SIEDLE_AND_SOEHNE" case KnxManufacturer_M_KNX1: return "M_KNX1" case KnxManufacturer_M_TOKKA: return "M_TOKKA" case KnxManufacturer_M_NANOSENSE: return "M_NANOSENSE" case KnxManufacturer_M_PEAR_AUTOMATION_GMBH: return "M_PEAR_AUTOMATION_GMBH" case KnxManufacturer_M_DGA: return "M_DGA" case KnxManufacturer_M_LUTRON: return "M_LUTRON" case KnxManufacturer_M_AIRZONE___ALTRA: return "M_AIRZONE___ALTRA" case KnxManufacturer_M_LITHOSS_DESIGN_SWITCHES: return "M_LITHOSS_DESIGN_SWITCHES" case KnxManufacturer_M_THREEATEL: return "M_THREEATEL" case KnxManufacturer_M_PHILIPS_CONTROLS: return "M_PHILIPS_CONTROLS" case KnxManufacturer_M_EBERLE: return "M_EBERLE" case KnxManufacturer_M_VELUX_AS: return "M_VELUX_AS" case KnxManufacturer_M_LOYTEC: return "M_LOYTEC" case KnxManufacturer_M_EKINEX_S_P_A_: return "M_EKINEX_S_P_A_" case KnxManufacturer_M_SIRLAN_TECHNOLOGIES: return "M_SIRLAN_TECHNOLOGIES" case KnxManufacturer_M_PROKNX_SAS: return "M_PROKNX_SAS" case KnxManufacturer_M_IT_GMBH: return "M_IT_GMBH" case KnxManufacturer_M_RENSON: return "M_RENSON" case KnxManufacturer_M_HEP_GROUP: return "M_HEP_GROUP" case KnxManufacturer_M_BALMART: return "M_BALMART" case KnxManufacturer_M_GFS_GMBH: return "M_GFS_GMBH" case KnxManufacturer_M_GEWISS: return "M_GEWISS" case KnxManufacturer_M_SCHENKER_STOREN_AG: return "M_SCHENKER_STOREN_AG" case KnxManufacturer_M_ALGODUE_ELETTRONICA_S_R_L_: return "M_ALGODUE_ELETTRONICA_S_R_L_" case KnxManufacturer_M_ABB_FRANCE: return "M_ABB_FRANCE" case KnxManufacturer_M_MAINTRONIC: return "M_MAINTRONIC" case KnxManufacturer_M_VANTAGE: return "M_VANTAGE" case KnxManufacturer_M_FORESIS: return "M_FORESIS" case KnxManufacturer_M_RESEARCH_AND_PRODUCTION_ASSOCIATION_SEM: return "M_RESEARCH_AND_PRODUCTION_ASSOCIATION_SEM" case KnxManufacturer_M_WEINZIERL_ENGINEERING_GMBH: return "M_WEINZIERL_ENGINEERING_GMBH" case KnxManufacturer_M_MOEHLENHOFF_WAERMETECHNIK_GMBH: return "M_MOEHLENHOFF_WAERMETECHNIK_GMBH" case KnxManufacturer_M_PKC_GROUP_OYJ: return "M_PKC_GROUP_OYJ" case KnxManufacturer_M_ALBERT_ACKERMANN: return "M_ALBERT_ACKERMANN" case KnxManufacturer_M_B_E_G_: return "M_B_E_G_" case KnxManufacturer_M_ELSNER_ELEKTRONIK_GMBH: return "M_ELSNER_ELEKTRONIK_GMBH" case KnxManufacturer_M_SIEMENS_BUILDING_TECHNOLOGIES_HKCHINA_LTD_: return "M_SIEMENS_BUILDING_TECHNOLOGIES_HKCHINA_LTD_" case KnxManufacturer_M_EUTRAC: return "M_EUTRAC" case KnxManufacturer_M_GUSTAV_HENSEL_GMBH_AND_CO__KG: return "M_GUSTAV_HENSEL_GMBH_AND_CO__KG" case KnxManufacturer_M_GARO_AB: return "M_GARO_AB" case KnxManufacturer_M_WALDMANN_LICHTTECHNIK: return "M_WALDMANN_LICHTTECHNIK" case KnxManufacturer_M_SCHUECO: return "M_SCHUECO" case KnxManufacturer_M_EMU: return "M_EMU" case KnxManufacturer_M_JNET_SYSTEMS_AG: return "M_JNET_SYSTEMS_AG" case KnxManufacturer_M_SCHUPA_GMBH: return "M_SCHUPA_GMBH" case KnxManufacturer_M_TOTAL_SOLUTION_GMBH: return "M_TOTAL_SOLUTION_GMBH" case KnxManufacturer_M_O_Y_L__ELECTRONICS: return "M_O_Y_L__ELECTRONICS" case KnxManufacturer_M_GALAX_SYSTEM: return "M_GALAX_SYSTEM" case KnxManufacturer_M_DISCH: return "M_DISCH" case KnxManufacturer_M_AUCOTEAM: return "M_AUCOTEAM" case KnxManufacturer_M_LUXMATE_CONTROLS: return "M_LUXMATE_CONTROLS" case KnxManufacturer_M_DANFOSS: return "M_DANFOSS" case KnxManufacturer_M_AST_GMBH: return "M_AST_GMBH" case KnxManufacturer_M_WILA_LEUCHTEN: return "M_WILA_LEUCHTEN" case KnxManufacturer_M_BPlusB_AUTOMATIONS__UND_STEUERUNGSTECHNIK: return "M_BPlusB_AUTOMATIONS__UND_STEUERUNGSTECHNIK" case KnxManufacturer_M_ABB_SCHWEIZ: return "M_ABB_SCHWEIZ" case KnxManufacturer_M_LINGG_AND_JANKE: return "M_LINGG_AND_JANKE" case KnxManufacturer_M_SAUTER: return "M_SAUTER" case KnxManufacturer_M_SIMU: return "M_SIMU" case KnxManufacturer_M_THEBEN_HTS_AG: return "M_THEBEN_HTS_AG" case KnxManufacturer_M_AMANN_GMBH: return "M_AMANN_GMBH" case KnxManufacturer_M_BERG_ENERGIEKONTROLLSYSTEME_GMBH: return "M_BERG_ENERGIEKONTROLLSYSTEME_GMBH" case KnxManufacturer_M_HUEPPE_FORM_SONNENSCHUTZSYSTEME_GMBH: return "M_HUEPPE_FORM_SONNENSCHUTZSYSTEME_GMBH" case KnxManufacturer_M_OVENTROP_KG: return "M_OVENTROP_KG" case KnxManufacturer_M_GRIESSER_AG: return "M_GRIESSER_AG" case KnxManufacturer_M_IPAS_GMBH: return "M_IPAS_GMBH" case KnxManufacturer_M_FELLER: return "M_FELLER" case KnxManufacturer_M_ELERO_GMBH: return "M_ELERO_GMBH" case KnxManufacturer_M_ARDAN_PRODUCTION_AND_INDUSTRIAL_CONTROLS_LTD_: return "M_ARDAN_PRODUCTION_AND_INDUSTRIAL_CONTROLS_LTD_" case KnxManufacturer_M_METEC_MESSTECHNIK_GMBH: return "M_METEC_MESSTECHNIK_GMBH" case KnxManufacturer_M_ELKA_ELEKTRONIK_GMBH: return "M_ELKA_ELEKTRONIK_GMBH" case KnxManufacturer_M_ELEKTROANLAGEN_D__NAGEL: return "M_ELEKTROANLAGEN_D__NAGEL" case KnxManufacturer_M_TRIDONIC_BAUELEMENTE_GMBH: return "M_TRIDONIC_BAUELEMENTE_GMBH" case KnxManufacturer_M_STENGLER_GESELLSCHAFT: return "M_STENGLER_GESELLSCHAFT" case KnxManufacturer_M_SCHNEIDER_ELECTRIC_MG: return "M_SCHNEIDER_ELECTRIC_MG" case KnxManufacturer_M_KNX_ASSOCIATION: return "M_KNX_ASSOCIATION" case KnxManufacturer_M_VIVO: return "M_VIVO" case KnxManufacturer_M_ABB: return "M_ABB" case KnxManufacturer_M_GLAMOX_AS: return "M_GLAMOX_AS" case KnxManufacturer_M_HUGO_MUELLER_GMBH_AND_CO_KG: return "M_HUGO_MUELLER_GMBH_AND_CO_KG" case KnxManufacturer_M_SIEMENS_HVAC: return "M_SIEMENS_HVAC" case KnxManufacturer_M_APT: return "M_APT" case KnxManufacturer_M_HIGHDOM: return "M_HIGHDOM" case KnxManufacturer_M_TOP_SERVICES: return "M_TOP_SERVICES" case KnxManufacturer_M_AMBIHOME: return "M_AMBIHOME" case KnxManufacturer_M_DATEC_ELECTRONIC_AG: return "M_DATEC_ELECTRONIC_AG" case KnxManufacturer_M_ABUS_SECURITY_CENTER: return "M_ABUS_SECURITY_CENTER" case KnxManufacturer_M_LITE_PUTER: return "M_LITE_PUTER" case KnxManufacturer_M_TANTRON_ELECTRONIC: return "M_TANTRON_ELECTRONIC" case KnxManufacturer_M_DEHN_AND_SOEHNE: return "M_DEHN_AND_SOEHNE" case KnxManufacturer_M_INTERRA: return "M_INTERRA" case KnxManufacturer_M_DKX_TECH: return "M_DKX_TECH" case KnxManufacturer_M_VIATRON: return "M_VIATRON" case KnxManufacturer_M_NAUTIBUS: return "M_NAUTIBUS" case KnxManufacturer_M_ON_SEMICONDUCTOR: return "M_ON_SEMICONDUCTOR" case KnxManufacturer_M_LONGCHUANG: return "M_LONGCHUANG" case KnxManufacturer_M_AIR_ON_AG: return "M_AIR_ON_AG" case KnxManufacturer_M_IB_COMPANY_GMBH: return "M_IB_COMPANY_GMBH" case KnxManufacturer_M_SATION_FACTORY: return "M_SATION_FACTORY" case KnxManufacturer_M_AGENTILO_GMBH: return "M_AGENTILO_GMBH" case KnxManufacturer_M_CRABTREE: return "M_CRABTREE" case KnxManufacturer_M_MAKEL_ELEKTRIK: return "M_MAKEL_ELEKTRIK" case KnxManufacturer_M_HELIOS_VENTILATOREN: return "M_HELIOS_VENTILATOREN" case KnxManufacturer_M_OTTO_SOLUTIONS_PTE_LTD: return "M_OTTO_SOLUTIONS_PTE_LTD" case KnxManufacturer_M_AIRMASTER: return "M_AIRMASTER" case KnxManufacturer_M_VALLOX_GMBH: return "M_VALLOX_GMBH" case KnxManufacturer_M_DALITEK: return "M_DALITEK" case KnxManufacturer_M_ASIN: return "M_ASIN" case KnxManufacturer_M_BRIDGES_INTELLIGENCE_TECHNOLOGY_INC_: return "M_BRIDGES_INTELLIGENCE_TECHNOLOGY_INC_" case KnxManufacturer_M_ARBONIA: return "M_ARBONIA" case KnxManufacturer_M_KERMI: return "M_KERMI" case KnxManufacturer_M_EVOKNX: return "M_EVOKNX" case KnxManufacturer_M_PROLUX: return "M_PROLUX" case KnxManufacturer_M_CLICHOME: return "M_CLICHOME" case KnxManufacturer_M_COMMAX: return "M_COMMAX" case KnxManufacturer_M_EAE: return "M_EAE" case KnxManufacturer_M_TENSE: return "M_TENSE" case KnxManufacturer_M_SEYOUNG_ELECTRONICS: return "M_SEYOUNG_ELECTRONICS" case KnxManufacturer_M_LIFEDOMUS: return "M_LIFEDOMUS" case KnxManufacturer_M_EUROTRONIC_TECHNOLOGY_GMBH: return "M_EUROTRONIC_TECHNOLOGY_GMBH" case KnxManufacturer_M_TCI: return "M_TCI" case KnxManufacturer_M_RISHUN_ELECTRONIC: return "M_RISHUN_ELECTRONIC" case KnxManufacturer_M_PAUL_HOCHKOEPPER: return "M_PAUL_HOCHKOEPPER" case KnxManufacturer_M_ZIPATO: return "M_ZIPATO" case KnxManufacturer_M_CM_SECURITY_GMBH_AND_CO_KG: return "M_CM_SECURITY_GMBH_AND_CO_KG" case KnxManufacturer_M_QING_CABLES: return "M_QING_CABLES" case KnxManufacturer_M_LABIO: return "M_LABIO" case KnxManufacturer_M_COSTER_TECNOLOGIE_ELETTRONICHE_S_P_A_: return "M_COSTER_TECNOLOGIE_ELETTRONICHE_S_P_A_" case KnxManufacturer_M_E_G_E: return "M_E_G_E" case KnxManufacturer_M_NETXAUTOMATION: return "M_NETXAUTOMATION" case KnxManufacturer_M_TECALOR: return "M_TECALOR" case KnxManufacturer_M_URMET_ELECTRONICS_HUIZHOU_LTD_: return "M_URMET_ELECTRONICS_HUIZHOU_LTD_" case KnxManufacturer_M_PEIYING_BUILDING_CONTROL: return "M_PEIYING_BUILDING_CONTROL" case KnxManufacturer_M_ALTENBURGER_ELECTRONIC: return "M_ALTENBURGER_ELECTRONIC" case KnxManufacturer_M_BPT_S_P_A__A_SOCIO_UNICO: return "M_BPT_S_P_A__A_SOCIO_UNICO" case KnxManufacturer_M_KANONTEC___KANONBUS: return "M_KANONTEC___KANONBUS" case KnxManufacturer_M_ISER_TECH: return "M_ISER_TECH" case KnxManufacturer_M_FINELINE: return "M_FINELINE" case KnxManufacturer_M_CP_ELECTRONICS_LTD: return "M_CP_ELECTRONICS_LTD" case KnxManufacturer_M_NIKO_SERVODAN_AS: return "M_NIKO_SERVODAN_AS" case KnxManufacturer_M_SIMON_309: return "M_SIMON_309" case KnxManufacturer_M_GM_MODULAR_PVT__LTD_: return "M_GM_MODULAR_PVT__LTD_" case KnxManufacturer_M_FU_CHENG_INTELLIGENCE: return "M_FU_CHENG_INTELLIGENCE" case KnxManufacturer_M_NEXKON: return "M_NEXKON" case KnxManufacturer_M_GRAESSLIN: return "M_GRAESSLIN" case KnxManufacturer_M_FEEL_S_R_L: return "M_FEEL_S_R_L" case KnxManufacturer_M_NOT_ASSIGNED_314: return "M_NOT_ASSIGNED_314" case KnxManufacturer_M_SHENZHEN_FANHAI_SANJIANG_ELECTRONICS_CO___LTD_: return "M_SHENZHEN_FANHAI_SANJIANG_ELECTRONICS_CO___LTD_" case KnxManufacturer_M_JIUZHOU_GREEBLE: return "M_JIUZHOU_GREEBLE" case KnxManufacturer_M_AUMUELLER_AUMATIC_GMBH: return "M_AUMUELLER_AUMATIC_GMBH" case KnxManufacturer_M_ETMAN_ELECTRIC: return "M_ETMAN_ELECTRIC" case KnxManufacturer_M_BLACK_NOVA: return "M_BLACK_NOVA" case KnxManufacturer_M_ZIDATECH_AG: return "M_ZIDATECH_AG" case KnxManufacturer_M_IDGS_BVBA: return "M_IDGS_BVBA" case KnxManufacturer_M_DAKANIMO: return "M_DAKANIMO" case KnxManufacturer_M_SIMON_42: return "M_SIMON_42" case KnxManufacturer_M_TREBOR_AUTOMATION_AB: return "M_TREBOR_AUTOMATION_AB" case KnxManufacturer_M_SATEL_SP__Z_O_O_: return "M_SATEL_SP__Z_O_O_" case KnxManufacturer_M_RUSSOUND__INC_: return "M_RUSSOUND__INC_" case KnxManufacturer_M_MIDEA_HEATING_AND_VENTILATING_EQUIPMENT_CO_LTD: return "M_MIDEA_HEATING_AND_VENTILATING_EQUIPMENT_CO_LTD" case KnxManufacturer_M_CONSORZIO_TERRANUOVA: return "M_CONSORZIO_TERRANUOVA" case KnxManufacturer_M_WOLF_HEIZTECHNIK_GMBH: return "M_WOLF_HEIZTECHNIK_GMBH" case KnxManufacturer_M_SONTEC: return "M_SONTEC" case KnxManufacturer_M_BELCOM_CABLES_LTD_: return "M_BELCOM_CABLES_LTD_" case KnxManufacturer_M_GUANGZHOU_SEAWIN_ELECTRICAL_TECHNOLOGIES_CO___LTD_: return "M_GUANGZHOU_SEAWIN_ELECTRICAL_TECHNOLOGIES_CO___LTD_" case KnxManufacturer_M_ACREL: return "M_ACREL" case KnxManufacturer_M_VIMAR: return "M_VIMAR" case KnxManufacturer_M_FRANKE_AQUAROTTER_GMBH: return "M_FRANKE_AQUAROTTER_GMBH" case KnxManufacturer_M_ORION_SYSTEMS: return "M_ORION_SYSTEMS" case KnxManufacturer_M_SCHRACK_TECHNIK_GMBH: return "M_SCHRACK_TECHNIK_GMBH" case KnxManufacturer_M_INSPRID: return "M_INSPRID" case KnxManufacturer_M_SUNRICHER: return "M_SUNRICHER" case KnxManufacturer_M_MENRED_AUTOMATION_SYSTEMSHANGHAI_CO__LTD_: return "M_MENRED_AUTOMATION_SYSTEMSHANGHAI_CO__LTD_" case KnxManufacturer_M_AUREX: return "M_AUREX" case KnxManufacturer_M_JOSEF_BARTHELME_GMBH_AND_CO__KG: return "M_JOSEF_BARTHELME_GMBH_AND_CO__KG" case KnxManufacturer_M_ARCHITECTURE_NUMERIQUE: return "M_ARCHITECTURE_NUMERIQUE" case KnxManufacturer_M_UP_GROUP: return "M_UP_GROUP" case KnxManufacturer_M_MOELLER_GEBAEUDEAUTOMATION_KG: return "M_MOELLER_GEBAEUDEAUTOMATION_KG" case KnxManufacturer_M_TEKNOS_AVINNO: return "M_TEKNOS_AVINNO" case KnxManufacturer_M_NINGBO_DOOYA_MECHANIC_AND_ELECTRONIC_TECHNOLOGY: return "M_NINGBO_DOOYA_MECHANIC_AND_ELECTRONIC_TECHNOLOGY" case KnxManufacturer_M_THERMOKON_SENSORTECHNIK_GMBH: return "M_THERMOKON_SENSORTECHNIK_GMBH" case KnxManufacturer_M_BELIMO_AUTOMATION_AG: return "M_BELIMO_AUTOMATION_AG" case KnxManufacturer_M_ZEHNDER_GROUP_INTERNATIONAL_AG: return "M_ZEHNDER_GROUP_INTERNATIONAL_AG" case KnxManufacturer_M_SKS_KINKEL_ELEKTRONIK: return "M_SKS_KINKEL_ELEKTRONIK" case KnxManufacturer_M_ECE_WURMITZER_GMBH: return "M_ECE_WURMITZER_GMBH" case KnxManufacturer_M_LARS: return "M_LARS" case KnxManufacturer_M_URC: return "M_URC" case KnxManufacturer_M_LIGHTCONTROL: return "M_LIGHTCONTROL" case KnxManufacturer_M_ALBRECHT_JUNG: return "M_ALBRECHT_JUNG" case KnxManufacturer_M_ELTAKO: return "M_ELTAKO" case KnxManufacturer_M_SHENZHEN_YM: return "M_SHENZHEN_YM" case KnxManufacturer_M_MEAN_WELL_ENTERPRISES_CO__LTD_: return "M_MEAN_WELL_ENTERPRISES_CO__LTD_" case KnxManufacturer_M_OSIX: return "M_OSIX" case KnxManufacturer_M_AYPRO_TECHNOLOGY: return "M_AYPRO_TECHNOLOGY" case KnxManufacturer_M_HEFEI_ECOLITE_SOFTWARE: return "M_HEFEI_ECOLITE_SOFTWARE" case KnxManufacturer_M_ENNO: return "M_ENNO" case KnxManufacturer_M_OHOSURE: return "M_OHOSURE" case KnxManufacturer_M_GAREFOWL: return "M_GAREFOWL" case KnxManufacturer_M_GEZE: return "M_GEZE" case KnxManufacturer_M_LG_ELECTRONICS_INC_: return "M_LG_ELECTRONICS_INC_" case KnxManufacturer_M_BOSCH_SIEMENS_HAUSHALTSGERAETE: return "M_BOSCH_SIEMENS_HAUSHALTSGERAETE" case KnxManufacturer_M_SMC_INTERIORS: return "M_SMC_INTERIORS" case KnxManufacturer_M_NOT_ASSIGNED_364: return "M_NOT_ASSIGNED_364" case KnxManufacturer_M_SCS_CABLE: return "M_SCS_CABLE" case KnxManufacturer_M_HOVAL: return "M_HOVAL" case KnxManufacturer_M_CANST: return "M_CANST" case KnxManufacturer_M_HANGZHOU_BERLIN: return "M_HANGZHOU_BERLIN" case KnxManufacturer_M_EVN_LICHTTECHNIK: return "M_EVN_LICHTTECHNIK" case KnxManufacturer_M_RUTEC: return "M_RUTEC" case KnxManufacturer_M_FINDER: return "M_FINDER" case KnxManufacturer_M_FUJITSU_GENERAL_LIMITED: return "M_FUJITSU_GENERAL_LIMITED" case KnxManufacturer_M_RITTO_GMBHANDCO_KG: return "M_RITTO_GMBHANDCO_KG" case KnxManufacturer_M_ZF_FRIEDRICHSHAFEN_AG: return "M_ZF_FRIEDRICHSHAFEN_AG" case KnxManufacturer_M_CREALED: return "M_CREALED" case KnxManufacturer_M_MILES_MAGIC_AUTOMATION_PRIVATE_LIMITED: return "M_MILES_MAGIC_AUTOMATION_PRIVATE_LIMITED" case KnxManufacturer_M_EPlus: return "M_EPlus" case KnxManufacturer_M_ITALCOND: return "M_ITALCOND" case KnxManufacturer_M_SATION: return "M_SATION" case KnxManufacturer_M_NEWBEST: return "M_NEWBEST" case KnxManufacturer_M_GDS_DIGITAL_SYSTEMS: return "M_GDS_DIGITAL_SYSTEMS" case KnxManufacturer_M_IDDERO: return "M_IDDERO" case KnxManufacturer_M_MBNLED: return "M_MBNLED" case KnxManufacturer_M_POWER_CONTROLS: return "M_POWER_CONTROLS" case KnxManufacturer_M_VITRUM: return "M_VITRUM" case KnxManufacturer_M_EKEY_BIOMETRIC_SYSTEMS_GMBH: return "M_EKEY_BIOMETRIC_SYSTEMS_GMBH" case KnxManufacturer_M_AMC: return "M_AMC" case KnxManufacturer_M_TRILUX_GMBH_AND_CO__KG: return "M_TRILUX_GMBH_AND_CO__KG" case KnxManufacturer_M_WEXCEDO: return "M_WEXCEDO" case KnxManufacturer_M_VEMER_SPA: return "M_VEMER_SPA" case KnxManufacturer_M_ALEXANDER_BUERKLE_GMBH_AND_CO_KG: return "M_ALEXANDER_BUERKLE_GMBH_AND_CO_KG" case KnxManufacturer_M_CITRON: return "M_CITRON" case KnxManufacturer_M_SHENZHEN_HEGUANG: return "M_SHENZHEN_HEGUANG" case KnxManufacturer_M_NOT_ASSIGNED_392: return "M_NOT_ASSIGNED_392" case KnxManufacturer_M_ZUMTOBEL: return "M_ZUMTOBEL" case KnxManufacturer_M_TRANE_B_V_B_A: return "M_TRANE_B_V_B_A" case KnxManufacturer_M_CAREL: return "M_CAREL" case KnxManufacturer_M_PROLITE_CONTROLS: return "M_PROLITE_CONTROLS" case KnxManufacturer_M_BOSMER: return "M_BOSMER" case KnxManufacturer_M_EUCHIPS: return "M_EUCHIPS" case KnxManufacturer_M_CONNECT_THINKA_CONNECT: return "M_CONNECT_THINKA_CONNECT" case KnxManufacturer_M_PEAKNX_A_DOGAWIST_COMPANY: return "M_PEAKNX_A_DOGAWIST_COMPANY" case KnxManufacturer_M_ACEMATIC: return "M_ACEMATIC" case KnxManufacturer_M_ELAUSYS: return "M_ELAUSYS" case KnxManufacturer_M_ITK_ENGINEERING_AG: return "M_ITK_ENGINEERING_AG" case KnxManufacturer_M_PHOENIX_CONTACT: return "M_PHOENIX_CONTACT" case KnxManufacturer_M_INTEGRA_METERING_AG: return "M_INTEGRA_METERING_AG" case KnxManufacturer_M_FMS_HOSPITALITY_PTE_LTD: return "M_FMS_HOSPITALITY_PTE_LTD" case KnxManufacturer_M_NUVO: return "M_NUVO" case KnxManufacturer_M_U__LUX_GMBH: return "M_U__LUX_GMBH" case KnxManufacturer_M_BRUMBERG_LEUCHTEN: return "M_BRUMBERG_LEUCHTEN" case KnxManufacturer_M_LIME: return "M_LIME" case KnxManufacturer_M_GREAT_EMPIRE_INTERNATIONAL_GROUP_CO___LTD_: return "M_GREAT_EMPIRE_INTERNATIONAL_GROUP_CO___LTD_" case KnxManufacturer_M_KAVOSHPISHRO_ASIA: return "M_KAVOSHPISHRO_ASIA" case KnxManufacturer_M_V2_SPA: return "M_V2_SPA" case KnxManufacturer_M_JOHNSON_CONTROLS: return "M_JOHNSON_CONTROLS" case KnxManufacturer_M_WAGO_KONTAKTTECHNIK: return "M_WAGO_KONTAKTTECHNIK" case KnxManufacturer_M_ARKUD: return "M_ARKUD" case KnxManufacturer_M_IRIDIUM_LTD_: return "M_IRIDIUM_LTD_" case KnxManufacturer_M_BSMART: return "M_BSMART" case KnxManufacturer_M_BAB_TECHNOLOGIE_GMBH: return "M_BAB_TECHNOLOGIE_GMBH" case KnxManufacturer_M_NICE_SPA: return "M_NICE_SPA" case KnxManufacturer_M_REDFISH_GROUP_PTY_LTD: return "M_REDFISH_GROUP_PTY_LTD" case KnxManufacturer_M_SABIANA_SPA: return "M_SABIANA_SPA" case KnxManufacturer_M_UBEE_INTERACTIVE_EUROPE: return "M_UBEE_INTERACTIVE_EUROPE" case KnxManufacturer_M_REXEL: return "M_REXEL" case KnxManufacturer_M_GES_TEKNIK_A_S_: return "M_GES_TEKNIK_A_S_" case KnxManufacturer_M_KNXPRESSO: return "M_KNXPRESSO" case KnxManufacturer_M_AVE_S_P_A_: return "M_AVE_S_P_A_" case KnxManufacturer_M_ZHUHAI_LTECH_TECHNOLOGY_CO___LTD_: return "M_ZHUHAI_LTECH_TECHNOLOGY_CO___LTD_" case KnxManufacturer_M_ARCOM: return "M_ARCOM" case KnxManufacturer_M_VIA_TECHNOLOGIES__INC_: return "M_VIA_TECHNOLOGIES__INC_" case KnxManufacturer_M_FEELSMART_: return "M_FEELSMART_" case KnxManufacturer_M_SUPCON: return "M_SUPCON" case KnxManufacturer_M_MANIC: return "M_MANIC" case KnxManufacturer_M_TDE_GMBH: return "M_TDE_GMBH" case KnxManufacturer_M_NANJING_SHUFAN_INFORMATION_TECHNOLOGY_CO__LTD_: return "M_NANJING_SHUFAN_INFORMATION_TECHNOLOGY_CO__LTD_" case KnxManufacturer_M_EWTECH: return "M_EWTECH" case KnxManufacturer_M_WIELAND_ELECTRIC: return "M_WIELAND_ELECTRIC" case KnxManufacturer_M_KLUGER_AUTOMATION_GMBH: return "M_KLUGER_AUTOMATION_GMBH" case KnxManufacturer_M_JOONGANG_CONTROL: return "M_JOONGANG_CONTROL" case KnxManufacturer_M_GREENCONTROLS_TECHNOLOGY_SDN__BHD_: return "M_GREENCONTROLS_TECHNOLOGY_SDN__BHD_" case KnxManufacturer_M_IME_S_P_A_: return "M_IME_S_P_A_" case KnxManufacturer_M_SICHUAN_HAODING: return "M_SICHUAN_HAODING" case KnxManufacturer_M_MINDJAGA_LTD_: return "M_MINDJAGA_LTD_" case KnxManufacturer_M_RUILI_SMART_CONTROL: return "M_RUILI_SMART_CONTROL" case KnxManufacturer_M_CODESYS_GMBH: return "M_CODESYS_GMBH" case KnxManufacturer_M_MOORGEN_DEUTSCHLAND_GMBH: return "M_MOORGEN_DEUTSCHLAND_GMBH" case KnxManufacturer_M_CULLMANN_TECH: return "M_CULLMANN_TECH" case KnxManufacturer_M_HERMANN_KLEINHUIS: return "M_HERMANN_KLEINHUIS" case KnxManufacturer_M_MERCK_WINDOW_TECHNOLOGIES_B_V_: return "M_MERCK_WINDOW_TECHNOLOGIES_B_V_" case KnxManufacturer_M_ABEGO: return "M_ABEGO" case KnxManufacturer_M_MYGEKKO: return "M_MYGEKKO" case KnxManufacturer_M_ERGO3_SARL: return "M_ERGO3_SARL" case KnxManufacturer_M_STMICROELECTRONICS_INTERNATIONAL_N_V_: return "M_STMICROELECTRONICS_INTERNATIONAL_N_V_" case KnxManufacturer_M_CJC_SYSTEMS: return "M_CJC_SYSTEMS" case KnxManufacturer_M_SUDOKU: return "M_SUDOKU" case KnxManufacturer_M_AZ_E_LITE_PTE_LTD: return "M_AZ_E_LITE_PTE_LTD" case KnxManufacturer_M_ARLIGHT: return "M_ARLIGHT" case KnxManufacturer_M_GRUENBECK_WASSERAUFBEREITUNG_GMBH: return "M_GRUENBECK_WASSERAUFBEREITUNG_GMBH" case KnxManufacturer_M_BTICINO: return "M_BTICINO" case KnxManufacturer_M_STIEBEL_ELTRON: return "M_STIEBEL_ELTRON" case KnxManufacturer_M_MODULE_ELECTRONIC: return "M_MODULE_ELECTRONIC" case KnxManufacturer_M_KOPLAT: return "M_KOPLAT" case KnxManufacturer_M_GUANGZHOU_LETOUR_LIFE_TECHNOLOGY_CO___LTD: return "M_GUANGZHOU_LETOUR_LIFE_TECHNOLOGY_CO___LTD" case KnxManufacturer_M_ILEVIA: return "M_ILEVIA" case KnxManufacturer_M_LN_SYSTEMTEQ: return "M_LN_SYSTEMTEQ" case KnxManufacturer_M_HISENSE_SMARTHOME: return "M_HISENSE_SMARTHOME" case KnxManufacturer_M_FLINK_AUTOMATION_SYSTEM: return "M_FLINK_AUTOMATION_SYSTEM" case KnxManufacturer_M_XXTER_BV: return "M_XXTER_BV" case KnxManufacturer_M_LYNXUS_TECHNOLOGY: return "M_LYNXUS_TECHNOLOGY" case KnxManufacturer_M_ROBOT_S_A_: return "M_ROBOT_S_A_" case KnxManufacturer_M_TEHALIT: return "M_TEHALIT" case KnxManufacturer_M_SHENZHEN_ATTE_SMART_LIFE_CO__LTD_: return "M_SHENZHEN_ATTE_SMART_LIFE_CO__LTD_" case KnxManufacturer_M_NOBLESSE: return "M_NOBLESSE" case KnxManufacturer_M_ADVANCED_DEVICES: return "M_ADVANCED_DEVICES" case KnxManufacturer_M_ATRINA_BUILDING_AUTOMATION_CO__LTD: return "M_ATRINA_BUILDING_AUTOMATION_CO__LTD" case KnxManufacturer_M_GUANGDONG_DAMING_LAFFEY_ELECTRIC_CO___LTD_: return "M_GUANGDONG_DAMING_LAFFEY_ELECTRIC_CO___LTD_" case KnxManufacturer_M_WESTERSTRAND_URFABRIK_AB: return "M_WESTERSTRAND_URFABRIK_AB" case KnxManufacturer_M_CONTROL4_CORPORATE: return "M_CONTROL4_CORPORATE" case KnxManufacturer_M_ONTROL: return "M_ONTROL" case KnxManufacturer_M_STARNET: return "M_STARNET" case KnxManufacturer_M_BETA_CAVI: return "M_BETA_CAVI" case KnxManufacturer_M_THEBEN_AG: return "M_THEBEN_AG" case KnxManufacturer_M_EASEMORE: return "M_EASEMORE" case KnxManufacturer_M_VIVALDI_SRL: return "M_VIVALDI_SRL" case KnxManufacturer_M_GREE_ELECTRIC_APPLIANCES_INC__OF_ZHUHAI: return "M_GREE_ELECTRIC_APPLIANCES_INC__OF_ZHUHAI" case KnxManufacturer_M_HWISCON: return "M_HWISCON" case KnxManufacturer_M_SHANGHAI_ELECON_INTELLIGENT_TECHNOLOGY_CO___LTD_: return "M_SHANGHAI_ELECON_INTELLIGENT_TECHNOLOGY_CO___LTD_" case KnxManufacturer_M_KAMPMANN: return "M_KAMPMANN" case KnxManufacturer_M_IMPOLUX_GMBH_LEDIMAX: return "M_IMPOLUX_GMBH_LEDIMAX" case KnxManufacturer_M_EVAUX: return "M_EVAUX" case KnxManufacturer_M_WEBRO_CABLES_AND_CONNECTORS_LIMITED: return "M_WEBRO_CABLES_AND_CONNECTORS_LIMITED" case KnxManufacturer_M_SHANGHAI_E_TECH_SOLUTION: return "M_SHANGHAI_E_TECH_SOLUTION" case KnxManufacturer_M_WILHELM_RUTENBECK: return "M_WILHELM_RUTENBECK" case KnxManufacturer_M_GUANGZHOU_HOKO_ELECTRIC_CO__LTD_: return "M_GUANGZHOU_HOKO_ELECTRIC_CO__LTD_" case KnxManufacturer_M_LAMMIN_HIGH_TECH_CO__LTD: return "M_LAMMIN_HIGH_TECH_CO__LTD" case KnxManufacturer_M_SHENZHEN_MERRYTEK_TECHNOLOGY_CO___LTD: return "M_SHENZHEN_MERRYTEK_TECHNOLOGY_CO___LTD" case KnxManufacturer_M_I_LUXUS: return "M_I_LUXUS" case KnxManufacturer_M_ELMOS_SEMICONDUCTOR_AG: return "M_ELMOS_SEMICONDUCTOR_AG" case KnxManufacturer_M_EMCOM_TECHNOLOGY_INC: return "M_EMCOM_TECHNOLOGY_INC" case KnxManufacturer_M_PROJECT_INNOVATIONS_GMBH: return "M_PROJECT_INNOVATIONS_GMBH" case KnxManufacturer_M_ITC: return "M_ITC" case KnxManufacturer_M_ABB_LV_INSTALLATION_MATERIALS_COMPANY_LTD__BEIJING: return "M_ABB_LV_INSTALLATION_MATERIALS_COMPANY_LTD__BEIJING" case KnxManufacturer_M_MAICO: return "M_MAICO" case KnxManufacturer_M_WINKHAUS: return "M_WINKHAUS" case KnxManufacturer_M_ELAN_SRL: return "M_ELAN_SRL" case KnxManufacturer_M_MINHHA_TECHNOLOGY_CO__LTD: return "M_MINHHA_TECHNOLOGY_CO__LTD" case KnxManufacturer_M_ZHEJIANG_TIANJIE_INDUSTRIAL_CORP_: return "M_ZHEJIANG_TIANJIE_INDUSTRIAL_CORP_" case KnxManufacturer_M_IAUTOMATION_PTY_LIMITED: return "M_IAUTOMATION_PTY_LIMITED" case KnxManufacturer_M_EXTRON: return "M_EXTRON" case KnxManufacturer_M_FREEDOMPRO: return "M_FREEDOMPRO" case KnxManufacturer_M_ONEHOME: return "M_ONEHOME" case KnxManufacturer_M_EOS_SAUNATECHNIK_GMBH: return "M_EOS_SAUNATECHNIK_GMBH" case KnxManufacturer_M_KUSATEK_GMBH: return "M_KUSATEK_GMBH" case KnxManufacturer_M_EISBAER_SCADA: return "M_EISBAER_SCADA" case KnxManufacturer_M_ROBERT_BOSCH: return "M_ROBERT_BOSCH" case KnxManufacturer_M_AUTOMATISMI_BENINCA_S_P_A_: return "M_AUTOMATISMI_BENINCA_S_P_A_" case KnxManufacturer_M_BLENDOM: return "M_BLENDOM" case KnxManufacturer_M_MADEL_AIR_TECHNICAL_DIFFUSION: return "M_MADEL_AIR_TECHNICAL_DIFFUSION" case KnxManufacturer_M_NIKO: return "M_NIKO" case KnxManufacturer_M_BOSCH_REXROTH_AG: return "M_BOSCH_REXROTH_AG" case KnxManufacturer_M_CANDM_PRODUCTS: return "M_CANDM_PRODUCTS" case KnxManufacturer_M_HOERMANN_KG_VERKAUFSGESELLSCHAFT: return "M_HOERMANN_KG_VERKAUFSGESELLSCHAFT" case KnxManufacturer_M_SHANGHAI_RAJAYASA_CO__LTD: return "M_SHANGHAI_RAJAYASA_CO__LTD" case KnxManufacturer_M_SUZUKI: return "M_SUZUKI" case KnxManufacturer_M_SILENT_GLISS_INTERNATIONAL_LTD_: return "M_SILENT_GLISS_INTERNATIONAL_LTD_" case KnxManufacturer_M_SOMFY: return "M_SOMFY" case KnxManufacturer_M_BEE_CONTROLS_ADGSC_GROUP: return "M_BEE_CONTROLS_ADGSC_GROUP" case KnxManufacturer_M_XDTECGMBH: return "M_XDTECGMBH" case KnxManufacturer_M_OSRAM: return "M_OSRAM" case KnxManufacturer_M_LEBENOR: return "M_LEBENOR" case KnxManufacturer_M_AUTOMANENG: return "M_AUTOMANENG" case KnxManufacturer_M_HONEYWELL_AUTOMATION_SOLUTION_CONTROLCHINA: return "M_HONEYWELL_AUTOMATION_SOLUTION_CONTROLCHINA" case KnxManufacturer_M_HANGZHOU_BINTHEN_INTELLIGENCE_TECHNOLOGY_CO__LTD: return "M_HANGZHOU_BINTHEN_INTELLIGENCE_TECHNOLOGY_CO__LTD" case KnxManufacturer_M_ETA_HEIZTECHNIK: return "M_ETA_HEIZTECHNIK" case KnxManufacturer_M_DIVUS_GMBH: return "M_DIVUS_GMBH" case KnxManufacturer_M_NANJING_TAIJIESAI_INTELLIGENT_TECHNOLOGY_CO__LTD_: return "M_NANJING_TAIJIESAI_INTELLIGENT_TECHNOLOGY_CO__LTD_" case KnxManufacturer_M_WOERTZ: return "M_WOERTZ" case KnxManufacturer_M_LUNATONE: return "M_LUNATONE" case KnxManufacturer_M_ZHEJIANG_SCTECH_BUILDING_INTELLIGENT: return "M_ZHEJIANG_SCTECH_BUILDING_INTELLIGENT" case KnxManufacturer_M_FOSHAN_QITE_TECHNOLOGY_CO___LTD_: return "M_FOSHAN_QITE_TECHNOLOGY_CO___LTD_" case KnxManufacturer_M_NOKE: return "M_NOKE" case KnxManufacturer_M_LANDCOM: return "M_LANDCOM" case KnxManufacturer_M_STORK_AS: return "M_STORK_AS" case KnxManufacturer_M_HANGZHOU_SHENDU_TECHNOLOGY_CO___LTD_: return "M_HANGZHOU_SHENDU_TECHNOLOGY_CO___LTD_" case KnxManufacturer_M_COOLAUTOMATION: return "M_COOLAUTOMATION" case KnxManufacturer_M_APRSTERN: return "M_APRSTERN" case KnxManufacturer_M_SONNEN: return "M_SONNEN" case KnxManufacturer_M_VIESSMANN_WERKE: return "M_VIESSMANN_WERKE" case KnxManufacturer_M_DNAKE: return "M_DNAKE" case KnxManufacturer_M_NEUBERGER_GEBAEUDEAUTOMATION_GMBH: return "M_NEUBERGER_GEBAEUDEAUTOMATION_GMBH" case KnxManufacturer_M_STILIGER: return "M_STILIGER" case KnxManufacturer_M_BERGHOF_AUTOMATION_GMBH: return "M_BERGHOF_AUTOMATION_GMBH" case KnxManufacturer_M_TOTAL_AUTOMATION_AND_CONTROLS_GMBH: return "M_TOTAL_AUTOMATION_AND_CONTROLS_GMBH" case KnxManufacturer_M_DOVIT: return "M_DOVIT" case KnxManufacturer_M_INSTALIGHTING_GMBH: return "M_INSTALIGHTING_GMBH" case KnxManufacturer_M_UNI_TEC: return "M_UNI_TEC" case KnxManufacturer_M_CASATUNES: return "M_CASATUNES" case KnxManufacturer_M_EMT: return "M_EMT" case KnxManufacturer_M_IMI_HYDRONIC_ENGINEERING: return "M_IMI_HYDRONIC_ENGINEERING" case KnxManufacturer_M_SENFFICIENT: return "M_SENFFICIENT" case KnxManufacturer_M_AUROLITE_ELECTRICAL_PANYU_GUANGZHOU_LIMITED: return "M_AUROLITE_ELECTRICAL_PANYU_GUANGZHOU_LIMITED" case KnxManufacturer_M_ABB_XIAMEN_SMART_TECHNOLOGY_CO___LTD_: return "M_ABB_XIAMEN_SMART_TECHNOLOGY_CO___LTD_" case KnxManufacturer_M_SAMSON_ELECTRIC_WIRE: return "M_SAMSON_ELECTRIC_WIRE" case KnxManufacturer_M_T_TOUCHING: return "M_T_TOUCHING" case KnxManufacturer_M_CORE_SMART_HOME: return "M_CORE_SMART_HOME" case KnxManufacturer_M_GREENCONNECT_SOLUTIONS_SA: return "M_GREENCONNECT_SOLUTIONS_SA" case KnxManufacturer_M_ELETTRONICA_CONDUTTORI: return "M_ELETTRONICA_CONDUTTORI" case KnxManufacturer_M_MKFC: return "M_MKFC" case KnxManufacturer_M_AUTOMATIONPlus: return "M_AUTOMATIONPlus" case KnxManufacturer_M_BERKER: return "M_BERKER" case KnxManufacturer_M_JOH__VAILLANT: return "M_JOH__VAILLANT" case KnxManufacturer_M_BLUE_AND_RED: return "M_BLUE_AND_RED" case KnxManufacturer_M_FROGBLUE: return "M_FROGBLUE" case KnxManufacturer_M_SAVESOR: return "M_SAVESOR" case KnxManufacturer_M_APP_TECH: return "M_APP_TECH" case KnxManufacturer_M_SENSORTEC_AG: return "M_SENSORTEC_AG" case KnxManufacturer_M_NYSA_TECHNOLOGY_AND_SOLUTIONS: return "M_NYSA_TECHNOLOGY_AND_SOLUTIONS" case KnxManufacturer_M_FARADITE: return "M_FARADITE" case KnxManufacturer_M_OPTIMUS: return "M_OPTIMUS" case KnxManufacturer_M_KTS_S_R_L_: return "M_KTS_S_R_L_" case KnxManufacturer_M_RAMCRO_SPA: return "M_RAMCRO_SPA" case KnxManufacturer_M_AMP_DEUTSCHLAND: return "M_AMP_DEUTSCHLAND" case KnxManufacturer_M_WUHAN_WISECREATE_UNIVERSE_TECHNOLOGY_CO___LTD: return "M_WUHAN_WISECREATE_UNIVERSE_TECHNOLOGY_CO___LTD" case KnxManufacturer_M_BEMI_SMART_HOME_LTD: return "M_BEMI_SMART_HOME_LTD" case KnxManufacturer_M_ARDOMUS: return "M_ARDOMUS" case KnxManufacturer_M_CHANGXING: return "M_CHANGXING" case KnxManufacturer_M_E_CONTROLS: return "M_E_CONTROLS" case KnxManufacturer_M_AIB_TECHNOLOGY: return "M_AIB_TECHNOLOGY" case KnxManufacturer_M_NVC: return "M_NVC" case KnxManufacturer_M_KBOX: return "M_KBOX" case KnxManufacturer_M_CNS: return "M_CNS" case KnxManufacturer_M_TYBA: return "M_TYBA" case KnxManufacturer_M_BOSCH_THERMOTECHNIK_GMBH: return "M_BOSCH_THERMOTECHNIK_GMBH" case KnxManufacturer_M_ATREL: return "M_ATREL" case KnxManufacturer_M_SIMON_ELECTRIC_CHINA_CO___LTD: return "M_SIMON_ELECTRIC_CHINA_CO___LTD" case KnxManufacturer_M_KORDZ_GROUP: return "M_KORDZ_GROUP" case KnxManufacturer_M_ND_ELECTRIC: return "M_ND_ELECTRIC" case KnxManufacturer_M_CONTROLIUM: return "M_CONTROLIUM" case KnxManufacturer_M_FAMO_GMBH_AND_CO__KG: return "M_FAMO_GMBH_AND_CO__KG" case KnxManufacturer_M_CDN_SMART: return "M_CDN_SMART" case KnxManufacturer_M_HESTON: return "M_HESTON" case KnxManufacturer_M_ESLA_CONEXIONES_S_L_: return "M_ESLA_CONEXIONES_S_L_" case KnxManufacturer_M_WEISHAUPT: return "M_WEISHAUPT" case KnxManufacturer_M_SEF___ECOTEC: return "M_SEF___ECOTEC" case KnxManufacturer_M_ASTRUM_TECHNOLOGY: return "M_ASTRUM_TECHNOLOGY" case KnxManufacturer_M_WUERTH_ELEKTRONIK_STELVIO_KONTEK_S_P_A_: return "M_WUERTH_ELEKTRONIK_STELVIO_KONTEK_S_P_A_" case KnxManufacturer_M_NANOTECO_CORPORATION: return "M_NANOTECO_CORPORATION" case KnxManufacturer_M_NIETIAN: return "M_NIETIAN" case KnxManufacturer_M_SUMSIR: return "M_SUMSIR" case KnxManufacturer_M_ORBIS_TECNOLOGIA_ELECTRICA_SA: return "M_ORBIS_TECNOLOGIA_ELECTRICA_SA" case KnxManufacturer_M_NANJING_ZHONGYI_IOT_TECHNOLOGY_CO___LTD_: return "M_NANJING_ZHONGYI_IOT_TECHNOLOGY_CO___LTD_" case KnxManufacturer_M_ANLIPS: return "M_ANLIPS" case KnxManufacturer_M_GUANGDONG_PAK_CORPORATION_CO___LTD: return "M_GUANGDONG_PAK_CORPORATION_CO___LTD" case KnxManufacturer_M_BVK_TECHNOLOGY: return "M_BVK_TECHNOLOGY" case KnxManufacturer_M_DORMA_GMBH_Plus_CO__KG: return "M_DORMA_GMBH_Plus_CO__KG" case KnxManufacturer_M_SOLOMIO_SRL: return "M_SOLOMIO_SRL" case KnxManufacturer_M_DOMOTICA_LABS: return "M_DOMOTICA_LABS" case KnxManufacturer_M_NVC_INTERNATIONAL: return "M_NVC_INTERNATIONAL" case KnxManufacturer_M_BA: return "M_BA" case KnxManufacturer_M_IRIS_CERAMICA_GROUP: return "M_IRIS_CERAMICA_GROUP" case KnxManufacturer_M_WIREEO: return "M_WIREEO" case KnxManufacturer_M_NVCLIGHTING: return "M_NVCLIGHTING" case KnxManufacturer_M_JINAN_TIAN_DA_SHENG_INFORMATION_TECHNOLOGY_CO_: return "M_JINAN_TIAN_DA_SHENG_INFORMATION_TECHNOLOGY_CO_" case KnxManufacturer_M_ARMITI_TRADING: return "M_ARMITI_TRADING" case KnxManufacturer_M_ELEK: return "M_ELEK" case KnxManufacturer_M_WINDOWMASTER_AS: return "M_WINDOWMASTER_AS" case KnxManufacturer_M_ACCORDIA_SA: return "M_ACCORDIA_SA" case KnxManufacturer_M_OURICAN: return "M_OURICAN" case KnxManufacturer_M_INLIWOSE: return "M_INLIWOSE" case KnxManufacturer_M_BOSCH_SHANGHAI_SMART_LIFE_TECHNOLOGY_LTD_: return "M_BOSCH_SHANGHAI_SMART_LIFE_TECHNOLOGY_LTD_" case KnxManufacturer_M_SHK_KNX: return "M_SHK_KNX" case KnxManufacturer_M_AMPIO: return "M_AMPIO" case KnxManufacturer_M_MINGXING_WISDOM: return "M_MINGXING_WISDOM" case KnxManufacturer_M_ALTEN_SW_GMBH: return "M_ALTEN_SW_GMBH" case KnxManufacturer_M_ABB___RESERVED: return "M_ABB___RESERVED" case KnxManufacturer_M_BUSCH_JAEGER_ELEKTRO___RESERVED: return "M_BUSCH_JAEGER_ELEKTRO___RESERVED" case KnxManufacturer_M_WALTHER_WERKE: return "M_WALTHER_WERKE" case KnxManufacturer_M_ORAS: return "M_ORAS" case KnxManufacturer_M_DAETWYLER: return "M_DAETWYLER" case KnxManufacturer_M_ELECTRAK: return "M_ELECTRAK" case KnxManufacturer_M_BUSCH_JAEGER_ELEKTRO: return "M_BUSCH_JAEGER_ELEKTRO" case KnxManufacturer_M_TECHEM: return "M_TECHEM" case KnxManufacturer_M_SCHNEIDER_ELECTRIC_INDUSTRIES_SAS: return "M_SCHNEIDER_ELECTRIC_INDUSTRIES_SAS" case KnxManufacturer_M_WHD_WILHELM_HUBER_Plus_SOEHNE: return "M_WHD_WILHELM_HUBER_Plus_SOEHNE" case KnxManufacturer_M_BISCHOFF_ELEKTRONIK: return "M_BISCHOFF_ELEKTRONIK" case KnxManufacturer_M_JEPAZ: return "M_JEPAZ" case KnxManufacturer_M_RTS_AUTOMATION: return "M_RTS_AUTOMATION" case KnxManufacturer_M_EIBMARKT_GMBH: return "M_EIBMARKT_GMBH" case KnxManufacturer_M_WAREMA_RENKHOFF_SE: return "M_WAREMA_RENKHOFF_SE" case KnxManufacturer_M_EELECTRON: return "M_EELECTRON" case KnxManufacturer_M_BELDEN_WIRE_AND_CABLE_B_V_: return "M_BELDEN_WIRE_AND_CABLE_B_V_" case KnxManufacturer_M_GIRA_GIERSIEPEN: return "M_GIRA_GIERSIEPEN" case KnxManufacturer_M_BECKER_ANTRIEBE_GMBH: return "M_BECKER_ANTRIEBE_GMBH" case KnxManufacturer_M_J_STEHLEPlusSOEHNE_GMBH: return "M_J_STEHLEPlusSOEHNE_GMBH" case KnxManufacturer_M_AGFEO: return "M_AGFEO" case KnxManufacturer_M_ZENNIO: return "M_ZENNIO" case KnxManufacturer_M_TAPKO_TECHNOLOGIES: return "M_TAPKO_TECHNOLOGIES" case KnxManufacturer_M_HDL: return "M_HDL" case KnxManufacturer_M_UPONOR: return "M_UPONOR" case KnxManufacturer_M_SE_LIGHTMANAGEMENT_AG: return "M_SE_LIGHTMANAGEMENT_AG" case KnxManufacturer_M_ARCUS_EDS: return "M_ARCUS_EDS" case KnxManufacturer_M_INTESIS: return "M_INTESIS" case KnxManufacturer_M_HAGER_ELECTRO: return "M_HAGER_ELECTRO" case KnxManufacturer_M_HERHOLDT_CONTROLS_SRL: return "M_HERHOLDT_CONTROLS_SRL" case KnxManufacturer_M_NIKO_ZUBLIN: return "M_NIKO_ZUBLIN" case KnxManufacturer_M_DURABLE_TECHNOLOGIES: return "M_DURABLE_TECHNOLOGIES" case KnxManufacturer_M_INNOTEAM: return "M_INNOTEAM" case KnxManufacturer_M_ISE_GMBH: return "M_ISE_GMBH" case KnxManufacturer_M_TEAM_FOR_TRONICS: return "M_TEAM_FOR_TRONICS" case KnxManufacturer_M_CIAT: return "M_CIAT" case KnxManufacturer_M_REMEHA_BV: return "M_REMEHA_BV" case KnxManufacturer_M_ESYLUX: return "M_ESYLUX" case KnxManufacturer_M_BASALTE: return "M_BASALTE" case KnxManufacturer_M_INSTA_GMBH: return "M_INSTA_GMBH" case KnxManufacturer_M_VESTAMATIC: return "M_VESTAMATIC" case KnxManufacturer_M_MDT_TECHNOLOGIES: return "M_MDT_TECHNOLOGIES" case KnxManufacturer_M_WARENDORFER_KUECHEN_GMBH: return "M_WARENDORFER_KUECHEN_GMBH" case KnxManufacturer_M_VIDEO_STAR: return "M_VIDEO_STAR" case KnxManufacturer_M_SITEK: return "M_SITEK" case KnxManufacturer_M_CONTROLTRONIC: return "M_CONTROLTRONIC" case KnxManufacturer_M_FUNCTION_TECHNOLOGY: return "M_FUNCTION_TECHNOLOGY" case KnxManufacturer_M_AMX: return "M_AMX" case KnxManufacturer_M_ELDAT: return "M_ELDAT" case KnxManufacturer_M_PANASONIC: return "M_PANASONIC" } return "" } func (e KnxManufacturer) String() string { return e.name() }
return KnxManufacturer_M_BALMART case "M_GFS_GMBH": return KnxManufacturer_M_GFS_GMBH case "M_GEWISS":
guide.py
# MGEAR is under the terms of the MIT License # Copyright (c) 2016 Jeremie Passerin, Miquel Campos """Guide Foot banking 01 module""" from functools import partial import pymel.core as pm from mgear.shifter.component import guide from mgear.core import transform, pyqt from mgear.vendor.Qt import QtWidgets, QtCore from maya.app.general.mayaMixin import MayaQWidgetDockableMixin from maya.app.general.mayaMixin import MayaQDockWidget import settingsUI as sui # guide info AUTHOR = "Jeremie Passerin, Miquel Campos" URL = "www.jeremiepasserin.com, www.miquel-campos.com" EMAIL = "[email protected], [email protected]" VERSION = [1, 0, 0] TYPE = "foot_bk_01" NAME = "foot" DESCRIPTION = "Foot with reversed controllers to control foot roll." ########################################################## # CLASS ########################################################## class Guide(guide.ComponentGuide): """Component Guide Class""" compType = TYPE compName = NAME description = DESCRIPTION author = AUTHOR url = URL email = EMAIL version = VERSION connectors = ["leg_2jnt_01", "leg_ms_2jnt_01", "leg_3jnt_01"] def postInit(self): """Initialize the position for the guide""" self.save_transform = ["root", "#_loc", "heel", "outpivot", "inpivot"] self.addMinMax("#_loc", 1, -1) def
(self): """Add the Guide Root, blade and locators""" self.root = self.addRoot() self.locs = self.addLocMulti("#_loc", self.root) centers = [self.root] centers.extend(self.locs) self.dispcrv = self.addDispCurve("crv", centers) # Heel and pivots vTemp = transform.getOffsetPosition(self.root, [0, -1, -1]) self.heel = self.addLoc("heel", self.root, vTemp) vTemp = transform.getOffsetPosition(self.root, [1, -1, -1]) self.outpivot = self.addLoc("outpivot", self.root, vTemp) vTemp = transform.getOffsetPosition(self.root, [-1, -1, -1]) self.inpivot = self.addLoc("inpivot", self.root, vTemp) cnt = [self.root, self.heel, self.outpivot, self.heel, self.inpivot] self.dispcrv = self.addDispCurve("1", cnt) def addParameters(self): """Add the configurations settings""" self.pRoll = self.addParam("useRollCtl", "bool", True) self.pUseIndex = self.addParam("useIndex", "bool", False) self.pParentJointIndex = self.addParam( "parentJointIndex", "long", -1, None, None) ########################################################## # Setting Page ########################################################## class settingsTab(QtWidgets.QDialog, sui.Ui_Form): """The Component settings UI""" def __init__(self, parent=None): super(settingsTab, self).__init__(parent) self.setupUi(self) class componentSettings(MayaQWidgetDockableMixin, guide.componentMainSettings): """Create the component setting window""" def __init__(self, parent=None): self.toolName = TYPE # Delete old instances of the componet settings window. pyqt.deleteInstances(self, MayaQDockWidget) super(self.__class__, self).__init__(parent=parent) self.settingsTab = settingsTab() self.setup_componentSettingWindow() self.create_componentControls() self.populate_componentControls() self.create_componentLayout() self.create_componentConnections() def setup_componentSettingWindow(self): self.mayaMainWindow = pyqt.maya_main_window() self.setObjectName(self.toolName) self.setWindowFlags(QtCore.Qt.Window) self.setWindowTitle(TYPE) self.resize(280, 350) def create_componentControls(self): return def populate_componentControls(self): """Populate Controls Populate the controls values from the custom attributes of the component. """ # populate tab self.tabs.insertTab(1, self.settingsTab, "Component Settings") # populate component settings self.populateCheck(self.settingsTab.useRollCtl_checkBox, "useRollCtl") # populate connections in main settings for cnx in Guide.connectors: self.mainSettingsTab.connector_comboBox.addItem(cnx) cBox = self.mainSettingsTab.connector_comboBox self.connector_items = [cBox.itemText(i) for i in range(cBox.count())] currentConnector = self.root.attr("connector").get() if currentConnector not in self.connector_items: self.mainSettingsTab.connector_comboBox.addItem(currentConnector) self.connector_items.append(currentConnector) pm.displayWarning("The current connector: %s, is not a valid " "connector for this component. " "Build will Fail!!") comboIndex = self.connector_items.index(currentConnector) self.mainSettingsTab.connector_comboBox.setCurrentIndex(comboIndex) def create_componentLayout(self): self.settings_layout = QtWidgets.QVBoxLayout() self.settings_layout.addWidget(self.tabs) self.settings_layout.addWidget(self.close_button) self.setLayout(self.settings_layout) def create_componentConnections(self): self.settingsTab.useRollCtl_checkBox.stateChanged.connect( partial(self.updateCheck, self.settingsTab.useRollCtl_checkBox, "useRollCtl")) self.mainSettingsTab.connector_comboBox.currentIndexChanged.connect( partial(self.updateConnector, self.mainSettingsTab.connector_comboBox, self.connector_items)) def dockCloseEventTriggered(self): pyqt.deleteInstances(self, MayaQDockWidget)
addObjects
empresaTO.ts
export class
{ public empr_sq_id: string; public empr_nm_razaosocial: string; constructor() { this.empr_sq_id = ''; this.empr_nm_razaosocial= ''; } }
EmpresaTO
convert.rs
use crate::Result; use jni::{ objects::{AutoLocal, JClass, JMethodID, JObject, JStaticMethodID, JValue}, signature::{JavaType, Primitive}, JNIEnv, }; pub(crate) struct Common<'a> { pub(crate) env: JNIEnv<'a>, pub(crate) class_boolean: JClass<'a>, pub(crate) class_byte: JClass<'a>, pub(crate) class_integer: JClass<'a>, pub(crate) class_short: JClass<'a>, pub(crate) class_long: JClass<'a>, pub(crate) class_float: JClass<'a>, pub(crate) class_double: JClass<'a>, pub(crate) class_character: JClass<'a>, pub(crate) class_string: JClass<'a>, pub(crate) class_persistentvector: JClass<'a>, pub(crate) class_persistenthashmap: JClass<'a>, pub(crate) class_imapiterable: JClass<'a>, pub(crate) class_keyword: JClass<'a>, } impl<'a> Common<'a> { pub fn new(env: JNIEnv<'a>) -> Result<Self> { Ok(Self { class_boolean: env.find_class("java/lang/Boolean")?, class_byte: env.find_class("java/lang/Byte")?, class_integer: env.find_class("java/lang/Integer")?, class_long: env.find_class("java/lang/Long")?, class_short: env.find_class("java/lang/Short")?, class_float: env.find_class("java/lang/Float")?, class_double: env.find_class("java/lang/Double")?, class_character: env.find_class("java/lang/Character")?, class_string: env.find_class("java/lang/String")?, class_keyword: env.find_class("clojure/lang/Keyword")?, class_persistentvector: env.find_class("clojure/lang/PersistentVector")?, class_persistenthashmap: env.find_class("clojure/lang/PersistentHashMap")?, class_imapiterable: env.find_class("clojure/lang/IMapIterable")?, env, }) } } pub struct Encoder<'a> { pub(crate) com: Common<'a>, valueof_boolean: JStaticMethodID<'a>, valueof_byte: JStaticMethodID<'a>, valueof_integer: JStaticMethodID<'a>, valueof_short: JStaticMethodID<'a>, valueof_long: JStaticMethodID<'a>, valueof_float: JStaticMethodID<'a>, valueof_double: JStaticMethodID<'a>, valueof_character: JStaticMethodID<'a>, class_arraylist: JClass<'a>, new_arraylist: JMethodID<'a>, add_arraylist: JMethodID<'a>, toarray_arraylist: JMethodID<'a>, intern_keyword: JStaticMethodID<'a>, create_persistentvector: JStaticMethodID<'a>, create_persistenthashmap: JStaticMethodID<'a>, } impl<'a> Encoder<'a> { pub fn new(env: JNIEnv<'a>) -> Result<Self> { let com = Common::new(env)?; let class_arraylist = com.env.find_class("java/util/ArrayList")?; Ok(Self { valueof_boolean: com.env.get_static_method_id( com.class_boolean, "valueOf", "(Z)Ljava/lang/Boolean;", )?, valueof_byte: com.env.get_static_method_id( com.class_byte, "valueOf", "(B)Ljava/lang/Byte;", )?, valueof_integer: com.env.get_static_method_id( com.class_integer, "valueOf", "(I)Ljava/lang/Integer;", )?, valueof_long: com.env.get_static_method_id( com.class_long, "valueOf", "(J)Ljava/lang/Long;", )?, valueof_short: com.env.get_static_method_id( com.class_short, "valueOf", "(S)Ljava/lang/Short;", )?, valueof_float: com.env.get_static_method_id( com.class_float, "valueOf", "(F)Ljava/lang/Float;", )?, valueof_double: com.env.get_static_method_id( com.class_double, "valueOf", "(D)Ljava/lang/Double;", )?, valueof_character: com.env.get_static_method_id( com.class_character, "valueOf", "(C)Ljava/lang/Character;", )?, new_arraylist: com.env.get_method_id(class_arraylist, "<init>", "()V")?, add_arraylist: com.env.get_method_id( class_arraylist, "add", "(Ljava/lang/Object;)Z", )?, toarray_arraylist: com.env.get_method_id( class_arraylist, "toArray", "()[Ljava/lang/Object;", )?, class_arraylist, intern_keyword: com.env.get_static_method_id( com.class_keyword, "intern", "(Ljava/lang/String;)Lclojure/lang/Keyword;", )?, create_persistentvector: com.env.get_static_method_id( com.class_persistentvector, "create", "(Ljava/lang/Iterable;)Lclojure/lang/PersistentVector;", )?, create_persistenthashmap: com.env.get_static_method_id( com.class_persistenthashmap, "create", "([Ljava/lang/Object;)Lclojure/lang/PersistentHashMap;", )?, com, }) } pub(crate) fn get_keyword(&'a self, name: &str) -> Result<JObject<'a>> { let s = self.com.env.auto_local(self.com.env.new_string(name)?); let k = self .com .env .call_static_method_unchecked( self.com.class_keyword, self.intern_keyword, JavaType::Object(String::new()), &[s.as_obj().into()], )? .l()?; Ok(k) } #[inline] pub(crate) fn to_boxed(&self, val: JValue<'a>) -> Result<JObject<'a>> { let com = &self.com; let res = match val { JValue::Object(_) => val, JValue::Bool(_) => com.env.call_static_method_unchecked( com.class_boolean, self.valueof_boolean, JavaType::Object(String::new()), &[val], )?, JValue::Byte(_) => com.env.call_static_method_unchecked( com.class_byte, self.valueof_byte, JavaType::Object(String::new()), &[val], )?, JValue::Int(_) => com.env.call_static_method_unchecked( com.class_integer, self.valueof_integer, JavaType::Object(String::new()), &[val], )?, JValue::Short(_) => com.env.call_static_method_unchecked( com.class_short, self.valueof_short, JavaType::Object(String::new()), &[val], )?, JValue::Long(_) => com.env.call_static_method_unchecked( com.class_long, self.valueof_long, JavaType::Object(String::new()), &[val], )?, JValue::Float(_) => com.env.call_static_method_unchecked( com.class_float, self.valueof_float, JavaType::Object(String::new()), &[val], )?, JValue::Double(_) => com.env.call_static_method_unchecked( com.class_double, self.valueof_double, JavaType::Object(String::new()), &[val], )?, JValue::Char(_) => com.env.call_static_method_unchecked( com.class_character, self.valueof_character, JavaType::Object(String::new()), &[val], )?, JValue::Void => JObject::null().into(), }; Ok(res.l()?) } } pub(crate) struct ArrayList<'a> { enc: &'a Encoder<'a>, obj: AutoLocal<'a, 'a>, } impl<'a> ArrayList<'a> { pub fn new(enc: &'a Encoder<'a>) -> Result<Self> { Ok(Self { obj: enc.com.env.auto_local(enc.com.env.new_object_unchecked( enc.class_arraylist, enc.new_arraylist, &[], )?), enc, }) } /// This method will invalidate the local ref `val`! pub fn add(&self, val: JObject<'a>) -> Result<()> { let val = self.enc.com.env.auto_local(val); self.enc.com.env.call_method_unchecked( self.obj.as_obj(), self.enc.add_arraylist, JavaType::Primitive(Primitive::Boolean), &[val.as_obj().into()], )?; Ok(()) } pub fn to_vector(self) -> Result<JObject<'a>> { Ok(self .enc .com .env .call_static_method_unchecked( self.enc.com.class_persistentvector, self.enc.create_persistentvector, JavaType::Object(String::new()), &[self.obj.as_obj().into()], )? .l()?) } pub fn to_hashmap(self) -> Result<JObject<'a>> { let arr = self.enc.com.env.auto_local( self.enc .com .env .call_method_unchecked( self.obj.as_obj(), self.enc.toarray_arraylist, JavaType::Array(Box::new(JavaType::Object(String::new()))), // why is this necessary? &[], )? .l()?, ); Ok(self .enc .com .env .call_static_method_unchecked( self.enc.com.class_persistenthashmap, self.enc.create_persistenthashmap, JavaType::Object(String::new()), &[arr.as_obj().into()], )? .l()?) } } pub struct Decoder<'a> { pub(crate) com: Common<'a>, pub(crate) value_boolean: JMethodID<'a>, pub(crate) value_byte: JMethodID<'a>, pub(crate) value_integer: JMethodID<'a>, pub(crate) value_short: JMethodID<'a>, pub(crate) value_long: JMethodID<'a>, pub(crate) value_float: JMethodID<'a>, pub(crate) value_double: JMethodID<'a>, pub(crate) class_rt: JClass<'a>, pub(crate) first_seq: JStaticMethodID<'a>, pub(crate) next_seq: JStaticMethodID<'a>, pub(crate) keyiterator_imapiterable: JMethodID<'a>, pub(crate) valiterator_imapiterable: JMethodID<'a>, pub(crate) getname_keyword: JMethodID<'a>, pub(crate) hasnext_iter: JMethodID<'a>, pub(crate) next_iter: JMethodID<'a>, /// a byte array pub(crate) class_bytes: JClass<'a>, } macro_rules! decode { ($func:ident, $out:ident, $class:ident, $value_method:ident, $prim:ident, $code:ident) => { pub(crate) fn $func(&self, obj: JObject) -> Result<Option<$out>> { if self .com .env .is_instance_of(obj, self.com.$class)? { Ok(Some(self .decode_prim(obj, self.$value_method, Primitive::$prim)? .$code()?)) } else { Ok(None) } } } } impl<'a> Decoder<'a> { pub fn new(env: JNIEnv<'a>) -> Result<Self> { let com = Common::new(env.clone())?; let class_rt = env.find_class("clojure/lang/RT")?; let class_iter = env.find_class("java/util/Iterator")?; let hasnext_iter = env.get_method_id(class_iter, "hasNext", "()Z")?; let next_iter = com .env .get_method_id(class_iter, "next", "()Ljava/lang/Object;")?; Ok(Decoder { value_boolean: com .env .get_method_id(com.class_boolean, "booleanValue", "()Z")?, value_byte: env.get_method_id(com.class_byte, "byteValue", "()B")?, value_float: com .env .get_method_id(com.class_float, "floatValue", "()F")?, value_double: com .env .get_method_id(com.class_double, "doubleValue", "()D")?, value_short: com .env .get_method_id(com.class_short, "shortValue", "()S")?, value_integer: com .env .get_method_id(com.class_integer, "intValue", "()I")?, value_long: env.get_method_id(com.class_long, "longValue", "()J")?, // seq_rt: env.get_static_method_id(class_rt, "seq", "(Ljava/lang/Object;)Lclojure/lang/ISeq;")?, first_seq: env.get_static_method_id( class_rt, "first", "(Ljava/lang/Object;)Ljava/lang/Object;", )?, next_seq: env.get_static_method_id( class_rt, "next", "(Ljava/lang/Object;)Lclojure/lang/ISeq;", )?, keyiterator_imapiterable: env.get_method_id( com.class_imapiterable, "keyIterator", "()Ljava/util/Iterator;", )?, valiterator_imapiterable: env.get_method_id( com.class_imapiterable, "valIterator", "()Ljava/util/Iterator;", )?, getname_keyword: env.get_method_id( com.class_keyword, "getName", "()Ljava/lang/String;", )?, hasnext_iter, next_iter, class_bytes: env.find_class("[B")?, class_rt, // class_iseq, com, }) } fn
( &self, obj: JObject<'a>, method: JMethodID<'a>, ret: Primitive, ) -> Result<JValue<'a>> { Ok(self .com .env .call_method_unchecked(obj, method, JavaType::Primitive(ret), &[])?) } decode!(decode_f32, f32, class_float, value_float, Float, f); decode!(decode_f64, f64, class_double, value_double, Double, d); decode!(decode_i64, i64, class_long, value_long, Long, j); decode!(decode_i32, i32, class_integer, value_integer, Int, i); decode!(decode_i16, i16, class_short, value_short, Short, s); decode!(decode_bool, bool, class_boolean, value_boolean, Boolean, z); decode!(decode_i8, i8, class_byte, value_byte, Byte, b); pub(crate) fn decode_string(&self, obj: JObject) -> Result<Option<String>> { if self.com.env.is_instance_of(obj, self.com.class_string)? { Ok(Some(self.com.env.get_string(obj.into())?.into())) } else { Ok(None) } } pub(crate) fn decode_bytes(&self, obj: JObject) -> Result<Option<Vec<u8>>> { if self.com.env.is_instance_of(obj, self.class_bytes)? { Ok(Some(self.com.env.convert_byte_array(obj.into_inner())?)) } else { Ok(None) } } pub(crate) fn decode_keyword(&self, obj: JObject) -> Result<Option<String>> { if self.com.env.is_instance_of(obj, self.com.class_keyword)? { let name = self.com.env.auto_local( self.com .env .call_method_unchecked( obj, self.getname_keyword, JavaType::Object(String::new()), &[], )? .l()?, ); let res = self.com.env.get_string(name.as_obj().into())?.into(); Ok(Some(res)) } else { Ok(None) } } pub(crate) fn map_to_iters( &self, obj: AutoLocal<'a, 'a>, ) -> Result<Option<(AutoLocal, AutoLocal)>> { if self .com .env .is_instance_of(obj.as_obj(), self.com.class_imapiterable)? { let key_iter = self.com.env.auto_local( self.com .env .call_method_unchecked( obj.as_obj(), self.keyiterator_imapiterable, JavaType::Object(String::new()), &[obj.as_obj().into()], )? .l()?, ); let val_iter = self.com.env.auto_local( self.com .env .call_method_unchecked( obj.as_obj(), self.valiterator_imapiterable, JavaType::Object(String::new()), &[obj.as_obj().into()], )? .l()?, ); Ok(Some((key_iter, val_iter))) } else { Ok(None) } } }
decode_prim
origin.go
package components import ( "github.com/gravestench/akara" "github.com/gravestench/mathlib" ) var _ akara.Component = &Origin{} // Origin is a component that contains normalized alpha transparency (0.0 ... 1.0) type Origin struct { *mathlib.Vector3 } // New creates a new alpha component instance. The default alpha is opaque with value 1.0 func (*Origin) New() akara.Component { const defaultOrigin = 0.5 // normalized, 0.5 is center return &Origin{ Vector3: &mathlib.Vector3{ X: defaultOrigin, Y: defaultOrigin, }, } } // OriginFactory is a wrapper for the generic component factory that returns Origin component instances. // This can be embedded inside of a system to give them the methods for adding, retrieving, and removing a Origin. type OriginFactory struct { *akara.ComponentFactory } // Add adds a Origin component to the given entity and returns it func (m *OriginFactory) Add(id akara.EID) *Origin { return m.ComponentFactory.Add(id).(*Origin) } // Get returns the Origin component for the given entity, and a bool for whether or not it exists func (m *OriginFactory) Get(id akara.EID) (*Origin, bool) { component, found := m.ComponentFactory.Get(id) if !found
return component.(*Origin), found }
{ return nil, found }
server-test.js
var express= require('express');
app.use( bodyParser.json() ); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); app.use(express.static(__dirname)); var connect = mongoose.connect('mongodb://localhost/ng-hearthstone', function(err) { console.log('hello',err) }) var db = mongoose.connection; db.once('open', function() { console.log('db opened') }); var cardsetSchema = new mongoose.Schema({ cardset:Object }); var cardsetCollection = mongoose.model('cardsetModel',cardsetSchema) app.get('/', function(req,res){ res.sendFile('index.html'); }); function prepareCards(cards){ var cardMap = {}; for(i = 0;i < cards.length;i++){ var cardsetName = cards[i].cardset[0].cardSet; cardMap[cardsetName] = []; for(var j = 0; j < cards[i].cardset.length;j++){ cardMap[cardsetName].push(cards[i].cardset[j]); } } return cardMap } function getCards(cardsetCollection,req,res){ cardsetCollection.find({}, function(err,cards){ if(err){ return res.send({}); } res.send(prepareCards(cards)); }); } app.get('/cards', getCards.bind(null,cardsetCollection));//Partial Application app.listen(8900, function() { console.log("listening on 8900!"); }); /*function addCards(){ var options = { url: 'https://omgvamp-hearthstone-v1.p.mashape.com/cards', headers: { "X-Mashape-Authorization":"CoOndkDhoKmshDPeHj0wo34mhYGhp1Qzv7rjsnZvEzmruV3rIQ" } }; function callback(error, response, body) { var info = JSON.parse(body); for(key in info){ var cardModel = new cardsetCollection({cardset:info[key]}) cardModel.save(function(err){ console.log('here') return undefined; }) } } request(options, callback); } addCards();*/ module.exports = {getCards:getCards,prepareCards:prepareCards};
var app = express(); var mongoose = require('mongoose'); var request = require('request'); var bodyParser = require('body-parser');
init_test.go
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016-present Datadog, Inc. package testinit import ( "testing" "github.com/DataDog/datadog-agent/rtloader/test/helpers" ) func
(t *testing.T) { // Reset memory counters helpers.ResetMemoryStats() if err := runInit(); err != nil { t.Errorf("Expected nil, got: %v", err) } // Check for expected allocations helpers.AssertMemoryExpectation(t, helpers.Allocations, initAllocations) }
TestInit
helpers.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Crap class but make code more compact. lmao WARNING! WARNING! HIGH CONCENTRATION OF SHIT! and in future here will be adding more and more methods and classes but i'm not shure """ import os def success(message): return '<div class="alert alert-success alert-dismissable">' \ '<button type="button" class="close" data-dismiss="alert">&times;</button>' \ '{}</div>'.format(message) def
(message): return '<div class="alert alert-danger alert-dismissable">' \ '<button type="button" class="close" data-dismiss="alert">&times;</button>' \ '{}</div>'.format(message) def playlist(path): """ Especially here ._. :param path: :return: """ listdir = os.listdir(path) raw_html = '' for i in listdir: raw_html += '<option>{}</option>'.format(unicode.encode(unicode(str(i), 'utf-8'), 'utf8')) return raw_html # fix utf-8 encode and some useful stuff such as <option> format
warning
events.ts
import { Runtime, Tabs } from "webextension-polyfill"; import { extensionSupportsUrl } from "../common/articleDetection"; import { collectAnonymousMetricsFeatureFlag, getFeatureFlag, isDevelopmentFeatureFlag, setFeatureFlag, } from "../common/featureFlags"; import browser from "../common/polyfill"; import { saveInitialInstallVersionIfMissing } from "../overlay/outline/updateMessages"; import { migrateAnnotationStorage } from "../sidebar/common/local"; import { fetchCss } from "./actions"; import { loadAnnotationCountsToMemory } from "./annotationCounts"; import { enableInTab, injectScript, togglePageViewMessage } from "./inject"; import { onNewInstall, requestOptionalPermissions } from "./install"; import { getRemoteFeatureFlags, reportDisablePageView, reportEnablePageView, reportEvent, reportSettings, startMetrics, } from "./metrics"; import { TabStateManager } from "./tabs"; const tabsManager = new TabStateManager(); // toggle page view on extension icon click browser.action.onClicked.addListener((tab: Tabs.Tab) => { const url = new URL(tab.url); if (!extensionSupportsUrl(url)) { // ideally show some error message here return; } enableInTab(tab.id).then((didEnable) => { if (!didEnable) { // already active, so disable togglePageViewMessage(tab.id); return; } tabsManager.checkIsArticle(tab.id, tab.url); if (didEnable) { tabsManager .getSocialAnnotationsCount(tab.id, tab.url) .then((socialCommentsCount) => reportEnablePageView("manual", socialCommentsCount) ); } }); // can only request permissions from user action, use this opportunity // can't make callback a promise for this to work requestOptionalPermissions(); }); // handle events from content scripts browser.runtime.onMessage.addListener( (message: any, sender: Runtime.MessageSender, sendResponse: () => void) => { // console.log(`Received '${message.event}' message:`, message); if (message.event === "disabledPageView") { reportDisablePageView(message.trigger, message.pageHeightPx); } else if (message.event === "requestEnhance") { // event sent from boot.js to inject additional functionality // browser apis are only available in scripts injected from background scripts or manifest.json console.log("boot.js requested injection into tab"); injectScript(sender.tab.id, "content-script/enhance.js"); tabsManager .getSocialAnnotationsCount(sender.tab.id, sender.url) .then((socialCommentsCount) => reportEnablePageView(message.trigger, socialCommentsCount) ); } else if (message.event === "openOptionsPage") { browser.runtime.openOptionsPage(); } else if (message.event === "fetchCss") { fetchCss(message.url).then(sendResponse); return true; } else if (message.event === "reportEvent") { reportEvent(message.name, message.data); } else if (message.event === "getRemoteFeatureFlags") { getRemoteFeatureFlags().then(sendResponse); return true; } else if (message.event === "checkLocalAnnotationCount") { // trigger from boot.js because we don't have tabs permissions tabsManager .checkIsArticle(sender.tab.id, sender.url) .then(sendResponse); return true; } else if (message.event === "getSocialAnnotationsCount") { tabsManager .getSocialAnnotationsCount(sender.tab.id, sender.url) .then(sendResponse); return true; } else if (message.event === "setSocialAnnotationsCount") { tabsManager.setSocialAnnotationsCount(sender.tab.id, message.count); } return false; } ); // run on install, extension update, or browser update browser.runtime.onInstalled.addListener(async ({ reason }) => { const extensionInfo = await browser.management.getSelf(); const isNewInstall = reason === "install"; const isDev = extensionInfo.installType === "development"; if (isDev) { // disable metrics in dev mode await setFeatureFlag(collectAnonymousMetricsFeatureFlag, false); await setFeatureFlag(isDevelopmentFeatureFlag, true); } // report aggregates on enabled extension features // this function should be executed every few days reportSettings(extensionInfo.version, isNewInstall); if (isNewInstall && !isDev) { onNewInstall(extensionInfo.version); } saveInitialInstallVersionIfMissing(extensionInfo.version); await migrateAnnotationStorage(); // show opt shortcut icon on mac browser.runtime.getPlatformInfo().then(({ os }) => browser.action.setTitle({ title: "Unclutter Current Article (⌥+C)", }) ); }); // track tab changes to update extension icon badge browser.tabs.onActivated.addListener((info: Tabs.OnActivatedActiveInfoType) => tabsManager.onChangeActiveTab(info.tabId) ); browser.tabs.onUpdated.addListener( (tabId: number, change: Tabs.OnUpdatedChangeInfoType) => { if (change.url) { // clear state for old url, checkLocalAnnotationCount will be sent for likely articles again tabsManager.onCloseTab(tabId); } } ); browser.tabs.onRemoved.addListener((tabId: number) => tabsManager.onCloseTab(tabId) ); // initialize on every service worker start async function in
{ const isDev = await getFeatureFlag(isDevelopmentFeatureFlag); if (isDev) { return; } startMetrics(); loadAnnotationCountsToMemory(); } initializeServiceWorker();
itializeServiceWorker()
main.rs
#[derive(Debug)] struct Player { pos: i32, score: i32, } impl Player { fn advance_pos(&mut self, pos: i32) { self.pos = ((self.pos + pos - 1) % 10) + 1 } fn increase_score(&mut self, score: i32) { self.score += score; } } fn main() { let player1_start_pos = get_player_start_position_from_input(); let player2_start_pos = get_player_start_position_from_input(); println!( "Part 1: {}", play_with_deterministic_dice(player1_start_pos, player2_start_pos) ); println!( "Part 2: {}", play_with_dirac_dice(player1_start_pos, player2_start_pos) ); } fn get_player_start_position_from_input() -> i32 { let mut input = String::new(); std::io::stdin() .read_line(&mut input) .expect("failed to read from stdin"); input .trim() .split_whitespace() .last() .unwrap() .parse() .unwrap() } fn play_with_deterministic_dice(player1_start_pos: i32, player2_start_pos: i32) -> i32 { let mut player1 = Player { pos: player1_start_pos, score: 0, }; let mut player2 = Player { pos: player2_start_pos, score: 0, }; let mut deterministic_dice = 0; let mut dice_rolled = 0; while player1.score < 1000 && player2.score < 1000 { let play = (0..3) .map(|_| roll_deterministic_dice(&mut deterministic_dice)) .sum(); dice_rolled += 3; player1.advance_pos(play); player1.increase_score(player1.pos); if player1.score >= 1000 { break; } let play = (0..3) .map(|_| roll_deterministic_dice(&mut deterministic_dice)) .sum(); dice_rolled += 3; player2.advance_pos(play); player2.increase_score(player2.pos); } player1.score.min(player2.score) * dice_rolled } fn roll_deterministic_dice(dice: &mut i32) -> i32 { *dice = (*dice % 100) + 1; *dice } fn play_with_dirac_dice(player1_start_pos: i32, player2_start_pos: i32) -> i128 { let mut caching_table = [[[[0 as i128; 22]; 22]; 10]; 10]; let mut playing_now = false; let options_list = calculate_dice_options_list(); caching_table[player1_start_pos as usize - 1][player2_start_pos as usize - 1][0][0] = 1; while !has_game_ended(&caching_table) { let mut new_caching_table = [[[[0 as i128; 22]; 22]; 10]; 10]; for p1_pos in 0..10 { for p2_pos in 0..10 { for p1_score in 0..=21 { for p2_score in 0..=21 { if p1_score == 21 || p2_score == 21 { new_caching_table[p1_pos][p2_pos][p1_score][p2_score] += caching_table[p1_pos][p2_pos][p1_score][p2_score]; continue; } for (dice, count) in options_list.iter().enumerate() { if !playing_now { let p1_new_pos = (p1_pos + dice + 1) % 10; let p1_new_score = (p1_score + p1_new_pos + 1).min(21); new_caching_table[p1_new_pos][p2_pos][p1_new_score][p2_score] += caching_table[p1_pos][p2_pos][p1_score][p2_score] * *count as i128; } else { let p2_new_pos = (p2_pos + dice + 1) % 10; let p2_new_score = (p2_score + p2_new_pos + 1).min(21); new_caching_table[p1_pos][p2_new_pos][p1_score][p2_new_score] += caching_table[p1_pos][p2_pos][p1_score][p2_score] * *count as i128; } } } } } } playing_now = !playing_now; caching_table = new_caching_table; } let wins = sum_winning_universes(&caching_table); wins.0.max(wins.1) } fn calculate_dice_options_list() -> [i32; 9] { // there are 3 * 3 * 3 = 27 options for scores let mut list = [0; 9]; // max sum is 9=3+3+3 for a in 1..=3 { for b in 1..=3 { for c in 1..=3 { list[a + b + c - 1] += 1; } } } list } fn has_game_ended(cache: &[[[[i128; 22]; 22]; 10]; 10]) -> bool { for p1_pos in 0..10 { for p2_pos in 0..10 { for p1_score in 0..=20 { for p2_score in 0..=20 { if cache[p1_pos][p2_pos][p1_score][p2_score] != 0 { return false; } } } } } true } fn sum_winning_universes(cache: &[[[[i128; 22]; 22]; 10]; 10]) -> (i128, i128) { let (mut p1_wins, mut p2_wins) = (0, 0);
p2_wins += cache[p1_pos][p2_pos][p1_score][21]; } for p2_score in 0..=21 { p1_wins += cache[p1_pos][p2_pos][21][p2_score]; } } } (p1_wins, p2_wins) }
for p1_pos in 0..10 { for p2_pos in 0..10 { for p1_score in 0..=21 {
0006_auto_20220427_1014.py
# Generated by Django 3.2.12 on 2022-04-27 05:44 from django.db import migrations class Migration(migrations.Migration):
dependencies = [ ('blog', '0005_auto_20220427_1002'), ] operations = [ migrations.RemoveField( model_name='post', name='category', ), migrations.DeleteModel( name='Category', ), ]
fib.py
from numba import jit import sys @jit def fib(n):
if __name__ == "__main__": n = int(sys.argv[1]) print("{}".format(fib(n)))
return 1 if n < 3 else fib(n-1) + fib(n-2)
Lists.go
package odf import ( //"fmt" "math/rand" "strconv" "strings" "github.com/LIJUCHACKO/XmlDB" ) type List struct { NodeId int Note *Notes ListStyleId int } func (Note *Notes) NewNumberedList(Style string) *List { var List *List = new(List) List.Note = Note ListStyle_name := "PLS" + strconv.Itoa(rand.Intn(100)) if len(strings.TrimSpace(Style)) > 0 { ListStyle_name = strings.TrimSpace(Style) } //fmt.Println("Style name=" + ListStyle_name) //office_Text List.NodeId = Note.WritetoScratchpad("<text:list xml:id=\"list5252122" + strconv.Itoa(rand.Intn(100)) + "\" text:style-name=\"" + ListStyle_name + "\"/>") // List.Office_Text = xml_content if len(strings.TrimSpace(Style)) == 0 { //office_style styletext := `<styles> <office:styles> <style:style style:name="Standard" style:family="paragraph" style:class="text"/> <style:style style:name="Text_20_body" style:display-name="Text body" style:family="paragraph" style:parent-style-name="Standard" style:class="text"> <style:paragraph-properties fo:margin-top="0cm" fo:margin-bottom="0.247cm" loext:contextual-spacing="false" fo:line-height="120%"/> </style:style> <style:style style:name="Numbering_20_Symbols" style:display-name="Numbering Symbols" style:family="text"/> </office:styles> <office:automatic-styles> <text:list-style style:name="` + ListStyle_name + `"> <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="1.27cm" fo:text-indent="-0.635cm" fo:margin-left="1.27cm"/> </style:list-level-properties> </text:list-level-style-number> <text:list-level-style-number text:level="2" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="1.905cm" fo:text-indent="-0.635cm" fo:margin-left="1.905cm"/> </style:list-level-properties> </text:list-level-style-number> <text:list-level-style-number text:level="3" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="2.54cm" fo:text-indent="-0.635cm" fo:margin-left="2.54cm"/> </style:list-level-properties> </text:list-level-style-number> <text:list-level-style-number text:level="4" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="3.175cm" fo:text-indent="-0.635cm" fo:margin-left="3.175cm"/> </style:list-level-properties> </text:list-level-style-number> <text:list-level-style-number text:level="5" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="3.81cm" fo:text-indent="-0.635cm" fo:margin-left="3.81cm"/> </style:list-level-properties> </text:list-level-style-number> <text:list-level-style-number text:level="6" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="4.445cm" fo:text-indent="-0.635cm" fo:margin-left="4.445cm"/> </style:list-level-properties> </text:list-level-style-number> <text:list-level-style-number text:level="7" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="5.08cm" fo:text-indent="-0.635cm" fo:margin-left="5.08cm"/> </style:list-level-properties> </text:list-level-style-number> <text:list-level-style-number text:level="8" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="5.715cm" fo:text-indent="-0.635cm" fo:margin-left="5.715cm"/> </style:list-level-properties> </text:list-level-style-number> <text:list-level-style-number text:level="9" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="6.35cm" fo:text-indent="-0.635cm" fo:margin-left="6.35cm"/> </style:list-level-properties> </text:list-level-style-number> <text:list-level-style-number text:level="10" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="6.985cm" fo:text-indent="-0.635cm" fo:margin-left="6.985cm"/> </style:list-level-properties> </text:list-level-style-number> </text:list-style> </office:automatic-styles> </styles>` id := Note.WritetoScratchpad(styletext) Note.IncludeStyle(id) } //fmt.Println(xmlDB.GetNodeContents(Note.Content, Note.Officeautostyleid)) StyleNodeid, _ := xmlDB.GetNode(Note.Content, Note.Officeautostyleid, "text:list-style[style:name=\""+ListStyle_name+"\"]") List.ListStyleId = StyleNodeid[0] return List } func (Note *Notes) NewBulletinList(Style string) *List { var List *List = new(List) List.Note = Note ListStyle_name := "PLS" + strconv.Itoa(rand.Intn(100)) if len(strings.TrimSpace(Style)) > 0
//fmt.Println("Style name=" + ListStyle_name) //office_Text List.NodeId = Note.WritetoScratchpad("<text:list xml:id=\"list5252122" + strconv.Itoa(rand.Intn(100)) + "\" text:style-name=\"" + ListStyle_name + "\"/>") // List.Office_Text = xml_content if len(strings.TrimSpace(Style)) == 0 { //office_style styletext := `<styles> <office:styles> <style:style style:name="Standard" style:family="paragraph" style:class="text"/> <style:style style:name="Text_20_body" style:display-name="Text body" style:family="paragraph" style:parent-style-name="Standard" style:class="text"> <style:paragraph-properties fo:margin-top="0cm" fo:margin-bottom="0.247cm" loext:contextual-spacing="false" fo:line-height="120%"/> </style:style> <style:style style:name="Numbering_20_Symbols" style:display-name="Numbering Symbols" style:family="text"/> </office:styles> <office:automatic-styles> <text:list-style style:name="` + ListStyle_name + `"> <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" text:bullet-char="•"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="1.27cm" fo:text-indent="-0.635cm" fo:margin-left="1.27cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" text:bullet-char="◦"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="1.905cm" fo:text-indent="-0.635cm" fo:margin-left="1.905cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" text:bullet-char="▪"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="2.54cm" fo:text-indent="-0.635cm" fo:margin-left="2.54cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" text:bullet-char="•"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="3.175cm" fo:text-indent="-0.635cm" fo:margin-left="3.175cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" text:bullet-char="◦"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="3.81cm" fo:text-indent="-0.635cm" fo:margin-left="3.81cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" text:bullet-char="▪"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="4.445cm" fo:text-indent="-0.635cm" fo:margin-left="4.445cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" text:bullet-char="•"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="5.08cm" fo:text-indent="-0.635cm" fo:margin-left="5.08cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" text:bullet-char="◦"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="5.715cm" fo:text-indent="-0.635cm" fo:margin-left="5.715cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" text:bullet-char="▪"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="6.35cm" fo:text-indent="-0.635cm" fo:margin-left="6.35cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" text:bullet-char="•"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="6.985cm" fo:text-indent="-0.635cm" fo:margin-left="6.985cm"/> </style:list-level-properties> </text:list-level-style-bullet> </text:list-style> </office:automatic-styles> </styles>` id := Note.WritetoScratchpad(styletext) Note.IncludeStyle(id) } //fmt.Println(xmlDB.GetNodeContents(Note.Content, Note.Officeautostyleid)) StyleNodeid, _ := xmlDB.GetNode(Note.Content, Note.Officeautostyleid, "text:list-style[style:name=\""+ListStyle_name+"\"]") List.ListStyleId = StyleNodeid[0] return List } func (List *List) Style() string { ListStyle_name := xmlDB.GetNodeAttribute(List.Note.Content, List.ListStyleId, "style:name") return ListStyle_name } func (List *List) toBulletinList() { ListStyle_name := List.Style() styletext := `<text:list-style style:name="` + ListStyle_name + `"> <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" text:bullet-char="•"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="1.27cm" fo:text-indent="-0.635cm" fo:margin-left="1.27cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" text:bullet-char="◦"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="1.905cm" fo:text-indent="-0.635cm" fo:margin-left="1.905cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" text:bullet-char="▪"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="2.54cm" fo:text-indent="-0.635cm" fo:margin-left="2.54cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" text:bullet-char="•"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="3.175cm" fo:text-indent="-0.635cm" fo:margin-left="3.175cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" text:bullet-char="◦"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="3.81cm" fo:text-indent="-0.635cm" fo:margin-left="3.81cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" text:bullet-char="▪"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="4.445cm" fo:text-indent="-0.635cm" fo:margin-left="4.445cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" text:bullet-char="•"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="5.08cm" fo:text-indent="-0.635cm" fo:margin-left="5.08cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" text:bullet-char="◦"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="5.715cm" fo:text-indent="-0.635cm" fo:margin-left="5.715cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" text:bullet-char="▪"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="6.35cm" fo:text-indent="-0.635cm" fo:margin-left="6.35cm"/> </style:list-level-properties> </text:list-level-style-bullet> <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" text:bullet-char="•"> <style:list-level-properties text:list-level-position-and-space-mode="label-alignment"> <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="6.985cm" fo:text-indent="-0.635cm" fo:margin-left="6.985cm"/> </style:list-level-properties> </text:list-level-style-bullet> </text:list-style>` xmlDB.ReplaceNode(List.Note.Content, List.ListStyleId, styletext) } func (List *List) AddItemPara(style string) *Paragraph { para := List.Note.NewParagraph(style) para.AddListStyleName(List.Style()) newids, _ := xmlDB.InserSubNode(List.Note.Content, List.NodeId, "<text:list-item/>") xmlDB.CutPasteAsSubNode(List.Note.Content, newids[0], para.NodeId) return para }
{ ListStyle_name = strings.TrimSpace(Style) }
social-whatsapp.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactIconBase = require('react-icon-base'); var _reactIconBase2 = _interopRequireDefault(_reactIconBase); function
(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var IoSocialWhatsapp = function IoSocialWhatsapp(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm17.8 2.5c9.5 0 17.2 7.6 17.2 17s-7.7 17.1-17.2 17.1c-3 0-5.8-0.8-8.3-2.1l-9.5 3 3.1-9.1c-1.5-2.6-2.5-5.7-2.5-8.9 0-9.4 7.8-17 17.2-17z m8.5 23.5c0.4-1 0.5-1.9 0.4-2s-0.4-0.3-0.8-0.6-2.5-1.4-2.9-1.5-0.7-0.2-1 0.2-1.3 1.3-1.5 1.6-0.5 0.4-1 0.1-1.8-0.8-3.4-2.3c-1.3-1.2-2.1-2.6-2.4-3.1s0-0.7 0.3-0.9c0.2-0.2 0.5-0.5 0.7-0.7s0.3-0.4 0.5-0.7 0-0.6 0-0.8-1-2.4-1.3-3.3-0.8-0.8-1-0.8h-0.8s-0.8 0.1-1.2 0.5-1.6 1.5-1.7 3.6 1.4 4.2 1.7 4.5 2.8 5 7.2 6.9 4.5 1.3 5.3 1.3 2.5-1 2.9-2z' }) ) ); }; exports.default = IoSocialWhatsapp; module.exports = exports['default'];
_interopRequireDefault
irq.rs
use crate::dma::DMAChannelIndex; use crate::timers::TimerIndex; pub struct GbaInterruptControl { /// (IME Register) Interrupt master enable bit pub(crate) master_enable: bool, /// Bits representing enabled interrupts. See `Interrupt`. pub(crate) enabled: u16, /// (IE Register) Request / Acknowledge interrupt bits. request_ack: u16, } impl GbaInterruptControl { pub fn new() -> GbaInterruptControl { GbaInterruptControl { master_enable: false, enabled: 0, request_ack: 0, } } pub(crate) fn
(&self) -> u16 { self.request_ack } /// Handles writing to the IF register. Writing a 1 to any bit in the IF register actually /// clears it. pub(crate) fn write_if(&mut self, value: u16) { self.request_ack &= !value; } /// Requests an interrupt. Returns true if the interrupt was enabled and the request was /// successfully made (IRQ request flag set). pub(crate) fn request(&mut self, interrupt: Interrupt) -> bool { if self.master_enable && self.is_enabled(interrupt) { self.request_ack |= interrupt.mask(); return true; } else { return false; } } pub(crate) fn is_enabled(&self, interrupt: Interrupt) -> bool { (self.enabled & interrupt.mask()) != 0 } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u8)] pub enum Interrupt { LCDVBlank = 0, LCDHBlank = 1, LCDVCounterMatch = 2, Timer0Overflow = 3, Timer1Overflow = 4, Timer2Overflow = 5, Timer3Overflow = 6, SerialCommunication = 7, DMA0 = 8, DMA1 = 9, DMA2 = 10, DMA3 = 11, Keypad = 12, GamePak = 13, None = 14, } impl Interrupt { #[inline] pub const fn mask(self) -> u16 { 1 << (self as u8 as u16) } pub fn timer(timer_index: TimerIndex) -> Interrupt { match timer_index { TimerIndex::TM0 => Interrupt::Timer0Overflow, TimerIndex::TM1 => Interrupt::Timer1Overflow, TimerIndex::TM2 => Interrupt::Timer2Overflow, TimerIndex::TM3 => Interrupt::Timer3Overflow, } } pub fn dma(dma_index: DMAChannelIndex) -> Interrupt { match dma_index { DMAChannelIndex::DMA0 => Interrupt::DMA0, DMAChannelIndex::DMA1 => Interrupt::DMA1, DMAChannelIndex::DMA2 => Interrupt::DMA2, DMAChannelIndex::DMA3 => Interrupt::DMA3, } } }
read_if
benches.rs
use crate::to_rows; use async_trait::async_trait; use cubestore::cluster::Cluster; use cubestore::config::{env_parse, Config, CubeServices}; use cubestore::table::TableValue; use cubestore::util::strings::path_to_string; use cubestore::CubeError; use flate2::read::GzDecoder; use std::any::Any; use std::io::Cursor; use std::path::Path; use std::sync::Arc; use std::time::Duration; use tar::Archive; use tokio::time::timeout; pub type BenchState = dyn Any + Send + Sync; #[async_trait] pub trait Bench: Send + Sync { fn config(self: &Self, prefix: &str) -> (String, Config); async fn setup(self: &Self, services: &CubeServices) -> Result<Arc<BenchState>, CubeError>; async fn bench( self: &Self, services: &CubeServices, state: Arc<BenchState>, ) -> Result<(), CubeError>; } fn config_name(prefix: &str, name: &str) -> String { format!("{}::{}", prefix, name) } pub fn cubestore_benches() -> Vec<Arc<dyn Bench>> { return vec![ Arc::new(SimpleBench {}), Arc::new(ParquetMetadataCacheBench {}), ]; } pub struct SimpleBenchState { query: String, } pub struct SimpleBench; #[async_trait] impl Bench for SimpleBench { fn config(self: &Self, prefix: &str) -> (String, Config) { let name = config_name(prefix, "simple"); let config = Config::test(name.as_str()); (name, config) } async fn
(self: &Self, _services: &CubeServices) -> Result<Arc<BenchState>, CubeError> { Ok(Arc::new(SimpleBenchState { query: "SELECT 23".to_string(), })) } async fn bench( self: &Self, services: &CubeServices, state: Arc<BenchState>, ) -> Result<(), CubeError> { let state = state .downcast_ref::<SimpleBenchState>() .ok_or(CubeError::internal("bad state".to_string()))?; let r = services .sql_service .exec_query(state.query.as_str()) .await?; let rows = to_rows(&r); assert_eq!(rows, vec![vec![TableValue::Int(23)]]); Ok(()) } } // To compare, bench without / with bench enabled. // CUBESTORE_METADATA_CACHE_MAX_CAPACITY_BYTES=0 cargo bench parquet_metadata_cache // CUBESTORE_METADATA_CACHE_MAX_CAPACITY_BYTES=1000000 cargo bench parquet_metadata_cache pub struct ParquetMetadataCacheBench; #[async_trait] impl Bench for ParquetMetadataCacheBench { fn config(self: &Self, prefix: &str) -> (String, Config) { let name = config_name(prefix, "parquet_metadata_cache"); let config = Config::test(name.as_str()).update_config(|mut c| { c.partition_split_threshold = 10_000_000; c.max_partition_split_threshold = 10_000_000; c.max_cached_queries = 0; c.metadata_cache_max_capacity_bytes = env_parse("CUBESTORE_METADATA_CACHE_MAX_CAPACITY_BYTES", 0); c.metadata_cache_time_to_idle_secs = 1000; c }); (name, config) } async fn setup(self: &Self, services: &CubeServices) -> Result<Arc<BenchState>, CubeError> { let dataset_path = download_and_unzip( "https://github.com/cube-js/testing-fixtures/raw/master/github-commits.tar.gz", "github-commits", ) .await?; let path = dataset_path.join("github-commits-000.csv"); let _ = services .sql_service .exec_query("CREATE SCHEMA IF NOT EXISTS test") .await?; let _ = services.sql_service .exec_query(format!("CREATE TABLE test.table (`repo` text, `email` text, `commit_count` int) WITH (input_format = 'csv') LOCATION '{}'", path_to_string(path)?).as_str()) .await?; // Wait for all pending (compaction) jobs to finish. wait_for_all_jobs(&services).await?; let state = Arc::new(()); // Warmup metadata cache. self.bench(services, state.clone()).await?; Ok(state) } async fn bench( self: &Self, services: &CubeServices, _state: Arc<BenchState>, ) -> Result<(), CubeError> { let repo = "2degrees/twod.wsgi"; let r = services .sql_service .exec_query( format!( "SELECT COUNT(*) FROM test.table WHERE repo = '{}' GROUP BY repo", repo ) .as_str(), ) .await?; let rows = to_rows(&r); assert_eq!(rows, vec![vec![TableValue::Int(6)]]); Ok(()) } } async fn download_and_unzip(url: &str, dataset: &str) -> Result<Box<Path>, CubeError> { let root = std::env::current_dir()?.join("data"); let dataset_path = root.join(dataset); if !dataset_path.exists() { println!("Downloading {}", dataset); let response = reqwest::get(url).await?; let content = Cursor::new(response.bytes().await?); let tarfile = GzDecoder::new(content); let mut archive = Archive::new(tarfile); archive.unpack(root)?; } assert!(dataset_path.exists()); Ok(dataset_path.into_boxed_path()) } async fn wait_for_all_jobs(services: &CubeServices) -> Result<(), CubeError> { let wait_for = services .meta_store .all_jobs() .await? .iter() .map(|j| { ( j.get_row().row_reference().clone(), j.get_row().job_type().clone(), ) }) .collect(); let listener = services.cluster.job_result_listener(); timeout( Duration::from_secs(10), listener.wait_for_job_results(wait_for), ) .await??; Ok(()) }
setup
index.js
import React, { PureComponent, Fragment } from 'react'; import { connect } from 'dva'; import { Row, Col, Card, Form, Input, Select, Button, Modal, message, } from 'antd'; import StandardTable from '@/components/StandardTable'; import PageHeaderWrapper from '@/components/PageHeaderWrapper'; import Result from '@/components/Result'; import styles from './index.less'; const FormItem = Form.Item; const { Option } = Select; const getValue = obj => Object.keys(obj) .map(key => obj[key]) .join(','); @connect(({ outband, loading }) => ({ outband, loading: loading.models.outband, })) @Form.create() class Xss extends PureComponent { state = { deleteVisible: false, deleteDone: false, bulkDeleteVisible: false, bulkDeleteDone: false, selectedRows: [], formValues: {}, current: '', }; columns = [ { title: 'name', dataIndex: 'name', }, { title: 'location', dataIndex: 'location', }, { title: 'toplocation', dataIndex: 'toplocation', }, { title: 'opener', dataIndex: 'opener', }, { title: 'cookie', dataIndex: 'cookie', }, { title: '源IP', dataIndex: 'source_ip', }, { title: '时间', dataIndex: 'created', }, { title: '操作', render: (match, record) => ( <Fragment> <a onClick={() => this.showDeleteModal(record)}>删除</a> </Fragment> ), }, ]; componentDidMount() { const { dispatch } = this.props; dispatch({ type: 'outband/fetchXss', payload: { method: 'xss' }, }); }; handleSearch = e => { e.preventDefault(); const { dispatch, form } = this.props; const fieldsValue = form.getFieldsValue(); this.setState({ formValues: { 'search': fieldsValue.search, // 'name': fieldsValue.name, // 'domain': fieldsValue.domain, 'sourceIP': fieldsValue.sourceIP, } }); dispatch({ type: 'outband/fetchXss', payload: { method: 'xss', ...fieldsValue }, }); }; handleSearchFormReset = () => { const { form } = this.props; form.resetFields(); this.setState({ formValues: {} }); }; showDeleteModal = (record) => { this.setState({ deleteVisible: true, deleteDone: false, current: record, }); }; handleDeleteCancel = () => { // setTimeout(() => this.addBtn.blur(), 0); this.setState({ deleteVisible: false, }); }; handleDeleteDone = () => { // setTimeout(() => this.addBtn.blur(), 0); this.setState({ deleteDone: true, deleteVisible: false, }); }; handleDeleteItem = () => { const { dispatch } = this.props; const { current: { id } }= this.state; this.setState({ deleteDone: true, }); dispatch({ type: 'outband/submitXss', payload: { id ,method:'xss'}, }); dispatch({ type: 'outband/fetchXss', payload: {method:'xss'}, }); }; handleStandardTableChange = (pagination, filtersArg, sorter) => { const { dispatch } = this.props; const { formValues } = this.state; const filters = Object.keys(filtersArg).reduce((obj, key) => { const newObj = { ...obj }; newObj[key] = getValue(filtersArg[key]); return newObj; }, {}); const params = { currentPage: pagination.current, pageSize: pagination.pageSize, method: 'xss', ...formValues, ...filters, }; if (sorter.field) { params.sorter = `${sorter.field}_${sorter.order}`; } dispatch({ type: 'outband/fetchXss', payload: params, }); }; showBulkDeleteVisible = () => { this.setState({ bulkDeleteVisible: true, }); }; handleBulkDelete = () => { const { dispatch } = this.props; const { selectedRows } = this.state; if (selectedRows.length === 0) return; this.setState({ selectedRows: [], bulkDeleteDone: true, }); dispatch({ type: 'outband/bulkOperateXss', payload: { ids: selectedRows.map(row => row.id), method: 'xss' } }); message.success('操作成功'); dispatch({ type: 'outband/fetchXss', payload: { method: 'xss' }, }); }; handleBulkDeleteDone = () => { this.setState({ bulkDeleteDone: false, bulkDeleteVisible: false }); }; handelBulkDeleteCancel = () => { this.setState({ bulkDeleteVisible: false }) }; handleSelectRows = rows => { this.setState({ selectedRows: rows, }); }; render() { const { outband: { xss }, loading, form: { getFieldDecorator }, } = this.props; const { selectedRows, deleteVisible, bulkDeleteVisible, bulkDeleteDone, deleteDone = {} } = this.state; const modalDeleteFooter = deleteDone ? { footer: null, onCancel: this.handleDeleteDone } : { okText: '删除', onOk: this.handleDeleteItem, onCancel: this.handleDeleteCancel }; const bulkDeleteFooter = bulkDeleteDone ? { footer: null, onCancel: this.handelBulkDeleteDone } : { okText: '删除', onOk: this.handleBulkDelete, onCancel: this.handelBulkDeleteCancel }; const getOperateModalContent = () => { if (deleteDone) { return ( <Result type="success" title="删除成功" description="删除xss记录成功" actions={ <Button type="primary" onClick={this.handleDeleteDone}> 知道了 </Button> } className={styles.formResult} /> ); } return (<p>确定删除该xss记录?</p>) } const getBulkDeleteModalContent = () => { if (bulkDeleteDone) { return ( <Result type="success" title="删除成功" description="删除xss记录成功" actions={ <Button type="primary" onClick={this.handleBulkDeleteDone}> 知道了 </Button> } className={styles.formResult} /> ); } return (<p>确定批量删除xss记录?</p>) } return ( <PageHeaderWrapper title="xsslog列表"> <Card bordered={false}>
<FormItem label="搜索"> {getFieldDecorator('search', { rules: [{ required: false, message: '请输入' }] }) (<Input placeholder="请输入" style={{ width: '100%' }} />)} </FormItem> </Col> <Col md={6} sm={24}> <FormItem label="location"> {getFieldDecorator('location', { rules: [{ required: false, message: '请输入' }] }) (<Input placeholder="请输入" style={{ width: '100%' }} />)} </FormItem> </Col> <Col md={6} sm={24}> <FormItem label="源IP"> {getFieldDecorator('sourceIp', { rules: [{ required: false, message: '请输入请求IP' }] }) (<Input placeholder="请输入" style={{ width: '100%' }} />)} </FormItem> </Col> <Col md={6} sm={24}> <span className={styles.submitButtons}> <Button type="primary" htmlType="submit"> 查询 </Button> <Button style={{ marginLeft: 8 }} onClick={this.handleSearchFormReset}> 重置 </Button> </span> </Col> </Row> </Form> <div className={styles.tableListOperator}> {selectedRows.length > 0 && ( <span> <Button onClick={this.showBulkDeleteVisible}>批量删除</Button> </span> )} </div> <StandardTable selectedRows={selectedRows} loading={loading} data={xss} columns={this.columns} rowKey={record => record.id} onSelectRow={this.handleSelectRows} onChange={this.handleStandardTableChange} /> </div> </Card> <Modal title="xss记录删除" destroyOnClose visible={deleteVisible} {...modalDeleteFooter} > {getOperateModalContent()} </Modal> <Modal title="批量删除" destroyOnClose visible={bulkDeleteVisible} {...bulkDeleteFooter} > {getBulkDeleteModalContent()} </Modal> </PageHeaderWrapper> ); } } export default Xss;
<div className={styles.tableListForm}> <Form onSubmit={this.handleSearch} layout="inline"> <Row gutter={{ md: 6, lg: 24, xl: 48 }}> <Col md={6} sm={24}>
task_test.py
"""Module for testing CommandTasks.""" import os, sys import time from django.test import TestCase from norc.core.models import CommandTask, Instance, Revision from norc.core.constants import Status from norc.norc_utils import log class TestTask(TestCase): """Tests for Norc tasks.""" def run_task(self, task): if type(task) == str: task = CommandTask.objects.create(name=task, command=task) return self.run_instance(Instance.objects.create(task=task)).status def run_instance(self, instance): instance.log = log.Log(os.devnull, echo=True) try: instance.start() except SystemExit: pass return Instance.objects.get(pk=instance.pk) def disarm(self, instance): """Have to soften _nuke sometimes or the test process will die.""" def _nuke(): sys.exit(1) instance._nuke = _nuke def test_success(self): """Tests that a task can end with status SUCCESS.""" self.assertEqual(Status.SUCCESS, self.run_task('echo "Success!"')) def test_failure(self): """Tests that a task can end with status FAILURE.""" self.assertEqual(Status.FAILURE, self.run_task('exit 1')) self.assertEqual(Status.FAILURE, self.run_task('asd78sad7ftaoq')) def test_timeout(self): "Tests that a task can end with status TIMEDOUT." task = CommandTask.objects.create( name='Timeout', command='sleep 5', timeout=1) instance = Instance.objects.create(task=task) self.disarm(instance) self.assertEqual(Status.TIMEDOUT, self.run_instance(instance).status) def test_finally(self): task = CommandTask.objects.create(name='Nothing', command='sleep 0') instance = Instance.objects.create(task=task) self.disarm(instance) def finally_(): instance.status = Status.ERROR instance.finally_ = finally_ self.assertEqual(Status.ERROR, self.run_instance(instance).status) def test_finally_timeout(self): t = CommandTask.objects.create(name='Nothing', command='sleep 0') instance = Instance.objects.create(task=t) self.disarm(instance) from norc.core.models import task task.FINALLY_TIMEOUT = 1 def finally_(): import time time.sleep(2) instance.finally_ = finally_ self.assertEqual(Status.TIMEDOUT, self.run_instance(instance).status) def test_double_timeout(self): """Tests a task timing out and then its final block timing out. NOTE: because the "nuking" of the process can't occur in a test environment, this test actually results in the final clause being run twice. This won't happen in a real setting because _nuke() is aptly named. """ t = CommandTask.objects.create( name='Nothing', command='sleep 2', timeout=1) instance = Instance.objects.create(task=t) self.disarm(instance) from norc.core.models import task task.FINALLY_TIMEOUT = 1 def finally_(): import time time.sleep(2) instance.finally_ = finally_ self.assertEqual(Status.TIMEDOUT, self.run_instance(instance).status) def test_nameless(self):
def test_revisions(self): r = Revision.objects.create(info="rev") t = CommandTask.objects.create(command="ls") i = Instance.objects.create(task=t) i.get_revision = lambda: r self.assertEqual(r, self.run_instance(i).revision)
"Tests that a task can be nameless." t = CommandTask.objects.create(command="echo 'Nameless!'") self.assertEqual(Status.SUCCESS, self.run_task(t))
recognize.py
from __future__ import absolute_import import os.path import math from PIL import Image, ImageStat import numpy as np from shapely.geometry import Polygon, asPolygon from shapely.ops import unary_union from tesserocr import ( RIL, PSM, PT, OEM, Orientation, WritingDirection, TextlineOrder, tesseract_version, PyTessBaseAPI, get_languages as get_languages_) from ocrd_utils import ( getLogger, make_file_id, assert_file_grp_cardinality, shift_coordinates, coordinates_for_segment, polygon_from_x0y0x1y1, polygon_from_points, points_from_polygon, xywh_from_polygon, MIMETYPE_PAGE, membername ) from ocrd_models.ocrd_page import ( ReadingOrderType, RegionRefType, RegionRefIndexedType, OrderedGroupType, OrderedGroupIndexedType, UnorderedGroupType, UnorderedGroupIndexedType, PageType, CoordsType, ImageRegionType, MathsRegionType, SeparatorRegionType, NoiseRegionType, TableRegionType, TextRegionType, TextLineType, WordType, GlyphType, TextEquivType, AlternativeImageType, to_xml) from ocrd_models.ocrd_page_generateds import ( ReadingDirectionSimpleType, TextLineOrderSimpleType, TextTypeSimpleType ) from ocrd_modelfactory import page_from_file from ocrd import Processor from .config import get_tessdata_path, OCRD_TOOL TOOL = 'ocrd-tesserocr-recognize' CHOICE_THRESHOLD_NUM = 10 # maximum number of choices to query and annotate CHOICE_THRESHOLD_CONF = 1 # maximum score drop from best choice to query and annotate # (ChoiceIterator usually rounds to 0.0 for non-best, so this better be maximum) def get_languages(*args, **kwargs):
# monkey-patch the tesserocr base class so have at least some state class TessBaseAPI(PyTessBaseAPI): parameters = {} psm = PSM.AUTO image = None path = '' lang = '' oem = OEM.DEFAULT def __repr__(self): return str({'parameters': self.parameters, 'psm': self.psm, 'image': self.image, 'path': self.path, 'lang': self.lang, 'oem': self.oem}) def InitFull(self, path=None, lang=None, oem=None, psm=None, variables=None): self.path = path or self.path self.lang = lang or self.lang self.oem = oem or self.oem self.parameters = variables or self.parameters super().InitFull(path=self.path, lang=self.lang, oem=self.oem, variables=self.parameters) def SetVariable(self, name, val): self.parameters[name] = val return super().SetVariable(name, val) def SetPageSegMode(self, psm): self.psm = psm super().SetPageSegMode(psm) def Reset(self, path=None, lang=None, oem=None, psm=None, parameters=None): self.Clear() self.InitFull(path=path, lang=lang, oem=oem, variables=parameters) self.SetPageSegMode(psm or self.psm) def __enter__(self): self.original_path = self.path self.original_lang = self.lang self.original_oem = self.oem self.original_parameters = self.parameters.copy() self.original_psm = self.psm return self def __exit__(self, exc_type, exc_val, exc_trace): self.path = self.original_path self.lang = self.original_lang self.oem = self.original_oem self.parameters = self.original_parameters self.psm = self.original_psm return None class TesserocrRecognize(Processor): def __init__(self, *args, **kwargs): kwargs['ocrd_tool'] = OCRD_TOOL['tools'][TOOL] kwargs['version'] = OCRD_TOOL['version'] + ' (' + tesseract_version().split('\n')[0] + ')' super(TesserocrRecognize, self).__init__(*args, **kwargs) if hasattr(self, 'workspace'): self.logger = getLogger('processor.TesserocrRecognize') def process(self): """Perform layout segmentation and/or text recognition with Tesseract on the workspace. Open and deserialise PAGE input files and their respective images, then iterate over the element hierarchy down to the requested ``textequiv_level`` if it exists and if ``segmentation_level`` is lower (i.e. more granular) or ``none``. Otherwise stop before (i.e. above) ``segmentation_level``. If any segmentation exist at that level already, and ``overwrite_segments`` is false, then descend into these segments, else remove them. Set up Tesseract to recognise each segment's image (either from AlternativeImage or cropping the bounding box rectangle and masking it from the polygon outline) with the appropriate segmentation mode and ``model``. (If no ``model`` is given, only layout analysis will be performed.) Next, if there still is a gap between the current level in the PAGE hierarchy and the requested ``textequiv_level``, then iterate down the result hierarchy, adding new segments at each level (as well as reading order references, text line order, reading direction and orientation at the region/table level). Then, at ``textequiv_level``, remove any existing TextEquiv, unless ``overwrite_text`` is false, and add text and confidence results, unless ``model`` is empty. The special value ``textequiv_level=none`` behaves like ``glyph``, except that no actual text recognition will be performed, only layout analysis (so no ``model`` is needed, and new segmentation is created down to the glyph level). The special value ``segmentation_level=none`` likewise is lowest, i.e. no actual layout analysis will be performed, only text recognition (so existing segmentation is needed down to ``textequiv_level``). Finally, make all higher levels consistent with these text results by concatenation, ordering according to each level's respective readingDirection, textLineOrder, and ReadingOrder, and joining by whitespace as appropriate for each level and according to its Relation/join status. In other words: - If ``segmentation_level=region``, then segment the page into regions (unless ``overwrite_segments=false``), else iterate existing regions. - If ``textequiv_level=region``, then unless ``model`` is empty, recognize text in the region and annotate it. Regardless, continue with the next region. Otherwise... - If ``segmentation_level=cell`` or higher, then segment table regions into text regions (i.e. cells) (unless ``overwrite_segments=false``), else iterate existing cells. - If ``textequiv_level=cell``, then unless ``model`` is empty, recognize text in the cell and annotate it. Regardless, continue with the next cell. Otherwise... - If ``segmentation_level=line`` or higher, then segment text regions into text lines (unless ``overwrite_segments=false``), else iterate existing text lines. - If ``textequiv_level=line``, then unless ``model`` is empty, recognize text in the text lines and annotate it. Regardless, continue with the next line. Otherwise... - If ``segmentation_level=word`` or higher, then segment text lines into words (unless ``overwrite_segments=false``), else iterate existing words. - If ``textequiv_level=word``, then unless ``model`` is empty, recognize text in the words and annotate it. Regardless, continue with the next word. Otherwise... - If ``segmentation_level=glyph`` or higher, then segment words into glyphs (unless ``overwrite_segments=false``), else iterate existing glyphs. - If ``textequiv_level=glyph``, then unless ``model`` is empty, recognize text in the glyphs and annotate it. Regardless, continue with the next glyph. Otherwise... - (i.e. ``none``) annotate no text and be done. Note that ``cell`` is an _optional_ level that is only relevant for table regions, not text or other regions. Also, when segmenting tables in the same run that detects them (via ``segmentation_level=region`` and ``find_tables``), cells will just be 'paragraphs'. In contrast, when segmenting tables that already exist (via ``segmentation_level=cell``), cells will be detected in ``sparse_text`` mode, i.e. as single-line text regions. Thus, ``segmentation_level`` is the entry point level for layout analysis, and setting it to ``none`` makes this processor behave as recognition-only. Whereas ``textequiv_level`` selects the exit point level for segmentation, and setting it to ``none`` makes this processor behave as segmentation-only, as does omitting ``model``. All segments above ``segmentation_level`` must already exist, and no segments below ``textequiv_level`` will be newly created. If ``find_tables``, then during region segmentation, also try to detect table blocks and add them as TableRegion, then query the page iterator for paragraphs and add them as TextRegion cells. If ``block_polygons``, then during region segmentation, query Tesseract for polygon outlines instead of bounding boxes for each region. (This is more precise, but due to some path representation errors does not always yield accurate/valid polygons.) If ``shrink_polygons``, then during segmentation (on any level), query Tesseract for all symbols/glyphs of each segment and calculate the convex hull for them. Annotate the resulting polygon instead of the coarse bounding box. (This is more precise and helps avoid overlaps between neighbours, especially when not segmenting all levels at once.) If ``sparse_text``, then during region segmentation, attempt to find single-line text blocks in no particular order (Tesseract's page segmentation mode ``SPARSE_TEXT``). If ``tesseract_parameters`` is given, setup each of its key-value pairs as run-time parameters in Tesseract. Finally, produce new output files by serialising the resulting hierarchy. """ self.logger.debug("TESSDATA: %s, installed Tesseract models: %s", *get_languages()) assert_file_grp_cardinality(self.input_file_grp, 1) assert_file_grp_cardinality(self.output_file_grp, 1) inlevel = self.parameter['segmentation_level'] outlevel = self.parameter['textequiv_level'] segment_only = outlevel == 'none' or not self.parameter.get('model', '') model = "eng" self.languages = get_languages()[1] if 'model' in self.parameter: model = self.parameter['model'] for sub_model in model.split('+'): if sub_model.endswith('.traineddata'): self.logger.warning("Model '%s' has a .traineddata extension, removing. Please use model names without .traineddata extension" % sub_model) sub_model = sub_model.replace('.traineddata', '') if sub_model not in get_languages()[1]: raise Exception("configured model " + sub_model + " is not installed") self.logger.info("Using model '%s' in %s for recognition at the %s level", model, get_languages()[0], outlevel) with TessBaseAPI(init=False) as tessapi: # Set init-time parameters # self.SetVariable("debug_file", "") # show debug output (default: /dev/null) if outlevel == 'glyph': # populate GetChoiceIterator() with LSTM models, too: tessapi.SetVariable("lstm_choice_mode", "2") # aggregate symbols tessapi.SetVariable("lstm_choice_iterations", "15") # squeeze out more best paths tessapi.SetVariable("pageseg_apply_music_mask", "1" if self.parameter['find_staves'] else "0") # TODO: maybe warn/raise when illegal combinations or characters not in the model unicharset? if self.parameter['char_whitelist']: tessapi.SetVariable("tessedit_char_whitelist", self.parameter['char_whitelist']) if self.parameter['char_blacklist']: tessapi.SetVariable("tessedit_char_blacklist", self.parameter['char_blacklist']) if self.parameter['char_unblacklist']: tessapi.SetVariable("tessedit_char_unblacklist", self.parameter['char_unblacklist']) # todo: determine relevancy of these variables: # tessedit_preserve_min_wd_len 2 # tessedit_prefer_joined_punct 0 # tessedit_write_rep_codes 0 # tessedit_parallelize 0 # tessedit_zero_rejection 0 # tessedit_zero_kelvin_rejection 0 # tessedit_reject_mode 0 # tessedit_use_reject_spaces 1 # tessedit_fix_fuzzy_spaces 1 # tessedit_char_blacklist # tessedit_char_whitelist # chs_leading_punct ('`" # chs_trailing_punct1 ).,;:?! # chs_trailing_punct2 )'`" # numeric_punctuation ., # unrecognised_char | # ok_repeated_ch_non_alphanum_wds -?*= # conflict_set_I_l_1 Il1[] # preserve_interword_spaces 0 # tessedit_enable_dict_correction 0 # tessedit_enable_bigram_correction 1 # stopper_smallword_size 2 # wordrec_max_join_chunks 4 # suspect_space_level 100 # suspect_short_words 2 # language_model_ngram_on 0 # language_model_ngram_order 8 # language_model_min_compound_length 3 # language_model_penalty_non_freq_dict_word 0.1 # language_model_penalty_non_dict_word 0.15 # language_model_penalty_punc 0.2 # language_model_penalty_case 0.1 # language_model_penalty_script 0.5 # language_model_penalty_chartype 0.3 # language_model_penalty_spacing 0.05 # textord_max_noise_size 7 # enable_noise_removal 1 # classify_bln_numeric_mode 0 # lstm_use_matrix 1 # user_words_file # user_patterns_file tesseract_params = self.parameter['tesseract_parameters'] for variable in tesseract_params: tessapi.SetVariable(variable, tesseract_params[variable]) # Initialize Tesseract (loading model) tessapi.InitFull(path=get_tessdata_path(), lang=model, oem=getattr(OEM, self.parameter['oem'])) # Iterate input files for (n, input_file) in enumerate(self.input_files): file_id = make_file_id(input_file, self.output_file_grp) page_id = input_file.pageId or input_file.ID self.logger.info("INPUT FILE %i / %s", n, page_id) pcgts, pcgts_tree, pcgts_mapping, pcgts_invmap = page_from_file(self.workspace.download_file(input_file), with_tree=True) pcgts.set_pcGtsId(file_id) self.add_metadata(pcgts) page = pcgts.get_Page() page_image, page_coords, page_image_info = self.workspace.image_from_page( page, page_id) if self.parameter['dpi'] > 0: dpi = self.parameter['dpi'] self.logger.info("Page '%s' images will use %d DPI from parameter override", page_id, dpi) elif page_image_info.resolution != 1: dpi = page_image_info.resolution if page_image_info.resolutionUnit == 'cm': dpi = round(dpi * 2.54) self.logger.info("Page '%s' images will use %d DPI from image meta-data", page_id, dpi) else: dpi = 0 self.logger.info("Page '%s' images will use DPI estimated from segmentation", page_id) if dpi: tessapi.SetVariable('user_defined_dpi', str(dpi)) self.logger.info("Processing page '%s'", page_id) # FIXME: We should somehow _mask_ existing regions in order to annotate incrementally (not redundantly). # Currently segmentation_level=region also means removing regions, # but we could have an independent setting for that, and attempt # to detect regions only where nothing exists yet (by clipping to # background before, or by removing clashing predictions after # detection). regions = page.get_AllRegions(classes=['Text']) if inlevel == 'region' and ( not regions or self.parameter['overwrite_segments']): for regiontype in [ 'AdvertRegion', 'ChartRegion', 'ChemRegion', 'GraphicRegion', 'ImageRegion', 'LineDrawingRegion', 'MathsRegion', 'MusicRegion', 'NoiseRegion', 'SeparatorRegion', 'TableRegion', 'TextRegion', 'UnknownRegion']: if getattr(page, 'get_' + regiontype)(): self.logger.info('Removing existing %ss on page %s', regiontype, page_id) getattr(page, 'set_' + regiontype)([]) page.set_ReadingOrder(None) # prepare Tesseract if self.parameter['find_tables']: if outlevel == 'region' and self.parameter.get('model', ''): raise Exception("When segmentation_level is region and find_tables is enabled, textequiv_level must be at least cell, because text results cannot be annotated on tables directly.") tessapi.SetVariable("textord_tabfind_find_tables", "1") # (default) # this should yield additional blocks within the table blocks # from the page iterator, but does not in fact (yet?): # (and it can run into assertion errors when the table structure # does not meet certain homogeneity expectations) #tessapi.SetVariable("textord_tablefind_recognize_tables", "1") else: # disable table detection here, so tables will be # analysed as independent text/line blocks: tessapi.SetVariable("textord_tabfind_find_tables", "0") tessapi.SetImage(page_image) # is already cropped to Border tessapi.SetPageSegMode(PSM.SPARSE_TEXT if self.parameter['sparse_text'] else PSM.AUTO) if segment_only: self.logger.debug("Detecting regions in page '%s'", page_id) tessapi.AnalyseLayout() else: self._reinit(tessapi, page, pcgts_mapping) self.logger.debug("Recognizing text in page '%s'", page_id) tessapi.Recognize() page_image_bin = tessapi.GetThresholdedImage() file_path = self.workspace.save_image_file( page_image_bin, file_id + '.IMG-BIN', page_id=page_id, file_grp=self.output_file_grp) # update PAGE (reference the image file): page.add_AlternativeImage(AlternativeImageType( filename=file_path, comments=page_coords['features'] + ',binarized,clipped')) self._process_regions_in_page(tessapi.GetIterator(), page, page_coords, pcgts_mapping, dpi) elif inlevel == 'cell': # Tables are obligatorily recursive regions; # they might have existing text regions (cells), # which will be processed in the next branch # (because the iterator is recursive to depth), # or be empty. This is independent of whether # or not they should be segmented into cells. if outlevel == 'region': raise Exception("When segmentation_level is cell, textequiv_level must be at least cell too, because text results cannot be annotated on tables directly.") # disable table detection here, so tables will be # analysed as independent text/line blocks: tessapi.SetVariable("textord_tabfind_find_tables", "0") tables = page.get_AllRegions(classes=['Table']) if not tables: self.logger.warning("Page '%s' contains no table regions (but segmentation is off)", page_id) else: self._process_existing_tables(tessapi, tables, page, page_image, page_coords, pcgts_mapping) elif regions: self._process_existing_regions(tessapi, regions, page_image, page_coords, pcgts_mapping) else: self.logger.warning("Page '%s' contains no text regions (but segmentation is off)", page_id) # post-processing # bottom-up text concatenation if outlevel != 'none' and self.parameter.get('model', ''): page_update_higher_textequiv_levels(outlevel, pcgts, self.parameter['overwrite_text']) # bottom-up polygonal outline projection # if inlevel != 'none' and self.parameter['shrink_polygons']: # page_shrink_higher_coordinate_levels(inlevel, outlevel, pcgts) self.workspace.add_file( ID=file_id, file_grp=self.output_file_grp, pageId=input_file.pageId, mimetype=MIMETYPE_PAGE, local_filename=os.path.join(self.output_file_grp, file_id + '.xml'), content=to_xml(pcgts)) def _process_regions_in_page(self, result_it, page, page_coords, mapping, dpi): index = 0 ro = page.get_ReadingOrder() if not ro: ro = ReadingOrderType() page.set_ReadingOrder(ro) og = ro.get_OrderedGroup() if og: # start counting from largest existing index for elem in (og.get_RegionRefIndexed() + og.get_OrderedGroupIndexed() + og.get_UnorderedGroupIndexed()): if elem.index >= index: index = elem.index + 1 else: # new top-level group og = OrderedGroupType(id="reading-order") ro.set_OrderedGroup(og) # equivalent to GetComponentImages with raw_image=True, # (which would also give raw coordinates), # except we are also interested in the iterator's BlockType() here, # and its BlockPolygon() for i, it in enumerate(iterate_level(result_it, RIL.BLOCK)): # (padding will be passed to both BoundingBox and GetImage) # (actually, Tesseract honours padding only on the left and bottom, # whereas right and top are increased less!) # TODO: output padding can create overlap between neighbours; at least find polygonal difference bbox = it.BoundingBox(RIL.BLOCK, padding=self.parameter['padding']) # sometimes these polygons are not planar, which causes # PIL.ImageDraw.Draw.polygon (and likely others as well) # to misbehave; however, PAGE coordinate semantics prohibit # multi-path polygons! # (probably a bug in Tesseract itself, cf. tesseract#2826): if self.parameter['block_polygons']: polygon = it.BlockPolygon() elif self.parameter['shrink_polygons'] and not it.Empty(RIL.SYMBOL): polygon = join_polygons([polygon_from_x0y0x1y1( symbol.BoundingBox(RIL.SYMBOL, padding=self.parameter['padding'])) for symbol in iterate_level(it, RIL.SYMBOL, parent=RIL.BLOCK)]) # simulate a RestartBlock(), not defined by Tesseract: it.Begin() for j, it in enumerate(iterate_level(it, RIL.BLOCK)): if i == j: break else: polygon = polygon_from_x0y0x1y1(bbox) xywh = xywh_from_polygon(polygon) polygon = coordinates_for_segment(polygon, None, page_coords) polygon2 = polygon_for_parent(polygon, page) if polygon2 is not None: polygon = polygon2 points = points_from_polygon(polygon) coords = CoordsType(points=points) # plausibilise candidate if polygon2 is None: self.logger.info('Ignoring extant region: %s', points) continue block_type = it.BlockType() if block_type in [ PT.FLOWING_TEXT, PT.HEADING_TEXT, PT.PULLOUT_TEXT, PT.CAPTION_TEXT, PT.VERTICAL_TEXT, PT.INLINE_EQUATION, PT.EQUATION, PT.TABLE] and ( xywh['w'] < 20 / 300.0*(dpi or 300) or xywh['h'] < 10 / 300.0*(dpi or 300)): self.logger.info('Ignoring too small region: %s', points) continue region_image_bin = it.GetBinaryImage(RIL.BLOCK) if not region_image_bin or not region_image_bin.getbbox(): self.logger.info('Ignoring binary-empty region: %s', points) continue # # keep and annotate new region ID = "region%04d" % index # # region type switch block_type = it.BlockType() self.logger.info("Detected region '%s': %s (%s)", ID, points, membername(PT, block_type)) if block_type in [PT.FLOWING_TEXT, PT.HEADING_TEXT, PT.PULLOUT_TEXT, PT.CAPTION_TEXT, # TABLE is contained in PTIsTextType, but # it is a bad idea to create a TextRegion # for it (better set `find_tables` False): # PT.TABLE, # will also get a 90° @orientation # (but that can be overridden by deskew/OSD): PT.VERTICAL_TEXT]: region = TextRegionType(id=ID, Coords=coords, type=TextTypeSimpleType.PARAGRAPH) if block_type == PT.VERTICAL_TEXT: region.set_orientation(90.0) elif block_type == PT.HEADING_TEXT: region.set_type(TextTypeSimpleType.HEADING) elif block_type == PT.PULLOUT_TEXT: region.set_type(TextTypeSimpleType.FLOATING) elif block_type == PT.CAPTION_TEXT: region.set_type(TextTypeSimpleType.CAPTION) page.add_TextRegion(region) og.add_RegionRefIndexed(RegionRefIndexedType(regionRef=ID, index=index)) if self.parameter['textequiv_level'] not in ['region', 'cell']: self._process_lines_in_region(it, region, page_coords, mapping) elif self.parameter.get('model', ''): region.add_TextEquiv(TextEquivType( Unicode=it.GetUTF8Text(RIL.BLOCK).rstrip("\n\f"), # iterator scores are arithmetic averages, too conf=it.Confidence(RIL.BLOCK)/100.0)) elif block_type in [PT.FLOWING_IMAGE, PT.HEADING_IMAGE, PT.PULLOUT_IMAGE]: region = ImageRegionType(id=ID, Coords=coords) page.add_ImageRegion(region) og.add_RegionRefIndexed(RegionRefIndexedType(regionRef=ID, index=index)) elif block_type in [PT.HORZ_LINE, PT.VERT_LINE]: region = SeparatorRegionType(id=ID, Coords=coords) page.add_SeparatorRegion(region) elif block_type in [PT.INLINE_EQUATION, PT.EQUATION]: region = MathsRegionType(id=ID, Coords=coords) page.add_MathsRegion(region) og.add_RegionRefIndexed(RegionRefIndexedType(regionRef=ID, index=index)) elif block_type == PT.TABLE: # without API access to StructuredTable we cannot # do much for a TableRegionType (i.e. nrows, ncols, # coordinates of cells for recursive regions etc), # but this can be achieved afterwards by segment-table region = TableRegionType(id=ID, Coords=coords) page.add_TableRegion(region) rogroup = OrderedGroupIndexedType(id=ID + '_order', regionRef=ID, index=index) og.add_OrderedGroupIndexed(rogroup) if self.parameter['textequiv_level'] == 'region': pass # impossible (see exception above) # todo: TableRegionType has no TextEquiv in PAGE # region.add_TextEquiv(TextEquivType( # Unicode=it.GetUTF8Text(RIL.BLOCK).rstrip("\n\f"), # # iterator scores are arithmetic averages, too # conf=it.Confidence(RIL.BLOCK)/100.0)) else: self._process_cells_in_table(it, region, rogroup, page_coords, mapping) else: region = NoiseRegionType(id=ID, Coords=coords) page.add_NoiseRegion() # # add orientation if isinstance(region, (TextRegionType, TableRegionType, ImageRegionType, MathsRegionType)): self._add_orientation(it, region, page_coords) # # iterator increment # index += 1 if (not og.get_RegionRefIndexed() and not og.get_OrderedGroupIndexed() and not og.get_UnorderedGroupIndexed()): # schema forbids empty OrderedGroup ro.set_OrderedGroup(None) def _process_cells_in_table(self, result_it, region, rogroup, page_coords, mapping): if self.parameter['segmentation_level'] == 'cell': ril = RIL.BLOCK # for sparse_text mode else: ril = RIL.PARA # for "cells" in PT.TABLE block for index, it in enumerate(iterate_level(result_it, ril)): bbox = it.BoundingBox(ril, padding=self.parameter['padding']) if self.parameter['shrink_polygons'] and not it.Empty(RIL.SYMBOL): polygon = join_polygons([polygon_from_x0y0x1y1( symbol.BoundingBox(RIL.SYMBOL, padding=self.parameter['padding'])) for symbol in iterate_level(it, RIL.SYMBOL, parent=ril)]) if ril == RIL.BLOCK: # simulate a RestartBlock(), not defined by Tesseract: it.Begin() for j, it in enumerate(iterate_level(it, RIL.BLOCK)): if index == j: break else: it.RestartParagraph() else: polygon = polygon_from_x0y0x1y1(bbox) polygon = coordinates_for_segment(polygon, None, page_coords) polygon2 = polygon_for_parent(polygon, region) if polygon2 is not None: polygon = polygon2 points = points_from_polygon(polygon) coords = CoordsType(points=points) if polygon2 is None: self.logger.info('Ignoring extant cell: %s', points) continue ID = region.id + "_cell%04d" % index self.logger.info("Detected cell '%s': %s", ID, points) cell = TextRegionType(id=ID, Coords=coords) region.add_TextRegion(cell) self._add_orientation(it, cell, page_coords) if rogroup: rogroup.add_RegionRefIndexed(RegionRefIndexedType(regionRef=ID, index=index)) if self.parameter['textequiv_level'] != 'cell': self._process_lines_in_region(it, cell, page_coords, mapping, parent_ril=ril) elif self.parameter.get('model', ''): cell.add_TextEquiv(TextEquivType( Unicode=it.GetUTF8Text(ril).rstrip("\n\f"), # iterator scores are arithmetic averages, too conf=it.Confidence(ril)/100.0)) def _process_lines_in_region(self, result_it, region, page_coords, mapping, parent_ril=RIL.BLOCK): if self.parameter['sparse_text']: it = result_it region.set_type(TextTypeSimpleType.OTHER) line = TextLineType(id=region.id + '_line', Coords=region.get_Coords()) region.add_TextLine(line) if self.parameter['textequiv_level'] != 'line': self._process_words_in_line(it, line, page_coords, mapping) elif self.parameter.get('model', ''): # todo: consider BlankBeforeWord, SetLineSeparator line.add_TextEquiv(TextEquivType( Unicode=it.GetUTF8Text(RIL.TEXTLINE).rstrip("\n\f"), # iterator scores are arithmetic averages, too conf=it.Confidence(RIL.TEXTLINE)/100.0)) return for index, it in enumerate(iterate_level(result_it, RIL.TEXTLINE, parent=parent_ril)): bbox = it.BoundingBox(RIL.TEXTLINE, padding=self.parameter['padding']) if self.parameter['shrink_polygons'] and not it.Empty(RIL.SYMBOL): polygon = join_polygons([polygon_from_x0y0x1y1( symbol.BoundingBox(RIL.SYMBOL, padding=self.parameter['padding'])) for symbol in iterate_level(it, RIL.SYMBOL, parent=RIL.TEXTLINE)]) it.RestartRow() else: polygon = polygon_from_x0y0x1y1(bbox) polygon = coordinates_for_segment(polygon, None, page_coords) polygon2 = polygon_for_parent(polygon, region) if polygon2 is not None: polygon = polygon2 points = points_from_polygon(polygon) coords = CoordsType(points=points) if polygon2 is None: self.logger.info('Ignoring extant line: %s', points) continue ID = region.id + "_line%04d" % index self.logger.info("Detected line '%s': %s", ID, points) line = TextLineType(id=ID, Coords=coords) region.add_TextLine(line) if self.parameter['textequiv_level'] != 'line': self._process_words_in_line(it, line, page_coords, mapping) elif self.parameter.get('model', ''): # todo: consider BlankBeforeWord, SetLineSeparator line.add_TextEquiv(TextEquivType( Unicode=it.GetUTF8Text(RIL.TEXTLINE).rstrip("\n\f"), # iterator scores are arithmetic averages, too conf=it.Confidence(RIL.TEXTLINE)/100.0)) def _process_words_in_line(self, result_it, line, coords, mapping): for index, it in enumerate(iterate_level(result_it, RIL.WORD)): bbox = it.BoundingBox(RIL.WORD, padding=self.parameter['padding']) if self.parameter['shrink_polygons'] and not it.Empty(RIL.SYMBOL): polygon = join_polygons([polygon_from_x0y0x1y1( symbol.BoundingBox(RIL.SYMBOL, padding=self.parameter['padding'])) for symbol in iterate_level(it, RIL.SYMBOL, parent=RIL.WORD)]) # simulate a BeginWord(index), not exposed by tesserocr: it.RestartRow() for j, it in enumerate(iterate_level(it, RIL.WORD)): if index == j: break else: polygon = polygon_from_x0y0x1y1(bbox) polygon = coordinates_for_segment(polygon, None, coords) polygon2 = polygon_for_parent(polygon, line) if polygon2 is not None: polygon = polygon2 points = points_from_polygon(polygon) if polygon2 is None: self.logger.info('Ignoring extant word: %s', points) continue ID = line.id + "_word%04d" % index self.logger.debug("Detected word '%s': %s", ID, points) word = WordType(id=ID, Coords=CoordsType(points=points)) line.add_Word(word) if self.parameter['textequiv_level'] != 'word': self._process_glyphs_in_word(it, word, coords, mapping) elif self.parameter.get('model', ''): word.add_TextEquiv(TextEquivType( Unicode=it.GetUTF8Text(RIL.WORD), # iterator scores are arithmetic averages, too conf=it.Confidence(RIL.WORD)/100.0)) def _process_glyphs_in_word(self, result_it, word, coords, mapping): for index, it in enumerate(iterate_level(result_it, RIL.SYMBOL)): bbox = it.BoundingBox(RIL.SYMBOL, padding=self.parameter['padding']) polygon = polygon_from_x0y0x1y1(bbox) polygon = coordinates_for_segment(polygon, None, coords) polygon2 = polygon_for_parent(polygon, word) if polygon2 is not None: polygon = polygon2 points = points_from_polygon(polygon) if polygon2 is None: self.logger.info('Ignoring extant glyph: %s', points) continue ID = word.id + '_glyph%04d' % index #self.logger.debug("Detected glyph '%s': %s", ID, points) glyph = GlyphType(id=ID, Coords=CoordsType(points)) word.add_Glyph(glyph) if self.parameter['textequiv_level'] != 'glyph': pass elif self.parameter.get('model', ''): glyph_text = it.GetUTF8Text(RIL.SYMBOL) # equals first choice? glyph_conf = it.Confidence(RIL.SYMBOL)/100 # equals first choice? #self.logger.debug('best glyph: "%s" [%f]', glyph_text, glyph_conf) glyph.add_TextEquiv(TextEquivType( index=0, Unicode=glyph_text, conf=glyph_conf)) choice_it = it.GetChoiceIterator() for choice_no, choice in enumerate(choice_it, 1): alternative_text = choice.GetUTF8Text() or '' alternative_conf = choice.Confidence()/100 if alternative_text == glyph_text: continue #self.logger.debug('alternative glyph: "%s" [%f]', alternative_text, alternative_conf) if (glyph_conf - alternative_conf > CHOICE_THRESHOLD_CONF or choice_no > CHOICE_THRESHOLD_NUM): break # todo: consider SymbolIsSuperscript (TextStyle), SymbolIsDropcap (RelationType) etc glyph.add_TextEquiv(TextEquivType( index=choice_no, Unicode=alternative_text, conf=alternative_conf)) def _process_existing_tables(self, tessapi, tables, page, page_image, page_coords, mapping): # prepare dict of reading order reading_order = dict() ro = page.get_ReadingOrder() if not ro: self.logger.warning("Page contains no ReadingOrder") rogroup = None else: rogroup = ro.get_OrderedGroup() or ro.get_UnorderedGroup() page_get_reading_order(reading_order, rogroup) segment_only = self.parameter['textequiv_level'] == 'none' or not self.parameter.get('model', '') # dive into tables for table in tables: cells = table.get_TextRegion() if cells: if not self.parameter['overwrite_segments']: self._process_existing_regions(tessapi, cells, page_image, page_coords, mapping) continue self.logger.info('Removing existing TextRegion cells in table %s', table.id) for cell in table.get_TextRegion(): if cell.id in reading_order: regionref = reading_order[cell.id] self.logger.debug('removing cell %s ref %s', cell.id, regionref.regionRef) # could be any of the 6 types above: regionrefs = regionref.parent_object_.__getattribute__( regionref.__class__.__name__.replace('Type', '')) # remove in-place regionrefs.remove(regionref) del reading_order[cell.id] # TODO: adjust index to make contiguous again? table.set_TextRegion([]) roelem = reading_order.get(table.id) if not roelem: self.logger.warning("Table '%s' is not referenced in reading order (%s)", table.id, "no target to add cells into") elif isinstance(roelem, (OrderedGroupType, OrderedGroupIndexedType)): self.logger.warning("Table '%s' already has an ordered group (%s)", table.id, "cells will be appended") elif isinstance(roelem, (UnorderedGroupType, UnorderedGroupIndexedType)): self.logger.warning("Table '%s' already has an unordered group (%s)", table.id, "cells will not be appended") roelem = None elif isinstance(roelem, RegionRefIndexedType): # replace regionref by group with same index and ref # (which can then take the cells as subregions) roelem2 = OrderedGroupIndexedType(id=table.id + '_order', index=roelem.index, regionRef=roelem.regionRef) roelem.parent_object_.add_OrderedGroupIndexed(roelem2) roelem.parent_object_.get_RegionRefIndexed().remove(roelem) roelem = roelem2 elif isinstance(roelem, RegionRefType): # replace regionref by group with same ref # (which can then take the cells as subregions) roelem2 = OrderedGroupType(id=table.id + '_order', regionRef=roelem.regionRef) roelem.parent_object_.add_OrderedGroup(roelem2) roelem.parent_object_.get_RegionRef().remove(roelem) roelem = roelem2 # set table image table_image, table_coords = self.workspace.image_from_segment( table, page_image, page_coords) if not table_image.width or not table_image.height: self.logger.warning("Skipping table region '%s' with zero size", table.id) continue if self.parameter['padding']: tessapi.SetImage(pad_image(table_image, self.parameter['padding'])) table_coords['transform'] = shift_coordinates( table_coords['transform'], 2*[self.parameter['padding']]) else: tessapi.SetImage(table_image) tessapi.SetPageSegMode(PSM.SPARSE_TEXT) # retrieve "cells" # TODO: we should XY-cut the sparse cells in regroup them into consistent cells if segment_only: self.logger.debug("Detecting cells in table '%s'", table.id) tessapi.AnalyseLayout() else: self._reinit(tessapi, table, mapping) self.logger.debug("Recognizing text in table '%s'", table.id) tessapi.Recognize() self._process_cells_in_table(tessapi.GetIterator(), table, roelem, table_coords, mapping) def _process_existing_regions(self, tessapi, regions, page_image, page_coords, mapping): if self.parameter['textequiv_level'] in ['region', 'cell'] and not self.parameter.get('model', ''): return segment_only = self.parameter['textequiv_level'] == 'none' or not self.parameter.get('model', '') for region in regions: region_image, region_coords = self.workspace.image_from_segment( region, page_image, page_coords) if not region_image.width or not region_image.height: self.logger.warning("Skipping text region '%s' with zero size", region.id) continue if (region.get_TextEquiv() and not self.parameter['overwrite_text'] if self.parameter['textequiv_level'] in ['region', 'cell'] else self.parameter['segmentation_level'] != 'line'): pass # image not used here elif self.parameter['padding']: region_image = pad_image(region_image, self.parameter['padding']) tessapi.SetImage(region_image) region_coords['transform'] = shift_coordinates( region_coords['transform'], 2*[self.parameter['padding']]) else: tessapi.SetImage(region_image) tessapi.SetPageSegMode(PSM.SINGLE_BLOCK) if not segment_only: self._reinit(tessapi, region, mapping) # cell (region in table): we could enter from existing_tables or top-level existing regions if self.parameter['textequiv_level'] in ['region', 'cell']: #if region.get_primaryScript() not in tessapi.GetLoadedLanguages()... if region.get_TextEquiv(): if not self.parameter['overwrite_text']: continue self.logger.warning("Region '%s' already contained text results", region.id) region.set_TextEquiv([]) self.logger.debug("Recognizing text in region '%s'", region.id) # todo: consider SetParagraphSeparator region.add_TextEquiv(TextEquivType( Unicode=tessapi.GetUTF8Text().rstrip("\n\f"), # iterator scores are arithmetic averages, too conf=tessapi.MeanTextConf()/100.0)) continue # next region (to avoid indentation below) ## line, word, or glyph level: textlines = region.get_TextLine() if self.parameter['segmentation_level'] == 'line' and ( not textlines or self.parameter['overwrite_segments']): if textlines: self.logger.info('Removing existing text lines in region %s', region.id) region.set_TextLine([]) if segment_only: self.logger.debug("Detecting lines in region '%s'", region.id) tessapi.AnalyseLayout() else: self.logger.debug("Recognizing text in region '%s'", region.id) tessapi.Recognize() self._process_lines_in_region(tessapi.GetIterator(), region, region_coords, mapping) elif textlines: self._process_existing_lines(tessapi, textlines, region_image, region_coords, mapping) else: self.logger.warning("Region '%s' contains no text lines (but segmentation is off)", region.id) def _process_existing_lines(self, tessapi, textlines, region_image, region_coords, mapping): if self.parameter['textequiv_level'] == 'line' and not self.parameter.get('model', ''): return segment_only = self.parameter['textequiv_level'] == 'none' or not self.parameter.get('model', '') for line in textlines: line_image, line_coords = self.workspace.image_from_segment( line, region_image, region_coords) if not line_image.width or not line_image.height: self.logger.warning("Skipping text line '%s' with zero size", line.id) continue if (line.get_TextEquiv() and not self.parameter['overwrite_text'] if self.parameter['textequiv_level'] == 'line' else self.parameter['segmentation_level'] != 'word'): pass # image not used here elif self.parameter['padding']: line_image = pad_image(line_image, self.parameter['padding']) tessapi.SetImage(line_image) line_coords['transform'] = shift_coordinates( line_coords['transform'], 2*[self.parameter['padding']]) else: tessapi.SetImage(line_image) if self.parameter['raw_lines']: tessapi.SetPageSegMode(PSM.RAW_LINE) else: tessapi.SetPageSegMode(PSM.SINGLE_LINE) if not segment_only: self._reinit(tessapi, line, mapping) #if line.get_primaryScript() not in tessapi.GetLoadedLanguages()... if self.parameter['textequiv_level'] == 'line': if line.get_TextEquiv(): if not self.parameter['overwrite_text']: continue self.logger.warning("Line '%s' already contained text results", line.id) line.set_TextEquiv([]) self.logger.debug("Recognizing text in line '%s'", line.id) # todo: consider BlankBeforeWord, SetLineSeparator line.add_TextEquiv(TextEquivType( Unicode=tessapi.GetUTF8Text().rstrip("\n\f"), # iterator scores are arithmetic averages, too conf=tessapi.MeanTextConf()/100.0)) continue # next line (to avoid indentation below) ## word, or glyph level: words = line.get_Word() if self.parameter['segmentation_level'] == 'word' and ( not words or self.parameter['overwrite_segments']): if words: self.logger.info('Removing existing words in line %s', line.id) line.set_Word([]) if segment_only: self.logger.debug("Detecting words in line '%s'", line.id) tessapi.AnalyseLayout() else: self.logger.debug("Recognizing text in line '%s'", line.id) tessapi.Recognize() ## internal word and glyph layout: self._process_words_in_line(tessapi.GetIterator(), line, line_coords, mapping) elif words: ## external word layout: self.logger.warning("Line '%s' contains words already, recognition might be suboptimal", line.id) self._process_existing_words(tessapi, words, line_image, line_coords, mapping) else: self.logger.warning("Line '%s' contains no words (but segmentation if off)", line.id) def _process_existing_words(self, tessapi, words, line_image, line_coords, mapping): if self.parameter['textequiv_level'] == 'word' and not self.parameter.get('model', ''): return segment_only = self.parameter['textequiv_level'] == 'none' or not self.parameter.get('model', '') for word in words: word_image, word_coords = self.workspace.image_from_segment( word, line_image, line_coords) if not word_image.width or not word_image.height: self.logger.warning("Skipping word '%s' with zero size", word.id) continue if (word.get_TextEquiv() and not self.parameter['overwrite_text'] if self.parameter['textequiv_level'] == 'word' else self.parameter['segmentation_level'] != 'glyph'): pass # image not used here elif self.parameter['padding']: word_image = pad_image(word_image, self.parameter['padding']) tessapi.SetImage(word_image) word_coords['transform'] = shift_coordinates( word_coords['transform'], 2*[self.parameter['padding']]) else: tessapi.SetImage(word_image) tessapi.SetPageSegMode(PSM.SINGLE_WORD) if not segment_only: self._reinit(tessapi, word, mapping) if self.parameter['textequiv_level'] == 'word': if word.get_TextEquiv(): if not self.parameter['overwrite_text']: continue self.logger.warning("Word '%s' already contained text results", word.id) word.set_TextEquiv([]) self.logger.debug("Recognizing text in word '%s'", word.id) word_conf = tessapi.AllWordConfidences() word.add_TextEquiv(TextEquivType( Unicode=tessapi.GetUTF8Text().rstrip("\n\f"), conf=word_conf[0]/100.0 if word_conf else 0.0)) continue # next word (to avoid indentation below) ## glyph level: glyphs = word.get_Glyph() if self.parameter['segmentation_level'] == 'glyph' and ( not glyphs or self.parameter['overwrite_segments']): if glyphs: self.logger.info('Removing existing glyphs in word %s', word.id) word.set_Glyph([]) if segment_only: self.logger.debug("Detecting glyphs in word '%s'", word.id) tessapi.AnalyseLayout() else: self.logger.debug("Recognizing text in word '%s'", word.id) tessapi.Recognize() ## internal glyph layout: self._process_glyphs_in_word(tessapi.GetIterator(), word, word_coords, mapping) elif glyphs: ## external glyph layout: self.logger.warning("Word '%s' contains glyphs already, recognition might be suboptimal", word.id) self._process_existing_glyphs(tessapi, glyphs, word_image, word_coords, mapping) else: self.logger.warning("Word '%s' contains no glyphs (but segmentation if off)", word.id) def _process_existing_glyphs(self, tessapi, glyphs, word_image, word_xywh, mapping): if not self.parameter.get('model', ''): return for glyph in glyphs: glyph_image, _ = self.workspace.image_from_segment( glyph, word_image, word_xywh) if not glyph_image.width or not glyph_image.height: self.logger.warning("Skipping glyph '%s' with zero size", glyph.id) continue if glyph.get_TextEquiv() and not self.parameter['overwrite_text']: pass # image not used here elif self.parameter['padding']: tessapi.SetImage(pad_image(glyph_image, self.parameter['padding'])) else: tessapi.SetImage(glyph_image) tessapi.SetPageSegMode(PSM.SINGLE_CHAR) self._reinit(tessapi, glyph, mapping) if glyph.get_TextEquiv(): if not self.parameter['overwrite_text']: continue self.logger.warning("Glyph '%s' already contained text results", glyph.id) glyph.set_TextEquiv([]) self.logger.debug("Recognizing text in glyph '%s'", glyph.id) glyph_text = tessapi.GetUTF8Text().rstrip("\n\f") glyph_conf = tessapi.AllWordConfidences() glyph_conf = glyph_conf[0]/100.0 if glyph_conf else 1.0 #self.logger.debug('best glyph: "%s" [%f]', glyph_text, glyph_conf) glyph.add_TextEquiv(TextEquivType( index=0, Unicode=glyph_text, conf=glyph_conf)) result_it = tessapi.GetIterator() if not result_it or result_it.Empty(RIL.SYMBOL): self.logger.error("No text in glyph '%s'", glyph.id) continue choice_it = result_it.GetChoiceIterator() for choice_no, choice in enumerate(choice_it, 1): alternative_text = choice.GetUTF8Text() alternative_conf = choice.Confidence()/100 if alternative_text == glyph_text: continue #self.logger.debug('alternative glyph: "%s" [%f]', alternative_text, alternative_conf) if (glyph_conf - alternative_conf > CHOICE_THRESHOLD_CONF or choice_no > CHOICE_THRESHOLD_NUM): break # todo: consider SymbolIsSuperscript (TextStyle), SymbolIsDropcap (RelationType) etc glyph.add_TextEquiv(TextEquivType( index=choice_no, Unicode=alternative_text, conf=alternative_conf)) def _add_orientation(self, result_it, region, coords): # Tesseract layout analysis already rotates the image, even for each # sub-segment (depending on RIL). # (These images can be queried via GetBinaryImage/GetImage, cf. segment_region) # Unfortunately, it does _not_ use expand=True, but chops off corners. # So the accuracy is not as good as setting the image to the sub-segments and # running without iterator. But there are other reasons to do all-in-one # segmentation (like overlaps), and its up to the user now. # Here we don't know whether the iterator will be used or the created PAGE segments. # For the latter case at least, we must annotate the angle, so the segment image # can be rotated before the next step. orientation, writing_direction, textline_order, deskew_angle = result_it.Orientation() # defined as 'how many radians does one have to rotate the block anti-clockwise' # i.e. positive amount to be applied counter-clockwise for deskewing: deskew_angle *= 180 / math.pi self.logger.debug('orientation/deskewing for %s: %s / %s / %s / %.3f°', region.id, membername(Orientation, orientation), membername(WritingDirection, writing_direction), membername(TextlineOrder, textline_order), deskew_angle) # defined as 'the amount of clockwise rotation to be applied to the input image' # i.e. the negative amount to be applied counter-clockwise for deskewing: # (as defined in Tesseract OrientationIdToValue): angle = { Orientation.PAGE_RIGHT: 90, Orientation.PAGE_DOWN: 180, Orientation.PAGE_LEFT: 270 }.get(orientation, 0) # annotate result: angle += deskew_angle # get deskewing (w.r.t. top image) already applied to image angle0 = coords['angle'] # page angle: PAGE @orientation is defined clockwise, # whereas PIL/ndimage rotation is in mathematical direction: orientation = -(angle + angle0) orientation = 180 - (180 - orientation) % 360 # map to [-179.999,180] region.set_orientation(orientation) if isinstance(region, TextRegionType): region.set_readingDirection({ WritingDirection.LEFT_TO_RIGHT: 'left-to-right', WritingDirection.RIGHT_TO_LEFT: 'right-to-left', WritingDirection.TOP_TO_BOTTOM: 'top-to-bottom' }.get(writing_direction, 'bottom-to-top')) region.set_textLineOrder({ TextlineOrder.LEFT_TO_RIGHT: 'left-to-right', TextlineOrder.RIGHT_TO_LEFT: 'right-to-left', TextlineOrder.TOP_TO_BOTTOM: 'top-to-bottom' }.get(textline_order, 'bottom-to-top')) def _reinit(self, tessapi, segment, mapping): """Reset Tesseract API to initial state, and apply API-level settings for the given segment. If ``xpath_parameters`` is used, try each XPath expression against ``segment``, and in case of a match, apply given parameters, respectively. If ``xpath_model`` is used, try each XPath expression against ``segment``, and in case of a match, load the given language/model, respectively. If ``auto_model`` is used, and no ``xpath_model`` was applied yet, try each given language/model individually on ``segment``, compare their confidences, and load the best-scoring language/model. Before returning, store all previous settings (to catch by the next call). """ # Tesseract API is stateful but does not allow copy constructors # for segment-by-segment configuration we therefore need to # re-initialize the API with the currently loaded settings, # and add some custom choices node = mapping.get(id(segment), None) tag = segment.__class__.__name__[:-4] if hasattr(segment, 'id'): at_ident = 'id' else: at_ident = 'imageFilename' ident = getattr(segment, at_ident) with tessapi: # apply temporary changes if self.parameter['xpath_parameters']: if node is not None and node.attrib.get(at_ident, None) == ident: ns = {'re': 'http://exslt.org/regular-expressions', 'pc': node.nsmap[node.prefix], node.prefix: node.nsmap[node.prefix]} for xpath, params in self.parameter['xpath_parameters'].items(): if node.xpath(xpath, namespaces=ns): self.logger.info("Found '%s' in '%s', setting '%s'", xpath, ident, params) for name, val in params.items(): tessapi.SetVariable(name, val) else: self.logger.error("Cannot find segment '%s' in etree mapping, " \ "ignoring xpath_parameters", ident) if self.parameter['xpath_model']: if node is not None and node.attrib.get(at_ident, None) == ident: ns = {'re': 'http://exslt.org/regular-expressions', 'pc': node.nsmap[node.prefix], node.prefix: node.nsmap[node.prefix]} models = [] for xpath, model in self.parameter['xpath_model'].items(): if node.xpath(xpath, namespaces=ns): self.logger.info("Found '%s' in '%s', reloading with '%s'", xpath, ident, model) models.append(model) if models: model = '+'.join(models) self.logger.debug("Reloading model '%s' for %s '%s'", model, tag, ident) tessapi.Reset(lang=model) return else: self.logger.error("Cannot find segment '%s' in etree mapping, " \ "ignoring xpath_model", ident) if self.parameter['auto_model']: models = self.parameter['model'].split('+') if len(models) > 1: confs = list() for model in models: tessapi.Reset(lang=model) tessapi.Recognize() confs.append(tessapi.MeanTextConf()) model = models[np.argmax(confs)] self.logger.debug("Reloading best model '%s' for %s '%s'", model, tag, ident) tessapi.Reset(lang=model) return if self.parameter['xpath_model'] or self.parameter['auto_model']: # default: undo all settings from previous calls (reset to init-state) tessapi.Reset() def page_element_unicode0(element): """Get Unicode string of the first text result.""" if element.get_TextEquiv(): return element.get_TextEquiv()[0].Unicode or '' else: return '' def page_element_conf0(element): """Get confidence (as float value) of the first text result.""" if element.get_TextEquiv(): # generateDS does not convert simpleType for attributes (yet?) return float(element.get_TextEquiv()[0].conf or "1.0") return 1.0 def page_get_reading_order(ro, rogroup): """Add all elements from the given reading order group to the given dictionary. Given a dict ``ro`` from layout element IDs to ReadingOrder element objects, and an object ``rogroup`` with additional ReadingOrder element objects, add all references to the dict, traversing the group recursively. """ regionrefs = list() if isinstance(rogroup, (OrderedGroupType, OrderedGroupIndexedType)): regionrefs = (rogroup.get_RegionRefIndexed() + rogroup.get_OrderedGroupIndexed() + rogroup.get_UnorderedGroupIndexed()) if isinstance(rogroup, (UnorderedGroupType, UnorderedGroupIndexedType)): regionrefs = (rogroup.get_RegionRef() + rogroup.get_OrderedGroup() + rogroup.get_UnorderedGroup()) for elem in regionrefs: ro[elem.get_regionRef()] = elem if not isinstance(elem, (RegionRefType, RegionRefIndexedType)): page_get_reading_order(ro, elem) def page_update_higher_textequiv_levels(level, pcgts, overwrite=True): """Update the TextEquivs of all PAGE-XML hierarchy levels above ``level`` for consistency. Starting with the lowest hierarchy level chosen for processing, join all first TextEquiv.Unicode (by the rules governing the respective level) into TextEquiv.Unicode of the next higher level, replacing them. If ``overwrite`` is false and the higher level already has text, keep it. When two successive elements appear in a ``Relation`` of type ``join``, then join them directly (without their respective white space). Likewise, average all first TextEquiv.conf into TextEquiv.conf of the next higher level. In the process, traverse the words and lines in their respective ``readingDirection``, the (text) regions which contain lines in their respective ``textLineOrder``, and the (text) regions which contain text regions in their ``ReadingOrder`` (if they appear there as an ``OrderedGroup``). Where no direction/order can be found, use XML ordering. Follow regions recursively, but make sure to traverse them in a depth-first strategy. """ page = pcgts.get_Page() relations = page.get_Relations() # get RelationsType if relations: relations = relations.get_Relation() # get list of RelationType else: relations = [] joins = list() # for relation in relations: if relation.get_type() == 'join': # ignore 'link' type here joins.append((relation.get_SourceRegionRef().get_regionRef(), relation.get_TargetRegionRef().get_regionRef())) reading_order = dict() ro = page.get_ReadingOrder() if ro: page_get_reading_order(reading_order, ro.get_OrderedGroup() or ro.get_UnorderedGroup()) if level != 'region': for region in page.get_AllRegions(classes=['Text']): # order is important here, because regions can be recursive, # and we want to concatenate by depth first; # typical recursion structures would be: # - TextRegion/@type=paragraph inside TextRegion # - TextRegion/@type=drop-capital followed by TextRegion/@type=paragraph inside TextRegion # - any region (including TableRegion or TextRegion) inside a TextRegion/@type=footnote # - TextRegion inside TableRegion subregions = region.get_TextRegion() if subregions: # already visited in earlier iterations # do we have a reading order for these? # TODO: what if at least some of the subregions are in reading_order? if (all(subregion.id in reading_order for subregion in subregions) and isinstance(reading_order[subregions[0].id], # all have .index? (OrderedGroupType, OrderedGroupIndexedType))): subregions = sorted(subregions, key=lambda subregion: reading_order[subregion.id].index) region_unicode = page_element_unicode0(subregions[0]) for subregion, next_subregion in zip(subregions, subregions[1:]): if (subregion.id, next_subregion.id) not in joins: region_unicode += '\n' # or '\f'? region_unicode += page_element_unicode0(next_subregion) region_conf = sum(page_element_conf0(subregion) for subregion in subregions) region_conf /= len(subregions) else: # TODO: what if a TextRegion has both TextLine and TextRegion children? lines = region.get_TextLine() if ((region.get_textLineOrder() or page.get_textLineOrder()) == TextLineOrderSimpleType.BOTTOMTOTOP): lines = list(reversed(lines)) if level != 'line': for line in lines: words = line.get_Word() if ((line.get_readingDirection() or region.get_readingDirection() or page.get_readingDirection()) == ReadingDirectionSimpleType.RIGHTTOLEFT): words = list(reversed(words)) if level != 'word': for word in words: glyphs = word.get_Glyph() if ((word.get_readingDirection() or line.get_readingDirection() or region.get_readingDirection() or page.get_readingDirection()) == ReadingDirectionSimpleType.RIGHTTOLEFT): glyphs = list(reversed(glyphs)) word_unicode = ''.join(page_element_unicode0(glyph) for glyph in glyphs) word_conf = sum(page_element_conf0(glyph) for glyph in glyphs) if glyphs: word_conf /= len(glyphs) if not word.get_TextEquiv() or overwrite: word.set_TextEquiv( # replace old, if any [TextEquivType(Unicode=word_unicode, conf=word_conf)]) line_unicode = ' '.join(page_element_unicode0(word) for word in words) line_conf = sum(page_element_conf0(word) for word in words) if words: line_conf /= len(words) if not line.get_TextEquiv() or overwrite: line.set_TextEquiv( # replace old, if any [TextEquivType(Unicode=line_unicode, conf=line_conf)]) region_unicode = '' region_conf = 0 if lines: region_unicode = page_element_unicode0(lines[0]) for line, next_line in zip(lines, lines[1:]): words = line.get_Word() next_words = next_line.get_Word() if not(words and next_words and (words[-1].id, next_words[0].id) in joins): region_unicode += '\n' region_unicode += page_element_unicode0(next_line) region_conf = sum(page_element_conf0(line) for line in lines) region_conf /= len(lines) if not region.get_TextEquiv() or overwrite: region.set_TextEquiv( # replace old, if any [TextEquivType(Unicode=region_unicode, conf=region_conf)]) def page_shrink_higher_coordinate_levels(maxlevel, minlevel, pcgts): """Project the coordinate hull of all PAGE-XML hierarchy levels above ``minlevel`` up to ``maxlevel``. Starting with the lowest hierarchy level chosen for processing, join all segments into a convex hull for the next higher level, replacing the parent coordinates, respectively. Follow regions recursively, but make sure to traverse them in a depth-first strategy. """ LOG = getLogger('processor.TesserocrRecognize') page = pcgts.get_Page() regions = page.get_AllRegions(classes=['Text']) if minlevel != 'region': for region in regions: lines = region.get_TextLine() if minlevel != 'line': for line in lines: words = line.get_Word() if minlevel != 'word': for word in words: glyphs = word.get_Glyph() if maxlevel in ['region', 'line', 'word', 'glyph'] and glyphs: joint_polygon = join_segments(glyphs) LOG.debug("setting hull for word '%s' from %d vertices", word.id, len(joint_polygon)) word.get_Coords().set_points(points_from_polygon(joint_polygon)) if maxlevel in ['region', 'line', 'word'] and words: joint_polygon = join_segments(words) LOG.debug("setting hull for line '%s' from %d vertices", line.id, len(joint_polygon)) line.get_Coords().set_points(points_from_polygon(joint_polygon)) if maxlevel in ['region', 'line'] and lines: joint_polygon = join_segments(lines) LOG.debug("setting hull for region '%s' from %d vertices", region.id, len(joint_polygon)) region.get_Coords().set_points(points_from_polygon(joint_polygon)) def join_segments(segments): return join_polygons([polygon_from_points(segment.get_Coords().points) for segment in segments]) def join_polygons(polygons, extend=2): # FIXME: construct concave hull / alpha shape jointp = unary_union([make_valid(Polygon(polygon)).buffer(extend) for polygon in polygons]).convex_hull if jointp.minimum_clearance < 1.0: # follow-up calculations will necessarily be integer; # so anticipate rounding here and then ensure validity jointp = asPolygon(np.round(jointp.exterior.coords)) jointp = make_valid(jointp) return jointp.exterior.coords[:-1] def pad_image(image, padding): # TODO: input padding can create extra edges if not binarized; at least try to smooth stat = ImageStat.Stat(image) # workaround for Pillow#4925 if len(stat.bands) > 1: background = tuple(stat.median) else: background = stat.median[0] padded = Image.new(image.mode, (image.width + 2 * padding, image.height + 2 * padding), background) padded.paste(image, (padding, padding)) return padded def polygon_for_parent(polygon, parent): """Clip polygon to parent polygon range. (Should be moved to ocrd_utils.coordinates_for_segment.) """ childp = Polygon(polygon) if isinstance(parent, PageType): if parent.get_Border(): parentp = Polygon(polygon_from_points(parent.get_Border().get_Coords().points)) else: parentp = Polygon([[0, 0], [0, parent.get_imageHeight()], [parent.get_imageWidth(), parent.get_imageHeight()], [parent.get_imageWidth(), 0]]) else: parentp = Polygon(polygon_from_points(parent.get_Coords().points)) # ensure input coords have valid paths (without self-intersection) # (this can happen when shapes valid in floating point are rounded) childp = make_valid(childp) parentp = make_valid(parentp) if not childp.is_valid: return None if not parentp.is_valid: return None # check if clipping is necessary if childp.within(parentp): return childp.exterior.coords[:-1] # clip to parent interp = childp.intersection(parentp) if interp.is_empty or interp.area == 0.0: # this happens if Tesseract "finds" something # outside of the valid Border of a deskewed/cropped page # (empty corners created by masking); will be ignored return None if interp.type == 'GeometryCollection': # heterogeneous result: filter zero-area shapes (LineString, Point) interp = unary_union([geom for geom in interp.geoms if geom.area > 0]) if interp.type == 'MultiPolygon': # homogeneous result: construct convex hull to connect # FIXME: construct concave hull / alpha shape interp = interp.convex_hull if interp.minimum_clearance < 1.0: # follow-up calculations will necessarily be integer; # so anticipate rounding here and then ensure validity interp = asPolygon(np.round(interp.exterior.coords)) interp = make_valid(interp) return interp.exterior.coords[:-1] # keep open def make_valid(polygon): for split in range(1, len(polygon.exterior.coords)-1): if polygon.is_valid or polygon.simplify(polygon.area).is_valid: break # simplification may not be possible (at all) due to ordering # in that case, try another starting point polygon = Polygon(polygon.exterior.coords[-split:]+polygon.exterior.coords[:-split]) for tolerance in range(1, int(polygon.area)): if polygon.is_valid: break # simplification may require a larger tolerance polygon = polygon.simplify(tolerance) return polygon def iterate_level(it, ril, parent=None): LOG = getLogger('processor.TesserocrRecognize') # improves over tesserocr.iterate_level by # honouring multi-level semantics so iterators # can be combined across levels if parent is None: parent = ril - 1 pos = 0 while it and not it.Empty(ril): yield it # With upstream Tesseract, these assertions may fail: # if ril > 0 and it.IsAtFinalElement(parent, ril): # for level in range(parent, ril): # assert it.IsAtFinalElement(parent, level), \ # "level %d iterator at %d is final w.r.t. %d but level %d is not" % ( # ril, pos, parent, level) # Hence the following workaround avails itself: if ril > 0 and all(it.IsAtFinalElement(parent, level) for level in range(parent, ril + 1)): break if not it.Next(ril): break while it.Empty(ril) and not it.Empty(0): # This happens when # - on RIL.PARA, RIL.TEXTLINE and RIL.WORD, # empty non-text (pseudo-) blocks intervene # - on RIL.SYMBOL, a word has no cblobs at all # (because they have all been rejected) # We must _not_ yield these (as they have strange # properties and bboxes). But most importantly, # they will have met IsAtFinalElement prematurely # (hence the similar loop above). # Since this may happen multiple consecutive times, # enclose this in a while loop. LOG.warning("level %d iterator at %d needs to skip empty segment", ril, pos) if not it.Next(ril): break pos += 1
""" Wraps tesserocr.get_languages() with a fixed path parameter. """ return get_languages_(*args, path=get_tessdata_path(), **kwargs)
test_listener.py
import pytest from ...annotations import skip_if_continuous_integration try: from pyglet.media.drivers import pulse has_pulse = True except ImportError: has_pulse = False try: from pyglet.media.drivers import openal has_openal = True except ImportError: has_openal = False try: from pyglet.media.drivers import directsound has_directsound = True except ImportError: has_directsound = False def check_listener_defaults(listener): assert listener.volume == 1.0 assert listener.position == (0, 0, 0) assert listener.forward_orientation == (0, 0, -1) assert listener.up_orientation == (0, 1, 0) def
(listener): listener.volume = 0.5 listener.position = (-1, 0, 0) listener.forward_orientation = (0, 0, 1) listener.up_orientation = (0, -1, 0) assert listener.volume == 0.5 assert listener.position == (-1, 0, 0) assert listener.forward_orientation == (0, 0, 1) assert listener.up_orientation == (0, -1, 0) @pytest.mark.skipif(not has_openal, reason="Test requires OpenAL") def test_openal_listener(): driver = openal.create_audio_driver() listener = driver.get_listener() check_listener_defaults(listener=listener) check_modifying_values(listener=listener) # Need to garbage collect the listener before the driver is deleted del listener @skip_if_continuous_integration() # test user cannot connect to PulseAudio daemon @pytest.mark.skipif(not has_pulse, reason="Test requires PulseAudio") def test_pulse_listener(): driver = pulse.create_audio_driver() listener = driver.get_listener() check_listener_defaults(listener=listener) check_modifying_values(listener=listener) # Need to garbage collect the listener before the driver is deleted del listener @pytest.mark.skipif(not has_directsound, reason="Test requires DirectSound") def test_directsound_listener(): driver = directsound.create_audio_driver() listener = driver.get_listener() check_listener_defaults(listener=listener) check_modifying_values(listener=listener) # Need to garbage collect the listener before the driver is deleted del listener
check_modifying_values
utils.py
from provider.facebook import FacebookProvider providers = { 'facebook': FacebookProvider } def
(provider): if provider in providers: return providers[provider] else: raise NotImplementedError('no provider named "%s"' % provider)
get_provider
iter.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Composable external iterators # The `Iterator` trait This module defines Rust's core iteration trait. The `Iterator` trait has one unimplemented method, `next`. All other methods are derived through default methods to perform operations such as `zip`, `chain`, `enumerate`, and `fold`. The goal of this module is to unify iteration across all containers in Rust. An iterator can be considered as a state machine which is used to track which element will be yielded next. There are various extensions also defined in this module to assist with various types of iteration, such as the `DoubleEndedIterator` for iterating in reverse, the `FromIterator` trait for creating a container from an iterator, and much more. ## Rust's `for` loop The special syntax used by rust's `for` loop is based around the `Iterator` trait defined in this module. For loops can be viewed as a syntactical expansion into a `loop`, for example, the `for` loop in this example is essentially translated to the `loop` below. ```rust let values = vec![1i, 2, 3]; // "Syntactical sugar" taking advantage of an iterator for &x in values.iter() { println!("{}", x); } // Rough translation of the iteration without a `for` iterator. let mut it = values.iter(); loop { match it.next() { Some(&x) => { println!("{}", x); } None => { break } } } ``` This `for` loop syntax can be applied to any iterator over any type. */ use clone::Clone; use cmp; use cmp::{PartialEq, PartialOrd, Ord}; use mem; use num::{Zero, One, CheckedAdd, CheckedSub, Saturating, ToPrimitive, Int}; use ops::{Add, Mul, Sub}; use option::{Option, Some, None}; use uint; /// Conversion from an `Iterator` pub trait FromIterator<A> { /// Build a container with elements from an external iterator. fn from_iter<T: Iterator<A>>(iterator: T) -> Self; } /// A type growable from an `Iterator` implementation pub trait Extendable<A>: FromIterator<A> { /// Extend a container with the elements yielded by an iterator fn extend<T: Iterator<A>>(&mut self, iterator: T); } /// An interface for dealing with "external iterators". These types of iterators /// can be resumed at any time as all state is stored internally as opposed to /// being located on the call stack. /// /// The Iterator protocol states that an iterator yields a (potentially-empty, /// potentially-infinite) sequence of values, and returns `None` to signal that /// it's finished. The Iterator protocol does not define behavior after `None` /// is returned. A concrete Iterator implementation may choose to behave however /// it wishes, either by returning `None` infinitely, or by doing something /// else. #[lang="iterator"] pub trait Iterator<A> { /// Advance the iterator and return the next value. Return `None` when the end is reached. fn next(&mut self) -> Option<A>; /// Returns a lower and upper bound on the remaining length of the iterator. /// /// An upper bound of `None` means either there is no known upper bound, or the upper bound /// does not fit within a `uint`. #[inline] fn size_hint(&self) -> (uint, Option<uint>) { (0, None) } /// Chain this iterator with another, returning a new iterator which will /// finish iterating over the current iterator, and then it will iterate /// over the other specified iterator. /// /// # Example /// /// ```rust /// let a = [0i]; /// let b = [1i]; /// let mut it = a.iter().chain(b.iter()); /// assert_eq!(it.next().unwrap(), &0); /// assert_eq!(it.next().unwrap(), &1); /// assert!(it.next().is_none()); /// ``` #[inline] fn chain<U: Iterator<A>>(self, other: U) -> Chain<Self, U> { Chain{a: self, b: other, flag: false} } /// Creates an iterator which iterates over both this and the specified /// iterators simultaneously, yielding the two elements as pairs. When /// either iterator returns None, all further invocations of next() will /// return None. /// /// # Example /// /// ```rust /// let a = [0i]; /// let b = [1i]; /// let mut it = a.iter().zip(b.iter()); /// let (x0, x1) = (0i, 1i); /// assert_eq!(it.next().unwrap(), (&x0, &x1)); /// assert!(it.next().is_none()); /// ``` #[inline] fn zip<B, U: Iterator<B>>(self, other: U) -> Zip<Self, U> { Zip{a: self, b: other} } /// Creates a new iterator which will apply the specified function to each /// element returned by the first, yielding the mapped element instead. /// /// # Example /// /// ```rust /// let a = [1i, 2]; /// let mut it = a.iter().map(|&x| 2 * x); /// assert_eq!(it.next().unwrap(), 2); /// assert_eq!(it.next().unwrap(), 4); /// assert!(it.next().is_none()); /// ``` #[inline] fn map<'r, B>(self, f: |A|: 'r -> B) -> Map<'r, A, B, Self> { Map{iter: self, f: f} } /// Creates an iterator which applies the predicate to each element returned /// by this iterator. Only elements which have the predicate evaluate to /// `true` will be yielded. /// /// # Example /// /// ```rust /// let a = [1i, 2]; /// let mut it = a.iter().filter(|&x| *x > 1); /// assert_eq!(it.next().unwrap(), &2); /// assert!(it.next().is_none()); /// ``` #[inline] fn filter<'r>(self, predicate: |&A|: 'r -> bool) -> Filter<'r, A, Self> { Filter{iter: self, predicate: predicate} } /// Creates an iterator which both filters and maps elements. /// If the specified function returns None, the element is skipped. /// Otherwise the option is unwrapped and the new value is yielded. /// /// # Example /// /// ```rust /// let a = [1i, 2]; /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None}); /// assert_eq!(it.next().unwrap(), 4); /// assert!(it.next().is_none()); /// ``` #[inline] fn filter_map<'r, B>(self, f: |A|: 'r -> Option<B>) -> FilterMap<'r, A, B, Self> { FilterMap { iter: self, f: f } } /// Creates an iterator which yields a pair of the value returned by this /// iterator plus the current index of iteration. /// /// # Example /// /// ```rust /// let a = [100i, 200]; /// let mut it = a.iter().enumerate(); /// let (x100, x200) = (100i, 200i); /// assert_eq!(it.next().unwrap(), (0, &x100)); /// assert_eq!(it.next().unwrap(), (1, &x200)); /// assert!(it.next().is_none()); /// ``` #[inline] fn enumerate(self) -> Enumerate<Self> { Enumerate{iter: self, count: 0} } /// Creates an iterator that has a `.peek()` method /// that returns an optional reference to the next element. /// /// # Example /// /// ```rust /// let xs = [100i, 200, 300]; /// let mut it = xs.iter().map(|x| *x).peekable(); /// assert_eq!(*it.peek().unwrap(), 100); /// assert_eq!(it.next().unwrap(), 100); /// assert_eq!(it.next().unwrap(), 200); /// assert_eq!(*it.peek().unwrap(), 300); /// assert_eq!(*it.peek().unwrap(), 300); /// assert_eq!(it.next().unwrap(), 300); /// assert!(it.peek().is_none()); /// assert!(it.next().is_none()); /// ``` #[inline] fn peekable(self) -> Peekable<A, Self> { Peekable{iter: self, peeked: None} } /// Creates an iterator which invokes the predicate on elements until it /// returns false. Once the predicate returns false, all further elements are /// yielded. /// /// # Example /// /// ```rust /// let a = [1i, 2, 3, 2, 1]; /// let mut it = a.iter().skip_while(|&a| *a < 3); /// assert_eq!(it.next().unwrap(), &3); /// assert_eq!(it.next().unwrap(), &2); /// assert_eq!(it.next().unwrap(), &1); /// assert!(it.next().is_none()); /// ``` #[inline] fn skip_while<'r>(self, predicate: |&A|: 'r -> bool) -> SkipWhile<'r, A, Self> { SkipWhile{iter: self, flag: false, predicate: predicate} } /// Creates an iterator which yields elements so long as the predicate /// returns true. After the predicate returns false for the first time, no /// further elements will be yielded. /// /// # Example /// /// ```rust /// let a = [1i, 2, 3, 2, 1]; /// let mut it = a.iter().take_while(|&a| *a < 3); /// assert_eq!(it.next().unwrap(), &1); /// assert_eq!(it.next().unwrap(), &2); /// assert!(it.next().is_none()); /// ``` #[inline] fn take_while<'r>(self, predicate: |&A|: 'r -> bool) -> TakeWhile<'r, A, Self> { TakeWhile{iter: self, flag: false, predicate: predicate} } /// Creates an iterator which skips the first `n` elements of this iterator, /// and then it yields all further items. /// /// # Example /// /// ```rust /// let a = [1i, 2, 3, 4, 5]; /// let mut it = a.iter().skip(3); /// assert_eq!(it.next().unwrap(), &4); /// assert_eq!(it.next().unwrap(), &5); /// assert!(it.next().is_none()); /// ``` #[inline] fn skip(self, n: uint) -> Skip<Self> { Skip{iter: self, n: n} } /// Creates an iterator which yields the first `n` elements of this /// iterator, and then it will always return None. /// /// # Example /// /// ```rust /// let a = [1i, 2, 3, 4, 5]; /// let mut it = a.iter().take(3); /// assert_eq!(it.next().unwrap(), &1); /// assert_eq!(it.next().unwrap(), &2); /// assert_eq!(it.next().unwrap(), &3); /// assert!(it.next().is_none()); /// ``` #[inline] fn take(self, n: uint) -> Take<Self> { Take{iter: self, n: n} } /// Creates a new iterator which behaves in a similar fashion to fold. /// There is a state which is passed between each iteration and can be /// mutated as necessary. The yielded values from the closure are yielded /// from the Scan instance when not None. /// /// # Example /// /// ```rust /// let a = [1i, 2, 3, 4, 5]; /// let mut it = a.iter().scan(1, |fac, &x| { /// *fac = *fac * x; /// Some(*fac) /// }); /// assert_eq!(it.next().unwrap(), 1); /// assert_eq!(it.next().unwrap(), 2); /// assert_eq!(it.next().unwrap(), 6); /// assert_eq!(it.next().unwrap(), 24); /// assert_eq!(it.next().unwrap(), 120); /// assert!(it.next().is_none()); /// ``` #[inline] fn scan<'r, St, B>(self, initial_state: St, f: |&mut St, A|: 'r -> Option<B>) -> Scan<'r, A, B, Self, St> { Scan{iter: self, f: f, state: initial_state} } /// Creates an iterator that maps each element to an iterator, /// and yields the elements of the produced iterators /// /// # Example /// /// ```rust /// use std::iter::count; /// /// let xs = [2u, 3]; /// let ys = [0u, 1, 0, 1, 2]; /// let mut it = xs.iter().flat_map(|&x| count(0u, 1).take(x)); /// // Check that `it` has the same elements as `ys` /// let mut i = 0; /// for x in it { /// assert_eq!(x, ys[i]); /// i += 1; /// } /// ``` #[inline] fn flat_map<'r, B, U: Iterator<B>>(self, f: |A|: 'r -> U) -> FlatMap<'r, A, Self, U> { FlatMap{iter: self, f: f, frontiter: None, backiter: None } } /// Creates an iterator that yields `None` forever after the underlying /// iterator yields `None`. Random-access iterator behavior is not /// affected, only single and double-ended iterator behavior. /// /// # Example /// /// ```rust /// fn process<U: Iterator<int>>(it: U) -> int { /// let mut it = it.fuse(); /// let mut sum = 0; /// for x in it { /// if x > 5 { /// continue; /// } /// sum += x; /// } /// // did we exhaust the iterator? /// if it.next().is_none() { /// sum += 1000; /// } /// sum /// } /// let x = vec![1i,2,3,7,8,9]; /// assert_eq!(process(x.into_iter()), 1006); /// ``` #[inline] fn fuse(self) -> Fuse<Self> { Fuse{iter: self, done: false} } /// Creates an iterator that calls a function with a reference to each /// element before yielding it. This is often useful for debugging an /// iterator pipeline. /// /// # Example /// /// ```rust /// use std::iter::AdditiveIterator; /// /// let xs = [1u, 4, 2, 3, 8, 9, 6]; /// let sum = xs.iter() /// .map(|&x| x) /// .inspect(|&x| println!("filtering {}", x)) /// .filter(|&x| x % 2 == 0) /// .inspect(|&x| println!("{} made it through", x)) /// .sum(); /// println!("{}", sum); /// ``` #[inline] fn inspect<'r>(self, f: |&A|: 'r) -> Inspect<'r, A, Self> { Inspect{iter: self, f: f} } /// Creates a wrapper around a mutable reference to the iterator. /// /// This is useful to allow applying iterator adaptors while still /// retaining ownership of the original iterator value. /// /// # Example /// /// ```rust /// let mut xs = range(0u, 10); /// // sum the first five values /// let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b); /// assert!(partial_sum == 10); /// // xs.next() is now `5` /// assert!(xs.next() == Some(5)); /// ``` fn by_ref<'r>(&'r mut self) -> ByRef<'r, Self> { ByRef{iter: self} } /// Apply a function to each element, or stop iterating if the /// function returns `false`. /// /// # Example /// /// ```rust,ignore /// range(0u, 5).advance(|x| {print!("{} ", x); true}); /// ``` #[deprecated = "use the `all` method instead"] #[inline] fn advance(&mut self, f: |A| -> bool) -> bool { loop { match self.next() { Some(x) => { if !f(x) { return false; } } None => { return true; } } } } /// Loops through the entire iterator, collecting all of the elements into /// a container implementing `FromIterator`. /// /// # Example /// /// ```rust /// let a = [1i, 2, 3, 4, 5]; /// let b: Vec<int> = a.iter().map(|&x| x).collect(); /// assert!(a.as_slice() == b.as_slice()); /// ``` #[inline] fn collect<B: FromIterator<A>>(&mut self) -> B { FromIterator::from_iter(self.by_ref()) } /// Loops through `n` iterations, returning the `n`th element of the /// iterator. /// /// # Example /// /// ```rust /// let a = [1i, 2, 3, 4, 5]; /// let mut it = a.iter(); /// assert!(it.nth(2).unwrap() == &3); /// assert!(it.nth(2) == None); /// ``` #[inline] fn nth(&mut self, mut n: uint) -> Option<A> { for x in *self { if n == 0 { return Some(x) } n -= 1; } None } /// Loops through the entire iterator, returning the last element of the /// iterator. /// /// # Example /// /// ```rust /// let a = [1i, 2, 3, 4, 5]; /// assert!(a.iter().last().unwrap() == &5); /// ``` #[inline] fn last(&mut self) -> Option<A> { let mut last = None; for x in *self { last = Some(x); } last } /// Performs a fold operation over the entire iterator, returning the /// eventual state at the end of the iteration. /// /// # Example /// /// ```rust /// let a = [1i, 2, 3, 4, 5]; /// assert!(a.iter().fold(0, |a, &b| a + b) == 15); /// ``` #[inline] fn fold<B>(&mut self, init: B, f: |B, A| -> B) -> B { let mut accum = init; for x in *self { accum = f(accum, x); } accum } /// Counts the number of elements in this iterator. /// /// # Example /// /// ```rust /// let a = [1i, 2, 3, 4, 5]; /// let mut it = a.iter(); /// assert!(it.count() == 5); /// assert!(it.count() == 0); /// ``` #[inline] fn count(&mut self) -> uint { self.fold(0, |cnt, _x| cnt + 1) } /// Tests whether the predicate holds true for all elements in the iterator. /// /// # Example /// /// ```rust /// let a = [1i, 2, 3, 4, 5]; /// assert!(a.iter().all(|x| *x > 0)); /// assert!(!a.iter().all(|x| *x > 2)); /// ``` #[inline] fn all(&mut self, f: |A| -> bool) -> bool { for x in *self { if !f(x) { return false; } } true } /// Tests whether any element of an iterator satisfies the specified /// predicate. /// /// # Example /// /// ```rust /// let a = [1i, 2, 3, 4, 5]; /// let mut it = a.iter(); /// assert!(it.any(|x| *x == 3)); /// assert!(!it.any(|x| *x == 3)); /// ``` #[inline] fn any(&mut self, f: |A| -> bool) -> bool { for x in *self { if f(x) { return true; } } false } /// Return the first element satisfying the specified predicate #[inline] fn find(&mut self, predicate: |&A| -> bool) -> Option<A> { for x in *self { if predicate(&x) { return Some(x) } } None } /// Return the index of the first element satisfying the specified predicate #[inline] fn position(&mut self, predicate: |A| -> bool) -> Option<uint> { let mut i = 0; for x in *self { if predicate(x) { return Some(i); } i += 1; } None } /// Return the element that gives the maximum value from the /// specified function. /// /// # Example /// /// ```rust /// let xs = [-3i, 0, 1, 5, -10]; /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10); /// ``` #[inline] fn max_by<B: Ord>(&mut self, f: |&A| -> B) -> Option<A> { self.fold(None, |max: Option<(A, B)>, x| { let x_val = f(&x); match max { None => Some((x, x_val)), Some((y, y_val)) => if x_val > y_val { Some((x, x_val)) } else { Some((y, y_val)) } } }).map(|(x, _)| x) } /// Return the element that gives the minimum value from the /// specified function. /// /// # Example /// /// ```rust /// let xs = [-3i, 0, 1, 5, -10]; /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0); /// ``` #[inline] fn min_by<B: Ord>(&mut self, f: |&A| -> B) -> Option<A> { self.fold(None, |min: Option<(A, B)>, x| { let x_val = f(&x); match min { None => Some((x, x_val)), Some((y, y_val)) => if x_val < y_val { Some((x, x_val)) } else { Some((y, y_val)) } } }).map(|(x, _)| x) } } /// A range iterator able to yield elements from both ends /// /// A `DoubleEndedIterator` can be thought of as a deque in that `next()` and `next_back()` exhaust /// elements from the *same* range, and do not work independently of each other. pub trait DoubleEndedIterator<A>: Iterator<A> { /// Yield an element from the end of the range, returning `None` if the range is empty. fn next_back(&mut self) -> Option<A>; /// Change the direction of the iterator /// /// The flipped iterator swaps the ends on an iterator that can already /// be iterated from the front and from the back. /// /// /// If the iterator also implements RandomAccessIterator, the flipped /// iterator is also random access, with the indices starting at the back /// of the original iterator. /// /// Note: Random access with flipped indices still only applies to the first /// `uint::MAX` elements of the original iterator. #[inline] fn rev(self) -> Rev<Self> { Rev{iter: self} } } /// A double-ended iterator yielding mutable references pub trait MutableDoubleEndedIterator { // FIXME: #5898: should be called `reverse` /// Use an iterator to reverse a container in-place fn reverse_(&mut self); } impl<'a, A:'a, T: DoubleEndedIterator<&'a mut A>> MutableDoubleEndedIterator for T { // FIXME: #5898: should be called `reverse` /// Use an iterator to reverse a container in-place fn reverse_(&mut self) { loop { match (self.next(), self.next_back()) { (Some(x), Some(y)) => mem::swap(x, y), _ => break } } } } /// An object implementing random access indexing by `uint` /// /// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`. /// Calling `next()` or `next_back()` on a `RandomAccessIterator` /// reduces the indexable range accordingly. That is, `it.idx(1)` will become `it.idx(0)` /// after `it.next()` is called. pub trait RandomAccessIterator<A>: Iterator<A> { /// Return the number of indexable elements. At most `std::uint::MAX` /// elements are indexable, even if the iterator represents a longer range. fn indexable(&self) -> uint; /// Return an element at an index, or `None` if the index is out of bounds fn idx(&mut self, index: uint) -> Option<A>; } /// An iterator that knows its exact length /// /// This trait is a helper for iterators like the vector iterator, so that /// it can support double-ended enumeration. /// /// `Iterator::size_hint` *must* return the exact size of the iterator. /// Note that the size must fit in `uint`. pub trait ExactSize<A> : DoubleEndedIterator<A> { /// Return the index of the last element satisfying the specified predicate /// /// If no element matches, None is returned. #[inline] fn rposition(&mut self, predicate: |A| -> bool) -> Option<uint> { let len = self.len(); for i in range(0, len).rev() { if predicate(self.next_back().expect("rposition: incorrect ExactSize")) { return Some(i); } } None } #[inline] /// Return the exact length of the iterator. fn len(&self) -> uint { let (lower, upper) = self.size_hint(); // Note: This assertion is overly defensive, but it checks the invariant // guaranteed by the trait. If this trait were rust-internal, // we could use debug_assert!; assert_eq! will check all Rust user // implementations too. assert_eq!(upper, Some(lower)); lower } } // All adaptors that preserve the size of the wrapped iterator are fine // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`. impl<A, T: ExactSize<A>> ExactSize<(uint, A)> for Enumerate<T> {} impl<'a, A, T: ExactSize<A>> ExactSize<A> for Inspect<'a, A, T> {} impl<A, T: ExactSize<A>> ExactSize<A> for Rev<T> {} impl<'a, A, B, T: ExactSize<A>> ExactSize<B> for Map<'a, A, B, T> {} impl<A, B, T: ExactSize<A>, U: ExactSize<B>> ExactSize<(A, B)> for Zip<T, U> {} /// An double-ended iterator with the direction inverted #[deriving(Clone)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Rev<T> { iter: T } impl<A, T: DoubleEndedIterator<A>> Iterator<A> for Rev<T> { #[inline] fn next(&mut self) -> Option<A> { self.iter.next_back() } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() } } impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Rev<T> { #[inline] fn next_back(&mut self) -> Option<A> { self.iter.next() } } impl<A, T: DoubleEndedIterator<A> + RandomAccessIterator<A>> RandomAccessIterator<A> for Rev<T> { #[inline] fn indexable(&self) -> uint { self.iter.indexable() } #[inline] fn idx(&mut self, index: uint) -> Option<A> { let amt = self.indexable(); self.iter.idx(amt - index - 1) } } /// A mutable reference to an iterator #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct ByRef<'a, T:'a> { iter: &'a mut T } impl<'a, A, T: Iterator<A>+'a> Iterator<A> for ByRef<'a, T> { #[inline] fn next(&mut self) -> Option<A> { self.iter.next() } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() } } impl<'a, A, T: DoubleEndedIterator<A>+'a> DoubleEndedIterator<A> for ByRef<'a, T> { #[inline] fn next_back(&mut self) -> Option<A> { self.iter.next_back() } } /// A trait for iterators over elements which can be added together pub trait AdditiveIterator<A> { /// Iterates over the entire iterator, summing up all the elements /// /// # Example /// /// ```rust /// use std::iter::AdditiveIterator; /// /// let a = [1i, 2, 3, 4, 5]; /// let mut it = a.iter().map(|&x| x); /// assert!(it.sum() == 15); /// ``` fn sum(&mut self) -> A; } impl<A: Add<A, A> + Zero, T: Iterator<A>> AdditiveIterator<A> for T { #[inline] fn sum(&mut self) -> A { let zero: A = Zero::zero(); self.fold(zero, |s, x| s + x) } } /// A trait for iterators over elements which can be multiplied together. pub trait MultiplicativeIterator<A> { /// Iterates over the entire iterator, multiplying all the elements /// /// # Example /// /// ```rust /// use std::iter::{count, MultiplicativeIterator}; /// /// fn factorial(n: uint) -> uint { /// count(1u, 1).take_while(|&i| i <= n).product() /// } /// assert!(factorial(0) == 1); /// assert!(factorial(1) == 1); /// assert!(factorial(5) == 120); /// ``` fn product(&mut self) -> A; } impl<A: Mul<A, A> + One, T: Iterator<A>> MultiplicativeIterator<A> for T { #[inline] fn product(&mut self) -> A { let one: A = One::one(); self.fold(one, |p, x| p * x) } } /// A trait for iterators over elements which can be compared to one another. pub trait OrdIterator<A> { /// Consumes the entire iterator to return the maximum element. /// /// # Example /// /// ```rust /// let a = [1i, 2, 3, 4, 5]; /// assert!(a.iter().max().unwrap() == &5); /// ``` fn max(&mut self) -> Option<A>; /// Consumes the entire iterator to return the minimum element. /// /// # Example /// /// ```rust /// let a = [1i, 2, 3, 4, 5]; /// assert!(a.iter().min().unwrap() == &1); /// ``` fn min(&mut self) -> Option<A>; /// `min_max` finds the minimum and maximum elements in the iterator. /// /// The return type `MinMaxResult` is an enum of three variants: /// /// - `NoElements` if the iterator is empty. /// - `OneElement(x)` if the iterator has exactly one element. /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two /// values are equal if and only if there is more than one /// element in the iterator and all elements are equal. /// /// On an iterator of length `n`, `min_max` does `1.5 * n` comparisons, /// and so faster than calling `min` and `max separately which does `2 * n` comparisons. /// /// # Example /// /// ```rust /// use std::iter::{NoElements, OneElement, MinMax}; /// /// let v: [int, ..0] = []; /// assert_eq!(v.iter().min_max(), NoElements); /// /// let v = [1i]; /// assert!(v.iter().min_max() == OneElement(&1)); /// /// let v = [1i, 2, 3, 4, 5]; /// assert!(v.iter().min_max() == MinMax(&1, &5)); /// /// let v = [1i, 2, 3, 4, 5, 6]; /// assert!(v.iter().min_max() == MinMax(&1, &6)); /// /// let v = [1i, 1, 1, 1]; /// assert!(v.iter().min_max() == MinMax(&1, &1)); /// ``` fn min_max(&mut self) -> MinMaxResult<A>; } impl<A: Ord, T: Iterator<A>> OrdIterator<A> for T { #[inline] fn max(&mut self) -> Option<A> { self.fold(None, |max, x| { match max { None => Some(x), Some(y) => Some(cmp::max(x, y)) } }) } #[inline] fn min(&mut self) -> Option<A> { self.fold(None, |min, x| { match min { None => Some(x), Some(y) => Some(cmp::min(x, y)) } }) } fn min_max(&mut self) -> MinMaxResult<A> { let (mut min, mut max) = match self.next() { None => return NoElements, Some(x) => { match self.next() { None => return OneElement(x), Some(y) => if x < y {(x, y)} else {(y,x)} } } }; loop { // `first` and `second` are the two next elements we want to look at. // We first compare `first` and `second` (#1). The smaller one is then compared to // current minimum (#2). The larger one is compared to current maximum (#3). This // way we do 3 comparisons for 2 elements. let first = match self.next() { None => break, Some(x) => x }; let second = match self.next() { None => { if first < min { min = first; } else if first > max { max = first; } break; } Some(x) => x }; if first < second { if first < min {min = first;} if max < second {max = second;} } else { if second < min {min = second;} if max < first {max = first;} } } MinMax(min, max) } } /// `MinMaxResult` is an enum returned by `min_max`. See `OrdIterator::min_max` for more detail. #[deriving(Clone, PartialEq, Show)] pub enum MinMaxResult<T> { /// Empty iterator NoElements, /// Iterator with one element, so the minimum and maximum are the same OneElement(T), /// More than one element in the iterator, the first element is not larger than the second MinMax(T, T) } impl<T: Clone> MinMaxResult<T> { /// `into_option` creates an `Option` of type `(T,T)`. The returned `Option` has variant /// `None` if and only if the `MinMaxResult` has variant `NoElements`. Otherwise variant /// `Some(x,y)` is returned where `x <= y`. If `MinMaxResult` has variant `OneElement(x)`, /// performing this operation will make one clone of `x`. /// /// # Example /// /// ```rust /// use std::iter::{NoElements, OneElement, MinMax, MinMaxResult}; /// /// let r: MinMaxResult<int> = NoElements; /// assert_eq!(r.into_option(), None) /// /// let r = OneElement(1i); /// assert_eq!(r.into_option(), Some((1,1))); /// /// let r = MinMax(1i,2i); /// assert_eq!(r.into_option(), Some((1,2))); /// ``` pub fn into_option(self) -> Option<(T,T)> { match self { NoElements => None, OneElement(x) => Some((x.clone(), x)), MinMax(x, y) => Some((x, y)) } } } /// A trait for iterators that are cloneable. pub trait CloneableIterator { /// Repeats an iterator endlessly /// /// # Example /// /// ```rust /// use std::iter::{CloneableIterator, count}; /// /// let a = count(1i,1i).take(1); /// let mut cy = a.cycle(); /// assert_eq!(cy.next(), Some(1)); /// assert_eq!(cy.next(), Some(1)); /// ``` fn cycle(self) -> Cycle<Self>; } impl<A, T: Clone + Iterator<A>> CloneableIterator for T { #[inline] fn cycle(self) -> Cycle<T> { Cycle{orig: self.clone(), iter: self} } } /// An iterator that repeats endlessly #[deriving(Clone)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Cycle<T> { orig: T, iter: T, } impl<A, T: Clone + Iterator<A>> Iterator<A> for Cycle<T> { #[inline] fn next(&mut self) -> Option<A> { match self.iter.next() { None => { self.iter = self.orig.clone(); self.iter.next() } y => y } } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { // the cycle iterator is either empty or infinite match self.orig.size_hint() { sz @ (0, Some(0)) => sz, (0, _) => (0, None), _ => (uint::MAX, None) } } } impl<A, T: Clone + RandomAccessIterator<A>> RandomAccessIterator<A> for Cycle<T> { #[inline] fn indexable(&self) -> uint { if self.orig.indexable() > 0 { uint::MAX } else { 0 } } #[inline] fn idx(&mut self, index: uint) -> Option<A> { let liter = self.iter.indexable(); let lorig = self.orig.indexable(); if lorig == 0 { None } else if index < liter { self.iter.idx(index) } else { self.orig.idx((index - liter) % lorig) } } } /// An iterator which strings two iterators together #[deriving(Clone)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Chain<T, U> { a: T, b: U, flag: bool, } impl<A, T: Iterator<A>, U: Iterator<A>> Iterator<A> for Chain<T, U> { #[inline] fn next(&mut self) -> Option<A> { if self.flag { self.b.next() } else { match self.a.next() { Some(x) => return Some(x), _ => () } self.flag = true; self.b.next() } } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { let (a_lower, a_upper) = self.a.size_hint(); let (b_lower, b_upper) = self.b.size_hint(); let lower = a_lower.saturating_add(b_lower); let upper = match (a_upper, b_upper) { (Some(x), Some(y)) => x.checked_add(&y), _ => None }; (lower, upper) } } impl<A, T: DoubleEndedIterator<A>, U: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Chain<T, U> { #[inline] fn next_back(&mut self) -> Option<A> { match self.b.next_back() { Some(x) => Some(x), None => self.a.next_back() } } } impl<A, T: RandomAccessIterator<A>, U: RandomAccessIterator<A>> RandomAccessIterator<A> for Chain<T, U> { #[inline] fn indexable(&self) -> uint { let (a, b) = (self.a.indexable(), self.b.indexable()); a.saturating_add(b) } #[inline] fn idx(&mut self, index: uint) -> Option<A> { let len = self.a.indexable(); if index < len { self.a.idx(index) } else { self.b.idx(index - len) } } } /// An iterator which iterates two other iterators simultaneously #[deriving(Clone)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Zip<T, U> { a: T, b: U } impl<A, B, T: Iterator<A>, U: Iterator<B>> Iterator<(A, B)> for Zip<T, U> { #[inline] fn next(&mut self) -> Option<(A, B)> { match self.a.next() { None => None, Some(x) => match self.b.next() { None => None, Some(y) => Some((x, y)) } } } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { let (a_lower, a_upper) = self.a.size_hint(); let (b_lower, b_upper) = self.b.size_hint(); let lower = cmp::min(a_lower, b_lower); let upper = match (a_upper, b_upper) { (Some(x), Some(y)) => Some(cmp::min(x,y)), (Some(x), None) => Some(x), (None, Some(y)) => Some(y), (None, None) => None }; (lower, upper) } } impl<A, B, T: ExactSize<A>, U: ExactSize<B>> DoubleEndedIterator<(A, B)> for Zip<T, U> { #[inline] fn next_back(&mut self) -> Option<(A, B)> { let a_sz = self.a.len(); let b_sz = self.b.len(); if a_sz != b_sz { // Adjust a, b to equal length if a_sz > b_sz { for _ in range(0, a_sz - b_sz) { self.a.next_back(); } } else { for _ in range(0, b_sz - a_sz) { self.b.next_back(); } } } match (self.a.next_back(), self.b.next_back()) { (Some(x), Some(y)) => Some((x, y)), (None, None) => None, _ => unreachable!(), } } } impl<A, B, T: RandomAccessIterator<A>, U: RandomAccessIterator<B>> RandomAccessIterator<(A, B)> for Zip<T, U> { #[inline] fn indexable(&self) -> uint { cmp::min(self.a.indexable(), self.b.indexable()) } #[inline] fn idx(&mut self, index: uint) -> Option<(A, B)> { match self.a.idx(index) { None => None, Some(x) => match self.b.idx(index) { None => None, Some(y) => Some((x, y)) } } } } /// An iterator which maps the values of `iter` with `f` #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Map<'a, A, B, T> { iter: T, f: |A|: 'a -> B } impl<'a, A, B, T> Map<'a, A, B, T> { #[inline] fn do_map(&mut self, elt: Option<A>) -> Option<B> { match elt { Some(a) => Some((self.f)(a)), _ => None } } } impl<'a, A, B, T: Iterator<A>> Iterator<B> for Map<'a, A, B, T> { #[inline] fn next(&mut self) -> Option<B> { let next = self.iter.next(); self.do_map(next) } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() } } impl<'a, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B> for Map<'a, A, B, T> { #[inline] fn next_back(&mut self) -> Option<B> { let next = self.iter.next_back(); self.do_map(next) } } impl<'a, A, B, T: RandomAccessIterator<A>> RandomAccessIterator<B> for Map<'a, A, B, T> { #[inline] fn indexable(&self) -> uint { self.iter.indexable() } #[inline] fn idx(&mut self, index: uint) -> Option<B> { let elt = self.iter.idx(index); self.do_map(elt) } } /// An iterator which filters the elements of `iter` with `predicate` #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Filter<'a, A, T> { iter: T, predicate: |&A|: 'a -> bool } impl<'a, A, T: Iterator<A>> Iterator<A> for Filter<'a, A, T> { #[inline] fn next(&mut self) -> Option<A> { for x in self.iter { if (self.predicate)(&x) { return Some(x); } else { continue } } None } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { let (_, upper) = self.iter.size_hint(); (0, upper) // can't know a lower bound, due to the predicate } } impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Filter<'a, A, T> { #[inline] fn next_back(&mut self) -> Option<A> { for x in self.iter.by_ref().rev() { if (self.predicate)(&x) { return Some(x); } } None } } /// An iterator which uses `f` to both filter and map elements from `iter` #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct FilterMap<'a, A, B, T> { iter: T, f: |A|: 'a -> Option<B> } impl<'a, A, B, T: Iterator<A>> Iterator<B> for FilterMap<'a, A, B, T> { #[inline] fn next(&mut self) -> Option<B> { for x in self.iter { match (self.f)(x) { Some(y) => return Some(y), None => () } } None } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { let (_, upper) = self.iter.size_hint(); (0, upper) // can't know a lower bound, due to the predicate } } impl<'a, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B> for FilterMap<'a, A, B, T> { #[inline] fn next_back(&mut self) -> Option<B> { for x in self.iter.by_ref().rev() { match (self.f)(x) { Some(y) => return Some(y), None => () } } None } } /// An iterator which yields the current count and the element during iteration #[deriving(Clone)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Enumerate<T> { iter: T, count: uint } impl<A, T: Iterator<A>> Iterator<(uint, A)> for Enumerate<T> { #[inline] fn next(&mut self) -> Option<(uint, A)> { match self.iter.next() { Some(a) => { let ret = Some((self.count, a)); self.count += 1; ret } _ => None } } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() } } impl<A, T: ExactSize<A>> DoubleEndedIterator<(uint, A)> for Enumerate<T> { #[inline] fn next_back(&mut self) -> Option<(uint, A)> { match self.iter.next_back() { Some(a) => { let len = self.iter.len(); Some((self.count + len, a)) } _ => None } } } impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<(uint, A)> for Enumerate<T> { #[inline] fn indexable(&self) -> uint { self.iter.indexable() } #[inline] fn idx(&mut self, index: uint) -> Option<(uint, A)> { match self.iter.idx(index) { Some(a) => Some((self.count + index, a)), _ => None, } } } /// An iterator with a `peek()` that returns an optional reference to the next element. #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Peekable<A, T> { iter: T, peeked: Option<A>, } impl<A, T: Iterator<A>> Iterator<A> for Peekable<A, T> { #[inline] fn next(&mut self) -> Option<A> { if self.peeked.is_some() { self.peeked.take() } else { self.iter.next() } } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { let (lo, hi) = self.iter.size_hint(); if self.peeked.is_some() { let lo = lo.saturating_add(1); let hi = match hi { Some(x) => x.checked_add(&1), None => None }; (lo, hi) } else { (lo, hi) } } } impl<'a, A, T: Iterator<A>> Peekable<A, T> { /// Return a reference to the next element of the iterator with out advancing it, /// or None if the iterator is exhausted. #[inline] pub fn peek(&'a mut self) -> Option<&'a A> { if self.peeked.is_none() { self.peeked = self.iter.next(); } match self.peeked { Some(ref value) => Some(value), None => None, } } /// Check whether peekable iterator is empty or not. #[inline] pub fn is_empty(&mut self) -> bool { self.peek().is_none() } } /// An iterator which rejects elements while `predicate` is true #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct SkipWhile<'a, A, T> { iter: T, flag: bool, predicate: |&A|: 'a -> bool } impl<'a, A, T: Iterator<A>> Iterator<A> for SkipWhile<'a, A, T> { #[inline] fn next(&mut self) -> Option<A> { for x in self.iter { if self.flag || !(self.predicate)(&x) { self.flag = true; return Some(x); } } None } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { let (_, upper) = self.iter.size_hint(); (0, upper) // can't know a lower bound, due to the predicate } } /// An iterator which only accepts elements while `predicate` is true #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct TakeWhile<'a, A, T> { iter: T, flag: bool, predicate: |&A|: 'a -> bool } impl<'a, A, T: Iterator<A>> Iterator<A> for TakeWhile<'a, A, T> { #[inline] fn next(&mut self) -> Option<A> { if self.flag { None } else { match self.iter.next() { Some(x) => { if (self.predicate)(&x) { Some(x) } else { self.flag = true; None } } None => None } } } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { let (_, upper) = self.iter.size_hint(); (0, upper) // can't know a lower bound, due to the predicate } } /// An iterator which skips over `n` elements of `iter`. #[deriving(Clone)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Skip<T> { iter: T, n: uint } impl<A, T: Iterator<A>> Iterator<A> for Skip<T> { #[inline] fn next(&mut self) -> Option<A> { let mut next = self.iter.next(); if self.n == 0 { next } else { let mut n = self.n; while n > 0 { n -= 1; match next { Some(_) => { next = self.iter.next(); continue } None => { self.n = 0; return None } } } self.n = 0; next } } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { let (lower, upper) = self.iter.size_hint(); let lower = lower.saturating_sub(self.n); let upper = match upper { Some(x) => Some(x.saturating_sub(self.n)), None => None }; (lower, upper) } } impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Skip<T> { #[inline] fn indexable(&self) -> uint { self.iter.indexable().saturating_sub(self.n) } #[inline] fn idx(&mut self, index: uint) -> Option<A> { if index >= self.indexable() { None } else { self.iter.idx(index + self.n) } } } /// An iterator which only iterates over the first `n` iterations of `iter`. #[deriving(Clone)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Take<T> { iter: T, n: uint } impl<A, T: Iterator<A>> Iterator<A> for Take<T> { #[inline] fn next(&mut self) -> Option<A> { if self.n != 0 { self.n -= 1; self.iter.next() } else { None } } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { let (lower, upper) = self.iter.size_hint(); let lower = cmp::min(lower, self.n); let upper = match upper { Some(x) if x < self.n => Some(x), _ => Some(self.n) }; (lower, upper) } } impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Take<T> { #[inline] fn indexable(&self) -> uint { cmp::min(self.iter.indexable(), self.n) } #[inline] fn idx(&mut self, index: uint) -> Option<A> { if index >= self.n { None } else { self.iter.idx(index) } } } /// An iterator to maintain state while iterating another iterator #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Scan<'a, A, B, T, St> { iter: T, f: |&mut St, A|: 'a -> Option<B>, /// The current internal state to be passed to the closure next. pub state: St, } impl<'a, A, B, T: Iterator<A>, St> Iterator<B> for Scan<'a, A, B, T, St> { #[inline] fn next(&mut self) -> Option<B> { self.iter.next().and_then(|a| (self.f)(&mut self.state, a)) } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { let (_, upper) = self.iter.size_hint(); (0, upper) // can't know a lower bound, due to the scan function } } /// An iterator that maps each element to an iterator, /// and yields the elements of the produced iterators /// #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct FlatMap<'a, A, T, U> { iter: T, f: |A|: 'a -> U, frontiter: Option<U>, backiter: Option<U>, } impl<'a, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for FlatMap<'a, A, T, U> { #[inline] fn next(&mut self) -> Option<B> { loop { for inner in self.frontiter.iter_mut() { for x in *inner { return Some(x) } } match self.iter.next().map(|x| (self.f)(x)) { None => return self.backiter.as_mut().and_then(|it| it.next()), next => self.frontiter = next, } } } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint()); let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint()); let lo = flo.saturating_add(blo); match (self.iter.size_hint(), fhi, bhi) { ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(&b)), _ => (lo, None) } } } impl<'a, A, T: DoubleEndedIterator<A>, B, U: DoubleEndedIterator<B>> DoubleEndedIterator<B> for FlatMap<'a, A, T, U> { #[inline] fn next_back(&mut self) -> Option<B> { loop { for inner in self.backiter.iter_mut() { match inner.next_back() { None => (), y => return y } } match self.iter.next_back().map(|x| (self.f)(x)) { None => return self.frontiter.as_mut().and_then(|it| it.next_back()), next => self.backiter = next, } } } } /// An iterator that yields `None` forever after the underlying iterator /// yields `None` once. #[deriving(Clone)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Fuse<T> { iter: T, done: bool } impl<A, T: Iterator<A>> Iterator<A> for Fuse<T> { #[inline] fn next(&mut self) -> Option<A> { if self.done { None } else { match self.iter.next() { None => { self.done = true; None } x => x } } } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { if self.done { (0, Some(0)) } else { self.iter.size_hint() } } } impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Fuse<T> { #[inline] fn next_back(&mut self) -> Option<A> { if self.done { None } else { match self.iter.next_back() { None => { self.done = true; None } x => x } } } } // Allow RandomAccessIterators to be fused without affecting random-access behavior impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Fuse<T> { #[inline] fn indexable(&self) -> uint { self.iter.indexable() } #[inline] fn idx(&mut self, index: uint) -> Option<A> { self.iter.idx(index) } } impl<T> Fuse<T> { /// Resets the fuse such that the next call to .next() or .next_back() will /// call the underlying iterator again even if it previously returned None. #[inline] pub fn reset_fuse(&mut self) { self.done = false } } /// An iterator that calls a function with a reference to each /// element before yielding it. #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Inspect<'a, A, T> { iter: T, f: |&A|: 'a } impl<'a, A, T> Inspect<'a, A, T> { #[inline] fn do_inspect(&mut self, elt: Option<A>) -> Option<A> { match elt { Some(ref a) => (self.f)(a), None => () } elt } } impl<'a, A, T: Iterator<A>> Iterator<A> for Inspect<'a, A, T> { #[inline] fn next(&mut self) -> Option<A> { let next = self.iter.next(); self.do_inspect(next) } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() } } impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Inspect<'a, A, T> { #[inline] fn next_back(&mut self) -> Option<A> { let next = self.iter.next_back(); self.do_inspect(next) } } impl<'a, A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Inspect<'a, A, T> { #[inline] fn indexable(&self) -> uint { self.iter.indexable() } #[inline] fn idx(&mut self, index: uint) -> Option<A> { let element = self.iter.idx(index); self.do_inspect(element) } } /// An iterator which just modifies the contained state throughout iteration. pub struct Unfold<'a, A, St> { f: |&mut St|: 'a -> Option<A>, /// Internal state that will be yielded on the next iteration pub state: St, } impl<'a, A, St> Unfold<'a, A, St> { /// Creates a new iterator with the specified closure as the "iterator /// function" and an initial state to eventually pass to the iterator #[inline] pub fn new<'a>(initial_state: St, f: |&mut St|: 'a -> Option<A>) -> Unfold<'a, A, St> { Unfold { f: f, state: initial_state } } } impl<'a, A, St> Iterator<A> for Unfold<'a, A, St> { #[inline] fn next(&mut self) -> Option<A> { (self.f)(&mut self.state) } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { // no possible known bounds at this point (0, None) } } /// An infinite iterator starting at `start` and advancing by `step` with each /// iteration #[deriving(Clone)] pub struct Counter<A> { /// The current state the counter is at (next value to be yielded) state: A, /// The amount that this iterator is stepping by step: A, } /// Creates a new counter with the specified start/step #[inline] pub fn count<A>(start: A, step: A) -> Counter<A> { Counter{state: start, step: step} } impl<A: Add<A, A> + Clone> Iterator<A> for Counter<A> { #[inline] fn next(&mut self) -> Option<A> { let result = self.state.clone(); self.state = self.state + self.step; Some(result) } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { (uint::MAX, None) // Too bad we can't specify an infinite lower bound } } /// An iterator over the range [start, stop) #[deriving(Clone)] pub struct Range<A> { state: A, stop: A, one: A } /// Returns an iterator over the given range [start, stop) (that is, starting /// at start (inclusive), and ending at stop (exclusive)). /// /// # Example /// /// ```rust /// let array = [0, 1, 2, 3, 4]; /// /// for i in range(0, 5u) { /// println!("{}", i); /// assert_eq!(i, array[i]); /// } /// ``` #[inline] pub fn range<A: Add<A, A> + PartialOrd + Clone + One>(start: A, stop: A) -> Range<A> { Range{state: start, stop: stop, one: One::one()} } // FIXME: #10414: Unfortunate type bound impl<A: Add<A, A> + PartialOrd + Clone + ToPrimitive> Iterator<A> for Range<A> { #[inline] fn next(&mut self) -> Option<A> { if self.state < self.stop { let result = self.state.clone(); self.state = self.state + self.one; Some(result) } else { None } } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { // This first checks if the elements are representable as i64. If they aren't, try u64 (to // handle cases like range(huge, huger)). We don't use uint/int because the difference of // the i64/u64 might lie within their range. let bound = match self.state.to_i64() { Some(a) => { let sz = self.stop.to_i64().map(|b| b.checked_sub(&a)); match sz { Some(Some(bound)) => bound.to_uint(), _ => None, } }, None => match self.state.to_u64() { Some(a) => { let sz = self.stop.to_u64().map(|b| b.checked_sub(&a)); match sz { Some(Some(bound)) => bound.to_uint(), _ => None } }, None => None } }; match bound { Some(b) => (b, Some(b)), // Standard fallback for unbounded/unrepresentable bounds None => (0, None) } } } /// `Int` is required to ensure the range will be the same regardless of /// the direction it is consumed. impl<A: Int + PartialOrd + Clone + ToPrimitive> DoubleEndedIterator<A> for Range<A> { #[inline] fn next_back(&mut self) -> Option<A> { if self.stop > self.state { self.stop = self.stop - self.one; Some(self.stop.clone()) } else { None } } } /// An iterator over the range [start, stop] #[deriving(Clone)] pub struct RangeInclusive<A> { range: Range<A>, done: bool, } /// Return an iterator over the range [start, stop] #[inline] pub fn range_inclusive<A: Add<A, A> + PartialOrd + Clone + One>(start: A, stop: A) -> RangeInclusive<A> { RangeInclusive{range: range(start, stop), done: false} } impl<A: Add<A, A> + PartialOrd + Clone + ToPrimitive> Iterator<A> for RangeInclusive<A> { #[inline] fn next(&mut self) -> Option<A> { match self.range.next() { Some(x) => Some(x), None => { if !self.done && self.range.state == self.range.stop { self.done = true; Some(self.range.stop.clone()) } else { None } } } } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { let (lo, hi) = self.range.size_hint(); if self.done { (lo, hi) } else { let lo = lo.saturating_add(1); let hi = match hi { Some(x) => x.checked_add(&1), None => None }; (lo, hi) } } } impl<A: Sub<A, A> + Int + PartialOrd + Clone + ToPrimitive> DoubleEndedIterator<A> for RangeInclusive<A> { #[inline] fn next_back(&mut self) -> Option<A> { if self.range.stop > self.range.state { let result = self.range.stop.clone(); self.range.stop = self.range.stop - self.range.one; Some(result) } else if !self.done && self.range.state == self.range.stop { self.done = true; Some(self.range.stop.clone()) } else { None } } } /// An iterator over the range [start, stop) by `step`. It handles overflow by stopping. #[deriving(Clone)] pub struct RangeStep<A> { state: A, stop: A, step: A, rev: bool, } /// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping. #[inline] pub fn range_step<A: CheckedAdd + PartialOrd + Clone + Zero>(start: A, stop: A, step: A) -> RangeStep<A> { let rev = step < Zero::zero(); RangeStep{state: start, stop: stop, step: step, rev: rev} } impl<A: CheckedAdd + PartialOrd + Clone> Iterator<A> for RangeStep<A> { #[inline] fn next(&mut self) -> Option<A> { if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) { let result = self.state.clone(); match self.state.checked_add(&self.step) { Some(x) => self.state = x, None => self.state = self.stop.clone() } Some(result) } else { None } } } /// An iterator over the range [start, stop] by `step`. It handles overflow by stopping. #[deriving(Clone)] pub struct RangeStepInclusive<A> { state: A, stop: A, step: A, rev: bool, done: bool, } /// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping. #[inline] pub fn range_step_inclusive<A: CheckedAdd + PartialOrd + Clone + Zero>(start: A, stop: A, step: A) -> RangeStepInclusive<A> { let rev = step < Zero::zero(); RangeStepInclusive{state: start, stop: stop, step: step, rev: rev, done: false} } impl<A: CheckedAdd + PartialOrd + Clone + PartialEq> Iterator<A> for RangeStepInclusive<A> { #[inline] fn next(&mut self) -> Option<A>
} /// An iterator that repeats an element endlessly #[deriving(Clone)] pub struct Repeat<A> { element: A } impl<A: Clone> Repeat<A> { /// Create a new `Repeat` that endlessly repeats the element `elt`. #[inline] pub fn new(elt: A) -> Repeat<A> { Repeat{element: elt} } } impl<A: Clone> Iterator<A> for Repeat<A> { #[inline] fn next(&mut self) -> Option<A> { self.idx(0) } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { (uint::MAX, None) } } impl<A: Clone> DoubleEndedIterator<A> for Repeat<A> { #[inline] fn next_back(&mut self) -> Option<A> { self.idx(0) } } impl<A: Clone> RandomAccessIterator<A> for Repeat<A> { #[inline] fn indexable(&self) -> uint { uint::MAX } #[inline] fn idx(&mut self, _: uint) -> Option<A> { Some(self.element.clone()) } } type IterateState<'a, T> = (|T|: 'a -> T, Option<T>, bool); /// An iterator that repeatedly applies a given function, starting /// from a given seed value. pub type Iterate<'a, T> = Unfold<'a, T, IterateState<'a, T>>; /// Creates a new iterator that produces an infinite sequence of /// repeated applications of the given function `f`. pub fn iterate<'a, T: Clone>(seed: T, f: |T|: 'a -> T) -> Iterate<'a, T> { Unfold::new((f, Some(seed), true), |st| { let &(ref mut f, ref mut val, ref mut first) = st; if *first { *first = false; } else { match val.take() { Some(x) => { *val = Some((*f)(x)) } None => {} } } val.clone() }) } /// Functions for lexicographical ordering of sequences. /// /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires /// that the elements implement both `PartialEq` and `PartialOrd`. /// /// If two sequences are equal up until the point where one ends, /// the shorter sequence compares less. pub mod order { use cmp; use cmp::{Eq, Ord, PartialOrd, PartialEq}; use option::{Option, Some, None}; use super::Iterator; /// Compare `a` and `b` for equality using `Eq` pub fn equals<A: Eq, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool { loop { match (a.next(), b.next()) { (None, None) => return true, (None, _) | (_, None) => return false, (Some(x), Some(y)) => if x != y { return false }, } } } /// Order `a` and `b` lexicographically using `Ord` pub fn cmp<A: Ord, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> cmp::Ordering { loop { match (a.next(), b.next()) { (None, None) => return cmp::Equal, (None, _ ) => return cmp::Less, (_ , None) => return cmp::Greater, (Some(x), Some(y)) => match x.cmp(&y) { cmp::Equal => (), non_eq => return non_eq, }, } } } /// Order `a` and `b` lexicographically using `PartialOrd` pub fn partial_cmp<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> Option<cmp::Ordering> { loop { match (a.next(), b.next()) { (None, None) => return Some(cmp::Equal), (None, _ ) => return Some(cmp::Less), (_ , None) => return Some(cmp::Greater), (Some(x), Some(y)) => match x.partial_cmp(&y) { Some(cmp::Equal) => (), non_eq => return non_eq, }, } } } /// Compare `a` and `b` for equality (Using partial equality, `PartialEq`) pub fn eq<A: PartialEq, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool { loop { match (a.next(), b.next()) { (None, None) => return true, (None, _) | (_, None) => return false, (Some(x), Some(y)) => if !x.eq(&y) { return false }, } } } /// Compare `a` and `b` for nonequality (Using partial equality, `PartialEq`) pub fn ne<A: PartialEq, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool { loop { match (a.next(), b.next()) { (None, None) => return false, (None, _) | (_, None) => return true, (Some(x), Some(y)) => if x.ne(&y) { return true }, } } } /// Return `a` < `b` lexicographically (Using partial order, `PartialOrd`) pub fn lt<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool { loop { match (a.next(), b.next()) { (None, None) => return false, (None, _ ) => return true, (_ , None) => return false, (Some(x), Some(y)) => if x.ne(&y) { return x.lt(&y) }, } } } /// Return `a` <= `b` lexicographically (Using partial order, `PartialOrd`) pub fn le<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool { loop { match (a.next(), b.next()) { (None, None) => return true, (None, _ ) => return true, (_ , None) => return false, (Some(x), Some(y)) => if x.ne(&y) { return x.le(&y) }, } } } /// Return `a` > `b` lexicographically (Using partial order, `PartialOrd`) pub fn gt<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool { loop { match (a.next(), b.next()) { (None, None) => return false, (None, _ ) => return false, (_ , None) => return true, (Some(x), Some(y)) => if x.ne(&y) { return x.gt(&y) }, } } } /// Return `a` >= `b` lexicographically (Using partial order, `PartialOrd`) pub fn ge<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool { loop { match (a.next(), b.next()) { (None, None) => return true, (None, _ ) => return false, (_ , None) => return true, (Some(x), Some(y)) => if x.ne(&y) { return x.ge(&y) }, } } } }
{ if !self.done && ((self.rev && self.state >= self.stop) || (!self.rev && self.state <= self.stop)) { let result = self.state.clone(); match self.state.checked_add(&self.step) { Some(x) => self.state = x, None => self.done = true } Some(result) } else { None } }
authenticated-organization-guard.service.spec.ts
import {TestBed} from '@angular/core/testing'; import {Injectable} from '@angular/core'; import {of as observableOf} from 'rxjs'; import {AuthenticatedOrganizationGuardService} from './authenticated-organization-guard.service'; import {Router} from '@angular/router'; import {AdministratorOrganizationDataService} from './AdministratorOrganizationData.service'; @Injectable() class MockRouter { navigate() {} } @Injectable() class MockAdministratorOrganizationDataService { getOrganization = observableOf({}); } describe('AuthenticatedOrganizationGuardService', () => { let service: AuthenticatedOrganizationGuardService; beforeEach(() => { TestBed.configureTestingModule({ providers: [
{provide: Router, useValue: MockRouter}, {provide: AdministratorOrganizationDataService, useValue: MockAdministratorOrganizationDataService } ], }); service = TestBed.inject(AuthenticatedOrganizationGuardService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should run #canActivate()', async () => { expect(service.canActivate).toHaveBeenCalled(); }); })
spectral_clustering_demo.py
import superimport import itertools import matplotlib.pyplot as plt import numpy as np from scipy.linalg import eigh from sklearn.cluster import KMeans from sklearn.metrics.pairwise import rbf_kernel import pyprobml_utils as pml plt.style.use('classic') def spectral_clustering_demo(): np.random.seed(0) num_clusters = 2 for data_type, data in (('circle', sample_circle(num_clusters)), ('spiral', sample_spiral())): kmeans = KMeans(n_clusters=num_clusters, random_state=0) kmeans.fit(data) assignments = kmeans.predict(data) plot_data(data, assignments, 'k-means clustering', data_type) sigma = 0.1 gamma = 1 / (2 * sigma ** 2) W = rbf_kernel(data, gamma=gamma) d = np.sum(W, 1, keepdims=True) sqrt_d = np.sqrt(d) normalized_W = (W / sqrt_d) / sqrt_d.T paranoid_assert(W, normalized_W, False) # We select the largest eigen values of normalized_W, rather # than the smallest eigenvalues of I - normalized_W. The two # problems are equivalent. The eigen values can be converted # between the two problems via `1 - eigen_values`. The eigen # vectors are the same between both problems. eigen_values, eigen_vectors = eigh(normalized_W, # Get only the top num_clusters eigenvalues eigvals=(data.shape[0] - num_clusters, data.shape[0]-1)) eigen_vectors = eigen_vectors / np.linalg.norm(eigen_vectors, axis=1, keepdims=True) kmeans.fit(eigen_vectors) assignments = kmeans.predict(eigen_vectors) plot_data(data, assignments, 'spectral clustering', data_type) plt.show() def paranoid_assert(W, normalized_W, enable): if not enable: return D = np.diag(np.sum(W, 1)) L = D - W D_inv_sqrt = np.diag(1 / np.diag(np.sqrt(D))) np.testing.assert_almost_equal(np.sum(L, 1), 0, err_msg="Rows of Laplacian must sum to 0.") np.testing.assert_allclose(normalized_W, D_inv_sqrt * W * D_inv_sqrt, rtol=0, atol=1) def sample_circle(num_clusters): points_per_cluster = 500 bandwidth = 0.1 data = np.zeros((num_clusters * points_per_cluster, 2)) for k, n in itertools.product(range(num_clusters), range(points_per_cluster)): theta = 2 * np.pi * np.random.uniform() rho = k + 1 + np.random.randn() * bandwidth x, y = pol2cart(theta, rho) idx = k * points_per_cluster + n data[idx, 0] = x data[idx, 1] = y data = data.reshape((num_clusters * points_per_cluster, 2)) return data def pol2cart(theta, rho): x = rho * np.cos(theta) y = rho * np.sin(theta) return(x, y) def
(): # Only 2 clusters in this case. This is hard-coded. points_per_cluster = 500 bandwidth = 0.1 data = np.empty((points_per_cluster, 2)) w = np.arange(1, points_per_cluster + 1).astype(np.float32) / points_per_cluster data[:,0] = (4 * w + 1) * np.cos(2*np.pi * w) + np.random.randn(points_per_cluster) * bandwidth data[:,1] = (4 * w + 1) * np.sin(2*np.pi * w) + np.random.randn(points_per_cluster) * bandwidth data = np.vstack((data, -data)) return data def plot_data(data, assignments, title, data_type): fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(data[assignments == 0, 0], data[assignments == 0, 1], 'o', color='r') ax.plot(data[assignments == 1, 0], data[assignments == 1, 1], 'o', color='b') ax.set_xlabel('x') ax.set_ylabel('y') ax.axis('square') ax.grid(True) ax.set_title(title) plt.tight_layout() pml.savefig(f"{data_type}_{title.replace(' ', '_')}.pdf") if __name__ == '__main__': spectral_clustering_demo()
sample_spiral
item-price-type.js
import { GraphQLFloat, GraphQLObjectType } from 'graphql'; export const ItemPriceType = new GraphQLObjectType({ name: 'ItemPriceType', description: 'Item Price',
fields: () => ({ amount: { type: GraphQLFloat } }) });
storage_factory.go
/* Copyright 2015 The Kubernetes Authors. Copyright 2020 Authors of Arktos - file modified. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package registry import ( "sync" "k8s.io/klog" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apiserver/pkg/registry/generic" "k8s.io/apiserver/pkg/storage" cacherstorage "k8s.io/apiserver/pkg/storage/cacher" "k8s.io/apiserver/pkg/storage/etcd3" "k8s.io/apiserver/pkg/storage/storagebackend" "k8s.io/apiserver/pkg/storage/storagebackend/factory" "k8s.io/client-go/tools/cache" ) // Creates a cacher based given storageConfig. func StorageWithCacher(capacity int) generic.StorageDecorator { return func( storageConfig *storagebackend.Config, resourcePrefix string, keyFunc func(obj runtime.Object) (string, error), newFunc func() runtime.Object, newListFunc func() runtime.Object, getAttrsFunc storage.AttrFunc, triggerFuncs storage.IndexerFuncs, indexers *cache.Indexers) (storage.Interface, factory.DestroyFunc) { s, d := generic.NewRawStorage(storageConfig) if capacity <= 0 { klog.V(5).Infof("Storage caching is disabled for %T", newFunc()) return s, d } if klog.V(5) { klog.Infof("Storage caching is enabled for %T with capacity %v", newFunc(), capacity) } // TODO: we would change this later to make storage always have cacher and hide low level KV layer inside. // Currently it has two layers of same storage interface -- cacher and low level kv. cacherConfig := cacherstorage.Config{ CacheCapacity: capacity, Storage: s,
Versioner: etcd3.APIObjectVersioner{}, ResourcePrefix: resourcePrefix, KeyFunc: keyFunc, NewFunc: newFunc, NewListFunc: newListFunc, GetAttrsFunc: getAttrsFunc, IndexerFuncs: triggerFuncs, Indexers: indexers, Codec: storageConfig.Codec, } cacher := cacherstorage.NewCacherFromConfig(cacherConfig) destroyFunc := func() { cacher.Stop() d() } // TODO : Remove RegisterStorageCleanup below when PR // https://github.com/kubernetes/kubernetes/pull/50690 // merges as that shuts down storage properly RegisterStorageCleanup(destroyFunc) return cacher, destroyFunc } } // TODO : Remove all the code below when PR // https://github.com/kubernetes/kubernetes/pull/50690 // merges as that shuts down storage properly // HACK ALERT : Track the destroy methods to call them // from the test harness. TrackStorageCleanup will be called // only from the test harness, so Register/Cleanup will be // no-op at runtime. var cleanupLock sync.Mutex var cleanup []func() = nil func TrackStorageCleanup() { cleanupLock.Lock() defer cleanupLock.Unlock() if cleanup != nil { panic("Conflicting storage tracking") } cleanup = make([]func(), 0) } func RegisterStorageCleanup(fn func()) { cleanupLock.Lock() defer cleanupLock.Unlock() if cleanup == nil { return } cleanup = append(cleanup, fn) } func CleanupStorage() { cleanupLock.Lock() old := cleanup cleanup = nil cleanupLock.Unlock() for _, d := range old { d() } }