_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q16200 | key_diff | train | def key_diff(key_bundle, key_defs):
"""
Creates a difference dictionary with keys that should added and keys that
should be deleted from a Key Bundle to get it updated to a state that
mirrors What is in the key_defs specification.
:param key_bundle: The original KeyBundle
:param key_defs: A set... | python | {
"resource": ""
} |
q16201 | update_key_bundle | train | def update_key_bundle(key_bundle, diff):
"""
Apply a diff specification to a KeyBundle.
The keys that are to be added are added.
The keys that should be deleted are marked as inactive.
:param key_bundle: The original KeyBundle
:param diff: The difference specification
:return: An updated ke... | python | {
"resource": ""
} |
q16202 | key_rollover | train | def key_rollover(kb):
"""
A nifty function that lets you do a key rollover that encompasses creating
a completely new set of keys. One new per every old one. With the same
specifications as the old one.
All the old ones are marked as inactive.
:param kb:
:return:
"""
key_spec = []
... | python | {
"resource": ""
} |
q16203 | KeyBundle.do_keys | train | def do_keys(self, keys):
"""
Go from JWK description to binary keys
:param keys:
:return:
"""
for inst in keys:
typ = inst["kty"]
try:
_usage = harmonize_usage(inst['use'])
except KeyError:
_usage = ['']... | python | {
"resource": ""
} |
q16204 | KeyBundle.do_remote | train | def do_remote(self):
"""
Load a JWKS from a webpage
:return: True or False if load was successful
"""
if self.verify_ssl:
args = {"verify": self.verify_ssl}
else:
args = {}
try:
logging.debug('KeyBundle fetch keys from... | python | {
"resource": ""
} |
q16205 | KeyBundle._parse_remote_response | train | def _parse_remote_response(self, response):
"""
Parse JWKS from the HTTP response.
Should be overriden by subclasses for adding support of e.g. signed
JWKS.
:param response: HTTP response from the 'jwks_uri' endpoint
:return: response parsed as JSON
"""
#... | python | {
"resource": ""
} |
q16206 | KeyBundle.update | train | def update(self):
"""
Reload the keys if necessary
This is a forced update, will happen even if cache time has not elapsed.
Replaced keys will be marked as inactive and not removed.
"""
res = True # An update was successful
if self.source:
_k... | python | {
"resource": ""
} |
q16207 | KeyBundle.remove_outdated | train | def remove_outdated(self, after, when=0):
"""
Remove keys that should not be available any more.
Outdated means that the key was marked as inactive at a time
that was longer ago then what is given in 'after'.
:param after: The length of time the key will remain in the KeyBundle
... | python | {
"resource": ""
} |
q16208 | KeyBundle.copy | train | def copy(self):
"""
Make deep copy of this KeyBundle
:return: The copy
"""
kb = KeyBundle()
kb._keys = self._keys[:]
kb.cache_time = self.cache_time
kb.verify_ssl = self.verify_ssl
if self.source:
kb.source = self.source
k... | python | {
"resource": ""
} |
q16209 | SimpleJWT.unpack | train | def unpack(self, token, **kwargs):
"""
Unpacks a JWT into its parts and base64 decodes the parts
individually
:param token: The JWT
:param kwargs: A possible empty set of claims to verify the header
against.
"""
if isinstance(token, str):
... | python | {
"resource": ""
} |
q16210 | SimpleJWT.pack | train | def pack(self, parts=None, headers=None):
"""
Packs components into a JWT
:param parts: List of parts to pack
:param headers: The JWT headers
:return:
"""
if not headers:
if self.headers:
headers = self.headers
else:
... | python | {
"resource": ""
} |
q16211 | SimpleJWT.verify_header | train | def verify_header(self, key, val):
"""
Check that a particular header claim is present and has a specific value
:param key: The claim
:param val: The value of the claim
:raises: KeyError if the claim is not present in the header
:return: True if the claim exists in the h... | python | {
"resource": ""
} |
q16212 | SimpleJWT.verify_headers | train | def verify_headers(self, check_presence=True, **kwargs):
"""
Check that a set of particular header claim are present and has
specific values
:param kwargs: The claim/value sets as a dictionary
:return: True if the claim that appears in the header has the
prescribed v... | python | {
"resource": ""
} |
q16213 | HMACSigner.sign | train | def sign(self, msg, key):
"""
Create a signature over a message as defined in RFC7515 using a
symmetric key
:param msg: The message
:param key: The key
:return: A signature
"""
h = hmac.HMAC(key, self.algorithm(), default_backend())
h.update(msg)
... | python | {
"resource": ""
} |
q16214 | HMACSigner.verify | train | def verify(self, msg, sig, key):
"""
Verifies whether sig is the correct message authentication code of data.
:param msg: The data
:param sig: The message authentication code to verify against data.
:param key: The key to use
:return: Returns true if the mac was valid ot... | python | {
"resource": ""
} |
q16215 | ensure_ec_params | train | def ensure_ec_params(jwk_dict, private):
"""Ensure all required EC parameters are present in dictionary"""
provided = frozenset(jwk_dict.keys())
if private is not None and private:
required = EC_PUBLIC_REQUIRED | EC_PRIVATE_REQUIRED
else:
required = EC_PUBLIC_REQUIRED
return ensure_p... | python | {
"resource": ""
} |
q16216 | ensure_rsa_params | train | def ensure_rsa_params(jwk_dict, private):
"""Ensure all required RSA parameters are present in dictionary"""
provided = frozenset(jwk_dict.keys())
if private is not None and private:
required = RSA_PUBLIC_REQUIRED | RSA_PRIVATE_REQUIRED
else:
required = RSA_PUBLIC_REQUIRED
return ens... | python | {
"resource": ""
} |
q16217 | ensure_params | train | def ensure_params(kty, provided, required):
"""Ensure all required parameters are present in dictionary"""
if not required <= provided:
missing = required - provided
raise MissingValue('Missing properties for kty={}, {}'.format(kty, str(list(missing)))) | python | {
"resource": ""
} |
q16218 | jwk_wrap | train | def jwk_wrap(key, use="", kid=""):
"""
Instantiate a Key instance with the given key
:param key: The keys to wrap
:param use: What the key are expected to be use for
:param kid: A key id
:return: The Key instance
"""
if isinstance(key, rsa.RSAPublicKey) or isinstance(key, rsa.RSAPrivate... | python | {
"resource": ""
} |
q16219 | update_keyjar | train | def update_keyjar(keyjar):
"""
Go through the whole key jar, key bundle by key bundle and update them one
by one.
:param keyjar: The key jar to update
"""
for iss, kbl in keyjar.items():
for kb in kbl:
kb.update() | python | {
"resource": ""
} |
q16220 | key_summary | train | def key_summary(keyjar, issuer):
"""
Return a text representation of the keyjar.
:param keyjar: A :py:class:`oidcmsg.key_jar.KeyJar` instance
:param issuer: Which key owner that we are looking at
:return: A text representation of the keys
"""
try:
kbl = keyjar[issuer]
except Key... | python | {
"resource": ""
} |
q16221 | KeyJar.get | train | def get(self, key_use, key_type="", owner="", kid=None, **kwargs):
"""
Get all keys that matches a set of search criteria
:param key_use: A key useful for this usage (enc, dec, sig, ver)
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, ... | python | {
"resource": ""
} |
q16222 | KeyJar.get_signing_key | train | def get_signing_key(self, key_type="", owner="", kid=None, **kwargs):
"""
Shortcut to use for signing keys only.
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, "" == me (default)
:param kid: A Key Identifier
:param kwargs: Ext... | python | {
"resource": ""
} |
q16223 | KeyJar.keys_by_alg_and_usage | train | def keys_by_alg_and_usage(self, issuer, alg, usage):
"""
Find all keys that can be used for a specific crypto algorithm and
usage by key owner.
:param issuer: Key owner
:param alg: a crypto algorithm
:param usage: What the key should be used for
:return: A possib... | python | {
"resource": ""
} |
q16224 | KeyJar.get_issuer_keys | train | def get_issuer_keys(self, issuer):
"""
Get all the keys that belong to an entity.
:param issuer: The entity ID
:return: A possibly empty list of keys
"""
res = []
for kbl in self.issuer_keys[issuer]:
res.extend(kbl.keys())
return res | python | {
"resource": ""
} |
q16225 | KeyJar.match_owner | train | def match_owner(self, url):
"""
Finds the first entity, with keys in the key jar, with an
identifier that matches the given URL. The match is a leading
substring match.
:param url: A URL
:return: An issue entity ID that exists in the Key jar
"""
for owner... | python | {
"resource": ""
} |
q16226 | KeyJar.load_keys | train | def load_keys(self, issuer, jwks_uri='', jwks=None, replace=False):
"""
Fetch keys from another server
:param jwks_uri: A URL pointing to a site that will return a JWKS
:param jwks: A dictionary representation of a JWKS
:param issuer: The provider URL
:param replace: If ... | python | {
"resource": ""
} |
q16227 | KeyJar.find | train | def find(self, source, issuer):
"""
Find a key bundle based on the source of the keys
:param source: A source url
:param issuer: The issuer of keys
:return: A :py:class:`oidcmsg.key_bundle.KeyBundle` instance or None
"""
try:
for kb in self.issuer_key... | python | {
"resource": ""
} |
q16228 | KeyJar.export_jwks_as_json | train | def export_jwks_as_json(self, private=False, issuer=""):
"""
Export a JWKS as a JSON document.
:param private: Whether it should be the private keys or the public
:param issuer: The entity ID.
:return: A JSON representation of a JWKS
"""
return json.dumps(self.ex... | python | {
"resource": ""
} |
q16229 | KeyJar.import_jwks | train | def import_jwks(self, jwks, issuer):
"""
Imports all the keys that are represented in a JWKS
:param jwks: Dictionary representation of a JWKS
:param issuer: Who 'owns' the JWKS
"""
try:
_keys = jwks["keys"]
except KeyError:
raise ValueErro... | python | {
"resource": ""
} |
q16230 | KeyJar.import_jwks_as_json | train | def import_jwks_as_json(self, jwks, issuer):
"""
Imports all the keys that are represented in a JWKS expressed as a
JSON object
:param jwks: JSON representation of a JWKS
:param issuer: Who 'owns' the JWKS
"""
return self.import_jwks(json.loads(jwks), issuer) | python | {
"resource": ""
} |
q16231 | KeyJar.get_jwt_decrypt_keys | train | def get_jwt_decrypt_keys(self, jwt, **kwargs):
"""
Get decryption keys from this keyjar based on information carried
in a JWE. These keys should be usable to decrypt an encrypted JWT.
:param jwt: A cryptojwt.jwt.JWT instance
:param kwargs: Other key word arguments
:retur... | python | {
"resource": ""
} |
q16232 | KeyJar.get_jwt_verify_keys | train | def get_jwt_verify_keys(self, jwt, **kwargs):
"""
Get keys from this key jar based on information in a JWS. These keys
should be usable to verify the signed JWT.
:param jwt: A cryptojwt.jwt.JWT instance
:param kwargs: Other key word arguments
:return: list of usable keys... | python | {
"resource": ""
} |
q16233 | KeyJar.copy | train | def copy(self):
"""
Make deep copy of this key jar.
:return: A :py:class:`oidcmsg.key_jar.KeyJar` instance
"""
kj = KeyJar()
for issuer in self.owners():
kj[issuer] = [kb.copy() for kb in self[issuer]]
kj.verify_ssl = self.verify_ssl
return k... | python | {
"resource": ""
} |
q16234 | pick_key | train | def pick_key(keys, use, alg='', key_type='', kid=''):
"""
Based on given criteria pick out the keys that fulfill them from a
given set of keys.
:param keys: List of keys. These are :py:class:`cryptojwt.jwk.JWK`
instances.
:param use: What the key is going to be used for 'sig'/'enc'
:par... | python | {
"resource": ""
} |
q16235 | JWT.pack_init | train | def pack_init(self, recv, aud):
"""
Gather initial information for the payload.
:return: A dictionary with claims and values
"""
argv = {'iss': self.iss, 'iat': utc_time_sans_frac()}
if self.lifetime:
argv['exp'] = argv['iat'] + self.lifetime
_aud = ... | python | {
"resource": ""
} |
q16236 | JWT.pack_key | train | def pack_key(self, owner_id='', kid=''):
"""
Find a key to be used for signing the Json Web Token
:param owner_id: Owner of the keys to chose from
:param kid: Key ID
:return: One key
"""
keys = pick_key(self.my_keys(owner_id, 'sig'), 'sig', alg=self.alg,
... | python | {
"resource": ""
} |
q16237 | JWT._verify | train | def _verify(self, rj, token):
"""
Verify a signed JSON Web Token
:param rj: A :py:class:`cryptojwt.jws.JWS` instance
:param token: The signed JSON Web Token
:return: A verified message
"""
keys = self.key_jar.get_jwt_verify_keys(rj.jwt)
return rj.verify_c... | python | {
"resource": ""
} |
q16238 | JWT._decrypt | train | def _decrypt(self, rj, token):
"""
Decrypt an encrypted JsonWebToken
:param rj: :py:class:`cryptojwt.jwe.JWE` instance
:param token: The encrypted JsonWebToken
:return:
"""
if self.iss:
keys = self.key_jar.get_jwt_decrypt_keys(rj.jwt, aud=self.iss)
... | python | {
"resource": ""
} |
q16239 | JWT.verify_profile | train | def verify_profile(msg_cls, info, **kwargs):
"""
If a message type is known for this JSON document. Verify that the
document complies with the message specifications.
:param msg_cls: The message class. A
:py:class:`oidcmsg.message.Message` instance
:param info: The i... | python | {
"resource": ""
} |
q16240 | JWT.unpack | train | def unpack(self, token):
"""
Unpack a received signed or signed and encrypted Json Web Token
:param token: The Json Web Token
:return: If decryption and signature verification work the payload
will be returned as a Message instance if possible.
"""
if not tok... | python | {
"resource": ""
} |
q16241 | factory | train | def factory(token, alg=''):
"""
Instantiate an JWS instance if the token is a signed JWT.
:param token: The token that might be a signed JWT
:param alg: The expected signature algorithm
:return: A JWS instance if the token was a signed JWT, otherwise None
"""
_jw = JWS(alg=alg)
if _jw.... | python | {
"resource": ""
} |
q16242 | JWS.sign_compact | train | def sign_compact(self, keys=None, protected=None, **kwargs):
"""
Produce a JWS using the JWS Compact Serialization
:param keys: A dictionary of keys
:param protected: The protected headers (a dictionary)
:param kwargs: claims you want to add to the standard headers
:retu... | python | {
"resource": ""
} |
q16243 | JWS.verify_compact | train | def verify_compact(self, jws=None, keys=None, allow_none=False,
sigalg=None):
"""
Verify a JWT signature
:param jws: A signed JSON Web Token
:param keys: A list of keys that can possibly be used to verify the
signature
:param allow_none: If sig... | python | {
"resource": ""
} |
q16244 | JWS.verify_compact_verbose | train | def verify_compact_verbose(self, jws=None, keys=None, allow_none=False,
sigalg=None):
"""
Verify a JWT signature and return dict with validation results
:param jws: A signed JSON Web Token
:param keys: A list of keys that can possibly be used to verify the... | python | {
"resource": ""
} |
q16245 | JWS.sign_json | train | def sign_json(self, keys=None, headers=None, flatten=False):
"""
Produce JWS using the JWS JSON Serialization
:param keys: list of keys to use for signing the JWS
:param headers: list of tuples (protected headers, unprotected
headers) for each signature
:return: A si... | python | {
"resource": ""
} |
q16246 | JWS._is_json_serialized_jws | train | def _is_json_serialized_jws(self, json_jws):
"""
Check if we've got a JSON serialized signed JWT.
:param json_jws: The message
:return: True/False
"""
json_ser_keys = {"payload", "signatures"}
flattened_json_ser_keys = {"payload", "signature"}
if not json... | python | {
"resource": ""
} |
q16247 | JWS._is_compact_jws | train | def _is_compact_jws(self, jws):
"""
Check if we've got a compact signed JWT
:param jws: The message
:return: True/False
"""
try:
jwt = JWSig().unpack(jws)
except Exception as err:
logger.warning('Could not parse JWS: {}'.format(err))
... | python | {
"resource": ""
} |
q16248 | RSASigner.sign | train | def sign(self, msg, key):
"""
Create a signature over a message as defined in RFC7515 using an
RSA key
:param msg: the message.
:type msg: bytes
:returns: bytes, the signature of data.
:rtype: bytes
"""
if not isinstance(key, rsa.RSAPrivateKey):
... | python | {
"resource": ""
} |
q16249 | RSASigner.verify | train | def verify(self, msg, signature, key):
"""
Verifies whether signature is a valid signature for message
:param msg: the message
:type msg: bytes
:param signature: The signature to be verified
:type signature: bytes
:param key: The key
:return: True is the ... | python | {
"resource": ""
} |
q16250 | generate_and_store_rsa_key | train | def generate_and_store_rsa_key(key_size=2048, filename='rsa.key',
passphrase=''):
"""
Generate a private RSA key and store a PEM representation of it in a
file.
:param key_size: The size of the key, default 2048 bytes.
:param filename: The name of the file to which th... | python | {
"resource": ""
} |
q16251 | import_public_rsa_key_from_file | train | def import_public_rsa_key_from_file(filename):
"""
Read a public RSA key from a PEM file.
:param filename: The name of the file
:param passphrase: A pass phrase to use to unpack the PEM file.
:return: A
cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey instance
"""
with ope... | python | {
"resource": ""
} |
q16252 | import_rsa_key | train | def import_rsa_key(pem_data):
"""
Extract an RSA key from a PEM-encoded X.509 certificate
:param pem_data: RSA key encoded in standard form
:return: rsa.RSAPublicKey instance
"""
if not pem_data.startswith(PREFIX):
pem_data = bytes('{}\n{}\n{}'.format(PREFIX, pem_data, POSTFIX),
... | python | {
"resource": ""
} |
q16253 | rsa_eq | train | def rsa_eq(key1, key2):
"""
Only works for RSAPublic Keys
:param key1:
:param key2:
:return:
"""
pn1 = key1.public_numbers()
pn2 = key2.public_numbers()
# Check if two RSA keys are in fact the same
if pn1 == pn2:
return True
else:
return False | python | {
"resource": ""
} |
q16254 | der_cert | train | def der_cert(der_data):
"""
Load a DER encoded certificate
:param der_data: DER-encoded certificate
:return: A cryptography.x509.certificate instance
"""
if isinstance(der_data, str):
der_data = bytes(der_data, 'utf-8')
return x509.load_der_x509_certificate(der_data, default_backend... | python | {
"resource": ""
} |
q16255 | load_x509_cert | train | def load_x509_cert(url, httpc, spec2key, **get_args):
"""
Get and transform a X509 cert into a key.
:param url: Where the X509 cert can be found
:param httpc: HTTP client to use for fetching
:param spec2key: A dictionary over keys already seen
:param get_args: Extra key word arguments to the HT... | python | {
"resource": ""
} |
q16256 | cmp_public_numbers | train | def cmp_public_numbers(pn1, pn2):
"""
Compare 2 sets of public numbers. These is a way to compare
2 public RSA keys. If the sets are the same then the keys are the same.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging to the 2nd key
:return: True i... | python | {
"resource": ""
} |
q16257 | cmp_private_numbers | train | def cmp_private_numbers(pn1, pn2):
"""
Compare 2 sets of private numbers. This is for comparing 2
private RSA keys.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging to the 2nd key
:return: True is the sets are the same otherwise False.
"""
i... | python | {
"resource": ""
} |
q16258 | RSAKey.deserialize | train | def deserialize(self):
"""
Based on a text based representation of an RSA key this method
instantiates a
cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or
RSAPublicKey instance
"""
# first look for the public parts of a RSA key
if self.n and... | python | {
"resource": ""
} |
q16259 | RSAKey.serialize | train | def serialize(self, private=False):
"""
Given a cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or
RSAPublicKey instance construct the JWK representation.
:param private: Should I do the private part or not
:return: A JWK as a dictionary
"""
if not se... | python | {
"resource": ""
} |
q16260 | RSAKey.load_key | train | def load_key(self, key):
"""
Load a RSA key. Try to serialize the key before binding it to this
instance.
:param key: An RSA key instance
"""
self._serialize(key)
if isinstance(key, rsa.RSAPrivateKey):
self.priv_key = key
self.pub_key = k... | python | {
"resource": ""
} |
q16261 | ECDSASigner.sign | train | def sign(self, msg, key):
"""
Create a signature over a message as defined in RFC7515 using an
Elliptic curve key
:param msg: The message
:param key: An ec.EllipticCurvePrivateKey instance
:return:
"""
if not isinstance(key, ec.EllipticCurvePrivateKey):
... | python | {
"resource": ""
} |
q16262 | ECDSASigner._cross_check | train | def _cross_check(self, pub_key):
"""
In Ecdsa, both the key and the algorithm define the curve.
Therefore, we must cross check them to make sure they're the same.
:param key:
:raises: ValueError is the curves are not the same
"""
if self.curve_name != pub_key.cur... | python | {
"resource": ""
} |
q16263 | ECDSASigner._split_raw_signature | train | def _split_raw_signature(sig):
"""
Split raw signature into components
:param sig: The signature
:return: A 2-tuple
"""
c_length = len(sig) // 2
r = int_from_bytes(sig[:c_length], byteorder='big')
s = int_from_bytes(sig[c_length:], byteorder='big')
... | python | {
"resource": ""
} |
q16264 | alg2keytype | train | def alg2keytype(alg):
"""
Go from algorithm name to key type.
:param alg: The algorithm name
:return: The key type
"""
if not alg or alg.lower() == "none":
return "none"
elif alg.startswith("RS") or alg.startswith("PS"):
return "RSA"
elif alg.startswith("HS") or alg.star... | python | {
"resource": ""
} |
q16265 | ecdh_derive_key | train | def ecdh_derive_key(key, epk, apu, apv, alg, dk_len):
"""
ECDH key derivation, as defined by JWA
:param key : Elliptic curve private key
:param epk : Elliptic curve public key
:param apu : PartyUInfo
:param apv : PartyVInfo
:param alg : Algorithm identifier
:param dk_len: Length of... | python | {
"resource": ""
} |
q16266 | JWE_EC.encrypt | train | def encrypt(self, key=None, iv="", cek="", **kwargs):
"""
Produces a JWE as defined in RFC7516 using an Elliptic curve key
:param key: *Not used>, only there to present the same API as
JWE_RSA and JWE_SYM
:param iv: Initialization vector
:param cek: Content master ke... | python | {
"resource": ""
} |
q16267 | JWE_RSA.encrypt | train | def encrypt(self, key, iv="", cek="", **kwargs):
"""
Produces a JWE as defined in RFC7516 using RSA algorithms
:param key: RSA key
:param iv: Initialization vector
:param cek: Content master key
:param kwargs: Extra keyword arguments
:return: A signed payload
... | python | {
"resource": ""
} |
q16268 | JWE_RSA.decrypt | train | def decrypt(self, token, key, cek=None):
""" Decrypts a JWT
:param token: The JWT
:param key: A key to use for decrypting
:param cek: Ephemeral cipher key
:return: The decrypted message
"""
if not isinstance(token, JWEnc):
jwe = JWEnc().unpack(token)
... | python | {
"resource": ""
} |
q16269 | JWE.encrypt | train | def encrypt(self, keys=None, cek="", iv="", **kwargs):
"""
Encrypt a payload
:param keys: A set of possibly usable keys
:param cek: Content master key
:param iv: Initialization vector
:param kwargs: Extra key word arguments
:return: Encrypted message
"""
... | python | {
"resource": ""
} |
q16270 | base64url_to_long | train | def base64url_to_long(data):
"""
Stricter then base64_to_long since it really checks that it's
base64url encoded
:param data: The base64 string
:return:
"""
_data = as_bytes(data)
_d = base64.urlsafe_b64decode(_data + b'==')
# verify that it's base64url encoded and not just base64
... | python | {
"resource": ""
} |
q16271 | b64d | train | def b64d(b):
"""Decode some base64-encoded bytes.
Raises BadSyntax if the string contains invalid characters or padding.
:param b: bytes
"""
cb = b.rstrip(b"=") # shouldn't but there you are
# Python's base64 functions ignore invalid characters, so we need to
# check for them explicitly... | python | {
"resource": ""
} |
q16272 | deser | train | def deser(val):
"""
Deserialize from a string representation of an long integer
to the python representation of a long integer.
:param val: The string representation of the long integer.
:return: The long integer.
"""
if isinstance(val, str):
_val = val.encode("utf-8")
else:
... | python | {
"resource": ""
} |
q16273 | JWK.common | train | def common(self):
"""
Return the set of parameters that are common to all types of keys.
:return: Dictionary
"""
res = {"kty": self.kty}
if self.use:
res["use"] = self.use
if self.kid:
res["kid"] = self.kid
if self.alg:
... | python | {
"resource": ""
} |
q16274 | JWK.verify | train | def verify(self):
"""
Verify that the information gathered from the on-the-wire
representation is of the right type.
This is supposed to be run before the info is deserialized.
:return: True/False
"""
for param in self.longs:
item = getattr(self, para... | python | {
"resource": ""
} |
q16275 | concat_sha256 | train | def concat_sha256(secret, dk_len, other_info):
"""
The Concat KDF, using SHA256 as the hash function.
Note: Does not validate that otherInfo meets the requirements of
SP800-56A.
:param secret: The shared secret value
:param dk_len: Length of key to be derived, in bits
:param other_info: Ot... | python | {
"resource": ""
} |
q16276 | JWx.pick_keys | train | def pick_keys(self, keys, use="", alg=""):
"""
The assumption is that upper layer has made certain you only get
keys you can use.
:param alg: The crypto algorithm
:param use: What the key should be used for
:param keys: A list of JWK instances
:return: A list of ... | python | {
"resource": ""
} |
q16277 | MyServer.setup_sensors | train | def setup_sensors(self):
"""Setup some server sensors."""
self._add_result = Sensor.float("add.result",
"Last ?add result.", "", [-10000, 10000])
self._add_result.set_value(0, Sensor.UNREACHABLE)
self._time_result = Sensor.timestamp("time.result",
"Last ?time res... | python | {
"resource": ""
} |
q16278 | MyServer.request_add | train | def request_add(self, req, x, y):
"""Add two numbers"""
r = x + y
self._add_result.set_value(r)
return ("ok", r) | python | {
"resource": ""
} |
q16279 | MyServer.request_time | train | def request_time(self, req):
"""Return the current time in ms since the Unix Epoch."""
r = time.time()
self._time_result.set_value(r)
return ("ok", r) | python | {
"resource": ""
} |
q16280 | MyServer.request_eval | train | def request_eval(self, req, expression):
"""Evaluate a Python expression."""
r = str(eval(expression))
self._eval_result.set_value(r)
return ("ok", r) | python | {
"resource": ""
} |
q16281 | MyServer.request_set_sensor_inactive | train | def request_set_sensor_inactive(self, req, sensor_name):
"""Set sensor status to inactive"""
sensor = self.get_sensor(sensor_name)
ts, status, value = sensor.read()
sensor.set_value(value, sensor.INACTIVE, ts)
return('ok',) | python | {
"resource": ""
} |
q16282 | MyServer.request_set_sensor_unreachable | train | def request_set_sensor_unreachable(self, req, sensor_name):
"""Set sensor status to unreachable"""
sensor = self.get_sensor(sensor_name)
ts, status, value = sensor.read()
sensor.set_value(value, sensor.UNREACHABLE, ts)
return('ok',) | python | {
"resource": ""
} |
q16283 | MyServer.request_raw_reverse | train | def request_raw_reverse(self, req, msg):
"""
A raw request handler to demonstrate the calling convention if
@request decoraters are not used. Reverses the message arguments.
"""
# msg is a katcp.Message.request object
reversed_args = msg.arguments[::-1]
# req.make... | python | {
"resource": ""
} |
q16284 | transform_future | train | def transform_future(transformation, future):
"""Returns a new future that will resolve with a transformed value
Takes the resolution value of `future` and applies transformation(*future.result())
to it before setting the result of the new future with the transformed value. If
future() resolves with an... | python | {
"resource": ""
} |
q16285 | monitor_resource_sync_state | train | def monitor_resource_sync_state(resource, callback, exit_event=None):
"""Coroutine that monitors a KATCPResource's sync state.
Calls callback(True/False) whenever the resource becomes synced or unsynced. Will
always do an initial callback(False) call. Exits without calling callback() if
exit_event is s... | python | {
"resource": ""
} |
q16286 | KATCPClientResource.until_state | train | def until_state(self, state, timeout=None):
"""Future that resolves when a certain client state is attained
Parameters
----------
state : str
Desired state, one of ("disconnected", "syncing", "synced")
timeout: float
Timeout for operation in seconds.
... | python | {
"resource": ""
} |
q16287 | KATCPClientResource.start | train | def start(self):
"""Start the client and connect"""
# TODO (NM 2015-03-12) Some checking to prevent multiple calls to start()
host, port = self.address
ic = self._inspecting_client = self.inspecting_client_factory(
host, port, self._ioloop_set_to)
self.ioloop = ic.iol... | python | {
"resource": ""
} |
q16288 | KATCPClientResourceSensorsManager._get_strategy_cache_key | train | def _get_strategy_cache_key(self, sensor_name):
"""Lookup sensor name in cache, allowing names in escaped form
The strategy cache uses the normal KATCP sensor names as the keys.
In order to allow access using an escaped sensor name, this method
tries to find the normal form of the name.... | python | {
"resource": ""
} |
q16289 | KATCPClientResourceSensorsManager.get_sampling_strategy | train | def get_sampling_strategy(self, sensor_name):
"""Get the current sampling strategy for the named sensor
Parameters
----------
sensor_name : str
Name of the sensor (normal or escaped form)
Returns
-------
strategy : tuple of str
contains... | python | {
"resource": ""
} |
q16290 | KATCPClientResourceSensorsManager.set_sampling_strategy | train | def set_sampling_strategy(self, sensor_name, strategy_and_params):
"""Set the sampling strategy for the named sensor
Parameters
----------
sensor_name : str
Name of the sensor
strategy_and_params : seq of str or str
As tuple contains (<strat_name>, [<str... | python | {
"resource": ""
} |
q16291 | KATCPClientResourceSensorsManager.reapply_sampling_strategies | train | def reapply_sampling_strategies(self):
"""Reapply all sensor strategies using cached values"""
check_sensor = self._inspecting_client.future_check_sensor
for sensor_name, strategy in list(self._strategy_cache.items()):
try:
sensor_exists = yield check_sensor(sensor_na... | python | {
"resource": ""
} |
q16292 | KATCPClientResourceRequest.issue_request | train | def issue_request(self, *args, **kwargs):
"""Issue the wrapped request to the server.
Parameters
----------
*args : list of objects
Arguments to pass on to the request.
Keyword Arguments
-----------------
timeout : float or None, optional
... | python | {
"resource": ""
} |
q16293 | ClientGroup.wait | train | def wait(self, sensor_name, condition_or_value, timeout=5.0, quorum=None,
max_grace_period=1.0):
"""Wait for sensor present on all group clients to satisfy a condition.
Parameters
----------
sensor_name : string
The name of the sensor to check
condition_... | python | {
"resource": ""
} |
q16294 | KATCPClientResourceContainer.set_ioloop | train | def set_ioloop(self, ioloop=None):
"""Set the tornado ioloop to use
Defaults to tornado.ioloop.IOLoop.current() if set_ioloop() is not called or if
ioloop=None. Must be called before start()
"""
ioloop = ioloop or tornado.ioloop.IOLoop.current()
self.ioloop = ioloop
... | python | {
"resource": ""
} |
q16295 | KATCPClientResourceContainer.is_connected | train | def is_connected(self):
"""Indication of the connection state of all children"""
return all([r.is_connected() for r in dict.values(self.children)]) | python | {
"resource": ""
} |
q16296 | KATCPClientResourceContainer.until_synced | train | def until_synced(self, timeout=None):
"""Return a tornado Future; resolves when all subordinate clients are synced"""
futures = [r.until_synced(timeout) for r in dict.values(self.children)]
yield tornado.gen.multi(futures, quiet_exceptions=tornado.gen.TimeoutError) | python | {
"resource": ""
} |
q16297 | KATCPClientResourceContainer.until_not_synced | train | def until_not_synced(self, timeout=None):
"""Return a tornado Future; resolves when any subordinate client is not synced"""
yield until_any(*[r.until_not_synced() for r in dict.values(self.children)],
timeout=timeout) | python | {
"resource": ""
} |
q16298 | KATCPClientResourceContainer.until_any_child_in_state | train | def until_any_child_in_state(self, state, timeout=None):
"""Return a tornado Future; resolves when any client is in specified state"""
return until_any(*[r.until_state(state) for r in dict.values(self.children)],
timeout=timeout) | python | {
"resource": ""
} |
q16299 | KATCPClientResourceContainer.until_all_children_in_state | train | def until_all_children_in_state(self, state, timeout=None):
"""Return a tornado Future; resolves when all clients are in specified state"""
futures = [r.until_state(state, timeout=timeout)
for r in dict.values(self.children)]
yield tornado.gen.multi(futures, quiet_exceptions=t... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.