code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if not isinstance(cert, X509):
raise TypeError("cert should be X509")
libcrypto.X509_STORE_add_cert(self.store, cert.cert) | def add_cert(self, cert) | Explicitely adds certificate to set of trusted in the store
@param cert - X509 object to add | 3.362373 | 3.814103 | 0.881563 |
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... | def setpurpose(self, purpose) | Sets certificate purpose which verified certificate should match
@param purpose - number from 1 to 9 or standard strind defined
in Openssl
possible strings - sslcient,sslserver, nssslserver, smimesign,i
smimeencrypt, crlsign, any, ocsphelper | 3.261693 | 3.322538 | 0.981687 |
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... | 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 epoch | 4.237123 | 4.468537 | 0.948213 |
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)) | def append(self, value) | Adds certificate to stack | 8.214558 | 6.900182 | 1.190484 |
dgst = DigestType(digesttype)
out = create_string_buffer(outlen)
if isinstance(password,chartype):
pwd = password.encode("utf-8")
else:
pwd = password
res = libcrypto.PKCS5_PBKDF2_HMAC(pwd, len(pwd), salt, len(salt),
iterations, dgst.digest,... | def pbkdf2(password, salt, outlen, digesttype="sha1", iterations=2000) | Interface to PKCS5_PBKDF2_HMAC function
Parameters:
@param password - password to derive key from
@param salt - random salt to use for key derivation
@param outlen - number of bytes to derive
@param digesttype - name of digest to use to use (default sha1)
@param iterations - number of iteration... | 4.003461 | 4.363694 | 0.917448 |
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 = libcry... | 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 number representing key | 1.71507 | 1.747933 | 0.981199 |
ciph_type = CipherType(algname)
return Cipher(ciph_type, key, iv, encrypt) | 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 command
line
@param key - binary string representing ciher key
@param encrypt - if True (default) cipher would be initialized
for encryption, otherwise - f... | 5.811393 | 9.55482 | 0.608216 |
padding_flag = 1 if padding else 0
libcrypto.EVP_CIPHER_CTX_set_padding(self.ctx, padding_flag) | def padding(self, padding=True) | Sets padding mode of the cipher | 4.26226 | 3.45976 | 1.231952 |
if self.cipher_finalized:
raise CipherError("No updates allowed")
if not isinstance(data, bintype):
raise TypeError("A byte string is expected")
if len(data) == 0:
return ""
outbuf = create_string_buffer(self.block_size+len(data))
outl... | def update(self, data) | Performs actual encrypton/decrypion
@param data - part of the plain text/ciphertext to process
@returns - part of ciphercext/plain text
Passed chunk of text doesn't need to contain full ciher
blocks. If neccessery, part of passed data would be kept
internally until next data wo... | 3.620926 | 3.729984 | 0.970762 |
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))
i... | def finish(self) | Finalizes processing. If some data are kept in the internal
state, they would be processed and returned. | 3.221288 | 3.155627 | 1.020808 |
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 | def _clean_ctx(self) | Cleans up cipher ctx and deallocates it | 5.857131 | 4.266749 | 1.372738 |
if not isinstance(eng,Engine):
eng=Engine(eng)
global default
libcrypto.ENGINE_set_default(eng.ptr, c_int(algorithms))
default = eng | 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 passed instead
of engine, attempts to load engine with this id | 6.628972 | 8.11414 | 0.816965 |
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):
... | 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 filter function, to determine what should be
kept in the dictionary. | 3.0337 | 2.943435 | 1.030666 |
difference_dict = {}
for key in dict_a:
if key not in dict_b:
difference_dict[key] = dict_a[key]
return difference_dict | 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.
e.g.,
{1:None, 2:3, 3:"yellow", 4:True} - {2:4, 1:"green"} =
{3:"yellow", 4:True} | 2.089067 | 2.572167 | 0.812181 |
if not strict:
return subtract_by_key(dict_a, dict_b)
difference_dict = {}
for key in dict_a:
if key not in dict_b or dict_b[key] != dict_a[key]:
difference_dict[key] = dict_a[key]
return difference_dict | def subtract(dict_a, dict_b, strict=False) | a stricter form of subtract_by_key(), this version will only remove an
entry from dict_a if the key is in dict_b *and* the value at that key
matches | 2.034892 | 1.997489 | 1.018725 |
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]
els... | 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 function. | 2.210003 | 2.07557 | 1.06477 |
for key in defaults:
dct.setdefault(key, defaults[key])
return dct | def setdefaults(dct, defaults) | Given a target dct and a dict of {key:default value} pairs,
calls setdefault for all of those pairs. | 2.879627 | 4.036347 | 0.713424 |
if complain and len(list_thing) > 1:
raise ValueError("More than one element in {}".format(list_thing))
elif len(list_thing) == 1:
return list_thing[0]
if complain:
raise ValueError("Nothing in {}".format(list_thing))
return None | def unlist(list_thing, complain=True) | transforms [Something] -> Something. By default, raises a ValueError for
any other list values. | 2.244348 | 2.286753 | 0.981456 |
container = iterable.__class__
placeholder = []
for item in iterable:
try:
placeholder.extend(flatten(item))
except TypeError:
placeholder.append(item)
return container(placeholder) | def flatten(iterable) | Fully flattens an iterable:
In: flatten([1,2,3,4,[5,6,[7,8]]])
Out: [1,2,3,4,5,6,7,8] | 3.83221 | 3.508166 | 1.092369 |
results = []
for element in iterable:
result = func(element)
if len(result) > 0:
results.extend(result)
return results | 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 | 2.56226 | 2.650743 | 0.96662 |
if not isinstance(sequence, collections.Iterable):
raise TypeError("'{}' object is not iterable".format(type(sequence).__name__))
return reduce(operator.mul, sequence, initial) | def product(sequence, initial=1) | like the built-in sum, but for multiplication. | 2.333497 | 2.188095 | 1.066452 |
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:
... | 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. Alternatively,
format_string can provide either a single string to attempt
or an iterable of strings to attempt. | 2.110889 | 1.981941 | 1.065061 |
# 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,
) | def to_datetime(plain_date, hours=0, minutes=0, seconds=0, ms=0) | given a datetime.date, gives back a datetime.datetime | 2.363684 | 2.162264 | 1.093152 |
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 cona... | def get_containing_period(cls, *periods) | Given a bunch of TimePeriods, return a TimePeriod that most closely
contains them. | 2.910596 | 2.75315 | 1.057188 |
attribute_chain = string_rep.split(separator)
current_obj = obj
for attr in attribute_chain:
try:
current_obj = getattr(current_obj, attr)
except AttributeError:
if default is _get_attr_raise_on_attribute_error:
raise AttributeError(
... | def get_attr(obj, string_rep, default=_get_attr_raise_on_attribute_error, separator=".") | getattr via a chain of attributes like so:
>>> import datetime
>>> some_date = datetime.date.today()
>>> get_attr(some_date, "month.numerator.__doc__")
'int(x[, base]) -> integer\n\nConvert a string or number to an integer, ... | 2.329412 | 2.880298 | 0.80874 |
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 | def get_user_password(env, param, force=False) | Allows the user to print the credential for a particular keyring entry
to the screen | 7.208792 | 7.298 | 0.987776 |
rex = "USE_KEYRING\[([\x27\x22])(.*)\\1\]"
# This is the old-style, per-environment keyring credential
if value == "USE_KEYRING":
username = utils.assemble_username(env, param)
# This is the new-style, global keyring credential that can be applied
# to multiple environments
else:
... | def pull_env_credential(env, param, value) | Dissects a keyring credential lookup string from the supernova config file
and returns the username/password combo | 7.192295 | 6.941039 | 1.036199 |
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 LookupErro... | def password_get(username=None) | Retrieves a password from the keychain based on the environment and
configuration parameter pair.
If this fails, None is returned. | 4.937716 | 5.349411 | 0.923039 |
username = '%s:%s' % (environment, parameter)
return password_set(username, password) | def set_user_password(environment, parameter, password) | Sets a user's password in the keyring storage | 5.812863 | 6.340844 | 0.916733 |
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 | def password_set(username=None, password=None) | Stores a password in a keychain for a particular environment and
configuration parameter pair. | 8.140917 | 10.347978 | 0.786716 |
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 | def prep_shell_environment(nova_env, nova_creds) | Appends new variables to the current shell environment temporarily. | 2.904132 | 2.969956 | 0.977837 |
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 = ... | def prep_nova_creds(nova_env, nova_creds) | Finds relevant config options in the supernova config and cleans them
up for novaclient. | 4.980996 | 4.773038 | 1.043569 |
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 succ... | def load_config(config_file_override=False) | Pulls the supernova configuration file and reads it | 3.286234 | 3.120461 | 1.053125 |
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.expanduse... | 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. | 2.307144 | 2.198788 | 1.04928 |
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... | def get_config_directory(override_files=False) | Looks for the most specific configuration directory possible, in order to
load individual configuration files. | 2.544322 | 2.444173 | 1.040975 |
process = subprocess.Popen(nova_args,
stdout=sys.stdout,
stderr=subprocess.PIPE,
env=env_vars)
process.wait()
return process | 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 and
I'm silly. | 2.527237 | 3.091911 | 0.817371 |
# 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 | 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 the executable.
Heat is a corner case since it uses -d instead of --debug. | 4.010566 | 3.309984 | 1.211657 |
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 | 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, we should add it to supernova's
arguments ONLY IF an executable wasn't set on the command line. The
command line executable must take priority. | 2.63702 | 2.581111 | 1.021661 |
if 'BYPASS_URL' in raw_creds.keys():
bypass_args = ['--bypass-url', raw_creds['BYPASS_URL']]
nova_args = bypass_args + nova_args
return nova_args | def check_for_bypass_url(raw_creds, nova_args) | Return a list of extra args that need to be passed on cmdline to nova. | 2.508058 | 2.276079 | 1.10192 |
stderr_output = stderr_pipe.read()
if len(stderr_output) > 0:
click.secho("\n__ Error Output {0}".format('_'*62), fg='white',
bold=True)
click.echo(stderr_output)
return True | def handle_stderr(stderr_pipe) | Takes stderr from the command's output and displays it AFTER the stdout
is printed by run_command(). | 5.920511 | 6.075637 | 0.974467 |
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()
en... | def run_command(nova_creds, nova_args, supernova_args) | Sets the environment variables for the executable, runs the executable,
and handles the output. | 5.669845 | 5.688751 | 0.996676 |
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:")... | def check_environment_presets() | Checks for environment variables that can cause problems with supernova | 3.730822 | 3.669166 | 1.016804 |
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 =... | 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 group_name. | 2.571848 | 2.08553 | 1.233187 |
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... | def is_valid_group(group_name, nova_creds) | Checks to see if the configuration file contains a SUPERNOVA_GROUP
configuration option. | 2.614611 | 2.201645 | 1.187571 |
if name.startswith('nova_'):
return name[5:]
elif name.startswith('novaclient_'):
return name[11:]
elif name.startswith('os_'):
return name[3:]
else:
return name | def rm_prefix(name) | Removes nova_ os_ novaclient_ prefix from string. | 2.611928 | 1.768013 | 1.477323 |
if action == 'get_credential':
result = credentials.get_user_password(env=environment,
param=parameter)
if not result:
click.echo("\nUnable to find a credential matching the data "
"provided.")
ctx.exi... | def run_supernova_keyring(ctx, action, environment, parameter) | Sets or retrieves credentials stored in your system's keyring using the
python-keyring module.
Global credentials can be shared between multiple configuration sections:
\b
[prod]
OS_PASSWORD=USE_KEYRING['sso_password']
...
\b
[staging]
OS_PASSWORD=USE_KEYRING['... | 3.064379 | 3.33765 | 0.918125 |
def __pad(strdata):
if request.args.get('callback'):
return "%s(%s);" % (request.args.get('callback'), strdata)
else:
return strdata | Pads `strdata` with a Request's callback argument, if specified, or does
nothing. | null | null | null | |
def __dumps(*args, **kwargs):
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) | Serializes `args` and `kwargs` as JSON. Supports serializing an array
as the top-level object, if it is the only argument. | null | null | null | |
def jsonpify(*args, **kwargs):
return current_app.response_class(__pad(__dumps(*args, **kwargs)),
mimetype=__mimetype()) | Creates a :class:`~flask.Response` with the JSON or JSON-P
representation of the given arguments with an `application/json`
or `application/javascript` mimetype, respectively. The arguments
to this function are the same as to the :class:`dict` constructor,
but also accept an array. If a `callback` ... | null | null | null | |
self.type_to_typestring = dict(zip(self.types,
self.python_type_strings))
self.typestring_to_type = dict(zip(self.python_type_strings,
self.types)) | 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 that ``type_to_typestring`` and
``typestring_to_type`` are constructed.
.. versionadded:: 0.2
Notes
-----
Subclasses need to call this f... | 3.500997 | 2.055007 | 1.703642 |
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__ + '.'
... | 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-``None``
'type_string` overrides whatever type string is looked up.
The override makes it easier for subclasses to convert something
that the parent marshaller can wri... | 2.950911 | 2.900522 | 1.017372 |
raise NotImplementedError('Can''t write data type: '
+ str(type(data))) | 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'.
.. versionchanged:: 0.2
Arguements changed.
Parameters
----------
f : h5py.File
The HDF5 file handle that is open.
grp : h5py.Group or h5py.File
... | 13.250325 | 22.183733 | 0.597299 |
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... | 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` to file at `name`
in h5py.Group `grp`. Metadata is written to HDF5
Attributes. Existing Attributes that are not being used are
deleted.
.. versionchanged:: 0.2
Arguements changed.
Param... | 5.719319 | 4.534396 | 1.261319 |
slsh = b'\\'.decode('ascii')
s = m.group(0)
count = s.count(slsh)
if count % 2 == 0:
return s
else:
if sys.hexversion >= 0x03000000:
c = chr(int(s[(count + 1):], base=16))
else:
c = unichr(int(s[(count + 1):], base=16))
return slsh * (coun... | def _replace_fun_unescape(m) | Decode single hex/unicode escapes found in regex matches.
Supports single hex/unicode escapes of the form ``'\\xYY'``,
``'\\uYYYY'``, and ``'\\UYYYYYYYY'`` where Y is a hex digit. Only
decodes if there is an odd number of backslashes.
.. versionadded:: 0.2
Parameters
----------
m : regex ... | 2.77864 | 3.087385 | 0.899998 |
if isinstance(pth, bytes):
pth = pth.decode('utf-8')
if sys.hexversion >= 0x03000000:
if not isinstance(pth, str):
raise TypeError('pth must be str or bytes.')
match = _find_dots_re.match(pth)
if match is None:
prefix = ''
s = pth
... | def escape_path(pth) | Hex/unicode escapes a path.
Escapes a path so that it can be represented faithfully in an HDF5
file without changing directories. This means that leading ``'.'``
must be escaped. ``'/'`` and null must be escaped to. Backslashes
are escaped as double backslashes. Other escaped characters are
replace... | 2.538772 | 2.725031 | 0.931649 |
if isinstance(pth, bytes):
pth = pth.decode('utf-8')
if sys.hexversion >= 0x03000000:
if not isinstance(pth, str):
raise TypeError('pth must be str or bytes.')
else:
if not isinstance(pth, unicode):
raise TypeError('pth must be unicode or str.')
# Loo... | def unescape_path(pth) | Hex/unicode unescapes a path.
Unescapes a path. Valid escapeds are ``'\\xYY'``, ``'\\uYYYY', or
``'\\UYYYYYYYY'`` where Y are hex digits giving the character's
unicode numerical value and double backslashes which are the escape
for single backslashes.
.. versionadded:: 0.2
Parameters
----... | 3.063611 | 3.040965 | 1.007447 |
# 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, collecti... | def process_path(pth) | Processes paths.
Processes the provided path and breaks it into it Group part
(`groupname`) and target part (`targetname`). ``bytes`` paths are
converted to ``str``. Separated paths are given as an iterable of
``str`` and ``bytes``. Each part of a separated path is escaped
using ``escape_path``. Ot... | 3.571372 | 3.409343 | 1.047525 |
components = [dt]
while 0 != len(components):
c = components.pop()
if 0 in c.shape:
return True
if c.names is not None:
components.extend([v[0] for v in c.fields.values()])
if c.base != c:
components.append(c.base)
return False | def does_dtype_have_a_zero_shape(dt) | Determine whether a dtype (or its fields) have zero shape.
Determines whether the given ``numpy.dtype`` has a shape with a zero
element or if one of its fields does, or if one of its fields'
fields does, and so on recursively. The following dtypes do not have
zero shape.
* ``'uint8'``
* ``[('a... | 3.471962 | 4.546684 | 0.763625 |
# Get the marshaller for type(data). The required modules should be
# here and imported.
tp = type(data)
m, has_modules = \
options.marshaller_collection.get_marshaller_for_type(tp)
# If a marshaller was found and we have the required modules, use it
# to write the data. Otherwise,... | def write_data(f, grp, name, data, type_string, options) | Writes a piece of data into an open HDF5 file.
Low level function to store a Python type (`data`) into the
specified Group.
Parameters
----------
f : h5py.File
The open HDF5 file.
grp : h5py.Group or h5py.File
The Group to place the data in.
name : str
The name to w... | 7.455455 | 7.731319 | 0.964319 |
if dsetgrp is None:
# If name isn't found, return error.
try:
dsetgrp = grp[name]
except:
raise hdf5storage.exceptions.CantReadError( \
'Could not find ' + posixpath.join(grp.name, name))
# Get all attributes with values.
if sys.hexversio... | def read_data(f, grp, name, options, dsetgrp=None) | Writes a piece of data into an open HDF5 file.
Low level function to read a Python type of the specified name from
specified Group.
.. versionchanged:: 0.2
Added argument `dsetgrp`.
Parameters
----------
f : h5py.File
The open HDF5 file.
grp : h5py.Group or h5py.File
... | 3.979939 | 3.91238 | 1.017268 |
# 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,
... | 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 constructs a ``numpy.object_`` array from its elements,
which is returned.
Parameters
----------
f : h5py.File
The HDF5 file handle that is open.
data : numpy.ndarray o... | 7.70968 | 8.485264 | 0.908596 |
# 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 2... | 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 the given group. Note, if length is not large enough and
`grp` is full enough, there may be no available names meaning that
this function will hang.
Parameters
----------
grp :... | 3.936429 | 3.648683 | 1.078863 |
# 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:
... | 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 UTF-32
strings) to UTF-16 in the equivalent array of ``numpy.uint16``. The
conversion will throw an exception if any characters cannot be
converted to UTF-16. Strings are expanded along... | 5.567937 | 5.539862 | 1.005068 |
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 o... | 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 are UTF-32
strings) into the equivalent array of ``numpy.uint32`` that is byte
for byte identical. Strings are expanded along rows (across columns)
so a 2x3x4 array of 10 element string... | 6.477703 | 6.481222 | 0.999457 |
# How the conversion is done depends on the exact underlying
# type. Numpy types are handled separately. For uint types, it is
# assumed to be stored as UTF-8, UTF-16, or UTF-32 depending on the
# size when converting to an str. numpy.string_ is just like
# converting a bytes. numpy.unicode ha... | def convert_to_str(data) | Decodes data to the Python 3.x str (Python 2.x unicode) type.
Decodes `data` to a Python 3.x ``str`` (Python 2.x ``unicode``). If
it can't be decoded, it is returned as is. Unsigned integers, Python
``bytes``, and Numpy strings (``numpy.unicode_`` and
``numpy.bytes_``). Python 3.x ``bytes``, Python 2.x... | 3.507315 | 3.352952 | 1.046038 |
# 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... | def decode_complex(data, complex_names=(None, None)) | Decodes possibly complex data read from an HDF5 file.
Decodes possibly complex datasets read from an HDF5 file. HDF5
doesn't have a native complex type, so they are stored as
H5T_COMPOUND types with fields such as 'r' and 'i' for the real and
imaginary parts. As there is no standardization for field na... | 5.038564 | 4.571844 | 1.102086 |
# 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
... | def encode_complex(data, complex_names) | Encodes complex data to having arbitrary complex field names.
Encodes complex `data` to have the real and imaginary field names
given in `complex_numbers`. This is needed because the field names
have to be set so that it can be written to an HDF5 file with the
right field names (HDF5 doesn't have a nat... | 5.125597 | 5.398938 | 0.949371 |
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,... | 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 string type).
.. versionadded:: 0.2
Parameters
----------
value :
The Attribute value.
Returns
-------
s : str or None
The ``str`` value of the at... | 2.088954 | 2.098056 | 0.995662 |
try:
target.attrs.modify(name, value)
except:
target.attrs.create(name, value) | 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 exists, it is overwritten if it differs from `value`.
Notes
-----
``set_attributes_all`` is the fastest way to set and delete
Attributes in bulk.
Parameters
----------
... | 3.643636 | 5.643181 | 0.645671 |
set_attribute(target, name, np.bytes_(value)) | 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. If it
already exists, it is overwritten if it differs from `value`.
Notes
-----
``set_attributes_all`` is the fastest way to set and delete
Attributes in bulk.
Parameters
---... | 8.629098 | 7.751517 | 1.113214 |
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)... | 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 exist yet, it is created. If it
already exists, it is overwritten with the list of string
`string_list` (they will be vlen strings).
Notes
-----
``set_attributes_all`` is the fastest way to set and d... | 2.212355 | 2.689033 | 0.822732 |
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 al... | def set_attributes_all(target, attributes, discard_others=True) | Set Attributes in bulk and optionally discard others.
Sets each Attribute in turn (modifying it in place if possible if it
is already present) and optionally discarding all other Attributes
not explicitly set. This function yields much greater performance
than the required individual calls to ``set_att... | 3.225991 | 3.183859 | 1.013233 |
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()} | def find_thirdparty_marshaller_plugins() | Find, but don't load, all third party marshaller plugins.
Third party marshaller plugins declare the entry point
``'hdf5storage.marshallers.plugins'`` with the name being the
Marshaller API version and the target being a function that returns
a ``tuple`` or ``list`` of all the marshallers provided by t... | 5.694917 | 4.195344 | 1.357437 |
# Pack the different options into an Options class if an Options was
# not given. By default, the matlab_compatible option is set to
# False. So, if it wasn't passed in the keywords, this needs to be
# added to override the default value (True) for a new Options.
if not isinstance(options, Opti... | def reads(paths, filename='data.h5', options=None, **keywords) | Reads data from an HDF5 file (high level).
High level function to read one or more pieces of data from an HDF5
file located at the paths specified in `paths` into Python
types. Each path is specified as a POSIX style path where the data
to read is located.
There are various options that can be use... | 4.756352 | 4.415195 | 1.077269 |
# 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)
... | 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 internal data structures used for looking up which
marshaller to use for reading/writing Python objects to/from
file.
Also checks for whether the requi... | 3.16751 | 2.996428 | 1.057096 |
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 Fal... | def _import_marshaller_modules(self, m) | Imports the modules required by the marshaller.
Parameters
----------
m : marshaller
The marshaller to load the modules for.
Returns
-------
success : bool
Whether the modules `m` requires could be imported
successfully or not. | 3.314095 | 3.139621 | 1.055572 |
if not isinstance(marshallers, collections.Iterable):
marshallers = [marshallers]
for m in marshallers:
if not isinstance(m, Marshallers.TypeMarshaller):
raise TypeError('Each marshaller must inherit from '
'hdf5storage.Mar... | def add_marshaller(self, marshallers) | Add a marshaller/s to the user provided list.
Adds a marshaller or a list of them to the user provided set of
marshallers.
Note that the builtin marshallers take priority when choosing
the right marshaller.
.. versionchanged:: 0.2
All marshallers must now inherit fr... | 3.377645 | 2.563815 | 1.317429 |
if not isinstance(marshallers, collections.Iterable):
marshallers = [marshallers]
for m in marshallers:
if m in self._user_marshallers:
self._user_marshallers.remove(m)
self._update_marshallers() | def remove_marshaller(self, marshallers) | Removes a marshaller/s from the user provided list.
Removes a marshaller or a list of them from the user provided set
of marshallers.
Parameters
----------
marshallers : marshaller or list of marshallers
The user marshaller/s to from the user provided collection. | 2.455407 | 2.606702 | 0.941959 |
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, Tru... | 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 object with type 'tp'. The modules it requires, if
available, will be loaded.
Parameters
----------
tp : type or str
Python object ``type`` ... | 2.943592 | 2.658717 | 1.107148 |
if type_string in self._type_strings:
index = self._type_strings[type_string]
m = self._marshallers[index]
if self._imported_required_modules[index]:
return m, True
if not self._has_required_modules[index]:
return m, False
... | def get_marshaller_for_type_string(self, type_string) | Gets the appropriate marshaller for a type string.
Retrieves the marshaller, if any, that can be used to read/write
a Python object with the given type string. The modules it
requires, if available, will be loaded.
Parameters
----------
type_string : str
Typ... | 2.980656 | 2.851547 | 1.045277 |
if matlab_class in self._matlab_classes:
index = self._matlab_classes[matlab_class]
m = self._marshallers[index]
if self._imported_required_modules[index]:
return m, True
if not self._has_required_modules[index]:
return m, ... | def get_marshaller_for_matlab_class(self, matlab_class) | Gets the appropriate marshaller for a MATLAB class string.
Retrieves the marshaller, if any, that can be used to read/write
a Python object associated with the given MATLAB class
string. The modules it requires, if available, will be loaded.
Parameters
----------
matlab... | 2.97765 | 2.991549 | 0.995354 |
graph = UndirectedGraph()
if num_nodes > 0:
first_node = graph.new_node()
if num_nodes > 1:
previous_node = first_node
for _ in range(num_nodes - 1):
new_node = graph.new_node()
graph.new_edge(previous_node, new_node)
... | def build_cycle_graph(num_nodes) | Builds a cycle graph with the specified number of nodes.
Ref: http://mathworld.wolfram.com/CycleGraph.html | 2.024071 | 1.995401 | 1.014368 |
# The easiest way to build a wheel graph is to build
# C_n-1 and then add a hub node and spoke edges
graph = build_cycle_graph(num_nodes - 1)
cycle_graph_vertices = graph.get_all_node_ids()
node_id = graph.new_node()
for cycle_node in cycle_graph_vertices:
graph.new_edge(node_id, ... | def build_wheel_graph(num_nodes) | Builds a wheel graph with the specified number of nodes.
Ref: http://mathworld.wolfram.com/WheelGraph.html | 5.615488 | 5.421929 | 1.035699 |
graph = UndirectedGraph()
# K5 has 5 nodes
for _ in range(5):
graph.new_node()
# K5 has 10 edges
# --Edge: a
graph.new_edge(1, 2)
# --Edge: b
graph.new_edge(2, 3)
# --Edge: c
graph.new_edge(3, 4)
# --Edge: d
graph.new_edge(4, 5)
# --Edge: e
graph.ne... | def build_k5_graph() | Makes a new K5 graph.
Ref: http://mathworld.wolfram.com/Pentatope.html | 1.719848 | 1.691095 | 1.017003 |
graph = UndirectedGraph()
# K3,3 has 6 nodes
for _ in range(1, 7):
graph.new_node()
# K3,3 has 9 edges
# --Edge: a
graph.new_edge(1, 4)
# --Edge: b
graph.new_edge(1, 5)
# --Edge: c
graph.new_edge(1, 6)
# --Edge: d
graph.new_edge(2, 4)
# --Edge: e
gr... | def build_k33_graph() | Makes a new K3,3 graph.
Ref: http://mathworld.wolfram.com/UtilityGraph.html | 1.871554 | 1.732863 | 1.080036 |
# Because the graph is so complicated, we want to
# build it via adjacency matrix specification
# -- Initialize the matrix to all zeros
adj = [[0 for _ in range(11)] for _ in range(11)]
# -- Add individual edge connections
row_connections = []
row_connections.append( (1,2,7,10) )... | def build_groetzch_graph() | Makes a new Groetzsch graph.
Ref: http://mathworld.wolfram.com/GroetzschGraph.html | 2.800783 | 2.826092 | 0.991045 |
# The easiest way to build the Franklin graph is to start
# with C12 and add the additional 6 edges
graph = build_cycle_graph(12)
edge_tpls = [
(1,8),
(2,7),
(3,10),
(4,9),
(5,12),
(6,11)
]
for i, j in edge_tpls:
graph.new_edge(i, j)... | def build_franklin_graph() | Makes a new Franklin graph.
Ref: http://mathworld.wolfram.com/FranklinGraph.html | 4.734118 | 4.493789 | 1.05348 |
# The easiest way to build the Chvatal graph is to start
# with C12 and add the additional 12 edges
graph = build_cycle_graph(12)
edge_tpls = [
(1,7), (1,9), (2,5), (2,11),
(3,7), (3,9), (4,10), (4,12),
(5,8), (6,10), (6,12), (8,11),
]
for i, j in edge_tpls:
... | def build_chvatal_graph() | Makes a new Chvatal graph.
Ref: http://mathworld.wolfram.com/ChvatalGraph.html | 3.725828 | 3.699168 | 1.007207 |
node_id = self.generate_node_id()
node = {'id': node_id,
'edges': [],
'data': {}
}
self.nodes[node_id] = node
self._num_nodes += 1
return node_id | def new_node(self) | Adds a new, blank node to the graph.
Returns the node id of the new node. | 3.366063 | 3.004119 | 1.120483 |
# Verify that both nodes exist in the graph
try:
self.nodes[node_a]
except KeyError:
raise NonexistentNodeError(node_a)
try:
self.nodes[node_b]
except KeyError:
raise NonexistentNodeError(node_b)
# Create the new ... | def new_edge(self, node_a, node_b, cost=1) | Adds a new edge from node_a to node_b that has a cost.
Returns the edge id of the new edge. | 2.231394 | 2.303071 | 0.968878 |
node = self.get_node(node_id)
return [self.get_edge(edge_id)['vertices'][1] for edge_id in node['edges']] | def neighbors(self, node_id) | Find all the nodes where there is an edge from the specified node to that node.
Returns a list of node ids. | 3.652335 | 3.588412 | 1.017814 |
neighbors = self.neighbors(node_a)
return node_b in neighbors | def adjacent(self, node_a, node_b) | Determines whether there is an edge from node_a to node_b.
Returns True if such an edge exists, otherwise returns False. | 4.92791 | 3.926188 | 1.255139 |
cost = float('inf')
node_object_a = self.get_node(node_a)
for edge_id in node_object_a['edges']:
edge = self.get_edge(edge_id)
tpl = (node_a, node_b)
if edge['vertices'] == tpl:
cost = edge['cost']
break
return ... | def edge_cost(self, node_a, node_b) | Returns the cost of moving between the edge that connects node_a to node_b.
Returns +inf if no such edge exists. | 3.072988 | 2.90914 | 1.056322 |
try:
node_object = self.nodes[node_id]
except KeyError:
raise NonexistentNodeError(node_id)
return node_object | def get_node(self, node_id) | Returns the node object identified by "node_id". | 3.21481 | 2.78943 | 1.152497 |
try:
edge_object = self.edges[edge_id]
except KeyError:
raise NonexistentEdgeError(edge_id)
return edge_object | def get_edge(self, edge_id) | Returns the edge object identified by "edge_id". | 3.365302 | 2.902513 | 1.159444 |
node = self.get_node(node_a)
# Determine the edge ids
edge_ids = []
for e_id in node['edges']:
edge = self.get_edge(e_id)
if edge['vertices'][1] == node_b:
edge_ids.append(e_id)
# Delete the edges
for e in edge_ids:
... | def delete_edge_by_nodes(self, node_a, node_b) | Removes all the edges from node_a to node_b from the graph. | 2.53378 | 2.507993 | 1.010282 |
node = self.get_node(node_id)
# Remove all edges from the node
for e in node['edges']:
self.delete_edge_by_id(e)
# Remove all edges to the node
edges = [edge_id for edge_id, edge in list(self.edges.items()) if edge['vertices'][1] == node_id]
for e i... | def delete_node(self, node_id) | Removes the node identified by node_id from the graph. | 2.438471 | 2.326715 | 1.048031 |
# Grab the edge
edge = self.get_edge(edge_id)
# Alter the vertices
edge['vertices'] = (node_b, edge['vertices'][1])
# Remove the edge from node_a
node = self.get_node(node_a)
node['edges'].remove(edge_id)
# Add the edge to node_b
node =... | def move_edge_source(self, edge_id, node_a, node_b) | Moves an edge originating from node_a so that it originates from node_b. | 2.371934 | 2.273772 | 1.043171 |
# Grab the edge
edge = self.get_edge(edge_id)
# Alter the vertices
edge['vertices'] = (edge['vertices'][0], node_a) | def move_edge_target(self, edge_id, node_a) | Moves an edge so that it targets node_a. | 5.135687 | 4.794542 | 1.071153 |
# Check if the nodes are adjacent
if not self.adjacent(node_a, node_b):
return []
# They're adjacent, so pull the list of edges from node_a and determine which ones point to node_b
node = self.get_node(node_a)
return [edge_id for edge_id in node['edges'] if ... | def get_edge_ids_by_node_ids(self, node_a, node_b) | Returns a list of edge ids connecting node_a to node_b. | 3.755493 | 3.611158 | 1.039969 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.