prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>AlertControl.tsx<|end_file_name|><|fim▁begin|>import * as React from 'react'; import { AccessPropertyName, Alert, AlertType } from '../Models'; import { ApplicationState, AppThunkAction } from '../store'; import { CloseAlertAction } from '../store/Alert';<|fim▁hole|> items: Alert[]; closeAlert(id: number): AppThunkAction<CloseAlertAction>; } export default class App extends React.Component<AlertProps, {}> { public render() { return ( <div className="alerts"> {this.props.items.map(this.renderAlert)} </div> ); } private renderAlert = (item: Alert) => { const closeAction = (e: any) => { e.preventDefault(); this.props.closeAlert(item.id); }; return ( <div key={item.id} className={'alert ' + item.alertType + ' alert-dismissable ' + `fade fade-${item.state}`} role="alert"> <a href="#" className="close" aria-label="close" onClick={closeAction}>&times;</a> {item.message} </div> ); } }<|fim▁end|>
export interface AlertProps {
<|file_name|>ButtonEvent.py<|end_file_name|><|fim▁begin|>''' ******************************************************************************* * ButtonEvent.py is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ButtonEvent.py is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ButtonEvent.py. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************** Created on Jan 5, 2010 @author: iocanto ''' BUTTON_SELECT = 257 BUTTON_HOTKEY_1 = 258; BUTTON_HOTKEY_2 = 259; BUTTON_HOTKEY_3 = 260; BUTTON_HOTKEY_4 = 261; BUTTON_RIGHT = 262; BUTTON_LEFT = 263; BUTTON_UP = 264; BUTTON_DOWN = 265; KEY_UP = 0 KEY_DOWN = 1 class ButtonEvent(): # Constructor def __init__(self, button = BUTTON_HOTKEY_1, action = KEY_UP ): self.__button = button self.__action = action def __str__ (self): return "ButtonEvent [__button %i]" % self.__button def getAction(self): return self.__action def getButton(self): return self.__button def getButtonName(self): return { 257 : "BUTTON_SELECT" , 258 : "BUTTON_HOTKEY_1", 259 : "BUTTON_HOTKEY_2", 260 : "BUTTON_HOTKEY_3", 261 : "BUTTON_HOTKEY_4", 262 : "BUTTON_RIGHT" ,<|fim▁hole|> def setAction(self, action): self.__action = action def setButton(self, button): self.__button = button<|fim▁end|>
263 : "BUTTON_LEFT" , 264 : "BUTTON_UP" , 265 : "BUTTON_DOWN" , }[self.__button]
<|file_name|>ThreadModel.java<|end_file_name|><|fim▁begin|>/* * 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 * <|fim▁hole|> * * 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 org.apache.mina.common; /** * Represents a thread model of an {@link IoService}. There's no essential * difference from {@link IoFilterChainBuilder}. The only difference is that * {@link ThreadModel} is executed later than the {@link IoFilterChainBuilder} * you specified. However, please don't abuse this internal behavior; it can * change. * * @author The Apache Directory Project ([email protected]) * @version $Rev$, $Date$ */ public interface ThreadModel extends IoFilterChainBuilder { /** * A {@link ThreadModel} which make MINA not manage a thread model at all. */ static final ThreadModel MANUAL = new ThreadModel() { public void buildFilterChain(IoFilterChain chain) throws Exception { // Do nothing. } }; }<|fim▁end|>
* http://www.apache.org/licenses/LICENSE-2.0
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>import { parseProgrammes, parseSubjects, parseCourses, } from "@education-data/parser"; import { join } from "path"; import { writeFileSync } from "fs"; <|fim▁hole|>import { format } from "date-fns"; import { sv } from "date-fns/locale"; import { sourceDirectory, outputDirectory, replacementsDirectory } from "./cfg"; async function main() { console.info("\n[parsing subject data]"); await parseSubjects(sourceDirectory, outputDirectory, replacementsDirectory); console.info("\n[parsing course data]"); await parseCourses( { get(code: string) { const subjects = require("./out/subjects.json"); const name = subjects.find((el) => el.code === code); return require(join(process.cwd(), "./out", name.file)); }, } as Map<string, any>, sourceDirectory, outputDirectory, replacementsDirectory ); console.info("\n[parsing program data]"); await parseProgrammes( sourceDirectory + "/../gyP1_6_S1_4", outputDirectory, replacementsDirectory ); p; writeFileSync( "./out/meta.json", JSON.stringify({ fetchTime: new Date().toISOString(), humanizedFetchTime: format(new Date(), "do LLLL, yyyy", { locale: sv, }), }) ); } main().catch((err) => { console.error(err); process.exit(1); });<|fim▁end|>
<|file_name|>validat2.cpp<|end_file_name|><|fim▁begin|>// validat2.cpp - written and placed in the public domain by Wei Dai #include "pch.h" #include "blumshub.h" #include "rsa.h" #include "md2.h" #include "elgamal.h" #include "nr.h" #include "dsa.h" #include "dh.h" #include "mqv.h" #include "luc.h" #include "xtrcrypt.h" #include "rabin.h" #include "rw.h" #include "eccrypto.h" #include "ecp.h" #include "ec2n.h" #include "asn.h" #include "rng.h" #include "files.h" #include "hex.h" #include "oids.h" #include "esign.h" #include "osrng.h" #include <iostream> #include <iomanip> #include "validate.h" USING_NAMESPACE(CryptoPP) USING_NAMESPACE(std) class FixedRNG : public RandomNumberGenerator { public: FixedRNG(BufferedTransformation &source) : m_source(source) {} byte GenerateByte() { byte b; m_source.Get(b); return b; } private: BufferedTransformation &m_source; }; bool ValidateBBS() { cout << "\nBlumBlumShub validation suite running...\n\n"; Integer p("212004934506826557583707108431463840565872545889679278744389317666981496005411448865750399674653351"); Integer q("100677295735404212434355574418077394581488455772477016953458064183204108039226017738610663984508231"); Integer seed("63239752671357255800299643604761065219897634268887145610573595874544114193025997412441121667211431"); BlumBlumShub bbs(p, q, seed); bool pass = true, fail; int j; const byte output1[] = { 0x49,0xEA,0x2C,0xFD,0xB0,0x10,0x64,0xA0,0xBB,0xB9, 0x2A,0xF1,0x01,0xDA,0xC1,0x8A,0x94,0xF7,0xB7,0xCE}; const byte output2[] = { 0x74,0x45,0x48,0xAE,0xAC,0xB7,0x0E,0xDF,0xAF,0xD7, 0xD5,0x0E,0x8E,0x29,0x83,0x75,0x6B,0x27,0x46,0xA1}; byte buf[20]; bbs.GenerateBlock(buf, 20); fail = memcmp(output1, buf, 20) != 0; pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); for (j=0;j<20;j++) cout << setw(2) << setfill('0') << hex << (int)buf[j]; cout << endl; bbs.Seek(10); bbs.GenerateBlock(buf, 10); fail = memcmp(output1+10, buf, 10) != 0; pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); for (j=0;j<10;j++) cout << setw(2) << setfill('0') << hex << (int)buf[j]; cout << endl; bbs.Seek(1234567); bbs.GenerateBlock(buf, 20); fail = memcmp(output2, buf, 20) != 0; pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); for (j=0;j<20;j++) <|fim▁hole|> return pass; } bool SignatureValidate(PK_Signer &priv, PK_Verifier &pub, bool thorough = false) { bool pass = true, fail; fail = !pub.GetMaterial().Validate(GlobalRNG(), thorough ? 3 : 2) || !priv.GetMaterial().Validate(GlobalRNG(), thorough ? 3 : 2); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "signature key validation\n"; const byte *message = (byte *)"test message"; const int messageLen = 12; byte buffer[512]; memset(buffer, 0, sizeof(buffer)); priv.SignMessage(GlobalRNG(), message, messageLen, buffer); fail = !pub.VerifyMessage(message, messageLen, buffer); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "signature and verification\n"; ++buffer[0]; fail = pub.VerifyMessage(message, messageLen, buffer); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "checking invalid signature" << endl; return pass; } bool CryptoSystemValidate(PK_Decryptor &priv, PK_Encryptor &pub, bool thorough = false) { bool pass = true, fail; fail = !pub.GetMaterial().Validate(GlobalRNG(), thorough ? 3 : 2) || !priv.GetMaterial().Validate(GlobalRNG(), thorough ? 3 : 2); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "cryptosystem key validation\n"; const byte *message = (byte *)"test message"; const int messageLen = 12; SecByteBlock ciphertext(priv.CiphertextLength(messageLen)); SecByteBlock plaintext(priv.MaxPlaintextLength(ciphertext.size())); pub.Encrypt(GlobalRNG(), message, messageLen, ciphertext); fail = priv.Decrypt(ciphertext, priv.CiphertextLength(messageLen), plaintext) != DecodingResult(messageLen); fail = fail || memcmp(message, plaintext, messageLen); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "encryption and decryption\n"; return pass; } bool SimpleKeyAgreementValidate(SimpleKeyAgreementDomain &d) { if (d.GetCryptoParameters().Validate(GlobalRNG(), 3)) cout << "passed simple key agreement domain parameters validation" << endl; else { cout << "FAILED simple key agreement domain parameters invalid" << endl; return false; } SecByteBlock priv1(d.PrivateKeyLength()), priv2(d.PrivateKeyLength()); SecByteBlock pub1(d.PublicKeyLength()), pub2(d.PublicKeyLength()); SecByteBlock val1(d.AgreedValueLength()), val2(d.AgreedValueLength()); d.GenerateKeyPair(GlobalRNG(), priv1, pub1); d.GenerateKeyPair(GlobalRNG(), priv2, pub2); memset(val1.begin(), 0x10, val1.size()); memset(val2.begin(), 0x11, val2.size()); if (!(d.Agree(val1, priv1, pub2) && d.Agree(val2, priv2, pub1))) { cout << "FAILED simple key agreement failed" << endl; return false; } if (memcmp(val1.begin(), val2.begin(), d.AgreedValueLength())) { cout << "FAILED simple agreed values not equal" << endl; return false; } cout << "passed simple key agreement" << endl; return true; } bool AuthenticatedKeyAgreementValidate(AuthenticatedKeyAgreementDomain &d) { if (d.GetCryptoParameters().Validate(GlobalRNG(), 3)) cout << "passed authenticated key agreement domain parameters validation" << endl; else { cout << "FAILED authenticated key agreement domain parameters invalid" << endl; return false; } SecByteBlock spriv1(d.StaticPrivateKeyLength()), spriv2(d.StaticPrivateKeyLength()); SecByteBlock epriv1(d.EphemeralPrivateKeyLength()), epriv2(d.EphemeralPrivateKeyLength()); SecByteBlock spub1(d.StaticPublicKeyLength()), spub2(d.StaticPublicKeyLength()); SecByteBlock epub1(d.EphemeralPublicKeyLength()), epub2(d.EphemeralPublicKeyLength()); SecByteBlock val1(d.AgreedValueLength()), val2(d.AgreedValueLength()); d.GenerateStaticKeyPair(GlobalRNG(), spriv1, spub1); d.GenerateStaticKeyPair(GlobalRNG(), spriv2, spub2); d.GenerateEphemeralKeyPair(GlobalRNG(), epriv1, epub1); d.GenerateEphemeralKeyPair(GlobalRNG(), epriv2, epub2); memset(val1.begin(), 0x10, val1.size()); memset(val2.begin(), 0x11, val2.size()); if (!(d.Agree(val1, spriv1, epriv1, spub2, epub2) && d.Agree(val2, spriv2, epriv2, spub1, epub1))) { cout << "FAILED authenticated key agreement failed" << endl; return false; } if (memcmp(val1.begin(), val2.begin(), d.AgreedValueLength())) { cout << "FAILED authenticated agreed values not equal" << endl; return false; } cout << "passed authenticated key agreement" << endl; return true; } bool ValidateRSA() { cout << "\nRSA validation suite running...\n\n"; byte out[100], outPlain[100]; bool pass = true, fail; { char *plain = "Everyone gets Friday off."; byte *signature = (byte *) "\x05\xfa\x6a\x81\x2f\xc7\xdf\x8b\xf4\xf2\x54\x25\x09\xe0\x3e\x84" "\x6e\x11\xb9\xc6\x20\xbe\x20\x09\xef\xb4\x40\xef\xbc\xc6\x69\x21" "\x69\x94\xac\x04\xf3\x41\xb5\x7d\x05\x20\x2d\x42\x8f\xb2\xa2\x7b" "\x5c\x77\xdf\xd9\xb1\x5b\xfc\x3d\x55\x93\x53\x50\x34\x10\xc1\xe1"; FileSource keys("rsa512a.dat", true, new HexDecoder); RSASSA_PKCS1v15_MD2_Signer rsaPriv(keys); RSASSA_PKCS1v15_MD2_Verifier rsaPub(rsaPriv); rsaPriv.SignMessage(GlobalRNG(), (byte *)plain, strlen(plain), out); fail = memcmp(signature, out, 64) != 0; pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "signature check against test vector\n"; fail = !rsaPub.VerifyMessage((byte *)plain, strlen(plain), out); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "verification check against test vector\n"; out[10]++; fail = rsaPub.VerifyMessage((byte *)plain, strlen(plain), out); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "invalid signature verification\n"; } { FileSource keys("rsa1024.dat", true, new HexDecoder); RSAES_PKCS1v15_Decryptor rsaPriv(keys); RSAES_PKCS1v15_Encryptor rsaPub(rsaPriv); pass = CryptoSystemValidate(rsaPriv, rsaPub) && pass; } { byte *plain = (byte *) "\x54\x85\x9b\x34\x2c\x49\xea\x2a"; byte *encrypted = (byte *) "\x14\xbd\xdd\x28\xc9\x83\x35\x19\x23\x80\xe8\xe5\x49\xb1\x58\x2a" "\x8b\x40\xb4\x48\x6d\x03\xa6\xa5\x31\x1f\x1f\xd5\xf0\xa1\x80\xe4" "\x17\x53\x03\x29\xa9\x34\x90\x74\xb1\x52\x13\x54\x29\x08\x24\x52" "\x62\x51"; byte *oaepSeed = (byte *) "\xaa\xfd\x12\xf6\x59\xca\xe6\x34\x89\xb4\x79\xe5\x07\x6d\xde\xc2" "\xf0\x6c\xb5\x8f"; ByteQueue bq; bq.Put(oaepSeed, 20); FixedRNG rng(bq); FileSource privFile("rsa400pv.dat", true, new HexDecoder); FileSource pubFile("rsa400pb.dat", true, new HexDecoder); RSAES_OAEP_SHA_Decryptor rsaPriv; rsaPriv.AccessKey().BERDecodeKey(privFile); RSAES_OAEP_SHA_Encryptor rsaPub(pubFile); memset(out, 0, 50); memset(outPlain, 0, 8); rsaPub.Encrypt(rng, plain, 8, out); DecodingResult result = rsaPriv.FixedLengthDecrypt(encrypted, outPlain); fail = !result.isValidCoding || (result.messageLength!=8) || memcmp(out, encrypted, 50) || memcmp(plain, outPlain, 8); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "PKCS 2.0 encryption and decryption\n"; } return pass; } bool ValidateDH() { cout << "\nDH validation suite running...\n\n"; FileSource f("dh1024.dat", true, new HexDecoder()); DH dh(f); return SimpleKeyAgreementValidate(dh); } bool ValidateMQV() { cout << "\nMQV validation suite running...\n\n"; FileSource f("mqv1024.dat", true, new HexDecoder()); MQV mqv(f); return AuthenticatedKeyAgreementValidate(mqv); } bool ValidateLUC_DH() { cout << "\nLUC-DH validation suite running...\n\n"; FileSource f("lucd512.dat", true, new HexDecoder()); LUC_DH dh(f); return SimpleKeyAgreementValidate(dh); } bool ValidateXTR_DH() { cout << "\nXTR-DH validation suite running...\n\n"; FileSource f("xtrdh171.dat", true, new HexDecoder()); XTR_DH dh(f); return SimpleKeyAgreementValidate(dh); } bool ValidateElGamal() { cout << "\nElGamal validation suite running...\n\n"; bool pass = true; { FileSource fc("elgc1024.dat", true, new HexDecoder); ElGamalDecryptor privC(fc); ElGamalEncryptor pubC(privC); privC.AccessKey().Precompute(); ByteQueue queue; privC.AccessKey().SavePrecomputation(queue); privC.AccessKey().LoadPrecomputation(queue); pass = CryptoSystemValidate(privC, pubC) && pass; } return pass; } bool ValidateDLIES() { cout << "\nDLIES validation suite running...\n\n"; bool pass = true; { FileSource fc("dlie1024.dat", true, new HexDecoder); DLIES<>::Decryptor privC(fc); DLIES<>::Encryptor pubC(privC); pass = CryptoSystemValidate(privC, pubC) && pass; } { cout << "Generating new encryption key..." << endl; DLIES<>::GroupParameters gp; gp.GenerateRandomWithKeySize(GlobalRNG(), 128); DLIES<>::Decryptor decryptor; decryptor.AccessKey().GenerateRandom(GlobalRNG(), gp); DLIES<>::Encryptor encryptor(decryptor); pass = CryptoSystemValidate(decryptor, encryptor) && pass; } return pass; } bool ValidateNR() { cout << "\nNR validation suite running...\n\n"; bool pass = true; { FileSource f("nr2048.dat", true, new HexDecoder); NR<SHA>::Signer privS(f); privS.AccessKey().Precompute(); NR<SHA>::Verifier pubS(privS); pass = SignatureValidate(privS, pubS) && pass; } { cout << "Generating new signature key..." << endl; NR<SHA>::Signer privS(GlobalRNG(), 256); NR<SHA>::Verifier pubS(privS); pass = SignatureValidate(privS, pubS) && pass; } return pass; } bool ValidateDSA(bool thorough) { cout << "\nDSA validation suite running...\n\n"; bool pass = true, fail; { FileSource fs("dsa512.dat", true, new HexDecoder()); GDSA<SHA>::Signer priv(fs); priv.AccessKey().Precompute(16); GDSA<SHA>::Verifier pub(priv); byte seed[]={0xd5, 0x01, 0x4e, 0x4b, 0x60, 0xef, 0x2b, 0xa8, 0xb6, 0x21, 0x1b, 0x40, 0x62, 0xba, 0x32, 0x24, 0xe0, 0x42, 0x7d, 0xd3}; Integer k("358dad57 1462710f 50e254cf 1a376b2b deaadfbfh"); Integer h("a9993e36 4706816a ba3e2571 7850c26c 9cd0d89dh"); byte sig[]={0x8b, 0xac, 0x1a, 0xb6, 0x64, 0x10, 0x43, 0x5c, 0xb7, 0x18, 0x1f, 0x95, 0xb1, 0x6a, 0xb9, 0x7c, 0x92, 0xb3, 0x41, 0xc0, 0x41, 0xe2, 0x34, 0x5f, 0x1f, 0x56, 0xdf, 0x24, 0x58, 0xf4, 0x26, 0xd1, 0x55, 0xb4, 0xba, 0x2d, 0xb6, 0xdc, 0xd8, 0xc8}; Integer r(sig, 20); Integer s(sig+20, 20); Integer pGen, qGen, rOut, sOut; int c; fail = !DSA::GeneratePrimes(seed, 160, c, pGen, 512, qGen); fail = fail || (pGen != pub.GetKey().GetGroupParameters().GetModulus()) || (qGen != pub.GetKey().GetGroupParameters().GetSubgroupOrder()); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "prime generation test\n"; priv.GetDigestSignatureScheme().RawSign(k, h, rOut, sOut); fail = (rOut != r) || (sOut != s); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "signature check against test vector\n"; fail = !pub.VerifyMessage((byte *)"abc", 3, sig); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "verification check against test vector\n"; fail = pub.VerifyMessage((byte *)"xyz", 3, sig); pass = pass && !fail; } FileSource fs1("dsa1024.dat", true, new HexDecoder()); DSA::Signer priv(fs1); DSA::Verifier pub(priv); FileSource fs2("dsa1024b.dat", true, new HexDecoder()); DSA::Verifier pub1(fs2); assert(pub.GetKey() == pub1.GetKey()); pass = SignatureValidate(priv, pub, thorough) && pass; return pass; } bool ValidateLUC() { cout << "\nLUC validation suite running...\n\n"; bool pass=true; { FileSource f("luc1024.dat", true, new HexDecoder); LUCSSA_PKCS1v15_SHA_Signer priv(f); LUCSSA_PKCS1v15_SHA_Verifier pub(priv); pass = SignatureValidate(priv, pub) && pass; } { LUCES_OAEP_SHA_Decryptor priv(GlobalRNG(), 512); LUCES_OAEP_SHA_Encryptor pub(priv); pass = CryptoSystemValidate(priv, pub) && pass; } return pass; } bool ValidateLUC_DL() { cout << "\nLUC-HMP validation suite running...\n\n"; FileSource f("lucs512.dat", true, new HexDecoder); LUC_HMP<SHA>::Signer privS(f); LUC_HMP<SHA>::Verifier pubS(privS); bool pass = SignatureValidate(privS, pubS); cout << "\nLUC-IES validation suite running...\n\n"; FileSource fc("lucc512.dat", true, new HexDecoder); LUC_IES<>::Decryptor privC(fc); LUC_IES<>::Encryptor pubC(privC); pass = CryptoSystemValidate(privC, pubC) && pass; return pass; } bool ValidateRabin() { cout << "\nRabin validation suite running...\n\n"; bool pass=true; { FileSource f("rabi1024.dat", true, new HexDecoder); RabinPSSR<SHA>::Signer priv(f); RabinPSSR<SHA>::Verifier pub(priv); pass = SignatureValidate(priv, pub) && pass; } { RabinES<OAEP<SHA> >::Decryptor priv(GlobalRNG(), 512); RabinES<OAEP<SHA> >::Encryptor pub(priv); pass = CryptoSystemValidate(priv, pub) && pass; } return pass; } bool ValidateRW() { cout << "\nRW validation suite running...\n\n"; FileSource f("rw1024.dat", true, new HexDecoder); RWSSA<SHA>::Signer priv(f); RWSSA<SHA>::Verifier pub(priv); return SignatureValidate(priv, pub); } /* bool ValidateBlumGoldwasser() { cout << "\nBlumGoldwasser validation suite running...\n\n"; FileSource f("blum512.dat", true, new HexDecoder); BlumGoldwasserPrivateKey priv(f); BlumGoldwasserPublicKey pub(priv); return CryptoSystemValidate(priv, pub); } */ bool ValidateECP() { cout << "\nECP validation suite running...\n\n"; ECIES<ECP>::Decryptor cpriv(GlobalRNG(), ASN1::secp192r1()); ECIES<ECP>::Encryptor cpub(cpriv); ByteQueue bq; cpriv.GetKey().DEREncode(bq); cpub.AccessKey().AccessGroupParameters().SetEncodeAsOID(true); cpub.GetKey().DEREncode(bq); ECDSA<ECP, SHA>::Signer spriv(bq); ECDSA<ECP, SHA>::Verifier spub(bq); ECDH<ECP>::Domain ecdhc(ASN1::secp192r1()); ECMQV<ECP>::Domain ecmqvc(ASN1::secp192r1()); spriv.AccessKey().Precompute(); ByteQueue queue; spriv.AccessKey().SavePrecomputation(queue); spriv.AccessKey().LoadPrecomputation(queue); bool pass = SignatureValidate(spriv, spub); cpub.AccessKey().Precompute(); cpriv.AccessKey().Precompute(); pass = CryptoSystemValidate(cpriv, cpub) && pass; pass = SimpleKeyAgreementValidate(ecdhc) && pass; pass = AuthenticatedKeyAgreementValidate(ecmqvc) && pass; cout << "Turning on point compression..." << endl; cpriv.AccessKey().AccessGroupParameters().SetPointCompression(true); cpub.AccessKey().AccessGroupParameters().SetPointCompression(true); ecdhc.AccessGroupParameters().SetPointCompression(true); ecmqvc.AccessGroupParameters().SetPointCompression(true); pass = CryptoSystemValidate(cpriv, cpub) && pass; pass = SimpleKeyAgreementValidate(ecdhc) && pass; pass = AuthenticatedKeyAgreementValidate(ecmqvc) && pass; cout << "Testing SEC 2 recommended curves..." << endl; OID oid; while (!(oid = DL_GroupParameters_EC<ECP>::GetNextRecommendedParametersOID(oid)).m_values.empty()) { DL_GroupParameters_EC<ECP> params(oid); bool fail = !params.Validate(GlobalRNG(), 2); cout << (fail ? "FAILED" : "passed") << " " << dec << params.GetCurve().GetField().MaxElementBitLength() << " bits" << endl; pass = pass && !fail; } return pass; } bool ValidateEC2N() { cout << "\nEC2N validation suite running...\n\n"; ECIES<EC2N>::Decryptor cpriv(GlobalRNG(), ASN1::sect193r1()); ECIES<EC2N>::Encryptor cpub(cpriv); ByteQueue bq; cpriv.DEREncode(bq); cpub.AccessKey().AccessGroupParameters().SetEncodeAsOID(true); cpub.DEREncode(bq); ECDSA<EC2N, SHA>::Signer spriv(bq); ECDSA<EC2N, SHA>::Verifier spub(bq); ECDH<EC2N>::Domain ecdhc(ASN1::sect193r1()); ECMQV<EC2N>::Domain ecmqvc(ASN1::sect193r1()); spriv.AccessKey().Precompute(); ByteQueue queue; spriv.AccessKey().SavePrecomputation(queue); spriv.AccessKey().LoadPrecomputation(queue); bool pass = SignatureValidate(spriv, spub); pass = CryptoSystemValidate(cpriv, cpub) && pass; pass = SimpleKeyAgreementValidate(ecdhc) && pass; pass = AuthenticatedKeyAgreementValidate(ecmqvc) && pass; cout << "Turning on point compression..." << endl; cpriv.AccessKey().AccessGroupParameters().SetPointCompression(true); cpub.AccessKey().AccessGroupParameters().SetPointCompression(true); ecdhc.AccessGroupParameters().SetPointCompression(true); ecmqvc.AccessGroupParameters().SetPointCompression(true); pass = CryptoSystemValidate(cpriv, cpub) && pass; pass = SimpleKeyAgreementValidate(ecdhc) && pass; pass = AuthenticatedKeyAgreementValidate(ecmqvc) && pass; #if 0 // TODO: turn this back on when I make EC2N faster for pentanomial basis cout << "Testing SEC 2 recommended curves..." << endl; OID oid; while (!(oid = ECParameters<EC2N>::GetNextRecommendedParametersOID(oid)).m_values.empty()) { ECParameters<EC2N> params(oid); bool fail = !params.ValidateParameters(GlobalRNG()); cout << (fail ? "FAILED" : "passed") << " " << params.GetCurve().GetField().MaxElementBitLength() << " bits" << endl; pass = pass && !fail; } #endif return pass; } bool ValidateECDSA() { cout << "\nECDSA validation suite running...\n\n"; // from Sample Test Vectors for P1363 GF2NT gf2n(191, 9, 0); byte a[]="\x28\x66\x53\x7B\x67\x67\x52\x63\x6A\x68\xF5\x65\x54\xE1\x26\x40\x27\x6B\x64\x9E\xF7\x52\x62\x67"; byte b[]="\x2E\x45\xEF\x57\x1F\x00\x78\x6F\x67\xB0\x08\x1B\x94\x95\xA3\xD9\x54\x62\xF5\xDE\x0A\xA1\x85\xEC"; EC2N ec(gf2n, PolynomialMod2(a,24), PolynomialMod2(b,24)); EC2N::Point P; ec.DecodePoint(P, (byte *)"\x04\x36\xB3\xDA\xF8\xA2\x32\x06\xF9\xC4\xF2\x99\xD7\xB2\x1A\x9C\x36\x91\x37\xF2\xC8\x4A\xE1\xAA\x0D" "\x76\x5B\xE7\x34\x33\xB3\xF9\x5E\x33\x29\x32\xE7\x0E\xA2\x45\xCA\x24\x18\xEA\x0E\xF9\x80\x18\xFB", ec.EncodedPointSize()); Integer n("40000000000000000000000004a20e90c39067c893bbb9a5H"); Integer d("340562e1dda332f9d2aec168249b5696ee39d0ed4d03760fH"); EC2N::Point Q(ec.Multiply(d, P)); ECDSA<EC2N, SHA>::Signer priv(ec, P, n, d); ECDSA<EC2N, SHA>::Verifier pub(priv); Integer h("A9993E364706816ABA3E25717850C26C9CD0D89DH"); Integer k("3eeace72b4919d991738d521879f787cb590aff8189d2b69H"); byte sig[]="\x03\x8e\x5a\x11\xfb\x55\xe4\xc6\x54\x71\xdc\xd4\x99\x84\x52\xb1\xe0\x2d\x8a\xf7\x09\x9b\xb9\x30" "\x0c\x9a\x08\xc3\x44\x68\xc2\x44\xb4\xe5\xd6\xb2\x1b\x3c\x68\x36\x28\x07\x41\x60\x20\x32\x8b\x6e"; Integer r(sig, 24); Integer s(sig+24, 24); Integer rOut, sOut; bool fail, pass=true; priv.GetDigestSignatureScheme().RawSign(k, h, rOut, sOut); fail = (rOut != r) || (sOut != s); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "signature check against test vector\n"; fail = !pub.VerifyMessage((byte *)"abc", 3, sig); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "verification check against test vector\n"; fail = pub.VerifyMessage((byte *)"xyz", 3, sig); pass = pass && !fail; pass = SignatureValidate(priv, pub) && pass; return pass; } bool ValidateESIGN() { cout << "\nESIGN validation suite running...\n\n"; bool pass = true, fail; const char *plain = "test"; const byte *signature = (byte *) "\xA3\xE3\x20\x65\xDE\xDA\xE7\xEC\x05\xC1\xBF\xCD\x25\x79\x7D\x99\xCD\xD5\x73\x9D\x9D\xF3\xA4\xAA\x9A\xA4\x5A\xC8\x23\x3D\x0D\x37\xFE\xBC\x76\x3F\xF1\x84\xF6\x59" "\x14\x91\x4F\x0C\x34\x1B\xAE\x9A\x5C\x2E\x2E\x38\x08\x78\x77\xCB\xDC\x3C\x7E\xA0\x34\x44\x5B\x0F\x67\xD9\x35\x2A\x79\x47\x1A\x52\x37\x71\xDB\x12\x67\xC1\xB6\xC6" "\x66\x73\xB3\x40\x2E\xD6\xF2\x1A\x84\x0A\xB6\x7B\x0F\xEB\x8B\x88\xAB\x33\xDD\xE4\x83\x21\x90\x63\x2D\x51\x2A\xB1\x6F\xAB\xA7\x5C\xFD\x77\x99\xF2\xE1\xEF\x67\x1A" "\x74\x02\x37\x0E\xED\x0A\x06\xAD\xF4\x15\x65\xB8\xE1\xD1\x45\xAE\x39\x19\xB4\xFF\x5D\xF1\x45\x7B\xE0\xFE\x72\xED\x11\x92\x8F\x61\x41\x4F\x02\x00\xF2\x76\x6F\x7C" "\x79\xA2\xE5\x52\x20\x5D\x97\x5E\xFE\x39\xAE\x21\x10\xFB\x35\xF4\x80\x81\x41\x13\xDD\xE8\x5F\xCA\x1E\x4F\xF8\x9B\xB2\x68\xFB\x28"; FileSource keys("esig1536.dat", true, new HexDecoder); ESIGN<SHA>::Signer signer(keys); ESIGN<SHA>::Verifier verifier(signer); fail = !SignatureValidate(signer, verifier); pass = pass && !fail; fail = !verifier.VerifyMessage((byte *)plain, strlen(plain), signature); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "verification check against test vector\n"; cout << "Generating signature key from seed..." << endl; InvertibleESIGNFunction priv; priv.GenerateRandom(GlobalRNG(), MakeParameters("Seed", ConstByteArrayParameter((const byte *)"test", 4))("KeySize", 3*512)); fail = !SignatureValidate(signer, verifier); pass = pass && !fail; return pass; }<|fim▁end|>
cout << setw(2) << setfill('0') << hex << (int)buf[j]; cout << endl;
<|file_name|>notebook_utils.py<|end_file_name|><|fim▁begin|># Copyright 2016 Google Inc. 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 #<|fim▁hole|># 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. """Python functions which run only within a Jupyter notebook.""" # internal imports import IPython from magenta.music import midi_synth _DEFAULT_SAMPLE_RATE = 44100 def play_sequence(sequence, synth=midi_synth.synthesize, sample_rate=_DEFAULT_SAMPLE_RATE, **synth_args): """Creates an interactive player for a synthesized note sequence. This function should only be called from a Jupyter notebook. Args: sequence: A music_pb2.NoteSequence to synthesize and play. synth: A synthesis function that takes a sequence and sample rate as input. sample_rate: The sample rate at which to synthesize. **synth_args: Additional keyword arguments to pass to the synth function. """ array_of_floats = synth(sequence, sample_rate=sample_rate, **synth_args) IPython.display.display(IPython.display.Audio(array_of_floats, rate=sample_rate))<|fim▁end|>
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software
<|file_name|>instr_vpmovm2q.rs<|end_file_name|><|fim▁begin|>use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn vpmovm2q_1() { run_test(&Instruction { mnemonic: Mnemonic::VPMOVM2Q, operand1: Some(Direct(XMM5)), operand2: Some(Direct(K1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 242, 254, 8, 56, 233], OperandSize::Dword) } #[test] fn vpmovm2q_2() { run_test(&Instruction { mnemonic: Mnemonic::VPMOVM2Q, operand1: Some(Direct(XMM1)), operand2: Some(Direct(K1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 242, 254, 8, 56, 201], OperandSize::Qword) } #[test] fn vpmovm2q_3() { run_test(&Instruction { mnemonic: Mnemonic::VPMOVM2Q, operand1: Some(Direct(YMM6)), operand2: Some(Direct(K1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 242, 254, 40, 56, 241], OperandSize::Dword) } #[test] fn vpmovm2q_4() { run_test(&Instruction { mnemonic: Mnemonic::VPMOVM2Q, operand1: Some(Direct(YMM9)), operand2: Some(Direct(K1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 114, 254, 40, 56, 201], OperandSize::Qword) }<|fim▁hole|> run_test(&Instruction { mnemonic: Mnemonic::VPMOVM2Q, operand1: Some(Direct(ZMM2)), operand2: Some(Direct(K7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 242, 254, 72, 56, 215], OperandSize::Dword) } #[test] fn vpmovm2q_6() { run_test(&Instruction { mnemonic: Mnemonic::VPMOVM2Q, operand1: Some(Direct(ZMM4)), operand2: Some(Direct(K7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 242, 254, 72, 56, 231], OperandSize::Qword) }<|fim▁end|>
#[test] fn vpmovm2q_5() {
<|file_name|>Base64.java<|end_file_name|><|fim▁begin|>/** * Encodes and decodes to and from Base64 notation. * * <p> * Change Log: * </p> * <ul> * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added * some convenience methods for reading and writing to and from files.</li> * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems * with other encodings (like EBCDIC).</li> * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the * encoded data was a single byte.</li> * <li>v2.0 - I got rid of methods that used booleans to set options. * Now everything is more consolidated and cleaner. The code now detects * when data that's being decoded is gzip-compressed and will decompress it * automatically. Generally things are cleaner. You'll probably have to * change some method calls that you were making to support the new * options format (<tt>int</tt>s that you "OR" together).</li> * <li>v1.5.1 - Fixed bug when decompressing and decoding to a * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>. * Added the ability to "suspend" encoding in the Output Stream so * you can turn on and off the encoding if you need to embed base64 * data in an otherwise "normal" stream (like an XML file).</li> * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself. * This helps when using GZIP streams. * Added the ability to GZip-compress objects before encoding them.</li> * <li>v1.4 - Added helper methods to read/write files.</li> * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li> * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream * where last buffer being read, if not completely full, was not returned.</li> * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li> * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> * </ul> * * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author [email protected] * @version 2.1 */ public class Base64 { /* ******** P U B L I C F I E L D S ******** */ /** No options specified. Value is zero. */ public final static int NO_OPTIONS = 0; /** Specify encoding. */ public final static int ENCODE = 1; /** Specify decoding. */ public final static int DECODE = 0; /** Specify that data should be gzip-compressed. */ public final static int GZIP = 2; /** Don't break lines when encoding (violates strict Base64 specification) */ public final static int DONT_BREAK_LINES = 8; /* ******** P R I V A T E F I E L D S ******** */ /** Maximum line length (76) of Base64 output. */ private final static int MAX_LINE_LENGTH = 76; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte)'='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte)'\n'; /** Preferred encoding. */ private final static String PREFERRED_ENCODING = "UTF-8"; /** The 64 valid Base64 values. */ private final static byte[] ALPHABET; private final static byte[] _NATIVE_ALPHABET = /* May be something funny like EBCDIC */ { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; /** Determine which ALPHABET to use. */ static { byte[] __bytes; try { __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes( PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException use) { __bytes = _NATIVE_ALPHABET; // Fall back to native encoding } // end catch ALPHABET = __bytes; } // end static /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,-9,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9 // Decimal 123 - 126 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; // I think I end up not using the BAD_ENCODING indicator. //private final static byte BAD_ENCODING = -9; // Indicates error in encoding private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding /** Defeats instantiation. */ private Base64(){} /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to the first three bytes of array <var>threeBytes</var> * and returns a four-byte array in Base64 notation. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * The array <var>threeBytes</var> needs only be as big as * <var>numSigBytes</var>. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes ) { encode3to4( threeBytes, 0, numSigBytes, b4, 0 ); return b4; } // end encode3to4 /** * Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset ) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); switch( numSigBytes ) { case 3: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; return destination; case 2: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; case 1: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = EQUALS_SIGN; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; default: return destination; } // end switch<|fim▁hole|> /** * Serializes an object and returns the Base64-encoded * version of that serialized object. If the object * cannot be serialized or there is another error, * the method will return <tt>null</tt>. * The object is not GZip-compressed before being encoded. * * @param serializableObject The object to encode * @return The Base64-encoded object * @since 1.4 */ public static String encodeObject( java.io.Serializable serializableObject ) { return encodeObject( serializableObject, NO_OPTIONS ); } // end encodeObject /** * Serializes an object and returns the Base64-encoded * version of that serialized object. If the object * cannot be serialized or there is another error, * the method will return <tt>null</tt>. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or * <p> * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * @param serializableObject The object to encode * @param options Specified options * @return The Base64-encoded object * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeObject( java.io.Serializable serializableObject, int options ) { // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.io.ObjectOutputStream oos = null; java.util.zip.GZIPOutputStream gzos = null; // Isolate options int gzip = (options & GZIP); int dontBreakLines = (options & DONT_BREAK_LINES); try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines ); // GZip? if( gzip == GZIP ) { gzos = new java.util.zip.GZIPOutputStream( b64os ); oos = new java.io.ObjectOutputStream( gzos ); } // end if: gzip else oos = new java.io.ObjectOutputStream( b64os ); oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { e.printStackTrace(); return null; } // end catch finally { try{ oos.close(); } catch( Exception e ){} try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); } // end catch } // end encode /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @since 1.4 */ public static String encodeBytes( byte[] source ) { return encodeBytes( source, 0, source.length, NO_OPTIONS ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * * @param source The data to convert * @param options Specified options * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes( byte[] source, int options ) { return encodeBytes( source, 0, source.length, options ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @since 1.4 */ public static String encodeBytes( byte[] source, int off, int len ) { return encodeBytes( source, off, len, NO_OPTIONS ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes( byte[] source, int off, int len, int options ) { // Isolate options int dontBreakLines = ( options & DONT_BREAK_LINES ); int gzip = ( options & GZIP ); // Compress? if( gzip == GZIP ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); return null; } // end catch finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); } // end catch } // end if: compress // Else, don't compress. Better not to use streams at all then. else { // Convert option to boolean in way that code likes it. boolean breakLines = dontBreakLines == 0; int len43 = len * 4 / 3; byte[] outBuff = new byte[ ( len43 ) // Main 4:3 + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e ); lineLength += 4; if( breakLines && lineLength == MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e ); e += 4; } // end if: some padding needed // Return value according to relevant encoding. try { return new String( outBuff, 0, e, PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( outBuff, 0, e ); } // end catch } // end else: don't compress } // end encodeBytes /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset ) { // Example: Dk== if( source[ srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); return 1; } // Example: DkL= else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); return 2; } // Example: DkLE else { try{ // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; }catch( Exception e){ System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) ); System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) ); System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) ); System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) ); return -1; } //e nd catch } } // end decodeToBytes /** * Very low-level access to decoding ASCII characters in * the form of a byte array. Does not support automatically * gunzipping or any other "fancy" features. * * @param source The Base64 encoded data * @param off The offset of where to begin decoding * @param len The length of characters to decode * @return decoded data * @since 1.3 */ public static byte[] decode( byte[] source, int off, int len ) { int len34 = len * 3 / 4; byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for( i = off; i < off+len; i++ ) { sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits sbiDecode = DECODABET[ sbiCrop ]; if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = sbiCrop; if( b4Posn > 3 ) { outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn ); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( sbiCrop == EQUALS_SIGN ) break; } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { //System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" ); return null; } // end else: } // each input character byte[] out = new byte[ outBuffPosn ]; System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); return out; } // end decode /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @return the decoded data * @since 1.4 */ public static byte[] decode( String s ) { byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) if( bytes != null && bytes.length >= 4 ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { // Just return originally-decoded bytes } // end catch finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * * @param encodedObject The Base64 data to decode * @return The decoded and deserialized object * @since 1.5 */ public static Object decodeToObject( String encodedObject ) { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); ois = new java.io.ObjectInputStream( bais ); obj = ois.readObject(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); obj = null; } // end catch catch( java.lang.ClassNotFoundException e ) { e.printStackTrace(); obj = null; } // end catch finally { try{ bais.close(); } catch( Exception e ){} try{ ois.close(); } catch( Exception e ){} } // end finally return obj; } // end decodeObject /** * Convenience method for encoding data to a file. * * @param dataToEncode byte array of data to encode in base64 form * @param filename Filename for saving encoded data * @return <tt>true</tt> if successful, <tt>false</tt> otherwise * * @since 2.1 */ public static boolean encodeToFile( byte[] dataToEncode, String filename ) { boolean success = false; Base64.OutputStream bos = null; try { bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.ENCODE ); bos.write( dataToEncode ); success = true; } // end try catch( java.io.IOException e ) { success = false; } // end catch: IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally return success; } // end encodeToFile /** * Convenience method for decoding data to a file. * * @param dataToDecode Base64-encoded data as a string * @param filename Filename for saving decoded data * @return <tt>true</tt> if successful, <tt>false</tt> otherwise * * @since 2.1 */ public static boolean decodeToFile( String dataToDecode, String filename ) { boolean success = false; Base64.OutputStream bos = null; try { bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.DECODE ); bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); success = true; } // end try catch( java.io.IOException e ) { success = false; } // end catch: IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally return success; } // end decodeToFile /** * Convenience method for reading a base64-encoded * file and decoding it. * * @param filename Filename for reading encoded data * @return decoded byte array or null if unsuccessful * * @since 2.1 */ public static byte[] decodeFromFile( String filename ) { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = null; int length = 0; int numBytes = 0; // Check for size of file if( file.length() > Integer.MAX_VALUE ) { System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." ); return null; } // end if: file too big for int index buffer = new byte[ (int)file.length() ]; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.DECODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) length += numBytes; // Save in a variable to return decodedData = new byte[ length ]; System.arraycopy( buffer, 0, decodedData, 0, length ); } // end try catch( java.io.IOException e ) { System.err.println( "Error decoding from file " + filename ); } // end catch: IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return decodedData; } // end decodeFromFile /** * Convenience method for reading a binary file * and base64-encoding it. * * @param filename Filename for reading binary data * @return base64-encoded string or null if unsuccessful * * @since 2.1 */ public static String encodeFromFile( String filename ) { String encodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = new byte[ (int)(file.length() * 1.4) ]; int length = 0; int numBytes = 0; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.ENCODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) length += numBytes; // Save in a variable to return encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); } // end try catch( java.io.IOException e ) { System.err.println( "Error encoding from file " + filename ); } // end catch: IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return encodedData; } // end encodeFromFile /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ /** * A {@link Base64.InputStream} will read data from another * <tt>java.io.InputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class InputStream extends java.io.FilterInputStream { private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters /** * Constructs a {@link Base64.InputStream} in DECODE mode. * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @since 1.3 */ public InputStream( java.io.InputStream in ) { this( in, DECODE ); } // end constructor /** * Constructs a {@link Base64.InputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> * * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @param options Specified options * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public InputStream( java.io.InputStream in, int options ) { super( in ); this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; this.encode = (options & ENCODE) == ENCODE; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[ bufferLength ]; this.position = -1; this.lineLength = 0; } // end constructor /** * Reads enough of the input stream to convert * to/from Base64 and returns the next byte. * * @return next byte * @since 1.3 */ public int read() throws java.io.IOException { // Do we need to get data? if( position < 0 ) { if( encode ) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for( int i = 0; i < 3; i++ ) { try { int b = in.read(); // If end of stream, b is -1. if( b >= 0 ) { b3[i] = (byte)b; numBinaryBytes++; } // end if: not end of stream } // end try: read catch( java.io.IOException e ) { // Only a problem if we got no data at all. if( i == 0 ) throw e; } // end catch } // end for: each needed input byte if( numBinaryBytes > 0 ) { encode3to4( b3, 0, numBinaryBytes, buffer, 0 ); position = 0; numSigBytes = 4; } // end if: got data else { return -1; } // end else } // end if: encoding // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for( i = 0; i < 4; i++ ) { // Read four "meaningful" bytes: int b = 0; do{ b = in.read(); } while( b >= 0 && DECODABET[ b & 0x7f ] <= WHITE_SPACE_ENC ); if( b < 0 ) break; // Reads a -1 if end of stream b4[i] = (byte)b; } // end for: each needed input byte if( i == 4 ) { numSigBytes = decode4to3( b4, 0, buffer, 0 ); position = 0; } // end if: got four characters else if( i == 0 ){ return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException( "Improperly padded Base64 input." ); } // end } // end else: decode } // end else: get data // Got data? if( position >= 0 ) { // End of relevant data? if( /*!encode &&*/ position >= numSigBytes ) return -1; if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) { lineLength = 0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[ position++ ]; if( position >= bufferLength ) position = -1; return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { // When JDK1.4 is more accepted, use an assertion here. throw new java.io.IOException( "Error in Base64 code reading stream." ); } // end else } // end read /** * Calls {@link #read()} repeatedly until the end of stream * is reached or <var>len</var> bytes are read. * Returns number of bytes read into array or -1 if * end of stream is encountered. * * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ public int read( byte[] dest, int off, int len ) throws java.io.IOException { int i; int b; for( i = 0; i < len; i++ ) { b = read(); //if( b < 0 && i == 0 ) // return -1; if( b >= 0 ) dest[off + i] = (byte)b; else if( i == 0 ) return -1; else break; // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ /** * A {@link Base64.OutputStream} will write data to another * <tt>java.io.OutputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class OutputStream extends java.io.FilterOutputStream { private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; /** * Constructs a {@link Base64.OutputStream} in ENCODE mode. * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @since 1.3 */ public OutputStream( java.io.OutputStream out ) { this( out, ENCODE ); } // end constructor /** * Constructs a {@link Base64.OutputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 1.3 */ public OutputStream( java.io.OutputStream out, int options ) { super( out ); this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; this.encode = (options & ENCODE) == ENCODE; this.bufferLength = encode ? 3 : 4; this.buffer = new byte[ bufferLength ]; this.position = 0; this.lineLength = 0; this.suspendEncoding = false; this.b4 = new byte[4]; } // end constructor /** * Writes the byte to the output stream after * converting to/from Base64 notation. * When encoding, bytes are buffered three * at a time before the output stream actually * gets a write() call. * When decoding, bytes are buffered four * at a time. * * @param theByte the byte to write * @since 1.3 */ public void write(int theByte) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { super.out.write( theByte ); return; } // end if: supsended // Encode? if( encode ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) // Enough to encode. { out.write( encode3to4( b4, buffer, bufferLength ) ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { out.write( NEW_LINE ); lineLength = 0; } // end if: end of line position = 0; } // end if: enough to output } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? if( DECODABET[ theByte & 0x7f ] > WHITE_SPACE_ENC ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) // Enough to output. { int len = Base64.decode4to3( buffer, 0, b4, 0 ); out.write( b4, 0, len ); //out.write( Base64.decode4to3( buffer ) ); position = 0; } // end if: enough to output } // end if: meaningful base64 character else if( DECODABET[ theByte & 0x7f ] != WHITE_SPACE_ENC ) { throw new java.io.IOException( "Invalid character in Base64 data." ); } // end else: not white space either } // end else: decoding } // end write /** * Calls {@link #write(int)} repeatedly until <var>len</var> * bytes are written. * * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @since 1.3 */ public void write( byte[] theBytes, int off, int len ) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { super.out.write( theBytes, off, len ); return; } // end if: supsended for( int i = 0; i < len; i++ ) { write( theBytes[ off + i ] ); } // end for: each byte written } // end write /** * Method added by PHIL. [Thanks, PHIL. -Rob] * This pads the buffer without closing the stream. */ public void flushBase64() throws java.io.IOException { if( position > 0 ) { if( encode ) { out.write( encode3to4( b4, buffer, position ) ); position = 0; } // end if: encoding else { throw new java.io.IOException( "Base64 input not properly padded." ); } // end else: decoding } // end if: buffer partially full } // end flush /** * Flushes and closes (I think, in the superclass) the stream. * * @since 1.3 */ public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer = null; out = null; } // end close /** * Suspends encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. * * @since 1.5.1 */ public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding = true; } // end suspendEncoding /** * Resumes encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; } // end resumeEncoding } // end inner class OutputStream } // end class Base64<|fim▁end|>
} // end encode3to4
<|file_name|>test_optimizers_by_linear_model.py<|end_file_name|><|fim▁begin|>import unittest import numpy as np import six import chainer from chainer import cuda import chainer.functions as F from chainer import optimizers from chainer import testing from chainer.testing import attr from chainer.testing import condition if cuda.available: cuda.init() class LinearModel(object): UNIT_NUM = 10 BATCH_SIZE = 32 EPOCH = 100 def __init__(self, optimizer): self.model = chainer.FunctionSet( l=F.Linear(self.UNIT_NUM, 2) ) self.optimizer = optimizer # true parameters self.w = np.random.uniform(-1, 1, (self.UNIT_NUM, 1)).astype(np.float32) self.b = np.random.uniform(-1, 1, (1, )).astype(np.float32) def _train_linear_classifier(self, model, optimizer, gpu): def _make_label(x): a = (np.dot(x, self.w) + self.b).reshape((self.BATCH_SIZE, )) t = np.empty_like(a).astype(np.int32) t[a >= 0] = 0 t[a < 0] = 1 return t def _make_dataset(batch_size, unit_num, gpu): x_data = np.random.uniform( -1, 1, (batch_size, unit_num)).astype(np.float32) t_data = _make_label(x_data) if gpu: x_data = cuda.to_gpu(x_data) t_data = cuda.to_gpu(t_data) x = chainer.Variable(x_data) t = chainer.Variable(t_data) return x, t for epoch in six.moves.range(self.EPOCH): x, t = _make_dataset(self.BATCH_SIZE, self.UNIT_NUM, gpu) optimizer.zero_grads() y = model.l(x) loss = F.softmax_cross_entropy(y, t) loss.backward() optimizer.update() x_test, t_test = _make_dataset(self.BATCH_SIZE, self.UNIT_NUM, gpu) y_test = model.l(x_test) return F.accuracy(y_test, t_test) def _accuracy_cpu(self): self.optimizer.setup(self.model) return self._train_linear_classifier(self.model, self.optimizer, False) def _accuracy_gpu(self): model = self.model optimizer = self.optimizer model.to_gpu() optimizer.setup(model) return self._train_linear_classifier(model, optimizer, True) def accuracy(self, gpu): if gpu: return cuda.to_cpu(self._accuracy_gpu().data) else: return self._accuracy_cpu().data class OptimizerTestBase(object): def create(self): raise NotImplementedError() def setUp(self): self.model = LinearModel(self.create()) @condition.retry(10) def test_linear_model_cpu(self): self.assertGreater(self.model.accuracy(False), 0.9) @attr.gpu @condition.retry(10) def test_linear_model_gpu(self): self.assertGreater(self.model.accuracy(True), 0.9) def test_initialize(self): model = self.model.model assert isinstance(model, chainer.FunctionSet) optimizer = self.create() optimizer.setup(model) self.assertEqual(len(optimizer.tuples), len(model.parameters)) msg = "'params_grads' must have 'parameters' and 'gradients'" with self.assertRaisesRegexp(ValueError, msg): optimizer.setup('xxx') class TestAdaDelta(OptimizerTestBase, unittest.TestCase): def create(self): return optimizers.AdaDelta(eps=1e-5) class TestAdaGrad(OptimizerTestBase, unittest.TestCase): def create(self): return optimizers.AdaGrad(0.1) class TestAdam(OptimizerTestBase, unittest.TestCase): def create(self): return optimizers.Adam(0.1) class TestMomentumSGD(OptimizerTestBase, unittest.TestCase): def create(self): return optimizers.MomentumSGD(0.1) class TestRMSprop(OptimizerTestBase, unittest.TestCase): def create(self): return optimizers.RMSprop(0.1) class TestRMSpropGraves(OptimizerTestBase, unittest.TestCase): def create(self): return optimizers.RMSpropGraves(0.1) <|fim▁hole|> testing.run_module(__name__, __file__)<|fim▁end|>
class TestSGD(OptimizerTestBase, unittest.TestCase): def create(self): return optimizers.SGD(0.1)
<|file_name|>docs.py<|end_file_name|><|fim▁begin|>from fabric.api import task, local, run from fabric.context_managers import lcd import settings @task(default=True) def build(): """ (Default) Build Sphinx HTML documentation """ with lcd('docs'): local('make html') @task() def deploy(): """ Upload docs to server<|fim▁hole|> local("rsync -avz --rsync-path='sudo rsync' -e 'ssh -p 2222 -i .vagrant/machines/web/virtualbox/private_key -o StrictHostKeyChecking=no' docs/build/html/ %s@%s:%s " % ('vagrant', 'localhost', destination)) elif settings.environment == 'ci': local("rsync -avz --rsync-path='sudo rsync' -e 'ssh -p 2222 -i /var/go/id_rsa_web -o StrictHostKeyChecking=no' docs/build/html/ %s@%s:%s " % ('vagrant', '192.168.10.10', destination))<|fim▁end|>
""" build() destination = '/usr/share/nginx/localhost/mysite/docs/build/html' if settings.environment == 'vagrant':
<|file_name|>element.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Element nodes. use app_units::Au; use cssparser::Color; use devtools_traits::AttrInfo; use dom::activation::Activatable; use dom::attr::AttrValue; use dom::attr::{Attr, AttrHelpersForLayout}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use dom::bindings::codegen::Bindings::ElementBinding; use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods; use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; use dom::bindings::js::{JS, LayoutJS, MutNullableHeap}; use dom::bindings::js::{Root, RootedReference}; use dom::bindings::trace::JSTraceable; use dom::bindings::xmlname::XMLName::InvalidXMLName; use dom::bindings::xmlname::{namespace_from_domstring, validate_and_extract, xml_name_type}; use dom::characterdata::CharacterData; use dom::create::create_element; use dom::document::{Document, LayoutDocumentHelpers}; use dom::domrect::DOMRect; use dom::domrectlist::DOMRectList; use dom::domtokenlist::DOMTokenList; use dom::event::Event; use dom::htmlanchorelement::HTMLAnchorElement; use dom::htmlbodyelement::{HTMLBodyElement, HTMLBodyElementLayoutHelpers}; use dom::htmlbuttonelement::HTMLButtonElement; use dom::htmlcollection::HTMLCollection; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlfontelement::{HTMLFontElement, HTMLFontElementLayoutHelpers}; use dom::htmlhrelement::{HTMLHRElement, HTMLHRLayoutHelpers}; use dom::htmliframeelement::{HTMLIFrameElement, HTMLIFrameElementLayoutMethods}; use dom::htmlimageelement::{HTMLImageElement, LayoutHTMLImageElementHelpers}; use dom::htmlinputelement::{HTMLInputElement, LayoutHTMLInputElementHelpers}; use dom::htmllabelelement::HTMLLabelElement; use dom::htmllegendelement::HTMLLegendElement; use dom::htmlobjectelement::HTMLObjectElement; use dom::htmloptgroupelement::HTMLOptGroupElement; use dom::htmlselectelement::HTMLSelectElement; use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementLayoutHelpers}; use dom::htmltableelement::{HTMLTableElement, HTMLTableElementLayoutHelpers}; use dom::htmltablerowelement::{HTMLTableRowElement, HTMLTableRowElementLayoutHelpers}; use dom::htmltablesectionelement::{HTMLTableSectionElement, HTMLTableSectionElementLayoutHelpers}; use dom::htmltemplateelement::HTMLTemplateElement; use dom::htmltextareaelement::{HTMLTextAreaElement, LayoutHTMLTextAreaElementHelpers}; use dom::namednodemap::NamedNodeMap; use dom::node::{CLICK_IN_PROGRESS, ChildrenMutation, LayoutNodeHelpers, Node}; use dom::node::{NodeDamage, SEQUENTIALLY_FOCUSABLE, UnbindContext}; use dom::node::{document_from_node, window_from_node}; use dom::nodelist::NodeList; use dom::text::Text; use dom::validation::Validatable; use dom::virtualmethods::{VirtualMethods, vtable_for}; use html5ever::serialize; use html5ever::serialize::SerializeOpts; use html5ever::serialize::TraversalScope; use html5ever::serialize::TraversalScope::{ChildrenOnly, IncludeNode}; use html5ever::tree_builder::{LimitedQuirks, NoQuirks, Quirks}; use ref_filter_map::ref_filter_map; use selectors::matching::{DeclarationBlock, ElementFlags, matches}; use selectors::matching::{HAS_SLOW_SELECTOR, HAS_EDGE_CHILD_SELECTOR, HAS_SLOW_SELECTOR_LATER_SIBLINGS}; use selectors::matching::{common_style_affecting_attributes, rare_style_affecting_attributes}; use selectors::parser::{AttrSelector, NamespaceConstraint, parse_author_origin_selector_list_from_str}; use smallvec::VecLike; use std::ascii::AsciiExt; use std::borrow::Cow; use std::cell::{Cell, Ref}; use std::default::Default; use std::mem; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use string_cache::{Atom, Namespace, QualName}; use style::element_state::*; use style::error_reporting::ParseErrorReporter; use style::properties::DeclaredValue; use style::properties::longhands::{self, background_image, border_spacing, font_family, font_size}; use style::properties::{PropertyDeclaration, PropertyDeclarationBlock, parse_style_attribute}; use style::selector_impl::{NonTSPseudoClass, ServoSelectorImpl}; use style::values::CSSFloat; use style::values::specified::{self, CSSColor, CSSRGBA, LengthOrPercentage}; use util::str::{DOMString, LengthOrPercentageOrAuto}; // TODO: Update focus state when the top-level browsing context gains or loses system focus, // and when the element enters or leaves a browsing context container. // https://html.spec.whatwg.org/multipage/#selector-focus #[dom_struct] pub struct Element { node: Node, local_name: Atom, namespace: Namespace, prefix: Option<DOMString>, attrs: DOMRefCell<Vec<JS<Attr>>>, id_attribute: DOMRefCell<Option<Atom>>, style_attribute: DOMRefCell<Option<PropertyDeclarationBlock>>, attr_list: MutNullableHeap<JS<NamedNodeMap>>, class_list: MutNullableHeap<JS<DOMTokenList>>, state: Cell<ElementState>, atomic_flags: AtomicElementFlags, } #[derive(PartialEq, HeapSizeOf)] pub enum ElementCreator { ParserCreated, ScriptCreated, } // // Element methods // impl Element { pub fn create(name: QualName, prefix: Option<Atom>, document: &Document, creator: ElementCreator) -> Root<Element> { create_element(name, prefix, document, creator) } pub fn new_inherited(local_name: Atom, namespace: Namespace, prefix: Option<DOMString>, document: &Document) -> Element { Element::new_inherited_with_state(ElementState::empty(), local_name, namespace, prefix, document) } pub fn new_inherited_with_state(state: ElementState, local_name: Atom, namespace: Namespace, prefix: Option<DOMString>, document: &Document) -> Element { Element { node: Node::new_inherited(document), local_name: local_name, namespace: namespace, prefix: prefix, attrs: DOMRefCell::new(vec![]), id_attribute: DOMRefCell::new(None), style_attribute: DOMRefCell::new(None), attr_list: Default::default(), class_list: Default::default(), state: Cell::new(state), atomic_flags: AtomicElementFlags::new(), } } pub fn new(local_name: Atom, namespace: Namespace, prefix: Option<DOMString>, document: &Document) -> Root<Element> { Node::reflect_node( box Element::new_inherited(local_name, namespace, prefix, document), document, ElementBinding::Wrap) } } #[allow(unsafe_code)] pub trait RawLayoutElementHelpers { unsafe fn get_attr_for_layout<'a>(&'a self, namespace: &Namespace, name: &Atom) -> Option<&'a AttrValue>; unsafe fn get_attr_val_for_layout<'a>(&'a self, namespace: &Namespace, name: &Atom) -> Option<&'a str>; unsafe fn get_attr_vals_for_layout<'a>(&'a self, name: &Atom) -> Vec<&'a str>; } #[inline] #[allow(unsafe_code)] pub unsafe fn get_attr_for_layout<'a>(elem: &'a Element, namespace: &Namespace, name: &Atom) -> Option<LayoutJS<Attr>> { // cast to point to T in RefCell<T> directly let attrs = elem.attrs.borrow_for_layout(); attrs.iter().find(|attr| { let attr = attr.to_layout(); *name == attr.local_name_atom_forever() && (*attr.unsafe_get()).namespace() == namespace }).map(|attr| attr.to_layout()) } #[allow(unsafe_code)] impl RawLayoutElementHelpers for Element { #[inline] unsafe fn get_attr_for_layout<'a>(&'a self, namespace: &Namespace, name: &Atom) -> Option<&'a AttrValue> { get_attr_for_layout(self, namespace, name).map(|attr| { attr.value_forever() }) } unsafe fn get_attr_val_for_layout<'a>(&'a self, namespace: &Namespace, name: &Atom) -> Option<&'a str> { get_attr_for_layout(self, namespace, name).map(|attr| { attr.value_ref_forever() }) } #[inline] unsafe fn get_attr_vals_for_layout<'a>(&'a self, name: &Atom) -> Vec<&'a str> { let attrs = self.attrs.borrow_for_layout(); attrs.iter().filter_map(|attr| { let attr = attr.to_layout(); if *name == attr.local_name_atom_forever() { Some(attr.value_ref_forever()) } else { None } }).collect() } } pub trait LayoutElementHelpers { #[allow(unsafe_code)] unsafe fn has_class_for_layout(&self, name: &Atom) -> bool; #[allow(unsafe_code)] unsafe fn get_classes_for_layout(&self) -> Option<&'static [Atom]>; #[allow(unsafe_code)] unsafe fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, &mut V) where V: VecLike<DeclarationBlock<Vec<PropertyDeclaration>>>; #[allow(unsafe_code)] unsafe fn get_colspan(self) -> u32; #[allow(unsafe_code)] unsafe fn html_element_in_html_document_for_layout(&self) -> bool; fn id_attribute(&self) -> *const Option<Atom>; fn style_attribute(&self) -> *const Option<PropertyDeclarationBlock>; fn local_name(&self) -> &Atom; fn namespace(&self) -> &Namespace; fn get_checked_state_for_layout(&self) -> bool; fn get_indeterminate_state_for_layout(&self) -> bool; fn get_state_for_layout(&self) -> ElementState; fn insert_atomic_flags(&self, flags: ElementFlags); } impl LayoutElementHelpers for LayoutJS<Element> { #[allow(unsafe_code)] #[inline] unsafe fn has_class_for_layout(&self, name: &Atom) -> bool { get_attr_for_layout(&*self.unsafe_get(), &ns!(), &atom!("class")).map_or(false, |attr| { attr.value_tokens_forever().unwrap().iter().any(|atom| atom == name) }) } #[allow(unsafe_code)] #[inline] unsafe fn get_classes_for_layout(&self) -> Option<&'static [Atom]> { get_attr_for_layout(&*self.unsafe_get(), &ns!(), &atom!("class")) .map(|attr| attr.value_tokens_forever().unwrap()) } #[allow(unsafe_code)] unsafe fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, hints: &mut V) where V: VecLike<DeclarationBlock<Vec<PropertyDeclaration>>> { #[inline] fn from_declaration(rule: PropertyDeclaration) -> DeclarationBlock<Vec<PropertyDeclaration>> { DeclarationBlock::from_declarations(Arc::new(vec![rule])) } let bgcolor = if let Some(this) = self.downcast::<HTMLBodyElement>() { this.get_background_color() } else if let Some(this) = self.downcast::<HTMLTableElement>() { this.get_background_color() } else if let Some(this) = self.downcast::<HTMLTableCellElement>() { this.get_background_color() } else if let Some(this) = self.downcast::<HTMLTableRowElement>() { this.get_background_color() } else if let Some(this) = self.downcast::<HTMLTableSectionElement>() { this.get_background_color() } else { None }; if let Some(color) = bgcolor { hints.push(from_declaration( PropertyDeclaration::BackgroundColor(DeclaredValue::Value( CSSColor { parsed: Color::RGBA(color), authored: None })))); } let background = if let Some(this) = self.downcast::<HTMLBodyElement>() { this.get_background() } else { None }; if let Some(url) = background { hints.push(from_declaration( PropertyDeclaration::BackgroundImage(DeclaredValue::Value( background_image::SpecifiedValue(Some(specified::Image::Url(url))))))); } let color = if let Some(this) = self.downcast::<HTMLFontElement>() { this.get_color() } else if let Some(this) = self.downcast::<HTMLBodyElement>() { // https://html.spec.whatwg.org/multipage/#the-page:the-body-element-20 this.get_color() } else if let Some(this) = self.downcast::<HTMLHRElement>() { // https://html.spec.whatwg.org/multipage/#the-hr-element-2:presentational-hints-5 this.get_color() } else { None }; if let Some(color) = color { hints.push(from_declaration( PropertyDeclaration::Color(DeclaredValue::Value(CSSRGBA { parsed: color, authored: None, })))); } let font_family = if let Some(this) = self.downcast::<HTMLFontElement>() { this.get_face() } else { None }; if let Some(font_family) = font_family { hints.push(from_declaration( PropertyDeclaration::FontFamily( DeclaredValue::Value( font_family::computed_value::T(vec![ font_family::computed_value::FontFamily::from_atom( font_family)]))))); } let font_size = if let Some(this) = self.downcast::<HTMLFontElement>() { this.get_size() } else { None }; if let Some(font_size) = font_size { hints.push(from_declaration( PropertyDeclaration::FontSize( DeclaredValue::Value( font_size::SpecifiedValue( LengthOrPercentage::Length(font_size)))))) } let cellspacing = if let Some(this) = self.downcast::<HTMLTableElement>() { this.get_cellspacing() } else { None }; if let Some(cellspacing) = cellspacing { let width_value = specified::Length::Absolute(Au::from_px(cellspacing as i32)); hints.push(from_declaration( PropertyDeclaration::BorderSpacing(DeclaredValue::Value( border_spacing::SpecifiedValue { horizontal: width_value, vertical: width_value, })))); } let size = if let Some(this) = self.downcast::<HTMLInputElement>() { // FIXME(pcwalton): More use of atoms, please! match (*self.unsafe_get()).get_attr_val_for_layout(&ns!(), &atom!("type")) { // Not text entry widget Some("hidden") | Some("date") | Some("month") | Some("week") | Some("time") | Some("datetime-local") | Some("number") | Some("range") | Some("color") | Some("checkbox") | Some("radio") | Some("file") | Some("submit") | Some("image") | Some("reset") | Some("button") => { None }, // Others _ => { match this.size_for_layout() { 0 => None, s => Some(s as i32), } }, } } else { None }; if let Some(size) = size { let value = specified::Length::ServoCharacterWidth(specified::CharacterWidth(size)); hints.push(from_declaration( PropertyDeclaration::Width(DeclaredValue::Value( specified::LengthOrPercentageOrAuto::Length(value))))); } let width = if let Some(this) = self.downcast::<HTMLIFrameElement>() { this.get_width() } else if let Some(this) = self.downcast::<HTMLImageElement>() { this.get_width() } else if let Some(this) = self.downcast::<HTMLTableElement>() { this.get_width() } else if let Some(this) = self.downcast::<HTMLTableCellElement>() { this.get_width() } else if let Some(this) = self.downcast::<HTMLHRElement>() { // https://html.spec.whatwg.org/multipage/#the-hr-element-2:attr-hr-width this.get_width() } else { LengthOrPercentageOrAuto::Auto }; match width { LengthOrPercentageOrAuto::Auto => {} LengthOrPercentageOrAuto::Percentage(percentage) => { let width_value = specified::LengthOrPercentageOrAuto::Percentage(specified::Percentage(percentage)); hints.push(from_declaration( PropertyDeclaration::Width(DeclaredValue::Value(width_value)))); } LengthOrPercentageOrAuto::Length(length) => { let width_value = specified::LengthOrPercentageOrAuto::Length( specified::Length::Absolute(length)); hints.push(from_declaration( PropertyDeclaration::Width(DeclaredValue::Value(width_value)))); } } let height = if let Some(this) = self.downcast::<HTMLIFrameElement>() { this.get_height() } else if let Some(this) = self.downcast::<HTMLImageElement>() { this.get_height() } else { LengthOrPercentageOrAuto::Auto }; match height { LengthOrPercentageOrAuto::Auto => {} LengthOrPercentageOrAuto::Percentage(percentage) => { let height_value = specified::LengthOrPercentageOrAuto::Percentage(specified::Percentage(percentage)); hints.push(from_declaration( PropertyDeclaration::Height(DeclaredValue::Value(height_value)))); } LengthOrPercentageOrAuto::Length(length) => { let height_value = specified::LengthOrPercentageOrAuto::Length( specified::Length::Absolute(length)); hints.push(from_declaration( PropertyDeclaration::Height(DeclaredValue::Value(height_value)))); } } let cols = if let Some(this) = self.downcast::<HTMLTextAreaElement>() { match this.get_cols() { 0 => None, c => Some(c as i32), } } else { None }; if let Some(cols) = cols { // TODO(mttr) ServoCharacterWidth uses the size math for <input type="text">, but // the math for <textarea> is a little different since we need to take // scrollbar size into consideration (but we don't have a scrollbar yet!) // // https://html.spec.whatwg.org/multipage/#textarea-effective-width let value = specified::Length::ServoCharacterWidth(specified::CharacterWidth(cols)); hints.push(from_declaration( PropertyDeclaration::Width(DeclaredValue::Value( specified::LengthOrPercentageOrAuto::Length(value))))); } let rows = if let Some(this) = self.downcast::<HTMLTextAreaElement>() { match this.get_rows() { 0 => None, r => Some(r as i32), } } else { None }; if let Some(rows) = rows { // TODO(mttr) This should take scrollbar size into consideration. // // https://html.spec.whatwg.org/multipage/#textarea-effective-height let value = specified::Length::FontRelative(specified::FontRelativeLength::Em(rows as CSSFloat)); hints.push(from_declaration( PropertyDeclaration::Height(DeclaredValue::Value( specified::LengthOrPercentageOrAuto::Length(value))))); } let border = if let Some(this) = self.downcast::<HTMLTableElement>() { this.get_border() } else { None }; if let Some(border) = border { let width_value = specified::Length::Absolute(Au::from_px(border as i32)); hints.push(from_declaration( PropertyDeclaration::BorderTopWidth(DeclaredValue::Value( longhands::border_top_width::SpecifiedValue(width_value))))); hints.push(from_declaration( PropertyDeclaration::BorderLeftWidth(DeclaredValue::Value( longhands::border_left_width::SpecifiedValue(width_value))))); hints.push(from_declaration( PropertyDeclaration::BorderBottomWidth(DeclaredValue::Value( longhands::border_bottom_width::SpecifiedValue(width_value))))); hints.push(from_declaration( PropertyDeclaration::BorderRightWidth(DeclaredValue::Value( longhands::border_right_width::SpecifiedValue(width_value))))); } } #[allow(unsafe_code)] unsafe fn get_colspan(self) -> u32 { if let Some(this) = self.downcast::<HTMLTableCellElement>() { this.get_colspan().unwrap_or(1) } else { // Don't panic since `display` can cause this to be called on arbitrary // elements. 1 } } #[inline] #[allow(unsafe_code)] unsafe fn html_element_in_html_document_for_layout(&self) -> bool { if (*self.unsafe_get()).namespace != ns!(html) { return false; } self.upcast::<Node>().owner_doc_for_layout().is_html_document_for_layout() } #[allow(unsafe_code)] fn id_attribute(&self) -> *const Option<Atom> { unsafe { (*self.unsafe_get()).id_attribute.borrow_for_layout() } } #[allow(unsafe_code)] fn style_attribute(&self) -> *const Option<PropertyDeclarationBlock> { unsafe { (*self.unsafe_get()).style_attribute.borrow_for_layout() } } #[allow(unsafe_code)] fn local_name(&self) -> &Atom { unsafe { &(*self.unsafe_get()).local_name } } #[allow(unsafe_code)] fn namespace(&self) -> &Namespace { unsafe { &(*self.unsafe_get()).namespace } } #[inline] #[allow(unsafe_code)] fn get_checked_state_for_layout(&self) -> bool { // TODO option and menuitem can also have a checked state. match self.downcast::<HTMLInputElement>() { Some(input) => unsafe { input.checked_state_for_layout() }, None => false, } } #[inline] #[allow(unsafe_code)] fn get_indeterminate_state_for_layout(&self) -> bool { // TODO progress elements can also be matched with :indeterminate match self.downcast::<HTMLInputElement>() { Some(input) => unsafe { input.indeterminate_state_for_layout() }, None => false, } } #[inline] #[allow(unsafe_code)] fn get_state_for_layout(&self) -> ElementState { unsafe { (*self.unsafe_get()).state.get() } } #[inline] #[allow(unsafe_code)] fn insert_atomic_flags(&self, flags: ElementFlags) { unsafe { (*self.unsafe_get()).atomic_flags.insert(flags); } } } #[derive(PartialEq, Eq, Copy, Clone, HeapSizeOf)] pub enum StylePriority { Important, Normal, } impl Element { pub fn html_element_in_html_document(&self) -> bool { self.namespace == ns!(html) && self.upcast::<Node>().is_in_html_doc() } pub fn local_name(&self) -> &Atom { &self.local_name } pub fn parsed_name(&self, mut name: DOMString) -> Atom { if self.html_element_in_html_document() { name.make_ascii_lowercase(); } Atom::from(name) } pub fn namespace(&self) -> &Namespace { &self.namespace } pub fn prefix(&self) -> &Option<DOMString> { &self.prefix } pub fn attrs(&self) -> Ref<Vec<JS<Attr>>> { self.attrs.borrow() } pub fn style_attribute(&self) -> &DOMRefCell<Option<PropertyDeclarationBlock>> { &self.style_attribute } pub fn summarize(&self) -> Vec<AttrInfo> { self.attrs.borrow().iter() .map(|attr| attr.summarize()) .collect() } pub fn is_void(&self) -> bool { if self.namespace != ns!(html) { return false } match self.local_name { /* List of void elements from https://html.spec.whatwg.org/multipage/#html-fragment-serialisation-algorithm */ atom!("area") | atom!("base") | atom!("basefont") | atom!("bgsound") | atom!("br") | atom!("col") | atom!("embed") | atom!("frame") | atom!("hr") | atom!("img") | atom!("input") | atom!("keygen") | atom!("link") | atom!("menuitem") | atom!("meta") | atom!("param") | atom!("source") | atom!("track") | atom!("wbr") => true, _ => false } } pub fn remove_inline_style_property(&self, property: &str) { let mut inline_declarations = self.style_attribute.borrow_mut(); if let &mut Some(ref mut declarations) = &mut *inline_declarations { let index = declarations.normal .iter() .position(|decl| decl.matches(property)); if let Some(index) = index { Arc::make_mut(&mut declarations.normal).remove(index); return; } let index = declarations.important .iter() .position(|decl| decl.matches(property)); if let Some(index) = index { Arc::make_mut(&mut declarations.important).remove(index); return; } } } pub fn update_inline_style(&self, property_decl: PropertyDeclaration, style_priority: StylePriority) { let mut inline_declarations = self.style_attribute().borrow_mut(); if let &mut Some(ref mut declarations) = &mut *inline_declarations { let existing_declarations = if style_priority == StylePriority::Important { &mut declarations.important } else { &mut declarations.normal }; // Usually, the reference count will be 1 here. But transitions could make it greater // than that. let existing_declarations = Arc::make_mut(existing_declarations); for declaration in &mut *existing_declarations { if declaration.name() == property_decl.name() { *declaration = property_decl; return; } } existing_declarations.push(property_decl); return; } let (important, normal) = if style_priority == StylePriority::Important { (vec![property_decl], vec![]) } else { (vec![], vec![property_decl]) }; *inline_declarations = Some(PropertyDeclarationBlock { important: Arc::new(important), normal: Arc::new(normal), }); } pub fn set_inline_style_property_priority(&self, properties: &[&str], style_priority: StylePriority) { let mut inline_declarations = self.style_attribute().borrow_mut(); if let &mut Some(ref mut declarations) = &mut *inline_declarations { let (from, to) = if style_priority == StylePriority::Important { (&mut declarations.normal, &mut declarations.important) } else { (&mut declarations.important, &mut declarations.normal) }; // Usually, the reference counts of `from` and `to` will be 1 here. But transitions // could make them greater than that. let from = Arc::make_mut(from); let to = Arc::make_mut(to); let mut new_from = Vec::new(); for declaration in from.drain(..) { let name = declaration.name(); if properties.iter().any(|p| name == **p) { to.push(declaration) } else { new_from.push(declaration) } } mem::replace(from, new_from); } } pub fn get_inline_style_declaration(&self, property: &Atom) -> Option<Ref<PropertyDeclaration>> { ref_filter_map(self.style_attribute.borrow(), |inline_declarations| { inline_declarations.as_ref().and_then(|declarations| { declarations.normal .iter() .chain(declarations.important.iter()) .find(|decl| decl.matches(&property)) }) }) } pub fn get_important_inline_style_declaration(&self, property: &Atom) -> Option<Ref<PropertyDeclaration>> { ref_filter_map(self.style_attribute.borrow(), |inline_declarations| { inline_declarations.as_ref().and_then(|declarations| { declarations.important .iter() .find(|decl| decl.matches(&property)) }) }) } pub fn serialize(&self, traversal_scope: TraversalScope) -> Fallible<DOMString> { let mut writer = vec![]; match serialize(&mut writer, &self.upcast::<Node>(), SerializeOpts { traversal_scope: traversal_scope, ..Default::default() }) { // FIXME(ajeffrey): Directly convert UTF8 to DOMString Ok(()) => Ok(DOMString::from(String::from_utf8(writer).unwrap())), Err(_) => panic!("Cannot serialize element"), } } pub fn root_element(&self) -> Root<Element> { if self.node.is_in_doc() { self.upcast::<Node>() .owner_doc() .GetDocumentElement() .unwrap() } else { self.upcast::<Node>() .inclusive_ancestors() .filter_map(Root::downcast) .last() .expect("We know inclusive_ancestors will return `self` which is an element") } } // https://dom.spec.whatwg.org/#locate-a-namespace-prefix pub fn lookup_prefix(&self, namespace: Namespace) -> Option<DOMString> { for node in self.upcast::<Node>().inclusive_ancestors() { match node.downcast::<Element>() { Some(element) => { // Step 1. if *element.namespace() == namespace { if let Some(prefix) = element.GetPrefix() { return Some(prefix); } } // Step 2. for attr in element.attrs.borrow().iter() { if *attr.prefix() == Some(atom!("xmlns")) && **attr.value() == *namespace.0 { return Some(attr.LocalName()); } } }, None => return None, } } None } } impl Element { pub fn is_focusable_area(&self) -> bool { if self.is_actually_disabled() { return false; } // TODO: Check whether the element is being rendered (i.e. not hidden). let node = self.upcast::<Node>(); if node.get_flag(SEQUENTIALLY_FOCUSABLE) { return true; } // https://html.spec.whatwg.org/multipage/#specially-focusable match node.type_id() { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) | NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) | NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) | NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => { true } _ => false, } } pub fn is_actually_disabled(&self) -> bool { let node = self.upcast::<Node>(); match node.type_id() { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) | NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) | NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) | NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) | NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptionElement)) => { self.disabled_state() } // TODO: // an optgroup element that has a disabled attribute // a menuitem element that has a disabled attribute // a fieldset element that is a disabled fieldset _ => false, } } } impl Element { pub fn push_new_attribute(&self, local_name: Atom, value: AttrValue, name: Atom, namespace: Namespace, prefix: Option<Atom>) { let window = window_from_node(self); let attr = Attr::new(&window, local_name, value, name, namespace, prefix, Some(self)); self.push_attribute(&attr); } pub fn push_attribute(&self, attr: &Attr) { assert!(attr.GetOwnerElement().r() == Some(self)); self.will_mutate_attr(); self.attrs.borrow_mut().push(JS::from_ref(attr)); if attr.namespace() == &ns!() { vtable_for(self.upcast()).attribute_mutated(attr, AttributeMutation::Set(None)); } } pub fn get_attribute(&self, namespace: &Namespace, local_name: &Atom) -> Option<Root<Attr>> { self.attrs .borrow() .iter() .find(|attr| attr.local_name() == local_name && attr.namespace() == namespace) .map(|js| Root::from_ref(&**js)) } // https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name pub fn get_attribute_by_name(&self, name: DOMString) -> Option<Root<Attr>> { let name = &self.parsed_name(name); self.attrs.borrow().iter().find(|a| a.name() == name).map(|js| Root::from_ref(&**js)) } pub fn set_attribute_from_parser(&self, qname: QualName, value: DOMString, prefix: Option<Atom>) { // Don't set if the attribute already exists, so we can handle add_attrs_if_missing if self.attrs .borrow() .iter() .any(|a| *a.local_name() == qname.local && *a.namespace() == qname.ns) { return; } let name = match prefix { None => qname.local.clone(), Some(ref prefix) => { let name = format!("{}:{}", &**prefix, &*qname.local); Atom::from(name) }, }; let value = self.parse_attribute(&qname.ns, &qname.local, value); self.push_new_attribute(qname.local, value, name, qname.ns, prefix); } pub fn set_attribute(&self, name: &Atom, value: AttrValue) { assert!(name == &name.to_ascii_lowercase()); assert!(!name.contains(":")); self.set_first_matching_attribute(name.clone(), value, name.clone(), ns!(), None, |attr| attr.local_name() == name); } // https://html.spec.whatwg.org/multipage/#attr-data-* pub fn set_custom_attribute(&self, name: DOMString, value: DOMString) -> ErrorResult { // Step 1. if let InvalidXMLName = xml_name_type(&name) { return Err(Error::InvalidCharacter); } // Steps 2-5. let name = Atom::from(name); let value = self.parse_attribute(&ns!(), &name, value); self.set_first_matching_attribute(name.clone(), value, name.clone(), ns!(), None, |attr| { *attr.name() == name && *attr.namespace() == ns!() }); Ok(()) } fn set_first_matching_attribute<F>(&self, local_name: Atom, value: AttrValue, name: Atom, namespace: Namespace, prefix: Option<Atom>, find: F) where F: Fn(&Attr) -> bool { let attr = self.attrs .borrow() .iter() .find(|attr| find(&attr)) .map(|js| Root::from_ref(&**js)); if let Some(attr) = attr { attr.set_value(value, self); } else { self.push_new_attribute(local_name, value, name, namespace, prefix); }; } pub fn parse_attribute(&self, namespace: &Namespace, local_name: &Atom, value: DOMString) -> AttrValue { if *namespace == ns!() { vtable_for(self.upcast()).parse_plain_attribute(local_name, value) } else { AttrValue::String(value) } } pub fn remove_attribute(&self, namespace: &Namespace, local_name: &Atom) -> Option<Root<Attr>> { self.remove_first_matching_attribute(|attr| { attr.namespace() == namespace && attr.local_name() == local_name }) } pub fn remove_attribute_by_name(&self, name: &Atom) -> Option<Root<Attr>> { self.remove_first_matching_attribute(|attr| attr.name() == name) } fn remove_first_matching_attribute<F>(&self, find: F) -> Option<Root<Attr>> where F: Fn(&Attr) -> bool { let idx = self.attrs.borrow().iter().position(|attr| find(&attr)); idx.map(|idx| { self.will_mutate_attr(); let attr = Root::from_ref(&*(*self.attrs.borrow())[idx]); self.attrs.borrow_mut().remove(idx); attr.set_owner(None); if attr.namespace() == &ns!() { vtable_for(self.upcast()).attribute_mutated(&attr, AttributeMutation::Removed); } attr }) } pub fn has_class(&self, name: &Atom) -> bool { let quirks_mode = document_from_node(self).quirks_mode(); let is_equal = |lhs: &Atom, rhs: &Atom| { match quirks_mode { NoQuirks | LimitedQuirks => lhs == rhs, Quirks => lhs.eq_ignore_ascii_case(&rhs), } }; self.get_attribute(&ns!(), &atom!("class")) .map_or(false, |attr| attr.value().as_tokens().iter().any(|atom| is_equal(name, atom))) } pub fn set_atomic_attribute(&self, local_name: &Atom, value: DOMString) { assert!(*local_name == local_name.to_ascii_lowercase()); let value = AttrValue::from_atomic(value); self.set_attribute(local_name, value); } pub fn has_attribute(&self, local_name: &Atom) -> bool { assert!(local_name.bytes().all(|b| b.to_ascii_lowercase() == b)); self.attrs .borrow() .iter() .any(|attr| attr.local_name() == local_name && attr.namespace() == &ns!()) } pub fn set_bool_attribute(&self, local_name: &Atom, value: bool) { if self.has_attribute(local_name) == value { return; } if value { self.set_string_attribute(local_name, DOMString::new()); } else { self.remove_attribute(&ns!(), local_name); } } pub fn get_url_attribute(&self, local_name: &Atom) -> DOMString { assert!(*local_name == local_name.to_ascii_lowercase()); if !self.has_attribute(local_name) { return DOMString::new(); } let url = self.get_string_attribute(local_name); let doc = document_from_node(self);<|fim▁hole|> match base.join(&url) { Ok(parsed) => DOMString::from(parsed.serialize()), Err(_) => DOMString::from(""), } } pub fn set_url_attribute(&self, local_name: &Atom, value: DOMString) { self.set_string_attribute(local_name, value); } pub fn get_string_attribute(&self, local_name: &Atom) -> DOMString { match self.get_attribute(&ns!(), local_name) { Some(x) => x.Value(), None => DOMString::new(), } } pub fn set_string_attribute(&self, local_name: &Atom, value: DOMString) { assert!(*local_name == local_name.to_ascii_lowercase()); self.set_attribute(local_name, AttrValue::String(value)); } pub fn get_tokenlist_attribute(&self, local_name: &Atom) -> Vec<Atom> { self.get_attribute(&ns!(), local_name).map(|attr| { attr.r() .value() .as_tokens() .to_vec() }).unwrap_or(vec!()) } pub fn set_tokenlist_attribute(&self, local_name: &Atom, value: DOMString) { assert!(*local_name == local_name.to_ascii_lowercase()); self.set_attribute(local_name, AttrValue::from_serialized_tokenlist(value)); } pub fn set_atomic_tokenlist_attribute(&self, local_name: &Atom, tokens: Vec<Atom>) { assert!(*local_name == local_name.to_ascii_lowercase()); self.set_attribute(local_name, AttrValue::from_atomic_tokens(tokens)); } pub fn get_int_attribute(&self, local_name: &Atom, default: i32) -> i32 { // TODO: Is this assert necessary? assert!(local_name.chars().all(|ch| { !ch.is_ascii() || ch.to_ascii_lowercase() == ch })); let attribute = self.get_attribute(&ns!(), local_name); match attribute { Some(ref attribute) => { match *attribute.r().value() { AttrValue::Int(_, value) => value, _ => panic!("Expected an AttrValue::Int: \ implement parse_plain_attribute"), } } None => default, } } pub fn set_int_attribute(&self, local_name: &Atom, value: i32) { assert!(*local_name == local_name.to_ascii_lowercase()); self.set_attribute(local_name, AttrValue::Int(DOMString::from(value.to_string()), value)); } pub fn get_uint_attribute(&self, local_name: &Atom, default: u32) -> u32 { assert!(local_name.chars().all(|ch| !ch.is_ascii() || ch.to_ascii_lowercase() == ch)); let attribute = self.get_attribute(&ns!(), local_name); match attribute { Some(ref attribute) => { match *attribute.value() { AttrValue::UInt(_, value) => value, _ => panic!("Expected an AttrValue::UInt: implement parse_plain_attribute"), } } None => default, } } pub fn set_uint_attribute(&self, local_name: &Atom, value: u32) { assert!(*local_name == local_name.to_ascii_lowercase()); // FIXME(ajeffrey): Directly convert u32 to DOMString self.set_attribute(local_name, AttrValue::UInt(DOMString::from(value.to_string()), value)); } pub fn will_mutate_attr(&self) { let node = self.upcast::<Node>(); node.owner_doc().element_attr_will_change(self); } // https://dom.spec.whatwg.org/#insert-adjacent pub fn insert_adjacent(&self, where_: DOMString, node: &Node) -> Fallible<Option<Root<Node>>> { let self_node = self.upcast::<Node>(); match &*where_ { "beforebegin" => { if let Some(parent) = self_node.GetParentNode() { Node::pre_insert(node, &parent, Some(self_node)).map(Some) } else { Ok(None) } } "afterbegin" => { Node::pre_insert(node, &self_node, self_node.GetFirstChild().r()).map(Some) } "beforeend" => { Node::pre_insert(node, &self_node, None).map(Some) } "afterend" => { if let Some(parent) = self_node.GetParentNode() { Node::pre_insert(node, &parent, self_node.GetNextSibling().r()).map(Some) } else { Ok(None) } } _ => Err(Error::Syntax) } } } impl ElementMethods for Element { // https://dom.spec.whatwg.org/#dom-element-namespaceuri fn GetNamespaceURI(&self) -> Option<DOMString> { Node::namespace_to_string(self.namespace.clone()) } // https://dom.spec.whatwg.org/#dom-element-localname fn LocalName(&self) -> DOMString { // FIXME(ajeffrey): Convert directly from Atom to DOMString DOMString::from(&*self.local_name) } // https://dom.spec.whatwg.org/#dom-element-prefix fn GetPrefix(&self) -> Option<DOMString> { self.prefix.clone() } // https://dom.spec.whatwg.org/#dom-element-tagname fn TagName(&self) -> DOMString { let qualified_name = match self.prefix { Some(ref prefix) => { Cow::Owned(format!("{}:{}", &**prefix, &*self.local_name)) }, None => Cow::Borrowed(&*self.local_name) }; DOMString::from(if self.html_element_in_html_document() { qualified_name.to_ascii_uppercase() } else { qualified_name.into_owned() }) } // https://dom.spec.whatwg.org/#dom-element-id fn Id(&self) -> DOMString { self.get_string_attribute(&atom!("id")) } // https://dom.spec.whatwg.org/#dom-element-id fn SetId(&self, id: DOMString) { self.set_atomic_attribute(&atom!("id"), id); } // https://dom.spec.whatwg.org/#dom-element-classname fn ClassName(&self) -> DOMString { self.get_string_attribute(&atom!("class")) } // https://dom.spec.whatwg.org/#dom-element-classname fn SetClassName(&self, class: DOMString) { self.set_tokenlist_attribute(&atom!("class"), class); } // https://dom.spec.whatwg.org/#dom-element-classlist fn ClassList(&self) -> Root<DOMTokenList> { self.class_list.or_init(|| DOMTokenList::new(self, &atom!("class"))) } // https://dom.spec.whatwg.org/#dom-element-attributes fn Attributes(&self) -> Root<NamedNodeMap> { self.attr_list.or_init(|| NamedNodeMap::new(&window_from_node(self), self)) } // https://dom.spec.whatwg.org/#dom-element-getattributenames fn GetAttributeNames(&self) -> Vec<DOMString> { self.attrs.borrow().iter().map(|attr| attr.Name()).collect() } // https://dom.spec.whatwg.org/#dom-element-getattribute fn GetAttribute(&self, name: DOMString) -> Option<DOMString> { self.GetAttributeNode(name) .map(|s| s.Value()) } // https://dom.spec.whatwg.org/#dom-element-getattributens fn GetAttributeNS(&self, namespace: Option<DOMString>, local_name: DOMString) -> Option<DOMString> { self.GetAttributeNodeNS(namespace, local_name) .map(|attr| attr.Value()) } // https://dom.spec.whatwg.org/#dom-element-getattributenode fn GetAttributeNode(&self, name: DOMString) -> Option<Root<Attr>> { self.get_attribute_by_name(name) } // https://dom.spec.whatwg.org/#dom-element-getattributenodens fn GetAttributeNodeNS(&self, namespace: Option<DOMString>, local_name: DOMString) -> Option<Root<Attr>> { let namespace = &namespace_from_domstring(namespace); self.get_attribute(namespace, &Atom::from(local_name)) } // https://dom.spec.whatwg.org/#dom-element-setattribute fn SetAttribute(&self, name: DOMString, value: DOMString) -> ErrorResult { // Step 1. if xml_name_type(&name) == InvalidXMLName { return Err(Error::InvalidCharacter); } // Step 2. let name = self.parsed_name(name); // Step 3-5. let value = self.parse_attribute(&ns!(), &name, value); self.set_first_matching_attribute( name.clone(), value, name.clone(), ns!(), None, |attr| *attr.name() == name); Ok(()) } // https://dom.spec.whatwg.org/#dom-element-setattributens fn SetAttributeNS(&self, namespace: Option<DOMString>, qualified_name: DOMString, value: DOMString) -> ErrorResult { let (namespace, prefix, local_name) = try!(validate_and_extract(namespace, &qualified_name)); let qualified_name = Atom::from(qualified_name); let value = self.parse_attribute(&namespace, &local_name, value); self.set_first_matching_attribute( local_name.clone(), value, qualified_name, namespace.clone(), prefix, |attr| *attr.local_name() == local_name && *attr.namespace() == namespace); Ok(()) } // https://dom.spec.whatwg.org/#dom-element-setattributenode fn SetAttributeNode(&self, attr: &Attr) -> Fallible<Option<Root<Attr>>> { // Step 1. if let Some(owner) = attr.GetOwnerElement() { if &*owner != self { return Err(Error::InUseAttribute); } } // Step 2. let position = self.attrs.borrow().iter().position(|old_attr| { attr.namespace() == old_attr.namespace() && attr.local_name() == old_attr.local_name() }); if let Some(position) = position { let old_attr = Root::from_ref(&*self.attrs.borrow()[position]); // Step 3. if old_attr.r() == attr { return Ok(Some(Root::from_ref(attr))); } // Step 4. self.will_mutate_attr(); attr.set_owner(Some(self)); self.attrs.borrow_mut()[position] = JS::from_ref(attr); old_attr.set_owner(None); if attr.namespace() == &ns!() { vtable_for(self.upcast()).attribute_mutated( &attr, AttributeMutation::Set(Some(&old_attr.value()))); } // Step 6. Ok(Some(old_attr)) } else { // Step 5. attr.set_owner(Some(self)); self.push_attribute(attr); // Step 6. Ok(None) } } // https://dom.spec.whatwg.org/#dom-element-setattributenodens fn SetAttributeNodeNS(&self, attr: &Attr) -> Fallible<Option<Root<Attr>>> { self.SetAttributeNode(attr) } // https://dom.spec.whatwg.org/#dom-element-removeattribute fn RemoveAttribute(&self, name: DOMString) { let name = self.parsed_name(name); self.remove_attribute_by_name(&name); } // https://dom.spec.whatwg.org/#dom-element-removeattributens fn RemoveAttributeNS(&self, namespace: Option<DOMString>, local_name: DOMString) { let namespace = namespace_from_domstring(namespace); let local_name = Atom::from(local_name); self.remove_attribute(&namespace, &local_name); } // https://dom.spec.whatwg.org/#dom-element-removeattributenode fn RemoveAttributeNode(&self, attr: &Attr) -> Fallible<Root<Attr>> { self.remove_first_matching_attribute(|a| a == attr) .ok_or(Error::NotFound) } // https://dom.spec.whatwg.org/#dom-element-hasattribute fn HasAttribute(&self, name: DOMString) -> bool { self.GetAttribute(name).is_some() } // https://dom.spec.whatwg.org/#dom-element-hasattributens fn HasAttributeNS(&self, namespace: Option<DOMString>, local_name: DOMString) -> bool { self.GetAttributeNS(namespace, local_name).is_some() } // https://dom.spec.whatwg.org/#dom-element-getelementsbytagname fn GetElementsByTagName(&self, localname: DOMString) -> Root<HTMLCollection> { let window = window_from_node(self); HTMLCollection::by_tag_name(window.r(), self.upcast(), localname) } // https://dom.spec.whatwg.org/#dom-element-getelementsbytagnamens fn GetElementsByTagNameNS(&self, maybe_ns: Option<DOMString>, localname: DOMString) -> Root<HTMLCollection> { let window = window_from_node(self); HTMLCollection::by_tag_name_ns(window.r(), self.upcast(), localname, maybe_ns) } // https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname fn GetElementsByClassName(&self, classes: DOMString) -> Root<HTMLCollection> { let window = window_from_node(self); HTMLCollection::by_class_name(window.r(), self.upcast(), classes) } // https://drafts.csswg.org/cssom-view/#dom-element-getclientrects fn GetClientRects(&self) -> Root<DOMRectList> { let win = window_from_node(self); let raw_rects = self.upcast::<Node>().content_boxes(); let rects = raw_rects.iter().map(|rect| { DOMRect::new(GlobalRef::Window(win.r()), rect.origin.x.to_f64_px(), rect.origin.y.to_f64_px(), rect.size.width.to_f64_px(), rect.size.height.to_f64_px()) }); DOMRectList::new(win.r(), rects) } // https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect fn GetBoundingClientRect(&self) -> Root<DOMRect> { let win = window_from_node(self); let rect = self.upcast::<Node>().bounding_content_box(); DOMRect::new(GlobalRef::Window(win.r()), rect.origin.x.to_f64_px(), rect.origin.y.to_f64_px(), rect.size.width.to_f64_px(), rect.size.height.to_f64_px()) } // https://drafts.csswg.org/cssom-view/#dom-element-scrollwidth fn ScrollWidth(&self) -> i32 { self.upcast::<Node>().scroll_area().size.width } // https://drafts.csswg.org/cssom-view/#dom-element-scrollheight fn ScrollHeight(&self) -> i32 { self.upcast::<Node>().scroll_area().size.height } // https://drafts.csswg.org/cssom-view/#dom-element-clienttop fn ClientTop(&self) -> i32 { self.upcast::<Node>().client_rect().origin.y } // https://drafts.csswg.org/cssom-view/#dom-element-clientleft fn ClientLeft(&self) -> i32 { self.upcast::<Node>().client_rect().origin.x } // https://drafts.csswg.org/cssom-view/#dom-element-clientwidth fn ClientWidth(&self) -> i32 { self.upcast::<Node>().client_rect().size.width } // https://drafts.csswg.org/cssom-view/#dom-element-clientheight fn ClientHeight(&self) -> i32 { self.upcast::<Node>().client_rect().size.height } /// https://w3c.github.io/DOM-Parsing/#widl-Element-innerHTML fn GetInnerHTML(&self) -> Fallible<DOMString> { // XXX TODO: XML case self.serialize(ChildrenOnly) } /// https://w3c.github.io/DOM-Parsing/#widl-Element-innerHTML fn SetInnerHTML(&self, value: DOMString) -> Fallible<()> { let context_node = self.upcast::<Node>(); // Step 1. let frag = try!(context_node.parse_fragment(value)); // Step 2. // https://github.com/w3c/DOM-Parsing/issues/1 let target = if let Some(template) = self.downcast::<HTMLTemplateElement>() { Root::upcast(template.Content()) } else { Root::from_ref(context_node) }; Node::replace_all(Some(frag.upcast()), &target); Ok(()) } // https://dvcs.w3.org/hg/innerhtml/raw-file/tip/index.html#widl-Element-outerHTML fn GetOuterHTML(&self) -> Fallible<DOMString> { self.serialize(IncludeNode) } // https://dvcs.w3.org/hg/innerhtml/raw-file/tip/index.html#widl-Element-outerHTML fn SetOuterHTML(&self, value: DOMString) -> Fallible<()> { let context_document = document_from_node(self); let context_node = self.upcast::<Node>(); // Step 1. let context_parent = match context_node.GetParentNode() { None => { // Step 2. return Ok(()); }, Some(parent) => parent, }; let parent = match context_parent.type_id() { // Step 3. NodeTypeId::Document(_) => return Err(Error::NoModificationAllowed), // Step 4. NodeTypeId::DocumentFragment => { let body_elem = Element::create(QualName::new(ns!(html), atom!("body")), None, context_document.r(), ElementCreator::ScriptCreated); Root::upcast(body_elem) }, _ => context_node.GetParentNode().unwrap() }; // Step 5. let frag = try!(parent.parse_fragment(value)); // Step 6. try!(context_parent.ReplaceChild(frag.upcast(), context_node)); Ok(()) } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(&self) -> Option<Root<Element>> { self.upcast::<Node>().preceding_siblings().filter_map(Root::downcast).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(&self) -> Option<Root<Element>> { self.upcast::<Node>().following_siblings().filter_map(Root::downcast).next() } // https://dom.spec.whatwg.org/#dom-parentnode-children fn Children(&self) -> Root<HTMLCollection> { let window = window_from_node(self); HTMLCollection::children(window.r(), self.upcast()) } // https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild fn GetFirstElementChild(&self) -> Option<Root<Element>> { self.upcast::<Node>().child_elements().next() } // https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild fn GetLastElementChild(&self) -> Option<Root<Element>> { self.upcast::<Node>().rev_children().filter_map(Root::downcast::<Element>).next() } // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount fn ChildElementCount(&self) -> u32 { self.upcast::<Node>().child_elements().count() as u32 } // https://dom.spec.whatwg.org/#dom-parentnode-prepend fn Prepend(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().prepend(nodes) } // https://dom.spec.whatwg.org/#dom-parentnode-append fn Append(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().append(nodes) } // https://dom.spec.whatwg.org/#dom-parentnode-queryselector fn QuerySelector(&self, selectors: DOMString) -> Fallible<Option<Root<Element>>> { let root = self.upcast::<Node>(); root.query_selector(selectors) } // https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible<Root<NodeList>> { let root = self.upcast::<Node>(); root.query_selector_all(selectors) } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(&self) { self.upcast::<Node>().remove_self(); } // https://dom.spec.whatwg.org/#dom-element-matches fn Matches(&self, selectors: DOMString) -> Fallible<bool> { match parse_author_origin_selector_list_from_str(&selectors) { Err(()) => Err(Error::Syntax), Ok(ref selectors) => { Ok(matches(selectors, &Root::from_ref(self), None)) } } } // https://dom.spec.whatwg.org/#dom-element-webkitmatchesselector fn WebkitMatchesSelector(&self, selectors: DOMString) -> Fallible<bool> { self.Matches(selectors) } // https://dom.spec.whatwg.org/#dom-element-closest fn Closest(&self, selectors: DOMString) -> Fallible<Option<Root<Element>>> { match parse_author_origin_selector_list_from_str(&selectors) { Err(()) => Err(Error::Syntax), Ok(ref selectors) => { let root = self.upcast::<Node>(); for element in root.inclusive_ancestors() { if let Some(element) = Root::downcast::<Element>(element) { if matches(selectors, &element, None) { return Ok(Some(element)); } } } Ok(None) } } } // https://dom.spec.whatwg.org/#dom-element-insertadjacentelement fn InsertAdjacentElement(&self, where_: DOMString, element: &Element) -> Fallible<Option<Root<Element>>> { let inserted_node = try!(self.insert_adjacent(where_, element.upcast())); Ok(inserted_node.map(|node| Root::downcast(node).unwrap())) } // https://dom.spec.whatwg.org/#dom-element-insertadjacenttext fn InsertAdjacentText(&self, where_: DOMString, data: DOMString) -> ErrorResult { // Step 1. let text = Text::new(data, &document_from_node(self)); // Step 2. self.insert_adjacent(where_, text.upcast()).map(|_| ()) } } pub fn fragment_affecting_attributes() -> [Atom; 3] { [atom!("width"), atom!("height"), atom!("src")] } impl VirtualMethods for Element { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<Node>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); let node = self.upcast::<Node>(); let doc = node.owner_doc(); match attr.local_name() { &atom!("style") => { // Modifying the `style` attribute might change style. *self.style_attribute.borrow_mut() = mutation.new_value(attr).map(|value| { let win = window_from_node(self); parse_style_attribute(&value, &doc.base_url(), win.css_error_reporter()) }); if node.is_in_doc() { node.dirty(NodeDamage::NodeStyleDamaged); } }, &atom!("id") => { *self.id_attribute.borrow_mut() = mutation.new_value(attr).and_then(|value| { let value = value.as_atom(); if value != &atom!("") { Some(value.clone()) } else { None } }); if node.is_in_doc() { let value = attr.value().as_atom().clone(); match mutation { AttributeMutation::Set(old_value) => { if let Some(old_value) = old_value { let old_value = old_value.as_atom().clone(); doc.unregister_named_element(self, old_value); } if value != atom!("") { doc.register_named_element(self, value); } }, AttributeMutation::Removed => { if value != atom!("") { doc.unregister_named_element(self, value); } } } } }, _ if attr.namespace() == &ns!() => { if fragment_affecting_attributes().iter().any(|a| a == attr.local_name()) || common_style_affecting_attributes().iter().any(|a| &a.atom == attr.local_name()) || rare_style_affecting_attributes().iter().any(|a| a == attr.local_name()) { node.dirty(NodeDamage::OtherNodeDamage); } }, _ => {}, }; // Make sure we rev the version even if we didn't dirty the node. If we // don't do this, various attribute-dependent htmlcollections (like those // generated by getElementsByClassName) might become stale. node.rev_version(); } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("id") => AttrValue::from_atomic(value), &atom!("class") => AttrValue::from_serialized_tokenlist(value), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } if !tree_in_doc { return; } if let Some(ref value) = *self.id_attribute.borrow() { let doc = document_from_node(self); doc.register_named_element(self, value.clone()); } } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); if !context.tree_in_doc { return; } if let Some(ref value) = *self.id_attribute.borrow() { let doc = document_from_node(self); doc.unregister_named_element(self, value.clone()); } } fn children_changed(&self, mutation: &ChildrenMutation) { if let Some(ref s) = self.super_type() { s.children_changed(mutation); } let flags = self.atomic_flags.get(); if flags.intersects(HAS_SLOW_SELECTOR) { // All children of this node need to be restyled when any child changes. self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); } else { if flags.intersects(HAS_SLOW_SELECTOR_LATER_SIBLINGS) { if let Some(next_child) = mutation.next_child() { for child in next_child.inclusively_following_siblings() { if child.is::<Element>() { child.dirty(NodeDamage::OtherNodeDamage); } } } } if flags.intersects(HAS_EDGE_CHILD_SELECTOR) { if let Some(child) = mutation.modified_edge_element() { child.dirty(NodeDamage::OtherNodeDamage); } } } } } impl<'a> ::selectors::Element for Root<Element> { type Impl = ServoSelectorImpl; fn parent_element(&self) -> Option<Root<Element>> { self.upcast::<Node>().GetParentElement() } fn first_child_element(&self) -> Option<Root<Element>> { self.node.child_elements().next() } fn last_child_element(&self) -> Option<Root<Element>> { self.node.rev_children().filter_map(Root::downcast).next() } fn prev_sibling_element(&self) -> Option<Root<Element>> { self.node.preceding_siblings().filter_map(Root::downcast).next() } fn next_sibling_element(&self) -> Option<Root<Element>> { self.node.following_siblings().filter_map(Root::downcast).next() } fn is_root(&self) -> bool { match self.node.GetParentNode() { None => false, Some(node) => node.is::<Document>(), } } fn is_empty(&self) -> bool { self.node.children().all(|node| !node.is::<Element>() && match node.downcast::<Text>() { None => true, Some(text) => text.upcast::<CharacterData>().data().is_empty() }) } fn get_local_name(&self) -> &Atom { self.local_name() } fn get_namespace(&self) -> &Namespace { self.namespace() } fn match_non_ts_pseudo_class(&self, pseudo_class: NonTSPseudoClass) -> bool { match pseudo_class { // https://github.com/servo/servo/issues/8718 NonTSPseudoClass::Link | NonTSPseudoClass::AnyLink => self.is_link(), NonTSPseudoClass::Visited => false, NonTSPseudoClass::ServoNonZeroBorder => { match self.downcast::<HTMLTableElement>() { None => false, Some(this) => { match this.get_border() { None | Some(0) => false, Some(_) => true, } } } }, NonTSPseudoClass::Active | NonTSPseudoClass::Focus | NonTSPseudoClass::Hover | NonTSPseudoClass::Enabled | NonTSPseudoClass::Disabled | NonTSPseudoClass::Checked | NonTSPseudoClass::Indeterminate => Element::state(self).contains(pseudo_class.state_flag()), } } fn get_id(&self) -> Option<Atom> { self.id_attribute.borrow().clone() } fn has_class(&self, name: &Atom) -> bool { Element::has_class(&**self, name) } fn each_class<F>(&self, mut callback: F) where F: FnMut(&Atom) { if let Some(ref attr) = self.get_attribute(&ns!(), &atom!("class")) { let tokens = attr.value(); let tokens = tokens.as_tokens(); for token in tokens { callback(token); } } } fn match_attr<F>(&self, attr: &AttrSelector, test: F) -> bool where F: Fn(&str) -> bool { let local_name = { if self.is_html_element_in_html_document() { &attr.lower_name } else { &attr.name } }; match attr.namespace { NamespaceConstraint::Specific(ref ns) => { self.get_attribute(ns, local_name) .map_or(false, |attr| { test(&attr.value()) }) }, NamespaceConstraint::Any => { self.attrs.borrow().iter().any(|attr| { attr.local_name() == local_name && test(&attr.value()) }) } } } fn is_html_element_in_html_document(&self) -> bool { self.html_element_in_html_document() } } impl Element { pub fn as_maybe_activatable(&self) -> Option<&Activatable> { let element = match self.upcast::<Node>().type_id() { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => { let element = self.downcast::<HTMLInputElement>().unwrap(); Some(element as &Activatable) }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => { let element = self.downcast::<HTMLButtonElement>().unwrap(); Some(element as &Activatable) }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) => { let element = self.downcast::<HTMLAnchorElement>().unwrap(); Some(element as &Activatable) }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLabelElement)) => { let element = self.downcast::<HTMLLabelElement>().unwrap(); Some(element as &Activatable) }, _ => { None } }; element.and_then(|elem| { if elem.is_instance_activatable() { Some(elem) } else { None } }) } // https://html.spec.whatwg.org/multipage/#category-submit pub fn as_maybe_validatable(&self) -> Option<&Validatable> { let element = match self.upcast::<Node>().type_id() { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => { let element = self.downcast::<HTMLInputElement>().unwrap(); Some(element as &Validatable) }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => { let element = self.downcast::<HTMLButtonElement>().unwrap(); Some(element as &Validatable) }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement)) => { let element = self.downcast::<HTMLObjectElement>().unwrap(); Some(element as &Validatable) }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) => { let element = self.downcast::<HTMLSelectElement>().unwrap(); Some(element as &Validatable) }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => { let element = self.downcast::<HTMLTextAreaElement>().unwrap(); Some(element as &Validatable) }, _ => { None } }; element } pub fn click_in_progress(&self) -> bool { self.upcast::<Node>().get_flag(CLICK_IN_PROGRESS) } pub fn set_click_in_progress(&self, click: bool) { self.upcast::<Node>().set_flag(CLICK_IN_PROGRESS, click) } // https://html.spec.whatwg.org/multipage/#nearest-activatable-element pub fn nearest_activable_element(&self) -> Option<Root<Element>> { match self.as_maybe_activatable() { Some(el) => Some(Root::from_ref(el.as_element())), None => { let node = self.upcast::<Node>(); for node in node.ancestors() { if let Some(node) = node.downcast::<Element>() { if node.as_maybe_activatable().is_some() { return Some(Root::from_ref(node)); } } } None } } } fn is_link(&self) -> bool { // FIXME: This is HTML only. let node = self.upcast::<Node>(); match node.type_id() { // https://html.spec.whatwg.org/multipage/#selector-link NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) | NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAreaElement)) | NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLinkElement)) => { self.has_attribute(&atom!("href")) }, _ => false, } } /// Please call this method *only* for real click events /// /// https://html.spec.whatwg.org/multipage/#run-authentic-click-activation-steps /// /// Use an element's synthetic click activation (or handle_event) for any script-triggered clicks. /// If the spec says otherwise, check with Manishearth first pub fn authentic_click_activation(&self, event: &Event) { // Not explicitly part of the spec, however this helps enforce the invariants // required to save state between pre-activation and post-activation // since we cannot nest authentic clicks (unlike synthetic click activation, where // the script can generate more click events from the handler) assert!(!self.click_in_progress()); let target = self.upcast(); // Step 2 (requires canvas support) // Step 3 self.set_click_in_progress(true); // Step 4 let e = self.nearest_activable_element(); match e { Some(ref el) => match el.as_maybe_activatable() { Some(elem) => { // Step 5-6 elem.pre_click_activation(); event.fire(target); if !event.DefaultPrevented() { // post click activation elem.activation_behavior(event, target); } else { elem.canceled_activation(); } } // Step 6 None => { event.fire(target); } }, // Step 6 None => { event.fire(target); } } // Step 7 self.set_click_in_progress(false); } pub fn state(&self) -> ElementState { self.state.get() } pub fn set_state(&self, which: ElementState, value: bool) { let mut state = self.state.get(); if state.contains(which) == value { return; } let node = self.upcast::<Node>(); node.owner_doc().element_state_will_change(self); if value { state.insert(which); } else { state.remove(which); } self.state.set(state); } pub fn active_state(&self) -> bool { self.state.get().contains(IN_ACTIVE_STATE) } pub fn set_active_state(&self, value: bool) { self.set_state(IN_ACTIVE_STATE, value) } pub fn focus_state(&self) -> bool { self.state.get().contains(IN_FOCUS_STATE) } pub fn set_focus_state(&self, value: bool) { self.set_state(IN_FOCUS_STATE, value); self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); } pub fn hover_state(&self) -> bool { self.state.get().contains(IN_HOVER_STATE) } pub fn set_hover_state(&self, value: bool) { self.set_state(IN_HOVER_STATE, value) } pub fn enabled_state(&self) -> bool { self.state.get().contains(IN_ENABLED_STATE) } pub fn set_enabled_state(&self, value: bool) { self.set_state(IN_ENABLED_STATE, value) } pub fn disabled_state(&self) -> bool { self.state.get().contains(IN_DISABLED_STATE) } pub fn set_disabled_state(&self, value: bool) { self.set_state(IN_DISABLED_STATE, value) } } impl Element { pub fn check_ancestors_disabled_state_for_form_control(&self) { let node = self.upcast::<Node>(); if self.disabled_state() { return; } for ancestor in node.ancestors() { let ancestor = ancestor; let ancestor = ancestor.r(); if !ancestor.is::<HTMLFieldSetElement>() { continue; } if !ancestor.downcast::<Element>().unwrap().disabled_state() { continue; } if ancestor.is_parent_of(node) { self.set_disabled_state(true); self.set_enabled_state(false); return; } match ancestor.children() .find(|child| child.is::<HTMLLegendElement>()) { Some(ref legend) => { // XXXabinader: should we save previous ancestor to avoid this iteration? if node.ancestors().any(|ancestor| ancestor == *legend) { continue; } }, None => (), } self.set_disabled_state(true); self.set_enabled_state(false); return; } } pub fn check_parent_disabled_state_for_option(&self) { if self.disabled_state() { return; } let node = self.upcast::<Node>(); if let Some(ref parent) = node.GetParentNode() { if parent.is::<HTMLOptGroupElement>() && parent.downcast::<Element>().unwrap().disabled_state() { self.set_disabled_state(true); self.set_enabled_state(false); } } } pub fn check_disabled_attribute(&self) { let has_disabled_attrib = self.has_attribute(&atom!("disabled")); self.set_disabled_state(has_disabled_attrib); self.set_enabled_state(!has_disabled_attrib); } } #[derive(Clone, Copy, PartialEq)] pub enum AttributeMutation<'a> { /// The attribute is set, keep track of old value. /// https://dom.spec.whatwg.org/#attribute-is-set Set(Option<&'a AttrValue>), /// The attribute is removed. /// https://dom.spec.whatwg.org/#attribute-is-removed Removed, } impl<'a> AttributeMutation<'a> { pub fn new_value<'b>(&self, attr: &'b Attr) -> Option<Ref<'b, AttrValue>> { match *self { AttributeMutation::Set(_) => Some(attr.value()), AttributeMutation::Removed => None, } } } /// Thread-safe wrapper for ElementFlags set during selector matching #[derive(JSTraceable, HeapSizeOf)] struct AtomicElementFlags(AtomicUsize); impl AtomicElementFlags { fn new() -> Self { AtomicElementFlags(AtomicUsize::new(0)) } fn get(&self) -> ElementFlags { ElementFlags::from_bits_truncate(self.0.load(Ordering::Relaxed) as u8) } fn insert(&self, flags: ElementFlags) { self.0.fetch_or(flags.bits() as usize, Ordering::Relaxed); } }<|fim▁end|>
let base = doc.base_url(); // https://html.spec.whatwg.org/multipage/#reflect // XXXManishearth this doesn't handle `javascript:` urls properly
<|file_name|>main.js<|end_file_name|><|fim▁begin|>var gridOptions = { columnDefs: [ { field: 'country', rowGroup: true, hide: true }, { field: 'athlete', minWidth: 180 }, { field: 'age' }, { field: 'year' }, { field: 'date', minWidth: 150 }, { field: 'sport', minWidth: 150 }, { field: 'gold' }, { field: 'silver' }, { field: 'bronze' }, { field: 'total' } ], defaultColDef: { flex: 1, minWidth: 100, sortable: true, filter: true }, autoGroupColumnDef: { minWidth: 200 }, groupDefaultExpanded: 1, }; <|fim▁hole|>} function onBtForEachNodeAfterFilter() { console.log('### api.forEachNodeAfterFilter() ###'); gridOptions.api.forEachNodeAfterFilter(this.printNode); } function onBtForEachNodeAfterFilterAndSort() { console.log('### api.forEachNodeAfterFilterAndSort() ###'); gridOptions.api.forEachNodeAfterFilterAndSort(this.printNode); } function onBtForEachLeafNode() { console.log('### api.forEachLeafNode() ###'); gridOptions.api.forEachLeafNode(this.printNode); } // inScope[printNode] function printNode(node, index) { if (node.group) { console.log(index + ' -> group: ' + node.key); } else { console.log(index + ' -> data: ' + node.data.country + ', ' + node.data.athlete); } } // setup the grid after the page has finished loading document.addEventListener('DOMContentLoaded', function() { var gridDiv = document.querySelector('#myGrid'); new agGrid.Grid(gridDiv, gridOptions); agGrid.simpleHttpRequest({ url: 'https://www.ag-grid.com/example-assets/olympic-winners.json' }) .then(function(data) { gridOptions.api.setRowData(data.slice(0, 50)); }); });<|fim▁end|>
function onBtForEachNode() { console.log('### api.forEachNode() ###'); gridOptions.api.forEachNode(this.printNode);
<|file_name|>testing.js<|end_file_name|><|fim▁begin|>'use strict'; angular.module('testing').controller('TestingController', ['$scope', '$http', '$location', 'Authentication', 'Appprogress', 'Users', 'Registrations', 'creditCardMgmt', 'createDialog', 'bankAccountMgmt', function ($scope, $http, $location, Authentication, Appprogress, Users, Registrations, creditCardMgmt, createDialogService, bankAccountMgmt) { $scope.user = Authentication.user; $scope.registration = null; $scope.cards = []; $scope.accounts = []; $scope.selectedPart = []; // If user is not signed in then redirect back home if (!$scope.user) $location.path('/'); var appProgress = Appprogress; // $scope.isExistingUser = true; $scope.getBankAccountsList = function () { console.log('getBankAccountsList()'); appProgress.showPleaseWait(); $http.get('/registrationsdetails/' + $scope.user._id).success(function (reg) { if (reg[0] && reg[0].bankAccountId) { for (var i = 0; i < reg[0].bankAccountId.length; i++) { $http.post('/getObject', { "objectHref": "/bank_accounts/" + reg[0].bankAccountId[i] }).success(function (response) { $scope.accounts.push({ "bankName": response.bank_name, "bankAccountName": response.name, "bankAccountNumber": response.account_number, "bankAccountType": response.account_type }); }); } } appProgress.hidePleaseWait(); }).error(function (err) { appProgress.hidePleaseWait(); }); $scope.gridAccounts = { data: 'accounts', multiSelect: false, selectedItems: $scope.selectedPart, columnDefs: [{ field: 'bankName', displayName: 'Bank Name', width: '**' }, { field: 'bankAccountName', displayName: 'Account Name' }, { field: 'bankAccountNumber', displayName: 'Account Number' }, { field: 'bankAccountType', displayName: 'Account Type' }] }; }; $scope.getBankAccount = function () { console.log('getBankAccount()'); appProgress.showPleaseWait(); $http.get('/registrationsdetails/' + $scope.user._id).success(function (reg) { if (reg && reg[0].bankAccountId) { $http.post('/getObject', { "objectHref": "/bank_accounts/" + reg[0].bankAccountIdbankAccountId }).success(function (response) { $("#bankName").val(response.bank_name); $("#bankAccountName").val(response.name); $("#bankAccountNumber").val(response.account_number); $("#bankAccountType").val(response.account_type); $("#bankSwift").val(response.routing_number); $("#bankAddress1").val(response.address ? response.address.line1 : ""); $("#bankAddress2").val(response.address ? response.address.line2 : ""); $("#bankCity").val(response.address ? response.address.city : ""); $("#bankState").val(response.address ? response.address.state : ""); $("#bankZip").val(response.address ? response.address.postal_code : ""); $("#bankCountry").val(response.address ? response.address.country_code : ""); appProgress.hidePleaseWait(); }). error(function (response) { appProgress.hidePleaseWait(); $scope.error = response.message; $scope.payment = null; }); } appProgress.hidePleaseWait(); }) .error(function (error) { appProgress.hidePleaseWait(); alert(error); }); }; $scope.updateBankAccount = function () { console.log('testing.updateBankAccount()'); // create objects for balanced payments to store bank account var account = { "routing_number": $("#bankSwift").val(), "account_type": $("#bankAccountType").val(), "name": $("#bankAccountName").val(), "account_number": $("#bankAccountNumber").val(), }; var address = { "city": $("#bankCity").val(), "line1": $("#bankAddress1").val(), "line2": $("#bankAddress2").val(), "state": $("#bankState").val(), "postal_code": $("#bankZip").val(), "country_code": $("#bankCountry").val() }; var createAccountObj = { "account": account, "address": address }; var userEmail = $scope.user.email; var userHref = ''; //TODO:balanced2 get the balanced customer identifier from the registration for this user // use that identifier to see if we have a customer record matching in balanced // if not theoretically it is a system error if we have the id locally and it is not in balanced however // we can for now just create a new one in that case and log the error $http.get('/registrationsdetails/' + $scope.user._id).success(function (reg) { if (reg && reg[0].balancedPaymentsId) { $http.post('/getObject', { "objectHref": "/customers/" + reg[0].balancedPaymentsId }).success(function (customer_response) { $http.post('/createAccount', createAccountObj).success(function (account_response) { console.log(account_response); var accountHref = account_response.href; if (accountHref == undefined) { console.log('error creating bank acount'); alert('error creating bank account'); return; } $http.post('/addAccountToCustomer', { "customerHref": "/customers/" + reg[0].balancedPaymentsId, "accountHref": accountHref }).success(function (addAccount_response) { console.log('Add account to customer'); console.log(addAccount_response); //Updare the registration object with the card id and save the reg object. var registration = new Registrations({ _id: reg[0]._id, user: $scope.user._id }); reg[0].bankAccountId.push(account_response.id); registration.bankAccountId = reg[0].bankAccountId; registration.$update(function (response) { console.log('registration saved'); $scope.success = true; }, function (error) { console.log('failed saving registration data.'); }); //TODO:balanced get the response credit card account identifier and store with registration.js schema for user alert("created"); }).error(function (response) { alert(response.message); }); }).error(function (response) { alert(response.message); }); }); } else { var customer = { "name": $scope.user.firstName + ' ' + $scope.user.lastName, "email": $scope.user.email, "phone": "" }; $http.post('/createCustomer', customer).success(function (customer_response) { console.log(customer_response); if (!customer_response.id) { alert('Error creating customer'); return; } //Updare the registration object with the customer id and save the reg object. //Updare the registration object with the card id and save the reg object. var registration = new Registrations({ balancedPaymentsId: customer_response.id, _id: reg[0]._id, user: $scope.user._id }); registration.$update(function (save_response) { console.log('registration saved'); $scope.success = true; $http.post('/createAccount', createAccountObj).success(function (account_response) { console.log(account_response); var accountHref = account_response.href; if (!accountHref) { alert('Error creating bank account'); return; } $http.post('/addAccountToCustomer', { "customerHref": "/customers/" + customer_response.id, "accountHref": accountHref }).success(function (addAccountResponse) { console.log(addAccountResponse); registration = new Registrations({ _id: reg[0]._id, user: $scope.user._id }); reg[0].bankAccountId.push(addAccountResponse.id); registration.bankAccountId = reg[0].bankAccountId; registration.$update(function (save_response) { console.log('registration saved'); $scope.success = true; }).error(function (err) { console.log('failed saving registration data.'); }); //TODO:balanced get the response credit card account identifier and store with registration.js schema for user alert("created"); }).error(function (response) { alert(response.message); }); }).error(function (response) { alert(response.message); }); }).error(function (err) { console.log('failed saving registration data.'); }); }). error(function (error) { alert(error); }); } }); }; $scope.getCreditCardsList = function () { console.log('getCreditCardsList()'); appProgress.showPleaseWait(); $http.get('/registrationsdetails/' + $scope.user._id).success(function (reg) { if (reg[0] && reg[0].creditCardId) { for (var i = 0; i < reg[0].creditCardId.length; i++) { $http.post('/getObject', { "objectHref": "/cards/" + reg[0].creditCardId[i] }).success(function (response) { $scope.cards.push({ "cardNumber": response.number, "ExpDate": response.expiration_month + "/" + response.expiration_year, "brand": response.brand, }); }); } } appProgress.hidePleaseWait(); }).error(function (err) { appProgress.hidePleaseWait(); }); $scope.cards = []; $scope.gridCards = { data: 'cards', multiSelect: false, selectedItems: $scope.selectedPart, columnDefs: [{ field: 'cardNumber', displayName: 'Card Number', width: '**', cellTemplate: '<div style="padding:5px"><img src="/img/icons/{{row.entity.brand}}.png" width="40px"/> {{row.entity.cardNumber}} </div>' }, { field: 'ExpDate', displayName: 'Expiration Date' }] }; }; $scope.selectGridRowMyCards = function () { }; $scope.addCard = function () { $('#addCardModal').modal({ backdrop: 'static', keyboard: false }); }; $scope.addCreditCardDialog2 = function () { createDialogService({ id: 'addCreditCardDialog2', title: 'Add Credit Card', backdrop: true, css: { margin: 'auto', width: '50%' }, controller: 'TestingController', templateUrl: 'modules/testing/views/createCreditCard.html', successButtonVisibility: true, cancelButtonVisibility: true, cancel: { label: 'Cancel'}, success: { label: 'Add Card', fn: function () { var successCallback = function () { appProgress.hidePleaseWait(); }; var failureCallback = function (error) { alert("An error occured while adding card."); console.error(error); appProgress.hidePleaseWait(); }; appProgress.showPleaseWait(); creditCardMgmt.updateCreditCard($scope, $scope.user, successCallback, failureCallback); } } }); }; $scope.addBankAccountDialog = function () { createDialogService({ id: 'addBankAccountDialog', title: 'Add Bank Account', backdrop: true, css: { margin: 'auto', width: '50%' }, controller: 'TestingController', templateUrl: 'modules/testing/views/dialogCreateBankAccount.html', successButtonVisibility: true, cancelButtonVisibility: true, cancel: { label: 'Cancel' }, success: { label: 'Add Account', fn: function () { var successCallback = function () { //TODO: refresh page? appProgress.hidePleaseWait(); }; var failureCallback = function (error) { alert("An error occured while adding bank account."); console.error(error); appProgress.hidePleaseWait(); }; appProgress.showPleaseWait(); bankAccountMgmt.updateBankAccount($scope, $scope.user, successCallback, failureCallback); } } }); }; $scope.getCreditCard = function () { console.log('getCreditCard()'); appProgress.showPleaseWait(); $http.get('/registrationsdetails/' + $scope.user._id).success(function (reg) { if (reg && reg[0].creditCardId[0]) { $http.post('/getObject', { "objectHref": "/cards/" + reg[0].creditCardId[0] }).success(function (response) { $("#ccNumber").val(response.number); $("#ccName").val(response.name); $("#ccCode").val(response.cvv); $("#ccExpMonth").val(response.expiration_month); $("#ccExpYear").val(response.expiration_year); $("#ccAddress1").val(response.address.line1); $("#ccAddress2").val(response.address.line2); $("#ccCity").val(response.address.city); $("#ccState").val(response.address.state); $("#ccZip").val(response.address.postal_code); appProgress.hidePleaseWait(); }). error(function (response) { appProgress.hidePleaseWait(); $scope.error = response.message; $scope.payment = null; }); } appProgress.hidePleaseWait(); }) .error(function (error) { appProgress.hidePleaseWait(); alert(error); }); appProgress.hidePleaseWait(); }; $scope.updateCreditCard = function () { console.log('testing.updateCreditCard()'); console.log($scope.payment); appProgress.showPleaseWait(); var card = { "expiration_month": $("#ccExpMonth").val(), "cvv": $("#ccCode").val(), "number": $("#ccNumber").val(), "expiration_year": $("#ccExpYear").val(), "name": $("#ccName").val() }; var address = { "city": $("#ccCity").val(), "line1": $("#ccAddress1").val(), "line2": $("#ccAddress2").val(), "state": $("#ccState").val(), "postal_code": $("#ccZip").val() }; var createCardObj = { "card": card, "address": address }; $http.get('/registrationsdetails/' + $scope.user._id).success(function (reg) { if (reg && reg[0].balancedPaymentsId) { $http.post('/getObject', { "objectHref": "/customers/" + reg[0].balancedPaymentsId }).success(function (response) { $scope.success = $scope.error = null; $http.post('/createCard', createCardObj).success(function (card_response) { console.log(card_response); var cardHref = card_response.href; created_card = card_response; $http.post('/addCardToCustomer', { "customerHref": "/customers/" + reg[0].balancedPaymentsId, "cardHref": created_card.href }).success(function (addCardResponse) { console.log(addCardResponse); console.log('created customer card'); //Updare the registration object with the card id and save the reg object. var registration = new Registrations({ _id: reg[0]._id, user: $scope.user._id }); reg[0].creditCardId.push(addCardResponse.id); registration.creditCardId = reg[0].creditCardId; registration.$update(function (response) { console.log('registration saved'); $scope.success = true; appProgress.hidePleaseWait(); $('#addCardModal').modal('hide'); $scope.getCreditCardsList(); }, function (error) { console.log('failed saving registration data.'); }); }).error(function (response) { alert(response.message); }); }).error(function (response) { alert(response.message); }); }).error(function (response) { }); } else { var customer = { "name": $scope.user.firstName + ' ' + $scope.user.lastName, "email": $scope.user.email, "phone": "" }; $http.post('/createCustomer', customer).success(function (customer_response) { console.log(customer_response); var userHref = customer_response.href; if (userHref == undefined) { console.log('Error creating customer'); appProgress.hidePleaseWait(); return; } var registration = new Registrations({ balancedPaymentsId: customer_response.id, _id: reg[0]._id, user: $scope.user._id }); registration.$update(function (response) { $scope.success = true; //TODO:balanced get the response customer identifier and store with registration.js schema for user $http.post('/createCard', createCardObj).success(function (card_response) { console.log(card_response); var cardHref = card_response.href; created_card = card_response; $http.post('/addCardToCustomer', { "customerHref": "/customers/" + customer_response.id, "cardHref": created_card.href }).success(function (addCardResponse) { console.log(addCardResponse); console.log('created customer card'); console.log(addCardResponse); registration = new Registrations({ _id: reg[0]._id, user: $scope.user._id }); reg[0].creditCardId.push(addCardResponse.id); registration.creditCardId = reg[0].creditCardId; registration.$update(function (save_response) { console.log('registration saved'); $scope.success = true; appProgress.hidePleaseWait(); $('#addCardModal').modal('hide'); $scope.getCreditCardsList(); }).error(function (err) { console.log('failed saving registration data.'); $scope.error = err; }); }).error(function (response) { alert(response.message); }); }).error(function (response) { alert(response.message); }); }, function (response) { $scope.error = response.data.message; }); }) .error(function (error) { alert(error); }); } }); }; $scope.sendSMS = function () { console.log('send sms test'); appProgress.showPleaseWait(); $http.post('/sendSMS', $scope.sms).success(function (response) { // If successful show success message and clear form $scope.success = true; $scope.sms = null; appProgress.hidePleaseWait(); }).error(function (response) { appProgress.hidePleaseWait(); $scope.error = response.message; $scope.sms = null; }); }; $scope.completePurchase = function () { appProgress.showPleaseWait(); $http.post('/completePurchase', $scope.payment).success(function (response) { // If successful show success message and clear form $scope.success = true; $scope.payment = null; appProgress.hidePleaseWait(); }).error(function (response) { appProgress.hidePleaseWait(); $scope.error = response.message; $scope.payment = null; }); }; $scope.sendEmail = function () { appProgress.showPleaseWait(); $http.post('/sendEmail', $scope.email).success(function (response) { // If successful show success message and clear form $scope.success = true; $scope.email = null; appProgress.hidePleaseWait(); }).error(function (response) { appProgress.hidePleaseWait(); $scope.error = response.message; $scope.email = null; }); }; var customer = { "name": "Mahmoud Ali", "dob_year": 1983, "dob_month": 12, "email": "[email protected]", "phone": "+201003183708" }; var card = { "expiration_month": "12", "cvv": "123", "number": "5105105105105100", "expiration_year": "2020", "customer": "" }; var address = { "city": '', "line1": '', "line2": '', "state": '', "postal_code": '' }; var createCardObj = { "card": card, "address": address }; var account = { "routing_number": "121000358",<|fim▁hole|> "account_number": "9900000001" }; var debit = { "appears_on_statement_as": "TEST Transaction", "amount": 5000, "description": "TEST description", "cardHref": "" }; var credit = { "appears_on_statement_as": "TEST Transaction", "amount": 5000, "description": "TEST description", "accountHref": "" }; var created_customer; var created_card; var created_account; var customerHref = ''; $scope.createDemo = function () { $http.post('/createCustomer', customer).success(function (customer_response) { console.log(customer_response); created_customer = customer_response; customerHref = customer_response.href; createCardObj.card.customer = created_customer; $http.post('/createCard', createCardObj).success(function (card_response) { console.log(card_response); var cardHref = card_response.href; created_card = card_response; debit.cardHref = cardHref; $http.post('/addCardToCustomer', { "customerHref": created_customer.href, "cardHref": created_card.href }).success(function (addCardResponse) { console.log(addCardResponse); $http.post('/debitCard', debit).success(function (debit_response) { console.log(debit_response); }); }); }); $http.post('/createAccount', account).success(function (account_response) { console.log(account_response); var accountHref = account_response.href; created_account = account_response; credit.accountHref = accountHref; $http.post('/addAccountToCustomer', { "customerHref": created_customer.href, "accountHref": created_account.href }).success(function (addAccountResponse) { console.log(addAccountResponse); $http.post('/creditAccount', credit).success(function (credit_response) { console.log(credit_response); }); }); }); }); }; /*$http.post('/deleteItem', {"objectHref":"/debits/WD5e3Cc1fRS4D76Zfjf0Vv8l"}).success(function (response) { console.log(response); });/*/ /* $http.post('/deleteItem', {"objectHref":"/cards/CCzkUIc7fbXT48UT73v3XOH"}).success(function (response) { console.log(response); }); $http.post('/deleteItem', {"objectHref":"/customers/CU3pVBwQatDaKcwmgzacl1KH"}).success(function (response) { console.log(response); }).error(function(err) { console.log(err); }); */ //$http.post('/deleteItem', {"objectHref":"/customers/CUwLmXhuPxwRkLVIcRQmqYb"}).success(function (response) { // console.log(response); // }).error(function(err) { // console.log(err); // }); /* $http.post('/deleteItem', {"objectHref":"/customers/CU1LjRwaTmFrhL4uDYhx8ni3"}).success(function (response) { console.log(response); }).error(function(err) { console.log(err); }); /*/ /*$http.post('/debits').success(function (response) { console.log(response); });*/ /*$http.post('/listCustomers', {}).success(function (response) { console.log(response); });*/ /*$http.post('/getObject', {"objectHref":"/debits/"}).success(function (response) { console.log(response); });*/ $scope.addPart = function () { appProgress.showPleaseWait(); $http.post('/createPart', $scope.part).success(function (response) { // If successful show success message and clear form $scope.success = true; $scope.part = null; appProgress.hidePleaseWait(); }).error(function (response) { appProgress.hidePleaseWait(); $scope.error = response.message; $scope.part = null; }); }; } ]);<|fim▁end|>
"account_type": "checking", "name": "Johann Bernoulli",
<|file_name|>graphicsapp.js<|end_file_name|><|fim▁begin|>/***** AVAILABLE JAVASCRIPT FUNCTIONS ******/ /* Function: GraphicsApp() * -------------------------------- * Creates a new GraphicsApp object and returns it. * * Parameters: none */ function GraphicsApp() {} /* Function: addButton(buttonName) * ----------------------------------------------- * Creates and adds a new button to the top area of the webpage. The button * will display the text buttonName. * * Parameters: * ----------- * buttonName: the text that is displayed on the button. */ GraphicsApp.prototype.addButton = function(buttonName, callbackFn) { var inputDiv = document.getElementById("inputDiv"); var button = document.createElement("BUTTON"); button.textContent = buttonName; button.onclick = callbackFn; if (typeof(inputDiv) === "undefined") { inputDiv = document.getElementsByTagName('body'); } inputDiv.appendChild(button); } /* Function: addTextField() * ----------------------------- * Creates and adds a new text field to the top area of the webpage. * Returns the text field object that was added to the page. * * Parameters: none * Returns: the text field that was created. */ GraphicsApp.prototype.addTextField = function() { // Make a new text field var textField = document.createElement("INPUT"); textField.type = "text"; textField.id = "inputField"; // Append it inside our input div var inputDiv = document.getElementById("inputDiv"); if (typeof(inputDiv) === "undefined") { inputDiv = document.getElementsByTagName('body'); } inputDiv.appendChild(textField); return textField; } /* Function: addCanvas() * -------------------------- * Creates and adds a new canvas to the center area of the webpage. * * Parameters: none */ GraphicsApp.prototype.addCanvas = function(width, height) { setBackground(width,height,0xFFFFFF); } /* Function: addTitle(title) * -------------------------------- * Adds a title with the given text at the top of the page. * * Parameters: * ----------- * title: the text of the title to add. */ GraphicsApp.prototype.addTitle = function(title) { // Set the page title to be equal to the passed in text var titleElem = document.createElement("TITLE"); titleElem.textContent = title; var head = document.getElementsByTagName("HEAD")[0]; head.appendChild(titleElem); // Also create and add an H1 element at the top displaying the passed in text var h1 = document.createElement("H1"); h1.textContent = title; var inputDiv = document.getElementById("inputDiv"); var body = document.getElementsByTagName("BODY")[0]; body.insertBefore(h1, inputDiv); } /* Function: displayErrorMessage(error) * -------------------------------- * Displays an error message to the user in red below the text box. * * Parameters: * ----------- * error: the error message to display. */ GraphicsApp.prototype.displayErrorMessage = function(error) { var errorField = document.getElementById("errorField"); errorField.innerHTML = error; } <|fim▁hole|>/* Function: getCurrentLocation() * ---------------------------- * Calculates the user's current location, and calls callbackFn, passing * the user's current latitude and longitude. The provided callbackFn should * therefore be something like * * function callback(latitude, longitude) { * ... * } * * * Parameters: * ----------- * callbackFn: the function that's called once the user's location has been calculated */ GraphicsApp.prototype.getCurrentLocation = function(callbackFn) { // Query the user's location navigator.geolocation.getCurrentPosition(function(position) { callbackFn(position.coords.latitude, position.coords.longitude); }); } /* Function: fetchWeatherForQuery(query, numDays, successFn, errorFn) * ------------------------------------------------------------- * Sends a request to the weather API, passing in the given query. * * Parameters: * ----------- * query: a string query of the place the weather should be fetched for. * * numDays: the number of days for which you want to get the weather. * * successFn: a function that takes a single parameter, the data returned from the API call. * This function will be called upon success of the API call. * * errorFn: a function that takes no parameters. This function will be called upon failure of the API call. */ GraphicsApp.prototype.fetchWeatherForQuery = function(query, numDays, successFn, errorFn) { var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=" + encodeURIComponent(query) + "&mode=json&cnt=" + encodeURIComponent(numDays) + "&units=metric"; this.sendWeatherRequestWithURL(url, successFn, errorFn); } /* Function: fetchWeatherForCoordinates(latitude, longitude, numDays, successFn, errorFn) * ---------------------------------------------------------------------------------- * Sends a request to the weather API, passing in the given coordinates. * * Parameters: * ----------- * latitude: the latitude to fetch the weather for. * * longitude: the longitude to fetch the weather for. * * numDays: the number of days for which you want to get the weather. * * successFn: a function that takes a single parameter, the data returned from the API call. * This function will be called upon success of the API call. * * errorFn: a function that takes no parameters. This function will be called upon failure of the API call. */ GraphicsApp.prototype.fetchWeatherForCoordinates = function(latitude, longitude, numDays, successFn, errorFn) { var url = "http://api.openweathermap.org/data/2.5/forecast/daily?lat=" + encodeURIComponent(latitude) + "&lon=" + encodeURIComponent(longitude) + "&mode=json&cnt=" + encodeURIComponent(numDays) + "&units=metric"; this.sendWeatherRequestWithURL(url, successFn, errorFn); } /*******************************************************/ /********* PRIVATE GraphicsApp METHODS ************/ /* Function: sendWeatherRequestWithURL(url, successFn, errorFn) * --------------------------------------------------------- * Makes an AJAX (Asynchronous Javascript and XML) GET request to the given URL. * If the request is unsuccessful, the errorFn callback is called. If successful, * the weather server will return an array of objects, each representing the weather for * a day. This function then adds the name of each day to each day object (eg. "Monday") and * passes the array to the successFn callback. * * Parameters: * ----------- * url: the URL to send the request to. * * successFn: the function to execute if a response is successfully returned. * * errorFn: the function to execute if the request fails. */ GraphicsApp.prototype.sendWeatherRequestWithURL = function(url, successFn, errorFn) { // The handler for the AJAX requests that call the student's callbacks var obj = this; function xhrHandler() { if (this.readyState != 4) return; else if (this.status != 200 && errorFn) errorFn(); else { var data = JSON.parse(this.responseText); var daysArray = data["list"]; // If there is no data, call the error handler if (daysArray == null) { if (errorFn) errorFn(); return; } else if (!successFn) return; var cleanedDaysArray = []; // Get the array of day names this weather data corresponds to var dayNames = obj.dayNamesStartingToday(daysArray.length); // Pull out only the relevant weather data and store an object for each // day inside of cleanedDaysArray for (var i = 0; i < daysArray.length; i++) { // Create a new day object with the relevant data inside var day = {}; day["dayName"] = dayNames[i]; day["tempHigh"] = daysArray[i]["temp"]["max"]; day["tempLow"] = daysArray[i]["temp"]["min"]; day["weatherDescription"] = daysArray[i]["weather"][0]["main"]; // Rain Clouds Clear Snow day["humidity"] = daysArray[i]["humidity"]; day["windSpeed"] = daysArray[i]["speed"]; // Add it to our days array cleanedDaysArray.push(day); } successFn(cleanedDaysArray); } } // Create and send the request xhr = new XMLHttpRequest(); xhr.onreadystatechange = xhrHandler; xhr.open("GET", url); xhr.send(); } /* Function: dayNamesStartingToday(numDays) * ------------------------------------- * Returns an array of length "numDays" containing consecutive * weekday names starting with today. For example, if today is * Tuesday, and numDays = 4, then dayNamesStartingToday would return * ["Tuesday", "Wednesday", "Thursday", "Friday"]. * * Parameters: * ----------- * numDays: the number day names to include in the array */ GraphicsApp.prototype.dayNamesStartingToday = function(numDays) { // Get the index of today var currDate = new Date(); var todayIndex = currDate.getDay(); var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; // Loop around the day names array starting today and add each day name var daysArray = []; for (var i = 0; i < numDays; i++) { // Loop around the day names array (if we get over 6, loop back around) var index = (todayIndex + i) % 7; daysArray.push(dayNames[index]); } return daysArray; } /****************************************/<|fim▁end|>
<|file_name|>issue-29037.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 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. // compile-pass #![allow(dead_code)] // This test ensures that each pointer type `P<X>` is covariant in `X`. use std::rc::Rc; use std::sync::Arc; fn a<'r>(x: Box<&'static str>) -> Box<&'r str> { x } fn b<'r, 'w>(x: &'w &'static str) -> &'w &'r str { x } <|fim▁hole|>fn d<'r>(x: Rc<&'static str>) -> Rc<&'r str> { x } fn main() {}<|fim▁end|>
fn c<'r>(x: Arc<&'static str>) -> Arc<&'r str> { x }
<|file_name|>CPUmon.rs<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
CPUmon
<|file_name|>proda.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python """ An interface to the web-based PROvider Direct Access (PRODA) system of Medicare Australia """ import mechanize # available via PIP import re m = mechanize.Browser() m.open("https://proda.humanservices.gov.au/prodalogin/pages/public/login.jsf?TAM_OP=login&USER")<|fim▁hole|>m.select_form(name="loginFormAndStuff") m['loginFormAndStuff:inputPassword'] = "Drc232crq838" m['loginFormAndStuff:username'] = 'ihaywood' m.submit() m.select_form(nr=0) m['otp.user.otp'] = raw_input("Emailed code") m.submit() print m.reply() #m.open("https://www2.medicareaustralia.gov.au:5447/pcert/hpos/home.do") #m.select_form(name="termsAndConditionsForm") #m['action'] = "I agree" #m.submit() #m.follow_link(text_regex=re.compile("Claims")) #m.follow_link(text_regex=re.compile("Make a new claim")) #m.follow_link(text_regex=re.compile("Medicare Bulk Bill Webclaim")) print m.read()<|fim▁end|>
<|file_name|>utils.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>use rustc_serialize::{Encodable, Encoder}; use url::Url; use git2::{self, ObjectType}; use core::GitReference; use util::{CargoResult, ChainError, human, ToUrl, internal}; #[derive(PartialEq, Clone, Debug)] pub struct GitRevision(git2::Oid); impl fmt::Display for GitRevision { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } /// GitRemote represents a remote repository. It gets cloned into a local /// GitDatabase. #[derive(PartialEq,Clone,Debug)] pub struct GitRemote { url: Url, } #[derive(PartialEq,Clone,RustcEncodable)] struct EncodableGitRemote { url: String, } impl Encodable for GitRemote { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitRemote { url: self.url.to_string() }.encode(s) } } /// GitDatabase is a local clone of a remote repository's database. Multiple /// GitCheckouts can be cloned from this GitDatabase. pub struct GitDatabase { remote: GitRemote, path: PathBuf, repo: git2::Repository, } #[derive(RustcEncodable)] pub struct EncodableGitDatabase { remote: GitRemote, path: String, } impl Encodable for GitDatabase { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitDatabase { remote: self.remote.clone(), path: self.path.display().to_string() }.encode(s) } } /// GitCheckout is a local checkout of a particular revision. Calling /// `clone_into` with a reference will resolve the reference into a revision, /// and return a CargoError if no revision for that reference was found. pub struct GitCheckout<'a> { database: &'a GitDatabase, location: PathBuf, revision: GitRevision, repo: git2::Repository, } #[derive(RustcEncodable)] pub struct EncodableGitCheckout { database: EncodableGitDatabase, location: String, revision: String, } impl<'a> Encodable for GitCheckout<'a> { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { EncodableGitCheckout { location: self.location.display().to_string(), revision: self.revision.to_string(), database: EncodableGitDatabase { remote: self.database.remote.clone(), path: self.database.path.display().to_string(), }, }.encode(s) } } // Implementations impl GitRemote { pub fn new(url: &Url) -> GitRemote { GitRemote { url: url.clone() } } pub fn url(&self) -> &Url { &self.url } pub fn rev_for(&self, path: &Path, reference: &GitReference) -> CargoResult<GitRevision> { let db = try!(self.db_at(path)); db.rev_for(reference) } pub fn checkout(&self, into: &Path) -> CargoResult<GitDatabase> { let repo = match git2::Repository::open(into) { Ok(repo) => { try!(self.fetch_into(&repo).chain_error(|| { internal(format!("failed to fetch into {}", into.display())) })); repo } Err(..) => { try!(self.clone_into(into).chain_error(|| { internal(format!("failed to clone into: {}", into.display())) })) } }; Ok(GitDatabase { remote: self.clone(), path: into.to_path_buf(), repo: repo, }) } pub fn db_at(&self, db_path: &Path) -> CargoResult<GitDatabase> { let repo = try!(git2::Repository::open(db_path)); Ok(GitDatabase { remote: self.clone(), path: db_path.to_path_buf(), repo: repo, }) } fn fetch_into(&self, dst: &git2::Repository) -> CargoResult<()> { // Create a local anonymous remote in the repository to fetch the url let url = self.url.to_string(); let refspec = "refs/heads/*:refs/heads/*"; fetch(dst, &url, refspec) } fn clone_into(&self, dst: &Path) -> CargoResult<git2::Repository> { let url = self.url.to_string(); if fs::metadata(&dst).is_ok() { try!(fs::remove_dir_all(dst)); } try!(fs::create_dir_all(dst)); let repo = try!(git2::Repository::init_bare(dst)); try!(fetch(&repo, &url, "refs/heads/*:refs/heads/*")); Ok(repo) } } impl GitDatabase { fn path<'a>(&'a self) -> &'a Path { &self.path } pub fn copy_to(&self, rev: GitRevision, dest: &Path) -> CargoResult<GitCheckout> { let checkout = match git2::Repository::open(dest) { Ok(repo) => { let checkout = GitCheckout::new(dest, self, rev, repo); if !checkout.is_fresh() { try!(checkout.fetch()); try!(checkout.reset()); assert!(checkout.is_fresh()); } checkout } Err(..) => try!(GitCheckout::clone_into(dest, self, rev)), }; try!(checkout.update_submodules().chain_error(|| { internal("failed to update submodules") })); Ok(checkout) } pub fn rev_for(&self, reference: &GitReference) -> CargoResult<GitRevision> { let id = match *reference { GitReference::Tag(ref s) => { try!((|| { let refname = format!("refs/tags/{}", s); let id = try!(self.repo.refname_to_id(&refname)); let obj = try!(self.repo.find_object(id, None)); let obj = try!(obj.peel(ObjectType::Commit)); Ok(obj.id()) }).chain_error(|| { human(format!("failed to find tag `{}`", s)) })) } GitReference::Branch(ref s) => { try!((|| { let b = try!(self.repo.find_branch(s, git2::BranchType::Local)); b.get().target().chain_error(|| { human(format!("branch `{}` did not have a target", s)) }) }).chain_error(|| { human(format!("failed to find branch `{}`", s)) })) } GitReference::Rev(ref s) => { let obj = try!(self.repo.revparse_single(s)); obj.id() } }; Ok(GitRevision(id)) } pub fn has_ref(&self, reference: &str) -> CargoResult<()> { try!(self.repo.revparse_single(reference)); Ok(()) } } impl<'a> GitCheckout<'a> { fn new(path: &Path, database: &'a GitDatabase, revision: GitRevision, repo: git2::Repository) -> GitCheckout<'a> { GitCheckout { location: path.to_path_buf(), database: database, revision: revision, repo: repo, } } fn clone_into(into: &Path, database: &'a GitDatabase, revision: GitRevision) -> CargoResult<GitCheckout<'a>> { let repo = try!(GitCheckout::clone_repo(database.path(), into)); let checkout = GitCheckout::new(into, database, revision, repo); try!(checkout.reset()); Ok(checkout) } fn clone_repo(source: &Path, into: &Path) -> CargoResult<git2::Repository> { let dirname = into.parent().unwrap(); try!(fs::create_dir_all(&dirname).chain_error(|| { human(format!("Couldn't mkdir {}", dirname.display())) })); if fs::metadata(&into).is_ok() { try!(fs::remove_dir_all(into).chain_error(|| { human(format!("Couldn't rmdir {}", into.display())) })); } let url = try!(source.to_url().map_err(human)); let url = url.to_string(); let repo = try!(git2::Repository::clone(&url, into).chain_error(|| { internal(format!("failed to clone {} into {}", source.display(), into.display())) })); Ok(repo) } fn is_fresh(&self) -> bool { match self.repo.revparse_single("HEAD") { Ok(head) => head.id().to_string() == self.revision.to_string(), _ => false, } } fn fetch(&self) -> CargoResult<()> { info!("fetch {}", self.repo.path().display()); let url = try!(self.database.path.to_url().map_err(human)); let url = url.to_string(); let refspec = "refs/heads/*:refs/heads/*"; try!(fetch(&self.repo, &url, refspec)); Ok(()) } fn reset(&self) -> CargoResult<()> { info!("reset {} to {}", self.repo.path().display(), self.revision); let object = try!(self.repo.find_object(self.revision.0, None)); try!(self.repo.reset(&object, git2::ResetType::Hard, None)); Ok(()) } fn update_submodules(&self) -> CargoResult<()> { return update_submodules(&self.repo); fn update_submodules(repo: &git2::Repository) -> CargoResult<()> { info!("update submodules for: {:?}", repo.workdir().unwrap()); for mut child in try!(repo.submodules()).into_iter() { try!(child.init(false)); let url = try!(child.url().chain_error(|| { internal("non-utf8 url for submodule") })); // A submodule which is listed in .gitmodules but not actually // checked out will not have a head id, so we should ignore it. let head = match child.head_id() { Some(head) => head, None => continue, }; // If the submodule hasn't been checked out yet, we need to // clone it. If it has been checked out and the head is the same // as the submodule's head, then we can bail out and go to the // next submodule. let head_and_repo = child.open().and_then(|repo| { let target = try!(repo.head()).target(); Ok((target, repo)) }); let repo = match head_and_repo { Ok((head, repo)) => { if child.head_id() == head { continue } repo } Err(..) => { let path = repo.workdir().unwrap().join(child.path()); try!(git2::Repository::clone(url, &path)) } }; // Fetch data from origin and reset to the head commit let refspec = "refs/heads/*:refs/heads/*"; try!(fetch(&repo, url, refspec).chain_error(|| { internal(format!("failed to fetch submodule `{}` from {}", child.name().unwrap_or(""), url)) })); let obj = try!(repo.find_object(head, None)); try!(repo.reset(&obj, git2::ResetType::Hard, None)); try!(update_submodules(&repo)); } Ok(()) } } } fn with_authentication<T, F>(url: &str, cfg: &git2::Config, mut f: F) -> CargoResult<T> where F: FnMut(&mut git2::Credentials) -> CargoResult<T> { // Prepare the authentication callbacks. // // We check the `allowed` types of credentials, and we try to do as much as // possible based on that: // // * Prioritize SSH keys from the local ssh agent as they're likely the most // reliable. The username here is prioritized from the credential // callback, then from whatever is configured in git itself, and finally // we fall back to the generic user of `git`. // // * If a username/password is allowed, then we fallback to git2-rs's // implementation of the credential helper. This is what is configured // with `credential.helper` in git, and is the interface for the OSX // keychain, for example. // // * After the above two have failed, we just kinda grapple attempting to // return *something*. let mut cred_helper = git2::CredentialHelper::new(url); cred_helper.config(cfg); let mut cred_error = false; let ret = f(&mut |url, username, allowed| { let creds = if allowed.contains(git2::SSH_KEY) || allowed.contains(git2::USERNAME) { let user = username.map(|s| s.to_string()) .or_else(|| cred_helper.username.clone()) .unwrap_or("git".to_string()); if allowed.contains(git2::USERNAME) { git2::Cred::username(&user) } else { git2::Cred::ssh_key_from_agent(&user) } } else if allowed.contains(git2::USER_PASS_PLAINTEXT) { git2::Cred::credential_helper(cfg, url, username) } else if allowed.contains(git2::DEFAULT) { git2::Cred::default() } else { Err(git2::Error::from_str("no authentication available")) }; cred_error = creds.is_err(); creds }); if cred_error { ret.chain_error(|| { human("Failed to authenticate when downloading repository") }) } else { ret } } pub fn fetch(repo: &git2::Repository, url: &str, refspec: &str) -> CargoResult<()> { // Create a local anonymous remote in the repository to fetch the url with_authentication(url, &try!(repo.config()), |f| { let mut cb = git2::RemoteCallbacks::new(); cb.credentials(|a, b, c| f(a, b, c)); let mut remote = try!(repo.remote_anonymous(&url, Some(refspec))); try!(remote.add_fetch("refs/tags/*:refs/tags/*")); remote.set_callbacks(&mut cb); try!(remote.fetch(&["refs/tags/*:refs/tags/*", refspec], None)); Ok(()) }) }<|fim▁end|>
use std::fmt; use std::path::{Path, PathBuf}; use std::fs;
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>import datetime from django.contrib.contenttypes.models import ContentType from django.utils import timezone from .models import Action<|fim▁hole|> def create_action(user, verb, target=None): now = timezone.now() last_minute = now - datetime.timedelta(seconds=60) similar_actions = Action.objects.filter(user_id=user.id, verb=verb, created__gte=last_minute) if target: target_ct = ContentType.objects.get_for_model(target) similar_actions = Action.objects.filter(target_ct=target_ct, target_id=target.id) if not similar_actions: action = Action(user=user, verb=verb, target=target) action.save() return True return False<|fim▁end|>
<|file_name|>chart_scatter.py<|end_file_name|><|fim▁begin|>####################################################################### # # An example of creating Excel Scatter charts with Python and XlsxWriter. # # Copyright 2013-2015, John McNamara, [email protected] # import xlsxwriter workbook = xlsxwriter.Workbook('chart_scatter.xlsx') worksheet = workbook.add_worksheet() bold = workbook.add_format({'bold': 1}) # Add the worksheet data that the charts will refer to. headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [10, 40, 50, 20, 10, 50], [30, 60, 70, 50, 40, 30], ] worksheet.write_row('A1', headings, bold) worksheet.write_column('A2', data[0]) worksheet.write_column('B2', data[1]) worksheet.write_column('C2', data[2]) ####################################################################### # # Create a new scatter chart. # chart1 = workbook.add_chart({'type': 'scatter'}) # Configure the first series. chart1.add_series({ 'name': '=Sheet1!$B$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!$B$2:$B$7', }) # Configure second series. Note use of alternative syntax to define ranges. chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2], }) # Add a chart title and some axis labels. chart1.set_title ({'name': 'Results of sample analysis'}) chart1.set_x_axis({'name': 'Test number'}) chart1.set_y_axis({'name': 'Sample length (mm)'}) # Set an Excel chart style. chart1.set_style(11) # Insert the chart into the worksheet (with an offset). worksheet.insert_chart('D2', chart1, {'x_offset': 25, 'y_offset': 10}) ####################################################################### # # Create a scatter chart sub-type with straight lines and markers. # chart2 = workbook.add_chart({'type': 'scatter', 'subtype': 'straight_with_markers'}) # Configure the first series. chart2.add_series({ 'name': '=Sheet1!$B$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!$B$2:$B$7', }) # Configure second series. chart2.add_series({ 'name': '=Sheet1!$C$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!$C$2:$C$7', }) # Add a chart title and some axis labels. chart2.set_title ({'name': 'Straight line with markers'}) chart2.set_x_axis({'name': 'Test number'}) chart2.set_y_axis({'name': 'Sample length (mm)'}) # Set an Excel chart style. chart2.set_style(12) # Insert the chart into the worksheet (with an offset). worksheet.insert_chart('D18', chart2, {'x_offset': 25, 'y_offset': 10}) ####################################################################### # # Create a scatter chart sub-type with straight lines and no markers. # chart3 = workbook.add_chart({'type': 'scatter', 'subtype': 'straight'}) # Configure the first series. chart3.add_series({ 'name': '=Sheet1!$B$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!$B$2:$B$7', }) # Configure second series. chart3.add_series({ 'name': '=Sheet1!$C$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!$C$2:$C$7', }) # Add a chart title and some axis labels. chart3.set_title ({'name': 'Straight line'}) chart3.set_x_axis({'name': 'Test number'}) chart3.set_y_axis({'name': 'Sample length (mm)'}) # Set an Excel chart style. chart3.set_style(13) # Insert the chart into the worksheet (with an offset). worksheet.insert_chart('D34', chart3, {'x_offset': 25, 'y_offset': 10}) ####################################################################### # # Create a scatter chart sub-type with smooth lines and markers. # chart4 = workbook.add_chart({'type': 'scatter', 'subtype': 'smooth_with_markers'}) # Configure the first series. chart4.add_series({ 'name': '=Sheet1!$B$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!$B$2:$B$7', }) # Configure second series. chart4.add_series({ 'name': '=Sheet1!$C$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!$C$2:$C$7', }) # Add a chart title and some axis labels. chart4.set_title ({'name': 'Smooth line with markers'}) chart4.set_x_axis({'name': 'Test number'}) chart4.set_y_axis({'name': 'Sample length (mm)'}) # Set an Excel chart style. chart4.set_style(14) # Insert the chart into the worksheet (with an offset).<|fim▁hole|># Create a scatter chart sub-type with smooth lines and no markers. # chart5 = workbook.add_chart({'type': 'scatter', 'subtype': 'smooth'}) # Configure the first series. chart5.add_series({ 'name': '=Sheet1!$B$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!$B$2:$B$7', }) # Configure second series. chart5.add_series({ 'name': '=Sheet1!$C$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!$C$2:$C$7', }) # Add a chart title and some axis labels. chart5.set_title ({'name': 'Smooth line'}) chart5.set_x_axis({'name': 'Test number'}) chart5.set_y_axis({'name': 'Sample length (mm)'}) # Set an Excel chart style. chart5.set_style(15) # Insert the chart into the worksheet (with an offset). worksheet.insert_chart('D66', chart5, {'x_offset': 25, 'y_offset': 10}) workbook.close()<|fim▁end|>
worksheet.insert_chart('D51', chart4, {'x_offset': 25, 'y_offset': 10}) ####################################################################### #
<|file_name|>crs.py<|end_file_name|><|fim▁begin|># Coordinate reference systems and functions. # # PROJ.4 is the law of this land: http://proj.osgeo.org/. But whereas PROJ.4 # coordinate reference systems are described by strings of parameters such as # # +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs # # here we use mappings: # # {'proj': 'longlat', 'ellps': 'WGS84', 'datum': 'WGS84', 'no_defs': True} # def to_string(crs): """Turn a parameter mapping into a more conventional PROJ.4 string. Mapping keys are tested against the ``all_proj_keys`` list. Values of ``True`` are omitted, leaving the key bare: {'no_defs': True} -> "+no_defs"<|fim▁hole|> """ items = [] for k, v in sorted(filter( lambda x: x[0] in all_proj_keys and x[1] is not False and type (x[1]) in (bool, int, float, str, unicode), crs.items() )): items.append( "+" + "=".join( map(str, filter(lambda y: y and y is not True, (k, v)))) ) return " ".join(items) def from_string(prjs): """Turn a PROJ.4 string into a mapping of parameters. Bare parameters like "+no_defs" are given a value of ``True``. All keys are checked against the ``all_proj_keys`` list. """ parts = [o.lstrip('+') for o in prjs.strip().split()] def parse(v): try: return int(v) except ValueError: pass try: return float(v) except ValueError: return v items = map( lambda kv: len(kv) == 2 and (kv[0], parse(kv[1])) or (kv[0], True), (p.split('=') for p in parts) ) return dict((k,v) for k, v in items if k in all_proj_keys) def from_epsg(code): """Given an integer code, returns an EPSG-like mapping. Note: the input code is not validated against an EPSG database. """ if int(code) <= 0: raise ValueError("EPSG codes are positive integers") return {'init': "epsg:%s" % code, 'no_defs': True} # Below is the big list of PROJ4 parameters from # http://trac.osgeo.org/proj/wiki/GenParms. # It is parsed into a list of paramter keys ``all_proj_keys``. _param_data = """ +a Semimajor radius of the ellipsoid axis +alpha ? Used with Oblique Mercator and possibly a few others +axis Axis orientation (new in 4.8.0) +b Semiminor radius of the ellipsoid axis +datum Datum name (see `proj -ld`) +ellps Ellipsoid name (see `proj -le`) +k Scaling factor (old name) +k_0 Scaling factor (new name) +lat_0 Latitude of origin +lat_1 Latitude of first standard parallel +lat_2 Latitude of second standard parallel +lat_ts Latitude of true scale +lon_0 Central meridian +lonc ? Longitude used with Oblique Mercator and possibly a few others +lon_wrap Center longitude to use for wrapping (see below) +nadgrids Filename of NTv2 grid file to use for datum transforms (see below) +no_defs Don't use the /usr/share/proj/proj_def.dat defaults file +over Allow longitude output outside -180 to 180 range, disables wrapping (see below) +pm Alternate prime meridian (typically a city name, see below) +proj Projection name (see `proj -l`) +south Denotes southern hemisphere UTM zone +to_meter Multiplier to convert map units to 1.0m +towgs84 3 or 7 term datum transform parameters (see below) +units meters, US survey feet, etc. +vto_meter vertical conversion to meters. +vunits vertical units. +x_0 False easting +y_0 False northing +zone UTM zone +a Semimajor radius of the ellipsoid axis +alpha ? Used with Oblique Mercator and possibly a few others +azi +b Semiminor radius of the ellipsoid axis +belgium +beta +czech +e Eccentricity of the ellipsoid = sqrt(1 - b^2/a^2) = sqrt( f*(2-f) ) +ellps Ellipsoid name (see `proj -le`) +es Eccentricity of the ellipsoid squared +f Flattening of the ellipsoid (often presented as an inverse, e.g. 1/298) +gamma +geoc +guam +h +k Scaling factor (old name) +K +k_0 Scaling factor (new name) +lat_0 Latitude of origin +lat_1 Latitude of first standard parallel +lat_2 Latitude of second standard parallel +lat_b +lat_t +lat_ts Latitude of true scale +lon_0 Central meridian +lon_1 +lon_2 +lonc ? Longitude used with Oblique Mercator and possibly a few others +lsat +m +M +n +no_cut +no_off +no_rot +ns +o_alpha +o_lat_1 +o_lat_2 +o_lat_c +o_lat_p +o_lon_1 +o_lon_2 +o_lon_c +o_lon_p +o_proj +over +p +path +proj Projection name (see `proj -l`) +q +R +R_a +R_A Compute radius such that the area of the sphere is the same as the area of the ellipsoid +rf Reciprocal of the ellipsoid flattening term (e.g. 298) +R_g +R_h +R_lat_a +R_lat_g +rot +R_V +s +south Denotes southern hemisphere UTM zone +sym +t +theta +tilt +to_meter Multiplier to convert map units to 1.0m +units meters, US survey feet, etc. +vopt +W +westo +x_0 False easting +y_0 False northing +zone UTM zone """ _lines = filter(lambda x: len(x) > 1, _param_data.split("\n")) all_proj_keys = list( set(line.split()[0].lstrip("+").strip() for line in _lines) ) + ['no_mayo']<|fim▁end|>
and items where the value is otherwise not a str, int, or float are omitted.
<|file_name|>board.js<|end_file_name|><|fim▁begin|>define(["require", "exports", "./base", "./layer", "./util", "./view"], function (require, exports, base_1, layer_1, util_1, view_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.COL_LABELS = base_1.COL_LABELS; class Board extends view_1.View { constructor(parent, position, layers) { super(); this.position = position; this.layers = []; if (typeof (parent) == 'string') { parent = util_1.getElement(parent); } this.elem = parent; this.backgroundColor = '#db6'; let canvas = document.createElement('canvas'); this.ctx = canvas.getContext('2d'); parent.appendChild(canvas); window.addEventListener('resize', () => { this.resizeCanvas(); this.draw(); }); this.resizeCanvas(); this.addLayer(new layer_1.Grid()); this.addLayers(layers); } resizeCanvas() { let pr = util_1.pixelRatio(); let canvas = this.ctx.canvas; let parent = canvas.parentElement; canvas.width = pr * (parent.offsetWidth); canvas.height = pr * (parent.offsetHeight); canvas.style.width = `${parent.offsetWidth}px`; canvas.style.height = `${parent.offsetHeight}px`; this.pointW = this.ctx.canvas.width / (base_1.N + 1); this.pointH = this.ctx.canvas.height / (base_1.N + 1); this.stoneRadius = 0.96 * Math.min(this.pointW, this.pointH) / 2; } newGame(rootPosition) { this.position = rootPosition; for (let layer of this.layers) { layer.clear(); } this.draw(); } addLayer(layer) { this.layers.push(layer); layer.addToBoard(this); } addLayers(layers) { for (let layer of layers) { this.addLayer(layer); } } setPosition(position) { if (this.position == position) { return; } this.position = position; let allProps = new Set(Object.keys(position)); for (let layer of this.layers) { layer.update(allProps);<|fim▁hole|> } update(update) { let anythingChanged = false; let keys = new Set(Object.keys(update)); for (let layer of this.layers) { if (layer.update(keys)) { anythingChanged = true; } } if (anythingChanged) { this.draw(); } } drawImpl() { let ctx = this.ctx; ctx.fillStyle = this.backgroundColor; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); for (let layer of this.layers) { if (layer.show) { layer.draw(); } } } getStone(p) { return this.position.stones[p.row * base_1.N + p.col]; } canvasToBoard(x, y, threshold) { let pr = util_1.pixelRatio(); x *= pr; y *= pr; let canvas = this.ctx.canvas; y = y * (base_1.N + 1) / canvas.height - 0.5; x = x * (base_1.N + 1) / canvas.width - 0.5; let row = Math.floor(y); let col = Math.floor(x); if (row < 0 || row >= base_1.N || col < 0 || col >= base_1.N) { return null; } if (threshold) { let fx = 0.5 - (x - col); let fy = 0.5 - (y - row); let disSqr = fx * fx + fy * fy; if (disSqr > threshold * threshold) { return null; } } return { row: row, col: col }; } boardToCanvas(row, col) { let canvas = this.ctx.canvas; return { x: canvas.width * (col + 1.0) / (base_1.N + 1), y: canvas.height * (row + 1.0) / (base_1.N + 1) }; } drawStones(ps, color, alpha) { if (ps.length == 0) { return; } let ctx = this.ctx; let pr = util_1.pixelRatio(); if (alpha == 1) { ctx.shadowBlur = 4 * pr; ctx.shadowOffsetX = 1.5 * pr; ctx.shadowOffsetY = 1.5 * pr; ctx.shadowColor = `rgba(0, 0, 0, ${color == base_1.Color.Black ? 0.4 : 0.3})`; } ctx.fillStyle = this.stoneFill(color, alpha); let r = this.stoneRadius; for (let p of ps) { let c = this.boardToCanvas(p.row, p.col); ctx.beginPath(); ctx.translate(c.x + 0.5, c.y + 0.5); ctx.arc(0, 0, r, 0, 2 * Math.PI); ctx.fill(); ctx.setTransform(1, 0, 0, 1, 0, 0); } if (alpha == 1) { ctx.shadowColor = 'rgba(0, 0, 0, 0)'; } } stoneFill(color, alpha) { let grad; if (color == base_1.Color.Black) { let ofs = -0.5 * this.stoneRadius; grad = this.ctx.createRadialGradient(ofs, ofs, 0, ofs, ofs, 2 * this.stoneRadius); grad.addColorStop(0, `rgba(68, 68, 68, ${alpha})`); grad.addColorStop(1, `rgba(16, 16, 16, ${alpha})`); } else if (color == base_1.Color.White) { let ofs = -0.2 * this.stoneRadius; grad = this.ctx.createRadialGradient(ofs, ofs, 0, ofs, ofs, 1.2 * this.stoneRadius); grad.addColorStop(0.4, `rgba(255, 255, 255, ${alpha})`); grad.addColorStop(1, `rgba(204, 204, 204, ${alpha})`); } else { throw new Error(`Invalid color ${color}`); } return grad; } } exports.Board = Board; class ClickableBoard extends Board { constructor(parent, position, layerDescs) { super(parent, position, layerDescs); this.enabled = false; this.listeners = []; this.ctx.canvas.addEventListener('mousemove', (e) => { let p = this.canvasToBoard(e.offsetX, e.offsetY, 0.45); if (p != null && this.getStone(p) != base_1.Color.Empty) { p = null; } let changed; if (p != null) { changed = this.p == null || this.p.row != p.row || this.p.col != p.col; } else { changed = this.p != null; } if (changed) { this.p = p; this.draw(); } }); this.ctx.canvas.addEventListener('mouseleave', (e) => { if (this.p != null) { this.p = null; this.draw(); } }); this.ctx.canvas.addEventListener('click', (e) => { if (!this.p || !this.enabled) { return; } for (let listener of this.listeners) { listener(this.p); } this.p = null; this.draw(); }); } onClick(cb) { this.listeners.push(cb); } setPosition(position) { if (position != this.position) { this.p = null; super.setPosition(position); } } drawImpl() { super.drawImpl(); let p = this.enabled ? this.p : null; this.ctx.canvas.style.cursor = p ? 'pointer' : ''; if (p) { this.drawStones([p], this.position.toPlay, 0.6); } } } exports.ClickableBoard = ClickableBoard; }); //# sourceMappingURL=board.js.map<|fim▁end|>
} this.draw();
<|file_name|>client.go<|end_file_name|><|fim▁begin|>// Copyright 2014, Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package vtctlclienttest contains the testsuite against which each // RPC implementation of the vtctlclient interface must be tested. package vtctlclienttest // NOTE: This file is not test-only code because it is referenced by tests in // other packages and therefore it has to be regularly visible. // NOTE: This code is in its own package such that its dependencies (e.g. // zookeeper) won't be drawn into production binaries as well. import ( "io" "strings" "testing" "time" "golang.org/x/net/context" "github.com/youtube/vitess/go/vt/logutil" "github.com/youtube/vitess/go/vt/tabletmanager/tmclient" "github.com/youtube/vitess/go/vt/topo" "github.com/youtube/vitess/go/vt/topo/memorytopo" "github.com/youtube/vitess/go/vt/vtctl/vtctlclient" // import the gRPC client implementation for tablet manager _ "github.com/youtube/vitess/go/vt/tabletmanager/grpctmclient" topodatapb "github.com/youtube/vitess/go/vt/proto/topodata" ) func init() { // enforce we will use the right protocol (gRPC) (note the // client is unused, but it is initialized, so it needs to exist) *tmclient.TabletManagerProtocol = "grpc" } // CreateTopoServer returns the test topo server properly configured func CreateTopoServer(t *testing.T) topo.Server { return memorytopo.NewServer("cell1") } // TestSuite runs the test suite on the given topo server and client func TestSuite(t *testing.T, ts topo.Server, client vtctlclient.VtctlClient) { ctx := context.Background() // Create a fake tablet tablet := &topodatapb.Tablet{ Alias: &topodatapb.TabletAlias{Cell: "cell1", Uid: 1}, Hostname: "localhost", Ip: "10.11.12.13", PortMap: map[string]int32{ "vt": 3333, "mysql": 3334, }, Tags: map[string]string{"tag": "value"}, Keyspace: "test_keyspace", Type: topodatapb.TabletType_MASTER, } if err := ts.CreateTablet(ctx, tablet); err != nil { t.Errorf("CreateTablet: %v", err) } // run a command that's gonna return something on the log channel stream, err := client.ExecuteVtctlCommand(ctx, []string{"ListAllTablets", "cell1"}, 30*time.Second) if err != nil { t.Fatalf("Remote error: %v", err) } got, err := stream.Recv() if err != nil { t.Fatalf("failed to get first line: %v", err) } expected := "cell1-0000000001 test_keyspace <null> master localhost:3333 localhost:3334 [tag: \"value\"]\n" if logutil.EventString(got) != expected { t.Errorf("Got unexpected log line '%v' expected '%v'", got.String(), expected) } got, err = stream.Recv() if err != io.EOF { t.Errorf("Didn't get end of log stream: %v %v", got, err) } // run a command that's gonna fail stream, err = client.ExecuteVtctlCommand(ctx, []string{"ListAllTablets", "cell2"}, 30*time.Second) if err != nil { t.Fatalf("Remote error: %v", err) } got, err = stream.Recv()<|fim▁hole|> expected = "node doesn't exist" if err == nil || !strings.Contains(err.Error(), expected) { t.Fatalf("Unexpected remote error, got: '%v' was expecting to find '%v'", err, expected) } // run a command that's gonna panic stream, err = client.ExecuteVtctlCommand(ctx, []string{"Panic"}, 30*time.Second) if err != nil { t.Fatalf("Remote error: %v", err) } got, err = stream.Recv() expected1 := "this command panics on purpose" expected2 := "uncaught vtctl panic" if err == nil || !strings.Contains(err.Error(), expected1) || !strings.Contains(err.Error(), expected2) { t.Fatalf("Unexpected remote error, got: '%v' was expecting to find '%v' and '%v'", err, expected1, expected2) } // and clean up the tablet if err := ts.DeleteTablet(ctx, tablet.Alias); err != nil { t.Errorf("DeleteTablet: %v", err) } }<|fim▁end|>
<|file_name|>tab.js<|end_file_name|><|fim▁begin|>semantic.dropdown = {}; // ready event semantic.dropdown.ready = function() { // selector cache var // alias handler ; // event handlers handler = { <|fim▁hole|> }; $('.first.example .menu .item') .tab({ context: '.first.example' }) ; $('.history.example .menu .item') .tab({ context : '.history.example', history : true, path : '/modules/tab.html' }) ; $('.dynamic.example .menu .item') .tab({ context : '.dynamic.example', auto : true, path : '/modules/tab.html' }) ; }; // attach ready event $(document) .ready(semantic.dropdown.ready) ;<|fim▁end|>
<|file_name|>ItemForestRelic.java<|end_file_name|><|fim▁begin|>package com.compwiz1548.elementaltemples.item; public class ItemForestRelic extends ItemET { public ItemForestRelic()<|fim▁hole|> } }<|fim▁end|>
{ super(); this.setUnlocalizedName("forestRelic"); this.setMaxStackSize(1);
<|file_name|>criteria-templates.types.disabled-spec.ts<|end_file_name|><|fim▁begin|>// import { IsExact } from "conditional-type-checks"; // import { // InNumberRangeCriterion, // InNumberSetCriterion, // InstancedCriterionTemplate, // NamedCriteria,<|fim▁hole|>// OrCriteriaTemplate, // NamedCriteriaTemplate, // } from "../../criterion"; // // [todo] comment out & fix // // $ExpectType true // type OrCriteria_OneItem = IsExact< // InstancedCriterionTemplate<OrCriteriaTemplate<[typeof InNumberRangeCriterion]>>, // OrCriteria<InNumberRangeCriterion> // >; // // $ExpectType true // type OrCriteria_TwoItems = IsExact< // InstancedCriterionTemplate<OrCriteriaTemplate<[typeof InNumberRangeCriterion, typeof InNumberSetCriterion]>>, // OrCriteria<InNumberRangeCriterion | InNumberSetCriterion> // >; // // $ExpectType true // type NamedCriteria_OneItem = IsExact< // InstancedCriterionTemplate<NamedCriteriaTemplate<{ foo: [typeof InNumberRangeCriterion] }>>, // NamedCriteria<{ foo: InNumberRangeCriterion }> // >; // // $ExpectType true // type NamedCriteria_TwoItems = IsExact< // InstancedCriterionTemplate< // NamedCriteriaTemplate<{ foo: [typeof InNumberRangeCriterion]; bar: [typeof InNumberSetCriterion] }> // >, // NamedCriteria<{ foo: InNumberRangeCriterion; bar: InNumberSetCriterion }> // >; // // $ExpectType true // type NamedCriteria_TwoItems_Nested = IsExact< // InstancedCriterionTemplate< // NamedCriteriaTemplate<{ // foo: [typeof InNumberRangeCriterion, OrCriteriaTemplate<[typeof InNumberRangeCriterion]>]; // bar: [typeof InNumberSetCriterion]; // }> // >, // NamedCriteria<{ foo: InNumberRangeCriterion | OrCriteria<InNumberRangeCriterion>; bar: InNumberSetCriterion }> // >;<|fim▁end|>
// OrCriteria,
<|file_name|>classifier_domain.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Domain objects for classifier models""" import copy class Classifier(object): """Domain object for a classifier. A classifier is a machine learning model created using a particular classification algorithm which is used for answer classification task. Attributes: id: str. The unique id of the classifier. exp_id: str. The exploration id to which this classifier belongs. exp_version_when_created: str. The version of the exploration when this classification model was created. state_name: str. The name of the state to which the classifier belongs. algorithm_id: str. The id of the algorithm used for generating classifier. cached_classifier_data: dict. The actual classifier model used for classification purpose. data_schema_version: int. Schema version of the data used by the classifier. This depends on the algorithm ID. """ def __init__(self, classifier_id, exp_id, exp_version_when_created, state_name, algorithm_id, cached_classifier_data, data_schema_version): """Constructs an Classifier domain object. Args: classifier_id: str. The unique id of the classifier. exp_id: str. The exploration id to which the classifier belongs. exp_version_when_created: str. The version of the exploration when this classification model was created. state_name: str. The name of the state to which the classifier belongs. algorithm_id: str. The id of the algorithm used for generating classifier. cached_classifier_data: dict. The actual classifier model used for classification purpose. data_schema_version: int. Schema version of the data used by the classifier. """ self.id = classifier_id self.exp_id = exp_id self.exp_version_when_created = exp_version_when_created self.state_name = state_name self.algorithm_id = algorithm_id self.cached_classifier_data = copy.deepcopy(cached_classifier_data) self.data_schema_version = data_schema_version def to_dict(self): """Constructs a dict representation of Classifier domain object. Returns: A dict representation of Classifier domain object.<|fim▁hole|> 'exp_id': self.exp_id, 'exp_version_when_created': self.exp_version_when_created, 'state_name': self.state_name, 'algorithm_id': self.algorithm_id, 'cached_classifier_data': self.cached_classifier_data, 'data_schema_version': self.data_schema_version }<|fim▁end|>
""" return { 'classifier_id': self.id,
<|file_name|>test_ivim.py<|end_file_name|><|fim▁begin|>""" Testing the Intravoxel incoherent motion module The values of the various parameters used in the tests are inspired by the study of the IVIM model applied to MR images of the brain by Federau, Christian, et al. [1]. References ---------- .. [1] Federau, Christian, et al. "Quantitative measurement of brain perfusion with intravoxel incoherent motion MR imaging." Radiology 265.3 (2012): 874-881. """ import warnings import numpy as np from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_raises, assert_array_less, run_module_suite, assert_, assert_equal) from dipy.testing import assert_greater_equal import pytest from dipy.reconst.ivim import ivim_prediction, IvimModel from dipy.core.gradients import gradient_table, generate_bvecs from dipy.sims.voxel import multi_tensor from dipy.utils.optpkg import optional_package cvxpy, have_cvxpy, _ = optional_package("cvxpy") needs_cvxpy = pytest.mark.skipif(not have_cvxpy, reason="REQUIRES CVXPY") def setup_module(): global gtab, ivim_fit_single, ivim_model_trr, data_single, params_trr, \ data_multi, ivim_params_trr, D_star, D, f, S0, gtab_with_multiple_b0, \ noisy_single, mevals, gtab_no_b0, ivim_fit_multi, ivim_model_VP, \ f_VP, D_star_VP, D_VP, params_VP # Let us generate some data for testing. bvals = np.array([0., 10., 20., 30., 40., 60., 80., 100., 120., 140., 160., 180., 200., 300., 400., 500., 600., 700., 800., 900., 1000.]) N = len(bvals) bvecs = generate_bvecs(N) gtab = gradient_table(bvals, bvecs.T, b0_threshold=0) S0, f, D_star, D = 1000.0, 0.132, 0.00885, 0.000921 # params for a single voxel params_trr = np.array([S0, f, D_star, D]) mevals = np.array(([D_star, D_star, D_star], [D, D, D])) # This gives an isotropic signal. signal = multi_tensor(gtab, mevals, snr=None, S0=S0, fractions=[f * 100, 100 * (1 - f)]) # Single voxel data data_single = signal[0] data_multi = np.zeros((2, 2, 1, len(gtab.bvals))) data_multi[0, 0, 0] = data_multi[0, 1, 0] = data_multi[ 1, 0, 0] = data_multi[1, 1, 0] = data_single ivim_params_trr = np.zeros((2, 2, 1, 4)) ivim_params_trr[0, 0, 0] = ivim_params_trr[0, 1, 0] = params_trr ivim_params_trr[1, 0, 0] = ivim_params_trr[1, 1, 0] = params_trr ivim_model_trr = IvimModel(gtab, fit_method='trr') ivim_model_one_stage = IvimModel(gtab, fit_method='trr') ivim_fit_single = ivim_model_trr.fit(data_single) ivim_fit_multi = ivim_model_trr.fit(data_multi) ivim_model_one_stage.fit(data_single) ivim_model_one_stage.fit(data_multi) bvals_no_b0 = np.array([5., 10., 20., 30., 40., 60., 80., 100., 120., 140., 160., 180., 200., 300., 400., 500., 600., 700., 800., 900., 1000.]) _ = generate_bvecs(N) # bvecs_no_b0 gtab_no_b0 = gradient_table(bvals_no_b0, bvecs.T, b0_threshold=0) bvals_with_multiple_b0 = np.array([0., 0., 0., 0., 40., 60., 80., 100., 120., 140., 160., 180., 200., 300., 400., 500., 600., 700., 800., 900., 1000.]) bvecs_with_multiple_b0 = generate_bvecs(N) gtab_with_multiple_b0 = gradient_table(bvals_with_multiple_b0, bvecs_with_multiple_b0.T, b0_threshold=0) noisy_single = np.array([4243.71728516, 4317.81298828, 4244.35693359, 4439.36816406, 4420.06201172, 4152.30078125, 4114.34912109, 4104.59375, 4151.61914062, 4003.58374023, 4013.68408203, 3906.39428711, 3909.06079102, 3495.27197266, 3402.57006836, 3163.10180664, 2896.04003906, 2663.7253418, 2614.87695312, 2316.55371094, 2267.7722168]) noisy_multi = np.zeros((2, 2, 1, len(gtab.bvals))) noisy_multi[0, 1, 0] = noisy_multi[ 1, 0, 0] = noisy_multi[1, 1, 0] = noisy_single noisy_multi[0, 0, 0] = data_single ivim_model_VP = IvimModel(gtab, fit_method='VarPro') f_VP, D_star_VP, D_VP = 0.13, 0.0088, 0.000921 # params for a single voxel params_VP = np.array([f, D_star, D]) ivim_params_VP = np.zeros((2, 2, 1, 3)) ivim_params_VP[0, 0, 0] = ivim_params_VP[0, 1, 0] = params_VP ivim_params_VP[1, 0, 0] = ivim_params_VP[1, 1, 0] = params_VP def single_exponential(S0, D, bvals): return S0 * np.exp(-bvals * D) def test_single_voxel_fit(): """ Test the implementation of the fitting for a single voxel. Here, we will use the multi_tensor function to generate a bi-exponential signal. The multi_tensor generates a multi tensor signal and expects eigenvalues of each tensor in mevals. Our basic test requires a scalar signal isotropic signal and hence we set the same eigenvalue in all three directions to generate the required signal. The bvals, f, D_star and D are inspired from the paper by Federau, Christian, et al. We use the function "generate_bvecs" to simulate bvectors corresponding to the bvalues. In the two stage fitting routine, initially we fit the signal values for bvals less than the specified split_b using the TensorModel and get an intial guess for f and D. Then, using these parameters we fit the entire data for all bvalues. """ est_signal = ivim_prediction(ivim_fit_single.model_params, gtab) assert_array_equal(est_signal.shape, data_single.shape) assert_array_almost_equal(ivim_fit_single.model_params, params_trr) assert_array_almost_equal(est_signal, data_single) # Test predict function for single voxel p = ivim_fit_single.predict(gtab) assert_array_equal(p.shape, data_single.shape) assert_array_almost_equal(p, data_single) def test_multivoxel(): """Test fitting with multivoxel data. We generate a multivoxel signal to test the fitting for multivoxel data. This is to ensure that the fitting routine takes care of signals packed as 1D, 2D or 3D arrays. """ ivim_fit_multi = ivim_model_trr.fit(data_multi) est_signal = ivim_fit_multi.predict(gtab, S0=1.) assert_array_equal(est_signal.shape, data_multi.shape) assert_array_almost_equal(ivim_fit_multi.model_params, ivim_params_trr) assert_array_almost_equal(est_signal, data_multi) def test_ivim_errors(): """ Test if errors raised in the module are working correctly. Scipy introduced bounded least squares fitting in the version 0.17 and is not supported by the older versions. Initializing an IvimModel with bounds for older Scipy versions should raise an error. """ ivim_model_trr = IvimModel(gtab, bounds=([0., 0., 0., 0.], [np.inf, 1., 1., 1.]), fit_method='trr') ivim_fit = ivim_model_trr.fit(data_multi) est_signal = ivim_fit.predict(gtab, S0=1.) assert_array_equal(est_signal.shape, data_multi.shape) assert_array_almost_equal(ivim_fit.model_params, ivim_params_trr) assert_array_almost_equal(est_signal, data_multi) def test_mask(): """ Test whether setting incorrect mask raises and error """ mask_correct = data_multi[..., 0] > 0.2 mask_not_correct = np.array([[False, True, False], [True, False]], dtype=np.bool) ivim_fit = ivim_model_trr.fit(data_multi, mask_correct) est_signal = ivim_fit.predict(gtab, S0=1.) assert_array_equal(est_signal.shape, data_multi.shape) assert_array_almost_equal(est_signal, data_multi) assert_array_almost_equal(ivim_fit.model_params, ivim_params_trr) assert_raises(ValueError, ivim_model_trr.fit, data_multi, mask=mask_not_correct) def test_with_higher_S0(): """ Test whether fitting works for S0 > 1. """ # params for a single voxel S0_2 = 1000. params2 = np.array([S0_2, f, D_star, D]) mevals2 = np.array(([D_star, D_star, D_star], [D, D, D])) # This gives an isotropic signal. signal2 = multi_tensor(gtab, mevals2, snr=None, S0=S0_2, fractions=[f * 100, 100 * (1 - f)]) # Single voxel data data_single2 = signal2[0] ivim_fit = ivim_model_trr.fit(data_single2) est_signal = ivim_fit.predict(gtab) assert_array_equal(est_signal.shape, data_single2.shape) assert_array_almost_equal(est_signal, data_single2) assert_array_almost_equal(ivim_fit.model_params, params2) def test_b0_threshold_greater_than0(): """ Added test case for default b0_threshold set to 50. Checks if error is thrown correctly. """ bvals_b0t = np.array([50., 10., 20., 30., 40., 60., 80., 100., 120., 140., 160., 180., 200., 300., 400., 500., 600., 700., 800., 900., 1000.]) N = len(bvals_b0t) bvecs = generate_bvecs(N) gtab = gradient_table(bvals_b0t, bvecs.T) with assert_raises(ValueError) as vae: _ = IvimModel(gtab, fit_method='trr') b0_s = "The IVIM model requires a measurement at b==0. As of " assert b0_s in vae.exception def test_bounds_x0(): """ Test to check if setting bounds for signal where initial value is higher than subsequent values works. These values are from the IVIM dataset which can be obtained by using the `read_ivim` function from dipy.data.fetcher. These are values from the voxel [160, 98, 33] which can be obtained by : .. code-block:: python from dipy.data.fetcher import read_ivim img, gtab = read_ivim() data = load_nifti_data(img) signal = data[160, 98, 33, :] """ x0_test = np.array([1., 0.13, 0.001, 0.0001]) test_signal = ivim_prediction(x0_test, gtab) ivim_fit = ivim_model_trr.fit(test_signal) est_signal = ivim_fit.predict(gtab) assert_array_equal(est_signal.shape, test_signal.shape) def test_predict(): """ Test the model prediction API. The predict method is already used in previous tests for estimation of the signal. But here, we will test is separately. """ assert_array_almost_equal(ivim_fit_single.predict(gtab), data_single) assert_array_almost_equal(ivim_model_trr.predict (ivim_fit_single.model_params, gtab), data_single) ivim_fit_multi = ivim_model_trr.fit(data_multi) assert_array_almost_equal(ivim_fit_multi.predict(gtab), data_multi) def test_fit_object(): """ Test the method of IvimFit class """ assert_raises(IndexError, ivim_fit_single.__getitem__, (-.1, 0, 0)) # Check if the S0 called is matching assert_array_almost_equal( ivim_fit_single.__getitem__(0).model_params, 1000.) ivim_fit_multi = ivim_model_trr.fit(data_multi) # Should raise a TypeError if the arguments are not passed as tuple assert_raises(TypeError, ivim_fit_multi.__getitem__, -.1, 0) # Should return IndexError if invalid indices are passed assert_raises(IndexError, ivim_fit_multi.__getitem__, (100, -0)) assert_raises(IndexError, ivim_fit_multi.__getitem__, (100, -0, 2)) assert_raises(IndexError, ivim_fit_multi.__getitem__, (-100, 0)) assert_raises(IndexError, ivim_fit_multi.__getitem__, [-100, 0]) assert_raises(IndexError, ivim_fit_multi.__getitem__, (1, 0, 0, 3, 4)) # Check if the get item returns the S0 value for voxel (1,0,0) assert_array_almost_equal( ivim_fit_multi.__getitem__((1, 0, 0)).model_params[0], data_multi[1, 0, 0][0]) def test_shape(): """ Test if `shape` in `IvimFit` class gives the correct output. """ assert_array_equal(ivim_fit_single.shape, ()) ivim_fit_multi = ivim_model_trr.fit(data_multi) assert_array_equal(ivim_fit_multi.shape, (2, 2, 1)) def test_multiple_b0(): # Generate a signal with multiple b0 # This gives an isotropic signal. signal = multi_tensor(gtab_with_multiple_b0, mevals, snr=None, S0=S0, fractions=[f * 100, 100 * (1 - f)]) # Single voxel data data_single = signal[0] ivim_model_multiple_b0 = IvimModel(gtab_with_multiple_b0, fit_method='trr') ivim_model_multiple_b0.fit(data_single) # Test if all signals are positive def test_no_b0(): assert_raises(ValueError, IvimModel, gtab_no_b0) def test_noisy_fit(): """ Test fitting for noisy signals. This tests whether the threshold condition applies correctly and returns the linear fitting parameters. For older scipy versions, the returned value of `f` from a linear fit is around 135 and D and D_star values are equal. Hence doing a test based on Scipy version. """ model_one_stage = IvimModel(gtab, fit_method='trr') with warnings.catch_warnings(record=True) as w: fit_one_stage = model_one_stage.fit(noisy_single) assert_equal(len(w), 3) for l_w in w: assert_(issubclass(l_w.category, UserWarning)) assert_("" in str(w[0].message)) assert_("x0 obtained from linear fitting is not feasibile" in str(w[0].message)) assert_("x0 is unfeasible" in str(w[1].message)) assert_("Bounds are violated for leastsq fitting" in str(w[2].message)) assert_array_less(fit_one_stage.model_params, [10000., 0.3, .01, 0.001]) def test_S0(): """ Test if the `IvimFit` class returns the correct S0 """ assert_array_almost_equal(ivim_fit_single.S0_predicted, S0) assert_array_almost_equal(ivim_fit_multi.S0_predicted, ivim_params_trr[..., 0]) def test_perfusion_fraction(): """ Test if the `IvimFit` class returns the correct f """ assert_array_almost_equal(ivim_fit_single.perfusion_fraction, f) assert_array_almost_equal( ivim_fit_multi.perfusion_fraction, ivim_params_trr[..., 1]) def test_D_star(): """ Test if the `IvimFit` class returns the correct D_star """ assert_array_almost_equal(ivim_fit_single.D_star, D_star) assert_array_almost_equal(ivim_fit_multi.D_star, ivim_params_trr[..., 2]) def test_D(): """ Test if the `IvimFit` class returns the correct D """ assert_array_almost_equal(ivim_fit_single.D, D) assert_array_almost_equal(ivim_fit_multi.D, ivim_params_trr[..., 3]) def test_estimate_linear_fit(): """ Test the linear estimates considering a single exponential fit. """ data_single_exponential_D = single_exponential(S0, D, gtab.bvals) assert_array_almost_equal(ivim_model_trr.estimate_linear_fit( data_single_exponential_D, split_b=500., less_than=False), (S0, D)) data_single_exponential_D_star = single_exponential(S0, D_star, gtab.bvals) assert_array_almost_equal(ivim_model_trr.estimate_linear_fit( data_single_exponential_D_star, split_b=100., less_than=True), (S0, D_star)) def test_estimate_f_D_star(): """ Test if the `estimate_f_D_star` returns the correct parameters after a non-linear fit. """ params_f_D = f + 0.001, D + 0.0001 assert_array_almost_equal(ivim_model_trr.estimate_f_D_star(params_f_D, data_single, S0, D), (f, D_star)) def test_fit_one_stage(): """ Test to check the results for the one_stage linear fit. """ model = IvimModel(gtab, two_stage=False) fit = model.fit(data_single) linear_fit_params = [9.88834140e+02, 1.19707191e-01, 7.91176970e-03, 9.30095210e-04] linear_fit_signal = [988.83414044, 971.77122546, 955.46786293, 939.87125905, 924.93258982, 896.85182201, 870.90346447, 846.81187693, 824.34108781, 803.28900104, 783.48245048, 764.77297789, 747.03322866, 669.54798887, 605.03328304, 549.00852235, 499.21077611, 454.40299244, 413.83192296, 376.98072773, 343.45531017] assert_array_almost_equal(fit.model_params, linear_fit_params) assert_array_almost_equal(fit.predict(gtab), linear_fit_signal) def test_leastsq_failing(): """ Test for cases where leastsq fitting fails and the results from a linear fit is returned. """ with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always", category=UserWarning) fit_single = ivim_model_trr.fit(noisy_single) assert_greater_equal(len(w), 3) u_warn = [l_w for l_w in w if issubclass(l_w.category, UserWarning)] assert_greater_equal(len(u_warn), 3) message = ["x0 obtained from linear fitting is not feasibile", "x0 is unfeasible", "Bounds are violated for leastsq fitting"]<|fim▁hole|> # Test for the S0 and D values assert_array_almost_equal(fit_single.S0_predicted, 4356.268901117833) assert_array_almost_equal(fit_single.D, 6.936684e-04) def test_leastsq_error(): """ Test error handling of the `_leastsq` method works when unfeasible x0 is passed. If an unfeasible x0 value is passed using which leastsq fails, the x0 value is returned as it is. """ with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always", category=UserWarning) fit = ivim_model_trr._leastsq(data_single, [-1, -1, -1, -1]) assert_greater_equal(len(w), 1) assert_(issubclass(w[-1].category, UserWarning)) assert_("" in str(w[-1].message)) assert_("x0 is unfeasible" in str(w[-1].message)) assert_array_almost_equal(fit, [-1, -1, -1, -1]) @needs_cvxpy def test_perfusion_fraction_vp(): """ Test if the `IvimFit` class returns the correct f """ ivim_fit_VP = ivim_model_VP.fit(data_single) assert_array_almost_equal(ivim_fit_VP.perfusion_fraction, f_VP, decimal=2) @needs_cvxpy def test_D_star_vp(): """ Test if the `IvimFit` class returns the correct D_star """ ivim_fit_VP = ivim_model_VP.fit(data_single) assert_array_almost_equal(ivim_fit_VP.D_star, D_star_VP, decimal=4) @needs_cvxpy def test_D_vp(): """ Test if the `IvimFit` class returns the correct D """ ivim_fit_VP = ivim_model_VP.fit(data_single) assert_array_almost_equal(ivim_fit_VP.D, D_VP, decimal=4) if __name__ == '__main__': run_module_suite()<|fim▁end|>
assert_greater_equal(len([lw for lw in u_warn for m in message if m in str(lw.message)]), 3)
<|file_name|>test_memorizingfile.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Copyright 2009, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. 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 # OWNER 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. """Tests for memorizingfile module.""" import StringIO import unittest import config # This must be imported before mod_pywebsocket. from mod_pywebsocket import memorizingfile class UtilTest(unittest.TestCase): def check(self, memorizing_file, num_read, expected_list): for unused in range(num_read): memorizing_file.readline() actual_list = memorizing_file.get_memorized_lines() self.assertEqual(len(expected_list), len(actual_list)) for expected, actual in zip(expected_list, actual_list): self.assertEqual(expected, actual) def test_get_memorized_lines(self): memorizing_file = memorizingfile.MemorizingFile(StringIO.StringIO( 'Hello\nWorld\nWelcome')) self.check(memorizing_file, 3, ['Hello\n', 'World\n', 'Welcome']) def test_get_memorized_lines_limit_memorized_lines(self): memorizing_file = memorizingfile.MemorizingFile(StringIO.StringIO( 'Hello\nWorld\nWelcome'), 2) self.check(memorizing_file, 3, ['Hello\n', 'World\n']) def test_get_memorized_lines_empty_file(self): memorizing_file = memorizingfile.MemorizingFile(StringIO.StringIO( '')) self.check(memorizing_file, 10, []) if __name__ == '__main__': unittest.main()<|fim▁hole|><|fim▁end|>
# vi:sts=4 sw=4 et
<|file_name|>SelectionToICompilationUnitList.java<|end_file_name|><|fim▁begin|>/* Copyright (C) 2013 Jason Gowan This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.gowan.plugin; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jface.viewers.IStructuredSelection; public class SelectionToICompilationUnitList implements List<ICompilationUnit> { private List<ICompilationUnit> list; public SelectionToICompilationUnitList(IStructuredSelection selection){ List<ICompilationUnit> localList = new ArrayList<ICompilationUnit>(); List<Object> selectionList = selection.toList(); for (Object object : selectionList) { localList.addAll( delegate(object) ); } this.list = localList; } protected List<ICompilationUnit> delegate(Object selected){ List<ICompilationUnit> compilationUnits = new ArrayList<ICompilationUnit>(); if( selected instanceof ICompilationUnit ){ compilationUnits.add((ICompilationUnit)selected); }else if ( selected instanceof IPackageFragment){ compilationUnits.addAll(get((IPackageFragment)selected)); }else if( selected instanceof IPackageFragmentRoot){ compilationUnits.addAll(get((IPackageFragmentRoot)selected)); }else if( selected instanceof IJavaProject){ compilationUnits.addAll(get((IJavaProject)selected)); } return compilationUnits; } protected List<ICompilationUnit> get(IJavaProject selected) { List<ICompilationUnit> result = new ArrayList<ICompilationUnit>(); IPackageFragmentRoot[] packageRoots; try { packageRoots = selected.getAllPackageFragmentRoots(); for(int i=0; i<packageRoots.length; i++){ result.addAll(get(packageRoots[i])); } } catch (JavaModelException e) { e.printStackTrace();<|fim▁hole|> } return result; } protected List<ICompilationUnit> get(IPackageFragment frag){ List<ICompilationUnit> result = new ArrayList<ICompilationUnit>(); try { result = Arrays.asList(frag.getCompilationUnits()); } catch (JavaModelException e) { e.printStackTrace(); } return result; } protected List<ICompilationUnit> get(IPackageFragmentRoot root){ List<ICompilationUnit> result = new ArrayList<ICompilationUnit>(); try { for (IJavaElement frag : Arrays.asList(root.getChildren())) { if( frag instanceof IPackageFragment ){ result.addAll(get((IPackageFragment) frag)); } } } catch (JavaModelException e) { e.printStackTrace(); } return result; } @Override public int size() { return list.size(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public boolean contains(Object o) { return list.contains(o); } @Override public Iterator<ICompilationUnit> iterator() { return list.iterator(); } @Override public Object[] toArray() { return list.toArray(); } @Override public <T> T[] toArray(T[] a) { return list.toArray(a); } @Override public boolean add(ICompilationUnit e) { return list.add(e); } @Override public boolean remove(Object o) { return list.remove(o); } @Override public boolean containsAll(Collection<?> c) { return list.contains(c); } @Override public boolean addAll(Collection<? extends ICompilationUnit> c) { return list.addAll(c); } @Override public boolean addAll(int index, Collection<? extends ICompilationUnit> c) { return list.addAll(c); } @Override public boolean removeAll(Collection<?> c) { return list.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return list.retainAll(c); } @Override public void clear() { list.clear(); } @Override public ICompilationUnit get(int index) { return list.get(index); } @Override public ICompilationUnit set(int index, ICompilationUnit element) { return list.set(index, element); } @Override public void add(int index, ICompilationUnit element) { list.add(index, element); } @Override public ICompilationUnit remove(int index) { return list.remove(index); } @Override public int indexOf(Object o) { return list.indexOf(o); } @Override public int lastIndexOf(Object o) { return list.lastIndexOf(o); } @Override public ListIterator<ICompilationUnit> listIterator() { return list.listIterator(); } @Override public ListIterator<ICompilationUnit> listIterator(int index) { return list.listIterator(index); } @Override public List<ICompilationUnit> subList(int fromIndex, int toIndex) { return list.subList(fromIndex, toIndex); } }<|fim▁end|>
<|file_name|>svh-a-change-type-arg.rs<|end_file_name|><|fim▁begin|>// Copyright 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. //! The `svh-a-*.rs` files are all deviations from the base file //! svh-a-base.rs with some difference (usually in `fn foo`) that //! should not affect the strict version hash (SVH) computation //! (#14132). #![crate_name = "a"] use std::marker::MarkerTrait; macro_rules! three { () => { 3 } } pub trait U : MarkerTrait {} pub trait V : MarkerTrait {} impl U for () {} impl V for () {} static A_CONSTANT : int = 2; pub fn foo<T:U>(_: i32) -> int {<|fim▁hole|>pub fn an_unused_name() -> int { 4 }<|fim▁end|>
3 }
<|file_name|>make_interim.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import logging from dotenv import find_dotenv, load_dotenv from constants import * import json from utils import json_from_file, merge_json import shutil from settings import * def prepare_train_data(): """ Runs data processing scripts to turn traning raw data from (../raw) into interim data to be analyzed (saved in ../interim). """ logger = logging.getLogger(__name__) logger.info('Making interim train data set from raw data') # Init absolute path of folders raw_input_folder_path = os.path.join(DATA_RAW_ROOT, DATASET_NAME, RAW_INPUT_FOLDER) raw_output_folder_path = os.path.join(DATA_RAW_ROOT, DATASET_NAME, RAW_OUTPUT_FOLDER) interim_folder_path = os.path.join(DATA_INTERIM_ROOT, DATASET_NAME) # Read veracities from both test and dev files veracity_labels = merge_json( json_from_file(os.path.join(raw_output_folder_path, VERACITY_LABEL_FILE[0])), json_from_file(os.path.join(raw_output_folder_path, VERACITY_LABEL_FILE[1]))) # Read stances from both test and dev files stance_labels = merge_json( json_from_file(os.path.join(raw_output_folder_path, STANCE_LABEL_FILE[0])), json_from_file(os.path.join(raw_output_folder_path, STANCE_LABEL_FILE[1]))) # If interim data existed, delete and create a new one if os.path.exists(interim_folder_path): shutil.rmtree(interim_folder_path) os.makedirs(interim_folder_path) for event_name in DATASET_EVENTS: interim_event_folder_path = os.path.join(interim_folder_path, event_name) os.makedirs(interim_event_folder_path) event_folder_path = os.path.join(raw_input_folder_path, event_name) list_tweet_ids = [name for name in os.listdir(event_folder_path) if os.path.isdir(os.path.join(event_folder_path,name))] for index, id in enumerate(list_tweet_ids): # thread conversation folder in raw source_tweet_folder_path = os.path.join(event_folder_path, id) # read source tweet source_tweet_file = open(os.path.join(source_tweet_folder_path,'source-tweet', id + '.json'), 'r') source_tweet_content = source_tweet_file.read() source_tweet_file.close() source_tweet = json.loads(source_tweet_content) source_tweet_replies = [] # read replies replies_folder_path = os.path.join(source_tweet_folder_path, 'replies') list_reply_ids = [name for name in os.listdir(replies_folder_path) if os.path.isfile(os.path.join(replies_folder_path, name))] for reply_id in list_reply_ids: reply_file = open(os.path.join(replies_folder_path, reply_id), "r") reply_content = reply_file.read() reply_file.close() reply = json.loads(reply_content) reply['stance'] = stance_labels[reply['id_str']] source_tweet_replies.append(reply) <|fim▁hole|> # read structure structure_file = open(os.path.join(source_tweet_folder_path,'structure.json'), "r") structure_content = structure_file.read() structure_file.close() structure = json.loads(structure_content) source_tweet['structure'] = structure source_tweet['veracity'] = veracity_labels[source_tweet['id_str']] source_tweet['stance'] = stance_labels[source_tweet['id_str']] # create tweet file in interim to write interim_tweet_file = open(os.path.join(interim_event_folder_path, str(index) + '.json'), "w") # write tweet to interim interim_tweet_file.write(json.dumps(source_tweet, indent = 4)) interim_tweet_file.close() def prepare_test_data(): """ Runs data processing scripts to turn testing raw data from (../raw) into interim data to be analyzed (saved in ../interim). """ logger = logging.getLogger(__name__) logger.info('Making interim test data set from raw data') # Init absolute path of folders raw_input_folder_path = os.path.join(DATA_RAW_ROOT, TESTSET_NAME) raw_output_folder_path = os.path.join(DATA_RAW_ROOT, TESTSET_NAME) interim_folder_path = os.path.join(DATA_INTERIM_ROOT, TESTSET_NAME) # Read veracities from both test and dev files veracity_labels = json_from_file(os.path.join(raw_output_folder_path, VERACITY_LABEL_TEST_FILE[0])) # Read stances from both test and dev files stance_labels = json_from_file(os.path.join(raw_output_folder_path, STANCE_LABEL_TEST_FILE[0])) # If interim data existed, delete and create a new one if os.path.exists(interim_folder_path): shutil.rmtree(interim_folder_path) os.makedirs(interim_folder_path) list_tweet_ids = [name for name in os.listdir(raw_input_folder_path) if os.path.isdir(os.path.join(raw_input_folder_path, name))] for index, id in enumerate(list_tweet_ids): # thread conversation folder in raw source_tweet_folder_path = os.path.join(raw_input_folder_path, id) # read source tweet source_tweet_file = open(os.path.join(source_tweet_folder_path, 'source-tweet', id + '.json'), 'r') source_tweet_content = source_tweet_file.read() source_tweet_file.close() source_tweet = json.loads(source_tweet_content) source_tweet_replies = [] # read replies replies_folder_path = os.path.join(source_tweet_folder_path, 'replies') list_reply_ids = [name for name in os.listdir(replies_folder_path) if os.path.isfile(os.path.join(replies_folder_path, name))] for reply_id in list_reply_ids: reply_file = open(os.path.join(replies_folder_path, reply_id), "r") reply_content = reply_file.read() reply_file.close() reply = json.loads(reply_content) reply['stance'] = stance_labels[reply['id_str']] source_tweet_replies.append(reply) source_tweet['replies'] = source_tweet_replies # read structure structure_file = open(os.path.join(source_tweet_folder_path, 'structure.json'), "r") structure_content = structure_file.read() structure_file.close() structure = json.loads(structure_content) source_tweet['structure'] = structure source_tweet['veracity'] = veracity_labels[source_tweet['id_str']] source_tweet['stance'] = stance_labels[source_tweet['id_str']] # create tweet file in interim to write interim_tweet_file = open(os.path.join(interim_folder_path, str(index) + '.json'), "w") # write tweet to interim interim_tweet_file.write(json.dumps(source_tweet, indent=4)) interim_tweet_file.close() if __name__ == '__main__': log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logging.basicConfig(level=logging.INFO, format=log_fmt) # find .env automagically by walking up directories until it's found, then # load up the .env entries as environment variables load_dotenv(find_dotenv()) prepare_train_data() prepare_test_data()<|fim▁end|>
source_tweet['replies'] = source_tweet_replies
<|file_name|>table_test.qtpl.go<|end_file_name|><|fim▁begin|>// Code generated by qtc from "table_test.qtpl". DO NOT EDIT. // See https://github.com/valyala/quicktemplate for details. //line views/templates/tables/table_test.qtpl:1 package tables //line views/templates/tables/table_test.qtpl:1 import ( qtio422016 "io" qt422016 "github.com/valyala/quicktemplate" ) //line views/templates/tables/table_test.qtpl:1 var ( _ = qtio422016.Copy _ = qt422016.AcquireByteBuffer ) //line views/templates/tables/table_test.qtpl:1 func StreamTableTesting(qw422016 *qt422016.Writer) { //line views/templates/tables/table_test.qtpl:1 qw422016.N().S(` <html> <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <link rel="import" href="/components/paper-datatable/paper-datatable-card.html"> <link rel="import" href="/components/paper-datatable/paper-datatable.html"> <iron-ajax url="/bookings/check.json" last-response="{{data}}" auto></iron-ajax> <template is="dom-bind" id="app"> <paper-datatable data="[[data]]" > <template is="dom-repeat" items="[[data.items]]"> <paper-datatable-column header="[[item[0]]]" property="[[item[0][1]]]" type="Number" sortable></paper-datatable-column> </template> </paper-datatable> </template> <script> $(function(){ Polymer({ is:"dom-bind", data:{ type: Array, notify: true }, }); }) </script> <script src="/webcomponents.js"></script> `) //line views/templates/tables/table_test.qtpl:26 } //line views/templates/tables/table_test.qtpl:26 func WriteTableTesting(qq422016 qtio422016.Writer) { //line views/templates/tables/table_test.qtpl:26 qw422016 := qt422016.AcquireWriter(qq422016) //line views/templates/tables/table_test.qtpl:26 StreamTableTesting(qw422016) //line views/templates/tables/table_test.qtpl:26 qt422016.ReleaseWriter(qw422016) //line views/templates/tables/table_test.qtpl:26 } //line views/templates/tables/table_test.qtpl:26<|fim▁hole|>func TableTesting() string { //line views/templates/tables/table_test.qtpl:26 qb422016 := qt422016.AcquireByteBuffer() //line views/templates/tables/table_test.qtpl:26 WriteTableTesting(qb422016) //line views/templates/tables/table_test.qtpl:26 qs422016 := string(qb422016.B) //line views/templates/tables/table_test.qtpl:26 qt422016.ReleaseByteBuffer(qb422016) //line views/templates/tables/table_test.qtpl:26 return qs422016 //line views/templates/tables/table_test.qtpl:26 }<|fim▁end|>
<|file_name|>media.py<|end_file_name|><|fim▁begin|># oppia/api/media.py from django.conf import settings from django.contrib.auth import authenticate from django.http import HttpResponseRedirect, Http404, HttpResponse, JsonResponse from django.utils.translation import ugettext_lazy as _ from django.views.decorators.csrf import csrf_exempt from django.contrib import messages from oppia.api.publish import get_messages_array from oppia.av.models import UploadedMedia from oppia.av import handler @csrf_exempt def upload_view(request): # get the messages to clear possible previous unprocessed messages get_messages_array(request) if request.method != 'POST': return HttpResponse(status=405) required = ['username', 'password'] validation_errors = [] for field in required: if field not in request.POST: validation_errors.append("field '{0}' missing".format(field)) # authenticate user username = request.POST.get("username") password = request.POST.get("password") user = authenticate(username=username, password=password) if user is None or not user.is_active: messages.error(request, "Invalid username/password") response_data = { 'message': _('Authentication errors'), 'messages': get_messages_array(request) } return JsonResponse(response_data, status=401) if validation_errors: return JsonResponse({'errors': validation_errors}, status=400, ) result = handler.upload(request, user) if result['result'] == UploadedMedia.UPLOAD_STATUS_SUCCESS: media = result['media'] embed_code = media.get_embed_code(request.build_absolute_uri(media.file.url)) <|fim▁hole|> return JsonResponse({'embed_code': embed_code}, status=201) else: response = {'messages': result['errors']} return JsonResponse(response, status=400)<|fim▁end|>
<|file_name|>file_util.py<|end_file_name|><|fim▁begin|>import os import unicodedata from keras.applications import InceptionV3, VGG16, MobileNet image_type = ['.jpg'] def check_img(file_name): """To check image Args: file_name : file name Returns: if this file is image """<|fim▁hole|> file_name, file_ext = os.path.splitext(file_name) if file_ext in image_type: return True return False def extract_type(file_name, delimiter): """To extract type from file name Args: file_name : face img name delimiter : delimiter Returns: type: type of face """ file_name, ext = os.path.splitext(file_name) type = file_name if delimiter in type: type = type.split(delimiter)[0] type = unicodedata.normalize('NFC', type) return type def make_model(model, image_size): if model == "inceptionv3": base_model = InceptionV3(include_top=False, input_shape=image_size + (3,)) elif model == "vgg16" or model is None: base_model = VGG16(include_top=False, input_shape=image_size + (3,)) elif model == "mobilenet": base_model = MobileNet(include_top=False, input_shape=image_size + (3,)) return base_model<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import random sys.path.append('.') from twisted.internet import reactor import marionette_tg.driver import marionette_tg.multiplexer import marionette_tg.record_layer import marionette_tg.updater EVENT_LOOP_FREQUENCY_S = 0.01 AUTOUPDATE_DELAY = 5 class MarionetteException(Exception): pass class Client(object): def __init__(self, format_name, format_version): self.multiplexer_outgoing_ = marionette_tg.multiplexer.BufferOutgoing() self.multiplexer_incoming_ = marionette_tg.multiplexer.BufferIncoming() self.multiplexer_incoming_.addCallback(self.process_cell) self.streams_ = {} self.stream_counter_ = random.randint(1,2**32-1) self.set_driver(format_name, format_version) self.reload_ = False # first update must be reactor.callLater(AUTOUPDATE_DELAY, self.check_for_update) def set_driver(self, format_name, format_version=None): self.format_name_ = format_name if format_version == None: self.format_version_ = marionette_tg.dsl.get_latest_version( 'client', format_name) else: self.format_version_ = format_version self.driver_ = marionette_tg.driver.ClientDriver("client") self.driver_.set_multiplexer_incoming(self.multiplexer_incoming_) self.driver_.set_multiplexer_outgoing(self.multiplexer_outgoing_) self.driver_.setFormat(self.format_name_, self.format_version_) def get_format(self): retval = str(self.format_name_) + \ ':' + \ str(self.format_version_) return retval def execute(self, reactor): if self.driver_.isRunning(): self.driver_.execute(reactor) else: if self.reload_: self.set_driver(self.format_name_) self.reload_ = False self.driver_.reset() reactor.callLater(EVENT_LOOP_FREQUENCY_S, self.execute, reactor) def process_cell(self, cell_obj): payload = cell_obj.get_payload() if payload: stream_id = cell_obj.get_stream_id() self.streams_[stream_id].srv_queue.put(payload) def start_new_stream(self, srv_queue=None): stream = marionette_tg.multiplexer.MarionetteStream( self.multiplexer_incoming_, self.multiplexer_outgoing_, self.stream_counter_, srv_queue) stream.host = self self.streams_[self.stream_counter_] = stream self.stream_counter_ = random.randint(1,2**32-1) return stream def terminate(self, stream_id): del self.streams_[stream_id] # call this function if you want reload formats from disk # at the next possible time def reload_driver(self): self.reload_ = True def check_for_update(self): # uncomment the following line to check for updates every N seconds # instead of just on startup # reactor.callLater(N, self.check_for_update, reactor) if marionette_tg.conf.get("general.autoupdate"): self.do_update(self.reload_driver) def do_update(self, callback): # could be replaced with code that updates from a different # source (e.g., local computations) update_server = marionette_tg.conf.get("general.update_server") updater = marionette_tg.updater.FormatUpdater(update_server, use_marionette=True, callback=callback) return updater.do_update() class Server(object): factory = None def __init__(self, format_name): self.multiplexer_outgoing_ = marionette_tg.multiplexer.BufferOutgoing() self.multiplexer_incoming_ = marionette_tg.multiplexer.BufferIncoming() self.multiplexer_incoming_.addCallback(self.process_cell) self.factory_instances = {} if self.check_for_update(): self.do_update() self.set_driver(format_name) self.reload_ = False def set_driver(self, format_name): self.format_name_ = format_name<|fim▁hole|> def execute(self, reactor): if not self.driver_.isRunning(): if self.reload_: self.set_driver(self.format_name_) self.reload_ = False self.driver_.execute(reactor) reactor.callLater(EVENT_LOOP_FREQUENCY_S, self.execute, reactor) def process_cell(self, cell_obj): cell_type = cell_obj.get_cell_type() stream_id = cell_obj.get_stream_id() if cell_type == marionette_tg.record_layer.END_OF_STREAM: self.factory_instances[stream_id].connectionLost() del self.factory_instances[stream_id] elif cell_type == marionette_tg.record_layer.NORMAL: if not self.factory_instances.get(stream_id): stream = marionette_tg.multiplexer.MarionetteStream( self.multiplexer_incoming_, self.multiplexer_outgoing_, stream_id) self.factory_instances[stream_id] = self.factory() self.factory_instances[stream_id].connectionMade(stream) payload = cell_obj.get_payload() if payload: self.factory_instances[stream_id].dataReceived(payload) # call this function if you want reload formats from disk # at the next possible time def reload_driver(self): self.reload_ = True def check_for_update(self): # uncomment the following line to check for updates every N seconds # instead of just on startup # reactor.callLater(N, self.check_for_update, reactor) if marionette_tg.conf.get("general.autoupdate"): self.do_update(self.reload_driver) def do_update(self, callback): # could be replaced with code that updates from a different # source (e.g., local computations) update_server = marionette_tg.conf.get("general.update_server") updater = marionette_tg.updater.FormatUpdater(update_server, use_marionette=False, callback=callback) return updater.do_update()<|fim▁end|>
self.driver_ = marionette_tg.driver.ServerDriver("server") self.driver_.set_multiplexer_incoming(self.multiplexer_incoming_) self.driver_.set_multiplexer_outgoing(self.multiplexer_outgoing_) self.driver_.setFormat(self.format_name_)
<|file_name|>test_spar_functions.py<|end_file_name|><|fim▁begin|>#----------------------------------------------------------------------------- # Copyright (c) 2014, HFTools Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- import os import numpy as np <|fim▁hole|>from hftools.testing import TestCase basepath = os.path.split(__file__)[0] def make_array(a): dims = (aobj.DimSweep("f", len(a)), aobj.DimMatrix_i("i", 2), aobj.DimMatrix_j("j", 2)) return aobj.hfarray(a, dims=dims) class Test_cascade(TestCase): def setUp(self): self.a = make_array([[[0, 1], [1, 0j]]]) self.b = make_array([[[0, 2], [2, 0j]]]) self.c = make_array([[[0.1, 0j], [0, 0.1]]]) def test_cascade_1(self): r = spfun.cascadeS(self.a, self.a) self.assertTrue(np.allclose(r, self.a)) def test_cascade_2(self): r = spfun.cascadeS(self.a, self.b) self.assertTrue(np.allclose(r, self.b)) def test_cascade_3(self): r = spfun.cascadeS(self.b, self.b) self.assertTrue(np.allclose(r, self.a * 4)) def test_cascade_4(self): r = spfun.cascadeS(self.a, self.c) self.assertTrue(np.allclose(r, self.c)) def test_cascade_5(self): r = spfun.cascadeS(self.b, self.c) self.assertTrue(np.allclose(r, make_array([[[0.4, 0j], [0, 0.1]]]))) def test_cascade_6(self): r = spfun.cascadeS(self.c, self.b) self.assertTrue(np.allclose(r, make_array([[[0.1, 0j], [0, 0.4]]]))) class Test_deembedleft(TestCase): def setUp(self): self.a = make_array([[[0, 1], [1, 0j]]]) self.b = make_array([[[0, 2], [2, 0j]]]) self.c = make_array([[[0.1, 0j], [0, 0.1]]]) def test_cascade_1(self): r = spfun.deembedleft(self.a, self.a) self.assertTrue(np.allclose(r, self.a)) def test_cascade_2(self): r = spfun.deembedleft(self.b, self.b) self.assertTrue(np.allclose(r, self.a)) def test_cascade_3(self): r = spfun.deembedleft(self.b, self.c) self.assertTrue(np.allclose(r, make_array([[[0.025, 0j], [0, 0.1]]]))) class Test_deembedright(TestCase): def setUp(self): self.a = make_array([[[0, 1], [1, 0j]]]) self.b = make_array([[[0, 2], [2, 0j]]]) self.c = make_array([[[0.1, 0j], [0, 0.1]]]) def test_cascade_1(self): r = spfun.deembedright(self.a, self.a) self.assertTrue(np.allclose(r, self.a)) def test_cascade_2(self): r = spfun.deembedright(self.b, self.b) self.assertTrue(np.allclose(r, self.a)) def test_cascade_3(self): r = spfun.deembedright(self.c, self.b) self.assertTrue(np.allclose(r, make_array([[[0.1, 0j], [0, 0.025]]]))) class Test_deembed(TestCase): def setUp(self): self.a = make_array([[[0, 1], [1, 0j]]]) self.b = make_array([[[0, 2], [2, 0j]]]) self.c = make_array([[[0.1, 0j], [0, 0.1]]]) def test_cascade_1(self): r = spfun.deembed(self.a, self.a, self.a) self.assertTrue(np.allclose(r, self.a)) def test_cascade_2(self): r = spfun.deembed(self.b, self.b, self.a) self.assertTrue(np.allclose(r, self.a)) def test_cascade_3(self): r = spfun.deembed(self.a, self.b, self.b) self.assertTrue(np.allclose(r, self.a)) def test_cascade_4(self): r = spfun.deembed(self.b, self.c, self.b) self.assertAllclose(r, make_array([[[0.025, 0j], [0, 0.025]]]))<|fim▁end|>
import hftools.dataset.arrayobj as aobj import hftools.networks.spar_functions as spfun
<|file_name|>cesdkhandler.cpp<|end_file_name|><|fim▁begin|>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "cesdkhandler.h" #include <utils/environment.h> #include <QtCore/QFile> #include <QtCore/QDebug> #include <QtCore/QXmlStreamReader> using namespace ProjectExplorer; using namespace ProjectExplorer::Internal; using Utils::Environment; CeSdkInfo::CeSdkInfo() : m_major(0), m_minor(0) { } void CeSdkInfo::addToEnvironment(Environment &env) { qDebug() << "adding " << name() << "to Environment"; env.set("INCLUDE", m_include); env.set("LIB", m_lib); env.prependOrSetPath(m_bin); } CeSdkHandler::CeSdkHandler() { } bool CeSdkHandler::parse(const QString &vsdir) { // look at the file at %VCInstallDir%/vcpackages/WCE.VCPlatform.config // and scan through all installed sdks... m_list.clear(); VCInstallDir = vsdir; QDir vStudioDir(VCInstallDir); if (!vStudioDir.cd("vcpackages")) return false; QFile configFile(vStudioDir.absoluteFilePath(QLatin1String("WCE.VCPlatform.config"))); qDebug()<<"##"; if (!configFile.exists() || !configFile.open(QIODevice::ReadOnly)) return false; qDebug()<<"parsing"; QString currentElement; CeSdkInfo currentItem; QXmlStreamReader xml(&configFile); while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement()) { currentElement = xml.name().toString(); if (currentElement == QLatin1String("Platform")) currentItem = CeSdkInfo(); else if (currentElement == QLatin1String("Directories")) { QXmlStreamAttributes attr = xml.attributes(); currentItem.m_include = fixPaths(attr.value(QLatin1String("Include")).toString()); currentItem.m_lib = fixPaths(attr.value(QLatin1String("Library")).toString()); currentItem.m_bin = fixPaths(attr.value(QLatin1String("Path")).toString()); } } else if (xml.isEndElement()) { if (xml.name().toString() == QLatin1String("Platform")) m_list.append(currentItem); } else if (xml.isCharacters() && !xml.isWhitespace()) { if (currentElement == QLatin1String("PlatformName")) currentItem.m_name = xml.text().toString(); else if (currentElement == QLatin1String("OSMajorVersion")) currentItem.m_major = xml.text().toString().toInt();<|fim▁hole|> else if (currentElement == QLatin1String("OSMinorVersion")) currentItem.m_minor = xml.text().toString().toInt(); } } if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qWarning("CeSdkHandler::parse(): XML ERROR: %d : %s", int(xml.lineNumber()), qPrintable(xml.errorString())); return false; } return m_list.size() > 0 ? true : false; } CeSdkInfo CeSdkHandler::find(const QString &name) { qDebug() << "looking for platform " << name; for (QList<CeSdkInfo>::iterator it = m_list.begin(); it != m_list.end(); ++it) { qDebug() << "...." << it->name(); if (it->name() == name) return *it; } return CeSdkInfo(); }<|fim▁end|>
<|file_name|>bulls_and_cows.py<|end_file_name|><|fim▁begin|>__author__ = 'BeyondSky' from collections import defaultdict class Solution(object): def getHint(self, secret, guess): """ :type secret: str :type guess: str :rtype: str """ bulls = cows = 0 digits = defaultdict(int) # first pass: count bulls and non-matching digits for index in range(len(secret)): if secret[index] == guess[index]: # matches, count the number of bulls bulls += 1 else: # not match, increase number of non-matching digits digits[secret[index]] += 1 # second pass: count number of cows for index in range(len(secret)): if secret[index] != guess[index]:<|fim▁hole|> digits[guess[index]] -= 1 return str(bulls) + 'A' + str(cows) + 'B'<|fim▁end|>
# decrease number of non-matching digit by 1 if it is greater than 0 if digits[guess[index]] > 0: cows += 1
<|file_name|>node_win32_etw_provider.cc<|end_file_name|><|fim▁begin|>#include "node_dtrace.h" #include "node_win32_etw_provider.h" #include "node_etw_provider.h" #include "node_win32_etw_provider-inl.h" namespace node { using v8::JitCodeEvent; using v8::V8; HMODULE advapi; REGHANDLE node_provider; EventRegisterFunc event_register; EventUnregisterFunc event_unregister; EventWriteFunc event_write; int events_enabled; static uv_async_t dispatch_etw_events_change_async; struct v8tags { char prefix[32 - sizeof(size_t)]; size_t prelen; }; // The v8 CODE_ADDED event name has a prefix indicating the type of event. // Many of these are internal to v8. // The trace_codes array specifies which types are written. struct v8tags trace_codes[] = { #define MAKE_V8TAG(s) { s, sizeof(s) - 1 } MAKE_V8TAG("LazyCompile:"), MAKE_V8TAG("Script:"), MAKE_V8TAG("Function:"), MAKE_V8TAG("RegExp:"), MAKE_V8TAG("Eval:") #undef MAKE_V8TAG }; /* Below are some code prefixes which are not being written. * "Builtin:" * "Stub:" * "CallIC:" * "LoadIC:" * "KeyedLoadIC:" * "StoreIC:" * "KeyedStoreIC:" * "CallPreMonomorphic:" * "CallInitialize:" * "CallMiss:" * "CallMegamorphic:" */ // v8 sometimes puts a '*' or '~' in front of the name. #define V8_MARKER1 '*' #define V8_MARKER2 '~' // If prefix is not in filtered list return -1, // else return length of prefix and marker. int FilterCodeEvents(const char* name, size_t len) { for (size_t i = 0; i < arraysize(trace_codes); i++) { size_t prelen = trace_codes[i].prelen; if (prelen < len) { if (strncmp(name, trace_codes[i].prefix, prelen) == 0) { if (name[prelen] == V8_MARKER1 || name[prelen] == V8_MARKER2) prelen++; return prelen; } } } return -1; } // callback from V8 module passes symbol and address info for stack walk void CodeAddressNotification(const JitCodeEvent* jevent) { int pre_offset = 0; if (NODE_V8SYMBOL_ENABLED()) { switch (jevent->type) { case JitCodeEvent::CODE_ADDED: pre_offset = FilterCodeEvents(jevent->name.str, jevent->name.len); if (pre_offset >= 0) { // skip over prefix and marker NODE_V8SYMBOL_ADD(jevent->name.str + pre_offset, jevent->name.len - pre_offset, jevent->code_start, jevent->code_len); } break; case JitCodeEvent::CODE_REMOVED: NODE_V8SYMBOL_REMOVE(jevent->code_start, 0); break; case JitCodeEvent::CODE_MOVED: NODE_V8SYMBOL_MOVE(jevent->code_start, jevent->new_code_start); break;<|fim▁hole|> default: break; } } } // Call v8 to enable or disable code event callbacks. // Must be on default thread to do this. // Note: It is possible to call v8 from ETW thread, but then // event callbacks are received in the same thread. Attempts // to write ETW events in this thread will fail. void etw_events_change_async(uv_async_t* handle) { if (events_enabled > 0) { NODE_V8SYMBOL_RESET(); v8::Isolate::GetCurrent()->SetJitCodeEventHandler( v8::kJitCodeEventEnumExisting, CodeAddressNotification); } else { v8::Isolate::GetCurrent()->SetJitCodeEventHandler( v8::kJitCodeEventDefault, nullptr); } } // This callback is called by ETW when consumers of our provider // are enabled or disabled. // The callback is dispatched on ETW thread. // Before calling into V8 to enable code events, switch to default thread. void NTAPI etw_events_enable_callback( LPCGUID SourceId, ULONG IsEnabled, UCHAR Level, ULONGLONG MatchAnyKeyword, ULONGLONG MatchAllKeywords, PEVENT_FILTER_DESCRIPTOR FilterData, PVOID CallbackContext) { if (IsEnabled) { events_enabled++; if (events_enabled == 1) { uv_async_send(&dispatch_etw_events_change_async); } } else { events_enabled--; if (events_enabled == 0) { uv_async_send(&dispatch_etw_events_change_async); } } } void init_etw() { events_enabled = 0; advapi = LoadLibraryW(L"advapi32.dll"); if (advapi) { event_register = (EventRegisterFunc) GetProcAddress(advapi, "EventRegister"); event_unregister = (EventUnregisterFunc) GetProcAddress(advapi, "EventUnregister"); event_write = (EventWriteFunc)GetProcAddress(advapi, "EventWrite"); // create async object used to invoke main thread from callback CHECK_EQ(0, uv_async_init(uv_default_loop(), &dispatch_etw_events_change_async, etw_events_change_async)); uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_etw_events_change_async)); if (event_register) { DWORD status = event_register(&NODE_ETW_PROVIDER, etw_events_enable_callback, nullptr, &node_provider); CHECK_EQ(status, ERROR_SUCCESS); } } } void shutdown_etw() { if (advapi && event_unregister && node_provider) { event_unregister(node_provider); node_provider = 0; } events_enabled = 0; v8::Isolate::GetCurrent()->SetJitCodeEventHandler( v8::kJitCodeEventDefault, nullptr); if (advapi) { FreeLibrary(advapi); advapi = nullptr; } } } // namespace node<|fim▁end|>
<|file_name|>epoch_fetch.rs<|end_file_name|><|fim▁begin|>// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::sync::{Arc, Weak}; use ethcore::encoded; use ethcore::engines::{EthEngine, StateDependentProof}; use ethcore::header::Header; use ethcore::machine::EthereumMachine; use ethcore::receipt::Receipt; use ethsync::LightSync; use futures::{future, Future}; use futures::future::Either; use light::client::fetch::ChainDataFetcher; use light::on_demand::{request, OnDemand}; use parking_lot::RwLock; use bigint::hash::H256; const ALL_VALID_BACKREFS: &str = "no back-references, therefore all back-references valid; qed"; type BoxFuture<T, E> = Box<Future<Item = T, Error = E>>; /// Allows on-demand fetch of data useful for the light client. pub struct EpochFetch { /// A handle to the sync service. pub sync: Arc<RwLock<Weak<LightSync>>>, /// The on-demand request service. pub on_demand: Arc<OnDemand>, } impl EpochFetch { fn request<T>(&self, req: T) -> BoxFuture<T::Out, &'static str> where T: Send + request::RequestAdapter + 'static, T::Out: Send + 'static { Box::new(match self.sync.read().upgrade() { Some(sync) => { let on_demand = &self.on_demand; let maybe_future = sync.with_context(move |ctx| {<|fim▁hole|> on_demand.request(ctx, req).expect(ALL_VALID_BACKREFS) }); match maybe_future { Some(x) => Either::A(x.map_err(|_| "Request canceled")), None => Either::B(future::err("Unable to access network.")), } } None => Either::B(future::err("Unable to access network")), }) } } impl ChainDataFetcher for EpochFetch { type Error = &'static str; type Body = BoxFuture<encoded::Block, &'static str>; type Receipts = BoxFuture<Vec<Receipt>, &'static str>; type Transition = BoxFuture<Vec<u8>, &'static str>; fn block_body(&self, header: &Header) -> Self::Body { self.request(request::Body(header.encoded().into())) } /// Fetch block receipts. fn block_receipts(&self, header: &Header) -> Self::Receipts { self.request(request::BlockReceipts(header.encoded().into())) } /// Fetch epoch transition proof at given header. fn epoch_transition(&self, hash: H256, engine: Arc<EthEngine>, checker: Arc<StateDependentProof<EthereumMachine>>) -> Self::Transition { self.request(request::Signal { hash: hash, engine: engine, proof_check: checker, }) } }<|fim▁end|>
<|file_name|>0039_auto_20161101_1555.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-11-01 22:55 from __future__ import unicode_literals from django.db import migrations from django.db import models class Migration(migrations.Migration): <|fim▁hole|> operations = [ migrations.AlterField( model_name='formatpreset', name='id', field=models.CharField(choices=[('high_res_video', 'High Resolution'), ('low_res_video', 'Low Resolution'), ('vector_video', 'Vectorized'), ('video_thumbnail', 'Thumbnail'), ('video_subtitle', 'Subtitle'), ('audio', 'Audio'), ('audio_thumbnail', 'Thumbnail'), ('document', 'Document'), ( 'document_thumbnail', 'Thumbnail'), ('exercise', 'Exercise'), ('exercise_thumbnail', 'Thumbnail'), ('exercise_image', 'Exercise Image'), ('exercise_graphie', 'Exercise Graphie'), ('channel_thumbnail', 'Channel Thumbnail')], max_length=150, primary_key=True, serialize=False), ), ]<|fim▁end|>
dependencies = [ ('contentcuration', '0038_contentnode_author'), ]
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
from .generate_detachment_ltd_erosion import DetachmentLtdErosion from .generate_erosion_by_depth_slope import DepthSlopeProductErosion __all__ = ["DetachmentLtdErosion", "DepthSlopeProductErosion"]
<|file_name|>test_quil.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python ############################################################################## # Copyright 2016-2017 Rigetti Computing # # 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 pyquil.forest as qvm_endpoint from pyquil.quil import Program from pyquil.quilbase import DirectQubit from pyquil.gates import I, X, Y, Z, H, T, S, RX, RY, RZ, CNOT, CCNOT, PHASE, CPHASE00, CPHASE01, \ CPHASE10, CPHASE, SWAP, CSWAP, ISWAP, PSWAP, MEASURE, HALT, WAIT, NOP, RESET, \ TRUE, FALSE, NOT, AND, OR, MOVE, EXCHANGE from pyquil.quilbase import InstructionGroup, DefGate, Gate, reset_label_counter, RawInstr, Addr import pytest import numpy as np from math import pi, sqrt def test_make_connection(): qvm_endpoint.Connection() def test_gate(): tg = Gate("TEST", qubits=(DirectQubit(1), DirectQubit(2)), params=[]) assert tg.out() == "TEST 1 2" def test_defgate(): dg = DefGate("TEST", np.array([[1., 0.], [0., 1.]])) assert dg.out() == "DEFGATE TEST:\n 1.0, 0.0\n 0.0, 1.0\n" test = dg.get_constructor() tg = test(DirectQubit(1), DirectQubit(2)) assert tg.out() == "TEST 1 2" def test_defgate_non_square_should_throw_error(): with pytest.raises(AssertionError) as error_info: DefGate("TEST", np.array([[0 + 0.5j, 0.5, 1], [0.5, 0 - 0.5j, 1]])) assert str(error_info.value) == "Matrix must be square." def test_defgate_non_unitary_should_throw_error(): with pytest.raises(AssertionError) as error_info: DefGate("TEST", np.array([[0, 1], [2, 3]])) assert str(error_info.value) == "Matrix must be unitary." def test_defgate_param(): dgp = DefGate("TEST", [[1., 0.], [0., 1.]]) assert dgp.out() == "DEFGATE TEST:\n 1.0, 0.0\n 0.0, 1.0\n" test = dgp.get_constructor() tg = test(DirectQubit(1)) assert tg.out() == "TEST 1" def test_instruction_group_gates(): ig = InstructionGroup() ig.inst(H(0), X(1)) assert len(ig.actions) == 2 assert ig.out() == "H 0\nX 1\n" def test_instruction_group_tuple(): ig = InstructionGroup() ig.inst(("Y", 0), ("X", 1)) assert len(ig.actions) == 2 assert ig.out() == "Y 0\nX 1\n" def test_instruction_group_string(): ig = InstructionGroup() ig.inst("Y 0", "X 1", ) assert len(ig.actions) == 2 assert ig.out() == "Y 0\nX 1\n" def test_program_gates(): ig = Program() ig.inst(H(0), X(1)) assert len(ig.actions) == 2 assert ig.out() == "H 0\nX 1\n" def test_program_pop(): prog = Program(X(0), X(1)) _, instruction = prog.pop() assert prog.out() == "X 0\n" assert Program(instruction).out() == "X 1\n" def test_plus_operator(): p = Program() p += H(0) p += [X(0), Y(0), Z(0)] assert len(p.actions) == 4 assert p.out() == "H 0\nX 0\nY 0\nZ 0\n" def test_program_plus_program(): p = Program().inst(X(0)) q = Program().inst(Y(0)) r = p + q assert len(p.actions) == 1 assert len(q.actions) == 1 assert len(r.actions) == 2 assert p.out() == "X 0\n" assert q.out() == "Y 0\n" assert r.out() == "X 0\nY 0\n" def test_program_tuple(): ig = Program() ig.inst(("Y", 0), ("X", 1)) assert len(ig.actions) == 2 assert ig.out() == "Y 0\nX 1\n" def test_program_string(): ig = Program() ig.inst("Y 0", "X 1", ) assert len(ig.actions) == 2 assert all(isinstance(i[1], RawInstr) for i in ig.actions) assert ig.out() == "Y 0\nX 1\n" def test_prog_init(): p = Program() p.inst(X(0)).measure(0, 0) assert p.out() == 'X 0\nMEASURE 0 [0]\n' def test_classical_regs(): p = Program() p.inst(X(0)).measure(0, 1) assert p.out() == 'X 0\nMEASURE 0 [1]\n' def test_simple_instructions(): p = Program().inst(HALT, WAIT, RESET, NOP) assert p.out() == 'HALT\nWAIT\nRESET\nNOP\n' def test_unary_classicals(): p = Program() p.inst(TRUE(0), FALSE(Addr(1)), NOT(2)) assert p.out() == 'TRUE [0]\n' \ 'FALSE [1]\n' \ 'NOT [2]\n' def test_binary_classicals(): p = Program() p.inst(AND(0, 1), OR(Addr(0), Addr(1)), MOVE(0, 1), EXCHANGE(0, Addr(1))) assert p.out() == 'AND [0] [1]\n' \ 'OR [0] [1]\n' \ 'MOVE [0] [1]\n' \ 'EXCHANGE [0] [1]\n' def test_measurement_calls(): p = Program() p.inst(MEASURE(0, 1), MEASURE(0, Addr(1))) assert p.out() == 'MEASURE 0 [1]\n' * 2 def test_construction_syntax(): p = Program().inst(X(0), Y(1), Z(0)).measure(0, 1) assert p.out() == 'X 0\nY 1\nZ 0\nMEASURE 0 [1]\n' p = Program().inst(X(0)).inst(Y(1)).measure(0, 1).inst(MEASURE(1, 2)) assert p.out() == 'X 0\nY 1\nMEASURE 0 [1]\nMEASURE 1 [2]\n' p = Program().inst(X(0)).measure(0, 1).inst(Y(1), X(0)).measure(0, 0) assert p.out() == 'X 0\nMEASURE 0 [1]\nY 1\nX 0\nMEASURE 0 [0]\n' def test_singles(): p = Program(I(0), X(0), Y(1), Z(1), H(2), T(2), S(1)) assert p.out() == 'I 0\nX 0\nY 1\nZ 1\nH 2\nT 2\nS 1\n' def test_rotations(): p = Program(RX(0.5)(0), RY(0.1)(1), RZ(1.4)(2)) assert p.out() == 'RX(0.5) 0\nRY(0.1) 1\nRZ(1.4) 2\n' def test_controlled_gates(): p = Program(CNOT(0, 1), CCNOT(0, 1, 2)) assert p.out() == 'CNOT 0 1\nCCNOT 0 1 2\n' def test_phases(): p = Program(PHASE(np.pi)(1), CPHASE00(np.pi)(0, 1), CPHASE01(np.pi)(0, 1), CPHASE10(np.pi)(0, 1), CPHASE(np.pi)(0, 1)) assert p.out() == 'PHASE(3.141592653589793) 1\nCPHASE00(3.141592653589793) 0 1\n' \ 'CPHASE01(3.141592653589793) 0 1\nCPHASE10(3.141592653589793) 0 1\n' \ 'CPHASE(3.141592653589793) 0 1\n' def test_swaps(): p = Program(SWAP(0, 1), CSWAP(0, 1, 2), ISWAP(0, 1), PSWAP(np.pi)(0, 1)) assert p.out() == 'SWAP 0 1\nCSWAP 0 1 2\nISWAP 0 1\nPSWAP(3.141592653589793) 0 1\n' def test_def_gate(): # First we define the new gate from a matrix x_gate_matrix = np.array(([0.0, 1.0], [1.0, 0.0])) sqrt_x = np.array([[ 0.5+0.5j, 0.5-0.5j], [ 0.5-0.5j, 0.5+0.5j]]) p = Program().defgate("SQRT-X", sqrt_x) # Then we can use the new gate p.inst(("SQRT-X", 0)) assert p.out() == 'DEFGATE SQRT-X:\n 0.5+0.5i, 0.5-0.5i\n 0.5-0.5i, 0.5+0.5i\n\nSQRT-X 0\n' def test_multiqubit_gate(): # A multi-qubit defgate example x_gate_matrix = np.array(([0.0, 1.0], [1.0, 0.0])) sqrt_x = np.array([[ 0.5+0.5j, 0.5-0.5j], [ 0.5-0.5j, 0.5+0.5j]]) x_sqrt_x = np.kron(sqrt_x, x_gate_matrix) p = Program().defgate("X-SQRT-X", x_sqrt_x) # Then we can use the new gate p.inst(("X-SQRT-X", 0, 1)) assert p.out() == 'DEFGATE X-SQRT-X:\n 0.0+0.0i, 0.5+0.5i, 0.0+0.0i, 0.5-0.5i\n ' \ '0.5+0.5i, 0.0+0.0i, 0.5-0.5i, 0.0+0.0i\n ' \<|fim▁hole|> def test_define_qft(): def qft3(q0, q1, q2): p = Program() p.inst(H(q2), CPHASE(pi / 2.0)(q1, q2), H(1), CPHASE(pi / 4.0)(q0, q2), CPHASE(pi / 2.0)(q0, q1), H(q0), SWAP(q0, q2)) return p # I(2) is to force 3 qubits in state prep program. state_prep = Program().inst(X(0)) prog = state_prep + qft3(0, 1, 2) output = prog.out() print output assert output == 'X 0\nH 2\nCPHASE(1.5707963267948966) 1 2\nH 1\nCPHASE(0.7853981633974483) 0 ' \ '2\nCPHASE(1.5707963267948966) 0 1\nH 0\nSWAP 0 2\n' def test_control_flows(): reset_label_counter() classical_flag_register = 2 p = Program(X(0), H(0)).measure(0, classical_flag_register) # run p in a loop until classical_flag_register is 0 loop_prog = Program(X(0)).measure(0, classical_flag_register) loop_prog.while_do(classical_flag_register, p) assert loop_prog.out() == 'X 0\nMEASURE 0 [2]\nLABEL @START1\nJUMP-UNLESS @END2 [2]\nX ' \ '0\nH 0\nMEASURE 0 [2]\nJUMP @START1\nLABEL @END2\n' # create a program that branches based on the value of a classical register x_prog = Program(X(0)) z_prog = Program() branch = Program(H(1)).measure(1, 1).if_then(1, x_prog, z_prog).measure(0, 0) assert branch.out() == 'H 1\nMEASURE 1 [1]\nJUMP-WHEN @THEN3 [1]\nJUMP @END4\nLABEL ' \ '@THEN3\nX 0\nLABEL @END4\nMEASURE 0 [0]\n' def test_if_option(): reset_label_counter() p = Program(X(0)).measure(0, 0).if_then(0, Program(X(1))) assert p.out() == 'X 0\nMEASURE 0 [0]\nJUMP-WHEN @THEN1 [0]\nJUMP @END2\n' \ 'LABEL @THEN1\nX 1\nLABEL @END2\n' def test_alloc_free(): p = Program() print p.resource_manager.in_use q1 = p.alloc() p.inst(H(q1)) p.free(q1) q2 = p.alloc() p.inst(H(q2)) p.free(q2) assert p.resource_manager.live_qubits == [] assert p.out() == "H 0\nH 0\n" def test_alloc_free(): p = Program() p.inst(H(0)) # H 0 q1 = p.alloc() # q1 = 1 q2 = p.alloc() # q2 = 3 p.inst(CNOT(q1, q2)) # CNOT 1 3 p.inst(H(2)) q3 = p.alloc() # q3 = 4 p.inst(X(q3)) # X 4 p.free(q1) # remove 1 q4 = p.alloc() # q4 = 1 p.inst(Y(q4)) # Y 1 p.free(q2) p.free(q3) p.free(q4) assert p.resource_manager.live_qubits == [] assert p.out() == "H 0\n" \ "CNOT 1 3\n" \ "H 2\n" \ "X 4\n" \ "Y 1\n" def test_multiple_instantiate(): p = Program() q = p.alloc() p.inst(H(q)) p.free(q) assert p.out() == 'H 0\n' assert p.out() == 'H 0\n' def test_alloc_no_free(): p = Program() q1 = p.alloc() q2 = p.alloc() p.inst(H(q1)) p.inst(H(q2)) assert p.out() == 'H 0\nH 1\n' assert p.out() == 'H 0\nH 1\n' def test_extract_qubits(): p = Program(RX(0.5)(0), RY(0.1)(1), RZ(1.4)(2)) assert p.extract_qubits() == set([0, 1, 2]) p.if_then(0, X(4), H(5)).measure(6, 2) assert p.extract_qubits() == set([0, 1, 2, 4, 5, 6]) p.while_do(0, Program(X(3)).measure(3, 0)) assert p.extract_qubits() == set([0, 1, 2, 3, 4, 5, 6]) new_qubit = p.alloc() p.inst(X(new_qubit)) p.synthesize() assert p.extract_qubits() == set([0, 1, 2, 3, 4, 5, 6, new_qubit.index()])<|fim▁end|>
'0.0+0.0i, 0.5-0.5i, 0.0+0.0i, 0.5+0.5i\n ' \ '0.5-0.5i, 0.0+0.0i, 0.5+0.5i, 0.0+0.0i\n\nX-SQRT-X 0 1\n'
<|file_name|>DROID_export_comparer.py<|end_file_name|><|fim▁begin|>import csv import os #### make sure these file names are the same as the ones on your system baseline_csv = r"baseline.csv" new_csv = r"cleaned_csv.csv" ########### do not edit below this line ################# baseline_as_rows = [] new_as_rows = [] if not os.path.exists(baseline_csv): quit("The baseline log csv file is not found - please check your filename '{}'".format(baseline_csv)) if not os.path.exists(new_csv): quit("Your local log csv file is not found - please check your filename '{}'".format(new_csv)) with open(baseline_csv) as data: baseline_as_csv = csv.reader(data) for row in baseline_as_csv: baseline_as_rows.append(row) with open(new_csv) as new_data: new_rows = csv.reader(new_data) for row in new_rows: <|fim▁hole|> quit("Your csv log file '{}' does not have the same number of rows as the baseline log '{}'.".format(new_csv, baseline_csv)) else: print "Your csv log file '{}' has the same number of rows as the baseline log '{}'.".format(new_csv, baseline_csv) print for i, row in enumerate(baseline_as_rows): if row != new_as_rows[i]: print "Different row data detected in row #{}".format(i+1) print "Baseline: \t{}".format(row) print "New: \t\t{}".format(new_as_rows[i]) print print "Comparison complete. If you do not see any rows indicated as 'different' your log file is the same as the baseline. Congrats!\nIf you see rows indicated as 'different' check your DROID settings and try again\n\n"<|fim▁end|>
new_as_rows.append(row) if len(baseline_as_rows) != len(new_as_rows):
<|file_name|>buffer.go<|end_file_name|><|fim▁begin|>// Copyright 2015 Google Inc. 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. package summary import ( info "github.com/google/cadvisor/info/v2" ) // Manages a buffer of usage samples. // This is similar to stats buffer in cache/memory. // The main difference is that we do not pre-allocate the buffer as most containers // won't live that long. type SamplesBuffer struct { // list of collected samples. samples []info.Usage // maximum size this buffer can grow to. maxSize int // index for the latest sample. index int } // Initializes an empty buffer. func NewSamplesBuffer(size int) *SamplesBuffer { return &SamplesBuffer{ index: -1, maxSize: size, } } // Returns the current number of samples in the buffer. func (s *SamplesBuffer) Size() int { return len(s.samples) } // Add an element to the buffer. Oldest one is overwritten if required. func (s *SamplesBuffer) Add(stat info.Usage) { if len(s.samples) < s.maxSize { s.samples = append(s.samples, stat) s.index++ return } s.index = (s.index + 1) % s.maxSize s.samples[s.index] = stat<|fim▁hole|>func (s *SamplesBuffer) RecentStats(n int) []*info.Usage { if n > len(s.samples) { n = len(s.samples) } start := s.index - (n - 1) if start < 0 { start += len(s.samples) } out := make([]*info.Usage, n) for i := 0; i < n; i++ { index := (start + i) % len(s.samples) out[i] = &s.samples[index] } return out }<|fim▁end|>
} // Returns pointers to the last 'n' stats.
<|file_name|>production.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import<|fim▁hole|><|fim▁end|>
from .base import *
<|file_name|>config.rs<|end_file_name|><|fim▁begin|>use std::collections::HashMap; use std::rc::Rc; use serde::de::{Deserialize, Deserializer}; use serde_derive::Deserialize; use toml::value; use crate::errors; use crate::icons::Icons; use crate::protocol::i3bar_event::MouseButton; use crate::themes::Theme; #[derive(Debug)] pub struct SharedConfig { pub theme: Rc<Theme>, icons: Rc<Icons>, icons_format: String, pub scrolling: Scrolling, } impl SharedConfig { pub fn new(config: &Config) -> Self { Self { theme: Rc::new(config.theme.clone()), icons: Rc::new(config.icons.clone()), icons_format: config.icons_format.clone(), scrolling: config.scrolling, } } pub fn icons_format_override(&mut self, icons_format: String) { self.icons_format = icons_format; } pub fn theme_override(&mut self, overrides: &HashMap<String, String>) -> errors::Result<()> { let mut theme = self.theme.as_ref().clone(); theme.apply_overrides(overrides)?; self.theme = Rc::new(theme); Ok(()) } pub fn icons_override(&mut self, overrides: HashMap<String, String>) { let mut icons = self.icons.as_ref().clone(); icons.0.extend(overrides); self.icons = Rc::new(icons); } pub fn get_icon(&self, icon: &str) -> crate::errors::Result<String> { use crate::errors::OptionExt; Ok(self.icons_format.clone().replace( "{icon}", self.icons .0 .get(icon) .internal_error("get_icon()", &format!("icon '{}' not found in your icons file. If you recently upgraded to v0.2 please check NEWS.md.", icon))?, )) } } impl Default for SharedConfig { fn default() -> Self { Self { theme: Rc::new(Theme::default()), icons: Rc::new(Icons::default()),<|fim▁hole|> } } } impl Clone for SharedConfig { fn clone(&self) -> Self { Self { theme: Rc::clone(&self.theme), icons: Rc::clone(&self.icons), icons_format: self.icons_format.clone(), scrolling: self.scrolling, } } } #[derive(Deserialize, Debug, Clone)] pub struct Config { #[serde(default)] pub icons: Icons, #[serde(default)] pub theme: Theme, #[serde(default = "Config::default_icons_format")] pub icons_format: String, /// Direction of scrolling, "natural" or "reverse". /// /// Configuring natural scrolling on input devices changes the way i3status-rust /// processes mouse wheel events: pushing the wheen away now is interpreted as downward /// motion which is undesired for sliders. Use "natural" to invert this. #[serde(default)] pub scrolling: Scrolling, #[serde(rename = "block", deserialize_with = "deserialize_blocks")] pub blocks: Vec<(String, value::Value)>, } impl Config { fn default_icons_format() -> String { " {icon} ".to_string() } } impl Default for Config { fn default() -> Self { Config { icons: Icons::default(), theme: Theme::default(), icons_format: Config::default_icons_format(), scrolling: Scrolling::default(), blocks: Vec::new(), } } } #[derive(Deserialize, Copy, Clone, Debug)] #[serde(rename_all = "lowercase")] pub enum Scrolling { Reverse, Natural, } #[derive(Copy, Clone, Debug)] pub enum LogicalDirection { Up, Down, } impl Scrolling { pub fn to_logical_direction(self, button: MouseButton) -> Option<LogicalDirection> { use LogicalDirection::*; use MouseButton::*; use Scrolling::*; match (self, button) { (Reverse, WheelUp) | (Natural, WheelDown) => Some(Up), (Reverse, WheelDown) | (Natural, WheelUp) => Some(Down), _ => None, } } } impl Default for Scrolling { fn default() -> Self { Scrolling::Reverse } } fn deserialize_blocks<'de, D>(deserializer: D) -> Result<Vec<(String, value::Value)>, D::Error> where D: Deserializer<'de>, { let mut blocks: Vec<(String, value::Value)> = Vec::new(); let raw_blocks: Vec<value::Table> = Deserialize::deserialize(deserializer)?; for mut entry in raw_blocks { if let Some(name) = entry.remove("block") { if let Some(name) = name.as_str() { blocks.push((name.to_owned(), value::Value::Table(entry))) } } } Ok(blocks) }<|fim▁end|>
icons_format: " {icon} ".to_string(), scrolling: Scrolling::default(),
<|file_name|>MessageRideArmor.java<|end_file_name|><|fim▁begin|>package zornco.reploidcraft.network; import net.minecraft.entity.Entity; import net.minecraft.server.MinecraftServer; import net.minecraft.world.WorldServer; import zornco.reploidcraft.ReploidCraft; import zornco.reploidcraft.entities.EntityRideArmor; import zornco.reploidcraft.utils.RiderState; import io.netty.buffer.ByteBuf; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; import cpw.mods.fml.relauncher.Side; public class MessageRideArmor implements IMessage, IMessageHandler<MessageRideArmor, IMessage> { public float moveForward = 0.0F; public float moveStrafe = 0.0F; public boolean jump = false; public boolean sneak = false; public boolean dash = false; public boolean punch = false; public int ID = 0; public int dimension = 0; public MessageRideArmor() {} public MessageRideArmor(EntityRideArmor rideArmor, Entity entity) { if(rideArmor != null && entity != null){ RiderState rs = ReploidCraft.proxy.getRiderState(entity); if (null != rs) { moveStrafe = rs.getMoveStrafe(); moveForward = rs.getMoveForward();<|fim▁hole|> jump = rs.isJump(); sneak = rs.isSneak(); } ID = rideArmor.getEntityId(); dimension = rideArmor.dimension; } } @Override public IMessage onMessage(MessageRideArmor message, MessageContext ctx) { RiderState rs = new RiderState(); rs.setMoveForward(message.moveForward); rs.setMoveStrafe(message.moveStrafe); rs.setJump(message.jump); rs.setSneak(message.sneak); Entity armor = getEntityByID(message.ID, message.dimension); if( armor != null && armor instanceof EntityRideArmor) { ((EntityRideArmor)armor).setRiderState(rs); } return null; } @Override public void fromBytes(ByteBuf buf) { moveForward = buf.readFloat(); moveStrafe = buf.readFloat(); jump = buf.readBoolean(); sneak = buf.readBoolean(); dash = buf.readBoolean(); punch = buf.readBoolean(); ID = buf.readInt(); dimension = buf.readInt(); } @Override public void toBytes(ByteBuf buf) { buf.writeFloat(moveForward); buf.writeFloat(moveStrafe); buf.writeBoolean(jump); buf.writeBoolean(sneak); buf.writeBoolean(dash); buf.writeBoolean(punch); buf.writeInt(ID); buf.writeInt(dimension); } public Entity getEntityByID(int entityId, int dimension) { Entity targetEntity = null; if (Side.SERVER == FMLCommonHandler.instance().getEffectiveSide()) { WorldServer worldserver = MinecraftServer.getServer().worldServerForDimension(dimension); targetEntity = worldserver.getEntityByID(entityId); } if ((null != targetEntity) && ((targetEntity instanceof EntityRideArmor))) { return (EntityRideArmor)targetEntity; } return null; } }<|fim▁end|>
<|file_name|>core_thread.rs<|end_file_name|><|fim▁begin|>use modulo_traits::core_msg::ToCoreThreadMsg; use modulo_traits::file_msg::{FileThreadId, ToFileThreadMsg}; use file::file_thread::FileThread; use std::collections::HashMap; use std::path::PathBuf; use std::sync::mpsc::{self, Sender, Receiver}; use std::thread::{self, JoinHandle}; pub struct Core { file_threads: HashMap<FileThreadId, Sender<ToFileThreadMsg>>, file_receiver: Receiver<ToCoreThreadMsg>, file_sender: Sender<ToCoreThreadMsg>, file_id_counter: usize, } impl Core { pub fn start() -> (Sender<ToCoreThreadMsg>, JoinHandle<()>) { let (sender, receiver) = mpsc::channel(); let file_sender = sender.clone(); let handle = thread::spawn(move || { let mut core = Core { file_threads: HashMap::new(), file_receiver: receiver, file_sender: file_sender, file_id_counter: 0, };<|fim▁hole|> (sender, handle) } /// Runs the event loop for the `CoreThread` pub fn run(&mut self) { while let Ok(msg) = self.file_receiver.recv() { match msg { ToCoreThreadMsg::FileThreadMsg(id, msg) => { let file_thread = match self.file_threads.get(&id) { Some(file_thread) => file_thread, None => return warn!("Received message for closed file thread: {:?}", id), }; let _ = file_thread.send(msg); }, ToCoreThreadMsg::SpawnFileThread(path) => self.handle_spawn_file_thread(path), } } } pub fn handle_spawn_file_thread(&mut self, path: Option<PathBuf>) { let (sender, receiver) = mpsc::channel(); let id = FileThreadId(self.file_id_counter); FileThread::start(id, path, self.file_sender.clone(), receiver); self.file_threads.insert(id, sender); self.file_id_counter += 1; } }<|fim▁end|>
core.run(); });
<|file_name|>test_c_generator.py<|end_file_name|><|fim▁begin|>import sys import unittest # Run from the root dir sys.path.insert(0, '.') from pycparser import c_parser, c_generator, c_ast _c_parser = c_parser.CParser( lex_optimize=False, yacc_debug=True, yacc_optimize=False, yacctab='yacctab') def compare_asts(ast1, ast2): if type(ast1) != type(ast2): return False if isinstance(ast1, tuple) and isinstance(ast2, tuple): if ast1[0] != ast2[0]: return False ast1 = ast1[1] ast2 = ast2[1] return compare_asts(ast1, ast2) for attr in ast1.attr_names: if getattr(ast1, attr) != getattr(ast2, attr): return False for i, c1 in enumerate(ast1.children()): if compare_asts(c1, ast2.children()[i]) == False: return False return True def parse_to_ast(src): return _c_parser.parse(src) class TestFunctionDeclGeneration(unittest.TestCase): class _FuncDeclVisitor(c_ast.NodeVisitor): def __init__(self): self.stubs = [] def visit_FuncDecl(self, node): gen = c_generator.CGenerator() self.stubs.append(gen.visit(node)) def test_partial_funcdecl_generation(self): src = r''' void noop(void); void *something(void *thing); int add(int x, int y);''' ast = parse_to_ast(src) v = TestFunctionDeclGeneration._FuncDeclVisitor() v.visit(ast) self.assertEqual(len(v.stubs), 3) self.assertTrue(r'void noop(void)' in v.stubs) self.assertTrue(r'void *something(void *thing)' in v.stubs) self.assertTrue(r'int add(int x, int y)' in v.stubs) class TestCtoC(unittest.TestCase): def _run_c_to_c(self, src): ast = parse_to_ast(src) generator = c_generator.CGenerator() return generator.visit(ast) def _assert_ctoc_correct(self, src): """ Checks that the c2c translation was correct by parsing the code generated by c2c for src and comparing the AST with the original AST. """ src2 = self._run_c_to_c(src) self.assertTrue(compare_asts(parse_to_ast(src), parse_to_ast(src2)), src2) def test_trivial_decls(self): self._assert_ctoc_correct('int a;') self._assert_ctoc_correct('int b, a;') self._assert_ctoc_correct('int c, b, a;') def test_complex_decls(self): self._assert_ctoc_correct('int** (*a)(void);') self._assert_ctoc_correct('int** (*a)(void*, int);') self._assert_ctoc_correct('int (*b)(char * restrict k, float);') self._assert_ctoc_correct('int test(const char* const* arg);') self._assert_ctoc_correct('int test(const char** const arg);') #s = 'int test(const char* const* arg);' #parse_to_ast(s).show() def test_ternary(self): self._assert_ctoc_correct(''' int main(void) { int a, b; (a == 0) ? (b = 1) : (b = 2); }''') def test_casts(self): self._assert_ctoc_correct(r''' int main() { int b = (int) f; int c = (int*) f; }''') def test_initlist(self): self._assert_ctoc_correct('int arr[] = {1, 2, 3};') def test_exprs(self): self._assert_ctoc_correct(''' int main(void) { int a; int b = a++; int c = ++a; int d = a--; int e = --a; }''') def test_statements(self): # note two minuses here self._assert_ctoc_correct(r''' int main() { int a; a = 5; ; b = - - a; return a; }''') def test_casts(self): self._assert_ctoc_correct(r''' int main() { int a = (int) b + 8; int t = (int) c; } ''') def test_struct_decl(self): self._assert_ctoc_correct(r''' typedef struct node_t { struct node_t* next; int data; } node; ''') def test_krstyle(self): self._assert_ctoc_correct(r''' int main(argc, argv) int argc; char** argv; { return 0; } ''') def test_switchcase(self): self._assert_ctoc_correct(r''' int main() { switch (myvar) { case 10: { k = 10; p = k + 1; break; } case 20: case 30: return 20; default: break; } } ''') def test_nest_initializer_list(self): self._assert_ctoc_correct(r''' int main() { int i[1][1] = { { 1 } }; }''') def test_nest_named_initializer(self): self._assert_ctoc_correct(r'''struct test { int i; struct test_i_t { int k; } test_i; int j; }; struct test test_var = {.i = 0, .test_i = {.k = 1}, .j = 2}; ''') def test_expr_list_in_initializer_list(self): self._assert_ctoc_correct(r''' int main() { int i[1] = { (1, 2) }; }''') def test_issue36(self): self._assert_ctoc_correct(r'''<|fim▁hole|> }''') def test_issue37(self): self._assert_ctoc_correct(r''' int main(void) { unsigned size; size = sizeof(size); return 0; }''') def test_issue83(self): self._assert_ctoc_correct(r''' void x(void) { int i = (9, k); } ''') def test_issue84(self): self._assert_ctoc_correct(r''' void x(void) { for (int i = 0;;) i; } ''') def test_exprlist_with_semi(self): self._assert_ctoc_correct(r''' void x() { if (i < j) tmp = C[i], C[i] = C[j], C[j] = tmp; if (i <= j) i++, j--; } ''') def test_exprlist_with_subexprlist(self): self._assert_ctoc_correct(r''' void x() { (a = b, (b = c, c = a)); } ''') def test_comma_operator_funcarg(self): self._assert_ctoc_correct(r''' void f(int x) { return x; } int main(void) { f((1, 2)); return 0; } ''') def test_comma_op_in_ternary(self): self._assert_ctoc_correct(r''' void f() { (0, 0) ? (0, 0) : (0, 0); } ''') def test_comma_op_assignment(self): self._assert_ctoc_correct(r''' void f() { i = (a, b, c); } ''') def test_pragma(self): self._assert_ctoc_correct(r''' #pragma foo void f() { #pragma bar i = (a, b, c); } ''') if __name__ == "__main__": unittest.main()<|fim▁end|>
int main() {
<|file_name|>LMS7002_DCCAL.py<|end_file_name|><|fim▁begin|>#*************************************************************** #* Name: LMS7002_DCCAL.py #* Purpose: Class implementing LMS7002 DCCAL functions #* Author: Lime Microsystems () #* Created: 2017-02-10 #* Copyright: Lime Microsystems (limemicro.com) #* License: #************************************************************** from LMS7002_base import * class LMS7002_DCCAL(LMS7002_base): __slots__ = [] # Used to generate error on typos def __init__(self, chip): self.chip = chip self.channel = None self.prefix = "DCCAL_" # # DCCAL_CFG (0x05C0) # # DCMODE @property def DCMODE(self): """ Get the value of DCMODE """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('CFG', 'DCMODE') else: raise ValueError("Bitfield DCMODE is not supported on chip version "+str(self.chip.chipID)) @DCMODE.setter def DCMODE(self, value): """ Set the value of DCMODE """ if self.chip.chipID == self.chip.chipIDMR3: if value not in [0, 1, 'MANUAL', 'AUTO']: raise ValueError("Value must be [0,1,'MANUAL','AUTO']") if value==0 or value=='MANUAL': val = 0 else: val = 1 self._writeReg('CFG', 'DCMODE', val) else: raise ValueError("Bitfield DCMODE is not supported on chip version "+str(self.chip.chipID)) # PD_DCDAC_RXB @property def PD_DCDAC_RXB(self): """ Get the value of PD_DCDAC_RXB """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('CFG', 'PD_DCDAC_RXB') else: raise ValueError("Bitfield PD_DCDAC_RXB is not supported on chip version "+str(self.chip.chipID)) @PD_DCDAC_RXB.setter def PD_DCDAC_RXB(self, value): """ Set the value of PD_DCDAC_RXB """ if self.chip.chipID == self.chip.chipIDMR3: if value not in [0, 1]: raise ValueError("Value must be [0,1]") self._writeReg('CFG', 'PD_DCDAC_RXB', value) else: raise ValueError("Bitfield PD_DCDAC_RXB is not supported on chip version "+str(self.chip.chipID)) # PD_DCDAC_RXA @property def PD_DCDAC_RXA(self): """ Get the value of PD_DCDAC_RXA """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('CFG', 'PD_DCDAC_RXA') else: raise ValueError("Bitfield PD_DCDAC_RXA is not supported on chip version "+str(self.chip.chipID)) @PD_DCDAC_RXA.setter def PD_DCDAC_RXA(self, value): """ Set the value of PD_DCDAC_RXA """ if self.chip.chipID == self.chip.chipIDMR3: if value not in [0, 1]: raise ValueError("Value must be [0,1]") self._writeReg('CFG', 'PD_DCDAC_RXA', value) else: raise ValueError("Bitfield PD_DCDAC_RXA is not supported on chip version "+str(self.chip.chipID)) # PD_DCDAC_TXB @property def PD_DCDAC_TXB(self): """ Get the value of PD_DCDAC_TXB """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('CFG', 'PD_DCDAC_TXB') else: raise ValueError("Bitfield PD_DCDAC_TXB is not supported on chip version "+str(self.chip.chipID)) @PD_DCDAC_TXB.setter def PD_DCDAC_TXB(self, value): """ Set the value of PD_DCDAC_TXB """ if self.chip.chipID == self.chip.chipIDMR3: if value not in [0, 1]: raise ValueError("Value must be [0,1]") self._writeReg('CFG', 'PD_DCDAC_TXB', value) else: raise ValueError("Bitfield PD_DCDAC_TXB is not supported on chip version "+str(self.chip.chipID)) # PD_DCDAC_TXA @property def PD_DCDAC_TXA(self): """ Get the value of PD_DCDAC_TXA """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('CFG', 'PD_DCDAC_TXA') else: raise ValueError("Bitfield PD_DCDAC_TXA is not supported on chip version "+str(self.chip.chipID)) @PD_DCDAC_TXA.setter def PD_DCDAC_TXA(self, value): """ Set the value of PD_DCDAC_TXA """ if self.chip.chipID == self.chip.chipIDMR3: if value not in [0, 1]: raise ValueError("Value must be [0,1]") self._writeReg('CFG', 'PD_DCDAC_TXA', value) else: raise ValueError("Bitfield PD_DCDAC_TXA is not supported on chip version "+str(self.chip.chipID)) # PD_DCCMP_RXB @property def PD_DCCMP_RXB(self): """ Get the value of PD_DCCMP_RXB """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('CFG', 'PD_DCCMP_RXB') else: raise ValueError("Bitfield PD_DCCMP_RXB is not supported on chip version "+str(self.chip.chipID)) @PD_DCCMP_RXB.setter def PD_DCCMP_RXB(self, value): """ Set the value of PD_DCCMP_RXB """ if self.chip.chipID == self.chip.chipIDMR3: if value not in [0, 1]: raise ValueError("Value must be [0,1]") self._writeReg('CFG', 'PD_DCCMP_RXB', value) else: raise ValueError("Bitfield PD_DCCMP_RXB is not supported on chip version "+str(self.chip.chipID)) # PD_DCCMP_RXA @property def PD_DCCMP_RXA(self): """ Get the value of PD_DCCMP_RXA """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('CFG', 'PD_DCCMP_RXA') else: raise ValueError("Bitfield PD_DCCMP_RXA is not supported on chip version "+str(self.chip.chipID)) @PD_DCCMP_RXA.setter def PD_DCCMP_RXA(self, value): """ Set the value of PD_DCCMP_RXA """ if self.chip.chipID == self.chip.chipIDMR3: if value not in [0, 1]: raise ValueError("Value must be [0,1]") self._writeReg('CFG', 'PD_DCCMP_RXA', value) else: raise ValueError("Bitfield PD_DCCMP_RXA is not supported on chip version "+str(self.chip.chipID)) # PD_DCCMP_TXB @property def PD_DCCMP_TXB(self): """ Get the value of PD_DCCMP_TXB """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('CFG', 'PD_DCCMP_TXB') else: raise ValueError("Bitfield PD_DCCMP_TXB is not supported on chip version "+str(self.chip.chipID)) @PD_DCCMP_TXB.setter def PD_DCCMP_TXB(self, value): """ Set the value of PD_DCCMP_TXB """ if self.chip.chipID == self.chip.chipIDMR3: if value not in [0, 1]: raise ValueError("Value must be [0,1]") self._writeReg('CFG', 'PD_DCCMP_TXB', value) else: raise ValueError("Bitfield PD_DCCMP_TXB is not supported on chip version "+str(self.chip.chipID)) # PD_DCCMP_TXA @property def PD_DCCMP_TXA(self): """ Get the value of PD_DCCMP_TXA """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('CFG', 'PD_DCCMP_TXA') else: raise ValueError("Bitfield PD_DCCMP_TXA is not supported on chip version "+str(self.chip.chipID)) @PD_DCCMP_TXA.setter def PD_DCCMP_TXA(self, value): """ Set the value of PD_DCCMP_TXA """ if self.chip.chipID == self.chip.chipIDMR3: if value not in [0, 1]: raise ValueError("Value must be [0,1]") self._writeReg('CFG', 'PD_DCCMP_TXA', value) else: raise ValueError("Bitfield PD_DCCMP_TXA is not supported on chip version "+str(self.chip.chipID)) # # DCCAL_STAT (0x05C1) # # DCCAL_CALSTATUS<7:0> @property def DCCAL_CALSTATUS(self): """ Get the value of DCCAL_CALSTATUS<7:0> """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('STAT', 'DCCAL_CALSTATUS<7:0>') else: raise ValueError("Bitfield DCCAL_CALSTATUS<7:0> is not supported on chip version "+str(self.chip.chipID)) @DCCAL_CALSTATUS.setter def DCCAL_CALSTATUS(self, value): """ Set the value of DCCAL_CALSTATUS<7:0> """ if self.chip.chipID == self.chip.chipIDMR3: if not(0<= value <=255): raise ValueError("Value must be [0..255]") self._writeReg('STAT', 'DCCAL_CALSTATUS<7:0>', value) else: raise ValueError("Bitfield DCCAL_CALSTATUS<7:0> is not supported on chip version "+str(self.chip.chipID)) # DCCAL_CMPSTATUS<7:0> @property def DCCAL_CMPSTATUS(self): """ Get the value of DCCAL_CMPSTATUS<7:0> """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('STAT', 'DCCAL_CMPSTATUS<7:0>') else: raise ValueError("Bitfield DCCAL_CMPSTATUS<7:0> is not supported on chip version "+str(self.chip.chipID)) @DCCAL_CMPSTATUS.setter def DCCAL_CMPSTATUS(self, value): """ Set the value of DCCAL_CMPSTATUS<7:0> """ if self.chip.chipID == self.chip.chipIDMR3: if not(0<= value <=255): raise ValueError("Value must be [0..255]") self._writeReg('STAT', 'DCCAL_CMPSTATUS<7:0>', value) else: raise ValueError("Bitfield DCCAL_CMPSTATUS<7:0> is not supported on chip version "+str(self.chip.chipID)) # # DCCAL_CFG2 (0x05C2) # # DCCAL_CMPCFG<7:0> @property def DCCAL_CMPCFG(self): """ Get the value of DCCAL_CMPCFG<7:0> """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('CFG2', 'DCCAL_CMPCFG<7:0>') else: raise ValueError("Bitfield DCCAL_CMPCFG<7:0> is not supported on chip version "+str(self.chip.chipID)) @DCCAL_CMPCFG.setter def DCCAL_CMPCFG(self, value): """ Set the value of DCCAL_CMPCFG<7:0> """ if self.chip.chipID == self.chip.chipIDMR3: if not(0<= value <=255): raise ValueError("Value must be [0..255]") self._writeReg('CFG2', 'DCCAL_CMPCFG<7:0>', value) else: raise ValueError("Bitfield DCCAL_CMPCFG<7:0> is not supported on chip version "+str(self.chip.chipID)) # DCCAL_START<7:0> @property def DCCAL_START(self): """ Get the value of DCCAL_START<7:0> """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('CFG2', 'DCCAL_START<7:0>') else: raise ValueError("Bitfield DCCAL_START<7:0> is not supported on chip version "+str(self.chip.chipID)) @DCCAL_START.setter def DCCAL_START(self, value): """ Set the value of DCCAL_START<7:0> """ if self.chip.chipID == self.chip.chipIDMR3: if not(0<= value <=255): raise ValueError("Value must be [0..255]") self._writeReg('CFG2', 'DCCAL_START<7:0>', value) else: raise ValueError("Bitfield DCCAL_START<7:0> is not supported on chip version "+str(self.chip.chipID)) def startRXBQ(self): """ Starts RXBQ calibration. """ self.DCCAL_START = 0 self.DCCAL_START = 1<<7 def startRXBI(self): """ Starts RXBI calibration. """ self.DCCAL_START = 0 self.DCCAL_START = 1<<6 def startRXAQ(self): """ Starts RXAQ calibration. """ self.DCCAL_START = 0 self.DCCAL_START = 1<<5 def startRXAI(self): """ Starts RXAI calibration. """ self.DCCAL_START = 0 self.DCCAL_START = 1<<4 def startTXBQ(self): """ Starts TXBQ calibration. """ self.DCCAL_START = 0 self.DCCAL_START = 1<<3 def startTXBI(self): """ Starts TXBI calibration. """ self.DCCAL_START = 0 self.DCCAL_START = 1<<2 def startTXAQ(self): """ Starts TXAQ calibration. """ self.DCCAL_START = 0 self.DCCAL_START = 1<<1 def startTXAI(self): """ Starts TXAI calibration. """ self.DCCAL_START = 0 self.DCCAL_START = 1 # # DCCAL_TXAI (0x05C3) # @property def DC_TXAI(self): """ Get the value of DC_TXAI """ if self.chip.chipID == self.chip.chipIDMR3: self._writeReg('TXAI', 'DCRD_TXAI', 0) self._writeReg('TXAI', 'DCRD_TXAI', 1) val = self._readReg('TXAI', 'DC_TXAI<10:0>') return self.signMagnitudeToInt(val, 11) else: raise ValueError("Bitfield DC_TXAI is not supported on chip version "+str(self.chip.chipID)) @DC_TXAI.setter def DC_TXAI(self, value): """ Set the value of DC_TXAI """ if self.chip.chipID == self.chip.chipIDMR3: if not(-1024<= value <=1024): raise ValueError("Value must be [-1024..1024]") val = self.intToSignMagnitude(value, 11) self._writeReg('TXAI', 'DC_TXAI<10:0>', val) self._writeReg('TXAI', 'DCWR_TXAI', 0) self._writeReg('TXAI', 'DCWR_TXAI', 1) else: raise ValueError("Bitfield TXAI is not supported on chip version "+str(self.chip.chipID)) # # DCCAL_TXAQ (0x05C4) # @property def DC_TXAQ(self): """ Get the value of DC_TXAQ """<|fim▁hole|> val = self._readReg('TXAQ', 'DC_TXAQ<10:0>') return self.signMagnitudeToInt(val, 11) else: raise ValueError("Bitfield DC_TXAQ is not supported on chip version "+str(self.chip.chipID)) @DC_TXAQ.setter def DC_TXAQ(self, value): """ Set the value of DC_TXAQ """ if self.chip.chipID == self.chip.chipIDMR3: if not(-1024<= value <=1024): raise ValueError("Value must be [-1024..1024]") val = self.intToSignMagnitude(value, 11) self._writeReg('TXAQ', 'DC_TXAQ<10:0>', val) self._writeReg('TXAQ', 'DCWR_TXAQ', 0) self._writeReg('TXAQ', 'DCWR_TXAQ', 1) else: raise ValueError("Bitfield TXAQ is not supported on chip version "+str(self.chip.chipID)) # # DCCAL_TXBI (0x05C5) # @property def DC_TXBI(self): """ Get the value of DC_TXBI """ if self.chip.chipID == self.chip.chipIDMR3: self._writeReg('TXBI', 'DCRD_TXBI', 0) self._writeReg('TXBI', 'DCRD_TXBI', 1) val = self._readReg('TXBI', 'DC_TXBI<10:0>') return self.signMagnitudeToInt(val, 11) else: raise ValueError("Bitfield DC_TXBI is not supported on chip version "+str(self.chip.chipID)) @DC_TXBI.setter def DC_TXBI(self, value): """ Set the value of DC_TXBI """ if self.chip.chipID == self.chip.chipIDMR3: if not(-1024<= value <=1024): raise ValueError("Value must be [-1024..1024]") val = self.intToSignMagnitude(value, 11) self._writeReg('TXBI', 'DC_TXBI<10:0>', val) self._writeReg('TXBI', 'DCWR_TXBI', 0) self._writeReg('TXBI', 'DCWR_TXBI', 1) else: raise ValueError("Bitfield TXBI is not supported on chip version "+str(self.chip.chipID)) # # DCCAL_TXBQ (0x05C6) # @property def DC_TXBQ(self): """ Get the value of DC_TXBQ """ if self.chip.chipID == self.chip.chipIDMR3: self._writeReg('TXBQ', 'DCRD_TXBQ', 0) self._writeReg('TXBQ', 'DCRD_TXBQ', 1) val = self._readReg('TXBQ', 'DC_TXBQ<10:0>') return self.signMagnitudeToInt(val, 11) else: raise ValueError("Bitfield DC_TXBQ is not supported on chip version "+str(self.chip.chipID)) @DC_TXBQ.setter def DC_TXBQ(self, value): """ Set the value of DC_TXBQ """ if self.chip.chipID == self.chip.chipIDMR3: if not(-1024<= value <=1024): raise ValueError("Value must be [-1024..1024]") val = self.intToSignMagnitude(value, 11) self._writeReg('TXBQ', 'DC_TXBQ<10:0>', val) self._writeReg('TXBQ', 'DCWR_TXBQ', 0) self._writeReg('TXBQ', 'DCWR_TXBQ', 1) else: raise ValueError("Bitfield TXBQ is not supported on chip version "+str(self.chip.chipID)) # # DCCAL_RXAI (0x05C7) # @property def DC_RXAI(self): """ Get the value of DC_RXAI """ if self.chip.chipID == self.chip.chipIDMR3: self._writeReg('RXAI', 'DCRD_RXAI', 0) self._writeReg('RXAI', 'DCRD_RXAI', 1) val = self._readReg('RXAI', 'DC_RXAI<6:0>') return self.signMagnitudeToInt(val, 7) else: raise ValueError("Bitfield DC_RXAI is not supported on chip version "+str(self.chip.chipID)) @DC_RXAI.setter def DC_RXAI(self, value): """ Set the value of DC_RXAI """ if self.chip.chipID == self.chip.chipIDMR3: if not(-63<= value <=63): raise ValueError("Value must be [-63..63]") val = self.intToSignMagnitude(value, 7) self._writeReg('RXAI', 'DC_RXAI<6:0>', val) self._writeReg('RXAI', 'DCWR_RXAI', 0) self._writeReg('RXAI', 'DCWR_RXAI', 1) else: raise ValueError("Bitfield RXAI is not supported on chip version "+str(self.chip.chipID)) # # DCCAL_RXAQ (0x05C8) # @property def DC_RXAQ(self): """ Get the value of DC_RXAQ """ if self.chip.chipID == self.chip.chipIDMR3: self._writeReg('RXAQ', 'DCRD_RXAQ', 0) self._writeReg('RXAQ', 'DCRD_RXAQ', 1) val = self._readReg('RXAQ', 'DC_RXAQ<6:0>') return self.signMagnitudeToInt(val, 7) else: raise ValueError("Bitfield DC_RXAQ is not supported on chip version "+str(self.chip.chipID)) @DC_RXAQ.setter def DC_RXAQ(self, value): """ Set the value of DC_RXAQ """ if self.chip.chipID == self.chip.chipIDMR3: if not(-63<= value <=63): raise ValueError("Value must be [-63..63]") val = self.intToSignMagnitude(value, 7) self._writeReg('RXAQ', 'DC_RXAQ<6:0>', val) self._writeReg('RXAQ', 'DCWR_RXAQ', 0) self._writeReg('RXAQ', 'DCWR_RXAQ', 1) else: raise ValueError("Bitfield RXAQ is not supported on chip version "+str(self.chip.chipID)) # # DCCAL_RXBI (0x05C9) # @property def DC_RXBI(self): """ Get the value of DC_RXBI """ if self.chip.chipID == self.chip.chipIDMR3: self._writeReg('RXBI', 'DCRD_RXBI', 0) self._writeReg('RXBI', 'DCRD_RXBI', 1) val = self._readReg('RXBI', 'DC_RXBI<6:0>') return self.signMagnitudeToInt(val, 7) else: raise ValueError("Bitfield DC_RXBI is not supported on chip version "+str(self.chip.chipID)) @DC_RXBI.setter def DC_RXBI(self, value): """ Set the value of DC_RXBI """ if self.chip.chipID == self.chip.chipIDMR3: if not(-63<= value <=63): raise ValueError("Value must be [-63..63]") val = self.intToSignMagnitude(value, 7) self._writeReg('RXBI', 'DC_RXBI<6:0>', val) self._writeReg('RXBI', 'DCWR_RXBI', 0) self._writeReg('RXBI', 'DCWR_RXBI', 1) else: raise ValueError("Bitfield RXBI is not supported on chip version "+str(self.chip.chipID)) # # DCCAL_RXBQ (0x05CA) # @property def DC_RXBQ(self): """ Get the value of DC_RXBQ """ if self.chip.chipID == self.chip.chipIDMR3: self._writeReg('RXBQ', 'DCRD_RXBQ', 0) self._writeReg('RXBQ', 'DCRD_RXBQ', 1) val = self._readReg('RXBQ', 'DC_RXBQ<6:0>') return self.signMagnitudeToInt(val, 7) else: raise ValueError("Bitfield DC_RXBQ is not supported on chip version "+str(self.chip.chipID)) @DC_RXBQ.setter def DC_RXBQ(self, value): """ Set the value of DC_RXBQ """ if self.chip.chipID == self.chip.chipIDMR3: if not(-63<= value <=63): raise ValueError("Value must be [-63..63]") val = self.intToSignMagnitude(value, 7) self._writeReg('RXBQ', 'DC_RXBQ<6:0>', val) self._writeReg('RXBQ', 'DCWR_RXBQ', 0) self._writeReg('RXBQ', 'DCWR_RXBQ', 1) else: raise ValueError("Bitfield RXBQ is not supported on chip version "+str(self.chip.chipID)) # DC_RXCDIV<7:0> @property def DC_RXCDIV(self): """ Get the value of DC_RXCDIV<7:0> """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('CLKDIV', 'DC_RXCDIV<7:0>') else: raise ValueError("Bitfield DC_RXCDIV<7:0> is not supported on chip version "+str(self.chip.chipID)) @DC_RXCDIV.setter def DC_RXCDIV(self, value): """ Set the value of DC_RXCDIV<7:0> """ if self.chip.chipID == self.chip.chipIDMR3: if not(0<= value <=255): raise ValueError("Value must be [0..255]") self._writeReg('CLKDIV', 'DC_RXCDIV<7:0>', value) else: raise ValueError("Bitfield DC_RXCDIV<7:0> is not supported on chip version "+str(self.chip.chipID)) # DC_TXCDIV<7:0> @property def DC_TXCDIV(self): """ Get the value of DC_TXCDIV<7:0> """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('CLKDIV', 'DC_TXCDIV<7:0>') else: raise ValueError("Bitfield DC_TXCDIV<7:0> is not supported on chip version "+str(self.chip.chipID)) @DC_TXCDIV.setter def DC_TXCDIV(self, value): """ Set the value of DC_TXCDIV<7:0> """ if self.chip.chipID == self.chip.chipIDMR3: if not(0<= value <=255): raise ValueError("Value must be [0..255]") self._writeReg('CLKDIV', 'DC_TXCDIV<7:0>', value) else: raise ValueError("Bitfield DC_TXCDIV<7:0> is not supported on chip version "+str(self.chip.chipID)) # HYSCMP_RXB<2:0> @property def HYSCMP_RXB(self): """ Get the value of HYSCMP_RXB<2:0> """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('HYSTCFG', 'HYSCMP_RXB<2:0>') else: raise ValueError("Bitfield HYSCMP_RXB<2:0> is not supported on chip version "+str(self.chip.chipID)) @HYSCMP_RXB.setter def HYSCMP_RXB(self, value): """ Set the value of HYSCMP_RXB<2:0> """ if self.chip.chipID == self.chip.chipIDMR3: if not(0 <= value <= 7): raise ValueError("Value must be [0..7]") self._writeReg('HYSTCFG', 'HYSCMP_RXB<2:0>', value) else: raise ValueError("Bitfield HYSCMP_RXB<2:0> is not supported on chip version "+str(self.chip.chipID)) # HYSCMP_RXA<2:0> @property def HYSCMP_RXA(self): """ Get the value of HYSCMP_RXA<2:0> """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('HYSTCFG', 'HYSCMP_RXA<2:0>') else: raise ValueError("Bitfield HYSCMP_RXA<2:0> is not supported on chip version "+str(self.chip.chipID)) @HYSCMP_RXA.setter def HYSCMP_RXA(self, value): """ Set the value of HYSCMP_RXA<2:0> """ if self.chip.chipID == self.chip.chipIDMR3: if not(0 <= value <= 7): raise ValueError("Value must be [0..7]") self._writeReg('HYSTCFG', 'HYSCMP_RXA<2:0>', value) else: raise ValueError("Bitfield HYSCMP_RXA<2:0> is not supported on chip version "+str(self.chip.chipID)) # HYSCMP_TXB<2:0> @property def HYSCMP_TXB(self): """ Get the value of HYSCMP_TXB<2:0> """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('HYSTCFG', 'HYSCMP_TXB<2:0>') else: raise ValueError("Bitfield HYSCMP_TXB<2:0> is not supported on chip version "+str(self.chip.chipID)) @HYSCMP_TXB.setter def HYSCMP_TXB(self, value): """ Set the value of HYSCMP_TXB<2:0> """ if self.chip.chipID == self.chip.chipIDMR3: if not(0 <= value <= 7): raise ValueError("Value must be [0..7]") self._writeReg('HYSTCFG', 'HYSCMP_TXB<2:0>', value) else: raise ValueError("Bitfield HYSCMP_TXB<2:0> is not supported on chip version "+str(self.chip.chipID)) # HYSCMP_TXA<2:0> @property def HYSCMP_TXA(self): """ Get the value of HYSCMP_TXA<2:0> """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('HYSTCFG', 'HYSCMP_TXA<2:0>') else: raise ValueError("Bitfield HYSCMP_TXA<2:0> is not supported on chip version "+str(self.chip.chipID)) @HYSCMP_TXA.setter def HYSCMP_TXA(self, value): """ Set the value of HYSCMP_TXA<2:0> """ if self.chip.chipID == self.chip.chipIDMR3: if not(0 <= value <= 7): raise ValueError("Value must be [0..7]") self._writeReg('HYSTCFG', 'HYSCMP_TXA<2:0>', value) else: raise ValueError("Bitfield HYSCMP_TXA<2:0> is not supported on chip version "+str(self.chip.chipID))<|fim▁end|>
if self.chip.chipID == self.chip.chipIDMR3: self._writeReg('TXAQ', 'DCRD_TXAQ', 0) self._writeReg('TXAQ', 'DCRD_TXAQ', 1)
<|file_name|>woocommerce.js<|end_file_name|><|fim▁begin|>(function ($, window, document) { "use strict"; $(document).on( 'ready', function(){ var $body = $('body'), $topbar = $( document.getElementById('topbar') ), $products_sliders = $('.products-slider-wrapper, .categories-slider-wrapper'); /************************* * SHOP STYLE SWITCHER *************************/ $('#list-or-grid').on( 'click', 'a', function(){ var trigger = $(this), view = trigger.attr( 'class' ).replace('-view', ''); $( 'ul.products li' ).removeClass( 'list grid' ).addClass( view ); trigger.parent().find( 'a' ).removeClass( 'active' ); trigger.addClass( 'active' ); $.cookie( yit_shop_view_cookie, view ); return false; }); /************************* * Fix Product Name and Price *************************/ var padding_nameprice = function () { $('li.product .product-wrapper .info-product.slideup').each(function () { $(this).find('h3').css( 'padding-' + ( ! yit.isRtl ? 'right' : 'left' ), $(this).find('span.price').width() + 10 ); }); }; if( $(window).width() > 1199 ){ padding_nameprice(); } $(document).on('yith-wcan-ajax-filtered', padding_nameprice ); /************************* * ADD TO CART *************************/ var product, product_onsale; var add_to_cart = function() { $('ul.products').on('click', 'li.product .add_to_cart_button', function () { product = $(this).parents('li.product'); product_onsale = product.find('.product-wrapper > .onsale'); if( typeof yit.load_gif != 'undefined' ) { product.find('.thumb-wrapper').block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}}); } else{ product.find('.thumb-wrapper').block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}}); } }); } add_to_cart(); $(document).on('yith-wcan-ajax-filtered', add_to_cart ); $body.on('added_to_cart', function () { if( typeof product_onsale === 'undefined' && typeof product === 'undefined' ) return; $( '.products-slider.swiper .swiper-slide .opacity .swiper-product-informations span.product-add-to-cart a.added_to_cart.wc-forward') .addClass( 'btn btn-flat' ) .prev('a').remove(); if ( product_onsale.length ) { product_onsale.remove(); } product.find('.thumb-wrapper').append('<div class="added_to_cart_box"><div class="added_to_cart_label">' + yit.added_to_cart + '</div></div>'); product.find('.added_to_cart_label').append(product.find('a.added_to_cart')); product.find('.product-wrapper div:first-child').addClass('nohover'); setTimeout( function(){ product.find('.added_to_cart_box').fadeOut(2000, function(){ $(this).remove(); }); product.find('.product-wrapper div:first-child').removeClass('nohover'); }, 3000 ); <|fim▁hole|> }, 4000); } product.find('.thumb-wrapper').unblock(); }); /************************* * PRODUCTS SLIDER *************************/ if( $.fn.owlCarousel && $.fn.imagesLoaded && $products_sliders.length ) { var product_slider = function(t) { t.imagesLoaded(function(){ var cols = t.data('columns') ? t.data('columns') : 4; var autoplay = (t.attr('data-autoplay')=='true') ? 3000 : false; var owl = t.find('.products').owlCarousel({ items : cols, responsiveClass : true, responsive:{ 0 : { items: 2 }, 479 : { items: 3 }, 767 : { items: 4 }, 992 : { items: cols } }, autoplay : autoplay, autoplayTimeout : 2000, autoplayHoverPause: true, loop : true, rtl: yit.isRtl == true }); // Custom Navigation Events t.on('click', '.es-nav-next', function () { owl.trigger('next.owl.carousel'); }); t.on('click', '.es-nav-prev', function () { owl.trigger('prev.owl.carousel'); }); }); }; // initialize slider in only visible tabs $products_sliders.each(function(){ var t = $(this); if( ! t.closest('.panel.group').length || t.closest('.panel.group').hasClass('showing') ){ product_slider( t ); } }); $('.tabs-container').on( 'yit_tabopened', function( e, tab ) { product_slider( tab.find( $products_sliders ) ); }); } /************************* * VARIATIONS SELECT *************************/ var variations_select = function(){ // variations select if( $.fn.selectbox ) { var form = $('form.variations_form'); var select = form.find('select:not(.yith_wccl_custom)'); if( form.data('wccl') ) { select = select.filter(function(){ return $(this).data('type') == 'select' }); } select.selectbox({ effect: 'fade', onOpen: function() { //$('.variations select').trigger('focusin'); } }); var update_select = function(event){ // console.log(event); select.selectbox("detach"); select.selectbox("attach"); }; // fix variations select form.on( 'woocommerce_update_variation_values', update_select); form.find('.reset_variations').on('click.yit', update_select); } }; variations_select(); /************************* * TOPBAR INDICATORS *************************/ $topbar.find('#lang_sel .lang_sel_sel').append('<span class="sf-sub-indicator"> +</span>'); $topbar.find('#wcml_currency_switcher > ul > li a.sbSelector').append('<span class="sf-sub-indicator"> +</span>'); /************************* * PRODUCT TABS *************************/ $('.single-product-tabs.vertical').on('click', 'ul.tabs li .tab_name', function () { var tab_trigger = $(this), panel = tab_trigger.siblings('.panel'), container = tab_trigger.closest('.single-product-tabs'); if ( ! tab_trigger.hasClass('active') ) { //remove opened tab container.find('.tab_name.active').siblings('div.panel').slideToggle('slow'); container.find('.tab_name.active').removeClass('active'); //open tab tab_trigger.addClass('active'); } else { tab_trigger.removeClass('active'); } panel.slideToggle('slow'); }); /************************* * INQUIRY FORM *************************/ var inquiry_form = function(){ if ( $('#inquiry-form .product-inquiry').length ) { $(document).on('click', '#inquiry-form .product-inquiry', function(event){ event.stopImmediatePropagation('click'); $(this).next('form.contact-form').slideToggle('slow'); }); } }; inquiry_form(); $(document).on('yit_quick_view_loaded', inquiry_form); if( $( 'body').hasClass( 'single-product' ) ) { setTimeout( function() { if( $.trim( $( 'div.user-message').html() ) != '' || $.trim( $( '.contact-form li div.msg-error' ).text() ) != '' ) { $('form.contact-form').slideToggle('slow'); } }, 200 ); } /************************* * Wishlist *************************/ var wishlist_share = function() { if ( $('#wishlist-share div.share-text').length ) { $(document).on('click', '#wishlist-share div.share-text', function(){ $(this).next('div.share-link-container').slideToggle('slow'); }); } }; wishlist_share(); $(document).on('yit_quick_view_loaded', wishlist_share); /************************* * Update Calculate Shipping Select *************************/ var wc_version = 2.2; if (typeof yit_woocommerce != 'undefined') wc_version = parseFloat(yit_woocommerce.version); if ( wc_version < 2.3 && $.fn.selectbox ) { $('#calc_shipping_state').next('.sbHolder').addClass('stateHolder'); $body.on('country_to_state_changing', function(){ $('.stateHolder').remove(); $('#calc_shipping_state').show().attr('sb', ''); $('select#calc_shipping_state').selectbox({ effect: 'fade', classHolder: 'stateHolder sbHolder' }); }); } /************************* * Login Form *************************/ // $('#login-form').on('submit', function(){ // var a = $('#reg_password').val(); // var b = $('#reg_password_retype').val(); // if(!(a==b)){ // $('#reg_password_retype').addClass('invalid'); // return false; // }else{ // $('#reg_password_retype').removeClass('invalid'); // return true; // } // }); /************************* * PRODUCT QUICK VIEW *************************/ function quick_view_trigger() { $('div.quick-view a.trigger').yit_quick_view({ item_container: 'li.product', loader : 'div.single-product.woocommerce', assets : yit_quick_view.assets, before : function (trigger, item) { // add loading in the button if( typeof yit.load_gif != 'undefined' ) { trigger.parent().block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}}); } else{ trigger.parent().block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}}); } item.find('.thumb-wrapper').addClass('hover'); }, openDialog : function (trigger, item) { // remove loading from button trigger.parent().unblock(); item.find('.thumb-wrapper').removeClass('hover'); }, completed : function (trigger, item, html, overlay) { var data = $('<div>' + html + '</div>'), title = data.find('h1.product_title').html(), price = data.find('p.price').html(), rating = data.find('div.star-rating').html(), container = document.getElementById('wrapper'), wrapper = $(overlay).find('.main .container'); // add main class to dialog container $(overlay).addClass('product-quick-view'); // head $('<p />').addClass('price').html(price).prependTo(wrapper.find('.head')); $('<div />').addClass('star-rating').html(rating).prependTo(wrapper.find('.head')); $('<h4 />').html(title).prependTo(wrapper.find('.head')); //prettyPhoto if ( typeof $.prettyPhoto != 'undefined' ) { data.find( "a[rel^='thumbnails'], a.zoom" ).prettyPhoto({ social_tools : false, theme : 'pp_woocommerce', horizontal_padding: 40, opacity : 0.9, deeplinking : false }); } // quantity fields $('div.quantity:not(.buttons_added), td.quantity:not(.buttons_added)').addClass('buttons_added').append('<input type="button" value="+" class="plus" />').prepend('<input type="button" value="-" class="minus" />'); variations_select(); // add to cart $('form.cart', overlay).on('submit', function (e) { e.preventDefault(); var form = $(this), button = form.find('button'), product_url = item.find('a.thumb').attr('href'); if( typeof yit.load_gif != 'undefined' ) { button.block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}}); } else if (typeof( woocommerce_params.plugin_url ) != 'undefined') { button.block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.plugin_url + '/assets/images/ajax-loader.gif) no-repeat center', opacity: 0.3, cursor: 'none'}}); } else { button.block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}}); } $.post(product_url, form.serialize() + '&_wp_http_referer=' + product_url, function (result) { var message = $( '.woocommerce-message', result ), cart_dropdown = $( '#header .yit_cart_widget', result); if( typeof wc_cart_fragments_params != 'undefined') { // update fragments var $supports_html5_storage; try { $supports_html5_storage = ( 'sessionStorage' in window && window.sessionStorage !== null ); window.sessionStorage.setItem('wc', 'test'); window.sessionStorage.removeItem('wc'); } catch (err) { $supports_html5_storage = false; } $.ajax({ url : wc_cart_fragments_params.wc_ajax_url.toString().replace('%%endpoint%%', 'get_refreshed_fragments'), type : 'POST', success: function (data) { if (data && data.fragments) { $.each(data.fragments, function (key, value) { $(key).replaceWith(value); }); if ($supports_html5_storage) { sessionStorage.setItem(wc_cart_fragments_params.fragment_name, JSON.stringify(data.fragments)); sessionStorage.setItem('wc_cart_hash', data.cart_hash); } $(document.body).trigger('wc_fragments_refreshed'); } } }); } // add message $('div.product', overlay).before(message); // remove loading button.unblock(); }); }); // others $('#wishlist-share').find('.share-link-container').hide(); $('#inquiry-form').find('form.contact-form').hide(); }, action : 'yit_load_product_quick_view' }); } if ($.fn.yit_quick_view && typeof yit_quick_view != 'undefined') { quick_view_trigger(); $(document).on('yith-wcan-ajax-filtered', quick_view_trigger); } /************************* * WISHLIST LABEL *************************/ $( '.yith-wcwl-add-button .add_to_wishlist').on( 'click', function() { var feedback = $(this).closest('.yith-wcwl-add-to-wishlist').find('.yith-wcwl-wishlistaddedbrowse span.feedback'); feedback.fadeIn(); setTimeout( function(){ feedback.fadeOut('slow'); }, 4000 ); }); /************************* * Widget Woo Price Filter *************************/ if( yit.price_filter_slider == 'no' || typeof yit.price_filter_slider == 'undefined' ) { var removePriceFilterSlider = function() { $( 'input#min_price, input#max_price' ).show(); $('form > div.price_slider_wrapper').find( 'div.price_slider, div.price_label' ).hide(); }; removePriceFilterSlider(); } /***************************** * TERMS AND CONDITIONS POPUP *****************************/ if ($.fn.yit_quick_view ) { var term_popup = function() { $('p.terms a').yit_quick_view({ item_container: 'p.terms', loader: '#primary .content', loadPage: true, before: function( trigger, item ) { // add loading in the button if( typeof yit.load_gif != 'undefined' ) { item.block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}}); } else { item.block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}}); } }, completed: function( trigger, item, html, overlay ) { var data = $('<div>' + html + '</div>'), title = trigger.text(), container = document.getElementById( 'wrapper' ), wrapper = $(overlay).find('.main .container'); // head $('<h4 />').html(title).prependTo( wrapper.find('.head') ); $(overlay).addClass('terms-popup'); $(overlay).find('.content').removeClass('col-sm-12 col-sm-9'); }, openDialog: function( trigger, item ) { item.unblock(); } }); }; $body.on('updated_checkout', term_popup); term_popup(); } }); })( jQuery, window, document );<|fim▁end|>
if (product.find('.product-wrapper > .added_to_cart_ico').length == 0) { setTimeout(function() { product.find('.product-wrapper').append('<span class="added_to_cart_ico">' + yit.added_to_cart_ico + '</span>');
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>/** * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS,<|fim▁hole|> import { FirebaseApp, FirebaseNamespace } from '@firebase/app-types'; import { Observer, Unsubscribe, NextFn, ErrorFn, CompleteFn } from '@firebase/util'; export class FirebaseMessaging { private constructor(); deleteToken(token: string): Promise<boolean>; getToken(): Promise<string | null>; onMessage( nextOrObserver: NextFn<any> | Observer<any>, error?: ErrorFn, completed?: CompleteFn ): Unsubscribe; onTokenRefresh( nextOrObserver: NextFn<any> | Observer<any>, error?: ErrorFn, completed?: CompleteFn ): Unsubscribe; requestPermission(): Promise<void>; setBackgroundMessageHandler( callback: (payload: any) => Promise<any> | void ): void; useServiceWorker(registration: ServiceWorkerRegistration): void; usePublicVapidKey(b64PublicKey: string): void; }<|fim▁end|>
* 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. */
<|file_name|>catalog.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- """Script to extract a catalog of Windows Registry keys and values.""" import argparse import logging import sys from dfwinreg import creg as dfwinreg_creg from dfwinreg import regf as dfwinreg_regf from dfwinreg import registry as dfwinreg_registry from winregrc import catalog from winregrc import output_writers class StdoutWriter(output_writers.StdoutOutputWriter): """Stdout output writer.""" def WriteKeyPath(self, key_path): """Writes a key path to the output. Args: key_path (str): key path. """ text = '{0:s}\n'.format(key_path) self.WriteText(text) def WriteValueDescriptor(self, value_name, value_data_type): """Writes a value descriptor to the output.<|fim▁hole|> Args: value_name (str): name of the value. value_data_type (str): data type of the value. """ text = '\t{0:s}\t{1:s}\n'.format(value_name, value_data_type) self.WriteText(text) def Main(): """The main program function. Returns: bool: True if successful or False if not. """ argument_parser = argparse.ArgumentParser(description=( 'Extracts a catalog of Windows Registry keys and values.')) argument_parser.add_argument( 'source', nargs='?', action='store', metavar='PATH', default=None, help='path of a Windows Registry file.') options = argument_parser.parse_args() if not options.source: print('Source value is missing.') print('') argument_parser.print_help() print('') return False logging.basicConfig( level=logging.INFO, format='[%(levelname)s] %(message)s') with open(options.source, 'rb') as file_object: try: registry_file = dfwinreg_regf.REGFWinRegistryFile() registry_file.Open(file_object) except IOError: registry_file = None if not registry_file: try: registry_file = dfwinreg_creg.CREGWinRegistryFile() registry_file.Open(file_object) except IOError: registry_file = None if not registry_file: print('Unable to open Windows Registry file.') return False # Using dfWinReg to determine Windows native key paths if available. registry = dfwinreg_registry.WinRegistry() key_path_prefix = registry.GetRegistryFileMapping(registry_file) registry_file.SetKeyPathPrefix(key_path_prefix) root_key = registry_file.GetRootKey() output_writer_object = StdoutWriter() if not output_writer_object.Open(): print('Unable to open output writer.') print('') return False try: has_results = False if root_key: collector_object = catalog.CatalogCollector() has_results = collector_object.Collect(root_key, output_writer_object) finally: output_writer_object.Close() if not has_results: print('No catalog keys and values found.') return True if __name__ == '__main__': if not Main(): sys.exit(1) else: sys.exit(0)<|fim▁end|>
<|file_name|>tables.py<|end_file_name|><|fim▁begin|>from django.core import urlresolvers from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import timesince, floatformat<|fim▁hole|> class CSVSummary(tables.LinkAction): name = "csv_summary" verbose_name = _("Download CSV Summary") classes = ("btn-download",) iconfont = "iconfont icon-folderadd media-object" card = "card card-blue" def get_link_url(self, usage=None): return self.table.kwargs['usage'].csv_link() class BaseUsageTable(tables.DataTable): vcpus = tables.Column('vcpus', verbose_name=_("VCPUs")) disk = tables.Column('local_gb', verbose_name=_("Disk")) memory = tables.Column('memory_mb', verbose_name=_("RAM"), filters=(mbformat,), attrs={"data-type": "size"}) hours = tables.Column('vcpu_hours', verbose_name=_("VCPU Hours"), filters=(lambda v: floatformat(v, 2),)) class GlobalUsageTable(BaseUsageTable): tenant = tables.Column('tenant_name', verbose_name=_("Project Name")) disk_hours = tables.Column('disk_gb_hours', verbose_name=_("Disk GB Hours"), filters=(lambda v: floatformat(v, 2),)) def get_object_id(self, datum): return datum.tenant_id class Meta: name = "global_usage" verbose_name = _("Usage Summary") columns = ("tenant", "vcpus", "disk", "memory", "hours", "disk_hours") table_actions = (CSVSummary,) multi_select = False def get_instance_link(datum): view = "horizon:project:instances:detail" if datum.get('instance_id', False): return urlresolvers.reverse(view, args=(datum.get('instance_id'),)) else: return None class TenantUsageTable(BaseUsageTable): instance = tables.Column('name', verbose_name=_("Instance Name"), link=get_instance_link) uptime = tables.Column('uptime_at', verbose_name=_("Uptime"), filters=(timesince,)) def get_object_id(self, datum): return datum.get('instance_id', id(datum)) class Meta: name = "tenant_usage" verbose_name = _("Usage Summary") columns = ("instance", "vcpus", "disk", "memory", "uptime") table_actions = () multi_select = False<|fim▁end|>
from horizon import tables from horizon.templatetags.sizeformat import mbformat
<|file_name|>const-int-overflowing.rs<|end_file_name|><|fim▁begin|><|fim▁hole|> //~^ ERROR temporary value dropped while borrowed let y: &'static (i32, bool) = &(5_i32.overflowing_sub(3)); //~^ ERROR temporary value dropped while borrowed let z: &'static (i32, bool) = &(5_i32.overflowing_mul(3)); //~^ ERROR temporary value dropped while borrowed }<|fim▁end|>
fn main() { let x: &'static (i32, bool) = &(5_i32.overflowing_add(3));
<|file_name|>self-impl.rs<|end_file_name|><|fim▁begin|>// Copyright 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<|fim▁hole|>// Test that we can use `Self` types in impls in the expected way. #![allow(unknown_features)] #![feature(box_syntax)] struct Foo; // Test uses on inherent impl. impl Foo { fn foo(_x: Self, _y: &Self, _z: Box<Self>) -> Self { Foo } } // Test uses when implementing a trait and with a type parameter. pub struct Baz<X> { pub f: X, } trait Bar<X> { fn bar(x: Self, y: &Self, z: Box<Self>) -> Self; fn dummy(&self, x: X) { } } impl Bar<int> for Box<Baz<int>> { fn bar(_x: Self, _y: &Self, _z: Box<Self>) -> Self { box Baz { f: 42 } } } fn main() { let _: Foo = Foo::foo(Foo, &Foo, box Foo); let _: Box<Baz<int>> = Bar::bar(box Baz { f: 42 }, &box Baz { f: 42 }, box box Baz { f: 42 }); }<|fim▁end|>
// option. This file may not be copied, modified, or distributed // except according to those terms.
<|file_name|>is_near_arterial.py<|end_file_name|><|fim▁begin|># Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def dependencies(self): return [my_attribute_label(self.distance_to_arterial)] <|fim▁hole|> return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant')) def post_check(self, values, dataset_pool): self.do_check("x == False or x == True", values) def get_is_near_arterial(distance, urbansim_constant): length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"]) from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be) if __name__=='__main__': opus_unittest.main()<|fim▁end|>
def compute(self, dataset_pool):
<|file_name|>holidayConfiguration.ts<|end_file_name|><|fim▁begin|>import { IHolidayExtractorConfiguration, BaseHolidayParserConfiguration } from "../baseHoliday"; import { RegExpUtility } from "recognizers-text-number"; import { DateUtils } from "../utilities"; import { FrenchDateTime } from "../../resources/frenchDateTime"; export class FrenchHolidayExtractorConfiguration implements IHolidayExtractorConfiguration { readonly holidayRegexes: RegExp[]; constructor() { this.holidayRegexes = [ RegExpUtility.getSafeRegExp(FrenchDateTime.HolidayRegex1, "gis"), RegExpUtility.getSafeRegExp(FrenchDateTime.HolidayRegex2, "gis"), RegExpUtility.getSafeRegExp(FrenchDateTime.HolidayRegex3, "gis"), RegExpUtility.getSafeRegExp(FrenchDateTime.HolidayRegex4, "gis") ]; } } export class FrenchHolidayParserConfiguration extends BaseHolidayParserConfiguration { constructor() { super(); this.holidayRegexList = [ RegExpUtility.getSafeRegExp(FrenchDateTime.HolidayRegex1, "gis"), RegExpUtility.getSafeRegExp(FrenchDateTime.HolidayRegex2, "gis"), RegExpUtility.getSafeRegExp(FrenchDateTime.HolidayRegex3, "gis"), RegExpUtility.getSafeRegExp(FrenchDateTime.HolidayRegex4, "gis") ]; this.holidayNames = FrenchDateTime.HolidayNames; this.holidayFuncDictionary = this.initHolidayFuncs(); } protected initHolidayFuncs(): ReadonlyMap<string, (year: number) => Date> { return new Map<string, (year: number) => Date>( [ ...super.initHolidayFuncs(), ["maosbirthday", FrenchHolidayParserConfiguration.MaoBirthday], ["yuandan", FrenchHolidayParserConfiguration.NewYear], ["teachersday", FrenchHolidayParserConfiguration.TeacherDay], ["singleday", FrenchHolidayParserConfiguration.SinglesDay], ["allsaintsday", FrenchHolidayParserConfiguration.HalloweenDay], ["youthday", FrenchHolidayParserConfiguration.YouthDay], ["childrenday", FrenchHolidayParserConfiguration.ChildrenDay], ["femaleday", FrenchHolidayParserConfiguration.FemaleDay], ["treeplantingday", FrenchHolidayParserConfiguration.TreePlantDay], ["arborday", FrenchHolidayParserConfiguration.TreePlantDay], ["girlsday", FrenchHolidayParserConfiguration.GirlsDay], ["whiteloverday", FrenchHolidayParserConfiguration.WhiteLoverDay], ["loverday", FrenchHolidayParserConfiguration.ValentinesDay], ["christmas", FrenchHolidayParserConfiguration.ChristmasDay], ["xmas", FrenchHolidayParserConfiguration.ChristmasDay], ["newyear", FrenchHolidayParserConfiguration.NewYear], ["newyearday", FrenchHolidayParserConfiguration.NewYear], ["newyearsday", FrenchHolidayParserConfiguration.NewYear], ["inaugurationday", FrenchHolidayParserConfiguration.InaugurationDay], ["groundhougday", FrenchHolidayParserConfiguration.GroundhogDay], ["valentinesday", FrenchHolidayParserConfiguration.ValentinesDay], ["stpatrickday", FrenchHolidayParserConfiguration.StPatrickDay], ["aprilfools", FrenchHolidayParserConfiguration.FoolDay], ["stgeorgeday", FrenchHolidayParserConfiguration.StGeorgeDay], ["mayday", FrenchHolidayParserConfiguration.Mayday], ["cincodemayoday", FrenchHolidayParserConfiguration.CincoDeMayoday], ["baptisteday", FrenchHolidayParserConfiguration.BaptisteDay], ["usindependenceday", FrenchHolidayParserConfiguration.UsaIndependenceDay], ["independenceday", FrenchHolidayParserConfiguration.UsaIndependenceDay], ["bastilleday", FrenchHolidayParserConfiguration.BastilleDay], ["halloweenday", FrenchHolidayParserConfiguration.HalloweenDay], ["allhallowday", FrenchHolidayParserConfiguration.AllHallowDay], ["allsoulsday", FrenchHolidayParserConfiguration.AllSoulsday], ["guyfawkesday", FrenchHolidayParserConfiguration.GuyFawkesDay], ["veteransday", FrenchHolidayParserConfiguration.Veteransday], ["christmaseve", FrenchHolidayParserConfiguration.ChristmasEve], ["newyeareve", FrenchHolidayParserConfiguration.NewYearEve], ["fathersday", FrenchHolidayParserConfiguration.FathersDay ], ["mothersday", FrenchHolidayParserConfiguration.MothersDay], ["labourday", FrenchHolidayParserConfiguration.LabourDay ] ]); } // All JavaScript dates are zero-based (-1) private static NewYear(year: number): Date { return new Date(year, 1 - 1, 1); } private static NewYearEve(year: number): Date { return new Date(year, 12 - 1, 31); } private static ChristmasDay(year: number): Date { return new Date(year, 12 - 1, 25); } private static ChristmasEve(year: number): Date { return new Date(year, 12 - 1, 24); } private static FemaleDay(year: number): Date { return new Date(year, 3 - 1, 8); } private static ChildrenDay(year: number): Date { return new Date(year, 6 - 1, 1); } private static HalloweenDay(year: number): Date { return new Date(year, 10 - 1, 31); } private static EasterDay(year: number): Date { return DateUtils.minValue(); }<|fim▁hole|> private static GirlsDay(year: number): Date { return new Date(year, 3, 7);} private static TreePlantDay(year: number): Date { return new Date(year, 3, 12);} private static YouthDay(year: number): Date { return new Date(year, 5, 4);} private static TeacherDay(year: number): Date { return new Date(year, 9, 10);} private static SinglesDay(year: number): Date { return new Date(year, 11, 11);} private static MaoBirthday(year: number): Date { return new Date(year, 12, 26);} private static InaugurationDay(year: number): Date { return new Date(year, 1, 20);} private static GroundhogDay(year: number): Date { return new Date(year, 2, 2);} private static StPatrickDay(year: number): Date { return new Date(year, 3, 17);} private static StGeorgeDay(year: number): Date { return new Date(year, 4, 23);} private static Mayday(year: number): Date { return new Date(year, 5, 1);} private static CincoDeMayoday(year: number): Date { return new Date(year, 5, 5);} private static BaptisteDay(year: number): Date { return new Date(year, 6, 24);} private static UsaIndependenceDay(year: number): Date { return new Date(year, 7, 4);} private static BastilleDay(year: number): Date { return new Date(year, 7, 14);} private static AllHallowDay(year: number): Date { return new Date(year, 11, 1);} private static AllSoulsday(year: number): Date { return new Date(year, 11, 2);} private static GuyFawkesDay(year: number): Date { return new Date(year, 11, 5);} private static Veteransday(year: number): Date { return new Date(year, 11, 11);} protected static FathersDay(year: number): Date { return new Date(year, 6, 17);} protected static MothersDay(year: number): Date { return new Date(year, 5, 27);} protected static LabourDay(year: number): Date { return new Date(year, 5, 1);} getSwiftYear(text: string): number { let trimedText = text.trim().toLowerCase(); let swift = -10; if (trimedText.endsWith("prochain")) { // next - 'l'annee prochain') swift = 1; } else if (trimedText.endsWith("dernier")) { // last - 'l'annee dernier' swift = -1; } else if (trimedText.startsWith("cette")) { // this - 'cette annees' swift = 0; } return swift; } sanitizeHolidayToken(holiday: string): string { return holiday.replace(/ /g, "") .replace(/'/g, ""); } }<|fim▁end|>
private static ValentinesDay(year: number): Date { return new Date(year, 2, 14);} private static WhiteLoverDay(year: number): Date { return new Date(year, 3, 14);} private static FoolDay(year: number): Date { return new Date(year, 4, 1);}
<|file_name|>count-inversions.py<|end_file_name|><|fim▁begin|>def count_inversion(sequence): flag, answer, sequence = True, 0, list(sequence) while flag: flag = False<|fim▁hole|> flag = True return answer def test_function(): assert count_inversion((1, 2, 5, 3, 4, 7, 6)) == 3, "Example" assert count_inversion((0, 1, 2, 3)) == 0, "Sorted" assert count_inversion((99, -99)) == 1, "Two numbers" assert count_inversion((5, 3, 2, 1, 0)) == 10, "Reversed"<|fim▁end|>
for i in xrange(1, len(sequence)): if sequence[i-1] > sequence[i]: sequence[i], sequence[i-1] = sequence[i-1], sequence[i] answer += 1
<|file_name|>apps.py<|end_file_name|><|fim▁begin|>"""Django app config for the analytics app."""<|fim▁hole|> class AnalyticsAppConfig(AppConfig): """Analytics app init code.""" name = 'readthedocs.analytics' verbose_name = 'Analytics'<|fim▁end|>
from django.apps import AppConfig
<|file_name|>EventPhase.ts<|end_file_name|><|fim▁begin|>/** * @module seng-event */ /** * An enum for possible event phases that an event can be in */ enum EventPhase { /** * Indicates that the event is currently not being dispatched */ NONE, /** * Indicates that the event is in the capturing phase, moving down from the top-most EventDispatcher * instance to the parent of the target EventDispatcher<|fim▁hole|> /** * Indicates that we are currently calling the event listeners on the event target during dispatch. */ AT_TARGET, /** * Indicates that we are currently moving back up from the parent of the target EventDispatcher to * the top-most EventDispatcher instance. */ BUBBLING_PHASE, } export default EventPhase;<|fim▁end|>
*/ CAPTURING_PHASE,
<|file_name|>magnet.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Hardware file for the Superconducting Magnet (SCM) QuDi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuDi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuDi. If not, see <http://www.gnu.org/licenses/>. Copyright (c) the Qudi Developers. See the COPYRIGHT.txt file at the top-level directory of this distribution and at <https://github.com/Ulm-IQO/qudi/> """ import socket from core.base import Base import numpy as np import time from interface.magnet_interface import MagnetInterface from collections import OrderedDict import re class Magnet(Base, MagnetInterface): """Magnet positioning software for superconducting magnet. Enables precise positioning of the magnetic field in spherical coordinates with the angle theta, phi and the radius rho. The superconducting magnet has three coils, one in x, y and z direction respectively. The current through these coils is used to compute theta, phi and rho. The alignment can be done manually as well as automatically via fluorescence alignment. """ _modtype = 'Magnet' _modclass = 'hardware' def __init__(self, **kwargs): """Here the connections to the power supplies and to the counter are established""" super().__init__(**kwargs) socket.setdefaulttimeout(3) try: self.soc_x = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.timeout: self.log.error("socket timeout for coil in x-direction") try: self.soc_y = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.timeout: self.log.error("socket timeout for coil in y-direction") try: self.soc_z = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.timeout: self.log.error("socket timeout for coil in z-direction") # default waiting time of the pc after a message was sent to the magnet # should be set in the config file self.waitingtime = 0.01 # This is saves in which interval the input theta was in the last movement self._inter = 1 # this is a new thing. "normal_mode" # allows one to set magnetic fields up to 1 T along each axis # and the magnetic field vector can't be larger than 1.2 T # In z_mode you are allowed to move in a 5° solid angle along the z-axis # with a maximum field of 3 T. # For more documentation or how to change the mode look into # the function switch_mode self.mode = "normal_mode" # constraints of the superconducting magnet in T # should be set in the config file # Normally you should get and set constraints in the # function get_constraints(). The problem is here that # the constraint rho is no constant and is dependent on the # current theta and phi value. self.x_constr = 1.0 self.y_constr = 1.0 self.z_constr = 3.0 self.rho_constr = 1.2 def on_activate(self): """ loads the config file and extracts the necessary configurations for the superconducting magnet @return int: (0: Ok, -1:error) """ # get necessary information from the config file config = self.getConfiguration() if 'magnet_port' in config.keys(): port = config['magnet_port'] else: self.log.error('No port hs been defined in the config file!') return -1 if 'magnet_IP_address_x' in config.keys(): self.soc_x.connect((config['magnet_IP_address_x'], port)) else: self.log.error('No ip-address for connection to x-coil defined!') return -1 if 'magnet_IP_address_y' in config.keys(): self.soc_y.connect((config['magnet_IP_address_y'], port)) else: self.log.error('No ip-address for connection to y-coil defined!') return -1 if 'magnet_IP_address_z' in config.keys(): self.soc_z.connect((config['magnet_IP_address_z'], port)) else: self.log.error('No ip-address for connection to z-coil defined!') return -1 if 'magnet_waitingtime' in config.keys(): self.waitingtime = config['magnet_waitingtime'] if 'magnet_x_constr' in config.keys(): self.x_constr = config['magnet_x_constr'] if 'magnet_y_constr' in config.keys(): self.y_constr = config['magnet_y_constr'] if 'magnet_z_constr' in config.keys(): self.z_constr = config['magnet_z_constr'] if 'magnet_rho_constr' in config.keys(): self.rho_constr = config['magnet_rho_constr'] # sending a signal to all coils to receive an answer to cut off the # useless welcome message. ask_dict = {'x': "STATE?\n", 'y': "STATE?\n", 'z': "STATE?\n"} answ_dict = self.ask(ask_dict) self.log.info("Magnet in state: {0}".format(answ_dict)) # sending a command to the magnet to turn into SI units regarding # field units. self.heat_all_switches() tell_dict = {'x': 'CONF:FIELD:UNITS 1', 'y': 'CONF:FIELD:UNITS 1', 'z': 'CONF:FIELD:UNITS 1'} self.tell(tell_dict) def on_deactivate(self): self.soc_x.close() self.soc_y.close() self.soc_z.close() def utf8_to_byte(self, myutf8): """ Convenience function for code refactoring @param string myutf8 the message to be encoded @return the encoded message in bytes """ return myutf8.encode('utf-8') def byte_to_utf8(self, mybytes): """ Convenience function for code refactoring @param bytes mybytes the byte message to be decoded @return the decoded string in uni code """ return mybytes.decode() # =========================== Magnet Functionality Core ==================================== def get_constraints(self): """ Retrieve the hardware constraints from the magnet driving device. @return dict: dict with constraints for the magnet hardware. These constraints will be passed via the logic to the GUI so that proper display elements with boundary conditions could be made. Provides all the constraints for each axis of a motorized stage (like total travel distance, velocity, ...) Each axis has its own dictionary, where the label is used as the identifier throughout the whole module. The dictionaries for each axis are again grouped together in a constraints dictionary in the form {'<label_axis0>': axis0 } where axis0 is again a dict with the possible values defined below. The possible keys in the constraint are defined in the interface file. If the hardware does not support the values for the constraints, then insert just None. If you are not sure about the meaning, look in other hardware files to get an impression. """ constraints = OrderedDict() pos_dict = self.get_pos() coord_list = [pos_dict['rho'], pos_dict['theta'], pos_dict['phi']] pos_max_dict = self.rho_pos_max({'rad': coord_list}) # get the constraints for the x axis: axis0 = {} axis0['label'] = 'rho' # name is just as a sanity included axis0['unit'] = 'T' # the SI units axis0['pos_min'] = 0 axis0['pos_max'] = pos_max_dict['rho'] axis0['pos_step'] = 300000 axis0['vel_min'] = 0 axis0['vel_max'] = 0.0404*0.01799 # unit is T/s axis0['vel_step'] = 10**4 # In fact position constraints for rho is dependent on theta and phi, which would need # the use of an additional function to calculate # going to change the return value to a function rho_max_pos which needs the current theta and # phi position # get the constraints for the x axis: axis1 = {} axis1['label'] = 'theta' # name is just as a sanity included axis1['unit'] = 'rad' # the SI units axis1['pos_min'] = -1000 # arbitrary values for now ( there isn't any restriction on them ) axis1['pos_max'] = 1000 # that is basically the traveling range axis1['pos_step'] = 36000 axis1['vel_min'] = 0 axis1['vel_max'] = 0.0404*0.01799 #unit is T/s axis1['vel_step'] = 10**4 # get the constraints for the x axis: axis2 = {} axis2['label'] = 'phi' # name is just as a sanity included axis2['unit'] = 'rad' # the SI units axis2['pos_min'] = -1000 # arbitrary values for now ( there isn't any restriction on them ) axis2['pos_max'] = 1000 # that is basically the traveling range axis2['pos_step'] = 92000 axis2['vel_min'] = 0 axis2['vel_max'] = 0.0380*0.07028 #unit is T/s axis2['vel_step'] = 10**4 # assign the parameter container for x to a name which will identify it constraints[axis0['label']] = axis0 constraints[axis1['label']] = axis1 constraints[axis2['label']] = axis2 return constraints def tell(self, param_dict): """Send a command string to the magnet. @param dict param_dict: has to have one of the following keys: 'x', 'y' or 'z' with an appropriate command for the magnet """ internal_counter = 0 if param_dict.get('x') is not None: if not param_dict['x'].endswith('\n'): param_dict['x'] += '\n' self.soc_x.send(self.utf8_to_byte(param_dict['x'])) internal_counter += 1 if param_dict.get('y') is not None: if not param_dict['y'].endswith('\n'): param_dict['y'] += '\n' self.soc_y.send(self.utf8_to_byte(param_dict['y'])) internal_counter += 1 if param_dict.get('z') is not None: if not param_dict['z'].endswith('\n'): param_dict['z'] += '\n' self.soc_z.send(self.utf8_to_byte(param_dict['z'])) internal_counter += 1 if internal_counter == 0: self.log.warning('no parameter_dict was given therefore the ' 'function tell() call was useless') def ask(self, param_dict): """Asks the magnet a 'question' and returns an answer from it. @param dictionary param_dict: has to have one of the following keys: 'x', 'y' or 'z' the items have to be valid questions for the magnet. @return answer_dict: contains the same labels as the param_dict if it was set correct and the corresponding items are the answers of the magnet (format is string), else an empty dictionary is returned """ answer_dict = {} if param_dict.get('x') is not None: if not param_dict['x'].endswith('\n'): param_dict['x'] += '\n' # repeat this block to get out crappy messages. self.soc_x.send(self.utf8_to_byte(param_dict['x'])) # time.sleep(self.waitingtime) # you need to wait until magnet generating # an answer. answer_dict['x'] = self.byte_to_utf8(self.soc_x.recv(1024)) # receive an answer self.soc_x.send(self.utf8_to_byte(param_dict['x'])) # time.sleep(self.waitingtime) # you need to wait until magnet generating # an answer. answer_dict['x'] = self.byte_to_utf8(self.soc_x.recv(1024)) # receive an answer answer_dict['x'] = answer_dict['x'].replace('\r', '') answer_dict['x'] = answer_dict['x'].replace('\n', '') if param_dict.get('y') is not None: if not param_dict['y'].endswith('\n'): param_dict['y'] += '\n' self.soc_y.send(self.utf8_to_byte(param_dict['y'])) # time.sleep(self.waitingtime) # you need to wait until magnet generating # an answer. answer_dict['y'] = self.byte_to_utf8(self.soc_y.recv(1024)) # receive an answer self.soc_y.send(self.utf8_to_byte(param_dict['y'])) # time.sleep(self.waitingtime) # you need to wait until magnet generating # an answer. answer_dict['y'] = self.byte_to_utf8(self.soc_y.recv(1024)) # receive an answer answer_dict['y'] = answer_dict['y'].replace('\r', '') answer_dict['y'] = answer_dict['y'].replace('\n', '') if param_dict.get('z') is not None: if not param_dict['z'].endswith('\n'): param_dict['z'] += '\n' self.soc_z.send(self.utf8_to_byte(param_dict['z'])) # time.sleep(self.waitingtime) # you need to wait until magnet generating # an answer. answer_dict['z'] = self.byte_to_utf8(self.soc_z.recv(1024)) # receive an answer self.soc_z.send(self.utf8_to_byte(param_dict['z'])) # time.sleep(self.waitingtime) # you need to wait until magnet generating # an answer. answer_dict['z'] = self.byte_to_utf8(self.soc_z.recv(1024)) # receive an answer answer_dict['z'] = answer_dict['z'].replace('\r', '') answer_dict['z'] = answer_dict['z'].replace('\n', '') if len(answer_dict) == 0: self.log.warning('no parameter_dict was given therefore the ' 'function call ask() was useless') return answer_dict def get_status(self, param_list=None): """ Get the status of the position @param list param_list: optional, if a specific status of an axis is desired, then the labels of the needed axis should be passed in the param_list. If nothing is passed, then from each axis the status is asked. @return dict: with the axis label as key and the status number as item. Possible states are { -1 : Error, 1: SCM doing something, 0: SCM doing nothing } """ # I have chosen the numbers rather lightly and # an improvement is probably easily achieved. if param_list is not None: status_plural = self.ask_status(param_list) else: status_plural = self.ask_status() status_dict = {} for axes in status_plural: status = status_plural[axes] translated_status = -1 if status == '1': translated_status = 1 elif status == '2': translated_status = 0 elif status == '3': translated_status = 0 elif status == '4': translated_status = 1 elif status == '5': translated_status = 0 elif status == '6': translated_status = 1 elif status == '7': translated_status = -1 elif status == '8': translated_status = 0 elif status == '9': translated_status = 1 elif status == '10': translated_status = 1 status_dict[axes] = translated_status # adjusting to the axis problem axes = ['rho', 'theta', 'phi'] return_dict = {axes[i] : status_dict[old_key] for i, old_key in enumerate(status_dict)} return return_dict def heat_switch(self, axis): """ This function enables heating of the PJSwitch, which is a necessary step to conduct current to the coils. @param string axis: desired axis (x, y, z) """ if axis == "x": self.soc_x.send(self.utf8_to_byte("PS 1\n")) elif axis == "y": self.soc_y.send(self.utf8_to_byte("PS 1\n")) elif axis == "z": self.soc_z.send(self.utf8_to_byte("PS 1\n")) else: self.log.error("In function heat_switch only 'x', 'y' and 'z' are possible axes") def heat_all_switches(self): """ Just a convenience function to heat all switches at once, as it is unusual to only apply a magnetic field in one direction""" self.heat_switch("x") self.heat_switch("y") self.heat_switch("z") def cool_switch(self, axis): """ Turns off the heating of the PJSwitch, axis depending on user input @param string axis: desired axis (x, y, z) """ if axis == "x": self.soc_x.send(self.utf8_to_byte("PS 0\n")) elif axis == "y": self.soc_y.send(self.utf8_to_byte("PS 0\n")) elif axis == "z": self.soc_z.send(self.utf8_to_byte("PS 0\n")) else: self.log.error("In function cool_switch only 'x', 'y' and 'z' are possible axes") def cool_all_switches(self): """ Just a convenience function to cool all switches at once This will take 600s.""" self.cool_switch("x") self.cool_switch("y") self.cool_switch("z") def initialize(self): """ Acts as a switch. When all coils of the superconducting magnet are heated it cools them, else the coils get heated. @return int: (0: Ok, -1:error) """ # need to ask if the PJSwitch is on answ_dict = {} answ_dict = self.ask({'x': "PS?", 'y': "PS?", 'z': "PS?"}) if answ_dict['x'] == answ_dict['y'] == answ_dict['z']: if answ_dict['x'] == '0': self.heat_all_switches() else: self.cool_all_switches() else: self.log.warning('can not correctly turn on/ turn off magnet, ' 'because not all coils are in the same state in function ' 'initialize') return -1 return 0 # how to realize this function ? def idle_magnet(self): """ Cool all coils of the superconducting magnet to achieve maximum accuracy after aligning. @return int: (0: Ok, -1:error) """ self.cool_all_switches() return 0 def wake_up_magnet(self): """ Heat all coils of the superconducting magnet to get back to the working state. @return int: (0: Ok, -1:error) """ self.heat_all_switches() return 0 def switch_mode(self, bool_var): """ This function is special for this Super Conducting Magnet (SCM). It stems from the constraints on the coils. There is one mode (so called "normal_mode" which allows a field strength of up to 1 T in each direction and a combined field strength of 1.2 T. The z_mode is special as the z-coil can conduct more current and therefore exert higher field values. In this mode the combined field strength is allowed to be as high as 3 T but only within a cone of 5° to the z-axis. @param bool_var: True sets mode to "normal_mode", and False to "z_mode" @return int: (0: 0k, -1:error) """ if bool_var: if self.mode != "normal_mode": self.calibrate() self.mode = "normal_mode" else: if self.mode != "z_mode": self.calibrate() self.mode = "z_mode" return 0 def target_field_setpoint(self, param_dict): """ Function to set the target field (in T), which will be reached through the function ramp(self, param_list). @param dict param_dict: Contains as keys the axes to be set e.g. 'x' or 'y' and the items are the float values for the new field generated by the coil of that axis. @return int: error code (0:OK, -1:error) """ field_dict = self.get_current_field() mode = self.mode if param_dict.get('x') is not None: field_dict['x'] = param_dict['x'] if param_dict.get('y') is not None: field_dict['y'] = param_dict['y'] if param_dict.get('z') is not None: field_dict['z'] = param_dict['z'] if param_dict.get('x') is None and param_dict.get('x') is None and param_dict.get('x') is None: self.log.warning('no valid axis was supplied in ' 'target_field_setpoint') return -1 new_coord = [field_dict['x'], field_dict['y'], field_dict['z']] check_var = self.check_constraints({mode: {'cart': new_coord}}) if check_var: if param_dict.get('x') is not None: self.soc_x.send(self.utf8_to_byte("CONF:FIELD:TARG " + str(param_dict['x']) + "\n")) if param_dict.get('y') is not None: self.soc_y.send(self.utf8_to_byte("CONF:FIELD:TARG " + str(param_dict['y']) + "\n")) if param_dict.get('z') is not None: self.soc_z.send(self.utf8_to_byte("CONF:FIELD:TARG " + str(param_dict['z']) + "\n")) else: self.log.warning('resulting field would be too high in ' 'target_field_setpoint') return -1 return 0 def ramp(self, param_list=None): """ function to ramp the magnetic field in the direction(s) to the target field values @param list param_list: This param is optional. If supplied it has to contain the labels for the axes, which should be ramped (only cartesian makes sense here), else all axes will be ramped. @return int: error code (0:OK, -1:error) """ if param_list is None: self.soc_x.send(self.utf8_to_byte("RAMP\n")) self.soc_y.send(self.utf8_to_byte("RAMP\n")) self.soc_z.send(self.utf8_to_byte("RAMP\n")) else: if 'x' in param_list: self.soc_x.send(self.utf8_to_byte("RAMP\n")) elif 'y' in param_list: self.soc_y.send(self.utf8_to_byte("RAMP\n")) elif 'z' in param_list: self.soc_z.send(self.utf8_to_byte("RAMP\n")) else: self.log.warning('in function ramp your definition of ' 'param_list was incorrect') return -1 return 0 def ramp_to_zero(self, axis): """ Function to ramp down a specific coil to zero current @param axis: string axis: (allowed inputs 'x', 'y' and 'z') """ if axis == "x": self.soc_x.send(self.utf8_to_byte("ZERO\n")) elif axis == "y": self.soc_y.send(self.utf8_to_byte("ZERO\n")) elif axis == "z": self.soc_z.send(self.utf8_to_byte("ZERO\n")) else: self.log.error("In function ramp_to_zero only 'x', 'y' and 'z' are possible axes") def calibrate(self, param_list=None): """ Calibrates the stage. In the case of the super conducting magnet this just means moving all or a user specified coil to zero magnetic field. @param dict param_list: param_list: optional, if a specific calibration of an axis is desired, then the labels of the needed axis should be passed in the param_list. If nothing is passed, then all connected axis will be calibrated. @return int: error code (0:OK, -1:error) After calibration the stage moves to home position which will be the zero point for the passed axis. The calibration procedure will be different for each stage. """ if not param_list: self.ramp_to_zero("x") self.ramp_to_zero("y") self.ramp_to_zero("z") else: if 'x' in param_list: self.ramp_to_zero("x") elif 'y' in param_list: self.ramp_to_zero("y") elif 'z' in param_list: self.ramp_to_zero("z") else: self.log.error('no valid axis was supplied') return -1 return 0 def set_coordinates(self, param_dict): """ Function to set spherical coordinates ( keep in mind all is in radians) This function is intended to replace the old set functions ( set_magnitude, set_theta, set_phi ). @param dict param_dict: dictionary, which passes all the relevant field values, that should be passed. Usage: {'axis_label': <the-abs-pos-value>}. 'axis_label' must correspond to a label given to one of the axis. In this case the axes are labeled 'rho', 'theta' and 'phi' @return int: error code (0:OK, -1:error) """ answ_dict = {} coord_list = [] transform_dict = {'cart': {'rad': coord_list}} answ_dict = self.get_current_field() coord_list.append(answ_dict['x']) coord_list.append(answ_dict['y']) coord_list.append(answ_dict['z']) coord_list = self.transform_coordinates(transform_dict) label_list = ['rho', 'theta', 'phi'] if param_dict.get('rho') is not None: coord_list[0] = param_dict['rho'] if param_dict.get('theta') is not None: coord_list[1] = param_dict['theta'] if param_dict.get('phi') is not None: coord_list[2] = param_dict['phi'] for key in param_dict.keys(): if key not in label_list: self.log.warning("The key "+key+" provided is no valid key in set_coordinates.") return -1 transform_dict = {'rad': {'cart': coord_list}} coord_list = self.transform_coordinates(transform_dict) set_point_dict = {'x': coord_list[0], 'y': coord_list[1], 'z': coord_list[2]} check_val = self.target_field_setpoint(set_point_dict) return check_val def move_abs(self, param_dict): """ Moves stage to absolute position (absolute movement) @param dict param_dict: dictionary, which passes all the relevant parameters, that should be changed. Usage: {'axis_label': <the-abs-pos-value>}. 'axis_label' must correspond to a label given to one of the axis. In this case the axes are labeled 'rho', 'theta' and 'phi'. @return int: error code (0:OK, -1:error) """ # the problem here is, that check_coordinates needs a complete dictionary with all # labels while move_abs doesn't need it. I think it is better to extend this flexibility to # check_constraints than changing move_abs. coord_list = [] mode = self.mode param_dict = self.update_coordinates(param_dict) coord_list.append(param_dict['rho']) coord_list.append(param_dict['theta']) coord_list.append(param_dict['phi']) # lets adjust theta theta = param_dict['theta'] phi = param_dict['phi'] # switch variable decides what has to be done ( in intervals [2*k*np.pi, 2k+1*np.pi] the movement would # be ok ( no rotation in phi ). In the other intervals one has to see if there was a movement before this # movement in one of these regions or not. If not just move, if there was shift to the interval [0, np.pi] and # move there. switch = np.ceil(theta / np.pi) % 2 inter1 = np.ceil(theta / np.pi) inter1 = int(inter1) # if inter1 > 0: # inter1 -= 1 # move the theta values in the right range # for the constraints # if in an even interval if switch: theta -= np.pi * (inter1 - 1) else: # get into the correct interval theta -= np.pi * (inter1 - 1) # now mirror at the center of the interval theta = np.pi/2 - (theta - np.pi/2) # interval was correct if switch: self._inter = inter1 # interval that needs rotation around z-axis in case it wasn't outside that interval before else: # actually it isn't necessary to distinguish here. I initially thought it is necessary and it would # be if one would move the magnet based on the magnet field of previous values. # I will leave the code here for now, when somebody in the future wants to extend this function # to allow both behaviors he can use the existing code. # theta was in a correct interval before but isn't now ( change of interval ) self.log.debug('need rotation around phi to adjust for negative theta value') self.log.debug('old int: {0}, new int: {1}'.format(self._inter, inter1)) if int(np.abs(self._inter - inter1)) is 1: phi += np.pi # theta wasn't in a correct interval before and is still in the same interval ( in this case do nothing ) elif int(np.abs(self._inter - inter1)) is 0: phi += np.pi else: self.log.warning("There was a difference in intervals larger " "than one between two consecutive movements. This is not supported " "yet.{0}".format(self._inter - inter1)) self._inter = inter1 # adjust the phi values so they are in the right interval. They might be in the wrong interval # due to user input or theta values inter2 = np.ceil(phi / (2 * np.pi)) inter2 = int(inter2) # if inter2 > 0: # inter2 -= 1 phi -= 2 * np.pi * (inter2 - 1) self.log.debug('show old dictionary: {0}'.format(param_dict)) # set the corrected values param_dict['theta'] = theta param_dict['phi'] = phi constr_dict = {mode: {'rad': coord_list}} self.log.debug('show new dictionary: {0}'.format(param_dict)) check_bool = self.check_constraints(constr_dict) if check_bool: check_1 = self.set_coordinates(param_dict) check_2 = self.ramp() else: self.log.warning("move_abs hasn't done anything, see check_constraints message why") return -1 if check_1 is check_2: if check_1 is 0: return 0 else: return -1 def move_rel(self, param_dict): """ Moves stage in given direction (in spheric coordinates with theta and phi in radian) @param dict param_dict: dictionary, which passes all the relevant parameters, which should be changed. Usage: {'axis_label': <the-abs-pos-value>}. 'axis_label' must correspond to a label given to one of the axis. @return int: error code (0:OK, -1:error) """ coord_list = [] answ_dict = self.get_current_field() coord_list.append(answ_dict['x']) coord_list.append(answ_dict['y']) coord_list.append(answ_dict['z']) transform_dict = {'cart': {'rad': coord_list}} coord_list = self.transform_coordinates(transform_dict) label_list = ['rho', 'theta', 'phi'] if param_dict.get('rho') is not None: coord_list[0] += param_dict['rho'] if param_dict.get('theta') is not None: coord_list[1] += param_dict['theta'] if param_dict.get('phi') is not None: coord_list[2] += param_dict['phi'] for key in param_dict.keys(): if key not in label_list: self.log.warning("The key "+key+" provided is no valid key in set_coordinates.") return -1 new_coord_dict = {'rho': coord_list[0], 'theta': coord_list[1], 'phi': coord_list[2]} check_val = self.move_abs(new_coord_dict) return check_val def transform_coordinates(self, param_dict): """ Function for generic coordinate transformation. This is a refactoring to the old functions (4) to be replaced by just one function @param dict param_dict: contains a param_dict, which contains a list of values to be transformed. The transformation depends on the keys of the first and the second dictionary. Possible keys are: "deg", "rad", "cart" for example if the first key is deg and the second is cartesian then the values in the list will be transformed from deg to cartesian. Ordering of the values should be [x,y,z] (cartesian) or [rho, theta, phi] for deg or rad @return list containing the transformed values """ # here all the possible cases for transformations # are checked if param_dict.get('deg') is not None: if param_dict['deg'].get('rad') is not None: try: rho, theta, phi = param_dict['deg'].get('rad') except ValueError: self.log.error('Supplied input list for transform_coordinates has to be of length 3: returning initial values') return [-1, -1, -1] theta = theta*np.pi/180 phi = phi*np.pi/180 return_list = [rho, theta, phi] return return_list if param_dict['deg'].get('cart') is not None: cartesian_list = [] try: rho, theta, phi = param_dict['deg'].get('cart') except ValueError: self.log.error('Supplied input list for transform_coordinates has to be of length 3: returning [-1,-1,-1]') return [-1, -1, -1] # transformations that should probably be revisited. # They are there in case the theta and phi values # are not in the correct range. while theta >= 180: phi += 180 theta = 360 - theta while theta < 0: theta = -theta phi += 180 while phi >= 360: phi += 360 while phi < 0: phi += 360 cartesian_list.append(rho * np.sin(theta * 2 * np.pi / 360) * np.cos(phi * 2 * np.pi / 360)) cartesian_list.append(rho * np.sin(theta * 2 * np.pi / 360) * np.sin(phi * 2 * np.pi / 360)) cartesian_list.append(rho * np.cos(theta * 2 * np.pi / 360)) return cartesian_list if param_dict.get('rad') is not None: if param_dict['rad'].get('deg') is not None: try: rho, theta, phi = param_dict['rad']['deg'] except ValueError: self.log.error("Supplied input list for transform_coordinates has to be of length 3: returning [-1, -1, -1]") return [-1,-1,-1] theta = 180*theta/np.pi phi = 180*phi/np.pi return_list = [rho, theta, phi] return return_list if param_dict['rad'].get('cart') is not None: try: rho, theta, phi = param_dict['rad']['cart'] except ValueError: self.log.error("Supplied input list for transf has to be of length 3: returning [-1, -1, -1]") return [-1,-1,-1] x_val = rho * np.sin(theta) * np.cos(phi) y_val = rho * np.sin(theta) * np.sin(phi) z_val = rho * np.cos(theta) return_list = [x_val, y_val, z_val] return return_list if param_dict.get('cart') is not None: if param_dict['cart'].get('deg') is not None: try: x_val, y_val, z_val = param_dict['cart']['deg'] except ValueError: self.log.error("Supplied input list for transform_coordinates has to be of length 3: returning [-1, -1, -1]") return [-1,-1,-1] rho = np.sqrt(x_val ** 2 + y_val ** 2 + z_val ** 2) if rho == 0: theta = 0 else: theta = np.arccos(z_val/rho) * 360/(2 * np.pi) if x_val == 0 and y_val == 0: phi = 0 else: phi = np.arctan2(y_val, x_val) * 360/(2 * np.pi) if phi < 0: phi += 360 return_list = [rho, theta, phi] return return_list if param_dict['cart'].get('rad') is not None: try: x_val, y_val, z_val = param_dict['cart']['rad'] except ValueError: self.log.error("Supplied input list for transform_coordinates has to be of length 3: returning [-1, -1, -1]") return [-1,-1,-1] rho = np.sqrt(x_val ** 2 + y_val ** 2 + z_val ** 2) if rho == 0: theta = 0 else: theta = np.arccos(z_val/rho) if x_val == 0 and y_val == 0: phi = 0 else: phi = np.arctan2(y_val, x_val) if phi < 0: phi += 2 * np.pi return_list = [rho, theta, phi] return return_list def get_current_field(self): """ Function that asks the magnet for the current field strength in each direction @param: @param x : representing the field strength in x direction @param y : representing the field strength in y direction float z : representing the field strength in z direction """ ask_dict = {} ask_dict['x'] = "FIELD:MAG?\n" ask_dict['y'] = "FIELD:MAG?\n" ask_dict['z'] = "FIELD:MAG?\n" answ_dict = self.ask(ask_dict) # having always a weird bug, where the response of the magnet # doesn't make sense, as it is always the same way I try to # catch these exceptions. # pattern to recognize decimal numbers ( There is one issue here e.g. (0.01940.01345) gives one match # with 0.01940. Don't think it will matter much.) my_pattern = re.compile('[-+]?[0-9][.][0-9]+') try: answ_dict['x'] = float(answ_dict['x']) except ValueError: match_list = re.findall(my_pattern, answ_dict['x']) answ_dict['x'] = float(match_list[0]) try: answ_dict['y'] = float(answ_dict['y']) except ValueError: match_list = re.findall(my_pattern, answ_dict['y']) answ_dict['y'] = float(match_list[0]) try: answ_dict['z'] = float(answ_dict['z']) except ValueError: match_list = re.findall(my_pattern, answ_dict['z']) answ_dict['z'] = float(match_list[0]) return answ_dict def get_pos(self, param_list=None): """ Gets current position of the stage @param list param_list: optional, if a specific position of an axis is desired, then the labels of the needed axis should be passed in the param_list. If nothing is passed, then from each axis the position is asked. @return dict mypos: with keys being the axis labels and item the current position. Given in spheric coordinates with Units T, rad , rad. """ mypos = {} mypos1 = {} answ_dict = self.get_current_field() coord_list = [answ_dict['x'], answ_dict['y'], answ_dict['z']] rho, theta, phi = self.transform_coordinates({'cart': {'rad': coord_list}}) mypos1['rho'] = rho mypos1['theta'] = theta mypos1['phi'] = phi if param_list is None: return mypos1 else: if "rho" in param_list: mypos['rho'] = mypos1['rho'] if "theta" in param_list: mypos['theta'] = mypos1['theta'] if "phi" in param_list: mypos['phi'] = mypos1['phi'] return mypos def stop_hard(self, param_list=None): """ function that pauses the heating of a specific coil depending on the elements in param_list. @param list param_list: Can contain elements 'x', 'y' or 'z'. In the case no list is supplied the heating of all coils is stopped @return integer: 0 everything is ok and -1 an error occured. """ if not param_list: self.soc_x.send(self.utf8_to_byte("PAUSE\n")) self.soc_y.send(self.utf8_to_byte("PAUSE\n")) self.soc_z.send(self.utf8_to_byte("PAUSE\n")) elif len(param_list) > 0: self.log.warning('Some useless parameters were passed.') return -1 else: if 'x' in param_list: self.soc_x.send(self.utf8_to_byte("PAUSE\n")) param_list.remove('x') if 'y' in param_list: self.soc_y.send(self.utf8_to_byte("PAUSE\n")) param_list.remove('y') if 'z' in param_list: self.soc_z.send(self.utf8_to_byte("PAUSE\n")) param_list.remove('z') return 0 def abort(self): """ Stops movement of the stage @return int: error code (0:OK, -1:error) """ # could think about possible exceptions here and # catch them and return -1 in case ab = self.stop_hard() return ab def ask_status(self, param_list = None): """ Function that returns the status of the coils ('x','y' and 'z') given in the param_dict @param list param_list: string (elements allowed 'x', 'y' and 'z') for which the status should be returned. Can be None, then the answer is the same as for the list ['x','y','z']. @return state: returns a string, which contains the number '1' to '10' representing the state, the magnet is in. For further information on the meaning of the numbers see translated_get_status() """ ask_dict = {} for i_dea in range(2): if not param_list: ask_dict['x'] = "STATE?\n" ask_dict['y'] = "STATE?\n" ask_dict['z'] = "STATE?\n" else: for axis in param_list: ask_dict[axis] = "STATE?\n" if i_dea == 0: pass # wait some time not sure if this is necessary. # time.sleep(self.waitingtime) answer_dict = self.ask(ask_dict) return answer_dict def translated_get_status(self, param_list=None): """ Just a translation of the numbers according to the manual supplied by American Magnets, Inc. @param list param_list: string (elements allowed 'x', 'y' and 'z') for which the translated status should be returned. Can be None, then the answer is the same as for the list ['x','y','z'] @return dictionary status_dict: keys are the elements of param_list and the items contain the message for the user. """ status_dict = self.ask_status(param_list) for myiter in status_dict.keys(): stateval = status_dict[myiter] try: if int(stateval) > 10: stateval = int(stateval) while stateval > 10: stateval //= 10 stateval = str(stateval) if stateval == '1': translated_status = 'RAMPING to target field/current' elif stateval == '2': translated_status = 'HOLDING at the target field/current' elif stateval == '3': translated_status = 'PAUSED' elif stateval == '4': translated_status = 'Ramping in MANUAL UP mode' elif stateval == '5': translated_status = 'Ramping in MANUAL DOWN mode' elif stateval == '6': translated_status = 'ZEROING CURRENT (in progress)' elif stateval == '7': translated_status = 'Quench detected' elif stateval == '8': translated_status = 'At ZERO current' elif stateval == '9': translated_status = 'Heating persistent switch' elif stateval == '10': translated_status = 'Cooling persistent switch' else: self.log.warning('Something went wrong in ask_status as the statevalue was not between 1 and 10!') return -1 except ValueError: self.log.warning("Sometimes the magnet returns nonsense after a request") return -1 status_dict[myiter] = translated_status return status_dict # This first version of set and get velocity will be very simple # Normally one can set up several ramping rates for different field # regions and so on. I also leave it to the user to find out how many # segments he has and so on. If nothing is changed the magnet should have # 1 segment and max_val should be the max_val that can be reached in that # direction. def set_velocity(self, param_dict): """ Function to change the ramp rate in T/s (ampere per second) @param dict: contains as keys the different cartesian axes ('x', 'y', 'z') and the dict contains list of parameters, that have to be supplied. In this case this is segment, ramp_rate and maxval. How does this work? The maxval for the current marks the endpoint and in between you have several segments with differen ramp_rates. @return int: error code (0:OK, -1:error) """ tell_dict = {} return_val = 0 internal_counter = 0 constraint_dict = self.get_constraints() if param_dict.get('x') is not None: param_list = list() param_list.append(1) # the segment param_list.append(param_dict['x']) param_list.append(1) # the upper bound of the velocity constraint_x = constraint_dict['rho']['vel_max'] if constraint_x > param_list[1]: tell_dict['x'] = 'CONF:RAMP:RATE:FIELD:' + str(param_list[0]) + ", " + str(param_list[1]) + ", " + str(param_list[2]) else: self.log.warning("constraint vel_max was violated in set_velocity with axis = 'x'") internal_counter += 1 if param_dict.get('y') is not None: param_list = list() param_list.append(1) # the segment param_list.append(param_dict['y']) param_list.append(1) # the upper bound of the velocity constraint_y = constraint_dict['theta']['vel_max'] if constraint_y > param_list[1]: tell_dict['y'] = 'CONF:RAMP:RATE:FIELD:' + str(param_list[0]) + ", " + str(param_list[1]) + ", " + str(param_list[2]) else: self.log.warning("constraint vel_max was violated in set_velocity with axis = 'y'") internal_counter += 1 if param_dict.get('z') is not None: param_list = list() param_list.append(1) # the segment param_list.append(param_dict['z']) param_list.append(3) # the upper bound of the velocity constraint_z = constraint_dict['phi']['vel_max'] if constraint_z > param_list[1]: tell_dict['z'] = 'CONF:RAMP:RATE:FIELD:' + str(param_list[0]) + ", " + str(param_list[1]) + ", " + str(param_list[2]) else: self.log.warning("constraint vel_max was violated in set_velocity with axis = 'z'") internal_counter += 1 if internal_counter > 0: self.tell(tell_dict) else: self.log.warning('There was no statement supplied in change_ramp_rate') return_val = -1 return return_val def get_velocity(self, param_list=None): """ Gets the current velocity for all connected axes. @param dict param_list: optional, if a specific velocity of an axis is desired, then the labels of the needed axis should be passed as the param_list. If nothing is passed, then from each axis the velocity is asked. @return dict: with the axis label as key and the velocity as item. """ ask_dict = {} return_dict = {} if param_list is None: ask_dict['x'] = "RAMP:RATE:FIELD:1?" ask_dict['y'] = "RAMP:RATE:FIELD:1?" ask_dict['z'] = "RAMP:RATE:FIELD:1?" answ_dict = self.ask(ask_dict) return_dict['x'] = float(answ_dict['x'].split(',')[0]) return_dict['y'] = float(answ_dict['y'].split(',')[0]) return_dict['z'] = float(answ_dict['z'].split(',')[0]) else: for axis in param_list: ask_dict[axis] = "RAMP:RATE:FIELD:1?" answ_dict = self.ask(ask_dict) for axis in param_list: return_dict[axis] = float(answ_dict[axis].split(',')[0]) return return_dict def check_constraints(self, param_dict): """ Function that verifies if for a given configuration of field strength exerted through the coils the constraints of the magnet are violated. @param dictionary param_dict: the structure of the dictionary is as follows {'z_mode': {'cart': [a,b,c]}} with available keys 'z_mode' and 'normal_mode'. The dictionary inside the dictionary can contain the label 'deg', 'cart' and 'rad'. The list contains then the new values and checks the constraints for them. z_mode means you can reach fields of 3 T in z-direction as long as the field vector is directed in z-direction within an accuracy of 5°. In this mode you should still be careful and the 5° restriction is kind of arbitrary and not experimented with. @return: boolean check_var: True if the constraints are fulfilled and False otherwise """ # First going to include a local function to check the constraints for cartesian coordinates # This helps to just reuse this function for the check of 'deg' and 'rad' cases. def check_cart_constraints(coord_list, mode): my_boolean = True try: x_val, y_val, z_val = coord_list except ValueError: self.log.error("In check_constraints list has not the right amount of elements (3).") return [-1, -1, -1] if mode == "normal_mode": if np.abs(x_val) > self.x_constr: my_boolean = False if np.abs(y_val) > self.y_constr: my_boolean = False if np.abs(z_val) > self.x_constr: my_boolean = False field_magnitude = np.sqrt(x_val**2 + y_val**2 + z_val**2) if field_magnitude > self.rho_constr: my_boolean = False elif mode == "z_mode": # Either in sphere on top of the cone # or in cone itself. my_boolean = False # angle 5° cone # 3T * cos(5°) height_cone = 2.9886 if (np.abs(z_val) <= height_cone) and ((x_val**2 + y_val**2) <= z_val**2): my_boolean = True elif x_val**2 + y_val**2 + (z_val - height_cone)**2 <= self.rho_constr: my_boolean = True elif x_val**2 + y_val**2 + (z_val + height_cone)**2 <= self.rho_constr: my_boolean = True if not my_boolean: self.log.warning("In check_constraints your settings don't lie in the allowed cone. See the "<|fim▁hole|> return my_boolean return_val = False if param_dict.get('normal_mode') is not None: if param_dict['normal_mode'].get("cart") is not None: return_val = check_cart_constraints(param_dict['normal_mode']["cart"], 'normal_mode') if param_dict['normal_mode'].get("rad") is not None: transform_dict = {'rad': {'cart': param_dict['normal_mode']["rad"]}} cart_coord = self.transform_coordinates(transform_dict) return_val = check_cart_constraints(cart_coord, 'normal_mode') # ok degree mode here won't work properly, because I don't check the move constraints if param_dict['normal_mode'].get("deg") is not None: transform_dict = {'deg': {'cart': param_dict['normal_mode']["deg"]}} cart_coord = self.transform_coordinates(transform_dict) return_val = check_cart_constraints(cart_coord, 'normal_mode') elif param_dict.get('z_mode') is not None: if param_dict['z_mode'].get("cart") is not None: return_val = check_cart_constraints(param_dict['z_mode']["cart"], 'z_mode') if param_dict['z_mode'].get("rad") is not None: transform_dict = {'rad':{'cart': param_dict['z_mode']["rad"]}} cart_coord = self.transform_coordinates(transform_dict) return_val = check_cart_constraints(cart_coord, 'z_mode') if param_dict['z_mode'].get("deg") is not None: transform_dict = {'deg': {'cart': param_dict['z_mode']["deg"]}} cart_coord = self.transform_coordinates(transform_dict) return_val = check_cart_constraints(cart_coord, 'z_mode') else: self.log.warning("no valid key was provided, therefore nothing happened in function check_constraints.") return return_val def rho_pos_max(self, param_dict): """ Function that calculates the constraint for rho either given theta and phi values in degree or x, y and z in cartesian coordinates. @param dictionary param_dict: Has to be of the form {'rad': [rho, theta, phi]} supports also 'deg' and 'cart' option. @return float pos_max: the max position for given theta and phi values. Returns -1 in case of failure. """ # so I'm going to rework this function. The answer in the case # of z_mode is easy. (Max value for r is constant 3 True) # For the "normal_mode" I decided to come up with a new # algorithm. # That algorithm can be summarized as follows: # Check if the vector (r,theta,phi) # with length so that it is on the surface of the sphere. In case it conflicts with the # rectangular constraints given by the coils itself (x<=10, y<=10, z<=10) # we need to find the # intersection between the vector and the cube (Sadly this will need # 6 cases, just like a dice), else we are finished. pos_max_dict = {'rho': -1, 'theta': -1, 'phi': -1} pos_max_dict['phi'] = 2*np.pi param_dict = {self.mode: param_dict} if param_dict.get("z_mode") is not None: pos_max_dict['theta'] = np.pi*5/180 # 5° cone if self.check_constraints(param_dict): pos_max_dict['rho'] = self.z_constr else: pos_max_dict['rho'] = 0.0 elif param_dict.get("normal_mode") is not None: pos_max_dict['theta'] = np.pi if param_dict["normal_mode"].get("cart") is not None: transform_dict = {'cart': {'rad': param_dict["normal_mode"].get("cart")}} coord_dict_rad = self.transform_coordinates(transform_dict) coord_dict_rad = {'rad': coord_dict_rad} coord_dict_rad['rad'][0] = self.rho_constr transform_dict = {'rad': {'cart': coord_dict_rad['rad']}} coord_dict_cart = self.transform_coordinates(transform_dict) coord_dict_cart = {'normal_mode': {'cart': coord_dict_cart}} elif param_dict["normal_mode"].get("rad") is not None: # getting the coord list and transforming the coordinates to # cartesian, so cart_constraints can make use of it # setting the radial coordinate, as only the angular coordinates # are of importance and e.g. a zero in the radial component would be # To set it to rho_constr is also important, as it allows a check # if the sphere is the valid constraint in the current direction. coord_list = param_dict["normal_mode"]["rad"] coord_dict_rad = param_dict["normal_mode"] coord_dict_rad['rad'][0] = self.rho_constr transform_dict = {'rad': {'cart': coord_dict_rad['rad']}} coord_dict_cart = self.transform_coordinates(transform_dict) coord_dict_cart = {'normal_mode': {'cart': coord_dict_cart}} elif param_dict["normal_mode"].get("deg") is not None: coord_list = param_dict["normal_mode"]["deg"] coord_dict_deg = param_dict["normal_mode"] coord_dict_deg['deg'][0] = self.rho_constr coord_dict_rad = self.transform_coordinates({'deg': {'rad': coord_dict_deg['deg']}}) coord_dict_rad = {'rad': coord_dict_rad} transform_dict = {'rad': {'cart': coord_dict_rad['rad']}} coord_dict_cart = self.transform_coordinates(transform_dict) coord_dict_cart = {'normal_mode': {'cart': coord_dict_cart}} my_boolean = self.check_constraints(coord_dict_cart) if my_boolean: pos_max_dict['rho'] = self.rho_constr else: # now I need to find out, which plane I need to check phi = coord_dict_rad['rad'][2] theta = coord_dict_rad['rad'][1] # Sides of the rectangular intersecting with position vector if (np.pi/4 <= theta) and (theta < np.pi - np.pi/4): if (7*np.pi/4 < phi < 2*np.pi) or (0 <= phi <= np.pi/4): pos_max_dict['rho'] = self.x_constr/(np.cos(phi)*np.sin(theta)) elif (np.pi/4 < phi) and (phi <= 3*np.pi/4): pos_max_dict['rho'] = self.y_constr / (np.sin(phi)*np.sin(theta)) elif (3*np.pi/4 < phi) and (phi <= 5*np.pi/4): pos_max_dict['rho'] = -self.x_constr/(np.cos(phi)*np.sin(theta)) elif (5*np.pi/4 < phi) and (phi <= 7*np.pi/4): pos_max_dict['rho'] = -self.y_constr / (np.sin(phi)*np.sin(theta)) # Top and bottom of the rectangular elif (0 <= theta) and (theta < np.pi/4): pos_max_dict['rho'] = self.x_constr / np.cos(theta) elif (3*np.pi/4 <= theta) and (theta <= np.pi): pos_max_dict['rho'] = - self.x_constr / np.cos(theta) return pos_max_dict def update_coordinates(self, param_dict): """ A small helper function that does make the functions set_coordinates, transform_coordinates compatible with the interface defined functions. The problem is, that in the interface functions each coordinate is item to an key which represents the axes of the current coordinate system. This function only makes the set of coordinates complete. E.g {'rho': 1.3} to {'rho': 1.3, 'theta': np.pi/2, 'phi': 0 } @param param_dict: Contains the incomplete dictionary @return: the complete dictionary """ current_coord_dict = self.get_pos() for key in current_coord_dict.keys(): if param_dict.get(key) is None: param_dict[key] = current_coord_dict[key] return param_dict def set_magnet_idle_state(self, magnet_idle=True): """ Set the magnet to couple/decouple to/from the control. @param bool magnet_idle: if True then magnet will be set to idle and each movement command will be ignored from the hardware file. If False the magnet will react on movement changes of any kind. @return bool: the actual state which was set in the magnet hardware. True = idle, decoupled from control False = Not Idle, coupled to control """ pass def get_magnet_idle_state(self): """ Retrieve the current state of the magnet, whether it is idle or not. @return bool: the actual state which was set in the magnet hardware. True = idle, decoupled from control False = Not Idle, coupled to control """ pass<|fim▁end|>
"function for more information")
<|file_name|>pyRelocationObject.cpp<|end_file_name|><|fim▁begin|>/* Copyright 2017 - 2022 R. Thomas * Copyright 2017 - 2022 Quarkslab * * 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. */ #include <algorithm> #include <string> #include <sstream> #include "LIEF/MachO/hash.hpp" #include "LIEF/MachO/RelocationObject.hpp" #include "pyMachO.hpp" namespace LIEF { namespace MachO { template<class T> using getter_t = T (RelocationObject::*)(void) const; template<class T> using setter_t = void (RelocationObject::*)(T); template<> void create<RelocationObject>(py::module& m) {<|fim▁hole|> py::class_<RelocationObject, Relocation>(m, "RelocationObject", R"delim( Class that represents a relocation presents in the MachO object file (``.o``). Usually, this kind of relocation is found in the :class:`lief.MachO.Section`. )delim") .def_property("value", static_cast<getter_t<int32_t>>(&RelocationObject::value), static_cast<setter_t<int32_t>>(&RelocationObject::value), R"delim( For **scattered** relocations, the address of the relocatable expression for the item in the file that needs to be updated if the address is changed. For relocatable expressions with the difference of two section addresses, the address from which to subtract (in mathematical terms, the minuend) is contained in the first relocation entry and the address to subtract (the subtrahend) is contained in the second relocation entry.", )delim") .def_property_readonly("is_scattered", &RelocationObject::is_scattered, "``True`` if the relocation is a scattered one") .def("__eq__", &RelocationObject::operator==) .def("__ne__", &RelocationObject::operator!=) .def("__hash__", [] (const RelocationObject& relocation) { return Hash::hash(relocation); }) .def("__str__", [] (const RelocationObject& relocation) { std::ostringstream stream; stream << relocation; std::string str = stream.str(); return str; }); } } }<|fim▁end|>
<|file_name|>test_noise.py<|end_file_name|><|fim▁begin|>import pytest import numpy as np import noisily as ns # FIXME This has got to be an abuse of fixtures, right? @pytest.fixture(scope='module', params=[(1, 1), (37, 57), (128, 128)]) def indices2D(request): shape = request.param return np.transpose(np.indices(shape)) @pytest.fixture(scope='module', params=[(1, 1, 1), (29, 13, 31), (64, 64, 64)]) def indices3D(request): shape = request.param return np.transpose(np.indices(shape)) @pytest.fixture(scope='module', params=[(1, 1, 1, 1), (7, 11, 17, 13), (32, 32, 32, 32)]) def indices4D(request): shape = request.param return np.transpose(np.indices(shape)) @pytest.fixture(scope='module', params=[ns.perlin2D, ns.value2D, ns.open_simplex2D, ns.cell2D_range, ns.cell2D_range_inv, ns.cell2D_value, ns.cell2D_manhattan, ns.cell2D_manhattan_inv, ns.cell2D_manhattan_value]) def noise2D(request): return request.param @pytest.fixture(scope='module', params=[ns.perlin3D, ns.value3D, ns.open_simplex3D, ns.cell3D_range, ns.cell3D_range_inv, ns.cell3D_value, ns.cell3D_manhattan, ns.cell3D_manhattan_inv, ns.cell3D_manhattan_value]) def noise3D(request): return request.param @pytest.fixture(scope='module', params=[ns.perlin4D, ns.value4D, ns.open_simplex4D, ns.cell4D_range, ns.cell4D_range_inv, ns.cell4D_value, ns.cell4D_manhattan, ns.cell4D_manhattan_inv, ns.cell4D_manhattan_value]) def noise4D(request): return request.param @pytest.fixture(scope='module', params=[{'seed': 123}, {'period': 64}, {'seed': 12345, 'period': 16}]) def generator2D(request, noise2D): return ns.generator(noise2D, **request.param) @pytest.fixture(scope='module', params=[{'seed': 123}, {'period': 64}, {'seed': 12345, 'period': 16}]) def generator3D(request, noise3D): return ns.generator(noise3D, **request.param) @pytest.fixture(scope='module', params=[{'seed': 123}, {'period': 64}, {'seed': 12345, 'period': 16}]) def generator4D(request, noise4D): return ns.generator(noise4D, **request.param) def test_output2D(generator2D, indices2D): output = generator2D(indices2D) assert output.shape == indices2D.shape[:-1] assert output.size == indices2D.size // 2 assert np.array_equal(output, generator2D(indices2D)) <|fim▁hole|> assert output.shape == indices3D.shape[:-1] assert output.size == indices3D.size // 3 assert np.array_equal(output, generator3D(indices3D)) def test_output4D(generator4D, indices4D): output = generator4D(indices4D) assert output.shape == indices4D.shape[:-1] assert output.size == indices4D.size // 4 assert np.array_equal(output, generator4D(indices4D))<|fim▁end|>
def test_output3D(generator3D, indices3D): output = generator3D(indices3D)
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.contrib import admin from django.db import models class Band(models.Model): name = models.CharField(max_length=100) bio = models.TextField() rank = models.IntegerField() class Meta: ordering = ('name',) class Song(models.Model): band = models.ForeignKey(Band) name = models.CharField(max_length=100) duration = models.IntegerField() other_interpreters = models.ManyToManyField(Band, related_name='covers') class Meta: ordering = ('name',) class SongInlineDefaultOrdering(admin.StackedInline): model = Song class SongInlineNewOrdering(admin.StackedInline): model = Song ordering = ('duration', ) class DynOrderingBandAdmin(admin.ModelAdmin): <|fim▁hole|> else: return ['name']<|fim▁end|>
def get_ordering(self, request): if request.user.is_superuser: return ['rank']
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>import json import urllib import urllib2 from django.core.files import File from django.conf import settings from django.contrib.gis.geos import Point from .models import FloodMap, ReturnPeriod def get_geoserver_baseurl(): ''' Just input the layer name, height, width and boundarybox ''' url = settings.NOAH_GEOSERVER_URL + '?' url += urllib.urlencode({ 'request': 'GetMap', 'service': 'WMS', 'version': '1.1.1', 'srs': 'EPSG:4326', 'format': 'kml', }) return url<|fim▁hole|>def get_floodmap_kml_file(layers, bbox, height=720, width=330, styles=''): url = get_geoserver_baseurl() + '&' + urllib.urlencode({ 'layers': layers, 'styles': styles, 'height': height, 'width': width, 'bbox': bbox, }) data = urllib2.urlopen(url) path = 'uploads/floodmaps/{}.kml'.format(layers) print path with open(path, 'wb+') as destination: for chunk in data.chunks(): destination.write(chunk) print 'test' return destination def get_floodmap_instances(municipality): url = settings.NOAH_API_URL + 'flood_maps' data = urllib2.urlopen(url) data = data.read() events = json.loads(data) for event in events: return_period = event['verbose_name'] # Assuming that NOAH API uses 'N-Years' format in its verbose names return_period = int(return_period.split('-')[0]) floodmaps = event['flood'] for floodmap in floodmaps: flood_center = floodmap['center'] layer = floodmap['geoserver_layer'] flood_center = Point(flood_center['lng'], flood_center['lat']) print floodmap if municipality.geom.contains(flood_center): return_period, created = ReturnPeriod.objects.get_or_create(years=return_period) coords = municipality.geom.extent bbox = '' for coord in coords: bbox += (str(coord) + ',') bbox = bbox[:-1] print bbox map_kml = get_floodmap_kml_file(layer, bbox) try: fm = FloodMap.objects.get(municipality=municipality, return_period=return_period) except FloodMap.DoesNotExist: fm = FloodMap(municipality=municipality, return_period=return_period) fm.map_kml = map_kml fm.save()<|fim▁end|>
<|file_name|>test_mman.rs<|end_file_name|><|fim▁begin|>use nix::sys::mman::{mmap, MapFlags, ProtFlags}; #[test] fn test_mmap_anonymous() { unsafe { let ptr = mmap(std::ptr::null_mut(), 1, ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS, -1, 0) .unwrap() as *mut u8; assert_eq !(*ptr, 0x00u8); *ptr = 0xffu8; assert_eq !(*ptr, 0xffu8); } } #[test] #[cfg(any(target_os = "linux", target_os = "netbsd"))] fn test_mremap_grow() { use nix::sys::mman::{mremap, MRemapFlags}; use nix::libc::{c_void, size_t}; const ONE_K : size_t = 1024; let slice : &mut[u8] = unsafe { let mem = mmap(std::ptr::null_mut(), ONE_K, ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE, -1, 0) .unwrap(); std::slice::from_raw_parts_mut(mem as * mut u8, ONE_K) }; assert_eq !(slice[ONE_K - 1], 0x00); slice[ONE_K - 1] = 0xFF; assert_eq !(slice[ONE_K - 1], 0xFF); let slice : &mut[u8] = unsafe { #[cfg(target_os = "linux")] let mem = mremap(slice.as_mut_ptr() as * mut c_void, ONE_K, 10 * ONE_K, MRemapFlags::MREMAP_MAYMOVE, None) .unwrap(); #[cfg(target_os = "netbsd")] let mem = mremap(slice.as_mut_ptr() as * mut c_void, ONE_K, 10 * ONE_K, MRemapFlags::MAP_REMAPDUP, None) .unwrap(); std::slice::from_raw_parts_mut(mem as * mut u8, 10 * ONE_K) }; // The first KB should still have the old data in it. assert_eq !(slice[ONE_K - 1], 0xFF); // The additional range should be zero-init'd and accessible. assert_eq !(slice[10 * ONE_K - 1], 0x00); slice[10 * ONE_K - 1] = 0xFF; assert_eq !(slice[10 * ONE_K - 1], 0xFF); } #[test] #[cfg(any(target_os = "linux", target_os = "netbsd"))] // Segfaults for unknown reasons under QEMU for 32-bit targets #[cfg_attr(all(target_pointer_width = "32", qemu), ignore)] fn test_mremap_shrink() { use nix::sys::mman::{mremap, MRemapFlags}; use nix::libc::{c_void, size_t}; const ONE_K : size_t = 1024; let slice : &mut[u8] = unsafe { let mem = mmap(std::ptr::null_mut(), 10 * ONE_K, ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE, -1, 0) .unwrap(); std::slice::from_raw_parts_mut(mem as * mut u8, ONE_K) }; assert_eq !(slice[ONE_K - 1], 0x00); slice[ONE_K - 1] = 0xFF; assert_eq !(slice[ONE_K - 1], 0xFF); let slice : &mut[u8] = unsafe { let mem = mremap(slice.as_mut_ptr() as * mut c_void, 10 * ONE_K, ONE_K, MRemapFlags::empty(), None) .unwrap(); // Since we didn't supply MREMAP_MAYMOVE, the address should be the // same. assert_eq !(mem, slice.as_mut_ptr() as * mut c_void); std::slice::from_raw_parts_mut(mem as * mut u8, ONE_K)<|fim▁hole|> // The first KB should still be accessible and have the old data in it. assert_eq !(slice[ONE_K - 1], 0xFF); }<|fim▁end|>
};
<|file_name|>reflector.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use syntax::ext::base::ExtCtxt; use syntax::codemap::Span; use syntax::ptr::P; use syntax::ast::{Item, MetaItem}; use syntax::ast; use utils::match_ty_unwrap; pub fn expand_reflector(cx: &mut ExtCtxt, span: Span, _: &MetaItem, item: &Item, push: |P<Item>|) { if let ast::ItemStruct(ref def, _) = item.node { let struct_name = item.ident; // This path has to be hardcoded, unfortunately, since we can't resolve paths at expansion time match def.fields.iter().find(|f| match_ty_unwrap(&*f.node.ty, &["dom", "bindings", "utils", "Reflector"]).is_some()) { // If it has a field that is a Reflector, use that Some(f) => { let field_name = f.node.ident(); let impl_item = quote_item!(cx, impl ::dom::bindings::utils::Reflectable for $struct_name { fn reflector<'a>(&'a self) -> &'a ::dom::bindings::utils::Reflector { &self.$field_name } } ); impl_item.map(|it| push(it)) }, // Or just call it on the first field (supertype). None => { let field_name = def.fields[0].node.ident(); let impl_item = quote_item!(cx, impl ::dom::bindings::utils::Reflectable for $struct_name { fn reflector<'a>(&'a self) -> &'a ::dom::bindings::utils::Reflector { self.$field_name.reflector() }<|fim▁hole|> }; } else { cx.span_err(span, "#[dom_struct] seems to have been applied to a non-struct"); } }<|fim▁end|>
} ); impl_item.map(|it| push(it)) }
<|file_name|>platform.rs<|end_file_name|><|fim▁begin|>/* * Copyright 2017 Sreejith Krishnan R * * 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. */ use std::any::Any; use ::paint::{TextRuler, MathRuler}; use super::ruler::Ruler as SnapshotRuler; use super::canvas::Canvas; pub struct Platform { ruler: SnapshotRuler, } impl Platform { pub fn new(typeface: &str) -> Platform { Platform { ruler: SnapshotRuler::new(typeface, 0) } } pub fn new_canvas(&self, width: f32, height: f32) -> Canvas {<|fim▁hole|> } } impl ::platform::Platform for Platform { fn get_text_ruler(&self, size: f32) -> &TextRuler { self.ruler.set_size(size); &self.ruler } fn get_math_ruler(&self, size: f32) -> &MathRuler { self.ruler.set_size(size); &self.ruler } fn px_to_du(&self, px: f32) -> f32 { px } fn sp_to_du(&self, sp: f32) -> f32 { 64.*sp } fn dp_to_du(&self, dp: f32) -> f32 { 64.*dp } fn as_any(&self) -> &Any { self } }<|fim▁end|>
Canvas::new(width.max(1.), height.max(1.), self.ruler.get_sk_typeface())
<|file_name|>p2d.rs<|end_file_name|><|fim▁begin|>use super::vector::Vector; #[derive(Debug, Copy, Clone)] pub struct P2d(pub f32, pub f32); impl Vector for P2d { type Scalar = f32; fn new() -> Self { P2d(0.0, 0.0) } fn length_squared(&self) -> f32 { self.0 * self.0 + self.1 * self.1 } fn reset(&mut self) { self.0 = 0.0; self.1 = 0.0; } fn scale(&self, factor: f32) -> Self { P2d(self.0 * factor, self.1 * factor) } fn sub(&self, other: &Self) -> Self { P2d(self.0 - other.0, self.1 - other.1) } fn add_scaled(&mut self, factor: f32, other: &P2d) { self.0 += factor * other.0; self.1 += factor * other.1; } fn clip_within(&self, min: &Self, max: &Self) -> Self { P2d(if self.0 < min.0 { min.0<|fim▁hole|> max.0 } else { self.0 }, if self.1 < min.1 { min.1 } else if self.1 > max.1 { max.1 } else { self.1 }) } }<|fim▁end|>
} else if self.0 > max.0 {
<|file_name|>app.py<|end_file_name|><|fim▁begin|>from django.conf.urls import patterns, url from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.utils.decorators import method_decorator from ..core.app import SatchlessApp from . import models class OrderApp(SatchlessApp): app_name = 'order' namespace = 'order' order_model = models.Order order_details_templates = [ 'satchless/order/view.html', 'satchless/order/%(order_model)s/view.html'<|fim▁hole|> 'satchless/order/%(order_model)s/my_orders.html' ] @method_decorator(login_required) def index(self, request): orders = self.order_model.objects.filter(user=request.user) context = self.get_context_data(request, orders=orders) format_data = { 'order_model': self.order_model._meta.model_name } templates = [p % format_data for p in self.order_list_templates] return TemplateResponse(request, templates, context) def details(self, request, order_token): order = self.get_order(request, order_token=order_token) context = self.get_context_data(request, order=order) format_data = { 'order_model': order._meta.model_name } templates = [p % format_data for p in self.order_details_templates] return TemplateResponse(request, templates, context) def get_order(self, request, order_token): if request.user.is_authenticated(): orders = self.order_model.objects.filter(user=request.user) else: orders = self.order_model.objects.filter(user=None) order = get_object_or_404(orders, token=order_token) return order def get_urls(self, prefix=None): prefix = prefix or self.app_name return patterns('', url(r'^$', self.index, name='index'), url(r'^(?P<order_token>[0-9a-zA-Z]+)/$', self.details, name='details'), ) order_app = OrderApp()<|fim▁end|>
] order_list_templates = [ 'satchless/order/my_orders.html',
<|file_name|>kvstore.rs<|end_file_name|><|fim▁begin|>//! test was move from base (it could not compile in base since its trait just change //! (bidirectional dependency)) //! TODO seems pretty useless : remove?? use keyval::KeyVal; use node::{Node,NodeID}; use peer::{Peer,Shadow}; use std::cmp::Eq; use std::cmp::PartialEq; use keyval::{Attachment,SettableAttachment}; use rustc_serialize::{Encodable, Encoder, Decoder}; // Testing only nodeK, with key different from id #[derive(RustcDecodable,RustcEncodable,Debug,Clone)] struct NodeK2(Node,String); impl Eq for NodeK2 {} impl PartialEq<NodeK2> for NodeK2 { fn eq(&self, other: &NodeK2) -> bool { other.0 == self.0 && other.1 == self.1 } } impl KeyVal for NodeK2 { type Key = String; fn get_key(&self) -> NodeID { self.1.clone() } /* fn get_key_ref<'a>(&'a self) -> &'a NodeID { &self.1 }*/ noattachment!(); } impl SettableAttachment for NodeK2 { } impl Peer for NodeK2 { type Address = <Node as Peer>::Address; type Shadow = <Node as Peer>::Shadow; #[inline] fn get_address(&self) -> &<Node as Peer>::Address { self.0.get_address() } #[inline] fn get_shadower (&self, write : bool) -> Self::Shadow { self.0.get_shadower(write) } fn default_auth_mode(&self) -> <Self::Shadow as Shadow>::ShadowMode { self.0.default_auth_mode() } fn default_message_mode(&self) -> <Self::Shadow as Shadow>::ShadowMode { self.0.default_message_mode() } fn default_header_mode(&self) -> <Self::Shadow as Shadow>::ShadowMode { self.0.default_header_mode() <|fim▁hole|> }<|fim▁end|>
}
<|file_name|>plot.py<|end_file_name|><|fim▁begin|>import numpy as np import matplotlib.pyplot as plt b = map(int,open('data/dist_distances_enfermos_same_chr').readlines()) a = map(int,open('data/dist_distances_sanos_same_chr').readlines()) <|fim▁hole|>plt.show()<|fim▁end|>
plt.hist(b, bins=100, normed=0, alpha=0.5, label='enfermos') plt.hist(a, bins=100, normed=0, alpha=0.5, label='sanos') plt.legend(loc='upper right')
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
__version__ = "1.3.15"
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>#![allow(unused_imports)] //#![feature(optin_builtin_traits)] //#![feature(clone_from_slice)] //#![feature(question_mark)] //#[macro_use] extern crate gfx; extern crate dxsafe; extern crate env_logger; #[macro_use] extern crate lazy_static; extern crate libc; #[macro_use] extern crate log; extern crate winapi; //extern crate dxguid_sys; extern crate d3dcompiler as d3dcompiler_sys; extern crate dxgi as dxgi_sys; #[macro_use] extern crate failure; extern crate kernel32; extern crate user32; //extern crate d3d12 as d3d12_sys; // I moved this into winapi in my fork, but it expected to be so in winapi 0.3 extern crate cgmath; extern crate crossbeam; extern crate d2d1 as d2d1_sys; extern crate dwrite as dwrite_sys; extern crate getopts; extern crate itertools; extern crate nalgebra; extern crate ncollide; extern crate obj; extern crate rand; extern crate time; #[macro_use] mod macros; mod create_device; mod error_conversion; mod window; mod utils; //mod gfx_d3d12; mod shape_gen; mod dxsems; mod core; mod cubes; mod camera; //mod hvoxel; mod downsampler; mod tonemapper; mod plshadow; //mod collision; mod cubestate; mod light; //mod d2d1test; mod drawtext; mod skybox; mod seh; mod wmtext; mod ws; #[cfg(feature = "openal")] mod sound; #[cfg(not(feature = "openal"))] mod nosound; #[cfg(not(feature = "openal"))] use nosound as sound; use create_device::*; use cubes::CubeParms; use dxsafe::*; use failure::{err_msg, Error, ResultExt}; use error_conversion::ResultExtHr; use getopts::Options; use itertools::Itertools; use std::env; use std::cell::RefCell; use std::collections::HashMap; use std::io::Write; use std::process; use std::rc::Rc; use std::sync::{Arc, Mutex}; use std::time::Duration; use utils::*; use winapi::*; use window::*; const FRAME_COUNT: u32 = 3; fn parse_non_zero_u32(s: &str) -> Result<u32, Error> { let n = s.parse()?; if n > 0 { Ok(n) } else { Err(err_msg("number shouldn't be zero")) } } #[derive(Debug, Copy, Clone)] enum IncExc { Inc(f32), Exc(f32), } use IncExc::{Exc, Inc}; fn parse_f32_range(s: &str, mn: IncExc, mx: IncExc) -> Result<f32, Error> { let x = s.parse()?; let in_range = match (mn, mx) { (Inc(mn), Inc(mx)) => mn <= x && x <= mx, (Exc(mn), Inc(mx)) => mn < x && x <= mx, (Inc(mn), Exc(mx)) => mn <= x && x < mx, (Exc(mn), Exc(mx)) => mn < x && x < mx, }; if in_range { Ok(x) } else { Err(err_msg(format!( "number {} not in range {:?} .. {:?}", x, mn, mx ))) } } fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} [0] [1] [N] [options]", program); print!("{}", opts.usage(&brief)); } fn main() { match mainr() { Err(err) => { for c in err.causes() { println!("{}", c); } //println!("{}", err.backtrace()); process::exit(101); } _ => (), } } fn mainr() -> Result<(), Error> { // install SEH guard to continue on continuable structured exception let _seh_guard = seh::SehGuard::new(); // install ctrl-C handler to shutdown gracefully seh::install_ctrl_c_handler(); // Initialize logger env_logger::init().unwrap(); println!("sound::init()"); sound::init(); // Set default values of cubes module parameters let mut parms = CubeParms { thread_count: 2, object_count: 2_000, backbuffer_count: FRAME_COUNT, speed_mult: 1.0, concurrent_state_update: true, // unused debug_layer: cfg!(debug_assertions), rt_format: DXGI_FORMAT_R16G16B16A16_FLOAT, enable_srgb: false, render_trace: false, fovy_deg: 60., render_text: true, }; let mut adapters_to_test = vec![]; let mut adapters_info = false; let program_name = env::args().next().unwrap().clone(); let mut opts = Options::new(); opts.optflag("h", "help", "Usage"); opts.optflag("i", "info", "Adapters information"); opts.optflag("", "f32-color", "Render using R32G32B32_FLOAT"); opts.optflag("d", "debug", "Enable debug layer"); opts.optflag("", "nodebug", "Disable debug layer"); opts.optflag("", "notext", "Disable DWrite text output"); opts.optflag("", "trace", "Enable logging in render cycle"); opts.optflag( "", "srgb", "Pretend that backbuffer uses sRGB (doesn't seem to affect anything)", ); opts.optopt("o", "objects", "Number of cubes", "NUM"); opts.optopt("t", "", "Number of state update threads", "NUM"); opts.optopt("b", "", "Number of backbuffers", "NUM"); opts.optopt("s", "", "Time speed multiplier", "FLOAT"); opts.optopt("", "fov", "Vertical FOV", "FLOAT"); let ms = opts.parse(env::args().skip(1))?; // help if ms.opt_present("h") { print_usage(&program_name, opts); return Ok(()); }; // adapters to use for anum in &ms.free { let n = anum.parse::<u32>() .with_context(|_| format!("Unrecognized command line argument \"{}\"", anum))?; adapters_to_test.push(n); } // adapters info if ms.opt_present("i") { adapters_info = true; }; // use f32 color if ms.opt_present("f32-color") { parms.rt_format = DXGI_FORMAT_R32G32B32A32_FLOAT; }; // enable sRGB if ms.opt_present("srgb") { parms.enable_srgb = true; }; if ms.opt_present("d") { parms.debug_layer = true; }; if ms.opt_present("nodebug") { parms.debug_layer = false; }; if ms.opt_present("notext") { parms.render_text = false; }; if ms.opt_present("trace") { parms.render_trace = true; }; // object count if let Some(num) = ms.opt_str("o") { parms.object_count = parse_non_zero_u32(&num).with_context(|_| { format!( "Object count in -o should be positive non-zero integer, not '{}'", num ) })?; }; if let Some(num) = ms.opt_str("t") { parms.thread_count = parse_non_zero_u32(&num).with_context(|_| { format!( "Thread count in -t should be positive non-zero integer, not '{}'", num ) })?; }; if let Some(num) = ms.opt_str("b") { parms.backbuffer_count = parse_non_zero_u32(&num).with_context(|_| { format!( "Backbuffer count in -b should be positive non-zero integer, not '{}'", num ) })?; }; if let Some(num) = ms.opt_str("s") { parms.speed_mult = parse_f32_range(&num, Inc(0.), Inc(::std::f32::INFINITY)) .with_context(|_| { format!( "Time speed multiplier in -s should be non-negative floating number, not '{}'", num ) })?; }; if let Some(num) = ms.opt_str("fov") { parms.fovy_deg = parse_f32_range(&num, Exc(0.), Exc(180.)).with_context(|_| { format!( "FOV in --fov should be floating number in (0., 180.) range, not '{}'", num ) })?; }; let factory: DXGIFactory4 = match create_dxgi_factory2(parms.debug_layer) { Ok(fact) => fact, Err(hr) => bail!("Cannot create DXGIFactory4 (0x{:x}). No can do. {}", hr, utils::hr2msg(hr)), }; let mut adapters = vec![]; // Iterate over available GPUs for (i, adapter) in &factory { let descr = adapter.get_desc1().unwrap(); println!( "Adapter {}: {}", i, wchar_array_to_string_lossy(&descr.Description) ); println!( " Dedicated video memory: {}MiB", descr.DedicatedVideoMemory / 1024 / 1024 ); if adapters_to_test.is_empty() || adapters_to_test[..].contains(&i) { // If there's no numbers in command line add each and every available adapter, // otherwise use adapter numbers from command line if adapters_info { print_adapter_info(&adapter); } adapters.push(adapter); } } if adapters_info { return Ok(()); } // I used this mutex to sync console output. let mutex = Arc::new(Mutex::new(())); crossbeam::scope(|scope| { //// d2d1 test window // scope.spawn(|| { // if let Err(err) = d2d1test::main() { // error!("d2d1test::main() error 0x{:x}", err); // } // }); for (id, a) in adapters.into_iter().enumerate() { let mutex = mutex.clone(); let parms = &parms; let dxgi_factory = factory.clone(); scope.spawn(move || { // Spawn a thread for each adapter match main_prime(id, dxgi_factory, a, mutex, parms) { Err(err) => { let stdout = ::std::io::stdout(); let mut handle = stdout.lock(); for c in err.causes() { let _ = writeln!(handle, "{}", c); } } _ => (), } }); } }); seh::uninstall_ctrl_c_handler(); Ok(()) } <|fim▁hole|> if let Ok(data) = dev.check_feature_support_virtual_address() { println!(" {:#?}", data); } if let Ok(data) = dev.check_feature_support_options() { println!(" {:#?}", data); } let rdesc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE1D, Alignment: 0, Width: 1024, Height: 1, DepthOrArraySize: 1, MipLevels: 10, Format: DXGI_FORMAT_R32G32B32A32_FLOAT, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, Flags: D3D12_RESOURCE_FLAG_NONE, }; let rai = dev.get_resource_allocation_info(0, &[rdesc]); println!(" {:#?}", rai); } } const VK_A: i32 = b'A' as i32; const VK_S: i32 = b'S' as i32; const VK_D: i32 = b'D' as i32; const VK_F: i32 = b'F' as i32; const VK_Q: i32 = b'Q' as i32; const VK_W: i32 = b'W' as i32; const VK_E: i32 = b'E' as i32; const VK_R: i32 = b'R' as i32; const VK_P: i32 = b'P' as i32; const KEYS_LEN: usize = 256; struct KeyState { keys: [bool; KEYS_LEN], } impl KeyState { pub fn set(&mut self, vk: i32) { if vk >= 0 && vk < self.keys.len() as i32 { self.keys[vk as usize] = true; } } pub fn unset(&mut self, vk: i32) { if vk >= 0 && vk < self.keys.len() as i32 { self.keys[vk as usize] = false; } } pub fn pressed(&self, vk: i32) -> bool { if vk >= 0 && vk < self.keys.len() as i32 { self.keys[vk as usize] } else { false } } } impl Default for KeyState { fn default() -> KeyState { KeyState { keys: [false; KEYS_LEN], } } } fn main_prime( id: usize, dxgi_factory: DXGIFactory4, adapter: DXGIAdapter1, _mutex: Arc<Mutex<()>>, parms: &CubeParms, ) -> Result<(), Error> { // Setup window. Currently window module supports only one window per thread. let descr = wchar_array_to_string_lossy(&adapter.get_desc1().into_error_context("Cannot get adapter description")?.Description); let title = format!("D3D12 Hello, rusty world! ({})", descr); let wnd = create_window(&title, 512, 256); let mut fps = 0.0; // Initialization of cubes module data required to render all stuff let data = RefCell::new( cubes::AppData::on_init(&wnd, &dxgi_factory, &adapter, parms) .with_context(|_| format!("Adapter '{}' failed initialization", descr))?); // x and y store last mouse coords from WM_MOUSEMOVE let mut x: i32 = 0; let mut y: i32 = 0; let mut keys = KeyState::default(); // state of left mouse button let mut mouse_down = false; let mut pause = false; // Profiling stuff let mut start = time::precise_time_s(); let mut prev_frame_time = time::precise_time_s(); // Window::poll_events() returns non-blocking iterator, which returns Option<MSG> for mmsg in wnd.poll_events() { // "if let Some(msg)" extracts msg from mmsg // if mmsg is None, then 'else' branch is taken if let Some(msg) = mmsg { //trace!("{:?} {} {:x} {:x}", msg.time, wmtext::wm_str(msg.message), msg.wParam, msg.lParam); // Instead of passing messages into cubes module, I process them here // It is not well-thought-out design decision, it's just slightly simpler now, and cost of changing it is low. match msg.message { // Usual message processing stuff WM_SIZE => { // Normally this message goes to wndproc, in window.rs I repost it into message queue to prevent reentrancy problems debug!("WM_SIZE {}, {} ", msg.wParam, msg.lParam); data.borrow_mut().on_resize( LOWORD(msg.lParam as u32) as u32, HIWORD(msg.lParam as u32) as u32, msg.wParam as u32, ); } WM_MOUSEMOVE => { let x1 = GET_X_LPARAM(msg.lParam) as i32; let y1 = GET_Y_LPARAM(msg.lParam) as i32; let (dx, dy) = (x1 - x, y - y1); x = x1; y = y1; if mouse_down { let mut data = data.borrow_mut(); let camera = data.camera(); let fov = camera.fov(); camera.roty(dy as f32 * fov / 300.); camera.rotx(-dx as f32 * fov / 300.); } } WM_MOUSEWHEEL => { let dz = (GET_WHEEL_DELTA_WPARAM(msg.wParam) as f32) / (WHEEL_DELTA as f32); let mut data = data.borrow_mut(); let camera = data.camera(); let mut vfov = camera.fov(); if vfov < 5.0 { vfov -= dz * 0.2; } else { vfov -= dz * 2.0; }; vfov = f32::max(vfov, 0.2); vfov = f32::min(vfov, 120.); camera.set_fov(vfov); } WM_KEYDOWN => { keys.set(msg.wParam as i32); } WM_KEYUP => { let vk = msg.wParam as i32; keys.unset(vk); if vk == VK_P { pause = !pause; }; } WM_LBUTTONDOWN => { mouse_down = true; set_capture(wnd.get_hwnd()); } WM_LBUTTONUP => { mouse_down = false; release_capture(); } _ => {} }; } else { // There's no pending window message. let do_not_render = data.borrow().is_minimized(); if do_not_render { // MSDN suggest to use MsgWaitForMultipleObjects here, but 10ms sleep shouldn't create problems std::thread::sleep(Duration::from_millis(10)); } else { let cur_frame_time = time::precise_time_s(); let frame_dt = cur_frame_time - prev_frame_time; prev_frame_time = cur_frame_time; // data is Rc<RefCell<cubes::AppData>> // Rc is not really needed. I didn't pass it around. // Take a mutable reference to cubes::AppData let mut data = data.borrow_mut(); { // Process WASD keys let camera = data.camera(); camera.restore_up((180. * frame_dt) as f32); let step = match (keys.pressed(VK_SHIFT), keys.pressed(VK_CONTROL)) { (false, false) => 0.1, (true, false) => 1.0, (false, true) => 0.01, (true, true) => 0.001, }; if keys.pressed(VK_W) { camera.go(step, 0., 0.); }; if keys.pressed(VK_S) { camera.go(-step, 0., 0.); }; if keys.pressed(VK_A) { camera.go(0., -step, 0.); }; if keys.pressed(VK_D) { camera.go(0., step, 0.); }; if keys.pressed(VK_R) { camera.go(0., 0., step); }; if keys.pressed(VK_F) { camera.go(0., 0., -step); }; // Process Q and E keys. They control camera's roll if keys.pressed(VK_Q) { camera.rotz(-step); }; if keys.pressed(VK_E) { camera.rotz(step); }; } // For this simple program I don't separate update and render steps. // State change and rendering is done inside on_render. ::perf_start("total"); let render_dt = if frame_dt > 0.1 { 0.1 } else { frame_dt as f32 }; data.on_render(pause, fps, render_dt)?; ::perf_end("total"); // register rendered frame in performance collector ::perf_frame(); // fps counting stuff let now = time::precise_time_s(); let frames = PERFDATA.with(|p_data| p_data.borrow().frames); if frames > 0 && now < start || now >= (start + 1.0) { // Once per second show stats print!("Adapter {} FPS: {:4}", id, frames); fps = frames as f32; PERFDATA.with(|p_data| { let p_data = p_data.borrow(); let frames = p_data.frames as f64; for (&pname, val) in p_data .perf .iter() .sorted_by(|&(&n1, _), &(&n2, _)| n1.cmp(n2)) { print!(" {}:{:.2}", pname, val * 1000. / frames); } println!(""); }); let _ = ::std::io::Write::flush(&mut ::std::io::stdout()); perf_reset(); start = now; } // stats } // do not render } // no window message if seh::ctrl_c_is_triggered() { break; }; } // message loop // Application should exit fullscreen state before terminating. data.borrow() .set_fullscreen(false) .expect("Cannot exit fullscreen mode"); // wait for all GPU processing to stop data.borrow().wait_frame(); // Save info_queue before final release of resources let maybe_iq = data.borrow_mut().take_info_queue(); // release resources drop(data); // Let debug layer say its last words if let Some(iq) = maybe_iq { core::dump_info_queue(&iq); }; Ok(()) } // Simple render statistics collector pub struct PerfData { frames: u64, perf: HashMap<&'static str, f64>, } impl PerfData { fn new() -> PerfData { PerfData { frames: 0, perf: HashMap::new(), } } } thread_local!(static PERFDATA: RefCell<PerfData> = RefCell::new(PerfData::new())); pub fn perf_frame() { PERFDATA.with(|pd| { pd.borrow_mut().frames += 1; }); } pub fn perf_reset() { PERFDATA.with(|pd| { let mut pd = pd.borrow_mut(); *pd = PerfData::new(); }); } pub fn perf_start(name: &'static str) { PERFDATA.with(|pd| { *pd.borrow_mut().perf.entry(name).or_insert(0.) -= time::precise_time_s(); }); } pub fn perf_end(name: &'static str) { PERFDATA.with(|pd| { *pd.borrow_mut().perf.get_mut(name).unwrap() += time::precise_time_s(); }); } pub fn perf_clear_start() { perf_start("clear"); } pub fn perf_clear_end() { perf_end("clear"); } pub fn perf_fillbuf_start() { perf_start("fillbuf"); } pub fn perf_fillbuf_end() { perf_end("fillbuf"); } pub fn perf_exec_start() { perf_start("exec"); } pub fn perf_exec_end() { perf_end("exec"); } pub fn perf_present_start() { perf_start("present"); } pub fn perf_present_end() { perf_end("present"); } pub fn perf_wait_start() { perf_start("wait"); } pub fn perf_wait_end() { perf_end("wait"); }<|fim▁end|>
fn print_adapter_info(adapter: &DXGIAdapter1) { if let Ok(dev) = d3d12_create_device(Some(adapter), D3D_FEATURE_LEVEL_11_0) {
<|file_name|>socket_mw.py<|end_file_name|><|fim▁begin|>import logging; logger = logging.getLogger("morse." + __name__) import socket import select import json import morse.core.middleware from functools import partial from morse.core import services class MorseSocketServ: def __init__(self, port, component_name): # List of socket clients self._client_sockets = [] self._message_size = 1024 self._component_name = component_name self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self._server.bind((str(socket.INADDR_ANY), port)) self._server.listen(1) logger.info("Socket Mw Server now listening on port " + str(port) + \ " for component " + str(component_name) + ".") def __del__(self): """ Terminate the ports used to accept requests """ if self._client_sockets: logger.info("Closing client sockets...") for s in self._client_sockets: s.close() if self._server: logger.info("Shutting down connections to server...") self._server.shutdown(socket.SHUT_RDWR) logger.info("Closing socket server...") self._server.close() del self._server def main_export(self, encode, component_instance): sockets = self._client_sockets + [self._server] try: inputready, outputready, exceptready = select.select(sockets, sockets, [], 0) except select.error: pass except socket.error: pass if self._server in inputready: sock, addr = self._server.accept() self._client_sockets.append(sock) if outputready != []: message = encode(component_instance) for o in outputready: try: o.send(message) except socket.error: self.close_socket(o) def main_read(self, decode, component_instance): sockets = self._client_sockets + [self._server] try: inputready, outputready, exceptready = select.select(sockets, [], [], 0) except select.error: pass except socket.error: pass for i in inputready: if i == self._server: sock, addr = self._server.accept() if self._client_sockets != []: logger.warning("More than one clients for an actuator!!") self._client_sockets.append(sock) else: try: msg = i.recv(self._message_size) logger.debug("received msg %s" % msg) if msg == b'': self.close_socket(i) else: component_instance.local_data = decode(msg) except socket.error as detail: self.close_socket(i) def close_socket(self, sock): self._client_sockets.remove(sock) try: sock.close() except socket.error as error_info: logger.warning("Socket error catched while closing: " + str(error_info)) class MorseSocketClass(morse.core.middleware.MorseMiddlewareClass): """ External communication using sockets. """ def __init__(self): """ Initialize the socket connections """ # Call the constructor of the parent class super(self.__class__,self).__init__() # port -> MorseSocketServ self._server_dict = {} # component name (string) -> Port (int) self._component_nameservice = {} self._base_port = 60000 # Register two special services in the socket service manager: # TODO To use a new special component instead of 'simulation', # uncomment the line :-) # bge.logic.morse_services.register_request_manager_mapping("streams", "SocketRequestManager") services.do_service_registration(self.list_streams, 'simulation') services.do_service_registration(self.get_stream_port, 'simulation') services.do_service_registration(self.get_all_stream_ports, 'simulation') def list_streams(self): """ List all publish streams. """ return list(self._component_nameservice.keys()) def get_stream_port(self, name): """ Get stream port for stream name. """ port = -1 try: port = self._component_nameservice[name] except KeyError: pass return port def get_all_stream_ports(self): """ Get stream ports for all streams. """ return self._component_nameservice def register_component(self, component_name, component_instance, mw_data): """ Open the port used to communicate by the specified component. """ # Create a socket server for this component serv = MorseSocketServ(self._base_port, component_name) self._server_dict[self._base_port] = serv self._component_nameservice[component_name] = self._base_port self._base_port = self._base_port + 1 # Extract the information for this middleware # This will be tailored for each middleware according to its needs function_name = mw_data[1] fun = self._check_function_exists(function_name) if fun != None: # Choose what to do, depending on the function being used<|fim▁hole|> elif function_name == "post_message": component_instance.output_functions.append(partial(MorseSocketServ.main_export, serv, fun)) # If the function is external and has already been loaded before else: # Pass by mw_data the generated server mw_data.append(serv) self._add_method(mw_data, component_instance) else: # Pass by mw_data the generated server mw_data.append(serv) self._add_method(mw_data, component_instance) def post_message(self, component_instance): return (json.dumps(component_instance.local_data) + '\n').encode() def read_message(self, msg): return json.loads(msg.decode('utf-8')) def print_open_sockets(self): """ Display a list of all currently opened sockets.""" logger.info("Socket Mid: Currently opened sockets:") for name, socket in self._socket_dict.iteritems(): logger.info(" - Port name '{0}' = '{1}'".format(name, socket))<|fim▁end|>
# Data read functions if function_name == "read_message": component_instance.input_functions.append(partial(MorseSocketServ.main_read, serv, fun)) # Data write functions
<|file_name|>edge-inspect-api-1.0.0.js<|end_file_name|><|fim▁begin|>/************************************************************************* Copyright (c) 20136 Adobe Systems Incorporated. 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. **************************************************************************/ /*jslint node:true, bitwise:true */ /*global localStorage, Crypto, EdgeInspectGlobals:true, Uint8Array, WebSocket, Window */ /* runInBrowserMode: defaults to false, assuming that you are running this in Node. If you are running this in node, it will attempt to require the following libraries for you: - ws - node-localstorage - cryptojs If you are running this in a browser, you will also need to include the third-party Crypto-JS v2.5.3 library */ var runInBrowserMode = false; (function (that) { 'use strict'; if (that.window !== undefined) { runInBrowserMode = that instanceof Window; } }(this)); EdgeInspectGlobals = {}; EdgeInspectGlobals.StorageManager = function (localStorage) { 'use strict'; var my = {}; // localStorage only holds strings. my.get = function (key) { return localStorage.getItem(key); }; my.put = function (key, value) { return localStorage.setItem(key, value); }; my.clear = function (key) { return localStorage.removeItem(key); }; my.log = function (message) { if (typeof message !== 'string') { // Anything but a string gets kicked back return false; } var log, unpacked; try { // Unpack the message, in case we have to scrub data unpacked = JSON.parse(message); } catch (ex) { // Can't parse the JSON, it's an error; return false; } if (unpacked.payload && unpacked.payload.action === "publish") { unpacked.payload.options.message.options.url = "***scrubbed***"; message = JSON.stringify(unpacked); } else if (unpacked.payload && unpacked.payload.options.rand) { delete unpacked.payload.options.rand; message = JSON.stringify(unpacked); } log = my.get("log"); if (log === null) { // This is an empty object log = []; } else { log = JSON.parse(log); } if (log.length > 1000) { log.shift(); } log.push(message); my.put("log", JSON.stringify(log)); return JSON.stringify(log); }; my.destroySavedSettings = function () { var i; for (i = 0; i < localStorage.length; i += 1) { localStorage.removeItem(localStorage.key(i)); } }; return my; }; EdgeInspectGlobals.CryptoHandler = function (Crypto) { 'use strict'; var my = {}, salt, passcode, keyAsBytes, keyAsHex, challenge; function calculateKey(asBytes) { if (typeof asBytes === 'undefined') { asBytes = false; } var result = Crypto.PBKDF2(passcode, salt, 32, { iterations: 1000, asBytes: asBytes}); return result; } function encryptAsBytes(plaintext) { return Crypto.util.base64ToBytes(Crypto.AES.encrypt(plaintext, keyAsBytes, { mode: new Crypto.mode.CBC(Crypto.pad.pkcs7) })); } function encryptAsHex(plaintext) { return Crypto.util.bytesToHex(encryptAsBytes(plaintext)); } function decryptAsBytes(encrypted) { return (Crypto.AES.decrypt(Crypto.util.bytesToBase64(encrypted), keyAsBytes, { mode: new Crypto.mode.CBC(Crypto.pad.pkcs7), asBytes: true })); } function decryptAsHex(encrypted) { return decryptAsBytes(Crypto.util.hexToBytes(encrypted)); } my.verify = function () { try { if (Crypto.MD5('test') === '098f6bcd4621d373cade4e832627b4f6') { return true; } else { return false; } } catch (ex) { return false; } }; my.configure = function (parameters) { if (parameters.encryptionkey) { challenge = my.getRandomString(); keyAsHex = parameters.encryptionkey; keyAsBytes = Crypto.util.hexToBytes(parameters.encryptionkey); } else { salt = parameters.salt; passcode = parameters.passcode; challenge = my.getRandomString(); keyAsHex = calculateKey(false); keyAsBytes = calculateKey(true); } }; my.getRandomString = function () { return Crypto.util.bytesToHex(Crypto.util.randomBytes(16)); }; my.getChallengeString = function () { return challenge; }; my.getKeyAsHex = function () { return keyAsHex; }; my.verifyChallenge = function (candidate) { var unpacked, mine, yours; try { unpacked = Crypto.util.bytesToHex(decryptAsHex(candidate)); mine = unpacked.substring(0, 32); yours = unpacked.substring(32, 64); } catch (ex) { // Cannot Decrypt return false; } if (mine === challenge) { return encryptAsHex(Crypto.util.hexToBytes((yours + my.getRandomString()))); } else { // rand mismatch return false; } }; my.decryptMessageFromDM = function (encrypted) { try { return JSON.parse(Crypto.charenc.UTF8.bytesToString(decryptAsBytes(new Uint8Array(encrypted)))); } catch (ex) { return false; } }; my.encryptMessageForDM = function (plaintext) { return encryptAsBytes(plaintext); }; return my; }; EdgeInspectGlobals.MessageFormatter = function (CryptoHandler) { 'use strict'; var my = {}, uuid, inspectionUrl, clientName = 'unset client name', mergeObjects, createAdminMessage, createDeviceMessage, createInventoryMessage, createPreferencesMessage, createBasicMessage, createPingMessage, actionMap; my.configure = function (parameters) { uuid = parameters.uuid; inspectionUrl = parameters.inspectionUrl; clientName = parameters.clientName; }; mergeObjects = (function () { return function (object, retval) { var i; for (i in object) { if (object.hasOwnProperty(i)) { if (typeof object[i] === 'string' || object[i] === null) { // This allows us to overload existing parameters if (!retval[i]) { retval[i] = object[i]; } } else { if (typeof retval[i] === 'undefined') { retval[i] = {}; } retval[i] = mergeObjects(object[i], retval[i]); } } } return retval; }; }()); createAdminMessage = (function () { return function (parameters) { var basicMessage = { options: { name: clientName, type: "administrator", id: uuid, rand: CryptoHandler.getChallengeString() }, source: uuid }; return JSON.stringify(mergeObjects(basicMessage, parameters)); }; }()); createInventoryMessage = (function () { return function (parameters) { if (typeof parameters.deviceids === 'string') { parameters.deviceids = [parameters.deviceids]; } var basicMessage = { action: 'inventory', options: { random: CryptoHandler.getRandomString() }, source: uuid }, wrappedParameters = {action: 'inventory', options: parameters }; return JSON.stringify(mergeObjects(basicMessage, wrappedParameters)); }; }()); createDeviceMessage = (function () { return function (parameters) { var basicMessage = { action: 'publish', options: { message: { source: uuid, options: { } }, random: CryptoHandler.getRandomString(), destinations: [] }, source: uuid }, wrappedParameters = {action: 'publish', options: parameters }; return JSON.stringify(mergeObjects(basicMessage, wrappedParameters)); }; }()); createPingMessage = (function () { return function () { return { action: 'ping', source: uuid, options: { random: CryptoHandler.getRandomString() } }; }; }()); createPreferencesMessage = (function () { return function (parameters) { var basicMessage = { action: 'preferences', options: { random: CryptoHandler.getRandomString() }, source: uuid }, wrappedParameters = {action: 'preferences', options: parameters }; return JSON.stringify(mergeObjects(basicMessage, wrappedParameters)); }; }()); createBasicMessage = (function () { return function (parameters) { var basicMessage = { options: { random: CryptoHandler.getRandomString() }, source: uuid }; return JSON.stringify(mergeObjects(basicMessage, parameters)); }; }()); my.basic = function (parameters) { return createAdminMessage(parameters); }; my.pairFirst = function () { var parameters = { action: 'pair', options: { passcode: CryptoHandler.getKeyAsHex() } }; return createAdminMessage(parameters); }; my.pair = function () { var parameters = { action: 'pair' }; return createAdminMessage(parameters); }; my.ping = function () { return createPingMessage(); }; my.connect = function (verified) { var parameters = { action: 'connect', options: { challenge: verified } }; return createAdminMessage(parameters); }; my.inventory = function (status) { var parameters = { subaction: 'listresources', status: status, type: 'device' }; return createInventoryMessage(parameters); }; my.passcode = function (passcode, deviceid) { var parameters = { subaction: 'passcode_response', passcode: passcode, id: deviceid }; return createInventoryMessage(parameters); }; my.eject = function (devices) { var parameters = { subaction: 'eject_device', deviceids: devices }; return createInventoryMessage(parameters); }; my.forget = function (devices) { var parameters = { subaction: 'forget_device', deviceids: devices }; return createInventoryMessage(parameters); }; <|fim▁hole|> }; return createInventoryMessage(parameters); }; my.hostinfo = function () { var parameters = { subaction: 'get_manager_info' }; return createInventoryMessage(parameters); }; my.browse = function (url, devices, fullscreen) { var parameters = { message: { action: 'browser_navigate', options: { url: url, fullscreen: fullscreen } }, destinations: devices }; return createDeviceMessage(parameters); }; my.inspect = function (url, devices, fullscreen) { var parameters = { message: { action: 'browser_navigate', options: { url: url, remoteinspect: inspectionUrl, fullscreen: fullscreen } }, destinations: devices }; return createDeviceMessage(parameters); }; my.screenshot = function (requestId, fullPage, dualOrientation, devices) { var parameters = { message: { action: 'screenshot_request', options: { request_id: requestId, full_page: fullPage, dual_orientation: dualOrientation } }, destinations: devices }; return createDeviceMessage(parameters); }; my.refresh = function (requestId, devices) { var parameters = { message: { action: 'force_refresh', options: { request_id: requestId } }, destinations: devices }; return createDeviceMessage(parameters); }; my.cancelScreenshot = function (requestId, devices) { var parameters = { message: { action: 'transfer_cancel', options: { request_id: requestId } }, destinations: devices }; return createDeviceMessage(parameters); }; my.showChrome = function (requestId, devices) { var parameters = { message: { action: 'show_chrome', options: { request_id: requestId } }, destinations: devices }; return createDeviceMessage(parameters); }; my.hideChrome = function (requestId, devices) { var parameters = { message: { action: 'full_screen', options: { request_id: requestId } }, destinations: devices }; return createDeviceMessage(parameters); }; my.preferences = function (action, prefs) { var parameters = { subaction: action }; if (typeof prefs !== 'undefined') { parameters.prefs = prefs; } return createPreferencesMessage(parameters); }; my.basic = function (action) { var parameters = { action: action }; return createBasicMessage(parameters); }; return my; }; EdgeInspectGlobals.MessageParser = function (StorageManager, CryptoHandler) { 'use strict'; var my = {}; my.parse = function (message) { var parsed; if (typeof message.data === 'string') { try { parsed = JSON.parse(message.data); } catch (ex) { StorageManager.log(JSON.stringify('MessageParser Error (Not Valid JSON): ' + message.data)); return false; } } else { parsed = CryptoHandler.decryptMessageFromDM(message.data); } if (parsed === false) { StorageManager.log(JSON.stringify('MessageParser Error (Could Not Decrypt): ' + message.data)); return false; } if (parsed.action !== 'pong') { if (parsed.options) { delete parsed.options.random; } StorageManager.log(JSON.stringify(parsed)); return parsed; } else { return false; } }; return my; }; EdgeInspectGlobals.ConnectionManager = function (WebSocket, StorageManager) { 'use strict'; var my = { isConnected: false }, handle, subscribers = {}, connectionData = {}, isConnecting = false, defaultConnectionData = { protocol: 'ws', host: '127.0.0.1', port: '7682' }; function performFirstRunCheck() { if (StorageManager.get('protocol') === null || StorageManager.get('host') === null || StorageManager.get('port') === null) { StorageManager.put('protocol', defaultConnectionData.protocol); StorageManager.put('host', defaultConnectionData.host); StorageManager.put('port', defaultConnectionData.port); } } function loadConnectionSettings() { connectionData.protocol = StorageManager.get('protocol'); connectionData.host = StorageManager.get('host'); connectionData.port = StorageManager.get('port'); } function publish(name, data) { var i; if (typeof subscribers[name] !== 'undefined') { for (i = 0; i < subscribers[name].length; i += 1) { subscribers[name][i](data); } } } my.subscribe = function (name, handler) { if (typeof subscribers[name] === 'undefined') { subscribers[name] = []; } subscribers[name].push(handler); }; my.connect = function () { if (!isConnecting) { isConnecting = true; loadConnectionSettings(); handle = new WebSocket(connectionData.protocol + "://" + connectionData.host + ":" + connectionData.port + "/shadow"); handle.binaryType = 'arraybuffer'; handle.onopen = function (ev) { my.isConnected = true; isConnecting = false; publish('connect'); }; handle.onclose = function (ev) { my.isConnected = false; isConnecting = false; publish('disconnect', ev); }; handle.onmessage = function (ev) { // Call out to a browser specific function publish('message', ev); }; handle.onerror = function (ev) { // Call out to a browser specific function publish('error', ev); }; } }; my.disconnect = function () { handle.close(1000, "All Done"); }; my.send = function (message) { var bufferedMessage; if (my.isConnected) { if (Array.isArray(message)) { if (runInBrowserMode) { // Convert array of binary into a typed array and send the buffer return handle.send(new Uint8Array(message).buffer); } else { // Expects node is using an instance of ws for WebSockets return handle.send(message, {mask: false, binary: true}); } } else { return handle.send(message); } } }; my.configure = function () { performFirstRunCheck(); }; my.reset = function () { StorageManager.clear('protocol'); StorageManager.clear('host'); StorageManager.clear('port'); connectionData = {}; return; }; my.getConnectionSettings = function () { return connectionData; }; return my; }; if (typeof exports !== 'undefined') { exports.EdgeInspectGlobals = EdgeInspectGlobals; } var EdgeInspect = function () { 'use strict'; var my = { deviceManagerFirstRun: false, isConnected: false, uuid: null, CONNECTED_EVENT: 'connected', DISCONNECTED_EVENT: 'disconnected', SCREENSHOTS_COMPLETE_EVENT: "screenshotsComplete", CLOSE_REASON_CLEAN: 1001, CLOSE_REASON_SERVER_SHUTDOWN: 2001, CLOSE_REASON_SERVER_EJECTED: 2002, CLOSE_REASON_SERVER_REJECTED: 2003, CLOSE_REASON_SERVER_MAX_CONNECTIONS: 2004, CLOSE_REASON_VERSION_MISMATCH: 3001, CLOSE_REASON_UNKNOWN: 4001 }, messageActionMap = {}, verifiedChallenge = false, deviceManagerMessageVersion = 0, hasSubscribed = false, keepAliveTimer = null, shutdownCode = false, subscribers = {}, defaultSalt = 'b8b5d15f0de11ceed565376436d25d74', StorageManager, ConnectionManager, CryptoHandler, MessageFormatter, MessageParser, WebSocketObject, LocalStorageObject, LocalStorageInstance, CryptoObject; if (runInBrowserMode) { // We're in a browser as far as we know, use the native objects. WebSocketObject = WebSocket; LocalStorageObject = {}; LocalStorageInstance = localStorage; CryptoObject = Crypto; } else { // We're not in a browser as far as we know. Probably Node, try requiring. WebSocketObject = require('ws'); LocalStorageObject = require('node-localstorage').LocalStorage; LocalStorageInstance = new LocalStorageObject('./EdgeInspect'); CryptoObject = require('cryptojs').Crypto; } StorageManager = new EdgeInspectGlobals.StorageManager(LocalStorageInstance); ConnectionManager = new EdgeInspectGlobals.ConnectionManager(WebSocketObject, StorageManager); CryptoHandler = new EdgeInspectGlobals.CryptoHandler(CryptoObject); MessageFormatter = new EdgeInspectGlobals.MessageFormatter(CryptoHandler); MessageParser = new EdgeInspectGlobals.MessageParser(StorageManager, CryptoHandler); function publish(name, data) { var i; if (typeof subscribers[name] !== 'undefined') { for (i = 0; i < subscribers[name].length; i += 1) { subscribers[name][i](data); } } } function checkForSupportedDeviceManager() { if (deviceManagerMessageVersion < 1) { shutdownCode = my.CLOSE_REASON_VERSION_MISMATCH; ConnectionManager.disconnect(); return false; } else { return true; } } function pingDeviceManager() { if (my.isConnected) { var pingMessage = MessageFormatter.ping(); StorageManager.log(pingMessage); ConnectionManager.send(CryptoHandler.encryptMessageForDM(pingMessage)); } } function startKeepAliveTimer() { keepAliveTimer = setInterval(pingDeviceManager, 20000); } function stopKeepAliveTimer() { if (keepAliveTimer) { clearInterval(keepAliveTimer); keepAliveTimer = null; } } function configure(driverName, driverId, encryptionToken) { if (typeof driverName === 'undefined') { throw new Error('You must provide at least a name and a UUID'); } if (driverName === '') { throw new Error('Your name cannot be empty.'); } if (!driverId.match(/^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/)) { throw new Error('Your driver ID is not a UUID.'); } var configureParameters = {}; my.uuid = driverId; if (typeof encryptionToken === 'undefined' || String(encryptionToken) === '') { configureParameters = {salt: defaultSalt, passcode: my.generateUUID()}; } else { configureParameters = {encryptionkey: encryptionToken}; } CryptoHandler.configure(configureParameters); // This should be refactored MessageFormatter.configure({uuid: my.uuid, inspectionUrl: '', clientName: driverName}); ConnectionManager.configure(); if (!hasSubscribed) { ConnectionManager.subscribe('connect', function () { var pairMessage = MessageFormatter.pair(); StorageManager.log(pairMessage); ConnectionManager.send(pairMessage); }); ConnectionManager.subscribe('message', function (message) { var parsed = MessageParser.parse(message); if (parsed) { if (typeof messageActionMap[parsed.action] !== 'undefined') { messageActionMap[parsed.action](parsed); } } }); ConnectionManager.subscribe('disconnect', function (message) { var reasonCode = parseInt(message.code, 10); my.isConnected = false; if (shutdownCode !== false) { reasonCode = shutdownCode; } publish(my.DISCONNECTED_EVENT, reasonCode); shutdownCode = false; }); hasSubscribed = true; } } function updateDeviceManagerMessageVersion(message) { deviceManagerMessageVersion = parseInt(message.version, 10); StorageManager.put('dmmsgversion', deviceManagerMessageVersion); } messageActionMap = { 'pair_ready' : function (message) { updateDeviceManagerMessageVersion(message); if (checkForSupportedDeviceManager()) { verifiedChallenge = CryptoHandler.verifyChallenge(message.options.challenge); var responseMessage; if (verifiedChallenge) { responseMessage = MessageFormatter.connect(verifiedChallenge); StorageManager.log(responseMessage); ConnectionManager.send(responseMessage); } else { responseMessage = MessageFormatter.pairFirst(); StorageManager.log(responseMessage); ConnectionManager.send(responseMessage); } } }, 'passcode_request' : function (message) { var responseMessage = MessageFormatter.pairFirst(); StorageManager.log(responseMessage); updateDeviceManagerMessageVersion(message); if (checkForSupportedDeviceManager()) { ConnectionManager.send(responseMessage); } }, 'connect_ok' : function () { my.isConnected = true; startKeepAliveTimer(); publish(my.CONNECTED_EVENT, CryptoHandler.getKeyAsHex()); }, 'transfer_complete' : function () { publish(my.SCREENSHOTS_COMPLETE_EVENT); } }; my.subscribe = function (name, handler) { if (typeof subscribers[name] === 'undefined') { subscribers[name] = []; } subscribers[name].push(handler); }; my.connect = function (driverName, driverId, encryptionToken) { configure(driverName, driverId, encryptionToken); if (!ConnectionManager.isConnected) { ConnectionManager.connect(); } }; my.disconnect = function () { if (ConnectionManager.isConnected) { stopKeepAliveTimer(); shutdownCode = my.CLOSE_REASON_CLEAN; ConnectionManager.disconnect(); } }; my.reset = function () { ConnectionManager.reset(); my.uuid = null; StorageManager.destroySavedSettings(); }; my.getConnectionSettings = function () { return ConnectionManager.getConnectionSettings(); }; my.sendURL = function (url, fullscreen) { if (typeof fullscreen === 'undefined' || fullscreen === false) { fullscreen = "false"; } else { fullscreen = "true"; } var sendUrlMessage = MessageFormatter.browse(url, [], fullscreen); StorageManager.log(sendUrlMessage); ConnectionManager.send(CryptoHandler.encryptMessageForDM(sendUrlMessage)); }; my.takeScreenshot = function (fullPage, dualOrientation) { var screenshotMessage = MessageFormatter.screenshot(my.generateUUID(), fullPage, dualOrientation, []); ConnectionManager.send(CryptoHandler.encryptMessageForDM(screenshotMessage)); }; my.generateUUID = function () { // Big hat tip to the https://github.com/jed and his public gist for this https://gist.github.com/982883 function b(a) { return a ? (a ^ Math.random() * 16 >> a / 4).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, b); } return b(); }; return my; }; if (typeof exports !== 'undefined') { exports.EdgeInspect = EdgeInspect; }<|fim▁end|>
my.cancel = function (devices) { var parameters = { subaction: 'cancel_connect', deviceids: devices
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2015 Conwet Lab., Universidad Politécnica de Madrid # This file is part of Wirecloud. # Wirecloud is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # Wirecloud is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with Wirecloud. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from uuid import uuid4 from django.contrib.auth.models import User, Group from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from markdown.extensions.toc import slugify __all__ = ('Organization', 'Team') class OrganizationManager(models.Manager): def is_available(self, name): return not User.objects.filter(username=name).exists() and not Group.objects.filter(name=name).exists() def search_available_name(self, username): max_length = 30 uuid_length = 8 short_username = slugify(username, '-')[:max_length - uuid_length] final_username = slugify(username, '-')[:max_length] while not self.is_available(final_username): final_username = short_username + uuid4().hex[:uuid_length]<|fim▁hole|> return final_username def create_organization(self, name, owners=[]): user = User.objects.create(username=name) group = Group.objects.create(name=name) org = self.create(user=user, group=group) team = Team.objects.create(organization=org, name='owners') for owner in owners: team.users.add(owner) return org @python_2_unicode_compatible class Organization(models.Model): user = models.OneToOneField(User) group = models.OneToOneField(Group) objects = OrganizationManager() class Meta: app_label = "platform" def __str__(self): return self.user.username class TeamManager(models.Manager): """ The manager for the auth's Team model. """ def get_by_natural_key(self, organization, name): return self.get(organization=organization, name=name) @python_2_unicode_compatible class Team(models.Model): """ Teams are a generic way of categorizing users to apply permissions, or some other label, to those users. A user can belong to any number of teams. """ organization = models.ForeignKey(Organization, on_delete=models.CASCADE) name = models.CharField(_('name'), max_length=80) users = models.ManyToManyField(User, verbose_name=_('users'), blank=True, related_name="teams") objects = TeamManager() class Meta: app_label = "platform" unique_together = ('organization', 'name') verbose_name = _('team') verbose_name_plural = _('teams') def __str__(self): return self.name def natural_key(self): return (self.organization, self.name)<|fim▁end|>
<|file_name|>background.js<|end_file_name|><|fim▁begin|>Array.prototype.equals = function(array) { // if the other array is a falsy value, return if (!array) return false; // compare lengths - can save a lot of time if (this.length != array.length) return false; for (var i = 0, l = this.length; i < l; i++) { // Check if we have nested arrays if (this[i] instanceof Array && array[i] instanceof Array) { // recurse into the nested arrays if (!this[i].equals(array[i])) return false; } else if (this[i] != array[i]) { // Warning - two different object instances will never be equal: {x:20} != {x:20} return false; } } return true; } var installed_date = new Date().getTime(); var DefaultSettings = { "installed_date": installed_date, "timestamp": "absolute", "full_after_24h": false, "name_display": "both", "typeahead_display_username_only": true, "circled_avatars": true, "no_columns_icons": true, "yt_rm_button": true, "small_icons_compose": true, "grayscale_notification_icons": false, "url_redirection": true, "blurred_modals": true, "only_one_thumbnails": true, "minimal_mode": true, "flash_tweets": "mentions", "shorten_text": false, "share_button": true, "providers": { "500px": true, "bandcamp": true, "cloudapp": true, "dailymotion": true, "deviantart": true, "dribbble": true, "droplr": true, "flickr": true, "imgly": true, "imgur": true, "instagram": true, "mobyto": true, "soundcloud": true, "ted": true, "toresize": true, "tumblr": true, "vimeo": true, "yfrog": true, } }; var currentOptions; function onInstall() { chrome.tabs.create({ url: "options/options.html#installed" }); } function onUpdate() { chrome.tabs.create({ url: "options/options.html#updated" }); } function getVersion() { var details = chrome.app.getDetails(); return details.version; } var currVersion = getVersion(); if (!localStorage['version']) { localStorage['version'] = currVersion; } var prevVersion = localStorage['version']; function init() { const TWEETDECK_WEB_URL = 'https://tweetdeck.twitter.com'; /** * Step 2: Collate a list of all the open tabs. */ function gatherTabs(urls, itemInfos) { var allTheTabs = []; var windowsChecked = 0; console.log("gatherTabs", itemInfos.timestamp); // First get all the windows... chrome.windows.getAll(function(windows) { for (var i = 0; i < windows.length; i++) { // ... and then all their tabs. chrome.tabs.getAllInWindow(windows[i].id, function(tabs) { windowsChecked++; allTheTabs = allTheTabs.concat(tabs); if (windowsChecked === windows.length) { // We have all the tabs! Search for a TweetDeck... openApp(urls, allTheTabs, itemInfos); } }); } }); } function openApp(urls, tabs, itemInfos) { console.log("openApp", itemInfos.timestamp); // Search urls in priority order... for (var i = 0; i < urls.length; i++) { var url = urls[i]; // Search tabs... for (var j = 0; j < tabs.length; j++) { var tab = tabs[j]; if (tab.url.indexOf(url) === 0) { // Found it! var tabId = tab.id; chrome.windows.update(tab.windowId, { focused: true }); chrome.tabs.update(tabId, { selected: true, active: true, highlighted: true }, function() { console.log("update", itemInfos.timestamp); var text = itemInfos.text; var url = itemInfos.url; chrome.tabs.sendMessage(tabId, { text: text, url: url, timestamp: itemInfos.timestamp, count: 2 }) }); return; } } } // Didn't find it! Open a new one! chrome.tabs.create({ url: urls[0] }, function(tab) { var count = 0; chrome.tabs.onUpdated.addListener(function(tabId, info) { if (info.status == "complete") { count += 1; console.log("onUpdated", itemInfos.timestamp, count); chrome.tabs.sendMessage(tabId, { text: itemInfos.text, url: itemInfos.url, timestamp: itemInfos.timestamp, count: count }); } }) }); }; var clickHandler = function(info, tab) { var text; var url; if (info.selectionText && currentOptions.shorten_text) { text = "\"" + info.selectionText.substr(0, 110) + "\""; } else if (info.selectionText) { text = "\"" + info.selectionText + "\""; } else { text = tab.title.substr(0, 110); } if (info.linkUrl) { url = info.linkUrl } else { url = info.pageUrl; } if (info.mediaType === "image") { url = info.srcUrl; text = ""; } gatherTabs([TWEETDECK_WEB_URL], { "text": text, "url": url, "timestamp": new Date().getTime() }); }; if (currentOptions.share_button) { console.debug('Share button enabled'); chrome.contextMenus.create({ "title": "Share on (Better) TweetDeck",<|fim▁hole|> }); } } chrome.storage.sync.get("BTDSettings", function(obj) { if (obj.BTDSettings !== undefined) { currentOptions = obj.BTDSettings; var reApply = false; for (var setting in DefaultSettings) { if (currentOptions[setting] == undefined) { console.debug("Defining", setting, "to default value", DefaultSettings[setting]); currentOptions[setting] = DefaultSettings[setting]; reApply = true; } } if (currVersion != prevVersion) { if (!(prevVersion.split(".")[0] == currVersion.split(".")[0] && prevVersion.split(".")[1] == currVersion.split(".")[1])) { onUpdate(); } localStorage['version'] = currVersion; } for (var provider in DefaultSettings["providers"]) { if (currentOptions["providers"][provider] == undefined) { console.log("Adding", provider, "as a new provider with value", DefaultSettings["providers"][provider]); currentOptions["providers"][provider] = DefaultSettings["providers"][provider]; reApply = true; } } for (var setting in currentOptions) { if (DefaultSettings[setting] == undefined) { console.log("Deleting", setting); delete currentOptions[setting]; reApply = true; } } for (var setting in currentOptions["providers"]) { if (DefaultSettings["providers"][setting] == undefined) { delete currentOptions["providers"][setting]; reApply = true; } } if (reApply === true) { chrome.storage.sync.set({ "BTDSettings": currentOptions }, function() { console.log("Options updated!"); console.log(currentOptions); init(); }); } else { init(); } } else { chrome.storage.sync.set({ "BTDSettings": DefaultSettings }, function() { console.log("Default options set"); onInstall(); init(); }) } });<|fim▁end|>
"contexts": ["page", "selection", "image", "link"], "onclick": clickHandler
<|file_name|>AbstractBookmarkMarkerPropertiesProvider.java<|end_file_name|><|fim▁begin|>package mesfavoris.bookmarktype; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.Optional; import mesfavoris.model.Bookmark; public abstract class AbstractBookmarkMarkerPropertiesProvider implements IBookmarkMarkerAttributesProvider { protected Optional<String> getMessage(Bookmark bookmark) { String comment = bookmark.getPropertyValue(Bookmark.PROPERTY_COMMENT); if (comment == null) { return Optional.empty(); } try (BufferedReader br = new BufferedReader(new StringReader(comment))) { return Optional.ofNullable(br.readLine()); } catch (IOException e) { return Optional.empty();<|fim▁hole|> } } }<|fim▁end|>
<|file_name|>textarea.js<|end_file_name|><|fim▁begin|>/** * Textarea Element * * @copyright: Copyright (C) 2005-2013, fabrikar.com - All rights reserved. * @license: GNU/GPL http://www.gnu.org/copyleft/gpl.html */ var FbTextarea = new Class({ Extends: FbElement, initialize: function (element, options) { this.plugin = 'fabriktextarea'; this.parent(element, options); // $$$ rob need to slightly delay this as if lots of js loaded (eg maps) // before the editor then the editor may not yet be loaded this.periodFn = function () { // Seems that tinyMCE isn't created if FbLike element published in form this.getTextContainer(); if (typeof tinyMCE !== 'undefined') { if (this.container !== false) { clearInterval(p); this.watchTextContainer(); } } else { clearInterval(p); this.watchTextContainer(); } }; var p = this.periodFn.periodical(200, this); Fabrik.addEvent('fabrik.form.page.change.end', function (form) { this.refreshEditor(); }.bind(this)); Fabrik.addEvent('fabrik.form.elements.added', function (form) { if (form.isMultiPage()) { this.refreshEditor(); } }.bind(this)); }, unclonableProperties: function () { var props = this.parent(); props.push('container'); return props; }, /** * Set names/ids/elements ect when the elements group is cloned * * @param int id element id * @since 3.0.7 */ cloneUpdateIds: function (id) { this.element = document.id(id); this.options.element = id; this.options.htmlId = id; }, watchTextContainer: function () { if (typeOf(this.element) === 'null') { this.element = document.id(this.options.element); } if (typeOf(this.element) === 'null') { this.element = document.id(this.options.htmlId); if (typeOf(this.element) === 'null') { // Can occur when element is part of hidden first group return; } } if (this.options.editable === true) { var c = this.getContainer(); if (c === false) { fconsole('no fabrikElementContainer class found for textarea'); return; } var element = c.getElement('.fabrik_characters_left'); if (typeOf(element) !== 'null') { this.warningFX = new Fx.Morph(element, {duration: 1000, transition: Fx.Transitions.Quart.easeOut}); this.origCol = element.getStyle('color'); if (this.options.wysiwyg && typeof(tinymce) !== 'undefined') { // Joomla 3.2 + usess tinyMce 4 if (tinymce.majorVersion >= 4) { tinyMCE.get(this.element.id).on('keyup', function (e) { this.informKeyPress(e); }.bind(this)); tinyMCE.get(this.element.id).on('focus', function (e) { var c = this.element.getParent('.fabrikElementContainer'); c.getElement('span.badge').addClass('badge-info'); c.getElement('.fabrik_characters_left').removeClass('muted'); }.bind(this)); tinyMCE.get(this.element.id).on('blur', function (e) { var c = this.element.getParent('.fabrikElementContainer'); c.getElement('span.badge').removeClass('badge-info'); c.getElement('.fabrik_characters_left').addClass('muted'); }.bind(this)); tinyMCE.get(this.element.id).on('blur', function (e) { this.forwardEvent('blur'); }.bind(this)); } else { tinymce.dom.Event.add(this.container, 'keyup', function (e) { this.informKeyPress(e); }.bind(this)); tinymce.dom.Event.add(this.container, 'blur', function (e) { this.forwardEvent('blur'); }.bind(this)); } } else { if (typeOf(this.container) !== 'null') { this.container.addEvent('keydown', function (e) { this.informKeyPress(e); }.bind(this)); this.container.addEvent('blur', function (e) { this.blurCharsLeft(e); }.bind(this)); this.container.addEvent('focus', function (e) { this.focusCharsLeft(e); }.bind(this)); } } } } }, /** * Forward an event from tinyMce to the text editor - useful for triggering ajax validations * * @param string event Event name */ forwardEvent: function (event) { var textarea = tinyMCE.activeEditor.getElement(), c = this.getContent(); textarea.set('value', c); textarea.fireEvent('blur', new Event.Mock(textarea, event)); }, focusCharsLeft: function () { var c = this.element.getParent('.fabrikElementContainer'); c.getElement('span.badge').addClass('badge-info'); c.getElement('.fabrik_characters_left').removeClass('muted'); }, blurCharsLeft: function () { var c = this.element.getParent('.fabrikElementContainer'); c.getElement('span.badge').removeClass('badge-info'); c.getElement('.fabrik_characters_left').addClass('muted'); }, /** * Used to find element when form clones a group * WYSIWYG text editor needs to return something specific as options.element has to use name * and not id. */ getCloneName: function () { var name = this.options.isGroupJoin ? this.options.htmlId : this.options.element; return name; }, /** * Run when element cloned in repeating group * * @param int c repeat group counter */ cloned: function (c) { if (this.options.wysiwyg) { var p = this.element.getParent('.fabrikElement'); var txt = p.getElement('textarea').clone(true, true); var charLeft = p.getElement('.fabrik_characters_left'); p.empty(); p.adopt(txt); if (typeOf(charLeft) !== 'null') { p.adopt(charLeft.clone()); } txt.removeClass('mce_editable'); txt.setStyle('display', ''); this.element = txt; var id = this.options.isGroupJoin ? this.options.htmlId : this.options.element; tinyMCE.execCommand('mceAddControl', false, id); } this.getTextContainer();<|fim▁hole|> }, /** * run when the element is decloled from the form as part of a deleted repeat group */ decloned: function (groupid) { if (this.options.wysiwyg) { var id = this.options.isGroupJoin ? this.options.htmlId : this.options.element; tinyMCE.execCommand('mceFocus', false, id); tinyMCE.execCommand('mceRemoveControl', false, id); } }, getTextContainer: function () { if (this.options.wysiwyg && this.options.editable) { var name = this.options.isGroupJoin ? this.options.htmlId : this.options.element; document.id(name).addClass('fabrikinput'); var instance = typeof(tinyMCE) !== 'undefined' ? tinyMCE.get(name) : false; if (instance) { this.container = instance.getDoc(); } else { this.contaner = false; } } else { // Regrab the element for inline editing (otherwise 2nd col you edit doesnt pickup the textarea. this.element = document.id(this.options.element); this.container = this.element; } return this.container; }, getContent: function () { if (this.options.wysiwyg) { return tinyMCE.activeEditor.getContent().replace(/<\/?[^>]+(>|$)/g, ""); } else { return this.container.value; } }, /** * On ajax loaded page need to re-load the editor * For Chrome */ refreshEditor: function () { if (this.options.wysiwyg) { if (typeof WFEditor !== 'undefined') { WFEditor.init(WFEditor.settings); } else if (typeof tinymce !== 'undefined') { tinyMCE.init(tinymce.settings); } // Need to re-observe the editor this.watchTextContainer(); } }, setContent: function (c) { if (this.options.wysiwyg) { var r = tinyMCE.getInstanceById(this.element.id).setContent(c); this.moveCursorToEnd(); return r; } else { this.getTextContainer(); if (typeOf(this.container) !== 'null') { this.container.value = c; } } return null; }, /** * For tinymce move the cursor to the end */ moveCursorToEnd: function () { var inst = tinyMCE.getInstanceById(this.element.id); inst.selection.select(inst.getBody(), true); inst.selection.collapse(false); }, informKeyPress: function () { var charsleftEl = this.getContainer().getElement('.fabrik_characters_left'); var content = this.getContent(); charsLeft = this.itemsLeft(); if (this.limitReached()) { this.limitContent(); this.warningFX.start({'opacity': 0, 'color': '#FF0000'}).chain(function () { this.start({'opacity': 1, 'color': '#FF0000'}).chain(function () { this.start({'opacity': 0, 'color': this.origCol}).chain(function () { this.start({'opacity': 1}); }); }); }); } else { charsleftEl.setStyle('color', this.origCol); } charsleftEl.getElement('span').set('html', charsLeft); }, /** * How many content items left (e.g 1 word, 100 characters) * * @return int */ itemsLeft: function () { var i = 0, content = this.getContent(); if (this.options.maxType === 'word') { i = this.options.max - content.split(' ').length; } else { i = this.options.max - (content.length + 1); } if (i < 0) { i = 0; } return i; }, /** * Limit the content based on maxType and max e.g. 100 words, 2000 characters */ limitContent: function () { var c, content = this.getContent(); if (this.options.maxType === 'word') { c = content.split(' ').splice(0, this.options.max); c = c.join(' '); c += (this.options.wysiwyg) ? '&nbsp;' : ' '; } else { c = content.substring(0, this.options.max); } this.setContent(c); }, /** * Has the max content limit been reached? * * @return bool */ limitReached: function () { var content = this.getContent(); if (this.options.maxType === 'word') { var words = content.split(' '); return words.length > this.options.max; } else { var charsLeft = this.options.max - (content.length + 1); return charsLeft < 0 ? true : false; } }, reset: function () { this.update(this.options.defaultVal); }, update: function (val) { this.getElement(); this.getTextContainer(); if (!this.options.editable) { this.element.set('html', val); return; } this.setContent(val); } });<|fim▁end|>
this.watchTextContainer(); this.parent(c);
<|file_name|>test_sitemaps.py<|end_file_name|><|fim▁begin|>from django.core.urlresolvers import reverse from django.test import TestCase as DjangoTestCase from blognajd.models import Story, SiteSettings from blognajd.sitemaps import StaticSitemap, StoriesSitemap class StaticSitemap1TestCase(DjangoTestCase): fixtures = ['sitesettings_tests.json'] def test_staticsitemap_items_disabled(self): sitesettings = SiteSettings.objects.get(pk=1) sitesettings.has_about_page = False sitesettings.has_projects_page = False sitesettings.has_contact_page = False sitesettings.save() self.assertEqual([i for i in StaticSitemap().items()], ['blog']) def test_staticsitemap_items_enabled(self): sitesettings = SiteSettings.objects.get(pk=1) sitesettings.has_about_page = True<|fim▁hole|> self.assertEqual(sorted([i for i in StaticSitemap().items()]), ['about', 'blog', 'contact', 'projects']) def test_staticsitemap_location(self): sitemap = StaticSitemap() for item in sitemap.items(): if item == 'contact': urlname = 'contactme-get-contact-form' else: urlname = item self.assertEqual(sitemap.location(item), reverse(urlname)) class StoriesSitemapTestCase(DjangoTestCase): fixtures = ['story_tests.json'] def setUp(self): self.story = Story.objects.get(pk=1) self.sitemap = StoriesSitemap() def test_storiessitemap_items(self): self.assertEqual(len(self.sitemap.items()), 1) def test_storiessitemap_lastmod(self): for item in self.sitemap.items(): self.assertEqual(self.sitemap.lastmod(item), self.story.mod_date)<|fim▁end|>
sitesettings.has_projects_page = True sitesettings.has_contact_page = True sitesettings.save()
<|file_name|>action.rs<|end_file_name|><|fim▁begin|>extern crate toml; extern crate collections; use std::io::fs; use std::io::fs::PathExtensions; use std::io::{Process, Command}; use std::collections::treemap::TreeMap; #[deriving(Clone)] pub struct Action { pub name: String, pub command: String, pub do_file: Option<Path>, pub undo_file: Option<Path> } impl Action { pub fn do_command(&self) -> Result<String, String> { execute_command(&self.do_file, &self.command, "No 'do' file") } pub fn undo_command(&self) -> Result<String, String> { execute_command(&self.undo_file, &self.command, "No 'undo' file") } pub fn find_actions(root: &Path, cmd: &String, special: &TreeMap<String, toml::Value>) -> Result<Vec<Action>, &'static str> { let dirs = try!(select_files(root, |_, path| valid_action_dir(path))); let mut actions: Vec<Action> = Vec::with_capacity(dirs.len()); for dir in dirs.iter() { let do_file = try!(select_files(dir, |name, _| name.starts_with("do"))).into_iter().next(); let undo_file = try!(select_files(dir, |name, _| name.starts_with("undo"))).into_iter().next(); let name = dir.filename_str().unwrap().to_string(); let command = match special.find(&number(&name).to_string()) { None => cmd.clone(), Some(v) => match v.lookup("command").map_or(None, |c| c.as_str()) { Some(value) => value.to_string(), None => return Err("'special' is invalid") }, }; actions.push(Action { name: name, command: command, do_file: do_file, undo_file: undo_file }); } actions.sort_by(|a, b| number(&a.name).cmp(&number(&b.name))); Ok(actions) } } fn number(name: &String) -> uint { let mut result = 0; for c in name.as_slice().chars() { if c.is_digit() { result += c.to_digit(10).unwrap(); } else { break; } } result } fn handle_output(process: Process) -> Result<String, String> { match process.wait_with_output() { Err(error) => Err(error.desc.to_string()), Ok(exit) => { if exit.status.success() { Ok(exit.output.into_ascii().into_string()) } else { Err(exit.error.into_ascii().into_string()) } } } } fn execute_command(file: &Option<Path>, cmd: &String, error: &'static str) -> Result<String, String> { let path = match file { &Some(ref path) => path, &None => return Ok(error.to_string()) }; let command = parse_command(cmd.as_slice(), path); let process = Command::new(command[0]) .cwd(&path.dir_path()) .args(command.tail()) .spawn(); match process { Ok(p) => handle_output(p), Err(error) => Err(error.desc.to_string()) } } fn parse_command<'a>(cmd: &'a str, path: &'a Path) -> Vec<&'a str> { let mut words: Vec<&str> = cmd.words().collect(); words.push(path.filename_str().unwrap()); words } fn valid_action_dir(path: &Path) -> bool { let name = path.filename_str().unwrap_or("");<|fim▁hole|> let valid_name = name.graphemes(true).next() .map_or(false, |s| s.char_at(0).is_digit()); valid_name && path.is_dir() } fn select_files(dir: &Path, p: |&str, &Path| -> bool) -> Result<Vec<Path>, &'static str> { let paths = match fs::readdir(dir) { Ok(paths) => paths, Err(error) => return Err(error.desc) }; let result = paths.iter().filter_map(|path| { let name = path.filename_str().unwrap_or(""); if p(name, path) { Some(path.clone()) } else { None } }).collect(); Ok(result) }<|fim▁end|>
<|file_name|>sigfig.py<|end_file_name|><|fim▁begin|>from math import floor, log10 def round_(x, n): """Round a float, x, to n significant figures. Caution should be applied when performing this operation. Significant figures are an implication of precision; arbitrarily truncating floats mid-calculation is probably not Good Practice in almost all cases. Rounding off a float to n s.f. results in a float. Floats are, in general, approximations of decimal numbers. The point here is that it is very possible to end up with an inexact number: >>> roundsf(0.0012395, 3) 0.00124 >>> roundsf(0.0012315, 3) 0.0012300000000000002 Basically, rounding in this way probably doesn't do what you want it to. """ n = int(n) x = float(x) if x == 0: return 0 e = floor(log10(abs(x)) - n + 1) # exponent, 10 ** e shifted_dp = x / (10 ** e) # decimal place shifted n d.p. return round(shifted_dp) * (10 ** e) # round and revert def string(x, n): """Convert a float, x, to a string with n significant figures. This function returns a decimal string representation of a float to a specified number of significant figures. >>> create_string(9.80665, 3) '9.81' >>> create_string(0.0120076, 3) '0.0120' >>> create_string(100000, 5) '100000' Note the last representation is, without context, ambiguous. This is a good reason to use scientific notation, but it's not always appropriate. Note ---- Performing this operation as a set of string operations arguably makes more sense than a mathematical operation conceptually. It's the presentation of the number that is being changed here, not the number itself (which is in turn only approximated by a float). """ n = int(n) x = float(x) if n < 1: raise ValueError("1+ significant digits required.") # retrieve the significand and exponent from the S.N. form s, e = ''.join(( '{:.', str(n - 1), 'e}')).format(x).split('e') e = int(e) # might as well coerce now if e == 0: # Significand requires no adjustment return s s = s.replace('.', '') if e < 0: # Placeholder zeros need creating return ''.join(('0.', '0' * (abs(e) - 1), s)) else: # Decimal place need shifting s += '0' * (e - n + 1) # s now has correct s.f.<|fim▁hole|> if i < n: sep = '.' if s[0] is '-': i += 1 return sep.join((s[:i], s[i:])) def scientific(x, n): """Represent a float in scientific notation. This function is merely a wrapper around the 'e' type flag in the formatting specification. """ n = int(n) x = float(x) if n < 1: raise ValueError("1+ significant digits required.") return ''.join(('{:.', str(n - 1), 'e}')).format(x) def general(x, n): """Represent a float in general form. This function is merely a wrapper around the 'g' type flag in the formatting specification. """ n = int(n) x = float(x) if n < 1: raise ValueError("1+ significant digits required.") return ''.join(('{:#.', str(n), 'g}')).format(x)<|fim▁end|>
i = e + 1 sep = ''
<|file_name|>games.js<|end_file_name|><|fim▁begin|>'use strict'; //Games service used for games REST endpoint angular.module('mean.games').factory('Games', ['$resource',<|fim▁hole|> function($resource) { return $resource('games/:gameid', { gameid: '@_id' }, { update: { method: 'PUT' } }); } ]);<|fim▁end|>
<|file_name|>ElementCountDTO.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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. */ package org.wso2.carbon.identity.entitlement.common.dto; public class ElementCountDTO { private int subElementCount; private int attributeDesignatorsElementCount; <|fim▁hole|> public int getSubElementCount() { return subElementCount; } public void setSubElementCount(int subElementCount) { this.subElementCount = subElementCount; } public int getAttributeSelectorElementCount() { return attributeSelectorElementCount; } public void setAttributeSelectorElementCount(int attributeSelectorElementCount) { this.attributeSelectorElementCount = attributeSelectorElementCount; } public int getAttributeValueElementCount() { return attributeValueElementCount; } public void setAttributeValueElementCount(int attributeValueElementCount) { this.attributeValueElementCount = attributeValueElementCount; } public int getAttributeDesignatorsElementCount() { return attributeDesignatorsElementCount; } public void setAttributeDesignatorsElementCount(int attributeDesignatorsElementCount) { this.attributeDesignatorsElementCount = attributeDesignatorsElementCount; } }<|fim▁end|>
private int attributeValueElementCount; private int attributeSelectorElementCount;
<|file_name|>macsec.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListType from pyangbind.lib.yangtypes import YANGDynClass from pyangbind.lib.yangtypes import ReferenceType from pyangbind.lib.base import PybindBase from collections import OrderedDict from decimal import Decimal from bitarray import bitarray import six # PY3 support of some PY2 keywords (needs improved) if six.PY3: import builtins as __builtin__ long = int elif six.PY2: import __builtin__ class yc_config_openconfig_macsec__macsec_mka_policies_policy_config(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka/policies/policy/config. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Configuration of the MKA policy """ __slots__ = ('_path_helper', '_extmethods', '__name','__key_server_priority','__macsec_cipher_suite','__confidentiality_offset','__delay_protection','__include_icv_indicator','__sak_rekey_interval','__sak_rekey_on_live_peer_loss','__use_updated_eth_header',) _yang_name = 'config' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True) self.__key_server_priority = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=True) self.__macsec_cipher_suite = YANGDynClass(unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=True) self.__confidentiality_offset = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=True) self.__delay_protection = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) self.__include_icv_indicator = YANGDynClass(base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) self.__sak_rekey_interval = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=True) self.__sak_rekey_on_live_peer_loss = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) self.__use_updated_eth_header = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka', 'policies', 'policy', 'config'] def _get_name(self): """ Getter method for name, mapped from YANG variable /macsec/mka/policies/policy/config/name (string) YANG Description: Name of the MKA policy. """ return self.__name def _set_name(self, v, load=False): """ Setter method for name, mapped from YANG variable /macsec/mka/policies/policy/config/name (string) If this variable is read-only (config: false) in the source YANG file, then _set_name is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_name() directly. YANG Description: Name of the MKA policy. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """name must be of a type compatible with string""", 'defined-type': "string", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True)""", }) self.__name = t if hasattr(self, '_set'): self._set() def _unset_name(self): self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True) def _get_key_server_priority(self): """ Getter method for key_server_priority, mapped from YANG variable /macsec/mka/policies/policy/config/key_server_priority (uint8) YANG Description: Specifies the key server priority used by the MACsec Key Agreement (MKA) protocol to select the key server when MACsec is enabled using static connectivity association key (CAK) security mode. The switch with the lower priority-number is selected as the key server. If the priority-number is identical on both sides of a point-to-point link, the MKA protocol selects the device with the lower MAC address as the key server """ return self.__key_server_priority def _set_key_server_priority(self, v, load=False): """ Setter method for key_server_priority, mapped from YANG variable /macsec/mka/policies/policy/config/key_server_priority (uint8) If this variable is read-only (config: false) in the source YANG file, then _set_key_server_priority is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_key_server_priority() directly. YANG Description: Specifies the key server priority used by the MACsec Key Agreement (MKA) protocol to select the key server when MACsec is enabled using static connectivity association key (CAK) security mode. The switch with the lower priority-number is selected as the key server. If the priority-number is identical on both sides of a point-to-point link, the MKA protocol selects the device with the lower MAC address as the key server """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """key_server_priority must be of a type compatible with uint8""", 'defined-type': "uint8", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=True)""", }) self.__key_server_priority = t if hasattr(self, '_set'): self._set() def _unset_key_server_priority(self): self.__key_server_priority = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=True) def _get_macsec_cipher_suite(self): """ Getter method for macsec_cipher_suite, mapped from YANG variable /macsec/mka/policies/policy/config/macsec_cipher_suite (macsec-types:macsec-cipher-suite) YANG Description: Set Cipher suite(s) for SAK derivation """ return self.__macsec_cipher_suite def _set_macsec_cipher_suite(self, v, load=False): """ Setter method for macsec_cipher_suite, mapped from YANG variable /macsec/mka/policies/policy/config/macsec_cipher_suite (macsec-types:macsec-cipher-suite) If this variable is read-only (config: false) in the source YANG file, then _set_macsec_cipher_suite is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_macsec_cipher_suite() directly. YANG Description: Set Cipher suite(s) for SAK derivation """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """macsec_cipher_suite must be of a type compatible with macsec-types:macsec-cipher-suite""", 'defined-type': "macsec-types:macsec-cipher-suite", 'generated-type': """YANGDynClass(unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=True)""", }) self.__macsec_cipher_suite = t if hasattr(self, '_set'): self._set() def _unset_macsec_cipher_suite(self): self.__macsec_cipher_suite = YANGDynClass(unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=True) def _get_confidentiality_offset(self): """ Getter method for confidentiality_offset, mapped from YANG variable /macsec/mka/policies/policy/config/confidentiality_offset (macsec-types:confidentiality-offset) YANG Description: The confidentiality offset specifies a number of octets in an Ethernet frame that are sent in unencrypted plain-text """ return self.__confidentiality_offset def _set_confidentiality_offset(self, v, load=False): """ Setter method for confidentiality_offset, mapped from YANG variable /macsec/mka/policies/policy/config/confidentiality_offset (macsec-types:confidentiality-offset) If this variable is read-only (config: false) in the source YANG file, then _set_confidentiality_offset is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_confidentiality_offset() directly. YANG Description: The confidentiality offset specifies a number of octets in an Ethernet frame that are sent in unencrypted plain-text """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """confidentiality_offset must be of a type compatible with macsec-types:confidentiality-offset""", 'defined-type': "macsec-types:confidentiality-offset", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=True)""", }) self.__confidentiality_offset = t if hasattr(self, '_set'): self._set() def _unset_confidentiality_offset(self): self.__confidentiality_offset = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=True) def _get_delay_protection(self): """ Getter method for delay_protection, mapped from YANG variable /macsec/mka/policies/policy/config/delay_protection (boolean) YANG Description: Traffic delayed longer than 2 seconds is rejected by the interfaces enabled with delay protection. """ return self.__delay_protection def _set_delay_protection(self, v, load=False): """ Setter method for delay_protection, mapped from YANG variable /macsec/mka/policies/policy/config/delay_protection (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_delay_protection is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_delay_protection() directly. YANG Description: Traffic delayed longer than 2 seconds is rejected by the interfaces enabled with delay protection. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """delay_protection must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)""", }) self.__delay_protection = t if hasattr(self, '_set'): self._set() def _unset_delay_protection(self): self.__delay_protection = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) def _get_include_icv_indicator(self): """ Getter method for include_icv_indicator, mapped from YANG variable /macsec/mka/policies/policy/config/include_icv_indicator (boolean) YANG Description: Generate and include an Integrity Check Value (ICV) field in the MKPDU. For compatibility with previous MACsec implementation that do not require an ICV """ return self.__include_icv_indicator def _set_include_icv_indicator(self, v, load=False): """ Setter method for include_icv_indicator, mapped from YANG variable /macsec/mka/policies/policy/config/include_icv_indicator (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_include_icv_indicator is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_include_icv_indicator() directly. YANG Description: Generate and include an Integrity Check Value (ICV) field in the MKPDU. For compatibility with previous MACsec implementation that do not require an ICV """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """include_icv_indicator must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)""", }) self.__include_icv_indicator = t if hasattr(self, '_set'): self._set() def _unset_include_icv_indicator(self): self.__include_icv_indicator = YANGDynClass(base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) def _get_sak_rekey_interval(self): """ Getter method for sak_rekey_interval, mapped from YANG variable /macsec/mka/policies/policy/config/sak_rekey_interval (uint32) YANG Description: SAK Rekey interval in seconds. The default value is 0 where no rekey is performed. """ return self.__sak_rekey_interval def _set_sak_rekey_interval(self, v, load=False): """ Setter method for sak_rekey_interval, mapped from YANG variable /macsec/mka/policies/policy/config/sak_rekey_interval (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_sak_rekey_interval is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sak_rekey_interval() directly. YANG Description: SAK Rekey interval in seconds. The default value is 0 where no rekey is performed. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """sak_rekey_interval must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=True)""", }) self.__sak_rekey_interval = t if hasattr(self, '_set'): self._set() def _unset_sak_rekey_interval(self): self.__sak_rekey_interval = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=True) def _get_sak_rekey_on_live_peer_loss(self): """ Getter method for sak_rekey_on_live_peer_loss, mapped from YANG variable /macsec/mka/policies/policy/config/sak_rekey_on_live_peer_loss (boolean) YANG Description: Rekey on peer loss """ return self.__sak_rekey_on_live_peer_loss def _set_sak_rekey_on_live_peer_loss(self, v, load=False): """ Setter method for sak_rekey_on_live_peer_loss, mapped from YANG variable /macsec/mka/policies/policy/config/sak_rekey_on_live_peer_loss (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_sak_rekey_on_live_peer_loss is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sak_rekey_on_live_peer_loss() directly. YANG Description: Rekey on peer loss """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """sak_rekey_on_live_peer_loss must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)""", }) self.__sak_rekey_on_live_peer_loss = t if hasattr(self, '_set'): self._set() def _unset_sak_rekey_on_live_peer_loss(self): self.__sak_rekey_on_live_peer_loss = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) def _get_use_updated_eth_header(self): """ Getter method for use_updated_eth_header, mapped from YANG variable /macsec/mka/policies/policy/config/use_updated_eth_header (boolean) YANG Description: Use updated ethernet header for ICV calculation. In case the Ethernet frame headers change, use the updated headers to calculate the ICV. """ return self.__use_updated_eth_header def _set_use_updated_eth_header(self, v, load=False): """ Setter method for use_updated_eth_header, mapped from YANG variable /macsec/mka/policies/policy/config/use_updated_eth_header (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_use_updated_eth_header is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_use_updated_eth_header() directly. YANG Description: Use updated ethernet header for ICV calculation. In case the Ethernet frame headers change, use the updated headers to calculate the ICV. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """use_updated_eth_header must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)""", }) self.__use_updated_eth_header = t if hasattr(self, '_set'): self._set() def _unset_use_updated_eth_header(self): self.__use_updated_eth_header = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) name = __builtin__.property(_get_name, _set_name) key_server_priority = __builtin__.property(_get_key_server_priority, _set_key_server_priority) macsec_cipher_suite = __builtin__.property(_get_macsec_cipher_suite, _set_macsec_cipher_suite) confidentiality_offset = __builtin__.property(_get_confidentiality_offset, _set_confidentiality_offset) delay_protection = __builtin__.property(_get_delay_protection, _set_delay_protection) include_icv_indicator = __builtin__.property(_get_include_icv_indicator, _set_include_icv_indicator) sak_rekey_interval = __builtin__.property(_get_sak_rekey_interval, _set_sak_rekey_interval) sak_rekey_on_live_peer_loss = __builtin__.property(_get_sak_rekey_on_live_peer_loss, _set_sak_rekey_on_live_peer_loss) use_updated_eth_header = __builtin__.property(_get_use_updated_eth_header, _set_use_updated_eth_header) _pyangbind_elements = OrderedDict([('name', name), ('key_server_priority', key_server_priority), ('macsec_cipher_suite', macsec_cipher_suite), ('confidentiality_offset', confidentiality_offset), ('delay_protection', delay_protection), ('include_icv_indicator', include_icv_indicator), ('sak_rekey_interval', sak_rekey_interval), ('sak_rekey_on_live_peer_loss', sak_rekey_on_live_peer_loss), ('use_updated_eth_header', use_updated_eth_header), ]) class yc_state_openconfig_macsec__macsec_mka_policies_policy_state(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka/policies/policy/state. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Operational state data for MKA policy """ __slots__ = ('_path_helper', '_extmethods', '__name','__key_server_priority','__macsec_cipher_suite','__confidentiality_offset','__delay_protection','__include_icv_indicator','__sak_rekey_interval','__sak_rekey_on_live_peer_loss','__use_updated_eth_header',) _yang_name = 'state' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False) self.__key_server_priority = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=False) self.__macsec_cipher_suite = YANGDynClass(unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=False) self.__confidentiality_offset = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=False) self.__delay_protection = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) self.__include_icv_indicator = YANGDynClass(base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) self.__sak_rekey_interval = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=False) self.__sak_rekey_on_live_peer_loss = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) self.__use_updated_eth_header = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka', 'policies', 'policy', 'state'] def _get_name(self): """ Getter method for name, mapped from YANG variable /macsec/mka/policies/policy/state/name (string) YANG Description: Name of the MKA policy. """ return self.__name def _set_name(self, v, load=False): """ Setter method for name, mapped from YANG variable /macsec/mka/policies/policy/state/name (string) If this variable is read-only (config: false) in the source YANG file, then _set_name is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_name() directly. YANG Description: Name of the MKA policy. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """name must be of a type compatible with string""", 'defined-type': "string", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)""", }) self.__name = t if hasattr(self, '_set'): self._set() def _unset_name(self): self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False) def _get_key_server_priority(self): """ Getter method for key_server_priority, mapped from YANG variable /macsec/mka/policies/policy/state/key_server_priority (uint8) YANG Description: Specifies the key server priority used by the MACsec Key Agreement (MKA) protocol to select the key server when MACsec is enabled using static connectivity association key (CAK) security mode. The switch with the lower priority-number is selected as the key server. If the priority-number is identical on both sides of a point-to-point link, the MKA protocol selects the device with the lower MAC address as the key server """ return self.__key_server_priority def _set_key_server_priority(self, v, load=False): """ Setter method for key_server_priority, mapped from YANG variable /macsec/mka/policies/policy/state/key_server_priority (uint8) If this variable is read-only (config: false) in the source YANG file, then _set_key_server_priority is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_key_server_priority() directly. YANG Description: Specifies the key server priority used by the MACsec Key Agreement (MKA) protocol to select the key server when MACsec is enabled using static connectivity association key (CAK) security mode. The switch with the lower priority-number is selected as the key server. If the priority-number is identical on both sides of a point-to-point link, the MKA protocol selects the device with the lower MAC address as the key server """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """key_server_priority must be of a type compatible with uint8""", 'defined-type': "uint8", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=False)""", }) self.__key_server_priority = t if hasattr(self, '_set'): self._set() def _unset_key_server_priority(self): self.__key_server_priority = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=False) def _get_macsec_cipher_suite(self): """ Getter method for macsec_cipher_suite, mapped from YANG variable /macsec/mka/policies/policy/state/macsec_cipher_suite (macsec-types:macsec-cipher-suite) YANG Description: Set Cipher suite(s) for SAK derivation """ return self.__macsec_cipher_suite def _set_macsec_cipher_suite(self, v, load=False): """ Setter method for macsec_cipher_suite, mapped from YANG variable /macsec/mka/policies/policy/state/macsec_cipher_suite (macsec-types:macsec-cipher-suite) If this variable is read-only (config: false) in the source YANG file, then _set_macsec_cipher_suite is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_macsec_cipher_suite() directly. YANG Description: Set Cipher suite(s) for SAK derivation """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """macsec_cipher_suite must be of a type compatible with macsec-types:macsec-cipher-suite""", 'defined-type': "macsec-types:macsec-cipher-suite", 'generated-type': """YANGDynClass(unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=False)""", }) self.__macsec_cipher_suite = t if hasattr(self, '_set'): self._set() def _unset_macsec_cipher_suite(self): self.__macsec_cipher_suite = YANGDynClass(unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=False) def _get_confidentiality_offset(self): """ Getter method for confidentiality_offset, mapped from YANG variable /macsec/mka/policies/policy/state/confidentiality_offset (macsec-types:confidentiality-offset) YANG Description: The confidentiality offset specifies a number of octets in an Ethernet frame that are sent in unencrypted plain-text """ return self.__confidentiality_offset def _set_confidentiality_offset(self, v, load=False): """ Setter method for confidentiality_offset, mapped from YANG variable /macsec/mka/policies/policy/state/confidentiality_offset (macsec-types:confidentiality-offset) If this variable is read-only (config: false) in the source YANG file, then _set_confidentiality_offset is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_confidentiality_offset() directly. YANG Description: The confidentiality offset specifies a number of octets in an Ethernet frame that are sent in unencrypted plain-text """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """confidentiality_offset must be of a type compatible with macsec-types:confidentiality-offset""", 'defined-type': "macsec-types:confidentiality-offset", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=False)""", }) self.__confidentiality_offset = t if hasattr(self, '_set'): self._set() def _unset_confidentiality_offset(self): self.__confidentiality_offset = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=False) def _get_delay_protection(self): """ Getter method for delay_protection, mapped from YANG variable /macsec/mka/policies/policy/state/delay_protection (boolean) YANG Description: Traffic delayed longer than 2 seconds is rejected by the interfaces enabled with delay protection. """ return self.__delay_protection def _set_delay_protection(self, v, load=False): """ Setter method for delay_protection, mapped from YANG variable /macsec/mka/policies/policy/state/delay_protection (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_delay_protection is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_delay_protection() directly. YANG Description: Traffic delayed longer than 2 seconds is rejected by the interfaces enabled with delay protection. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """delay_protection must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)""", }) self.__delay_protection = t if hasattr(self, '_set'): self._set() def _unset_delay_protection(self): self.__delay_protection = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) def _get_include_icv_indicator(self): """ Getter method for include_icv_indicator, mapped from YANG variable /macsec/mka/policies/policy/state/include_icv_indicator (boolean) YANG Description: Generate and include an Integrity Check Value (ICV) field in the MKPDU. For compatibility with previous MACsec implementation that do not require an ICV """ return self.__include_icv_indicator def _set_include_icv_indicator(self, v, load=False): """ Setter method for include_icv_indicator, mapped from YANG variable /macsec/mka/policies/policy/state/include_icv_indicator (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_include_icv_indicator is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_include_icv_indicator() directly. YANG Description: Generate and include an Integrity Check Value (ICV) field in the MKPDU. For compatibility with previous MACsec implementation that do not require an ICV """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """include_icv_indicator must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)""", }) self.__include_icv_indicator = t if hasattr(self, '_set'): self._set() def _unset_include_icv_indicator(self): self.__include_icv_indicator = YANGDynClass(base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) def _get_sak_rekey_interval(self): """ Getter method for sak_rekey_interval, mapped from YANG variable /macsec/mka/policies/policy/state/sak_rekey_interval (uint32) YANG Description: SAK Rekey interval in seconds. The default value is 0 where no rekey is performed. """ return self.__sak_rekey_interval def _set_sak_rekey_interval(self, v, load=False): """ Setter method for sak_rekey_interval, mapped from YANG variable /macsec/mka/policies/policy/state/sak_rekey_interval (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_sak_rekey_interval is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sak_rekey_interval() directly. YANG Description: SAK Rekey interval in seconds. The default value is 0 where no rekey is performed. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sak_rekey_interval must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=False)""", }) self.__sak_rekey_interval = t if hasattr(self, '_set'): self._set() def _unset_sak_rekey_interval(self): self.__sak_rekey_interval = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=False) def _get_sak_rekey_on_live_peer_loss(self): """ Getter method for sak_rekey_on_live_peer_loss, mapped from YANG variable /macsec/mka/policies/policy/state/sak_rekey_on_live_peer_loss (boolean) YANG Description: Rekey on peer loss """ return self.__sak_rekey_on_live_peer_loss def _set_sak_rekey_on_live_peer_loss(self, v, load=False): """ Setter method for sak_rekey_on_live_peer_loss, mapped from YANG variable /macsec/mka/policies/policy/state/sak_rekey_on_live_peer_loss (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_sak_rekey_on_live_peer_loss is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sak_rekey_on_live_peer_loss() directly. YANG Description: Rekey on peer loss """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sak_rekey_on_live_peer_loss must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)""", }) self.__sak_rekey_on_live_peer_loss = t if hasattr(self, '_set'): self._set() def _unset_sak_rekey_on_live_peer_loss(self): self.__sak_rekey_on_live_peer_loss = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) def _get_use_updated_eth_header(self): """ Getter method for use_updated_eth_header, mapped from YANG variable /macsec/mka/policies/policy/state/use_updated_eth_header (boolean) YANG Description: Use updated ethernet header for ICV calculation. In case the Ethernet frame headers change, use the updated headers to calculate the ICV. """ return self.__use_updated_eth_header def _set_use_updated_eth_header(self, v, load=False): """ Setter method for use_updated_eth_header, mapped from YANG variable /macsec/mka/policies/policy/state/use_updated_eth_header (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_use_updated_eth_header is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_use_updated_eth_header() directly. YANG Description: Use updated ethernet header for ICV calculation. In case the Ethernet frame headers change, use the updated headers to calculate the ICV. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """use_updated_eth_header must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)""", }) self.__use_updated_eth_header = t if hasattr(self, '_set'): self._set() def _unset_use_updated_eth_header(self): self.__use_updated_eth_header = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) name = __builtin__.property(_get_name) key_server_priority = __builtin__.property(_get_key_server_priority) macsec_cipher_suite = __builtin__.property(_get_macsec_cipher_suite) confidentiality_offset = __builtin__.property(_get_confidentiality_offset) delay_protection = __builtin__.property(_get_delay_protection) include_icv_indicator = __builtin__.property(_get_include_icv_indicator) sak_rekey_interval = __builtin__.property(_get_sak_rekey_interval) sak_rekey_on_live_peer_loss = __builtin__.property(_get_sak_rekey_on_live_peer_loss) use_updated_eth_header = __builtin__.property(_get_use_updated_eth_header) _pyangbind_elements = OrderedDict([('name', name), ('key_server_priority', key_server_priority), ('macsec_cipher_suite', macsec_cipher_suite), ('confidentiality_offset', confidentiality_offset), ('delay_protection', delay_protection), ('include_icv_indicator', include_icv_indicator), ('sak_rekey_interval', sak_rekey_interval), ('sak_rekey_on_live_peer_loss', sak_rekey_on_live_peer_loss), ('use_updated_eth_header', use_updated_eth_header), ]) class yc_policy_openconfig_macsec__macsec_mka_policies_policy(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka/policies/policy. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: List of MKA policies """ __slots__ = ('_path_helper', '_extmethods', '__name','__config','__state',) _yang_name = 'policy' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_policies_policy_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_policies_policy_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka', 'policies', 'policy'] def _get_name(self): """ Getter method for name, mapped from YANG variable /macsec/mka/policies/policy/name (leafref) YANG Description: Reference to MKA policy name """ return self.__name def _set_name(self, v, load=False): """ Setter method for name, mapped from YANG variable /macsec/mka/policies/policy/name (leafref) If this variable is read-only (config: false) in the source YANG file, then _set_name is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_name() directly. YANG Description: Reference to MKA policy name """ parent = getattr(self, "_parent", None) if parent is not None and load is False: raise AttributeError("Cannot set keys directly when" + " within an instantiated list") if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """name must be of a type compatible with leafref""", 'defined-type': "leafref", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)""", }) self.__name = t if hasattr(self, '_set'): self._set() def _unset_name(self): self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) def _get_config(self): """ Getter method for config, mapped from YANG variable /macsec/mka/policies/policy/config (container) YANG Description: Configuration of the MKA policy """ return self.__config def _set_config(self, v, load=False): """ Setter method for config, mapped from YANG variable /macsec/mka/policies/policy/config (container) If this variable is read-only (config: false) in the source YANG file, then _set_config is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_config() directly. YANG Description: Configuration of the MKA policy """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_config_openconfig_macsec__macsec_mka_policies_policy_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """config must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_policies_policy_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__config = t if hasattr(self, '_set'): self._set() def _unset_config(self): self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_policies_policy_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) def _get_state(self): """ Getter method for state, mapped from YANG variable /macsec/mka/policies/policy/state (container) YANG Description: Operational state data for MKA policy """ return self.__state def _set_state(self, v, load=False): """ Setter method for state, mapped from YANG variable /macsec/mka/policies/policy/state (container) If this variable is read-only (config: false) in the source YANG file, then _set_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_state() directly. YANG Description: Operational state data for MKA policy """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_mka_policies_policy_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """state must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_policies_policy_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__state = t if hasattr(self, '_set'): self._set() def _unset_state(self): self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_policies_policy_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) name = __builtin__.property(_get_name, _set_name) config = __builtin__.property(_get_config, _set_config) state = __builtin__.property(_get_state, _set_state) _pyangbind_elements = OrderedDict([('name', name), ('config', config), ('state', state), ]) class yc_policies_openconfig_macsec__macsec_mka_policies(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka/policies. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Enclosing container for the list of MKA policies """ __slots__ = ('_path_helper', '_extmethods', '__policy',) _yang_name = 'policies' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__policy = YANGDynClass(base=YANGListType("name",yc_policy_openconfig_macsec__macsec_mka_policies_policy, yang_name="policy", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka', 'policies'] def _get_policy(self): """ Getter method for policy, mapped from YANG variable /macsec/mka/policies/policy (list) YANG Description: List of MKA policies """ return self.__policy def _set_policy(self, v, load=False): """ Setter method for policy, mapped from YANG variable /macsec/mka/policies/policy (list) If this variable is read-only (config: false) in the source YANG file, then _set_policy is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_policy() directly. YANG Description: List of MKA policies """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("name",yc_policy_openconfig_macsec__macsec_mka_policies_policy, yang_name="policy", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """policy must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("name",yc_policy_openconfig_macsec__macsec_mka_policies_policy, yang_name="policy", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)""", }) self.__policy = t if hasattr(self, '_set'): self._set() def _unset_policy(self): self.__policy = YANGDynClass(base=YANGListType("name",yc_policy_openconfig_macsec__macsec_mka_policies_policy, yang_name="policy", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True) policy = __builtin__.property(_get_policy, _set_policy) _pyangbind_elements = OrderedDict([('policy', policy), ]) class yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_config(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains/key-chain/config. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Configuration of the MKA key chain """ __slots__ = ('_path_helper', '_extmethods', '__name',) _yang_name = 'config' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka', 'key-chains', 'key-chain', 'config'] def _get_name(self): """ Getter method for name, mapped from YANG variable /macsec/mka/key_chains/key_chain/config/name (string) YANG Description: MKA Key-chain name """ return self.__name def _set_name(self, v, load=False): """ Setter method for name, mapped from YANG variable /macsec/mka/key_chains/key_chain/config/name (string) If this variable is read-only (config: false) in the source YANG file, then _set_name is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_name() directly. YANG Description: MKA Key-chain name """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """name must be of a type compatible with string""", 'defined-type': "string", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True)""", }) self.__name = t if hasattr(self, '_set'): self._set() def _unset_name(self): self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True) name = __builtin__.property(_get_name, _set_name) _pyangbind_elements = OrderedDict([('name', name), ]) class yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_state(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains/key-chain/state. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Operational state data for MKA key chain """ __slots__ = ('_path_helper', '_extmethods', '__name',) _yang_name = 'state' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka', 'key-chains', 'key-chain', 'state'] def _get_name(self): """ Getter method for name, mapped from YANG variable /macsec/mka/key_chains/key_chain/state/name (string) YANG Description: MKA Key-chain name """ return self.__name def _set_name(self, v, load=False): """ Setter method for name, mapped from YANG variable /macsec/mka/key_chains/key_chain/state/name (string) If this variable is read-only (config: false) in the source YANG file, then _set_name is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_name() directly. YANG Description: MKA Key-chain name """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """name must be of a type compatible with string""", 'defined-type': "string", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)""", }) self.__name = t if hasattr(self, '_set'): self._set() def _unset_name(self): self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False) name = __builtin__.property(_get_name) _pyangbind_elements = OrderedDict([('name', name), ]) class yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_config(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains/key-chain/mka-keys/mka-key/config. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Configuration of MKA key """ __slots__ = ('_path_helper', '_extmethods', '__id','__key_clear_text','__cryptographic_algorithm','__valid_date_time','__expiration_date_time',) _yang_name = 'config' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__id = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=True) self.__key_clear_text = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True) self.__cryptographic_algorithm = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=True) self.__valid_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True) self.__expiration_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka', 'key-chains', 'key-chain', 'mka-keys', 'mka-key', 'config'] def _get_id(self): """ Getter method for id, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/id (oc-yang:hex-string) YANG Description: Key identifier is used as the Connectivity Association Key name (CKN) """ return self.__id def _set_id(self, v, load=False): """ Setter method for id, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/id (oc-yang:hex-string) If this variable is read-only (config: false) in the source YANG file, then _set_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_id() directly. YANG Description: Key identifier is used as the Connectivity Association Key name (CKN) """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """id must be of a type compatible with oc-yang:hex-string""", 'defined-type': "oc-yang:hex-string", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=True)""", }) self.__id = t if hasattr(self, '_set'): self._set() def _unset_id(self): self.__id = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=True) def _get_key_clear_text(self): """ Getter method for key_clear_text, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/key_clear_text (string) YANG Description: The key, used for signing and encrypting. Supplied as a clear text string. When read, also returned as clear text string. """ return self.__key_clear_text def _set_key_clear_text(self, v, load=False): """ Setter method for key_clear_text, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/key_clear_text (string) If this variable is read-only (config: false) in the source YANG file, then _set_key_clear_text is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_key_clear_text() directly. YANG Description: The key, used for signing and encrypting. Supplied as a clear text string. When read, also returned as clear text string. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """key_clear_text must be of a type compatible with string""", 'defined-type': "string", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True)""", }) self.__key_clear_text = t if hasattr(self, '_set'): self._set() def _unset_key_clear_text(self): self.__key_clear_text = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True) def _get_cryptographic_algorithm(self): """ Getter method for cryptographic_algorithm, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/cryptographic_algorithm (enumeration) YANG Description: MKA Cryptographic authentication algorithm to use """ return self.__cryptographic_algorithm def _set_cryptographic_algorithm(self, v, load=False): """ Setter method for cryptographic_algorithm, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/cryptographic_algorithm (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_cryptographic_algorithm is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_cryptographic_algorithm() directly. YANG Description: MKA Cryptographic authentication algorithm to use """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """cryptographic_algorithm must be of a type compatible with enumeration""", 'defined-type': "openconfig-macsec:enumeration", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=True)""", }) self.__cryptographic_algorithm = t if hasattr(self, '_set'): self._set() def _unset_cryptographic_algorithm(self): self.__cryptographic_algorithm = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=True) def _get_valid_date_time(self): """ Getter method for valid_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/valid_date_time (union) YANG Description: Date and time the key starts being valid according to local date and time configuration. """ return self.__valid_date_time def _set_valid_date_time(self, v, load=False): """ Setter method for valid_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/valid_date_time (union) If this variable is read-only (config: false) in the source YANG file, then _set_valid_date_time is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_valid_date_time() directly. YANG Description: Date and time the key starts being valid according to local date and time configuration. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """valid_date_time must be of a type compatible with union""", 'defined-type': "openconfig-macsec:union", 'generated-type': """YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True)""", }) self.__valid_date_time = t if hasattr(self, '_set'): self._set() def _unset_valid_date_time(self): self.__valid_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True) def _get_expiration_date_time(self): """ Getter method for expiration_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/expiration_date_time (union) YANG Description: Key date and time expiration according to local date and time configuration. """ return self.__expiration_date_time def _set_expiration_date_time(self, v, load=False): """ Setter method for expiration_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/expiration_date_time (union) If this variable is read-only (config: false) in the source YANG file, then _set_expiration_date_time is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_expiration_date_time() directly. YANG Description: Key date and time expiration according to local date and time configuration. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """expiration_date_time must be of a type compatible with union""", 'defined-type': "openconfig-macsec:union", 'generated-type': """YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True)""", }) self.__expiration_date_time = t if hasattr(self, '_set'): self._set() def _unset_expiration_date_time(self): self.__expiration_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True) id = __builtin__.property(_get_id, _set_id) key_clear_text = __builtin__.property(_get_key_clear_text, _set_key_clear_text) cryptographic_algorithm = __builtin__.property(_get_cryptographic_algorithm, _set_cryptographic_algorithm) valid_date_time = __builtin__.property(_get_valid_date_time, _set_valid_date_time) expiration_date_time = __builtin__.property(_get_expiration_date_time, _set_expiration_date_time) _pyangbind_elements = OrderedDict([('id', id), ('key_clear_text', key_clear_text), ('cryptographic_algorithm', cryptographic_algorithm), ('valid_date_time', valid_date_time), ('expiration_date_time', expiration_date_time), ]) class yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_state(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains/key-chain/mka-keys/mka-key/state. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Operational state data for MKA key """ __slots__ = ('_path_helper', '_extmethods', '__id','__key_clear_text','__cryptographic_algorithm','__valid_date_time','__expiration_date_time',) _yang_name = 'state' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__id = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False) self.__key_clear_text = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False) self.__cryptographic_algorithm = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=False) self.__valid_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False) self.__expiration_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka', 'key-chains', 'key-chain', 'mka-keys', 'mka-key', 'state'] def _get_id(self): """ Getter method for id, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/id (oc-yang:hex-string) YANG Description: Key identifier is used as the Connectivity Association Key name (CKN) """ return self.__id def _set_id(self, v, load=False): """ Setter method for id, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/id (oc-yang:hex-string) If this variable is read-only (config: false) in the source YANG file, then _set_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_id() directly. YANG Description: Key identifier is used as the Connectivity Association Key name (CKN) """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """id must be of a type compatible with oc-yang:hex-string""", 'defined-type': "oc-yang:hex-string", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)""", }) self.__id = t if hasattr(self, '_set'): self._set() def _unset_id(self): self.__id = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False) def _get_key_clear_text(self): """ Getter method for key_clear_text, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/key_clear_text (string) YANG Description: The key, used for signing and encrypting. Supplied as a clear text string. When read, also returned as clear text string. """ return self.__key_clear_text def _set_key_clear_text(self, v, load=False): """ Setter method for key_clear_text, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/key_clear_text (string) If this variable is read-only (config: false) in the source YANG file, then _set_key_clear_text is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_key_clear_text() directly. YANG Description: The key, used for signing and encrypting. Supplied as a clear text string. When read, also returned as clear text string. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """key_clear_text must be of a type compatible with string""", 'defined-type': "string", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)""", }) self.__key_clear_text = t if hasattr(self, '_set'): self._set() def _unset_key_clear_text(self): self.__key_clear_text = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False) def _get_cryptographic_algorithm(self): """ Getter method for cryptographic_algorithm, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/cryptographic_algorithm (enumeration) YANG Description: MKA Cryptographic authentication algorithm to use """ return self.__cryptographic_algorithm def _set_cryptographic_algorithm(self, v, load=False): """ Setter method for cryptographic_algorithm, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/cryptographic_algorithm (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_cryptographic_algorithm is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_cryptographic_algorithm() directly. YANG Description: MKA Cryptographic authentication algorithm to use """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """cryptographic_algorithm must be of a type compatible with enumeration""", 'defined-type': "openconfig-macsec:enumeration", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=False)""", }) self.__cryptographic_algorithm = t if hasattr(self, '_set'): self._set() def _unset_cryptographic_algorithm(self): self.__cryptographic_algorithm = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=False) def _get_valid_date_time(self): """ Getter method for valid_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/valid_date_time (union) YANG Description: Date and time the key starts being valid according to local date and time configuration. """ return self.__valid_date_time def _set_valid_date_time(self, v, load=False): """ Setter method for valid_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/valid_date_time (union) If this variable is read-only (config: false) in the source YANG file, then _set_valid_date_time is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_valid_date_time() directly. YANG Description: Date and time the key starts being valid according to local date and time configuration. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """valid_date_time must be of a type compatible with union""", 'defined-type': "openconfig-macsec:union", 'generated-type': """YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False)""", }) self.__valid_date_time = t if hasattr(self, '_set'): self._set() def _unset_valid_date_time(self): self.__valid_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False) def _get_expiration_date_time(self): """ Getter method for expiration_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/expiration_date_time (union) YANG Description: Key date and time expiration according to local date and time configuration. """ return self.__expiration_date_time def _set_expiration_date_time(self, v, load=False): """ Setter method for expiration_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/expiration_date_time (union) If this variable is read-only (config: false) in the source YANG file, then _set_expiration_date_time is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_expiration_date_time() directly. YANG Description: Key date and time expiration according to local date and time configuration. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """expiration_date_time must be of a type compatible with union""", 'defined-type': "openconfig-macsec:union", 'generated-type': """YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False)""", }) self.__expiration_date_time = t if hasattr(self, '_set'): self._set() def _unset_expiration_date_time(self): self.__expiration_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False) id = __builtin__.property(_get_id) key_clear_text = __builtin__.property(_get_key_clear_text) cryptographic_algorithm = __builtin__.property(_get_cryptographic_algorithm) valid_date_time = __builtin__.property(_get_valid_date_time) expiration_date_time = __builtin__.property(_get_expiration_date_time) _pyangbind_elements = OrderedDict([('id', id), ('key_clear_text', key_clear_text), ('cryptographic_algorithm', cryptographic_algorithm), ('valid_date_time', valid_date_time), ('expiration_date_time', expiration_date_time), ]) class yc_mka_key_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains/key-chain/mka-keys/mka-key. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: List of MKA keys """ __slots__ = ('_path_helper', '_extmethods', '__id','__config','__state',) _yang_name = 'mka-key' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__id = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka', 'key-chains', 'key-chain', 'mka-keys', 'mka-key'] def _get_id(self): """ Getter method for id, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/id (leafref) YANG Description: Reference to the MKA key id """ return self.__id def _set_id(self, v, load=False): """ Setter method for id, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/id (leafref) If this variable is read-only (config: false) in the source YANG file, then _set_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_id() directly. YANG Description: Reference to the MKA key id """ parent = getattr(self, "_parent", None) if parent is not None and load is False: raise AttributeError("Cannot set keys directly when" + " within an instantiated list") if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """id must be of a type compatible with leafref""", 'defined-type': "leafref", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)""", }) self.__id = t if hasattr(self, '_set'): self._set() def _unset_id(self): self.__id = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) def _get_config(self): """ Getter method for config, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config (container) YANG Description: Configuration of MKA key """ return self.__config def _set_config(self, v, load=False): """ Setter method for config, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config (container) If this variable is read-only (config: false) in the source YANG file, then _set_config is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_config() directly. YANG Description: Configuration of MKA key """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """config must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__config = t if hasattr(self, '_set'): self._set() def _unset_config(self): self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) def _get_state(self): """ Getter method for state, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state (container) YANG Description: Operational state data for MKA key """ return self.__state def _set_state(self, v, load=False): """ Setter method for state, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state (container) If this variable is read-only (config: false) in the source YANG file, then _set_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_state() directly. YANG Description: Operational state data for MKA key """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """state must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__state = t if hasattr(self, '_set'): self._set() def _unset_state(self): self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) id = __builtin__.property(_get_id, _set_id) config = __builtin__.property(_get_config, _set_config) state = __builtin__.property(_get_state, _set_state) _pyangbind_elements = OrderedDict([('id', id), ('config', config), ('state', state), ]) class yc_mka_keys_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains/key-chain/mka-keys. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Enclosing container for the list of MKA keys """ __slots__ = ('_path_helper', '_extmethods', '__mka_key',) _yang_name = 'mka-keys' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__mka_key = YANGDynClass(base=YANGListType("id",yc_mka_key_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key, yang_name="mka-key", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='id', extensions=None), is_container='list', yang_name="mka-key", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka', 'key-chains', 'key-chain', 'mka-keys'] def _get_mka_key(self): """ Getter method for mka_key, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key (list) YANG Description: List of MKA keys """ return self.__mka_key def _set_mka_key(self, v, load=False): """ Setter method for mka_key, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key (list) If this variable is read-only (config: false) in the source YANG file, then _set_mka_key is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_mka_key() directly. YANG Description: List of MKA keys """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("id",yc_mka_key_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key, yang_name="mka-key", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='id', extensions=None), is_container='list', yang_name="mka-key", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """mka_key must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("id",yc_mka_key_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key, yang_name="mka-key", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='id', extensions=None), is_container='list', yang_name="mka-key", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)""", }) self.__mka_key = t if hasattr(self, '_set'): self._set() def _unset_mka_key(self): self.__mka_key = YANGDynClass(base=YANGListType("id",yc_mka_key_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key, yang_name="mka-key", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='id', extensions=None), is_container='list', yang_name="mka-key", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True) mka_key = __builtin__.property(_get_mka_key, _set_mka_key) _pyangbind_elements = OrderedDict([('mka_key', mka_key), ]) class yc_key_chain_openconfig_macsec__macsec_mka_key_chains_key_chain(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains/key-chain. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: MKA Key chain name """ __slots__ = ('_path_helper', '_extmethods', '__name','__config','__state','__mka_keys',) _yang_name = 'key-chain' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) self.__mka_keys = YANGDynClass(base=yc_mka_keys_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys, is_container='container', yang_name="mka-keys", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka', 'key-chains', 'key-chain'] def _get_name(self): """ Getter method for name, mapped from YANG variable /macsec/mka/key_chains/key_chain/name (leafref) YANG Description: Reference to the MKA Key chain name """ return self.__name def _set_name(self, v, load=False): """ Setter method for name, mapped from YANG variable /macsec/mka/key_chains/key_chain/name (leafref) If this variable is read-only (config: false) in the source YANG file, then _set_name is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_name() directly. YANG Description: Reference to the MKA Key chain name """ parent = getattr(self, "_parent", None) if parent is not None and load is False: raise AttributeError("Cannot set keys directly when" + " within an instantiated list") if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """name must be of a type compatible with leafref""", 'defined-type': "leafref", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)""", }) self.__name = t if hasattr(self, '_set'): self._set() def _unset_name(self): self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) def _get_config(self): """ Getter method for config, mapped from YANG variable /macsec/mka/key_chains/key_chain/config (container) YANG Description: Configuration of the MKA key chain """ return self.__config def _set_config(self, v, load=False): """ Setter method for config, mapped from YANG variable /macsec/mka/key_chains/key_chain/config (container) If this variable is read-only (config: false) in the source YANG file, then _set_config is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_config() directly. YANG Description: Configuration of the MKA key chain """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """config must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__config = t if hasattr(self, '_set'): self._set() def _unset_config(self): self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) def _get_state(self): """ Getter method for state, mapped from YANG variable /macsec/mka/key_chains/key_chain/state (container) YANG Description: Operational state data for MKA key chain """ return self.__state def _set_state(self, v, load=False): """ Setter method for state, mapped from YANG variable /macsec/mka/key_chains/key_chain/state (container) If this variable is read-only (config: false) in the source YANG file, then _set_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_state() directly. YANG Description: Operational state data for MKA key chain """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """state must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__state = t if hasattr(self, '_set'): self._set() def _unset_state(self): self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) def _get_mka_keys(self): """ Getter method for mka_keys, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys (container) YANG Description: Enclosing container for the list of MKA keys """ return self.__mka_keys def _set_mka_keys(self, v, load=False): """ Setter method for mka_keys, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys (container) If this variable is read-only (config: false) in the source YANG file, then _set_mka_keys is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_mka_keys() directly. YANG Description: Enclosing container for the list of MKA keys """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_mka_keys_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys, is_container='container', yang_name="mka-keys", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """mka_keys must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_mka_keys_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys, is_container='container', yang_name="mka-keys", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__mka_keys = t if hasattr(self, '_set'): self._set() def _unset_mka_keys(self): self.__mka_keys = YANGDynClass(base=yc_mka_keys_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys, is_container='container', yang_name="mka-keys", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) name = __builtin__.property(_get_name, _set_name) config = __builtin__.property(_get_config, _set_config) state = __builtin__.property(_get_state, _set_state) mka_keys = __builtin__.property(_get_mka_keys, _set_mka_keys) _pyangbind_elements = OrderedDict([('name', name), ('config', config), ('state', state), ('mka_keys', mka_keys), ]) class yc_key_chains_openconfig_macsec__macsec_mka_key_chains(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Enclosing container for the MKA key chains """ __slots__ = ('_path_helper', '_extmethods', '__key_chain',) _yang_name = 'key-chains' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__key_chain = YANGDynClass(base=YANGListType("name",yc_key_chain_openconfig_macsec__macsec_mka_key_chains_key_chain, yang_name="key-chain", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka', 'key-chains'] def _get_key_chain(self): """ Getter method for key_chain, mapped from YANG variable /macsec/mka/key_chains/key_chain (list) YANG Description: MKA Key chain name """ return self.__key_chain def _set_key_chain(self, v, load=False): """ Setter method for key_chain, mapped from YANG variable /macsec/mka/key_chains/key_chain (list) If this variable is read-only (config: false) in the source YANG file, then _set_key_chain is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_key_chain() directly. YANG Description: MKA Key chain name """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("name",yc_key_chain_openconfig_macsec__macsec_mka_key_chains_key_chain, yang_name="key-chain", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """key_chain must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("name",yc_key_chain_openconfig_macsec__macsec_mka_key_chains_key_chain, yang_name="key-chain", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)""", }) self.__key_chain = t if hasattr(self, '_set'): self._set() def _unset_key_chain(self): self.__key_chain = YANGDynClass(base=YANGListType("name",yc_key_chain_openconfig_macsec__macsec_mka_key_chains_key_chain, yang_name="key-chain", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True) key_chain = __builtin__.property(_get_key_chain, _set_key_chain) _pyangbind_elements = OrderedDict([('key_chain', key_chain), ]) class yc_counters_openconfig_macsec__macsec_mka_state_counters(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka/state/counters. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: MKA global counters """ __slots__ = ('_path_helper', '_extmethods', '__out_mkpdu_errors','__in_mkpdu_icv_verification_errors','__in_mkpdu_validation_errors','__in_mkpdu_bad_peer_errors','__in_mkpdu_peer_list_errors','__sak_generation_errors','__sak_hash_errors','__sak_encryption_errors','__sak_decryption_errors','__sak_cipher_mismatch_errors',) _yang_name = 'counters' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__out_mkpdu_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__in_mkpdu_icv_verification_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-icv-verification-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__in_mkpdu_validation_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-validation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__in_mkpdu_bad_peer_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-bad-peer-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__in_mkpdu_peer_list_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-peer-list-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__sak_generation_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-generation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__sak_hash_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-hash-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__sak_encryption_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-encryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__sak_decryption_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-decryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__sak_cipher_mismatch_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-cipher-mismatch-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka', 'state', 'counters'] def _get_out_mkpdu_errors(self): """ Getter method for out_mkpdu_errors, mapped from YANG variable /macsec/mka/state/counters/out_mkpdu_errors (oc-yang:counter64) YANG Description: MKPDU TX error count """ return self.__out_mkpdu_errors def _set_out_mkpdu_errors(self, v, load=False): """ Setter method for out_mkpdu_errors, mapped from YANG variable /macsec/mka/state/counters/out_mkpdu_errors (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_out_mkpdu_errors is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_out_mkpdu_errors() directly. YANG Description: MKPDU TX error count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """out_mkpdu_errors must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__out_mkpdu_errors = t if hasattr(self, '_set'): self._set() def _unset_out_mkpdu_errors(self): self.__out_mkpdu_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_in_mkpdu_icv_verification_errors(self): """ Getter method for in_mkpdu_icv_verification_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_icv_verification_errors (oc-yang:counter64) YANG Description: MKPDU RX ICV verification error count """ return self.__in_mkpdu_icv_verification_errors def _set_in_mkpdu_icv_verification_errors(self, v, load=False): """ Setter method for in_mkpdu_icv_verification_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_icv_verification_errors (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_in_mkpdu_icv_verification_errors is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_in_mkpdu_icv_verification_errors() directly. YANG Description: MKPDU RX ICV verification error count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-icv-verification-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """in_mkpdu_icv_verification_errors must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-icv-verification-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__in_mkpdu_icv_verification_errors = t if hasattr(self, '_set'): self._set() def _unset_in_mkpdu_icv_verification_errors(self): self.__in_mkpdu_icv_verification_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-icv-verification-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_in_mkpdu_validation_errors(self): """ Getter method for in_mkpdu_validation_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_validation_errors (oc-yang:counter64) YANG Description: MKPDU RX validation error count """ return self.__in_mkpdu_validation_errors def _set_in_mkpdu_validation_errors(self, v, load=False): """ Setter method for in_mkpdu_validation_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_validation_errors (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_in_mkpdu_validation_errors is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_in_mkpdu_validation_errors() directly. YANG Description: MKPDU RX validation error count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-validation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """in_mkpdu_validation_errors must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-validation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__in_mkpdu_validation_errors = t if hasattr(self, '_set'): self._set() def _unset_in_mkpdu_validation_errors(self): self.__in_mkpdu_validation_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-validation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_in_mkpdu_bad_peer_errors(self): """ Getter method for in_mkpdu_bad_peer_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_bad_peer_errors (oc-yang:counter64) YANG Description: MKPDU RX bad peer message number error count """ return self.__in_mkpdu_bad_peer_errors def _set_in_mkpdu_bad_peer_errors(self, v, load=False): """ Setter method for in_mkpdu_bad_peer_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_bad_peer_errors (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_in_mkpdu_bad_peer_errors is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_in_mkpdu_bad_peer_errors() directly. YANG Description: MKPDU RX bad peer message number error count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-bad-peer-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """in_mkpdu_bad_peer_errors must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-bad-peer-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__in_mkpdu_bad_peer_errors = t if hasattr(self, '_set'): self._set() def _unset_in_mkpdu_bad_peer_errors(self): self.__in_mkpdu_bad_peer_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-bad-peer-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_in_mkpdu_peer_list_errors(self): """ Getter method for in_mkpdu_peer_list_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_peer_list_errors (oc-yang:counter64) YANG Description: MKPDU RX non-recent peer list Message Number error count """ return self.__in_mkpdu_peer_list_errors def _set_in_mkpdu_peer_list_errors(self, v, load=False): """ Setter method for in_mkpdu_peer_list_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_peer_list_errors (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_in_mkpdu_peer_list_errors is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_in_mkpdu_peer_list_errors() directly. YANG Description: MKPDU RX non-recent peer list Message Number error count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-peer-list-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """in_mkpdu_peer_list_errors must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-peer-list-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__in_mkpdu_peer_list_errors = t if hasattr(self, '_set'): self._set() def _unset_in_mkpdu_peer_list_errors(self): self.__in_mkpdu_peer_list_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-peer-list-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_sak_generation_errors(self): """ Getter method for sak_generation_errors, mapped from YANG variable /macsec/mka/state/counters/sak_generation_errors (oc-yang:counter64) YANG Description: MKA error SAK generation count """ return self.__sak_generation_errors def _set_sak_generation_errors(self, v, load=False): """ Setter method for sak_generation_errors, mapped from YANG variable /macsec/mka/state/counters/sak_generation_errors (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_sak_generation_errors is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sak_generation_errors() directly. YANG Description: MKA error SAK generation count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-generation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sak_generation_errors must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-generation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__sak_generation_errors = t if hasattr(self, '_set'): self._set() def _unset_sak_generation_errors(self): self.__sak_generation_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-generation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_sak_hash_errors(self): """ Getter method for sak_hash_errors, mapped from YANG variable /macsec/mka/state/counters/sak_hash_errors (oc-yang:counter64) YANG Description: MKA error Hash Key generation count """ return self.__sak_hash_errors def _set_sak_hash_errors(self, v, load=False): """ Setter method for sak_hash_errors, mapped from YANG variable /macsec/mka/state/counters/sak_hash_errors (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_sak_hash_errors is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sak_hash_errors() directly. YANG Description: MKA error Hash Key generation count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-hash-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sak_hash_errors must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-hash-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__sak_hash_errors = t if hasattr(self, '_set'): self._set() def _unset_sak_hash_errors(self): self.__sak_hash_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-hash-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_sak_encryption_errors(self): """ Getter method for sak_encryption_errors, mapped from YANG variable /macsec/mka/state/counters/sak_encryption_errors (oc-yang:counter64) YANG Description: MKA error SAK encryption/wrap count """ return self.__sak_encryption_errors def _set_sak_encryption_errors(self, v, load=False): """ Setter method for sak_encryption_errors, mapped from YANG variable /macsec/mka/state/counters/sak_encryption_errors (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_sak_encryption_errors is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sak_encryption_errors() directly. YANG Description: MKA error SAK encryption/wrap count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-encryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sak_encryption_errors must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-encryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__sak_encryption_errors = t if hasattr(self, '_set'): self._set() def _unset_sak_encryption_errors(self): self.__sak_encryption_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-encryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_sak_decryption_errors(self): """ Getter method for sak_decryption_errors, mapped from YANG variable /macsec/mka/state/counters/sak_decryption_errors (oc-yang:counter64) YANG Description: MKA error SAK decryption/unwrap count """ return self.__sak_decryption_errors def _set_sak_decryption_errors(self, v, load=False): """ Setter method for sak_decryption_errors, mapped from YANG variable /macsec/mka/state/counters/sak_decryption_errors (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_sak_decryption_errors is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sak_decryption_errors() directly. YANG Description: MKA error SAK decryption/unwrap count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-decryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sak_decryption_errors must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-decryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__sak_decryption_errors = t if hasattr(self, '_set'): self._set() def _unset_sak_decryption_errors(self): self.__sak_decryption_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-decryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_sak_cipher_mismatch_errors(self): """ Getter method for sak_cipher_mismatch_errors, mapped from YANG variable /macsec/mka/state/counters/sak_cipher_mismatch_errors (oc-yang:counter64) YANG Description: MKA error SAK cipher mismatch count """ return self.__sak_cipher_mismatch_errors def _set_sak_cipher_mismatch_errors(self, v, load=False): """ Setter method for sak_cipher_mismatch_errors, mapped from YANG variable /macsec/mka/state/counters/sak_cipher_mismatch_errors (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_sak_cipher_mismatch_errors is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sak_cipher_mismatch_errors() directly. YANG Description: MKA error SAK cipher mismatch count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-cipher-mismatch-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sak_cipher_mismatch_errors must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-cipher-mismatch-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__sak_cipher_mismatch_errors = t if hasattr(self, '_set'): self._set() def _unset_sak_cipher_mismatch_errors(self): self.__sak_cipher_mismatch_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-cipher-mismatch-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) out_mkpdu_errors = __builtin__.property(_get_out_mkpdu_errors) in_mkpdu_icv_verification_errors = __builtin__.property(_get_in_mkpdu_icv_verification_errors) in_mkpdu_validation_errors = __builtin__.property(_get_in_mkpdu_validation_errors) in_mkpdu_bad_peer_errors = __builtin__.property(_get_in_mkpdu_bad_peer_errors) in_mkpdu_peer_list_errors = __builtin__.property(_get_in_mkpdu_peer_list_errors) sak_generation_errors = __builtin__.property(_get_sak_generation_errors) sak_hash_errors = __builtin__.property(_get_sak_hash_errors) sak_encryption_errors = __builtin__.property(_get_sak_encryption_errors) sak_decryption_errors = __builtin__.property(_get_sak_decryption_errors) sak_cipher_mismatch_errors = __builtin__.property(_get_sak_cipher_mismatch_errors) _pyangbind_elements = OrderedDict([('out_mkpdu_errors', out_mkpdu_errors), ('in_mkpdu_icv_verification_errors', in_mkpdu_icv_verification_errors), ('in_mkpdu_validation_errors', in_mkpdu_validation_errors), ('in_mkpdu_bad_peer_errors', in_mkpdu_bad_peer_errors), ('in_mkpdu_peer_list_errors', in_mkpdu_peer_list_errors), ('sak_generation_errors', sak_generation_errors), ('sak_hash_errors', sak_hash_errors), ('sak_encryption_errors', sak_encryption_errors), ('sak_decryption_errors', sak_decryption_errors), ('sak_cipher_mismatch_errors', sak_cipher_mismatch_errors), ]) class yc_state_openconfig_macsec__macsec_mka_state(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka/state. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Operational state data for MKA """ __slots__ = ('_path_helper', '_extmethods', '__counters',) _yang_name = 'state' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka', 'state'] def _get_counters(self): """ Getter method for counters, mapped from YANG variable /macsec/mka/state/counters (container) YANG Description: MKA global counters """ return self.__counters def _set_counters(self, v, load=False): """ Setter method for counters, mapped from YANG variable /macsec/mka/state/counters (container) If this variable is read-only (config: false) in the source YANG file, then _set_counters is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_counters() directly. YANG Description: MKA global counters """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_counters_openconfig_macsec__macsec_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """counters must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_counters_openconfig_macsec__macsec_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)""", }) self.__counters = t if hasattr(self, '_set'): self._set() def _unset_counters(self): self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) counters = __builtin__.property(_get_counters) _pyangbind_elements = OrderedDict([('counters', counters), ]) class yc_mka_openconfig_macsec__macsec_mka(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/mka. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: The MKA """ __slots__ = ('_path_helper', '_extmethods', '__policies','__key_chains','__state',) _yang_name = 'mka' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__policies = YANGDynClass(base=yc_policies_openconfig_macsec__macsec_mka_policies, is_container='container', yang_name="policies", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) self.__key_chains = YANGDynClass(base=yc_key_chains_openconfig_macsec__macsec_mka_key_chains, is_container='container', yang_name="key-chains", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'mka'] def _get_policies(self): """ Getter method for policies, mapped from YANG variable /macsec/mka/policies (container) YANG Description: Enclosing container for the list of MKA policies """ return self.__policies def _set_policies(self, v, load=False): """ Setter method for policies, mapped from YANG variable /macsec/mka/policies (container) If this variable is read-only (config: false) in the source YANG file, then _set_policies is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_policies() directly. YANG Description: Enclosing container for the list of MKA policies """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_policies_openconfig_macsec__macsec_mka_policies, is_container='container', yang_name="policies", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """policies must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_policies_openconfig_macsec__macsec_mka_policies, is_container='container', yang_name="policies", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__policies = t if hasattr(self, '_set'): self._set() def _unset_policies(self): self.__policies = YANGDynClass(base=yc_policies_openconfig_macsec__macsec_mka_policies, is_container='container', yang_name="policies", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) def _get_key_chains(self): """ Getter method for key_chains, mapped from YANG variable /macsec/mka/key_chains (container) YANG Description: Enclosing container for the MKA key chains """ return self.__key_chains def _set_key_chains(self, v, load=False): """ Setter method for key_chains, mapped from YANG variable /macsec/mka/key_chains (container) If this variable is read-only (config: false) in the source YANG file, then _set_key_chains is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_key_chains() directly. YANG Description: Enclosing container for the MKA key chains """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_key_chains_openconfig_macsec__macsec_mka_key_chains, is_container='container', yang_name="key-chains", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """key_chains must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_key_chains_openconfig_macsec__macsec_mka_key_chains, is_container='container', yang_name="key-chains", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__key_chains = t if hasattr(self, '_set'): self._set() def _unset_key_chains(self): self.__key_chains = YANGDynClass(base=yc_key_chains_openconfig_macsec__macsec_mka_key_chains, is_container='container', yang_name="key-chains", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) def _get_state(self): """ Getter method for state, mapped from YANG variable /macsec/mka/state (container) YANG Description: Operational state data for MKA """ return self.__state def _set_state(self, v, load=False): """ Setter method for state, mapped from YANG variable /macsec/mka/state (container) If this variable is read-only (config: false) in the source YANG file, then _set_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_state() directly. YANG Description: Operational state data for MKA """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """state must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__state = t if hasattr(self, '_set'): self._set() def _unset_state(self): self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) policies = __builtin__.property(_get_policies, _set_policies) key_chains = __builtin__.property(_get_key_chains, _set_key_chains) state = __builtin__.property(_get_state, _set_state) _pyangbind_elements = OrderedDict([('policies', policies), ('key_chains', key_chains), ('state', state), ]) class yc_config_openconfig_macsec__macsec_interfaces_interface_config(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/config. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Configuration data for MACsec on each interface """ __slots__ = ('_path_helper', '_extmethods', '__name','__enable','__replay_protection',) _yang_name = 'config' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=True) self.__enable = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) self.__replay_protection = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'config'] def _get_name(self): """ Getter method for name, mapped from YANG variable /macsec/interfaces/interface/config/name (oc-if:base-interface-ref) YANG Description: Reference to the MACsec Ethernet interface """ return self.__name def _set_name(self, v, load=False): """ Setter method for name, mapped from YANG variable /macsec/interfaces/interface/config/name (oc-if:base-interface-ref) If this variable is read-only (config: false) in the source YANG file, then _set_name is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_name() directly. YANG Description: Reference to the MACsec Ethernet interface """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """name must be of a type compatible with oc-if:base-interface-ref""", 'defined-type': "oc-if:base-interface-ref", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=True)""", }) self.__name = t if hasattr(self, '_set'): self._set() def _unset_name(self): self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=True) def _get_enable(self): """ Getter method for enable, mapped from YANG variable /macsec/interfaces/interface/config/enable (boolean) YANG Description: Enable MACsec on an interface """ return self.__enable def _set_enable(self, v, load=False): """ Setter method for enable, mapped from YANG variable /macsec/interfaces/interface/config/enable (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_enable is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_enable() directly. YANG Description: Enable MACsec on an interface """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """enable must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)""", }) self.__enable = t if hasattr(self, '_set'): self._set() def _unset_enable(self): self.__enable = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True) def _get_replay_protection(self): """ Getter method for replay_protection, mapped from YANG variable /macsec/interfaces/interface/config/replay_protection (uint16) YANG Description: MACsec window size, as defined by the number of out-of-order frames that are accepted. A value of 0 means that frames are accepted only in the correct order. """ return self.__replay_protection def _set_replay_protection(self, v, load=False): """ Setter method for replay_protection, mapped from YANG variable /macsec/interfaces/interface/config/replay_protection (uint16) If this variable is read-only (config: false) in the source YANG file, then _set_replay_protection is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_replay_protection() directly. YANG Description: MACsec window size, as defined by the number of out-of-order frames that are accepted. A value of 0 means that frames are accepted only in the correct order. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """replay_protection must be of a type compatible with uint16""", 'defined-type': "uint16", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=True)""", }) self.__replay_protection = t if hasattr(self, '_set'): self._set() def _unset_replay_protection(self): self.__replay_protection = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=True) name = __builtin__.property(_get_name, _set_name) enable = __builtin__.property(_get_enable, _set_enable) replay_protection = __builtin__.property(_get_replay_protection, _set_replay_protection) _pyangbind_elements = OrderedDict([('name', name), ('enable', enable), ('replay_protection', replay_protection), ]) class yc_counters_openconfig_macsec__macsec_interfaces_interface_state_counters(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/state/counters. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: MACsec interface counters """ __slots__ = ('_path_helper', '_extmethods', '__tx_untagged_pkts','__rx_untagged_pkts','__rx_badtag_pkts','__rx_unknownsci_pkts','__rx_nosci_pkts',) _yang_name = 'counters' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__tx_untagged_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__rx_untagged_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__rx_badtag_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-badtag-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__rx_unknownsci_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-unknownsci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__rx_nosci_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-nosci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'state', 'counters'] def _get_tx_untagged_pkts(self): """ Getter method for tx_untagged_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/tx_untagged_pkts (oc-yang:counter64) YANG Description: MACsec interface level Transmit untagged Packets counter. This counter will increment if MACsec is enabled on interface and the outgoing packet is not tagged with MACsec header. """ return self.__tx_untagged_pkts def _set_tx_untagged_pkts(self, v, load=False): """ Setter method for tx_untagged_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/tx_untagged_pkts (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_tx_untagged_pkts is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_tx_untagged_pkts() directly. YANG Description: MACsec interface level Transmit untagged Packets counter. This counter will increment if MACsec is enabled on interface and the outgoing packet is not tagged with MACsec header. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """tx_untagged_pkts must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__tx_untagged_pkts = t if hasattr(self, '_set'): self._set() def _unset_tx_untagged_pkts(self): self.__tx_untagged_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_rx_untagged_pkts(self): """ Getter method for rx_untagged_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_untagged_pkts (oc-yang:counter64) YANG Description: MACsec interface level Receive untagged Packets counter. This counter will increment if MACsec is enabled on interface and the incoming packet does not have MACsec tag. """ return self.__rx_untagged_pkts def _set_rx_untagged_pkts(self, v, load=False): """ Setter method for rx_untagged_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_untagged_pkts (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_rx_untagged_pkts is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_rx_untagged_pkts() directly. YANG Description: MACsec interface level Receive untagged Packets counter. This counter will increment if MACsec is enabled on interface and the incoming packet does not have MACsec tag. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """rx_untagged_pkts must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__rx_untagged_pkts = t if hasattr(self, '_set'): self._set() def _unset_rx_untagged_pkts(self): self.__rx_untagged_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_rx_badtag_pkts(self): """ Getter method for rx_badtag_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_badtag_pkts (oc-yang:counter64) YANG Description: MACsec interface level Receive Bad Tag Packets counter. This counter will increment if MACsec is enabled on interface and incoming packet has incorrect MACsec tag. """ return self.__rx_badtag_pkts def _set_rx_badtag_pkts(self, v, load=False): """ Setter method for rx_badtag_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_badtag_pkts (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_rx_badtag_pkts is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_rx_badtag_pkts() directly. YANG Description: MACsec interface level Receive Bad Tag Packets counter. This counter will increment if MACsec is enabled on interface and incoming packet has incorrect MACsec tag. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-badtag-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """rx_badtag_pkts must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-badtag-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__rx_badtag_pkts = t if hasattr(self, '_set'): self._set() def _unset_rx_badtag_pkts(self): self.__rx_badtag_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-badtag-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_rx_unknownsci_pkts(self): """ Getter method for rx_unknownsci_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_unknownsci_pkts (oc-yang:counter64) YANG Description: MACsec interface level Receive Unknown SCI Packets counter. This counter will increment if MACsec is enabled on the interface and SCI present in the MACsec tag of the incoming packet does not match any SCI present in ingress SCI table. """ return self.__rx_unknownsci_pkts def _set_rx_unknownsci_pkts(self, v, load=False): """ Setter method for rx_unknownsci_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_unknownsci_pkts (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_rx_unknownsci_pkts is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_rx_unknownsci_pkts() directly. YANG Description: MACsec interface level Receive Unknown SCI Packets counter. This counter will increment if MACsec is enabled on the interface and SCI present in the MACsec tag of the incoming packet does not match any SCI present in ingress SCI table. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-unknownsci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """rx_unknownsci_pkts must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-unknownsci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__rx_unknownsci_pkts = t if hasattr(self, '_set'): self._set() def _unset_rx_unknownsci_pkts(self): self.__rx_unknownsci_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-unknownsci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_rx_nosci_pkts(self): """ Getter method for rx_nosci_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_nosci_pkts (oc-yang:counter64) YANG Description: MACsec interface level Receive No SCI Packets counter. This counter will increment if MACsec is enabled on interface and incoming packet does not have SCI field in MACsec tag. """ return self.__rx_nosci_pkts def _set_rx_nosci_pkts(self, v, load=False): """ Setter method for rx_nosci_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_nosci_pkts (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_rx_nosci_pkts is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_rx_nosci_pkts() directly. YANG Description: MACsec interface level Receive No SCI Packets counter. This counter will increment if MACsec is enabled on interface and incoming packet does not have SCI field in MACsec tag. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-nosci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """rx_nosci_pkts must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-nosci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__rx_nosci_pkts = t if hasattr(self, '_set'): self._set() def _unset_rx_nosci_pkts(self): self.__rx_nosci_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-nosci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) tx_untagged_pkts = __builtin__.property(_get_tx_untagged_pkts) rx_untagged_pkts = __builtin__.property(_get_rx_untagged_pkts) rx_badtag_pkts = __builtin__.property(_get_rx_badtag_pkts) rx_unknownsci_pkts = __builtin__.property(_get_rx_unknownsci_pkts) rx_nosci_pkts = __builtin__.property(_get_rx_nosci_pkts) _pyangbind_elements = OrderedDict([('tx_untagged_pkts', tx_untagged_pkts), ('rx_untagged_pkts', rx_untagged_pkts), ('rx_badtag_pkts', rx_badtag_pkts), ('rx_unknownsci_pkts', rx_unknownsci_pkts), ('rx_nosci_pkts', rx_nosci_pkts), ]) class yc_state_openconfig_macsec__macsec_interfaces_interface_state(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/state. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Operational state data """ __slots__ = ('_path_helper', '_extmethods', '__name','__enable','__replay_protection','__counters',) _yang_name = 'state' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=False) self.__enable = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) self.__replay_protection = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=False) self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'state'] def _get_name(self): """ Getter method for name, mapped from YANG variable /macsec/interfaces/interface/state/name (oc-if:base-interface-ref) YANG Description: Reference to the MACsec Ethernet interface """ return self.__name def _set_name(self, v, load=False): """ Setter method for name, mapped from YANG variable /macsec/interfaces/interface/state/name (oc-if:base-interface-ref) If this variable is read-only (config: false) in the source YANG file, then _set_name is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_name() directly. YANG Description: Reference to the MACsec Ethernet interface """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """name must be of a type compatible with oc-if:base-interface-ref""", 'defined-type': "oc-if:base-interface-ref", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=False)""", }) self.__name = t if hasattr(self, '_set'): self._set() def _unset_name(self): self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=False) def _get_enable(self): """ Getter method for enable, mapped from YANG variable /macsec/interfaces/interface/state/enable (boolean) YANG Description: Enable MACsec on an interface """ return self.__enable def _set_enable(self, v, load=False): """ Setter method for enable, mapped from YANG variable /macsec/interfaces/interface/state/enable (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_enable is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_enable() directly. YANG Description: Enable MACsec on an interface """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """enable must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)""", }) self.__enable = t if hasattr(self, '_set'): self._set() def _unset_enable(self): self.__enable = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False) def _get_replay_protection(self): """ Getter method for replay_protection, mapped from YANG variable /macsec/interfaces/interface/state/replay_protection (uint16) YANG Description: MACsec window size, as defined by the number of out-of-order frames that are accepted. A value of 0 means that frames are accepted only in the correct order. """ return self.__replay_protection def _set_replay_protection(self, v, load=False): """ Setter method for replay_protection, mapped from YANG variable /macsec/interfaces/interface/state/replay_protection (uint16) If this variable is read-only (config: false) in the source YANG file, then _set_replay_protection is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_replay_protection() directly. YANG Description: MACsec window size, as defined by the number of out-of-order frames that are accepted. A value of 0 means that frames are accepted only in the correct order. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """replay_protection must be of a type compatible with uint16""", 'defined-type': "uint16", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=False)""", }) self.__replay_protection = t if hasattr(self, '_set'): self._set() def _unset_replay_protection(self): self.__replay_protection = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=False) def _get_counters(self): """ Getter method for counters, mapped from YANG variable /macsec/interfaces/interface/state/counters (container) YANG Description: MACsec interface counters """ return self.__counters def _set_counters(self, v, load=False): """ Setter method for counters, mapped from YANG variable /macsec/interfaces/interface/state/counters (container) If this variable is read-only (config: false) in the source YANG file, then _set_counters is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_counters() directly. YANG Description: MACsec interface counters """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_counters_openconfig_macsec__macsec_interfaces_interface_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """counters must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)""", }) self.__counters = t if hasattr(self, '_set'): self._set() def _unset_counters(self): self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) name = __builtin__.property(_get_name) enable = __builtin__.property(_get_enable) replay_protection = __builtin__.property(_get_replay_protection) counters = __builtin__.property(_get_counters) _pyangbind_elements = OrderedDict([('name', name), ('enable', enable), ('replay_protection', replay_protection), ('counters', counters), ]) class yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state_counters(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-tx/scsa-tx/state/counters. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Counters container for macsec-scsa-tx-interface-stats """ __slots__ = ('_path_helper', '_extmethods', '__sc_auth_only','__sc_encrypted','__sa_auth_only','__sa_encrypted',) _yang_name = 'counters' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__sc_auth_only = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__sc_encrypted = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__sa_auth_only = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__sa_encrypted = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'scsa-tx', 'scsa-tx', 'state', 'counters'] def _get_sc_auth_only(self): """ Getter method for sc_auth_only, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sc_auth_only (oc-yang:counter64) YANG Description: Secure Channel Authenticated only TX Packets counter. This counter reflects the number of authenticated only transmitted packets in a secure channel. """ return self.__sc_auth_only def _set_sc_auth_only(self, v, load=False): """ Setter method for sc_auth_only, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sc_auth_only (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_sc_auth_only is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sc_auth_only() directly. YANG Description: Secure Channel Authenticated only TX Packets counter. This counter reflects the number of authenticated only transmitted packets in a secure channel. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sc_auth_only must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__sc_auth_only = t if hasattr(self, '_set'): self._set() def _unset_sc_auth_only(self): self.__sc_auth_only = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_sc_encrypted(self): """ Getter method for sc_encrypted, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sc_encrypted (oc-yang:counter64) YANG Description: Secure Channel Encrypted TX Packets counter. This counter reflects the number of encrypted and authenticated transmitted packets in a secure channel. """ return self.__sc_encrypted def _set_sc_encrypted(self, v, load=False): """ Setter method for sc_encrypted, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sc_encrypted (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_sc_encrypted is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sc_encrypted() directly. YANG Description: Secure Channel Encrypted TX Packets counter. This counter reflects the number of encrypted and authenticated transmitted packets in a secure channel. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sc_encrypted must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__sc_encrypted = t if hasattr(self, '_set'): self._set() def _unset_sc_encrypted(self): self.__sc_encrypted = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_sa_auth_only(self): """ Getter method for sa_auth_only, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sa_auth_only (oc-yang:counter64) YANG Description: Secure Association Authenticated only TX Packets counter. This counter reflects the number of authenticated only, transmitted packets in a secure association. """ return self.__sa_auth_only def _set_sa_auth_only(self, v, load=False): """ Setter method for sa_auth_only, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sa_auth_only (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_sa_auth_only is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sa_auth_only() directly. YANG Description: Secure Association Authenticated only TX Packets counter. This counter reflects the number of authenticated only, transmitted packets in a secure association. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sa_auth_only must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__sa_auth_only = t if hasattr(self, '_set'): self._set() def _unset_sa_auth_only(self): self.__sa_auth_only = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_sa_encrypted(self): """ Getter method for sa_encrypted, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sa_encrypted (oc-yang:counter64) YANG Description: Secure Association Encrypted TX Packets counter. This counter reflects the number of encrypted and authenticated transmitted packets in a secure association. """ return self.__sa_encrypted def _set_sa_encrypted(self, v, load=False): """ Setter method for sa_encrypted, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sa_encrypted (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_sa_encrypted is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sa_encrypted() directly. YANG Description: Secure Association Encrypted TX Packets counter. This counter reflects the number of encrypted and authenticated transmitted packets in a secure association. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sa_encrypted must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__sa_encrypted = t if hasattr(self, '_set'): self._set() def _unset_sa_encrypted(self): self.__sa_encrypted = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) sc_auth_only = __builtin__.property(_get_sc_auth_only) sc_encrypted = __builtin__.property(_get_sc_encrypted) sa_auth_only = __builtin__.property(_get_sa_auth_only) sa_encrypted = __builtin__.property(_get_sa_encrypted) _pyangbind_elements = OrderedDict([('sc_auth_only', sc_auth_only), ('sc_encrypted', sc_encrypted), ('sa_auth_only', sa_auth_only), ('sa_encrypted', sa_encrypted), ]) class yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-tx/scsa-tx/state. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: State container for macsec-scsa-tx-interface-stats """ __slots__ = ('_path_helper', '_extmethods', '__sci_tx','__counters',) _yang_name = 'state' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__sci_tx = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False) self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'scsa-tx', 'scsa-tx', 'state'] def _get_sci_tx(self): """ Getter method for sci_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/sci_tx (oc-yang:hex-string) YANG Description: Secure Channel Identifier. Every Transmit Channel is uniquely identified using this field. """ return self.__sci_tx def _set_sci_tx(self, v, load=False): """ Setter method for sci_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/sci_tx (oc-yang:hex-string) If this variable is read-only (config: false) in the source YANG file, then _set_sci_tx is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sci_tx() directly. YANG Description: Secure Channel Identifier. Every Transmit Channel is uniquely identified using this field. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sci_tx must be of a type compatible with oc-yang:hex-string""", 'defined-type': "oc-yang:hex-string", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)""", }) self.__sci_tx = t if hasattr(self, '_set'): self._set() def _unset_sci_tx(self): self.__sci_tx = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False) def _get_counters(self): """ Getter method for counters, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters (container) YANG Description: Counters container for macsec-scsa-tx-interface-stats """ return self.__counters def _set_counters(self, v, load=False): """ Setter method for counters, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters (container) If this variable is read-only (config: false) in the source YANG file, then _set_counters is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_counters() directly. YANG Description: Counters container for macsec-scsa-tx-interface-stats """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """counters must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)""", }) self.__counters = t if hasattr(self, '_set'): self._set() def _unset_counters(self): self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) sci_tx = __builtin__.property(_get_sci_tx) counters = __builtin__.property(_get_counters) _pyangbind_elements = OrderedDict([('sci_tx', sci_tx), ('counters', counters), ]) class yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-tx/scsa-tx. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: TX Secure Channel and Secure Association Statistics """ __slots__ = ('_path_helper', '_extmethods', '__sci_tx','__state',) _yang_name = 'scsa-tx' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__sci_tx = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False) self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'scsa-tx', 'scsa-tx'] def _get_sci_tx(self): """ Getter method for sci_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/sci_tx (leafref) YANG Description: TX Secure Channel and Secure Association Statistics """ return self.__sci_tx def _set_sci_tx(self, v, load=False): """ Setter method for sci_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/sci_tx (leafref) If this variable is read-only (config: false) in the source YANG file, then _set_sci_tx is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sci_tx() directly. YANG Description: TX Secure Channel and Secure Association Statistics """ parent = getattr(self, "_parent", None) if parent is not None and load is False: raise AttributeError("Cannot set keys directly when" + " within an instantiated list") if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sci_tx must be of a type compatible with leafref""", 'defined-type': "leafref", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)""", }) self.__sci_tx = t if hasattr(self, '_set'): self._set() def _unset_sci_tx(self): self.__sci_tx = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False) def _get_state(self): """ Getter method for state, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state (container) YANG Description: State container for macsec-scsa-tx-interface-stats """ return self.__state def _set_state(self, v, load=False): """ Setter method for state, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state (container) If this variable is read-only (config: false) in the source YANG file, then _set_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_state() directly. YANG Description: State container for macsec-scsa-tx-interface-stats """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """state must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)""", }) self.__state = t if hasattr(self, '_set'): self._set() def _unset_state(self): self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) sci_tx = __builtin__.property(_get_sci_tx) state = __builtin__.property(_get_state) _pyangbind_elements = OrderedDict([('sci_tx', sci_tx), ('state', state), ]) class yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-tx. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Enclosing container for transmitted packets for Secure Channel and Secure Association """ __slots__ = ('_path_helper', '_extmethods', '__scsa_tx',) _yang_name = 'scsa-tx' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__scsa_tx = YANGDynClass(base=YANGListType("sci_tx",yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx, yang_name="scsa-tx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-tx', extensions=None), is_container='list', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'scsa-tx'] def _get_scsa_tx(self): """ Getter method for scsa_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx (list) YANG Description: TX Secure Channel and Secure Association Statistics """ return self.__scsa_tx def _set_scsa_tx(self, v, load=False): """ Setter method for scsa_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx (list) If this variable is read-only (config: false) in the source YANG file, then _set_scsa_tx is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_scsa_tx() directly. YANG Description: TX Secure Channel and Secure Association Statistics """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("sci_tx",yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx, yang_name="scsa-tx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-tx', extensions=None), is_container='list', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """scsa_tx must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("sci_tx",yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx, yang_name="scsa-tx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-tx', extensions=None), is_container='list', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False)""", }) self.__scsa_tx = t if hasattr(self, '_set'): self._set() def _unset_scsa_tx(self): self.__scsa_tx = YANGDynClass(base=YANGListType("sci_tx",yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx, yang_name="scsa-tx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-tx', extensions=None), is_container='list', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False) scsa_tx = __builtin__.property(_get_scsa_tx) _pyangbind_elements = OrderedDict([('scsa_tx', scsa_tx), ]) class yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state_counters(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-rx/scsa-rx/state/counters. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Counters container for macsec-scsa-rx-interface-stats """ __slots__ = ('_path_helper', '_extmethods', '__sc_invalid','__sc_valid','__sa_invalid','__sa_valid',) _yang_name = 'counters' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__sc_invalid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__sc_valid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__sa_invalid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__sa_valid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'scsa-rx', 'scsa-rx', 'state', 'counters'] def _get_sc_invalid(self): """ Getter method for sc_invalid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sc_invalid (oc-yang:counter64) YANG Description: Invalid Secure Channel RX Packets counter. This counter reflects the number of invalid received packets in a secure channel. """ return self.__sc_invalid def _set_sc_invalid(self, v, load=False): """ Setter method for sc_invalid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sc_invalid (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_sc_invalid is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sc_invalid() directly. YANG Description: Invalid Secure Channel RX Packets counter. This counter reflects the number of invalid received packets in a secure channel. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sc_invalid must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__sc_invalid = t if hasattr(self, '_set'): self._set() def _unset_sc_invalid(self): self.__sc_invalid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_sc_valid(self): """ Getter method for sc_valid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sc_valid (oc-yang:counter64) YANG Description: Valid Secure Channel RX Packets counter. This counter reflects the number of valid received packets in a secure channel. """ return self.__sc_valid def _set_sc_valid(self, v, load=False): """ Setter method for sc_valid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sc_valid (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_sc_valid is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sc_valid() directly. YANG Description: Valid Secure Channel RX Packets counter. This counter reflects the number of valid received packets in a secure channel. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sc_valid must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__sc_valid = t if hasattr(self, '_set'): self._set() def _unset_sc_valid(self): self.__sc_valid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_sa_invalid(self): """ Getter method for sa_invalid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sa_invalid (oc-yang:counter64) YANG Description: Invalid Secure Association RX Packets counter. This counter reflects the number of integrity check fails for received packets in a secure association. """ return self.__sa_invalid def _set_sa_invalid(self, v, load=False): """ Setter method for sa_invalid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sa_invalid (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_sa_invalid is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sa_invalid() directly. YANG Description: Invalid Secure Association RX Packets counter. This counter reflects the number of integrity check fails for received packets in a secure association. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sa_invalid must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__sa_invalid = t if hasattr(self, '_set'): self._set() def _unset_sa_invalid(self): self.__sa_invalid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_sa_valid(self): """ Getter method for sa_valid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sa_valid (oc-yang:counter64) YANG Description: Secure Association Valid RX Packets counter. This counter reflects the number of packets in a secure association that passed integrity check. """ return self.__sa_valid def _set_sa_valid(self, v, load=False): """ Setter method for sa_valid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sa_valid (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_sa_valid is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sa_valid() directly. YANG Description: Secure Association Valid RX Packets counter. This counter reflects the number of packets in a secure association that passed integrity check. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sa_valid must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__sa_valid = t if hasattr(self, '_set'): self._set() def _unset_sa_valid(self): self.__sa_valid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) sc_invalid = __builtin__.property(_get_sc_invalid) sc_valid = __builtin__.property(_get_sc_valid) sa_invalid = __builtin__.property(_get_sa_invalid) sa_valid = __builtin__.property(_get_sa_valid) _pyangbind_elements = OrderedDict([('sc_invalid', sc_invalid), ('sc_valid', sc_valid), ('sa_invalid', sa_invalid), ('sa_valid', sa_valid), ]) class yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-rx/scsa-rx/state. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: State container for macsec-scsa-rx-interface-stats """ __slots__ = ('_path_helper', '_extmethods', '__sci_rx','__counters',) _yang_name = 'state' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__sci_rx = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False) self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'scsa-rx', 'scsa-rx', 'state'] def _get_sci_rx(self): """ Getter method for sci_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/sci_rx (oc-yang:hex-string) YANG Description: Secure Channel Identifier. Every Receive Channel is uniquely identified using this field. """ return self.__sci_rx def _set_sci_rx(self, v, load=False): """ Setter method for sci_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/sci_rx (oc-yang:hex-string) If this variable is read-only (config: false) in the source YANG file, then _set_sci_rx is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sci_rx() directly. YANG Description: Secure Channel Identifier. Every Receive Channel is uniquely identified using this field. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sci_rx must be of a type compatible with oc-yang:hex-string""", 'defined-type': "oc-yang:hex-string", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)""", }) self.__sci_rx = t if hasattr(self, '_set'): self._set() def _unset_sci_rx(self): self.__sci_rx = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False) def _get_counters(self): """ Getter method for counters, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters (container) YANG Description: Counters container for macsec-scsa-rx-interface-stats """ return self.__counters def _set_counters(self, v, load=False): """ Setter method for counters, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters (container) If this variable is read-only (config: false) in the source YANG file, then _set_counters is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_counters() directly. YANG Description: Counters container for macsec-scsa-rx-interface-stats """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """counters must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)""", }) self.__counters = t if hasattr(self, '_set'): self._set() def _unset_counters(self): self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) sci_rx = __builtin__.property(_get_sci_rx) counters = __builtin__.property(_get_counters) _pyangbind_elements = OrderedDict([('sci_rx', sci_rx), ('counters', counters), ]) class yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-rx/scsa-rx. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: RX Secure Channel and Secure Association Statistics """ __slots__ = ('_path_helper', '_extmethods', '__sci_rx','__state',) _yang_name = 'scsa-rx' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__sci_rx = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False) self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'scsa-rx', 'scsa-rx'] def _get_sci_rx(self): """ Getter method for sci_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/sci_rx (leafref) YANG Description: RX Secure Channel and Secure Association Statistics """ return self.__sci_rx def _set_sci_rx(self, v, load=False): """ Setter method for sci_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/sci_rx (leafref) If this variable is read-only (config: false) in the source YANG file, then _set_sci_rx is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sci_rx() directly. YANG Description: RX Secure Channel and Secure Association Statistics """ parent = getattr(self, "_parent", None) if parent is not None and load is False: raise AttributeError("Cannot set keys directly when" + " within an instantiated list") if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """sci_rx must be of a type compatible with leafref""", 'defined-type': "leafref", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)""", }) self.__sci_rx = t if hasattr(self, '_set'): self._set() def _unset_sci_rx(self): self.__sci_rx = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False) def _get_state(self): """ Getter method for state, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state (container) YANG Description: State container for macsec-scsa-rx-interface-stats """ return self.__state def _set_state(self, v, load=False): """ Setter method for state, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state (container) If this variable is read-only (config: false) in the source YANG file, then _set_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_state() directly. YANG Description: State container for macsec-scsa-rx-interface-stats """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """state must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)""", }) self.__state = t if hasattr(self, '_set'): self._set() def _unset_state(self): self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) sci_rx = __builtin__.property(_get_sci_rx) state = __builtin__.property(_get_state) _pyangbind_elements = OrderedDict([('sci_rx', sci_rx), ('state', state), ]) class yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-rx. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Enclosing container for received packets for Secure Channel and Secure Association """ __slots__ = ('_path_helper', '_extmethods', '__scsa_rx',) _yang_name = 'scsa-rx' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__scsa_rx = YANGDynClass(base=YANGListType("sci_rx",yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx, yang_name="scsa-rx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-rx', extensions=None), is_container='list', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'scsa-rx'] def _get_scsa_rx(self): """ Getter method for scsa_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx (list) YANG Description: RX Secure Channel and Secure Association Statistics """ return self.__scsa_rx def _set_scsa_rx(self, v, load=False): """ Setter method for scsa_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx (list) If this variable is read-only (config: false) in the source YANG file, then _set_scsa_rx is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_scsa_rx() directly. YANG Description: RX Secure Channel and Secure Association Statistics """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("sci_rx",yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx, yang_name="scsa-rx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-rx', extensions=None), is_container='list', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """scsa_rx must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("sci_rx",yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx, yang_name="scsa-rx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-rx', extensions=None), is_container='list', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False)""", }) self.__scsa_rx = t if hasattr(self, '_set'): self._set() def _unset_scsa_rx(self): self.__scsa_rx = YANGDynClass(base=YANGListType("sci_rx",yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx, yang_name="scsa-rx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-rx', extensions=None), is_container='list', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False) scsa_rx = __builtin__.property(_get_scsa_rx) _pyangbind_elements = OrderedDict([('scsa_rx', scsa_rx), ]) class yc_config_openconfig_macsec__macsec_interfaces_interface_mka_config(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/mka/config. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Configuration data for MKA interface """ __slots__ = ('_path_helper', '_extmethods', '__mka_policy','__key_chain',) _yang_name = 'config' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__mka_policy = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) self.__key_chain = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'mka', 'config'] def _get_mka_policy(self): """ Getter method for mka_policy, mapped from YANG variable /macsec/interfaces/interface/mka/config/mka_policy (leafref) YANG Description: Apply MKA policy on the interface """ return self.__mka_policy def _set_mka_policy(self, v, load=False): """ Setter method for mka_policy, mapped from YANG variable /macsec/interfaces/interface/mka/config/mka_policy (leafref) If this variable is read-only (config: false) in the source YANG file, then _set_mka_policy is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_mka_policy() directly. YANG Description: Apply MKA policy on the interface """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """mka_policy must be of a type compatible with leafref""", 'defined-type': "leafref", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)""", }) self.__mka_policy = t if hasattr(self, '_set'): self._set() def _unset_mka_policy(self): self.__mka_policy = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) def _get_key_chain(self): """ Getter method for key_chain, mapped from YANG variable /macsec/interfaces/interface/mka/config/key_chain (leafref) YANG Description: Configure Key Chain name """ return self.__key_chain def _set_key_chain(self, v, load=False): """ Setter method for key_chain, mapped from YANG variable /macsec/interfaces/interface/mka/config/key_chain (leafref) If this variable is read-only (config: false) in the source YANG file, then _set_key_chain is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_key_chain() directly. YANG Description: Configure Key Chain name """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """key_chain must be of a type compatible with leafref""", 'defined-type': "leafref", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)""", }) self.__key_chain = t if hasattr(self, '_set'): self._set() def _unset_key_chain(self): self.__key_chain = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) mka_policy = __builtin__.property(_get_mka_policy, _set_mka_policy) key_chain = __builtin__.property(_get_key_chain, _set_key_chain) _pyangbind_elements = OrderedDict([('mka_policy', mka_policy), ('key_chain', key_chain), ]) class yc_counters_openconfig_macsec__macsec_interfaces_interface_mka_state_counters(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/mka/state/counters. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: MKA interface counters """ __slots__ = ('_path_helper', '_extmethods', '__in_mkpdu','__in_sak_mkpdu','__in_cak_mkpdu','__out_mkpdu','__out_sak_mkpdu','__out_cak_mkpdu',) _yang_name = 'counters' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__in_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__in_sak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__in_cak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__out_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__out_sak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) self.__out_cak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'mka', 'state', 'counters'] def _get_in_mkpdu(self): """ Getter method for in_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/in_mkpdu (oc-yang:counter64) YANG Description: Validated MKPDU received count """ return self.__in_mkpdu def _set_in_mkpdu(self, v, load=False): """ Setter method for in_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/in_mkpdu (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_in_mkpdu is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_in_mkpdu() directly. YANG Description: Validated MKPDU received count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """in_mkpdu must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__in_mkpdu = t if hasattr(self, '_set'): self._set() def _unset_in_mkpdu(self): self.__in_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_in_sak_mkpdu(self): """ Getter method for in_sak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/in_sak_mkpdu (oc-yang:counter64) YANG Description: Validated MKPDU received SAK count """ return self.__in_sak_mkpdu def _set_in_sak_mkpdu(self, v, load=False): """ Setter method for in_sak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/in_sak_mkpdu (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_in_sak_mkpdu is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_in_sak_mkpdu() directly. YANG Description: Validated MKPDU received SAK count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """in_sak_mkpdu must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__in_sak_mkpdu = t if hasattr(self, '_set'): self._set() def _unset_in_sak_mkpdu(self): self.__in_sak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_in_cak_mkpdu(self): """ Getter method for in_cak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/in_cak_mkpdu (oc-yang:counter64) YANG Description: Validated MKPDU received CAK count """ return self.__in_cak_mkpdu def _set_in_cak_mkpdu(self, v, load=False): """ Setter method for in_cak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/in_cak_mkpdu (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_in_cak_mkpdu is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_in_cak_mkpdu() directly. YANG Description: Validated MKPDU received CAK count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """in_cak_mkpdu must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__in_cak_mkpdu = t if hasattr(self, '_set'): self._set() def _unset_in_cak_mkpdu(self): self.__in_cak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_out_mkpdu(self): """ Getter method for out_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/out_mkpdu (oc-yang:counter64) YANG Description: MKPDU sent count """ return self.__out_mkpdu def _set_out_mkpdu(self, v, load=False): """ Setter method for out_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/out_mkpdu (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_out_mkpdu is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_out_mkpdu() directly. YANG Description: MKPDU sent count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """out_mkpdu must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__out_mkpdu = t if hasattr(self, '_set'): self._set() def _unset_out_mkpdu(self): self.__out_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_out_sak_mkpdu(self): """ Getter method for out_sak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/out_sak_mkpdu (oc-yang:counter64) YANG Description: MKPDU SAK sent count """ return self.__out_sak_mkpdu def _set_out_sak_mkpdu(self, v, load=False): """ Setter method for out_sak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/out_sak_mkpdu (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_out_sak_mkpdu is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_out_sak_mkpdu() directly. YANG Description: MKPDU SAK sent count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """out_sak_mkpdu must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__out_sak_mkpdu = t if hasattr(self, '_set'): self._set() def _unset_out_sak_mkpdu(self): self.__out_sak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) def _get_out_cak_mkpdu(self): """ Getter method for out_cak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/out_cak_mkpdu (oc-yang:counter64) YANG Description: MKPDU CAK sent count """ return self.__out_cak_mkpdu def _set_out_cak_mkpdu(self, v, load=False): """ Setter method for out_cak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/out_cak_mkpdu (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_out_cak_mkpdu is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_out_cak_mkpdu() directly. YANG Description: MKPDU CAK sent count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """out_cak_mkpdu must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""", }) self.__out_cak_mkpdu = t if hasattr(self, '_set'): self._set() def _unset_out_cak_mkpdu(self): self.__out_cak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False) in_mkpdu = __builtin__.property(_get_in_mkpdu) in_sak_mkpdu = __builtin__.property(_get_in_sak_mkpdu) in_cak_mkpdu = __builtin__.property(_get_in_cak_mkpdu) out_mkpdu = __builtin__.property(_get_out_mkpdu) out_sak_mkpdu = __builtin__.property(_get_out_sak_mkpdu) out_cak_mkpdu = __builtin__.property(_get_out_cak_mkpdu) _pyangbind_elements = OrderedDict([('in_mkpdu', in_mkpdu), ('in_sak_mkpdu', in_sak_mkpdu), ('in_cak_mkpdu', in_cak_mkpdu), ('out_mkpdu', out_mkpdu), ('out_sak_mkpdu', out_sak_mkpdu), ('out_cak_mkpdu', out_cak_mkpdu), ]) class yc_state_openconfig_macsec__macsec_interfaces_interface_mka_state(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/mka/state. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Operational state data for MKA interface """ __slots__ = ('_path_helper', '_extmethods', '__mka_policy','__key_chain','__counters',) _yang_name = 'state' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__mka_policy = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False) self.__key_chain = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False) self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'mka', 'state'] def _get_mka_policy(self): """ Getter method for mka_policy, mapped from YANG variable /macsec/interfaces/interface/mka/state/mka_policy (leafref) YANG Description: Apply MKA policy on the interface """ return self.__mka_policy def _set_mka_policy(self, v, load=False): """ Setter method for mka_policy, mapped from YANG variable /macsec/interfaces/interface/mka/state/mka_policy (leafref) If this variable is read-only (config: false) in the source YANG file, then _set_mka_policy is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_mka_policy() directly. YANG Description: Apply MKA policy on the interface """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """mka_policy must be of a type compatible with leafref""", 'defined-type': "leafref", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)""", }) self.__mka_policy = t if hasattr(self, '_set'): self._set() def _unset_mka_policy(self): self.__mka_policy = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False) def _get_key_chain(self): """ Getter method for key_chain, mapped from YANG variable /macsec/interfaces/interface/mka/state/key_chain (leafref) YANG Description: Configure Key Chain name """ return self.__key_chain def _set_key_chain(self, v, load=False): """ Setter method for key_chain, mapped from YANG variable /macsec/interfaces/interface/mka/state/key_chain (leafref) If this variable is read-only (config: false) in the source YANG file, then _set_key_chain is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_key_chain() directly. YANG Description: Configure Key Chain name """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """key_chain must be of a type compatible with leafref""", 'defined-type': "leafref", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)""", }) self.__key_chain = t if hasattr(self, '_set'): self._set() def _unset_key_chain(self): self.__key_chain = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False) def _get_counters(self): """ Getter method for counters, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters (container) YANG Description: MKA interface counters """ return self.__counters def _set_counters(self, v, load=False): """ Setter method for counters, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters (container) If this variable is read-only (config: false) in the source YANG file, then _set_counters is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_counters() directly. YANG Description: MKA interface counters """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_counters_openconfig_macsec__macsec_interfaces_interface_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """counters must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)""", }) self.__counters = t if hasattr(self, '_set'): self._set() def _unset_counters(self): self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False) mka_policy = __builtin__.property(_get_mka_policy) key_chain = __builtin__.property(_get_key_chain) counters = __builtin__.property(_get_counters) _pyangbind_elements = OrderedDict([('mka_policy', mka_policy), ('key_chain', key_chain), ('counters', counters), ]) class yc_mka_openconfig_macsec__macsec_interfaces_interface_mka(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/mka. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Enclosing container for the MKA interface """ __slots__ = ('_path_helper', '_extmethods', '__config','__state',) _yang_name = 'mka' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_interfaces_interface_mka_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface', 'mka'] def _get_config(self): """ Getter method for config, mapped from YANG variable /macsec/interfaces/interface/mka/config (container) YANG Description: Configuration data for MKA interface """ return self.__config def _set_config(self, v, load=False): """ Setter method for config, mapped from YANG variable /macsec/interfaces/interface/mka/config (container) If this variable is read-only (config: false) in the source YANG file, then _set_config is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_config() directly. YANG Description: Configuration data for MKA interface """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_config_openconfig_macsec__macsec_interfaces_interface_mka_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """config must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_config_openconfig_macsec__macsec_interfaces_interface_mka_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__config = t if hasattr(self, '_set'): self._set() def _unset_config(self): self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_interfaces_interface_mka_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) def _get_state(self): """ Getter method for state, mapped from YANG variable /macsec/interfaces/interface/mka/state (container) YANG Description: Operational state data for MKA interface """ return self.__state def _set_state(self, v, load=False): """ Setter method for state, mapped from YANG variable /macsec/interfaces/interface/mka/state (container) If this variable is read-only (config: false) in the source YANG file, then _set_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_state() directly. YANG Description: Operational state data for MKA interface """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_interfaces_interface_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """state must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__state = t if hasattr(self, '_set'): self._set() def _unset_state(self): self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) config = __builtin__.property(_get_config, _set_config) state = __builtin__.property(_get_state, _set_state) _pyangbind_elements = OrderedDict([('config', config), ('state', state), ]) class yc_interface_openconfig_macsec__macsec_interfaces_interface(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: List of interfaces on which MACsec is enabled / available """ __slots__ = ('_path_helper', '_extmethods', '__name','__config','__state','__scsa_tx','__scsa_rx','__mka',) _yang_name = 'interface' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_interfaces_interface_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) self.__scsa_tx = YANGDynClass(base=yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx, is_container='container', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) self.__scsa_rx = YANGDynClass(base=yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx, is_container='container', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) self.__mka = YANGDynClass(base=yc_mka_openconfig_macsec__macsec_interfaces_interface_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) load = kwargs.pop("load", None)<|fim▁hole|> if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces', 'interface'] def _get_name(self): """ Getter method for name, mapped from YANG variable /macsec/interfaces/interface/name (leafref) YANG Description: Reference to the list key """ return self.__name def _set_name(self, v, load=False): """ Setter method for name, mapped from YANG variable /macsec/interfaces/interface/name (leafref) If this variable is read-only (config: false) in the source YANG file, then _set_name is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_name() directly. YANG Description: Reference to the list key """ parent = getattr(self, "_parent", None) if parent is not None and load is False: raise AttributeError("Cannot set keys directly when" + " within an instantiated list") if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """name must be of a type compatible with leafref""", 'defined-type': "leafref", 'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)""", }) self.__name = t if hasattr(self, '_set'): self._set() def _unset_name(self): self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True) def _get_config(self): """ Getter method for config, mapped from YANG variable /macsec/interfaces/interface/config (container) YANG Description: Configuration data for MACsec on each interface """ return self.__config def _set_config(self, v, load=False): """ Setter method for config, mapped from YANG variable /macsec/interfaces/interface/config (container) If this variable is read-only (config: false) in the source YANG file, then _set_config is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_config() directly. YANG Description: Configuration data for MACsec on each interface """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_config_openconfig_macsec__macsec_interfaces_interface_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """config must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_config_openconfig_macsec__macsec_interfaces_interface_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__config = t if hasattr(self, '_set'): self._set() def _unset_config(self): self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_interfaces_interface_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) def _get_state(self): """ Getter method for state, mapped from YANG variable /macsec/interfaces/interface/state (container) YANG Description: Operational state data """ return self.__state def _set_state(self, v, load=False): """ Setter method for state, mapped from YANG variable /macsec/interfaces/interface/state (container) If this variable is read-only (config: false) in the source YANG file, then _set_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_state() directly. YANG Description: Operational state data """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_interfaces_interface_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """state must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__state = t if hasattr(self, '_set'): self._set() def _unset_state(self): self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) def _get_scsa_tx(self): """ Getter method for scsa_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx (container) YANG Description: Enclosing container for transmitted packets for Secure Channel and Secure Association """ return self.__scsa_tx def _set_scsa_tx(self, v, load=False): """ Setter method for scsa_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx (container) If this variable is read-only (config: false) in the source YANG file, then _set_scsa_tx is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_scsa_tx() directly. YANG Description: Enclosing container for transmitted packets for Secure Channel and Secure Association """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx, is_container='container', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """scsa_tx must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx, is_container='container', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__scsa_tx = t if hasattr(self, '_set'): self._set() def _unset_scsa_tx(self): self.__scsa_tx = YANGDynClass(base=yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx, is_container='container', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) def _get_scsa_rx(self): """ Getter method for scsa_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx (container) YANG Description: Enclosing container for received packets for Secure Channel and Secure Association """ return self.__scsa_rx def _set_scsa_rx(self, v, load=False): """ Setter method for scsa_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx (container) If this variable is read-only (config: false) in the source YANG file, then _set_scsa_rx is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_scsa_rx() directly. YANG Description: Enclosing container for received packets for Secure Channel and Secure Association """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx, is_container='container', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """scsa_rx must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx, is_container='container', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__scsa_rx = t if hasattr(self, '_set'): self._set() def _unset_scsa_rx(self): self.__scsa_rx = YANGDynClass(base=yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx, is_container='container', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) def _get_mka(self): """ Getter method for mka, mapped from YANG variable /macsec/interfaces/interface/mka (container) YANG Description: Enclosing container for the MKA interface """ return self.__mka def _set_mka(self, v, load=False): """ Setter method for mka, mapped from YANG variable /macsec/interfaces/interface/mka (container) If this variable is read-only (config: false) in the source YANG file, then _set_mka is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_mka() directly. YANG Description: Enclosing container for the MKA interface """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_mka_openconfig_macsec__macsec_interfaces_interface_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """mka must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_mka_openconfig_macsec__macsec_interfaces_interface_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__mka = t if hasattr(self, '_set'): self._set() def _unset_mka(self): self.__mka = YANGDynClass(base=yc_mka_openconfig_macsec__macsec_interfaces_interface_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) name = __builtin__.property(_get_name, _set_name) config = __builtin__.property(_get_config, _set_config) state = __builtin__.property(_get_state, _set_state) scsa_tx = __builtin__.property(_get_scsa_tx, _set_scsa_tx) scsa_rx = __builtin__.property(_get_scsa_rx, _set_scsa_rx) mka = __builtin__.property(_get_mka, _set_mka) _pyangbind_elements = OrderedDict([('name', name), ('config', config), ('state', state), ('scsa_tx', scsa_tx), ('scsa_rx', scsa_rx), ('mka', mka), ]) class yc_interfaces_openconfig_macsec__macsec_interfaces(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec/interfaces. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Enclosing container for the MACsec interfaces list """ __slots__ = ('_path_helper', '_extmethods', '__interface',) _yang_name = 'interfaces' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__interface = YANGDynClass(base=YANGListType("name",yc_interface_openconfig_macsec__macsec_interfaces_interface, yang_name="interface", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="interface", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec', 'interfaces'] def _get_interface(self): """ Getter method for interface, mapped from YANG variable /macsec/interfaces/interface (list) YANG Description: List of interfaces on which MACsec is enabled / available """ return self.__interface def _set_interface(self, v, load=False): """ Setter method for interface, mapped from YANG variable /macsec/interfaces/interface (list) If this variable is read-only (config: false) in the source YANG file, then _set_interface is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_interface() directly. YANG Description: List of interfaces on which MACsec is enabled / available """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("name",yc_interface_openconfig_macsec__macsec_interfaces_interface, yang_name="interface", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="interface", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """interface must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("name",yc_interface_openconfig_macsec__macsec_interfaces_interface, yang_name="interface", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="interface", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)""", }) self.__interface = t if hasattr(self, '_set'): self._set() def _unset_interface(self): self.__interface = YANGDynClass(base=YANGListType("name",yc_interface_openconfig_macsec__macsec_interfaces_interface, yang_name="interface", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="interface", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True) interface = __builtin__.property(_get_interface, _set_interface) _pyangbind_elements = OrderedDict([('interface', interface), ]) class yc_macsec_openconfig_macsec__macsec(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /macsec. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: The MACsec """ __slots__ = ('_path_helper', '_extmethods', '__mka','__interfaces',) _yang_name = 'macsec' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__mka = YANGDynClass(base=yc_mka_openconfig_macsec__macsec_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) self.__interfaces = YANGDynClass(base=yc_interfaces_openconfig_macsec__macsec_interfaces, is_container='container', yang_name="interfaces", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['macsec'] def _get_mka(self): """ Getter method for mka, mapped from YANG variable /macsec/mka (container) YANG Description: The MKA """ return self.__mka def _set_mka(self, v, load=False): """ Setter method for mka, mapped from YANG variable /macsec/mka (container) If this variable is read-only (config: false) in the source YANG file, then _set_mka is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_mka() directly. YANG Description: The MKA """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_mka_openconfig_macsec__macsec_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """mka must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_mka_openconfig_macsec__macsec_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__mka = t if hasattr(self, '_set'): self._set() def _unset_mka(self): self.__mka = YANGDynClass(base=yc_mka_openconfig_macsec__macsec_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) def _get_interfaces(self): """ Getter method for interfaces, mapped from YANG variable /macsec/interfaces (container) YANG Description: Enclosing container for the MACsec interfaces list """ return self.__interfaces def _set_interfaces(self, v, load=False): """ Setter method for interfaces, mapped from YANG variable /macsec/interfaces (container) If this variable is read-only (config: false) in the source YANG file, then _set_interfaces is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_interfaces() directly. YANG Description: Enclosing container for the MACsec interfaces list """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_interfaces_openconfig_macsec__macsec_interfaces, is_container='container', yang_name="interfaces", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """interfaces must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_interfaces_openconfig_macsec__macsec_interfaces, is_container='container', yang_name="interfaces", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__interfaces = t if hasattr(self, '_set'): self._set() def _unset_interfaces(self): self.__interfaces = YANGDynClass(base=yc_interfaces_openconfig_macsec__macsec_interfaces, is_container='container', yang_name="interfaces", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) mka = __builtin__.property(_get_mka, _set_mka) interfaces = __builtin__.property(_get_interfaces, _set_interfaces) _pyangbind_elements = OrderedDict([('mka', mka), ('interfaces', interfaces), ]) class openconfig_macsec(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec - based on the path /openconfig-macsec. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: This module defines configuration and state data for MACsec IEEE Std 802.1AE-2018. """ __slots__ = ('_path_helper', '_extmethods', '__macsec',) _yang_name = 'openconfig-macsec' _yang_namespace = 'http://openconfig.net/yang/macsec' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__macsec = YANGDynClass(base=yc_macsec_openconfig_macsec__macsec, is_container='container', yang_name="macsec", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [] def _get_macsec(self): """ Getter method for macsec, mapped from YANG variable /macsec (container) YANG Description: The MACsec """ return self.__macsec def _set_macsec(self, v, load=False): """ Setter method for macsec, mapped from YANG variable /macsec (container) If this variable is read-only (config: false) in the source YANG file, then _set_macsec is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_macsec() directly. YANG Description: The MACsec """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_macsec_openconfig_macsec__macsec, is_container='container', yang_name="macsec", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """macsec must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=yc_macsec_openconfig_macsec__macsec, is_container='container', yang_name="macsec", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""", }) self.__macsec = t if hasattr(self, '_set'): self._set() def _unset_macsec(self): self.__macsec = YANGDynClass(base=yc_macsec_openconfig_macsec__macsec, is_container='container', yang_name="macsec", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True) macsec = __builtin__.property(_get_macsec, _set_macsec) _pyangbind_elements = OrderedDict([('macsec', macsec), ]) class openconfig_macsec_types(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-macsec-types - based on the path /openconfig-macsec-types. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: This module defines types related to the MACsec configuration and operational state model. """ _pyangbind_elements = {}<|fim▁end|>
<|file_name|>copy from.js<|end_file_name|><|fim▁begin|>var config = { width: 800, height: 600, type: Phaser.AUTO, parent: 'phaser-example', scene: { create: create, update: update } }; var game = new Phaser.Game(config); var graphics; var pointerRect; var rectangles; function create () { graphics = this.add.graphics({ lineStyle: { color: 0x0000aa }, fillStyle: { color: 0x0000aa, alpha: 0.5 } }); pointerRect = new Phaser.Geom.Rectangle(0, 0, 80, 60); rectangles = []; for(var x = 0; x < 10; x++) { rectangles[x] = []; for(var y = 0; y < 10; y++) { rectangles[x][y] = new Phaser.Geom.Rectangle(x * 80, y * 60, 80, 60); } } this.input.on('pointermove', function (pointer) { var x = Math.floor(pointer.x / 80); var y = Math.floor(pointer.y / 60); pointerRect.setPosition(x * 80, y * 60); Phaser.Geom.Rectangle.CopyFrom(pointerRect, rectangles[x][y]); }); } <|fim▁hole|> graphics.fillRectShape(pointerRect); for(var x = 0; x < 10; x++) { for(var y = 0; y < 10; y++) { var rect = rectangles[x][y]; if(rect.width > 10) { rect.width *= 0.95; rect.height *= 0.95; } graphics.strokeRectShape(rect); } } }<|fim▁end|>
function update () { graphics.clear();
<|file_name|>move_imagery.py<|end_file_name|><|fim▁begin|>import os import shutil import re import zipfile import xml.etree.ElementTree as ET from tempfile import TemporaryDirectory import psycopg2 conn = psycopg2.connect( database='innoter', user='postgres', password='postgres', host='192.168.0.107', port='5432') cursor = conn.cursor() dst_dir = r"\\nas1\storage\DG_archive\sat" path_list = [] cursor.execute( """SELECT path, order_id FROM geoarchive.dg_orders WHERE aero is not TRUE""") results = cursor.fetchall() for i, result in enumerate(results): zip_path, order_id = result[0], result[1] print(i + 1, zip_path) dst_filepath = os.path.join(dst_dir, os.path.basename(zip_path)) shutil.move(zip_path, dst_filepath) cursor.execute("""UPDATE geoarchive.dg_orders SET path = %s WHERE order_id = %s""", [dst_filepath, order_id, ], ) conn.commit() print('Готово...\n') <|fim▁hole|># order_shape = [fnm for fnm in zf.namelist() if re.match(r'.+ORDER_SHAPE.+', fnm, re.I)] # if not order_shape: # # for fnm in zf.namelist(): # # if re.match(r'.+ORDER_SHAPE.+', fnm, re.I) is None: # cursor.execute("""UPDATE geoarchive.dg_orders # SET aero = TRUE # WHERE order_id = %s""", [order_id, ],) # conn.commit() # print(80*'=', order_id, 80*'=') # aero_list.append(order_id) # # print('\nDone:\n', len(aero_list)) # for i in aero_list: # print(i)<|fim▁end|>
# with zipfile.ZipFile(zip_path) as zf:
<|file_name|>material-database.js<|end_file_name|><|fim▁begin|>import { setAttrs } from '../actions/object' /*MATERIALDB_GROUP*/ export const addGroup = () => ({ type: "MATERIALDB_GROUP_ADD" });<|fim▁hole|> /*MATERIALDB_PRESET (operations)*/ export const addPreset = (groupId, attrs = {}) => ({ type: "MATERIALDB_PRESET_ADD", payload: { groupId, attrs } }) export const deletePreset = (presetId) => ({ type: "MATERIALDB_PRESET_DELETE", payload: presetId }); export const setPresetAttrs = (presetId, attrs) => ({ type: "MATERIALDB_PRESET_SET_ATTRS", payload: { presetId, attrs } }); export const togglePresetEdit = (presetId) => ({ type: "MATERIALDB_PRESET_TOGGLE_EDIT", payload: presetId }); /*MATERIALDB PICKER*/ export const applyPreset = (presetId) => ({ type: "MATERIALDB_PRESET_APPLY", payload: presetId }); export const newPreset = (preset, grouping, name) => ({ type: "MATERIALDB_PRESET_NEW", payload: { preset, grouping, name } }) /*MATERIALDB*/ export const uploadMaterialDatabase = (file, content) => ({ type: "MATERIALDB_UPLOAD", payload: { file, database: JSON.parse(content) } }); export const importMaterialDatabase = (file, content) => ({ type: "MATERIALDB_IMPORT", payload: { file, database: content } }); export const downloadMaterialDatabase = (database) => ({ type: "MATERIALDB_DOWNLOAD", payload: { database } });<|fim▁end|>
export const deleteGroup = (groupId) => ({ type: "MATERIALDB_GROUP_DELETE", payload: groupId }); export const setGroupAttrs = (groupId, attrs) => ({ type: "MATERIALDB_GROUP_SET_ATTRS", payload: { groupId, attrs } }); export const toggleGroupView = (groupId) => ({ type: "MATERIALDB_GROUP_TOGGLE_VIEW", payload: groupId }); export const toggleGroupEdit = (groupId) => ({ type: "MATERIALDB_GROUP_TOGGLE_EDIT", payload: groupId });
<|file_name|>webserve.py<|end_file_name|><|fim▁begin|># This file is part of PlexPy. # # PlexPy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PlexPy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PlexPy. If not, see <http://www.gnu.org/licenses/>. from plexpy import logger, notifiers, plextv, pmsconnect, common, log_reader, datafactory, graphs, users from plexpy.helpers import checked, radio from mako.lookup import TemplateLookup from mako import exceptions import plexpy import threading import cherrypy import hashlib import random import json import os try: # pylint:disable=E0611 # ignore this error because we are catching the ImportError from collections import OrderedDict # pylint:enable=E0611 except ImportError: # Python 2.6.x fallback, from libs from ordereddict import OrderedDict def serve_template(templatename, **kwargs): interface_dir = os.path.join(str(plexpy.PROG_DIR), 'data/interfaces/') template_dir = os.path.join(str(interface_dir), plexpy.CONFIG.INTERFACE) _hplookup = TemplateLookup(directories=[template_dir]) try: template = _hplookup.get_template(templatename) return template.render(**kwargs) except: return exceptions.html_error_template().render() class WebInterface(object): def __init__(self): self.interface_dir = os.path.join(str(plexpy.PROG_DIR), 'data/') @cherrypy.expose def index(self): if plexpy.CONFIG.FIRST_RUN_COMPLETE: raise cherrypy.HTTPRedirect("home") else: raise cherrypy.HTTPRedirect("welcome") @cherrypy.expose def home(self): config = { "home_stats_length": plexpy.CONFIG.HOME_STATS_LENGTH, "home_stats_type": plexpy.CONFIG.HOME_STATS_TYPE, "home_stats_count": plexpy.CONFIG.HOME_STATS_COUNT, "pms_identifier": plexpy.CONFIG.PMS_IDENTIFIER, } return serve_template(templatename="index.html", title="Home", config=config) @cherrypy.expose def welcome(self, **kwargs): config = { "launch_browser": checked(plexpy.CONFIG.LAUNCH_BROWSER), "refresh_users_on_startup": checked(plexpy.CONFIG.REFRESH_USERS_ON_STARTUP), "pms_identifier": plexpy.CONFIG.PMS_IDENTIFIER, "pms_ip": plexpy.CONFIG.PMS_IP, "pms_is_remote": checked(plexpy.CONFIG.PMS_IS_REMOTE), "pms_port": plexpy.CONFIG.PMS_PORT, "pms_token": plexpy.CONFIG.PMS_TOKEN, "pms_ssl": checked(plexpy.CONFIG.PMS_SSL), "pms_uuid": plexpy.CONFIG.PMS_UUID, "tv_notify_enable": checked(plexpy.CONFIG.TV_NOTIFY_ENABLE), "movie_notify_enable": checked(plexpy.CONFIG.MOVIE_NOTIFY_ENABLE), "music_notify_enable": checked(plexpy.CONFIG.MUSIC_NOTIFY_ENABLE), "tv_notify_on_start": checked(plexpy.CONFIG.TV_NOTIFY_ON_START), "movie_notify_on_start": checked(plexpy.CONFIG.MOVIE_NOTIFY_ON_START), "music_notify_on_start": checked(plexpy.CONFIG.MUSIC_NOTIFY_ON_START), "video_logging_enable": checked(plexpy.CONFIG.VIDEO_LOGGING_ENABLE), "music_logging_enable": checked(plexpy.CONFIG.MUSIC_LOGGING_ENABLE), "logging_ignore_interval": plexpy.CONFIG.LOGGING_IGNORE_INTERVAL, "check_github": checked(plexpy.CONFIG.CHECK_GITHUB) } # The setup wizard just refreshes the page on submit so we must redirect to home if config set. # Also redirecting to home if a PMS token already exists - will remove this in future. if plexpy.CONFIG.FIRST_RUN_COMPLETE or plexpy.CONFIG.PMS_TOKEN: raise cherrypy.HTTPRedirect("home") else: return serve_template(templatename="welcome.html", title="Welcome", config=config) @cherrypy.expose def get_date_formats(self): if plexpy.CONFIG.DATE_FORMAT: date_format = plexpy.CONFIG.DATE_FORMAT else: date_format = 'YYYY-MM-DD' if plexpy.CONFIG.TIME_FORMAT: time_format = plexpy.CONFIG.TIME_FORMAT else: time_format = 'HH:mm' formats = {'date_format': date_format, 'time_format': time_format} cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(formats) @cherrypy.expose def home_stats(self, time_range='30', stat_type='0', stat_count='5', **kwargs): data_factory = datafactory.DataFactory() stats_data = data_factory.get_home_stats(time_range=time_range, stat_type=stat_type, stat_count=stat_count) return serve_template(templatename="home_stats.html", title="Stats", data=stats_data) @cherrypy.expose def library_stats(self, **kwargs): pms_connect = pmsconnect.PmsConnect() stats_data = pms_connect.get_library_stats() return serve_template(templatename="library_stats.html", title="Library Stats", data=stats_data) @cherrypy.expose def history(self): return serve_template(templatename="history.html", title="History") @cherrypy.expose def users(self): return serve_template(templatename="users.html", title="Users") @cherrypy.expose def graphs(self): return serve_template(templatename="graphs.html", title="Graphs") @cherrypy.expose def sync(self): return serve_template(templatename="sync.html", title="Synced Items") @cherrypy.expose def user(self, user=None, user_id=None): user_data = users.Users() if user_id: try: user_details = user_data.get_user_details(user_id=user_id) except: logger.warn("Unable to retrieve friendly name for user_id %s " % user_id) elif user: try: user_details = user_data.get_user_details(user=user) except: logger.warn("Unable to retrieve friendly name for user %s " % user) else: logger.debug(u"User page requested but no parameters received.") raise cherrypy.HTTPRedirect("home") return serve_template(templatename="user.html", title="User", data=user_details) @cherrypy.expose def edit_user_dialog(self, user=None, user_id=None, **kwargs): user_data = users.Users() if user_id: result = user_data.get_user_friendly_name(user_id=user_id) status_message = '' elif user: result = user_data.get_user_friendly_name(user=user) status_message = '' else: result = None status_message = 'An error occured.' return serve_template(templatename="edit_user.html", title="Edit User", data=result, status_message=status_message) @cherrypy.expose def edit_user(self, user=None, user_id=None, friendly_name=None, **kwargs): if 'do_notify' in kwargs: do_notify = kwargs.get('do_notify') else: do_notify = 0 if 'keep_history' in kwargs: keep_history = kwargs.get('keep_history') else: keep_history = 0 if 'thumb' in kwargs: custom_avatar = kwargs['thumb'] else: custom_avatar = '' user_data = users.Users() if user_id: try: user_data.set_user_friendly_name(user_id=user_id, friendly_name=friendly_name, do_notify=do_notify, keep_history=keep_history) user_data.set_user_profile_url(user_id=user_id, profile_url=custom_avatar) status_message = "Successfully updated user." return status_message except: status_message = "Failed to update user." return status_message if user: try: user_data.set_user_friendly_name(user=user, friendly_name=friendly_name, do_notify=do_notify, keep_history=keep_history) user_data.set_user_profile_url(user=user, profile_url=custom_avatar) status_message = "Successfully updated user." return status_message except: status_message = "Failed to update user." return status_message @cherrypy.expose def get_stream_data(self, row_id=None, user=None, **kwargs): data_factory = datafactory.DataFactory() stream_data = data_factory.get_stream_details(row_id) return serve_template(templatename="stream_data.html", title="Stream Data", data=stream_data, user=user) @cherrypy.expose def get_ip_address_details(self, ip_address=None, **kwargs): import socket try: socket.inet_aton(ip_address) except socket.error: ip_address = None return serve_template(templatename="ip_address_modal.html", title="IP Address Details", data=ip_address) @cherrypy.expose def get_user_list(self, **kwargs): user_data = users.Users() user_list = user_data.get_user_list(kwargs=kwargs) cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(user_list) @cherrypy.expose def checkGithub(self): from plexpy import versioncheck versioncheck.checkGithub() raise cherrypy.HTTPRedirect("home") @cherrypy.expose def logs(self): return serve_template(templatename="logs.html", title="Log", lineList=plexpy.LOG_LIST) @cherrypy.expose def clearLogs(self): plexpy.LOG_LIST = [] logger.info("Web logs cleared") raise cherrypy.HTTPRedirect("logs") @cherrypy.expose def toggleVerbose(self): plexpy.VERBOSE = not plexpy.VERBOSE logger.initLogger(console=not plexpy.QUIET, log_dir=plexpy.CONFIG.LOG_DIR, verbose=plexpy.VERBOSE) logger.info("Verbose toggled, set to %s", plexpy.VERBOSE) logger.debug("If you read this message, debug logging is available") raise cherrypy.HTTPRedirect("logs") @cherrypy.expose def getLog(self, start=0, length=100, **kwargs): start = int(start) length = int(length) search_value = "" search_regex = "" order_column = 0 order_dir = "desc" if 'order[0][dir]' in kwargs: order_dir = kwargs.get('order[0][dir]', "desc") if 'order[0][column]' in kwargs: order_column = kwargs.get('order[0][column]', "0") if 'search[value]' in kwargs: search_value = kwargs.get('search[value]', "") if 'search[regex]' in kwargs: search_regex = kwargs.get('search[regex]', "") filtered = [] if search_value == "": filtered = plexpy.LOG_LIST[::] else: filtered = [row for row in plexpy.LOG_LIST for column in row if search_value.lower() in column.lower()] sortcolumn = 0 if order_column == '1': sortcolumn = 2 elif order_column == '2': sortcolumn = 1 filtered.sort(key=lambda x: x[sortcolumn], reverse=order_dir == "desc") rows = filtered[start:(start + length)] rows = [[row[0], row[2], row[1]] for row in rows] return json.dumps({ 'recordsFiltered': len(filtered), 'recordsTotal': len(plexpy.LOG_LIST), 'data': rows, }) @cherrypy.expose def get_plex_log(self, window=1000, **kwargs): log_lines = [] try: log_lines = {'data': log_reader.get_log_tail(window=window)} except: logger.warn("Unable to retrieve Plex Logs.") cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(log_lines) @cherrypy.expose def generateAPI(self): apikey = hashlib.sha224(str(random.getrandbits(256))).hexdigest()[0:32] logger.info("New API generated") return apikey @cherrypy.expose def settings(self): interface_dir = os.path.join(plexpy.PROG_DIR, 'data/interfaces/') interface_list = [name for name in os.listdir(interface_dir) if os.path.isdir(os.path.join(interface_dir, name))] # Initialise blank passwords so we do not expose them in the html forms # but users are still able to clear them if plexpy.CONFIG.HTTP_PASSWORD != '': http_password = ' ' else: http_password = '' config = { "http_host": plexpy.CONFIG.HTTP_HOST, "http_username": plexpy.CONFIG.HTTP_USERNAME, "http_port": plexpy.CONFIG.HTTP_PORT, "http_password": http_password, "launch_browser": checked(plexpy.CONFIG.LAUNCH_BROWSER), "enable_https": checked(plexpy.CONFIG.ENABLE_HTTPS), "https_cert": plexpy.CONFIG.HTTPS_CERT, "https_key": plexpy.CONFIG.HTTPS_KEY, "api_enabled": checked(plexpy.CONFIG.API_ENABLED), "api_key": plexpy.CONFIG.API_KEY, "update_db_interval": plexpy.CONFIG.UPDATE_DB_INTERVAL, "freeze_db": checked(plexpy.CONFIG.FREEZE_DB), "log_dir": plexpy.CONFIG.LOG_DIR, "cache_dir": plexpy.CONFIG.CACHE_DIR, "check_github": checked(plexpy.CONFIG.CHECK_GITHUB), "interface_list": interface_list, "growl_enabled": checked(plexpy.CONFIG.GROWL_ENABLED), "growl_host": plexpy.CONFIG.GROWL_HOST, "growl_password": plexpy.CONFIG.GROWL_PASSWORD, "prowl_enabled": checked(plexpy.CONFIG.PROWL_ENABLED), "prowl_keys": plexpy.CONFIG.PROWL_KEYS, "prowl_priority": plexpy.CONFIG.PROWL_PRIORITY, "xbmc_enabled": checked(plexpy.CONFIG.XBMC_ENABLED), "xbmc_host": plexpy.CONFIG.XBMC_HOST, "xbmc_username": plexpy.CONFIG.XBMC_USERNAME, "xbmc_password": plexpy.CONFIG.XBMC_PASSWORD, "plex_enabled": checked(plexpy.CONFIG.PLEX_ENABLED), "plex_client_host": plexpy.CONFIG.PLEX_CLIENT_HOST, "plex_username": plexpy.CONFIG.PLEX_USERNAME, "plex_password": plexpy.CONFIG.PLEX_PASSWORD, "nma_enabled": checked(plexpy.CONFIG.NMA_ENABLED), "nma_apikey": plexpy.CONFIG.NMA_APIKEY, "nma_priority": int(plexpy.CONFIG.NMA_PRIORITY), "pushalot_enabled": checked(plexpy.CONFIG.PUSHALOT_ENABLED), "pushalot_apikey": plexpy.CONFIG.PUSHALOT_APIKEY, "pushover_enabled": checked(plexpy.CONFIG.PUSHOVER_ENABLED), "pushover_keys": plexpy.CONFIG.PUSHOVER_KEYS, "pushover_apitoken": plexpy.CONFIG.PUSHOVER_APITOKEN, "pushover_priority": plexpy.CONFIG.PUSHOVER_PRIORITY, "pushbullet_enabled": checked(plexpy.CONFIG.PUSHBULLET_ENABLED), "pushbullet_apikey": plexpy.CONFIG.PUSHBULLET_APIKEY, "pushbullet_deviceid": plexpy.CONFIG.PUSHBULLET_DEVICEID, "twitter_enabled": checked(plexpy.CONFIG.TWITTER_ENABLED), "osx_notify_enabled": checked(plexpy.CONFIG.OSX_NOTIFY_ENABLED), "osx_notify_app": plexpy.CONFIG.OSX_NOTIFY_APP, "boxcar_enabled": checked(plexpy.CONFIG.BOXCAR_ENABLED), "boxcar_token": plexpy.CONFIG.BOXCAR_TOKEN, "cache_sizemb": plexpy.CONFIG.CACHE_SIZEMB, "email_enabled": checked(plexpy.CONFIG.EMAIL_ENABLED), "email_from": plexpy.CONFIG.EMAIL_FROM, "email_to": plexpy.CONFIG.EMAIL_TO, "email_smtp_server": plexpy.CONFIG.EMAIL_SMTP_SERVER, "email_smtp_user": plexpy.CONFIG.EMAIL_SMTP_USER, "email_smtp_password": plexpy.CONFIG.EMAIL_SMTP_PASSWORD, "email_smtp_port": int(plexpy.CONFIG.EMAIL_SMTP_PORT), "email_tls": checked(plexpy.CONFIG.EMAIL_TLS), "pms_identifier": plexpy.CONFIG.PMS_IDENTIFIER, "pms_ip": plexpy.CONFIG.PMS_IP, "pms_logs_folder": plexpy.CONFIG.PMS_LOGS_FOLDER, "pms_port": plexpy.CONFIG.PMS_PORT, "pms_token": plexpy.CONFIG.PMS_TOKEN, "pms_ssl": checked(plexpy.CONFIG.PMS_SSL), "pms_use_bif": checked(plexpy.CONFIG.PMS_USE_BIF), "pms_uuid": plexpy.CONFIG.PMS_UUID, "plexwatch_database": plexpy.CONFIG.PLEXWATCH_DATABASE, "date_format": plexpy.CONFIG.DATE_FORMAT,<|fim▁hole|> "grouping_charts": checked(plexpy.CONFIG.GROUPING_CHARTS), "tv_notify_enable": checked(plexpy.CONFIG.TV_NOTIFY_ENABLE), "movie_notify_enable": checked(plexpy.CONFIG.MOVIE_NOTIFY_ENABLE), "music_notify_enable": checked(plexpy.CONFIG.MUSIC_NOTIFY_ENABLE), "tv_notify_on_start": checked(plexpy.CONFIG.TV_NOTIFY_ON_START), "movie_notify_on_start": checked(plexpy.CONFIG.MOVIE_NOTIFY_ON_START), "music_notify_on_start": checked(plexpy.CONFIG.MUSIC_NOTIFY_ON_START), "tv_notify_on_stop": checked(plexpy.CONFIG.TV_NOTIFY_ON_STOP), "movie_notify_on_stop": checked(plexpy.CONFIG.MOVIE_NOTIFY_ON_STOP), "music_notify_on_stop": checked(plexpy.CONFIG.MUSIC_NOTIFY_ON_STOP), "tv_notify_on_pause": checked(plexpy.CONFIG.TV_NOTIFY_ON_PAUSE), "movie_notify_on_pause": checked(plexpy.CONFIG.MOVIE_NOTIFY_ON_PAUSE), "music_notify_on_pause": checked(plexpy.CONFIG.MUSIC_NOTIFY_ON_PAUSE), "monitoring_interval": plexpy.CONFIG.MONITORING_INTERVAL, "refresh_users_interval": plexpy.CONFIG.REFRESH_USERS_INTERVAL, "refresh_users_on_startup": checked(plexpy.CONFIG.REFRESH_USERS_ON_STARTUP), "ip_logging_enable": checked(plexpy.CONFIG.IP_LOGGING_ENABLE), "video_logging_enable": checked(plexpy.CONFIG.VIDEO_LOGGING_ENABLE), "music_logging_enable": checked(plexpy.CONFIG.MUSIC_LOGGING_ENABLE), "logging_ignore_interval": plexpy.CONFIG.LOGGING_IGNORE_INTERVAL, "pms_is_remote": checked(plexpy.CONFIG.PMS_IS_REMOTE), "notify_watched_percent": plexpy.CONFIG.NOTIFY_WATCHED_PERCENT, "notify_on_start_subject_text": plexpy.CONFIG.NOTIFY_ON_START_SUBJECT_TEXT, "notify_on_start_body_text": plexpy.CONFIG.NOTIFY_ON_START_BODY_TEXT, "notify_on_stop_subject_text": plexpy.CONFIG.NOTIFY_ON_STOP_SUBJECT_TEXT, "notify_on_stop_body_text": plexpy.CONFIG.NOTIFY_ON_STOP_BODY_TEXT, "notify_on_pause_subject_text": plexpy.CONFIG.NOTIFY_ON_PAUSE_SUBJECT_TEXT, "notify_on_pause_body_text": plexpy.CONFIG.NOTIFY_ON_PAUSE_BODY_TEXT, "notify_on_resume_subject_text": plexpy.CONFIG.NOTIFY_ON_RESUME_SUBJECT_TEXT, "notify_on_resume_body_text": plexpy.CONFIG.NOTIFY_ON_RESUME_BODY_TEXT, "notify_on_buffer_subject_text": plexpy.CONFIG.NOTIFY_ON_BUFFER_SUBJECT_TEXT, "notify_on_buffer_body_text": plexpy.CONFIG.NOTIFY_ON_BUFFER_BODY_TEXT, "notify_on_watched_subject_text": plexpy.CONFIG.NOTIFY_ON_WATCHED_SUBJECT_TEXT, "notify_on_watched_body_text": plexpy.CONFIG.NOTIFY_ON_WATCHED_BODY_TEXT, "home_stats_length": plexpy.CONFIG.HOME_STATS_LENGTH, "home_stats_type": checked(plexpy.CONFIG.HOME_STATS_TYPE), "home_stats_count": plexpy.CONFIG.HOME_STATS_COUNT, "buffer_threshold": plexpy.CONFIG.BUFFER_THRESHOLD, "buffer_wait": plexpy.CONFIG.BUFFER_WAIT } return serve_template(templatename="settings.html", title="Settings", config=config) @cherrypy.expose def configUpdate(self, **kwargs): # Handle the variable config options. Note - keys with False values aren't getting passed checked_configs = [ "launch_browser", "enable_https", "api_enabled", "freeze_db", "growl_enabled", "prowl_enabled", "xbmc_enabled", "check_github", "plex_enabled", "nma_enabled", "pushalot_enabled", "pushover_enabled", "pushbullet_enabled", "twitter_enabled", "osx_notify_enabled", "boxcar_enabled", "email_enabled", "email_tls", "grouping_global_history", "grouping_user_history", "grouping_charts", "pms_use_bif", "pms_ssl", "tv_notify_enable", "movie_notify_enable", "music_notify_enable", "tv_notify_on_start", "movie_notify_on_start", "music_notify_on_start", "tv_notify_on_stop", "movie_notify_on_stop", "music_notify_on_stop", "tv_notify_on_pause", "movie_notify_on_pause", "music_notify_on_pause", "refresh_users_on_startup", "ip_logging_enable", "video_logging_enable", "music_logging_enable", "pms_is_remote", "home_stats_type" ] for checked_config in checked_configs: if checked_config not in kwargs: # checked items should be zero or one. if they were not sent then the item was not checked kwargs[checked_config] = 0 # If http password exists in config, do not overwrite when blank value received if 'http_password' in kwargs: if kwargs['http_password'] == ' ' and plexpy.CONFIG.HTTP_PASSWORD != '': kwargs['http_password'] = plexpy.CONFIG.HTTP_PASSWORD for plain_config, use_config in [(x[4:], x) for x in kwargs if x.startswith('use_')]: # the use prefix is fairly nice in the html, but does not match the actual config kwargs[plain_config] = kwargs[use_config] del kwargs[use_config] # Check if we should refresh our data refresh_users = False reschedule = False if 'monitoring_interval' in kwargs and 'refresh_users_interval' in kwargs: if (kwargs['monitoring_interval'] != str(plexpy.CONFIG.MONITORING_INTERVAL)) or \ (kwargs['refresh_users_interval'] != str(plexpy.CONFIG.REFRESH_USERS_INTERVAL)): reschedule = True if 'pms_ip' in kwargs: if kwargs['pms_ip'] != plexpy.CONFIG.PMS_IP: refresh_users = True plexpy.CONFIG.process_kwargs(kwargs) # Write the config plexpy.CONFIG.write() # Get new server URLs for SSL communications. plextv.get_real_pms_url() # Reconfigure scheduler if intervals changed if reschedule: plexpy.initialize_scheduler() # Refresh users table if our server IP changes. if refresh_users: threading.Thread(target=plextv.refresh_users).start() raise cherrypy.HTTPRedirect("settings") @cherrypy.expose def set_notification_config(self, **kwargs): # Handle the variable config options. Note - keys with False values aren't getting passed checked_configs = [ "email_tls" ] for checked_config in checked_configs: if checked_config not in kwargs: # checked items should be zero or one. if they were not sent then the item was not checked kwargs[checked_config] = 0 for plain_config, use_config in [(x[4:], x) for x in kwargs if x.startswith('use_')]: # the use prefix is fairly nice in the html, but does not match the actual config kwargs[plain_config] = kwargs[use_config] del kwargs[use_config] plexpy.CONFIG.process_kwargs(kwargs) # Write the config plexpy.CONFIG.write() cherrypy.response.status = 200 @cherrypy.expose def do_state_change(self, signal, title, timer): message = title quote = self.random_arnold_quotes() plexpy.SIGNAL = signal return serve_template(templatename="shutdown.html", title=title, message=message, timer=timer, quote=quote) @cherrypy.expose def get_history(self, user=None, user_id=None, **kwargs): custom_where=[] if user_id: custom_where = [['user_id', user_id]] elif user: custom_where = [['user', user]] if 'rating_key' in kwargs: rating_key = kwargs.get('rating_key', "") custom_where = [['rating_key', rating_key]] if 'parent_rating_key' in kwargs: rating_key = kwargs.get('parent_rating_key', "") custom_where = [['parent_rating_key', rating_key]] if 'grandparent_rating_key' in kwargs: rating_key = kwargs.get('grandparent_rating_key', "") custom_where = [['grandparent_rating_key', rating_key]] if 'start_date' in kwargs: start_date = kwargs.get('start_date', "") custom_where = [['strftime("%Y-%m-%d", datetime(date, "unixepoch", "localtime"))', start_date]] data_factory = datafactory.DataFactory() history = data_factory.get_history(kwargs=kwargs, custom_where=custom_where) cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(history) @cherrypy.expose def history_table_modal(self, start_date=None, **kwargs): return serve_template(templatename="history_table_modal.html", title="History Data", data=start_date) @cherrypy.expose def shutdown(self): return self.do_state_change('shutdown', 'Shutting Down', 15) @cherrypy.expose def restart(self): return self.do_state_change('restart', 'Restarting', 30) @cherrypy.expose def update(self): return self.do_state_change('update', 'Updating', 120) @cherrypy.expose def api(self, *args, **kwargs): from plexpy.api import Api a = Api() a.checkParams(*args, **kwargs) return a.fetchData() @cherrypy.expose def twitterStep1(self): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" tweet = notifiers.TwitterNotifier() return tweet._get_authorization() @cherrypy.expose def twitterStep2(self, key): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" tweet = notifiers.TwitterNotifier() result = tweet._get_credentials(key) logger.info(u"result: " + str(result)) if result: return "Key verification successful" else: return "Unable to verify key" @cherrypy.expose def testTwitter(self): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" tweet = notifiers.TwitterNotifier() result = tweet.test_notify() if result: return "Tweet successful, check your twitter to make sure it worked" else: return "Error sending tweet" @cherrypy.expose def osxnotifyregister(self, app): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" from osxnotify import registerapp as osxnotify result, msg = osxnotify.registerapp(app) if result: osx_notify = notifiers.OSX_NOTIFY() osx_notify.notify('Registered', result, 'Success :-)') logger.info('Registered %s, to re-register a different app, delete this app first' % result) else: logger.warn(msg) return msg @cherrypy.expose def get_pms_token(self): token = plextv.PlexTV() result = token.get_token() if result: return result else: logger.warn('Unable to retrieve Plex.tv token.') return False @cherrypy.expose def get_pms_sessions_json(self, **kwargs): pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_sessions('json') if result: cherrypy.response.headers['Content-type'] = 'application/json' return result else: logger.warn('Unable to retrieve data.') return False @cherrypy.expose def get_current_activity(self, **kwargs): try: pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_current_activity() except: return serve_template(templatename="current_activity.html", data=None) if result: return serve_template(templatename="current_activity.html", data=result) else: logger.warn('Unable to retrieve data.') return serve_template(templatename="current_activity.html", data=None) @cherrypy.expose def get_current_activity_header(self, **kwargs): try: pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_current_activity() except IOError, e: return serve_template(templatename="current_activity_header.html", data=None) if result: return serve_template(templatename="current_activity_header.html", data=result['stream_count']) else: logger.warn('Unable to retrieve data.') return serve_template(templatename="current_activity_header.html", data=None) @cherrypy.expose def get_recently_added(self, count='0', **kwargs): try: pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_recently_added_details(count) except IOError, e: return serve_template(templatename="recently_added.html", data=None) if result: return serve_template(templatename="recently_added.html", data=result['recently_added']) else: logger.warn('Unable to retrieve data.') return serve_template(templatename="recently_added.html", data=None) @cherrypy.expose def pms_image_proxy(self, img='', width='0', height='0', fallback=None, **kwargs): try: pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_image(img, width, height) cherrypy.response.headers['Content-type'] = result[1] return result[0] except: logger.warn('Image proxy queried but errors occured.') if fallback == 'poster': logger.info('Trying fallback image...') try: fallback_image = open(self.interface_dir + common.DEFAULT_POSTER_THUMB, 'rb') cherrypy.response.headers['Content-type'] = 'image/png' return fallback_image except IOError, e: logger.error('Unable to read fallback image. %s' % e) elif fallback == 'cover': logger.info('Trying fallback image...') try: fallback_image = open(self.interface_dir + common.DEFAULT_COVER_THUMB, 'rb') cherrypy.response.headers['Content-type'] = 'image/png' return fallback_image except IOError, e: logger.error('Unable to read fallback image. %s' % e) return None @cherrypy.expose def info(self, item_id=None, source=None, **kwargs): metadata = None config = { "pms_identifier": plexpy.CONFIG.PMS_IDENTIFIER } if source == 'history': data_factory = datafactory.DataFactory() metadata = data_factory.get_metadata_details(row_id=item_id) else: pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_metadata_details(rating_key=item_id) if result: metadata = result['metadata'] if metadata: return serve_template(templatename="info.html", data=metadata, title="Info", config=config) else: logger.warn('Unable to retrieve data.') return serve_template(templatename="info.html", data=None, title="Info") @cherrypy.expose def get_user_recently_watched(self, user=None, user_id=None, limit='10', **kwargs): data_factory = datafactory.DataFactory() result = data_factory.get_recently_watched(user_id=user_id, user=user, limit=limit) if result: return serve_template(templatename="user_recently_watched.html", data=result, title="Recently Watched") else: logger.warn('Unable to retrieve data.') return serve_template(templatename="user_recently_watched.html", data=None, title="Recently Watched") @cherrypy.expose def get_user_watch_time_stats(self, user=None, user_id=None, **kwargs): user_data = users.Users() result = user_data.get_user_watch_time_stats(user_id=user_id, user=user) if result: return serve_template(templatename="user_watch_time_stats.html", data=result, title="Watch Stats") else: logger.warn('Unable to retrieve data.') return serve_template(templatename="user_watch_time_stats.html", data=None, title="Watch Stats") @cherrypy.expose def get_user_platform_stats(self, user=None, user_id=None, **kwargs): user_data = users.Users() result = user_data.get_user_platform_stats(user_id=user_id, user=user) if result: return serve_template(templatename="user_platform_stats.html", data=result, title="Platform Stats") else: logger.warn('Unable to retrieve data.') return serve_template(templatename="user_platform_stats.html", data=None, title="Platform Stats") @cherrypy.expose def get_item_children(self, rating_key='', **kwargs): pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_item_children(rating_key) if result: return serve_template(templatename="info_children_list.html", data=result, title="Children List") else: logger.warn('Unable to retrieve data.') return serve_template(templatename="info_children_list.html", data=None, title="Children List") @cherrypy.expose def get_metadata_json(self, rating_key='', **kwargs): pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_metadata(rating_key, 'json') if result: cherrypy.response.headers['Content-type'] = 'application/json' return result else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_metadata_xml(self, rating_key='', **kwargs): pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_metadata(rating_key) if result: cherrypy.response.headers['Content-type'] = 'application/xml' return result else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_recently_added_json(self, count='0', **kwargs): pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_recently_added(count, 'json') if result: cherrypy.response.headers['Content-type'] = 'application/json' return result else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_episode_list_json(self, rating_key='', **kwargs): pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_episode_list(rating_key, 'json') if result: cherrypy.response.headers['Content-type'] = 'application/json' return result else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_user_ips(self, user_id=None, user=None, **kwargs): custom_where=[] if user_id: custom_where = [['user_id', user_id]] elif user: custom_where = [['user', user]] user_data = users.Users() history = user_data.get_user_unique_ips(kwargs=kwargs, custom_where=custom_where) cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(history) @cherrypy.expose def get_plays_by_date(self, time_range='30', y_axis='plays', **kwargs): graph = graphs.Graphs() result = graph.get_total_plays_per_day(time_range=time_range, y_axis=y_axis) if result: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(result) else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_plays_by_dayofweek(self, time_range='30', y_axis='plays', **kwargs): graph = graphs.Graphs() result = graph.get_total_plays_per_dayofweek(time_range=time_range, y_axis=y_axis) if result: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(result) else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_plays_by_hourofday(self, time_range='30', y_axis='plays', **kwargs): graph = graphs.Graphs() result = graph.get_total_plays_per_hourofday(time_range=time_range, y_axis=y_axis) if result: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(result) else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_plays_per_month(self, y_axis='plays', **kwargs): graph = graphs.Graphs() result = graph.get_total_plays_per_month(y_axis=y_axis) if result: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(result) else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_plays_by_top_10_platforms(self, time_range='30', y_axis='plays', **kwargs): graph = graphs.Graphs() result = graph.get_total_plays_by_top_10_platforms(time_range=time_range, y_axis=y_axis) if result: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(result) else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_plays_by_top_10_users(self, time_range='30', y_axis='plays', **kwargs): graph = graphs.Graphs() result = graph.get_total_plays_by_top_10_users(time_range=time_range, y_axis=y_axis) if result: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(result) else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_plays_by_stream_type(self, time_range='30', y_axis='plays', **kwargs): graph = graphs.Graphs() result = graph.get_total_plays_per_stream_type(time_range=time_range, y_axis=y_axis) if result: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(result) else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_plays_by_source_resolution(self, time_range='30', y_axis='plays', **kwargs): graph = graphs.Graphs() result = graph.get_total_plays_by_source_resolution(time_range=time_range, y_axis=y_axis) if result: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(result) else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_plays_by_stream_resolution(self, time_range='30', y_axis='plays', **kwargs): graph = graphs.Graphs() result = graph.get_total_plays_by_stream_resolution(time_range=time_range, y_axis=y_axis) if result: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(result) else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_stream_type_by_top_10_users(self, time_range='30', y_axis='plays', **kwargs): graph = graphs.Graphs() result = graph.get_stream_type_by_top_10_users(time_range=time_range, y_axis=y_axis) if result: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(result) else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_stream_type_by_top_10_platforms(self, time_range='30', y_axis='plays', **kwargs): graph = graphs.Graphs() result = graph.get_stream_type_by_top_10_platforms(time_range=time_range, y_axis=y_axis) if result: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(result) else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_friends_list(self, **kwargs): plex_tv = plextv.PlexTV() result = plex_tv.get_plextv_friends('json') if result: cherrypy.response.headers['Content-type'] = 'application/json' return result else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_user_details(self, **kwargs): plex_tv = plextv.PlexTV() result = plex_tv.get_plextv_user_details('json') if result: cherrypy.response.headers['Content-type'] = 'application/json' return result else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_server_list(self, **kwargs): plex_tv = plextv.PlexTV() result = plex_tv.get_plextv_server_list('json') if result: cherrypy.response.headers['Content-type'] = 'application/json' return result else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_sync_lists(self, machine_id='', **kwargs): plex_tv = plextv.PlexTV() result = plex_tv.get_plextv_sync_lists(machine_id=machine_id, output_format='json') if result: cherrypy.response.headers['Content-type'] = 'application/json' return result else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_servers(self, **kwargs): pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_server_list(output_format='json') if result: cherrypy.response.headers['Content-type'] = 'application/json' return result else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_servers_info(self, **kwargs): pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_servers_info() if result: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(result) else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_server_prefs(self, **kwargs): pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_server_prefs(output_format='json') if result: cherrypy.response.headers['Content-type'] = 'application/json' return result else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_activity(self, **kwargs): pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_current_activity() if result: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(result) else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_full_users_list(self, **kwargs): plex_tv = plextv.PlexTV() result = plex_tv.get_full_users_list() if result: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(result) else: logger.warn('Unable to retrieve data.') @cherrypy.expose def refresh_users_list(self, **kwargs): threading.Thread(target=plextv.refresh_users).start() logger.info('Manual user list refresh requested.') @cherrypy.expose def get_sync(self, machine_id=None, user_id=None, **kwargs): pms_connect = pmsconnect.PmsConnect() server_id = pms_connect.get_server_identity() plex_tv = plextv.PlexTV() if not machine_id: result = plex_tv.get_synced_items(machine_id=server_id['machine_identifier'], user_id=user_id) else: result = plex_tv.get_synced_items(machine_id=machine_id, user_id=user_id) if result: output = {"data": result} else: logger.warn('Unable to retrieve sync data for user.') output = {"data": []} cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps(output) @cherrypy.expose def get_sync_item(self, sync_id, **kwargs): pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_sync_item(sync_id, output_format='json') if result: cherrypy.response.headers['Content-type'] = 'application/json' return result else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_sync_transcode_queue(self, **kwargs): pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_sync_transcode_queue(output_format='json') if result: cherrypy.response.headers['Content-type'] = 'application/json' return result else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_server_pref(self, pref=None, **kwargs): pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_server_pref(pref=pref) if result: return result else: logger.warn('Unable to retrieve data.') @cherrypy.expose def get_plexwatch_export_data(self, database_path=None, table_name=None, import_ignore_interval=0, **kwargs): from plexpy import plexwatch_import db_check_msg = plexwatch_import.validate_database(database=database_path, table_name=table_name) if db_check_msg == 'success': threading.Thread(target=plexwatch_import.import_from_plexwatch, kwargs={'database': database_path, 'table_name': table_name, 'import_ignore_interval': import_ignore_interval}).start() return 'Import has started. Check the PlexPy logs to monitor any problems.' else: return db_check_msg @cherrypy.expose def plexwatch_import(self, **kwargs): return serve_template(templatename="plexwatch_import.html", title="Import PlexWatch Database") @cherrypy.expose def get_server_id(self, hostname=None, port=None, **kwargs): from plexpy import http_handler if hostname and port: request_handler = http_handler.HTTPHandler(host=hostname, port=port, token=None) uri = '/identity' request = request_handler.make_request(uri=uri, proto='http', request_type='GET', output_format='', no_token=True) if request: cherrypy.response.headers['Content-type'] = 'application/xml' return request else: logger.warn('Unable to retrieve data.') return None else: return None @cherrypy.expose def random_arnold_quotes(self, **kwargs): from random import randint quote_list = ['To crush your enemies, see them driven before you, and to hear the lamentation of their women!', 'Your clothes, give them to me, now!', 'Do it!', 'If it bleeds, we can kill it', 'See you at the party Richter!', 'Let off some steam, Bennett', 'I\'ll be back', 'Get to the chopper!', 'Hasta La Vista, Baby!', 'It\'s not a tumor!', 'Dillon, you son of a bitch!', 'Benny!! Screw you!!', 'Stop whining! You kids are soft. You lack discipline.', 'Nice night for a walk.', 'Stick around!', 'I need your clothes, your boots and your motorcycle.', 'No, it\'s not a tumor. It\'s not a tumor!', 'I LIED!', 'See you at the party, Richter!', 'Are you Sarah Conner?', 'I\'m a cop you idiot!', 'Come with me if you want to live.', 'Who is your daddy and what does he do?' ] random_number = randint(0, len(quote_list) - 1) return quote_list[int(random_number)] @cherrypy.expose def get_notification_agent_config(self, config_id, **kwargs): config = notifiers.get_notification_agent_config(config_id=config_id) checkboxes = {'email_tls': checked(plexpy.CONFIG.EMAIL_TLS)} return serve_template(templatename="notification_config.html", title="Notification Configuration", data=config, checkboxes=checkboxes) @cherrypy.expose def get_notification_agent_triggers(self, config_id, **kwargs): if config_id.isdigit(): agents = notifiers.available_notification_agents() for agent in agents: if int(config_id) == agent['id']: this_agent = agent break else: this_agent = None else: return None return serve_template(templatename="notification_triggers_modal.html", title="Notification Triggers", data=this_agent) @cherrypy.expose def delete_history_rows(self, row_id, **kwargs): data_factory = datafactory.DataFactory() if row_id: delete_row = data_factory.delete_session_history_rows(row_id=row_id) if delete_row: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps({'message': delete_row}) else: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps({'message': 'no data received'}) @cherrypy.expose def delete_all_user_history(self, user_id, **kwargs): data_factory = datafactory.DataFactory() if user_id: delete_row = data_factory.delete_all_user_history(user_id=user_id) if delete_row: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps({'message': delete_row}) else: cherrypy.response.headers['Content-type'] = 'application/json' return json.dumps({'message': 'no data received'})<|fim▁end|>
"time_format": plexpy.CONFIG.TIME_FORMAT, "grouping_global_history": checked(plexpy.CONFIG.GROUPING_GLOBAL_HISTORY), "grouping_user_history": checked(plexpy.CONFIG.GROUPING_USER_HISTORY),
<|file_name|>negamax.rs<|end_file_name|><|fim▁begin|>//! An implementation of Negamax. //! //! Currently, only the basic alpha-pruning variant is implemented. Further work //! could add advanced features, like history and/or transposition tables. This //! picks randomly among the "best" moves, so that it's non-deterministic. use super::super::interface::*; use rand; use rand::Rng; use std::cmp::max; use std::marker::PhantomData; fn negamax<E: Evaluator>(s: &mut <E::G as Game>::S, depth: usize, mut alpha: Evaluation, beta: Evaluation, p: Player) -> Evaluation where <<E as Evaluator>::G as Game>::M: Copy { let maybe_winner = E::G::get_winner(s); if depth == 0 || maybe_winner.is_some() { return p * E::evaluate(s, maybe_winner); } let mut moves = [None; 100]; E::G::generate_moves(s, p, &mut moves); let mut best = Evaluation::Worst; for m in moves.iter().take_while(|om| om.is_some()).map(|om| om.unwrap()) { m.apply(s); let value = -negamax::<E>(s, depth - 1, -beta, -alpha, -p); m.undo(s); best = max(best, value); alpha = max(alpha, value); if alpha >= beta { break } } best } /// Options to use for the `Negamax` engine. pub struct Options { /// The maximum depth within the game tree. pub max_depth: usize, } pub struct Negamax<E> { opts: Options, rng: rand::ThreadRng, _eval: PhantomData<E>, } impl<E: Evaluator> Negamax<E> { pub fn new(opts: Options) -> Negamax<E> { Negamax { opts: opts, rng: rand::thread_rng(), _eval: PhantomData, } } } impl<E: Evaluator> Strategy<E::G> for Negamax<E><|fim▁hole|> let mut best = Evaluation::Worst; let mut moves = [None; 100]; E::G::generate_moves(s, p, &mut moves); let mut candidate_moves = Vec::new(); let mut s_clone = s.clone(); for m in moves.iter().take_while(|m| m.is_some()).map(|m| m.unwrap()) { // determine value for this move m.apply(&mut s_clone); let value = -negamax::<E>(&mut s_clone, self.opts.max_depth, Evaluation::Worst, Evaluation::Best, -p); m.undo(&mut s_clone); // this move is a candidate move if value == best { candidate_moves.push(m); // this move is better than any previous, so it's the sole candidate } else if value > best { candidate_moves.clear(); candidate_moves.push(m); best = value; } } if candidate_moves.is_empty() { None } else { Some(candidate_moves[self.rng.gen_range(0, candidate_moves.len())]) } } }<|fim▁end|>
where <E::G as Game>::S: Clone, <E::G as Game>::M: Copy { fn choose_move(&mut self, s: &<E::G as Game>::S, p: Player) -> Option<<E::G as Game>::M> {
<|file_name|>exp_app.js<|end_file_name|><|fim▁begin|>var express = require('express'); var reload = require('reload'); var fs = require('fs'); var wss = new require('ws').Server({port: 3030}); var app = express(); var Chopper = require('./lib/Chopper'); app.set('port', process.env.PORT || 3000); app.set('view engine', 'ejs'); app.use(require('./routes/index')); app.use(require('./routes/visual')); app.use(require('./routes/d3')); app.use(require('./routes/control')); app.use(require('./routes/config')); app.use(require('./routes/api')); app.use('/jquery', express.static('./node_modules/jquery/dist')); app.use(express.static('./public')); // global vars for the EJS (Embedded JavaScript) framework app.locals.siteTitle = 'CS'; // Control Systems title var server = app.listen(app.get('port'), function () { console.log('Example app listening on port: ' + app.get('port') + '!'); }); reload(server, app); wss.on('connection', function (ws) { ws.send('Welcome to cyber chat'); ws.on('message', function (msg) { <|fim▁hole|> } }) }); var chop = new Chopper(); chop.on('ready', function() { console.log('Chopper ready'); app.set('chopper', chop); }); chop.on('change', function(value) { wss.clients.forEach(function (ws, index, list) { ws.send(JSON.stringify(value)); }) }); chop.on('data', function(type, data) { fs.writeFile(type + Date.now() + '.csv', data, function (err) { console.log(`${type} data saved`); }); });<|fim▁end|>
if (msg == 'exit') { ws.close();
<|file_name|>monitor.rs<|end_file_name|><|fim▁begin|>use winapi::{ shared::{ minwindef::{BOOL, DWORD, LPARAM, TRUE, WORD}, windef::{HDC, HMONITOR, HWND, LPRECT, POINT}, }, um::{wingdi, winuser}, }; use std::{ collections::{BTreeSet, VecDeque}, io, mem, ptr, }; use super::util; use crate::{ dpi::{PhysicalPosition, PhysicalSize}, monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode}, platform_impl::platform::{ dpi::{dpi_to_scale_factor, get_monitor_dpi}, window::Window, }, }; #[derive(Clone)] pub struct VideoMode { pub(crate) size: (u32, u32), pub(crate) bit_depth: u16, pub(crate) refresh_rate: u16, pub(crate) monitor: MonitorHandle, pub(crate) native_video_mode: wingdi::DEVMODEW, } impl PartialEq for VideoMode { fn eq(&self, other: &Self) -> bool { self.size == other.size && self.bit_depth == other.bit_depth && self.refresh_rate == other.refresh_rate && self.monitor == other.monitor } } impl Eq for VideoMode {} impl std::hash::Hash for VideoMode { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.size.hash(state); self.bit_depth.hash(state); self.refresh_rate.hash(state); self.monitor.hash(state); } } impl std::fmt::Debug for VideoMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("VideoMode") .field("size", &self.size) .field("bit_depth", &self.bit_depth) .field("refresh_rate", &self.refresh_rate) .field("monitor", &self.monitor) .finish() } } impl VideoMode { pub fn size(&self) -> PhysicalSize<u32> { self.size.into() } pub fn bit_depth(&self) -> u16 { self.bit_depth } pub fn refresh_rate(&self) -> u16 { self.refresh_rate } pub fn monitor(&self) -> RootMonitorHandle { RootMonitorHandle { inner: self.monitor.clone(), } } } #[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)] pub struct MonitorHandle(HMONITOR); // Send is not implemented for HMONITOR, we have to wrap it and implement it manually. // For more info see:<|fim▁hole|> unsafe extern "system" fn monitor_enum_proc( hmonitor: HMONITOR, _hdc: HDC, _place: LPRECT, data: LPARAM, ) -> BOOL { let monitors = data as *mut VecDeque<MonitorHandle>; (*monitors).push_back(MonitorHandle::new(hmonitor)); TRUE // continue enumeration } pub fn available_monitors() -> VecDeque<MonitorHandle> { let mut monitors: VecDeque<MonitorHandle> = VecDeque::new(); unsafe { winuser::EnumDisplayMonitors( ptr::null_mut(), ptr::null_mut(), Some(monitor_enum_proc), &mut monitors as *mut _ as LPARAM, ); } monitors } pub fn primary_monitor() -> MonitorHandle { const ORIGIN: POINT = POINT { x: 0, y: 0 }; let hmonitor = unsafe { winuser::MonitorFromPoint(ORIGIN, winuser::MONITOR_DEFAULTTOPRIMARY) }; MonitorHandle::new(hmonitor) } pub fn current_monitor(hwnd: HWND) -> MonitorHandle { let hmonitor = unsafe { winuser::MonitorFromWindow(hwnd, winuser::MONITOR_DEFAULTTONEAREST) }; MonitorHandle::new(hmonitor) } impl Window { pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { available_monitors() } pub fn primary_monitor(&self) -> Option<RootMonitorHandle> { let monitor = primary_monitor(); Some(RootMonitorHandle { inner: monitor }) } } pub(crate) fn get_monitor_info(hmonitor: HMONITOR) -> Result<winuser::MONITORINFOEXW, io::Error> { let mut monitor_info: winuser::MONITORINFOEXW = unsafe { mem::zeroed() }; monitor_info.cbSize = mem::size_of::<winuser::MONITORINFOEXW>() as DWORD; let status = unsafe { winuser::GetMonitorInfoW( hmonitor, &mut monitor_info as *mut winuser::MONITORINFOEXW as *mut winuser::MONITORINFO, ) }; if status == 0 { Err(io::Error::last_os_error()) } else { Ok(monitor_info) } } impl MonitorHandle { pub(crate) fn new(hmonitor: HMONITOR) -> Self { MonitorHandle(hmonitor) } #[inline] pub fn name(&self) -> Option<String> { let monitor_info = get_monitor_info(self.0).unwrap(); Some(util::wchar_ptr_to_string(monitor_info.szDevice.as_ptr())) } #[inline] pub fn native_identifier(&self) -> String { self.name().unwrap() } #[inline] pub fn hmonitor(&self) -> HMONITOR { self.0 } #[inline] pub fn size(&self) -> PhysicalSize<u32> { let monitor_info = get_monitor_info(self.0).unwrap(); PhysicalSize { width: (monitor_info.rcMonitor.right - monitor_info.rcMonitor.left) as u32, height: (monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top) as u32, } } #[inline] pub fn position(&self) -> PhysicalPosition<i32> { let monitor_info = get_monitor_info(self.0).unwrap(); PhysicalPosition { x: monitor_info.rcMonitor.left, y: monitor_info.rcMonitor.top, } } #[inline] pub fn scale_factor(&self) -> f64 { dpi_to_scale_factor(get_monitor_dpi(self.0).unwrap_or(96)) } #[inline] pub fn video_modes(&self) -> impl Iterator<Item = RootVideoMode> { // EnumDisplaySettingsExW can return duplicate values (or some of the // fields are probably changing, but we aren't looking at those fields // anyway), so we're using a BTreeSet deduplicate let mut modes = BTreeSet::new(); let mut i = 0; loop { unsafe { let monitor_info = get_monitor_info(self.0).unwrap(); let device_name = monitor_info.szDevice.as_ptr(); let mut mode: wingdi::DEVMODEW = mem::zeroed(); mode.dmSize = mem::size_of_val(&mode) as WORD; if winuser::EnumDisplaySettingsExW(device_name, i, &mut mode, 0) == 0 { break; } i += 1; const REQUIRED_FIELDS: DWORD = wingdi::DM_BITSPERPEL | wingdi::DM_PELSWIDTH | wingdi::DM_PELSHEIGHT | wingdi::DM_DISPLAYFREQUENCY; assert!(mode.dmFields & REQUIRED_FIELDS == REQUIRED_FIELDS); modes.insert(RootVideoMode { video_mode: VideoMode { size: (mode.dmPelsWidth, mode.dmPelsHeight), bit_depth: mode.dmBitsPerPel as u16, refresh_rate: mode.dmDisplayFrequency as u16, monitor: self.clone(), native_video_mode: mode, }, }); } } modes.into_iter() } }<|fim▁end|>
// https://github.com/retep998/winapi-rs/issues/360 // https://github.com/retep998/winapi-rs/issues/396 unsafe impl Send for MonitorHandle {}
<|file_name|>serial_serial.py<|end_file_name|><|fim▁begin|># Copyright (C) 2016 The BET Development Team # -*- coding: utf-8 -*- # This demonstrates how to use BET in serial to sample a serial external model. # run by calling "python serial_serial.py" import os import subprocess import scipy.io as sio import bet.sampling.basicSampling as bsam def lb_model(input_data): io_file_name = "io_file" io_mdat = dict() io_mdat['input'] = input_data <|fim▁hole|> # save the input to file sio.savemat(io_file_name, io_mdat) # run the model subprocess.call(['python', 'serial_model.py', io_file_name]) # read the output from file io_mdat = sio.loadmat(io_file_name) output_data = io_mdat['output'] return output_data my_sampler = bsam.sampler(lb_model) my_discretization = my_sampler.create_random_discretization(sample_type='r', input_obj=4, savefile="serial_serial_example", num_samples=100)<|fim▁end|>
<|file_name|>start.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # coding:utf-8 import os import sys import time import traceback from datetime import datetime import atexit # reduce resource request for threading # for OpenWrt import threading try: threading.stack_size(128 * 1024) except: pass try: import tracemalloc tracemalloc.start(10) except: pass current_path = os.path.dirname(os.path.abspath(__file__)) default_path = os.path.abspath(os.path.join(current_path, os.pardir)) data_path = os.path.abspath(os.path.join(default_path, os.pardir, os.pardir, 'data')) data_launcher_path = os.path.join(data_path, 'launcher') noarch_lib = os.path.abspath(os.path.join(default_path, 'lib', 'noarch')) sys.path.append(noarch_lib) running_file = os.path.join(data_launcher_path, "Running.Lck") def create_data_path(): if not os.path.isdir(data_path): os.mkdir(data_path) if not os.path.isdir(data_launcher_path): os.mkdir(data_launcher_path) data_gae_proxy_path = os.path.join(data_path, 'gae_proxy') if not os.path.isdir(data_gae_proxy_path): os.mkdir(data_gae_proxy_path) create_data_path() from xlog import getLogger log_file = os.path.join(data_launcher_path, "launcher.log") xlog = getLogger("launcher", file_name=log_file) def uncaughtExceptionHandler(etype, value, tb): if etype == KeyboardInterrupt: # Ctrl + C on console xlog.warn("KeyboardInterrupt, exiting...") module_init.stop_all() os._exit(0) exc_info = ''.join(traceback.format_exception(etype, value, tb)) print(("uncaught Exception:\n" + exc_info)) with open(os.path.join(data_launcher_path, "error.log"), "a") as fd: now = datetime.now() time_str = now.strftime("%b %d %H:%M:%S.%f")[:19] fd.write("%s type:%s value=%s traceback:%s" % (time_str, etype, value, exc_info)) xlog.error("uncaught Exception, type=%s value=%s traceback:%s", etype, value, exc_info) # sys.exit(1) sys.excepthook = uncaughtExceptionHandler has_desktop = True def unload(module): for m in list(sys.modules.keys()): if m == module or m.startswith(module + "."): del sys.modules[m] for p in list(sys.path_importer_cache.keys()): if module in p: del sys.path_importer_cache[p] try: del module except: pass try: sys.path.insert(0, noarch_lib) import OpenSSL as oss_test xlog.info("use build-in openssl lib") except Exception as e1: xlog.info("import build-in openssl fail:%r", e1) sys.path.pop(0) del sys.path_importer_cache[noarch_lib] unload("OpenSSL") unload("cryptography") unload("cffi") try: import OpenSSL except Exception as e2: xlog.exception("import system python-OpenSSL fail:%r", e2) print("Try install python-openssl\r\n") input("Press Enter to continue...") os._exit(0) import sys_platform from config import config import web_control import module_init import update import update_from_github import download_modules def exit_handler(): print('Stopping all modules before exit!') module_init.stop_all() web_control.stop() atexit.register(exit_handler) def main(): # change path to launcher global __file__ __file__ = os.path.abspath(__file__) if os.path.islink(__file__): __file__ = getattr(os, 'readlink', lambda x: x)(__file__) os.chdir(os.path.dirname(os.path.abspath(__file__))) if sys.platform == "win32" and config.show_compat_suggest: import win_compat_suggest win_compat_suggest.main() current_version = update_from_github.current_version() xlog.info("start XX-Net %s", current_version) web_control.confirm_xxnet_not_running() import post_update post_update.check() allow_remote = 0 no_mess_system = 0 if len(sys.argv) > 1: for s in sys.argv[1:]: xlog.info("command args:%s", s) if s == "-allow_remote": allow_remote = 1 elif s == "-no_mess_system": no_mess_system = 1 if allow_remote or config.allow_remote_connect: xlog.info("start with allow remote connect.") module_init.xargs["allow_remote"] = 1 if os.getenv("XXNET_NO_MESS_SYSTEM", "0") != "0" or no_mess_system or config.no_mess_system: xlog.info("start with no_mess_system, no CA will be imported to system.") module_init.xargs["no_mess_system"] = 1 if os.path.isfile(running_file): restart_from_except = True else: restart_from_except = False module_init.start_all_auto() web_control.start(allow_remote) if has_desktop and config.popup_webui == 1 and not restart_from_except: host_port = config.control_port import webbrowser webbrowser.open("http://localhost:%s/" % host_port) update.start() if has_desktop: download_modules.start_download() update_from_github.cleanup() if config.show_systray:<|fim▁hole|> while True: time.sleep(1) if __name__ == '__main__': try: main() except KeyboardInterrupt: # Ctrl + C on console module_init.stop_all() os._exit(0) sys.exit() except Exception as e: xlog.exception("launcher except:%r", e) input("Press Enter to continue...")<|fim▁end|>
sys_platform.sys_tray.serve_forever() else:
<|file_name|>func_noerror_query_getattr.py<|end_file_name|><|fim▁begin|># pylint:disable=R0201 from OpenOrange import * from Document import Document from Label import Label from SQLTools import codeOrder, monthCode from datetime import datetime class AlotmentDoc(Document): classattr = "classattr" def getRecorda(self): class newObj(object): Status = 1 RootLabel = "100" SerNr = "SerNr" Labels = "100,200" TransDate = datetime.now().date() def name(self): return "Alotment" return newObj() def getExtra(self, val1, val2="2", val3="3", val4=4): specs = self.getRecorda() sql = "WHERE?AND [al].{%s} IN ('%s')\n" % ("SerNr", "','".join([val1, val3, val2])) sql += "WHERE?AND [al].{SerNr} = i|%i|\n" % specs.Status sql += "WHERE?AND [al].TransDate < d|%s|\n" % specs.TransDate sql += "WHERE?AND SerNr = "<|fim▁hole|> sql += "%s" % val4 if 1 in [0, 0]: pass else: sql += "" return sql def getExtra2(self, test): parent = self specs = self.getRecorda() mydict = {1:1, 2:2} mylist = [1, 2] listcomp = "listcomp," + "extra" if test > 0: return specs.Status x = "'%s' as test_date\n, " % date("") x += "'%s' as test_time\n, " % time("") x += "'%i' as test_len\n, " % len(specs.RootLabel) x += "'%s' as test_map\n, " % "','".join(map(str, mylist)) x += "'%s' as test_keys\n, " % "','".join(mydict.keys()) x += "'%s' as test_subscript\n," % ["SerNr","RoomType"][specs.Status] #x += "'%s' as test_classattr\n, " % self.classattr x += '"%s" as test_dic\n, ' % mydict x += "'%s' as test_parentattr\n, " % parent.record #Parent None attribute x += '"%s" as test_binoplist\n, ' % mylist #+ mylist x += '"%s" as test_listcomp1\n, ' % "".join([a.strip() for a in listcomp.split(',')]) x += '"%s" as test_listcomp2\n, ' % "".join([d for d in listcomp]) x += '"%s" as test_listcomp3\n, ' % "".join([str(b) for b in listcomp]) x += '"%s" as test_listcomp4\n,' % "".join([c.strip() for c in listcomp]) x += '"%s" as test_listcomp5\n,' % [('s|%s|') % (z) for z in mylist] x += '"%s" as test_listcomp6\n,' % "".join([y for y in ("a", "b")]) # pylint:disable=E1101 x += '"%s" as inferenceErr\n,' % self.non.existant x += '"%s" as indexErr\n' % mylist[2] return x def getExtra3(self): specs = self.getRecorda() subquery = Query() subquery.sql = "SerNr" return "ORDER BY %s, %s" % (specs.SerNr, subquery.sql) def getExtra4(self): specs = self.getRecorda() labels = None if specs.Labels: lis = [] labs = specs.Labels.split(",") for lb in labs: lis.append("','".join(Label.getTreeLeaves(lb))) labels = "','".join(lis) return "WHERE?AND SerNr IN ('%s') " % labels def getExtra5(self, txt): txt = txt.replace(":1","RoomType IS NULL\n") return txt def getExtra6(self): txt = "" q = {} q["one"] = Query() q["one"].sql = "WHERE?AND SerNr IS NULL\n" q["two"] = Query() q["two"].sql = "WHERE?AND SerNr IS NOT NULL\n" slist = ["one", "two"] for index in slist: txt += q[index].sql return txt def getExtra7(self): specs = self.getRecorda() factor = 0.0 if 1 > 0: factor = (float(specs.Status) / float(specs.Status)) txt = "WHERE?AND (%s / 1) * %s > 0\n" % (1, factor) return txt def run(self): specs = self.getRecorda() leaves = Label.getTreeLeaves(specs.RootLabel) query7 = Query() query7.sql = "SELECT SerNr, %s,\n" % codeOrder("SerNr", leaves) query7.sql += monthCode("[al].TransDate") query7.sql += "\n, %s, \n" % self.getExtra2(test=1) query7.sql += self.getExtra2(0) query7.sql += "\nFROM %s al\n" % specs.name() query7.sql += self.getExtra("1", "2", val3="33") query7.sql += self.getExtra4() query7.sql += self.getExtra5("WHERE?AND :1") query7.sql += self.getExtra6() query7.sql += self.getExtra7() method = getattr(self, "getExtra3____"[:-4]) query7.sql += method() query7.open() self.run2([100, 200]) def run2(self, extraList): query2 = Query() query2.sql = self.getMore(extraList) query2.open() def getMore(self, moreList): return "SELECT * FROM Alotment WHERE SerNr IN ('%s')" % "','".join(moreList)<|fim▁end|>
if specs.Status == 1:
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings <|fim▁hole|>class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserActivateKey', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('activation_key', models.CharField(max_length=40, null=True, blank=True)), ('key_expires', models.DateTimeField(null=True, blank=True)), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'tcms_user_activate_keys', }, ), ]<|fim▁end|>