desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Delete train log. Parameters args : dictionary, find items to delete, leave it empty to delete all log.'
@AutoFill def del_train_log(self, args={}):
self.db.TrainLog.delete_many(args) print '[TensorDB] Delete TrainLog SUCCESS'
'Save the validating log. Parameters args : dictionary, items to save. Examples >>> db.valid_log(time=time.time(), {\'loss\': loss, \'acc\': acc})'
@AutoFill def valid_log(self, args={}):
_result = self.db.ValidLog.insert_one(args) _log = self._print_dict(args) print ('[TensorDB] ValidLog: ' + _log) return _result
'Delete validation log. Parameters args : dictionary, find items to delete, leave it empty to delete all log.'
@AutoFill def del_valid_log(self, args={}):
self.db.ValidLog.delete_many(args) print '[TensorDB] Delete ValidLog SUCCESS'
'Save the testing log. Parameters args : dictionary, items to save. Examples >>> db.test_log(time=time.time(), {\'loss\': loss, \'acc\': acc})'
@AutoFill def test_log(self, args={}):
_result = self.db.TestLog.insert_one(args) _log = self._print_dict(args) print ('[TensorDB] TestLog: ' + _log) return _result
'Delete test log. Parameters args : dictionary, find items to delete, leave it empty to delete all log.'
@AutoFill def del_test_log(self, args={}):
self.db.TestLog.delete_many(args) print '[TensorDB] Delete TestLog SUCCESS'
'Save the job. Parameters script : a script file name or None. args : dictionary, items to save. Examples >>> # Save your job >>> db.save_job(\'your_script.py\', {\'job_id\': 1, \'learning_rate\': 0.01, \'n_units\': 100}) >>> # Run your job >>> temp = db.find_one_job(args={\'job_id\': 1}) >>> print(temp[\'learning_rate...
@AutoFill def save_job(self, script=None, args={}):
self.__autofill(args) if (script is not None): _script = open(script, 'rb').read() args.update({'script': _script, 'script_name': script}) _result = self.db.Job.replace_one(args, args, upsert=True) _log = self._print_dict(args) print '[TensorDB] Save Job: script={}, args=...
'Find one job from MongoDB Job Collections. Parameters args : dictionary, find items. Returns dictionary : contains all meta data and script.'
@AutoFill def find_one_job(self, args={}):
temp = self.db.Job.find_one(args) if (temp is not None): if ('script_name' in temp.keys()): f = open(('_' + temp['script_name']), 'wb') f.write(temp['script']) f.close() print '[TensorDB] Find Job: {}'.format(args) else: print '[TensorDB] ...
'Print all info of parameters in the network'
def print_params(self, details=True):
for (i, p) in enumerate(self.all_params): if details: try: val = p.eval() print ' param {:3}: {:20} {:15} {} (mean: {:<18}, median: {:<18}, std: {:<18}) '.format(i, p.name, str(val.shape), p.dtype.name, v...
'Print all info of layers in the network'
def print_layers(self):
for (i, layer) in enumerate(self.all_layers): print ' layer {:3}: {:20} {:15} {}'.format(i, layer.name, str(layer.get_shape()), layer.dtype.name)
'Return the number of parameters in the network'
def count_params(self):
n_params = 0 for (i, p) in enumerate(self.all_params): n = 1 for s in p.get_shape(): try: s = int(s) except: s = 1 if s: n = (n * s) n_params = (n_params + n) return n_params
'Run a step of the model feeding the given inputs. Parameters session : tensorflow session to use. encoder_inputs : list of numpy int vectors to feed as encoder inputs. decoder_inputs : list of numpy int vectors to feed as decoder inputs. target_weights : list of numpy float vectors to feed as target weights. bucket_id...
def step(self, session, encoder_inputs, decoder_inputs, target_weights, bucket_id, forward_only):
(encoder_size, decoder_size) = self.buckets[bucket_id] if (len(encoder_inputs) != encoder_size): raise ValueError(('Encoder length must be equal to the one in bucket, %d != %d.' % (len(encoder_inputs), encoder_size))) if (len(decoder_inputs) != decoder_size): ...
'Get a random batch of data from the specified bucket, prepare for step. To feed data in step(..) it must be a list of batch-major vectors, while data here contains single length-major cases. So the main logic of this function is to re-index data cases to be in the proper format for feeding. Parameters data : a tuple o...
def get_batch(self, data, bucket_id, PAD_ID=0, GO_ID=1, EOS_ID=2, UNK_ID=3):
(encoder_size, decoder_size) = self.buckets[bucket_id] (encoder_inputs, decoder_inputs) = ([], []) for _ in xrange(self.batch_size): (encoder_input, decoder_input) = random.choice(data[bucket_id]) encoder_pad = ([PAD_ID] * (encoder_size - len(encoder_input))) encoder_inputs.append(li...
'Initializes the vocabulary.'
def __init__(self, vocab, unk_id):
self._vocab = vocab self._unk_id = unk_id
'Returns the integer id of a word string.'
def word_to_id(self, word):
if (word in self._vocab): return self._vocab[word] else: return self._unk_id
'Returns the integer word id of a word string.'
def word_to_id(self, word):
if (word in self.vocab): return self.vocab[word] else: return self.unk_id
'Returns the word string of an integer word id.'
def id_to_word(self, word_id):
if (word_id >= len(self.reverse_vocab)): return self.reverse_vocab[self.unk_id] else: return self.reverse_vocab[word_id]
'Loads a key in PKCS#1 DER or PEM format. :param keyfile: contents of a DER- or PEM-encoded file that contains the public key. :param format: the format of the file to load; \'PEM\' or \'DER\' :return: a PublicKey object'
@classmethod def load_pkcs1(cls, keyfile, format='PEM'):
methods = {'PEM': cls._load_pkcs1_pem, 'DER': cls._load_pkcs1_der} method = cls._assert_format_exists(format, methods) return method(keyfile)
'Checks whether the given file format exists in \'methods\'.'
@staticmethod def _assert_format_exists(file_format, methods):
try: return methods[file_format] except KeyError: formats = ', '.join(sorted(methods.keys())) raise ValueError(('Unsupported format: %r, try one of %s' % (file_format, formats)))
'Saves the public key in PKCS#1 DER or PEM format. :param format: the format to save; \'PEM\' or \'DER\' :returns: the DER- or PEM-encoded public key.'
def save_pkcs1(self, format='PEM'):
methods = {'PEM': self._save_pkcs1_pem, 'DER': self._save_pkcs1_der} method = self._assert_format_exists(format, methods) return method()
'Performs blinding on the message using random number \'r\'. :param message: the message, as integer, to blind. :type message: int :param r: the random number to blind with. :type r: int :return: the blinded message. :rtype: int The blinding is such that message = unblind(decrypt(blind(encrypt(message))). See https://e...
def blind(self, message, r):
return ((message * pow(r, self.e, self.n)) % self.n)
'Performs blinding on the message using random number \'r\'. :param blinded: the blinded message, as integer, to unblind. :param r: the random number to unblind with. :return: the original message. The blinding is such that message = unblind(decrypt(blind(encrypt(message))). See https://en.wikipedia.org/wiki/Blinding_%...
def unblind(self, blinded, r):
return ((rsa.common.inverse(r, self.n) * blinded) % self.n)
'Returns the key as tuple for pickling.'
def __getstate__(self):
return (self.n, self.e)
'Sets the key from tuple.'
def __setstate__(self, state):
(self.n, self.e) = state
'Loads a key in PKCS#1 DER format. :param keyfile: contents of a DER-encoded file that contains the public key. :return: a PublicKey object First let\'s construct a DER encoded key: >>> import base64 >>> b64der = \'MAwCBQCNGmYtAgMBAAE=\' >>> der = base64.standard_b64decode(b64der) This loads the file: >>> PublicKey._lo...
@classmethod def _load_pkcs1_der(cls, keyfile):
from pyasn1.codec.der import decoder from rsa.asn1 import AsnPubKey (priv, _) = decoder.decode(keyfile, asn1Spec=AsnPubKey()) return cls(n=int(priv['modulus']), e=int(priv['publicExponent']))
'Saves the public key in PKCS#1 DER format. @returns: the DER-encoded public key.'
def _save_pkcs1_der(self):
from pyasn1.codec.der import encoder from rsa.asn1 import AsnPubKey asn_key = AsnPubKey() asn_key.setComponentByName('modulus', self.n) asn_key.setComponentByName('publicExponent', self.e) return encoder.encode(asn_key)
'Loads a PKCS#1 PEM-encoded public key file. The contents of the file before the "-----BEGIN RSA PUBLIC KEY-----" and after the "-----END RSA PUBLIC KEY-----" lines is ignored. :param keyfile: contents of a PEM-encoded file that contains the public key. :return: a PublicKey object'
@classmethod def _load_pkcs1_pem(cls, keyfile):
der = rsa.pem.load_pem(keyfile, 'RSA PUBLIC KEY') return cls._load_pkcs1_der(der)
'Saves a PKCS#1 PEM-encoded public key file. :return: contents of a PEM-encoded file that contains the public key.'
def _save_pkcs1_pem(self):
der = self._save_pkcs1_der() return rsa.pem.save_pem(der, 'RSA PUBLIC KEY')
'Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL. These files can be recognised in that they start with BEGIN PUBLIC KEY rather than BEGIN RSA PUBLIC KEY. The contents of the file before the "-----BEGIN PUBLIC KEY-----" and after the "-----END PUBLIC KEY-----" lines is ignored. :param keyfile: contents of a P...
@classmethod def load_pkcs1_openssl_pem(cls, keyfile):
der = rsa.pem.load_pem(keyfile, 'PUBLIC KEY') return cls.load_pkcs1_openssl_der(der)
'Loads a PKCS#1 DER-encoded public key file from OpenSSL. :param keyfile: contents of a DER-encoded file that contains the public key, from OpenSSL. :return: a PublicKey object'
@classmethod def load_pkcs1_openssl_der(cls, keyfile):
from rsa.asn1 import OpenSSLPubKey from pyasn1.codec.der import decoder from pyasn1.type import univ (keyinfo, _) = decoder.decode(keyfile, asn1Spec=OpenSSLPubKey()) if (keyinfo['header']['oid'] != univ.ObjectIdentifier('1.2.840.113549.1.1.1')): raise TypeError('This is not a DER...
'Returns the key as tuple for pickling.'
def __getstate__(self):
return (self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef)
'Sets the key from tuple.'
def __setstate__(self, state):
(self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef) = state
'Decrypts the message using blinding to prevent side-channel attacks. :param encrypted: the encrypted message :type encrypted: int :returns: the decrypted message :rtype: int'
def blinded_decrypt(self, encrypted):
blind_r = rsa.randnum.randint((self.n - 1)) blinded = self.blind(encrypted, blind_r) decrypted = rsa.core.decrypt_int(blinded, self.d, self.n) return self.unblind(decrypted, blind_r)
'Encrypts the message using blinding to prevent side-channel attacks. :param message: the message to encrypt :type message: int :returns: the encrypted message :rtype: int'
def blinded_encrypt(self, message):
blind_r = rsa.randnum.randint((self.n - 1)) blinded = self.blind(message, blind_r) encrypted = rsa.core.encrypt_int(blinded, self.d, self.n) return self.unblind(encrypted, blind_r)
'Loads a key in PKCS#1 DER format. :param keyfile: contents of a DER-encoded file that contains the private key. :return: a PrivateKey object First let\'s construct a DER encoded key: >>> import base64 >>> b64der = \'MC4CAQACBQDeKYlRAgMBAAECBQDHn4npAgMA/icCAwDfxwIDANcXAgInbwIDAMZt\' >>> der = base64.standard_b64decode(...
@classmethod def _load_pkcs1_der(cls, keyfile):
from pyasn1.codec.der import decoder (priv, _) = decoder.decode(keyfile) if (priv[0] != 0): raise ValueError(('Unable to read this file, version %s != 0' % priv[0])) as_ints = tuple((int(x) for x in priv[1:9])) return cls(*as_ints)
'Saves the private key in PKCS#1 DER format. @returns: the DER-encoded private key.'
def _save_pkcs1_der(self):
from pyasn1.type import univ, namedtype from pyasn1.codec.der import encoder class AsnPrivKey(univ.Sequence, ): componentType = namedtype.NamedTypes(namedtype.NamedType('version', univ.Integer()), namedtype.NamedType('modulus', univ.Integer()), namedtype.NamedType('publicExponent', univ.Integer()), ...
'Loads a PKCS#1 PEM-encoded private key file. The contents of the file before the "-----BEGIN RSA PRIVATE KEY-----" and after the "-----END RSA PRIVATE KEY-----" lines is ignored. :param keyfile: contents of a PEM-encoded file that contains the private key. :return: a PrivateKey object'
@classmethod def _load_pkcs1_pem(cls, keyfile):
der = rsa.pem.load_pem(keyfile, b('RSA PRIVATE KEY')) return cls._load_pkcs1_der(der)
'Saves a PKCS#1 PEM-encoded private key file. :return: contents of a PEM-encoded file that contains the private key.'
def _save_pkcs1_pem(self):
der = self._save_pkcs1_der() return rsa.pem.save_pem(der, b('RSA PRIVATE KEY'))
'Runs the program.'
def __call__(self):
(cli, cli_args) = self.parse_cli() key = self.read_key(cli_args[0], cli.keyform) indata = self.read_infile(cli.input) print(self.operation_progressive.title(), file=sys.stderr) outdata = self.perform_operation(indata, key, cli_args) if self.has_output: self.write_outfile(outdata, cli.out...
'Parse the CLI options :returns: (cli_opts, cli_args)'
def parse_cli(self):
parser = OptionParser(usage=self.usage, description=self.description) parser.add_option('-i', '--input', type='string', help=self.input_help) if self.has_output: parser.add_option('-o', '--output', type='string', help=self.output_help) parser.add_option('--keyform', help=('Key format of ...
'Reads a public or private key.'
def read_key(self, filename, keyform):
print(('Reading %s key from %s' % (self.keyname, filename)), file=sys.stderr) with open(filename, 'rb') as keyfile: keydata = keyfile.read() return self.key_class.load_pkcs1(keydata, keyform)
'Read the input file'
def read_infile(self, inname):
if inname: print(('Reading input from %s' % inname), file=sys.stderr) with open(inname, 'rb') as infile: return infile.read() print('Reading input from stdin', file=sys.stderr) return sys.stdin.read()
'Write the output file'
def write_outfile(self, outdata, outname):
if outname: print(('Writing output to %s' % outname), file=sys.stderr) with open(outname, 'wb') as outfile: outfile.write(outdata) else: print('Writing output to stdout', file=sys.stderr) sys.stdout.write(outdata)
'Encrypts files.'
def perform_operation(self, indata, pub_key, cli_args=None):
return rsa.encrypt(indata, pub_key)
'Decrypts files.'
def perform_operation(self, indata, priv_key, cli_args=None):
return rsa.decrypt(indata, priv_key)
'Signs files.'
def perform_operation(self, indata, priv_key, cli_args):
hash_method = cli_args[1] if (hash_method not in HASH_METHODS): raise SystemExit(('Invalid hash method, choose one of %s' % ', '.join(HASH_METHODS))) return rsa.sign(indata, priv_key, hash_method)
'Verifies files.'
def perform_operation(self, indata, pub_key, cli_args):
signature_file = cli_args[1] with open(signature_file, 'rb') as sigfile: signature = sigfile.read() try: rsa.verify(indata, signature, pub_key) except rsa.VerificationError: raise SystemExit('Verification failed.') print('Verification OK', file=sys.stderr)
'Closes any open file handles.'
def __del__(self):
for fobj in self.file_objects: fobj.close()
'Runs the program.'
def __call__(self):
(cli, cli_args) = self.parse_cli() key = self.read_key(cli_args[0], cli.keyform) infile = self.get_infile(cli.input) outfile = self.get_outfile(cli.output) print(self.operation_progressive.title(), file=sys.stderr) self.perform_operation(infile, outfile, key, cli_args)
'Returns the input file object'
def get_infile(self, inname):
if inname: print(('Reading input from %s' % inname), file=sys.stderr) fobj = open(inname, 'rb') self.file_objects.append(fobj) else: print('Reading input from stdin', file=sys.stderr) fobj = sys.stdin return fobj
'Returns the output file object'
def get_outfile(self, outname):
if outname: print(('Will write output to %s' % outname), file=sys.stderr) fobj = open(outname, 'wb') self.file_objects.append(fobj) else: print('Will write output to stdout', file=sys.stderr) fobj = sys.stdout return fobj
'Encrypts files to VARBLOCK.'
def perform_operation(self, infile, outfile, pub_key, cli_args=None):
return rsa.bigfile.encrypt_bigfile(infile, outfile, pub_key)
'Decrypts a VARBLOCK file.'
def perform_operation(self, infile, outfile, priv_key, cli_args=None):
return rsa.bigfile.decrypt_bigfile(infile, outfile, priv_key)
'Receive EXACTLY the number of bytes requested from the file object. Blocks until the required number of bytes have been received.'
def _readall(self, file, count):
data = '' while (len(data) < count): d = file.read((count - len(data))) if (not d): raise GeneralProxyError('Connection closed unexpectedly') data += d return data
'set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]]) Sets the proxy to be used. proxy_type - The type of the proxy to be used. Three types are supported: PROXY_TYPE_SOCKS4 (including socks4a), PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP addr - The address of the server (IP or DNS). port - The...
def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None):
self.proxy = (proxy_type, addr, port, rdns, (username.encode() if username else None), (password.encode() if password else None))
'Implements proxy connection for UDP sockets, which happens during the bind() phase.'
def bind(self, *pos, **kw):
(proxy_type, proxy_addr, proxy_port, rdns, username, password) = self.proxy if ((not proxy_type) or (self.type != socket.SOCK_DGRAM)): return _orig_socket.bind(self, *pos, **kw) if self._proxyconn: raise socket.error(EINVAL, 'Socket already bound to an address') if (proxy_...
'Returns the bound IP address and port number at the proxy.'
def get_proxy_sockname(self):
return self.proxy_sockname
'Returns the IP and port number of the proxy.'
def get_proxy_peername(self):
return _BaseSocket.getpeername(self)
'Returns the IP address and port number of the destination machine (note: get_proxy_peername returns the proxy)'
def get_peername(self):
return self.proxy_peername
'Negotiates a stream connection through a SOCKS5 server.'
def _negotiate_SOCKS5(self, *dest_addr):
CONNECT = '\x01' (self.proxy_peername, self.proxy_sockname) = self._SOCKS5_request(self, CONNECT, dest_addr)
'Send SOCKS5 request with given command (CMD field) and address (DST field). Returns resolved DST address that was used.'
def _SOCKS5_request(self, conn, cmd, dst):
(proxy_type, addr, port, rdns, username, password) = self.proxy writer = conn.makefile('wb') reader = conn.makefile('rb', 0) try: if (username and password): writer.write('\x05\x02\x00\x02') else: writer.write('\x05\x01\x00') writer.flush() chosen_...
'Return the host and port packed for the SOCKS5 protocol, and the resolved address as a tuple object.'
def _write_SOCKS5_address(self, addr, file):
(host, port) = addr (proxy_type, _, _, rdns, username, password) = self.proxy try: addr_bytes = socket.inet_aton(host) file.write(('\x01' + addr_bytes)) host = socket.inet_ntoa(addr_bytes) except socket.error: if rdns: host_bytes = host.encode('idna') ...
'Negotiates a connection through a SOCKS4 server.'
def _negotiate_SOCKS4(self, dest_addr, dest_port):
(proxy_type, addr, port, rdns, username, password) = self.proxy writer = self.makefile('wb') reader = self.makefile('rb', 0) try: remote_resolve = False try: addr_bytes = socket.inet_aton(dest_addr) except socket.error: if rdns: addr_bytes ...
'Negotiates a connection through an HTTP server. NOTE: This currently only supports HTTP CONNECT-style proxies.'
def _negotiate_HTTP(self, dest_addr, dest_port):
(proxy_type, addr, port, rdns, username, password) = self.proxy addr = (dest_addr if rdns else socket.gethostbyname(dest_addr)) self.sendall(((((((('CONNECT ' + addr.encode('idna')) + ':') + str(dest_port).encode()) + ' HTTP/1.1\r\n') + 'Host: ') + dest_addr.encode('idna')) + '\r\n\r\n')) fobj ...
'Connects to the specified destination through a proxy. Uses the same API as socket\'s connect(). To select the proxy server, use set_proxy(). dest_pair - 2-tuple of (IP/hostname, port).'
def connect(self, dest_pair):
(dest_addr, dest_port) = dest_pair if (self.type == socket.SOCK_DGRAM): if (not self._proxyconn): self.bind(('', 0)) dest_addr = socket.gethostbyname(dest_addr) if ((dest_addr == '0.0.0.0') and (not dest_port)): self.proxy_peername = None else: ...
'Return proxy address to connect to as tuple object'
def _proxy_addr(self):
(proxy_type, proxy_addr, proxy_port, rdns, username, password) = self.proxy proxy_port = (proxy_port or DEFAULT_PORTS.get(proxy_type)) if (not proxy_port): raise GeneralProxyError('Invalid proxy type') return (proxy_addr, proxy_port)
'ASN.1 tag class Returns : :py:class:`int` Tag class'
@property def tagClass(self):
return self.__tagClass
'ASN.1 tag format Returns : :py:class:`int` Tag format'
@property def tagFormat(self):
return self.__tagFormat
'ASN.1 tag ID Returns : :py:class:`int` Tag ID'
@property def tagId(self):
return self.__tagId
'Return base ASN.1 tag Returns : :class:`~pyasn1.type.tag.Tag` Base tag of this *TagSet*'
@property def baseTag(self):
return self.__baseTag
'Return ASN.1 tags Returns : :py:class:`tuple` Tuple of :class:`~pyasn1.type.tag.Tag` objects that this *TagSet* contains'
@property def superTags(self):
return self.__superTags
'Return explicitly tagged *TagSet* Create a new *TagSet* representing callee *TagSet* explicitly tagged with passed tag(s). With explicit tagging mode, new tags are appended to existing tag(s). Parameters superTag: :class:`~pyasn1.type.tag.Tag` *Tag* object to tag this *TagSet* Returns : :class:`~pyasn1.type.tag.TagSet...
def tagExplicitly(self, superTag):
if (superTag.tagClass == tagClassUniversal): raise error.PyAsn1Error("Can't tag with UNIVERSAL class tag") if (superTag.tagFormat != tagFormatConstructed): superTag = Tag(superTag.tagClass, tagFormatConstructed, superTag.tagId) return (self + superTag)
'Return implicitly tagged *TagSet* Create a new *TagSet* representing callee *TagSet* implicitly tagged with passed tag(s). With implicit tagging mode, new tag(s) replace the last existing tag. Parameters superTag: :class:`~pyasn1.type.tag.Tag` *Tag* object to tag this *TagSet* Returns : :class:`~pyasn1.type.tag.TagSet...
def tagImplicitly(self, superTag):
if self.__superTags: superTag = Tag(superTag.tagClass, self.__superTags[(-1)].tagFormat, superTag.tagId) return (self[:(-1)] + superTag)
'Test type relationship against given *TagSet* The callee is considered to be a supertype of given *TagSet* tag-wise if all tags in *TagSet* are present in the callee and they are in the same order. Parameters tagSet: :class:`~pyasn1.type.tag.TagSet` *TagSet* object to evaluate against the callee Returns : :py:class:`b...
def isSuperTagSetOf(self, tagSet):
if (len(tagSet) < self.__lenOfSuperTags): return False return (self.__superTags == tagSet[:self.__lenOfSuperTags])
'For |ASN.1| type is equivalent to *tagSet*'
@property def effectiveTagSet(self):
return self._tagSet
'Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects within callee object.'
@property def tagMap(self):
try: return self._tagMap except AttributeError: self._tagMap = tagmap.TagMap({self._tagSet: self}) return self._tagMap
'Examine |ASN.1| type for equality with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. No Python inheritance relationship between PyASN1 objects is considered. Parameters other: a pyasn1 type object Cla...
def isSameTypeWith(self, other, matchTags=True, matchConstraints=True):
return ((self is other) or (((not matchTags) or (self._tagSet == other.tagSet)) and ((not matchConstraints) or (self._subtypeSpec == other.subtypeSpec))))
'Examine |ASN.1| type for subtype relationship with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. No Python inheritance relationship between PyASN1 objects is considered. Parameters other: a pyasn1 typ...
def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True):
return (((not matchTags) or self._tagSet.isSuperTagSetOf(other.tagSet)) and ((not matchConstraints) or self._subtypeSpec.isSuperTypeOf(other.subtypeSpec)))
'Indicate if |ASN.1| object represents ASN.1 type or ASN.1 value. The PyASN1 type objects can only participate in types comparison and serve as a blueprint for serialization codecs to resolve ambiguous types. The PyASN1 value objects can additionally participate in most of built-in Python operations. Returns : :class:`...
@property def isValue(self):
return (self._value is not noValue)
'Create a copy of a |ASN.1| type or object. Any parameters to the *clone()* method will replace corresponding properties of the |ASN.1| object. Parameters value: :class:`tuple`, :class:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. tagSet: :py:class:`...
def clone(self, value=noValue, tagSet=None, subtypeSpec=None):
isModified = False if ((value is None) or (value is noValue)): value = self._value else: isModified = True if ((tagSet is None) or (tagSet is noValue)): tagSet = self._tagSet else: isModified = True if ((subtypeSpec is None) or (subtypeSpec is noValue)): s...
'Create a copy of a |ASN.1| type or object. Any parameters to the *subtype()* method will be added to the corresponding properties of the |ASN.1| object. Parameters value: :class:`tuple`, :class:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. implicitT...
def subtype(self, value=noValue, implicitTag=None, explicitTag=None, subtypeSpec=None):
isModified = False if ((value is None) or (value is noValue)): value = self._value else: isModified = True if ((implicitTag is not None) and (implicitTag is not noValue)): tagSet = self._tagSet.tagImplicitly(implicitTag) isModified = True elif ((explicitTag is not Non...
'Provide human-friendly printable object representation. Returns : :class:`str` human-friendly type and/or value representation.'
def prettyPrint(self, scope=0):
if self.isValue: return self.prettyOut(self._value) else: return '<no value>'
'Create a copy of a |ASN.1| type or object. Any parameters to the *clone()* method will replace corresponding properties of the |ASN.1| object. Parameters tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Obj...
def clone(self, tagSet=None, subtypeSpec=None, sizeSpec=None, cloneValueFlag=None):
if (tagSet is None): tagSet = self._tagSet if (subtypeSpec is None): subtypeSpec = self._subtypeSpec if (sizeSpec is None): sizeSpec = self._sizeSpec clone = self.__class__(self._componentType, tagSet, subtypeSpec, sizeSpec) if cloneValueFlag: self._cloneComponentValu...
'Create a copy of a |ASN.1| type or object. Any parameters to the *subtype()* method will be added to the corresponding properties of the |ASN.1| object. Parameters tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsInterse...
def subtype(self, implicitTag=None, explicitTag=None, subtypeSpec=None, sizeSpec=None, cloneValueFlag=None):
if ((implicitTag is not None) and (implicitTag is not noValue)): tagSet = self._tagSet.tagImplicitly(implicitTag) elif ((explicitTag is not None) and (explicitTag is not noValue)): tagSet = self._tagSet.tagExplicitly(explicitTag) else: tagSet = self._tagSet if ((subtypeSpec is No...
'Return *TagSet* to ASN.1 type map present in callee *TagMap*'
@property def presentTypes(self):
return self.__presentTypes
'Return *TagSet* collection unconditionally absent in callee *TagMap*'
@property def skipTypes(self):
return self.__skipTypes
'Return default ASN.1 type being returned for any missing *TagSet*'
@property def defaultType(self):
return self.__defaultType
'Create a copy of a |ASN.1| type or object. Any parameters to the *clone()* method will replace corresponding properties of the |ASN.1| object. Parameters value: :class:`int`, :class:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. tagSet: :py:class:`~p...
def clone(self, value=noValue, tagSet=None, subtypeSpec=None, namedValues=None):
isModified = False if ((value is None) or (value is noValue)): value = self._value else: isModified = True if ((tagSet is None) or (tagSet is noValue)): tagSet = self._tagSet else: isModified = True if ((subtypeSpec is None) or (subtypeSpec is noValue)): s...
'Create a copy of a |ASN.1| type or object. Any parameters to the *subtype()* method will be added to the corresponding properties of the |ASN.1| object. Parameters value: :class:`int`, :class:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. implicitTag...
def subtype(self, value=noValue, implicitTag=None, explicitTag=None, subtypeSpec=None, namedValues=None):
isModified = False if ((value is None) or (value is noValue)): value = self._value else: isModified = True if ((implicitTag is not None) and (implicitTag is not noValue)): tagSet = self._tagSet.tagImplicitly(implicitTag) isModified = True elif ((explicitTag is not Non...
'Create a copy of a |ASN.1| type or object. Any parameters to the *clone()* method will replace corresponding properties of the |ASN.1| object. Parameters value : :class:`int`, :class:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. tagSet: :py:class:`~...
def clone(self, value=noValue, tagSet=None, subtypeSpec=None, namedValues=None, binValue=noValue, hexValue=noValue):
isModified = False if (((value is None) or (value is noValue)) and (binValue is noValue) and (hexValue is noValue)): value = self._value else: isModified = True if ((tagSet is None) or (tagSet is noValue)): tagSet = self._tagSet else: isModified = True if ((subtyp...
'Create a copy of a |ASN.1| type or object. Any parameters to the *subtype()* method will be added to the corresponding properties of the |ASN.1| object. Parameters value : :class:`int`, :class:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. implicitTa...
def subtype(self, value=noValue, implicitTag=None, explicitTag=None, subtypeSpec=None, namedValues=None, binValue=noValue, hexValue=noValue):
isModified = False if (((value is None) or (value is noValue)) and (binValue is noValue) and (hexValue is noValue)): value = self._value else: isModified = True if ((implicitTag is not None) and (implicitTag is not noValue)): tagSet = self._tagSet.tagImplicitly(implicitTag) ...
'Get |ASN.1| value as a sequence of 8-bit integers. If |ASN.1| object length is not a multiple of 8, result will be left-padded with zeros.'
def asNumbers(self):
return tuple(octets.octs2ints(self.asOctets()))
'Get |ASN.1| value as a sequence of octets. If |ASN.1| object length is not a multiple of 8, result will be left-padded with zeros.'
def asOctets(self):
return integer.to_bytes(self._value, length=len(self))
'Get |ASN.1| value as a single integer value.'
def asInteger(self):
return self._value
'Get |ASN.1| value as a text string of bits.'
def asBinary(self):
binString = binary.bin(self._value)[2:] return (('0' * (len(self._value) - len(binString))) + binString)
'Create a copy of a |ASN.1| type or object. Any parameters to the *clone()* method will replace corresponding properties of the |ASN.1| object. Parameters value : :class:`str`, :class:`bytes` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. tagSet: :py:class:...
def clone(self, value=noValue, tagSet=None, subtypeSpec=None, encoding=None, binValue=noValue, hexValue=noValue):
isModified = False if (((value is None) or (value is noValue)) and (binValue is noValue) and (hexValue is noValue)): value = self._value else: isModified = True if ((tagSet is None) or (tagSet is noValue)): tagSet = self._tagSet else: isModified = True if ((subtyp...
'Create a copy of a |ASN.1| type or object. Any parameters to the *subtype()* method will be added to the corresponding properties of the |ASN.1| object. Parameters value : :class:`str`, :class:`bytes` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. implicit...
def subtype(self, value=noValue, implicitTag=None, explicitTag=None, subtypeSpec=None, encoding=None, binValue=noValue, hexValue=noValue):
isModified = False if (((value is None) or (value is noValue)) and (binValue is noValue) and (hexValue is noValue)): value = self._value else: isModified = True if ((implicitTag is not None) and (implicitTag is not noValue)): tagSet = self._tagSet.tagImplicitly(implicitTag) ...
'Create a copy of a |ASN.1| type or object. Any parameters to the *clone()* method will replace corresponding properties of the |ASN.1| object. Parameters value: :class:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. tagSet: :py:class:`~pyasn1.type.tag...
def clone(self, value=noValue, tagSet=None):
return OctetString.clone(self, value, tagSet)
'Create a copy of a |ASN.1| type or object. Any parameters to the *subtype()* method will be added to the corresponding properties of the |ASN.1| object. Parameters value: :class:`int`, :class:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. implicitTag...
def subtype(self, value=noValue, implicitTag=None, explicitTag=None):
return OctetString.subtype(self, value, implicitTag, explicitTag)
'Indicate if this |ASN.1| object is a prefix of other |ASN.1| object. Parameters other: |ASN.1| object |ASN.1| object Returns : :class:`bool` :class:`True` if this |ASN.1| object is a parent (e.g. prefix) of the other |ASN.1| object or :class:`False` otherwise.'
def isPrefixOf(self, other):
l = len(self) if (l <= len(other)): if (self._value[:l] == other[:l]): return True return False
'Create a copy of a |ASN.1| type or object. Any parameters to the *clone()* method will replace corresponding properties of the |ASN.1| object. Parameters value: :class:`tuple`, :class:`float` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. tagSet: :py:class...
def clone(self, value=noValue, tagSet=None, subtypeSpec=None):
return base.AbstractSimpleAsn1Item.clone(self, value, tagSet, subtypeSpec)