text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile_swagger_schema(schema_dir, resource_listing): """Build a SwaggerSchema from various files. :param schema_dir: the directory schema files live inside ...
mapping = build_schema_mapping(schema_dir, resource_listing) resource_validators = ingest_resources(mapping, schema_dir) endpoints = list(build_swagger_12_endpoints(resource_listing, mapping)) return SwaggerSchema(endpoints, resource_validators)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_bravado_core_config(settings): """Create a configuration dict for bravado_core based on pyramid_swagger settings. :param settings: pyramid registry se...
# Map pyramid_swagger config key -> bravado_core config key config_keys = { 'pyramid_swagger.enable_request_validation': 'validate_requests', 'pyramid_swagger.enable_response_validation': 'validate_responses', 'pyramid_swagger.enable_swagger_spec_validation': 'validate_swagger_spec', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ingest_resources(mapping, schema_dir): """Consume the Swagger schemas and produce a queryable datastructure. :param mapping: Map from resource name to filepa...
ingested_resources = [] for name, filepath in iteritems(mapping): try: ingested_resources.append(load_schema(filepath)) # If we have trouble reading any files, raise a more user-friendly # error. except IOError: raise ApiDeclarationNotFoundError( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_array(self, infile, var_name): """Directly return a numpy array for a given variable name"""
file_handle = self.read_cdf(infile) try: # return the data array return file_handle.variables[var_name][:] except KeyError: print("Cannot find variable: {0}".format(var_name)) raise KeyError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_ma_array(self, infile, var_name): """Create a masked array based on cdf's FillValue"""
file_obj = self.read_cdf(infile) # .data is not backwards compatible to old scipy versions, [:] is data = file_obj.variables[var_name][:] # load numpy if available try: import numpy as np except Exception: raise ImportError("numpy is required to...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def digest(self,data=None): """ Method digest is redefined to return keyed MAC value instead of just digest. """
if data is not None: self.update(data) b=create_string_buffer(256) size=c_size_t(256) if libcrypto.EVP_DigestSignFinal(self.ctx,b,pointer(size))<=0: raise DigestError('SignFinal') self.digest_finalized=True return b.raw[:size.value]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bytes(num, check_result=False): """ Returns num bytes of cryptographically strong pseudo-random bytes. If checkc_result is True, raises error if PRNG is not ...
if num <= 0: raise ValueError("'num' should be > 0") buf = create_string_buffer(num) result = libcrypto.RAND_bytes(buf, num) if check_result and result == 0: raise RandError("Random Number Generator not seeded sufficiently") return buf.raw[:num]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(dotted, shortname, longname): """ Creates new OID in the database @param dotted - dotted-decimal representation of new OID @param shortname - short na...
if pyver > 2: dotted = dotted.encode('ascii') shortname = shortname.encode('utf-8') longname = longname.encode('utf-8') nid = libcrypto.OBJ_create(dotted, shortname, longname) if nid == 0: raise LibCryptoError("Problem adding new OID to the database") return Oid(nid)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dotted(self): " Returns dotted-decimal reperesentation " obj = libcrypto.OBJ_nid2obj(self.nid) buf = create_string_buffer(256) libcrypto.OBJ_obj2txt(buf, 256, obj, 1) if pyver == 2: return buf.value else: return buf.value.decode('ascii')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromobj(obj): """ Creates an OID object from the pointer to ASN1_OBJECT c structure. This method intended for internal use for submodules which deal with lib...
nid = libcrypto.OBJ_obj2nid(obj) if nid == 0: buf = create_string_buffer(80) dotted_len = libcrypto.OBJ_obj2txt(buf, 80, obj, 1) dotted = buf[:dotted_len] oid = create(dotted, dotted, dotted) else: oid = Oid(nid) return oid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _password_callback(c): """ Converts given user function or string to C password callback function, passable to openssl. IF function is passed, it would be ca...
if c is None: return PW_CALLBACK_FUNC(0) if callable(c): if pyver ==2 : def __cb(buf, length, rwflag, userdata): pwd = c(rwflag) cnt = min(len(pwd),length) memmove(buf,pwd, cnt) return cnt else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify(self, digest, signature, **kwargs): """ Verifies given signature on given digest Returns True if Ok, False if don't match Keyword arguments allows to ...
ctx = libcrypto.EVP_PKEY_CTX_new(self.key, None) if ctx is None: raise PKeyError("Initailizing verify context") if libcrypto.EVP_PKEY_verify_init(ctx) < 1: raise PKeyError("verify_init") self._configure_context(ctx, kwargs) ret = libcrypto.EVP_PKEY_verify...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exportpub(self, format="PEM"): """ Returns public key as PEM or DER structure. """
bio = Membio() if format == "PEM": retcode = libcrypto.PEM_write_bio_PUBKEY(bio.bio, self.key) else: retcode = libcrypto.i2d_PUBKEY_bio(bio.bio, self.key) if retcode == 0: raise PKeyError("error serializing public key") return str(bio)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exportpriv(self, format="PEM", password=None, cipher=None): """ Returns private key as PEM or DER Structure. If password and cipher are specified, encrypts k...
bio = Membio() if cipher is None: evp_cipher = None else: evp_cipher = cipher.cipher if format == "PEM": ret = libcrypto.PEM_write_bio_PrivateKey(bio.bio, self.key, evp_cipher, None, 0, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _configure_context(ctx, opts, skip=()): """ Configures context of public key operations @param ctx - context to configure @param opts - dictionary of options...
for oper in opts: if oper in skip: continue if isinstance(oper,chartype): op = oper.encode("ascii") else: op = oper if isinstance(opts[oper],chartype): value = opts[oper].encode("ascii") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, length=None): """ Reads data from readble BIO. For test purposes. @param length - if specifed, limits amount of data read. If not BIO is read unti...
if not length is None: if not isinstance(length, inttype) : raise TypeError("length to read should be number") buf = create_string_buffer(length) readbytes = libcrypto.BIO_read(self.bio, buf, length) if readbytes == -2: raise NotIm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, data): """ Writes data to writable bio. For test purposes """
if pyver == 2: if isinstance(data, unicode): data = data.encode("utf-8") else: data = str(data) else: if not isinstance(data, bytes): data=str(data).encode("utf-8") written = libcrypto.BIO_write(self.bio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CMS(data, format="PEM"): """ Factory function to create CMS objects from received messages. Parses CMS data and returns either SignedData or EnvelopedData ob...
bio = Membio(data) if format == "PEM": ptr = libcrypto.PEM_read_bio_CMS(bio.bio, None, None, None) else: ptr = libcrypto.d2i_CMS_bio(bio.bio, None) if ptr is None: raise CMSError("Error parsing CMS data") typeoid = Oid(libcrypto.OBJ_obj2nid(libcrypto.CMS_get0_type(ptr))) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pem(self): """ Serialize in PEM format """
bio = Membio() if not libcrypto.PEM_write_bio_CMS(bio.bio, self.ptr): raise CMSError("writing CMS to PEM") return str(bio)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(data, cert, pkey, flags=Flags.BINARY, certs=None): """ Creates SignedData message by signing data with pkey and certificate. @param data - data to sig...
if not pkey.cansign: raise ValueError("Specified keypair has no private part") if cert.pubkey != pkey: raise ValueError("Certificate doesn't match public key") bio = Membio(data) if certs is not None and len(certs) > 0: certstack_obj = StackOfX509(cer...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sign(self, cert, pkey, digest_type=None, data=None, flags=Flags.BINARY): """ Adds another signer to already signed message @param cert - signer's certificate...
if not pkey.cansign: raise ValueError("Specified keypair has no private part") if cert.pubkey != pkey: raise ValueError("Certificate doesn't match public key") if libcrypto.CMS_add1_signer(self.ptr, cert.cert, pkey.key, digest_ty...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify(self, store, flags, data=None, certs=None): """ Verifies signature under CMS message using trusted cert store @param store - X509Store object with tru...
bio = None if data != None: bio_obj = Membio(data) bio = bio_obj.bio if certs is not None and len(certs) > 0: certstack_obj = StackOfX509(certs) # keep reference to prevent immediate __del__ call certstack = certstack_obj.ptr else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def signers(self): """ Return list of signer's certificates """
signerlist = libcrypto.CMS_get0_signers(self.ptr) if signerlist is None: raise CMSError("Cannot get signers") return StackOfX509(ptr=signerlist, disposable=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data(self): """ Returns signed data if present in the message """
# Check if signatire is detached if self.detached: return None bio = Membio() if not libcrypto.CMS_verify(self.ptr, None, None, None, bio.bio, Flags.NO_VERIFY): raise CMSError("extract data") return str(bio)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def certs(self): """ List of the certificates contained in the structure """
certstack = libcrypto.CMS_get1_certs(self.ptr) if certstack is None: raise CMSError("getting certs") return StackOfX509(ptr=certstack, disposable=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(recipients, data, cipher, flags=0): """ Creates and encrypts message @param recipients - list of X509 objects @param data - contents of the message @p...
recp = StackOfX509(recipients) bio = Membio(data) cms_ptr = libcrypto.CMS_encrypt(recp.ptr, bio.bio, cipher.cipher, flags) if cms_ptr is None: raise CMSError("encrypt EnvelopedData") return EnvelopedData(cms_ptr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(data, cipher, key, flags=0): """ Creates an EncryptedData message. @param data data to encrypt @param cipher cipher.CipherType object represening requ...
bio = Membio(data) ptr = libcrypto.CMS_EncryptedData_encrypt(bio.bio, cipher.cipher, key, len(key), flags) if ptr is None: raise CMSError("encrypt data") return EncryptedData(ptr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decrypt(self, key, flags=0): """ Decrypts encrypted data message @param key - symmetic key to decrypt @param flags - OR-ed combination of Flags constant """
bio = Membio() if libcrypto.CMS_EncryptedData_decrypt(self.ptr, key, len(key), None, bio.bio, flags) <= 0: raise CMSError("decrypt data") return str(bio)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name(self): """ Returns name of the digest """
if not hasattr(self, 'digest_name'): self.digest_name = Oid(libcrypto.EVP_MD_type(self.digest) ).longname() return self.digest_name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, data, length=None): """ Hashes given byte string @param data - string to hash @param length - if not specifed, entire string is hashed, otherwis...
if self.digest_finalized: raise DigestError("No updates allowed") if not isinstance(data, bintype): raise TypeError("A byte string is expected") if length is None: length = len(data) elif length > len(data): raise ValueError("Specified len...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def digest(self, data=None): """ Finalizes digest operation and return digest value Optionally hashes more data before finalizing """
if self.digest_finalized: return self.digest_out.raw[:self.digest_size] if data is not None: self.update(data) self.digest_out = create_string_buffer(256) length = c_long(0) result = libcrypto.EVP_DigestFinal_ex(self.ctx, self.digest_out, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """ Creates copy of the digest CTX to allow to compute digest while being able to hash more data """
new_digest = Digest(self.digest_type) libcrypto.EVP_MD_CTX_copy(new_digest.ctx, self.ctx) return new_digest
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clean_ctx(self): """ Clears and deallocates context """
try: if self.ctx is not None: libcrypto.EVP_MD_CTX_free(self.ctx) del self.ctx except AttributeError: pass self.digest_out = None self.digest_finalized = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hexdigest(self, data=None): """ Returns digest in the hexadecimal form. For compatibility with hashlib """
from base64 import b16encode if pyver == 2: return b16encode(self.digest(data)) else: return b16encode(self.digest(data)).decode('us-ascii')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _X509__asn1date_to_datetime(asn1date): """ Converts openssl ASN1_TIME object to python datetime.datetime """
bio = Membio() libcrypto.ASN1_TIME_print(bio.bio, asn1date) pydate = datetime.strptime(str(bio), "%b %d %H:%M:%S %Y %Z") return pydate.replace(tzinfo=utc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find(self, oid): """ Return list of extensions with given Oid """
if not isinstance(oid, Oid): raise TypeError("Need crytypescrypto.oid.Oid as argument") found = [] index = -1 end = len(self) while True: index = libcrypto.X509_get_ext_by_NID(self.cert.cert, oid.nid, inde...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_critical(self, crit=True): """ Return list of critical extensions (or list of non-cricital, if optional second argument is False """
if crit: flag = 1 else: flag = 0 found = [] end = len(self) index = -1 while True: index = libcrypto.X509_get_ext_by_critical(self.cert.cert, flag, index) if index >= e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pem(self): """ Returns PEM represntation of the certificate """
bio = Membio() if libcrypto.PEM_write_bio_X509(bio.bio, self.cert) == 0: raise X509Error("error serializing certificate") return str(bio)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serial(self): """ Serial number of certificate as integer """
asnint = libcrypto.X509_get_serialNumber(self.cert) bio = Membio() libcrypto.i2a_ASN1_INTEGER(bio.bio, asnint) return int(str(bio), 16)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_cert(self, cert): """ Explicitely adds certificate to set of trusted in the store @param cert - X509 object to add """
if not isinstance(cert, X509): raise TypeError("cert should be X509") libcrypto.X509_STORE_add_cert(self.store, cert.cert)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setpurpose(self, purpose): """ Sets certificate purpose which verified certificate should match @param purpose - number from 1 to 9 or standard strind define...
if isinstance(purpose, str): purp_no = libcrypto.X509_PURPOSE_get_by_sname(purpose) if purp_no <= 0: raise X509Error("Invalid certificate purpose '%s'" % purpose) elif isinstance(purpose, int): purp_no = purpose if libcrypto.X509_STORE_set_pur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def settime(self, time): """ Set point in time used to check validity of certificates for Time can be either python datetime object or number of seconds sinse ep...
if isinstance(time, datetime) or isinstance(time, datetime.date): seconds = int(time.strftime("%s")) elif isinstance(time, int): seconds = time else: raise TypeError("datetime.date, datetime.datetim...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, value): """ Adds certificate to stack """
if not self.need_free: raise ValueError("Stack is read-only") if not isinstance(value, X509): raise TypeError('StackOfX509 can contain only X509 objects') sk_push(self.ptr, libcrypto.X509_dup(value.cert))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(curve, data): """ Creates EC keypair from the just secret key and curve name @param curve - name of elliptic curve @param num - byte array or long num...
ec_key = libcrypto.EC_KEY_new_by_curve_name(curve.nid) if ec_key is None: raise PKeyError("EC_KEY_new_by_curvename") group = libcrypto.EC_KEY_get0_group(ec_key) if group is None: raise PKeyError("EC_KEY_get0_group") libcrypto.EC_GROUP_set_asn1_flag(group, 1) raw_key = libcrypto....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new(algname, key, encrypt=True, iv=None): """ Returns new cipher object ready to encrypt-decrypt data @param algname - string algorithm name like in opemssl ...
ciph_type = CipherType(algname) return Cipher(ciph_type, key, iv, encrypt)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def padding(self, padding=True): """ Sets padding mode of the cipher """
padding_flag = 1 if padding else 0 libcrypto.EVP_CIPHER_CTX_set_padding(self.ctx, padding_flag)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finish(self): """ Finalizes processing. If some data are kept in the internal state, they would be processed and returned. """
if self.cipher_finalized: raise CipherError("Cipher operation is already completed") outbuf = create_string_buffer(self.block_size) self.cipher_finalized = True outlen = c_int(0) result = libcrypto.EVP_CipherFinal_ex(self.ctx, outbuf, byref(outlen)) if result...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clean_ctx(self): """ Cleans up cipher ctx and deallocates it """
try: if self.ctx is not None: self.__ctxcleanup(self.ctx) libcrypto.EVP_CIPHER_CTX_free(self.ctx) del self.ctx except AttributeError: pass self.cipher_finalized = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_default(eng, algorithms=0xFFFF): """ Sets specified engine as default for all algorithms, supported by it For compatibility with 0.2.x if string is passe...
if not isinstance(eng,Engine): eng=Engine(eng) global default libcrypto.ENGINE_set_default(eng.ptr, c_int(algorithms)) default = eng
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_keyed_iterable(iterable, key, filter_func=None): """Construct a dictionary out of an iterable, using an attribute name as the key. Optionally provide a ...
generated = {} for element in iterable: try: k = getattr(element, key) except AttributeError: raise RuntimeError("{} does not have the keyed attribute: {}".format( element, key )) if filter_func is None or filter_func(element): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subtract_by_key(dict_a, dict_b): """given two dicts, a and b, this function returns c = a - b, where a - b is defined as the key difference between a and b. ...
difference_dict = {} for key in dict_a: if key not in dict_b: difference_dict[key] = dict_a[key] return difference_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def winnow_by_keys(dct, keys=None, filter_func=None): """separates a dict into has-keys and not-has-keys pairs, using either a list of keys or a filtering functi...
has = {} has_not = {} for key in dct: key_passes_check = False if keys is not None: key_passes_check = key in keys elif filter_func is not None: key_passes_check = filter_func(key) if key_passes_check: has[key] = dct[key] else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flat_map(iterable, func): """func must take an item and return an interable that contains that item. this is flatmap in the classic mode"""
results = [] for element in iterable: result = func(element) if len(result) > 0: results.extend(result) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def product(sequence, initial=1): """like the built-in sum, but for multiplication."""
if not isinstance(sequence, collections.Iterable): raise TypeError("'{}' object is not iterable".format(type(sequence).__name__)) return reduce(operator.mul, sequence, initial)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def date_from_string(string, format_string=None): """Runs through a few common string formats for datetimes, and attempts to coerce them into a datetime. Alterna...
if isinstance(format_string, str): return datetime.datetime.strptime(string, format_string).date() elif format_string is None: format_string = [ "%Y-%m-%d", "%m-%d-%Y", "%m/%d/%Y", "%d/%m/%Y", ] for format in format_string: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_datetime(plain_date, hours=0, minutes=0, seconds=0, ms=0): """given a datetime.date, gives back a datetime.datetime"""
# don't mess with datetimes if isinstance(plain_date, datetime.datetime): return plain_date return datetime.datetime( plain_date.year, plain_date.month, plain_date.day, hours, minutes, seconds, ms, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_containing_period(cls, *periods): """Given a bunch of TimePeriods, return a TimePeriod that most closely contains them."""
if any(not isinstance(period, TimePeriod) for period in periods): raise TypeError("periods must all be TimePeriods: {}".format(periods)) latest = datetime.datetime.min earliest = datetime.datetime.max for period in periods: # the best we can do to conain None ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user_password(env, param, force=False): """ Allows the user to print the credential for a particular keyring entry to the screen """
username = utils.assemble_username(env, param) if not utils.confirm_credential_display(force): return # Retrieve the credential from the keychain password = password_get(username) if password: return (username, password) else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def password_get(username=None): """ Retrieves a password from the keychain based on the environment and configuration parameter pair. If this fails, None is ret...
password = keyring.get_password('supernova', username) if password is None: split_username = tuple(username.split(':')) msg = ("Couldn't find a credential for {0}:{1}. You need to set one " "with: supernova-keyring -s {0} {1}").format(*split_username) raise LookupError(ms...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_user_password(environment, parameter, password): """ Sets a user's password in the keyring storage """
username = '%s:%s' % (environment, parameter) return password_set(username, password)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def password_set(username=None, password=None): """ Stores a password in a keychain for a particular environment and configuration parameter pair. """
result = keyring.set_password('supernova', username, password) # NOTE: keyring returns None when the storage is successful. That's weird. if result is None: return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prep_shell_environment(nova_env, nova_creds): """ Appends new variables to the current shell environment temporarily. """
new_env = {} for key, value in prep_nova_creds(nova_env, nova_creds): if type(value) == six.binary_type: value = value.decode() new_env[key] = value return new_env
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prep_nova_creds(nova_env, nova_creds): """ Finds relevant config options in the supernova config and cleans them up for novaclient. """
try: raw_creds = dict(nova_creds.get('DEFAULT', {}), **nova_creds[nova_env]) except KeyError: msg = "{0} was not found in your supernova configuration "\ "file".format(nova_env) raise KeyError(msg) proxy_re = re.compile(r"(^http_proxy|^https_proxy)") creds = [] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_config(config_file_override=False): """ Pulls the supernova configuration file and reads it """
supernova_config = get_config_file(config_file_override) supernova_config_dir = get_config_directory(config_file_override) if not supernova_config and not supernova_config_dir: raise Exception("Couldn't find a valid configuration file to parse") nova_creds = ConfigObj() # Can we successf...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config_file(override_files=False): """ Looks for the most specific configuration file available. An override can be provided as a string if needed. """
if override_files: if isinstance(override_files, six.string_types): possible_configs = [override_files] else: raise Exception("Config file override must be a string") else: xdg_config_home = os.environ.get('XDG_CONFIG_HOME') or \ os.path.expanduser('~...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config_directory(override_files=False): """ Looks for the most specific configuration directory possible, in order to load individual configuration files...
if override_files: possible_dirs = [override_files] else: xdg_config_home = os.environ.get('XDG_CONFIG_HOME') or \ os.path.expanduser('~/.config') possible_dirs = [os.path.join(xdg_config_home, "supernova.d/"), os.path.expanduser("~/.supernova.d/"),...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_executable(nova_args, env_vars): """ Executes the executable given by the user. Hey, I know this method has a silly name, but I write the code here a...
process = subprocess.Popen(nova_args, stdout=sys.stdout, stderr=subprocess.PIPE, env=env_vars) process.wait() return process
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_for_debug(supernova_args, nova_args): """ If the user wanted to run the executable with debugging enabled, we need to apply the correct arguments to th...
# Heat requires special handling for debug arguments if supernova_args['debug'] and supernova_args['executable'] == 'heat': nova_args.insert(0, '-d ') elif supernova_args['debug']: nova_args.insert(0, '--debug ') return nova_args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_for_executable(supernova_args, env_vars): """ It's possible that a user might set their custom executable via an environment variable. If we detect one...
exe = supernova_args.get('executable', 'default') if exe != 'default': return supernova_args if 'OS_EXECUTABLE' in env_vars.keys(): supernova_args['executable'] = env_vars['OS_EXECUTABLE'] return supernova_args supernova_args['executable'] = 'nova' return supernova_args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_for_bypass_url(raw_creds, nova_args): """ Return a list of extra args that need to be passed on cmdline to nova. """
if 'BYPASS_URL' in raw_creds.keys(): bypass_args = ['--bypass-url', raw_creds['BYPASS_URL']] nova_args = bypass_args + nova_args return nova_args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_command(nova_creds, nova_args, supernova_args): """ Sets the environment variables for the executable, runs the executable, and handles the output. """
nova_env = supernova_args['nova_env'] # (gtmanfred) make a copy of this object. If we don't copy it, the insert # to 0 happens multiple times because it is the same object in memory. nova_args = copy.copy(nova_args) # Get the environment variables ready env_vars = os.environ.copy() env_va...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_environment_presets(): """ Checks for environment variables that can cause problems with supernova """
presets = [x for x in os.environ.copy().keys() if x.startswith('NOVA_') or x.startswith('OS_')] if len(presets) < 1: return True else: click.echo("_" * 80) click.echo("*WARNING* Found existing environment variables that may " "cause conflicts:") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_envs_in_group(group_name, nova_creds): """ Takes a group_name and finds any environments that have a SUPERNOVA_GROUP configuration line that matches the ...
envs = [] for key, value in nova_creds.items(): supernova_groups = value.get('SUPERNOVA_GROUP', []) if hasattr(supernova_groups, 'startswith'): supernova_groups = [supernova_groups] if group_name in supernova_groups: envs.append(key) elif group_name == 'a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid_group(group_name, nova_creds): """ Checks to see if the configuration file contains a SUPERNOVA_GROUP configuration option. """
valid_groups = [] for key, value in nova_creds.items(): supernova_groups = value.get('SUPERNOVA_GROUP', []) if hasattr(supernova_groups, 'startswith'): supernova_groups = [supernova_groups] valid_groups.extend(supernova_groups) valid_groups.append('all') if group_nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rm_prefix(name): """ Removes nova_ os_ novaclient_ prefix from string. """
if name.startswith('nova_'): return name[5:] elif name.startswith('novaclient_'): return name[11:] elif name.startswith('os_'): return name[3:] else: return name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __pad(strdata): """ Pads `strdata` with a Request's callback argument, if specified, or does nothing. """
if request.args.get('callback'): return "%s(%s);" % (request.args.get('callback'), strdata) else: return strdata
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __dumps(*args, **kwargs): """ Serializes `args` and `kwargs` as JSON. Supports serializing an array as the top-level object, if it is the only argument. "...
indent = None if (current_app.config.get('JSONIFY_PRETTYPRINT_REGULAR', False) and not request.is_xhr): indent = 2 return json.dumps(args[0] if len(args) is 1 else dict(*args, **kwargs), indent=indent)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_type_lookups(self): """ Update type and typestring lookup dicts. Must be called once the ``types`` and ``python_type_strings`` attributes are set so t...
self.type_to_typestring = dict(zip(self.types, self.python_type_strings)) self.typestring_to_type = dict(zip(self.python_type_strings, self.types))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_type_string(self, data, type_string): """ Gets type string. Finds the type string for 'data' contained in ``python_type_strings`` using its ``type``. Non...
if type_string is not None: return type_string else: tp = type(data) try: return self.type_to_typestring[tp] except KeyError: return self.type_to_typestring[tp.__module__ + '.' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, f, grp, name, data, type_string, options): """ Writes an object's metadata to file. Writes the Python object 'data' to 'name' in h5py.Group 'grp'...
raise NotImplementedError('Can''t write data type: ' + str(type(data)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_metadata(self, f, dsetgrp, data, type_string, options, attributes=None): """ Writes an object to file. Writes the metadata for a Python object `data` t...
if attributes is None: attributes = dict() # Make sure we have a complete type_string. if options.store_python_metadata \ and 'Python.Type' not in attributes: attributes['Python.Type'] = \ ('string', self.get_type_string(data, type_string)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_path(pth): """ Processes paths. Processes the provided path and breaks it into it Group part (`groupname`) and target part (`targetname`). ``bytes`` ...
# Do conversions and possibly escapes. if isinstance(pth, bytes): p = pth.decode('utf-8') elif (sys.hexversion >= 0x03000000 and isinstance(pth, str)) \ or (sys.hexversion < 0x03000000 \ and isinstance(pth, unicode)): p = pth elif not isinstance(pth, collections....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_object_array(f, data, options): """ Writes an array of objects recursively. Writes the elements of the given object array recursively in the HDF5 Group...
# We need to grab the special reference dtype and make an empty # array to store all the references in. ref_dtype = h5py.special_dtype(ref=h5py.Reference) data_refs = np.zeros(shape=data.shape, dtype='object') # We need to make sure that the group to hold references is present, # and create it...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_object_array(f, data, options): """ Reads an array of objects recursively. Read the elements of the given HDF5 Reference array recursively in the and co...
# Go through all the elements of data and read them using their # references, and the putting the output in new object array. data_derefed = np.zeros(shape=data.shape, dtype='object') for index, x in np.ndenumerate(data): data_derefed[index] = read_data(f, None, None, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_unused_name_in_group(grp, length): """ Gives a name that isn't used in a Group. Generates a name of the desired length that is not a Dataset or Group in...
# While # # ltrs = string.ascii_letters + string.digits # name = ''.join([random.choice(ltrs) for i in range(length)]) # # seems intuitive, its performance is abysmal compared to # # '%0{0}x'.format(length) % random.getrandbits(length * 4) # # The difference is a factor of 20. I...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_numpy_str_to_uint16(data): """ Converts a numpy.unicode\_ to UTF-16 in numpy.uint16 form. Convert a ``numpy.unicode_`` or an array of them (they are ...
# An empty string should be an empty uint16 if data.nbytes == 0: return np.uint16([]) # We need to use the UTF-16 codec for our endianness. Using the # right one means we don't have to worry about removing the BOM. if sys.byteorder == 'little': codec = 'UTF-16LE' else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_numpy_str_to_uint32(data): """ Converts a numpy.unicode\_ to its numpy.uint32 representation. Convert a ``numpy.unicode_`` or an array of them (they ...
if data.nbytes == 0: # An empty string should be an empty uint32. return np.uint32([]) else: # We need to calculate the new shape from the current shape, # which will have to be expanded along the rows to fit all the # characters (the dtype.itemsize gets the number of by...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_complex(data, complex_names=(None, None)): """ Decodes possibly complex data read from an HDF5 file. Decodes possibly complex datasets read from an HD...
# Now, complex types are stored in HDF5 files as an H5T_COMPOUND type # with fields along the lines of ('r', 're', 'real') and ('i', 'im', # 'imag', 'imaginary') for the real and imaginary parts, which most # likely won't be properly extracted back into making a Python # complex type unless the pro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_complex(data, complex_names): """ Encodes complex data to having arbitrary complex field names. Encodes complex `data` to have the real and imaginary ...
# Grab the dtype name, and convert it to the right non-complex type # if it isn't already one. dtype_name = data.dtype.name if dtype_name[0:7] == 'complex': dtype_name = 'float' + str(int(float(dtype_name[7:])/2)) # Create the new version of the data with the right field names for # th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_attribute_to_string(value): """ Convert an attribute value to a string. Converts the attribute value to a string if possible (get ``None`` if isn't a...
if value is None: return value elif (sys.hexversion >= 0x03000000 and isinstance(value, str)) \ or (sys.hexversion < 0x03000000 \ and isinstance(value, unicode)): return value elif isinstance(value, bytes): return value.decode() elif isinstance(value, np....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_attribute(target, name, value): """ Sets an attribute on a Dataset or Group. If the attribute `name` doesn't exist yet, it is created. If it already exis...
try: target.attrs.modify(name, value) except: target.attrs.create(name, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_attribute_string(target, name, value): """ Sets an attribute to a string on a Dataset or Group. If the attribute `name` doesn't exist yet, it is created....
set_attribute(target, name, np.bytes_(value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_attribute_string_array(target, name, string_list): """ Sets an attribute to an array of string on a Dataset or Group. If the attribute `name` doesn't exi...
s_list = [convert_to_str(s) for s in string_list] if sys.hexversion >= 0x03000000: target.attrs.create(name, s_list, dtype=h5py.special_dtype(vlen=str)) else: target.attrs.create(name, s_list, dtype=h5py.special_dtype(vlen=unicode))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_attributes_all(target, attributes, discard_others=True): """ Set Attributes in bulk and optionally discard others. Sets each Attribute in turn (modifying...
attrs = target.attrs existing = dict(attrs.items()) # Generate special dtype for string arrays. if sys.hexversion >= 0x03000000: str_arr_dtype = h5py.special_dtype(vlen=str) else: str_arr_dtype = dtype=h5py.special_dtype(vlen=unicode) # Go through each attribute. If it is alread...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_thirdparty_marshaller_plugins(): """ Find, but don't load, all third party marshaller plugins. Third party marshaller plugins declare the entry point ``...
all_plugins = tuple(pkg_resources.iter_entry_points( 'hdf5storage.marshallers.plugins')) return {ver: {p.module_name: p for p in all_plugins if p.name == ver} for ver in supported_marshaller_api_versions()}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def savemat(file_name, mdict, appendmat=True, format='7.3', oned_as='row', store_python_metadata=True, action_for_matlab_incompatible='error', marshaller_collecti...
# If format is a number less than 7.3, the call needs to be # dispatched to the scipy version, if it is available, with all the # relevant and extra keywords options provided. if float(format) < 7.3: import scipy.io scipy.io.savemat(file_name, mdict, appendmat=appendmat, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadmat(file_name, mdict=None, appendmat=True, variable_names=None, marshaller_collection=None, **keywords): """ Loads data to a MATLAB MAT file. Reads data ...
# Will first assume that it is the HDF5 based 7.3 format. If an # OSError occurs, then it wasn't an HDF5 file and the scipy function # can be tried instead. try: # Make the options with the given marshallers. options = Options(marshaller_collection=marshaller_collection) # Appe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_marshallers(self): """ Update the full marshaller list and other data structures. Makes a full list of both builtin and user marshallers and rebuilds...
# Combine all sets of marshallers. self._marshallers = [] for v in self._priority: if v == 'builtin': self._marshallers.extend(self._builtin_marshallers) elif v == 'plugin': self._marshallers.extend(self._plugin_marshallers) el...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _import_marshaller_modules(self, m): """ Imports the modules required by the marshaller. Parameters m : marshaller The marshaller to load the modules for. Re...
try: for name in m.required_modules: if name not in sys.modules: if _has_importlib: importlib.import_module(name) else: __import__(name) except ImportError: return False ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_marshaller_for_type(self, tp): """ Gets the appropriate marshaller for a type. Retrieves the marshaller, if any, that can be used to read/write a Python ...
if not isinstance(tp, str): tp = tp.__module__ + '.' + tp.__name__ if tp in self._types: index = self._types[tp] else: return None, False m = self._marshallers[index] if self._imported_required_modules[index]: return m, True ...