code
stringlengths
1
18.2k
the user). http://en.wikipedia.org/wiki/Advanced_Encryption_Standard http://en.wikipedia.org/wiki/CTR_mode#Counter_.28CTR.29 https://en.wikipedia.org/wiki/PBKDF2 >>> ed25519_key = generate_ed25519_key() >>> password = 'secret' >>> encrypted_key = encrypt_key(ed25519_key, password) >>> decrypted_key = decrypt_key(encryp...
with encrypt_key(). password: The password, or passphrase, to decrypt 'encrypted_key'. 'password' is not used directly as the encryption key, a stronger encryption key is derived from it. The supported general-purpose module takes care of re-deriving the encryption key. <Exceptions> securesystemslib.exceptions.FormatEr...
RSAKEY_SCHEMA, ED25519KEY_SCHEMA). """ # Does 'encrypted_key' have the correct format? # This check ensures 'encrypted_key' has the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats....
that the original key object is restored. # encrypt_key() generates an encrypted string of the key object using # AES-256-CTR-Mode, where 'password' is strengthened with PBKDF2-HMAC-SHA256. key_object = \ securesystemslib.pyca_crypto_keys.decrypt_key(encrypted_key, passphrase) # The corresponding encrypt_key() encrypts...
def create_rsa_encrypted_pem(private_key, passphrase): """ <Purpose> Return a string in PEM format (TraditionalOpenSSL), where the private part of the RSA key is encrypted using the best available encryption for a given key's backend. This is a curated (by cryptography.io) encryption choice and the algorithm may change...
= create_rsa_encrypted_pem(private, passphrase) >>> securesystemslib.formats.PEMRSA_SCHEMA.matches(encrypted_pem) True <Arguments> private_key: The private key string in PEM format. passphrase: The passphrase, or password, to encrypt the private part of the RSA key. 'passphrase' is not used directly as the encryption k...
be created. TypeError, 'private_key' is unset. <Side Effects> None. <Returns> A string in PEM format, where the private RSA key is encrypted. Conforms to 'securesystemslib.formats.PEMRSA_SCHEMA'. """ # Does 'private_key' have the correct format? # This check will ensure 'private_key' has the appropriate number # of obj...
securesystemslib.formats.PEMRSA_SCHEMA.check_match(private_key) # Does 'passphrase' have the correct format? securesystemslib.formats.PASSWORD_SCHEMA.check_match(passphrase) encrypted_pem = None # Generate the public and private RSA keys. A 2048-bit minimum is enforced by # create_rsa_encrypted_pem() via a # securesyst...
def is_pem_public(pem): """ <Purpose> Checks if a passed PEM formatted string is a PUBLIC key, by looking for the following pattern: '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----' >>> rsa_key = generate_rsa_key() >>> public = rsa_key['keyval']['public'] >>> private = rsa_key['keyval']['private'] >>> is_pem_p...
True if 'pem' is public and false otherwise. """ # Do the arguments have the correct format? # This check will ensure arguments have the appropriate number # of objects and object types, and that all dict keys are properly named. # Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.for...
header_start + len(pem_header)) except ValueError: return False return True
def is_pem_private(pem, keytype='rsa'): """ <Purpose> Checks if a passed PEM formatted string is a PRIVATE key, by looking for the following patterns: '-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----' '-----BEGIN EC PRIVATE KEY----- ... -----END EC PRIVATE KEY-----' >>> rsa_key = generate_rsa_key() >>...
format. <Exceptions> securesystemslib.exceptions.FormatError, if any of the arguments are improperly formatted. <Side Effects> None <Returns> True if 'pem' is private and false otherwise. """ # Do the arguments have the correct format? # This check will ensure arguments have the appropriate number # of objects and obje...
securesystemslib.formats.NAME_SCHEMA.check_match(keytype) if keytype == 'rsa': pem_header = '-----BEGIN RSA PRIVATE KEY-----' pem_footer = '-----END RSA PRIVATE KEY-----' elif keytype == 'ec': pem_header = '-----BEGIN EC PRIVATE KEY-----' pem_footer = '-----END EC PRIVATE KEY-----' else: raise securesystemslib.exceptio...
def import_ecdsakey_from_private_pem(pem, scheme='ecdsa-sha2-nistp256', password=None): """ <Purpose> Import the private ECDSA key stored in 'pem', and generate its public key (which will also be included in the returned ECDSA key object). In addition, a keyid identifier for the ECDSA key is generated. The object retur...
PRIVATE KEY----- ... -----END EC PRIVATE KEY-----'}} The private key is a string in PEM format. >>> ecdsa_key = generate_ecdsa_key() >>> private_pem = ecdsa_key['keyval']['private'] >>> ecdsa_key = import_ecdsakey_from_private_pem(private_pem) >>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key) True <Argume...
to decrypt the private part of the ECDSA key if it is encrypted. 'password' is not used directly as the encryption key, a stronger encryption key is derived from it. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.UnsupportedAlgorithmError, if...
# Does 'pem' have the correct format? # This check will ensure 'pem' conforms to # 'securesystemslib.formats.ECDSARSA_SCHEMA'. securesystemslib.formats.PEMECDSA_SCHEMA.check_match(pem) # Is 'scheme' properly formatted? securesystemslib.formats.ECDSA_SCHEME_SCHEMA.check_match(scheme) if password is not None: securesyste...
= \ securesystemslib.ecdsa_keys.create_ecdsa_public_and_private_from_pem(pem, password) # Generate the keyid of the ECDSA key. 'key_value' corresponds to the # 'keyval' entry of the 'ECDSAKEY_SCHEMA' dictionary. The private key # information is not included in the generation of the 'keyid' identifier. # Convert any '\r...
= _get_keyid(keytype, scheme, key_value) # Build the 'ecdsakey_dict' dictionary. Update 'key_value' with the ECDSA # private key prior to adding 'key_value' to 'ecdsakey_dict'. key_value['private'] = private ecdsakey_dict['keytype'] = keytype ecdsakey_dict['scheme'] = scheme ecdsakey_dict['keyid'] = keyid ecdsakey_dict...
def import_ecdsakey_from_public_pem(pem, scheme='ecdsa-sha2-nistp256'): """ <Purpose> Generate an ECDSA key object from 'pem'. In addition, a keyid identifier for the ECDSA key is generated. The object returned conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA' and has the form: {'keytype': 'ecdsa-sha2-nistp256', '...
>>> public = ecdsa_key['keyval']['public'] >>> ecdsa_key['keyval']['private'] = '' >>> scheme = ecdsa_key['scheme'] >>> ecdsa_key2 = import_ecdsakey_from_public_pem(public, scheme) >>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key) True >>> securesystemslib.formats.ECDSAKEY_SCHEMA.matches(ecdsa_key2) True ...
Leading or trailing whitespace is not included in the PEM string stored in the rsakey object returned. <Returns> A dictionary containing the ECDSA keys and other identifying information. Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'. """ # Does 'pem' have the correct format? # This check will ensure arguments ...
Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.PEMECDSA_SCHEMA.check_match(pem) # Is 'scheme' properly formatted? securesystemslib.formats.ECDSA_SCHEME_SCHEMA.check_match(scheme) # Ensure the PEM string has a public header and footer. Although a simple # validation of 'pem'...
public_pem = extract_pem(pem, private_pem=False) else: raise securesystemslib.exceptions.FormatError('Invalid public' ' pem: ' + repr(pem)) # Begin building the ECDSA key dictionary. ecdsakey_dict = {} keytype = 'ecdsa-sha2-nistp256' # Generate the keyid of the ECDSA key. 'key_value' corresponds to the # 'keyval' entry...
(e.g., Windows) newline characters to '\n' so that a # consistent keyid is generated. key_value = {'public': public_pem.replace('\r\n', '\n'), 'private': ''} keyid = _get_keyid(keytype, scheme, key_value) ecdsakey_dict['keytype'] = keytype ecdsakey_dict['scheme'] = scheme ecdsakey_dict['keyid'] = keyid ecdsakey_dict['k...
def import_ecdsakey_from_pem(pem, scheme='ecdsa-sha2-nistp256'): """ <Purpose> Import either a public or private ECDSA PEM. In contrast to the other explicit import functions (import_ecdsakey_from_public_pem and import_ecdsakey_from_private_pem), this function is useful for when it is not known whether 'pem' is private...
Effects> None. <Returns> A dictionary containing the ECDSA keys and other identifying information. Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'. """ # Does 'pem' have the correct format? # This check will ensure arguments has the appropriate number # of objects and object types, and that all dict keys are pro...
'' private_pem = '' # Ensure the PEM string has a public or private header and footer. Although # a simple validation of 'pem' is performed here, a fully valid PEM string is # needed later to successfully verify signatures. Performing stricter # validation of PEMs are left to the external libraries that use 'pem'. if i...
# Return an ecdsakey object (ECDSAKEY_SCHEMA) with the private key included. return import_ecdsakey_from_private_pem(pem, password=None) else: raise securesystemslib.exceptions.FormatError('PEM contains neither a public' ' nor private key: ' + repr(pem)) # Begin building the ECDSA key dictionary. ecdsakey_dict = {} key...
information is not included in the generation of the 'keyid' identifier. # If a PEM is found to contain a private key, the generated rsakey object # should be returned above. The following key object is for the case of a # PEM with only a public key. Convert any '\r\n' (e.g., Windows) newline # characters to '\n' so th...
generated. key_value = {'public': public_pem.replace('\r\n', '\n'), 'private': ''} keyid = _get_keyid(keytype, scheme, key_value) ecdsakey_dict['keytype'] = keytype ecdsakey_dict['scheme'] = scheme ecdsakey_dict['keyid'] = keyid ecdsakey_dict['keyval'] = key_value return ecdsakey_dict
def parse_func_body(self): """If success, return a tuple (args, body)""" self.save() self._expected = [] if self.next_is_rc(Tokens.OPAR, False): # do not render right hidden self.handle_hidden_right() # render hidden after new level args = self.parse_param_list() if args is not None: # may be an empty table if self.nex...
self._expected = [] token = self.next_is_rc(Tokens.END, False) if token: body.stop_char = token.stop self.success() return args, body else: self.abort() else: self.abort() return self.failure()
def get_concrete_class(cls, class_name): """This method provides easier access to all writers inheriting Writer class :param class_name: name of the parser (name of the parser class which should be used) :type class_name: str :return: Writer subclass specified by parser_name :rtype: Writer subclass :raise ValueError: "...
r is not None: return r return None cls = recurrent_class_lookup(cls) if cls: return cls else: raise ValueError("'class_name '%s' is invalid" % class_name)
def GetPupil(self): """Retrieve pupil data """ pupil_data = _co.namedtuple('pupil_data', ['ZemaxApertureType', 'ApertureValue', 'entrancePupilDiameter', 'entrancePupilPosition', 'exitPupilDiameter', 'exitPupilPosition', 'ApodizationType', 'ApodizationFactor']) data = self._ilensdataeditor.GetPupil() return pupil_data(*...
def ping(self, targets=list(), filename=str(), status=str()): """ Attempt to ping a list of hosts or networks (can be a single host) :param targets: List - Name(s) or IP(s) of the host(s). :param filename: String - name of the file containing hosts to ping :param status: String - if one of ['alive', 'dead', 'noip'] the...
specified, then all results will be returned. :return: Type and results depends on whether status is specified: if status == '': return dict: {targets: results} if status != '': return list: targets if targets == status """ if targets and filename: raise SyntaxError("You must specify only one of either targets=[] " "or...
a list of targets or " "filename='', but not both.") elif filename: targets = self.read_file(filename) my_targets = {'hosts': [], 'nets': []} addresses = [] # Check for valid networks and add hosts and nets to my_targets for target in targets: # Targets may include networks in the format "network mask", or, # a file co...
if len(target.split()) > 1: target_items = target.split() for item in target_items: try: ip = IPAddress(item) # If it is an IPv4 address or mask put in in addresses if ip.version == 4: addresses.append(str(ip)) except AddrFormatError: # IP Address not detected, so assume it's a host name my_targets['hosts'].append(item...
acceptable to fping if net.ip.is_unicast() and net.version == 4 and \ net.netmask.netmask_bits() in range(8, 31): my_targets['nets'].append(target_items[0]) else: msg = str(str(net) + ':Only IPv4 unicast addresses' ' with bit masks\n ' ' from 8 to 30 are supported.') raise AttributeError(msg) # Iterate over the IP stri...
unicast, and mask is an actual mask if ip.is_unicast() and mask.is_netmask(): net = IPNetwork(str(ip) + '/' + str( mask.netmask_bits())) # Convert ip and mask to CIDR and remove from addresses my_targets['nets'].append(str(net.cidr)) addresses.pop(0) addresses.pop(0) elif ip.is_unicast() and not ip.is_netmask(): # mask...
it if addresses: ip = IPAddress(addresses[0]) if ip.is_unicast() and not ip.is_netmask(): my_targets['hosts'].append(addresses[0]) addresses.pop() # target has only one item, so check it else: try: ip = IPAddress(target) if ip.version == 4 and ip.is_unicast() and \ not ip.is_netmask(): my_targets['hosts'].append(target...
name my_targets['hosts'].append(target) except ValueError: # CIDR network detected net = IPNetwork(target) if net.ip.is_unicast() and net.version == 4 and \ net.netmask.netmask_bits() in range(8, 31): my_targets['nets'].append(target) else: msg = str(str(net) + ':Only IPv4 unicast addresses' ' with bit masks\n ' ' from...
target in range(len(my_targets['hosts'])): commands.append([self.fping, '-nV', my_targets['hosts'][ target]]) if len(my_targets['nets']) != 0: for target in range(len(my_targets['nets'])): commands.append([self.fping, '-ngV', my_targets['nets'][ target]]) """ Start pinging each item in my_targets and return the request...
elif status == 'dead': return self.dead elif status == 'noip': return self.noip else: raise SyntaxError("Valid status options are 'alive', 'dead' or " "'noip'")
def get_results(cmd): """ def get_results(cmd: list) -> str: return lines Get the ping results using fping. :param cmd: List - the fping command and its options :return: String - raw string output containing csv fping results including the newline characters """ try: return subprocess.check_output(cmd) except subproces...
def read_file(filename): """ Reads the lines of a file into a list, and returns the list :param filename: String - path and name of the file :return: List - lines within the file """ lines = [] with open(filename) as f: for line in f: if len(line.strip()) != 0: lines.append(line.strip()) return lines
def _prepare_outputs(self, data_out, outputs): """ Open a ROOT file with option 'RECREATE' to create a new file (the file will be overwritten if it already exists), and using the ZLIB compression algorithm (with compression level 1) for better compatibility with older ROOT versions (see https://root.cern.ch/doc/v614/re...
'RECREATE', '', compress)) # multiple tables - require directory elif isinstance(data_out, ROOTModule.TFile): outputs.append(data_out) else: # assume it's a file like object self.file_emulation = True filename = os.path.join(tempfile.mkdtemp(),'tmp.root') outputs.append(ROOTModule.TFile.Open(filename, 'RECREATE', '', c...
def write(self, data_in, data_out, *args, **kwargs): """ :param data_in: :type data_in: hepconverter.parsers.ParsedData :param data_out: filelike object :type data_out: file :param args: :param kwargs: """ self._get_tables(data_in) self.file_emulation = False outputs = [] self._prepare_outputs(data_out, outputs) output...
self.file_emulation: filename = output.GetName() output.Close()
def _pairwise(iterable): """ itertools recipe "s -> (s0,s1), (s1,s2), (s2, s3), ... """ a, b = itertools.tee(iterable) next(b, None) return zip(a, b)
def _groups_of(length, total_length): """ Return an iterator of tuples for slicing, in 'length' chunks. Parameters ---------- length : int Length of each chunk. total_length : int Length of the object we are slicing Returns ------- iterable of tuples Values defining a slice range resulting in length 'length'. """ indic...
def save(sources, targets, masked=False): """ Save the numeric results of each source into its corresponding target. Parameters ---------- sources: list The list of source arrays for saving from; limited to length 1. targets: list The list of target arrays for saving to; limited to length 1. masked: boolean Uses a mask...
1 and len(targets) == 1 array = sources[0] target = targets[0] # Request bitesize pieces of the source and assign them to the # target. # NB. This algorithm does not use the minimal number of chunks. # e.g. If the second dimension could be sliced as 0:99, 99:100 # then clearly the first dimension would have to be singl...
0:99 case, but could be bigger slices for the # 99:100 case. # It's not yet clear if this really matters. all_slices = _all_slices(array) for index in np.ndindex(*[len(slices) for slices in all_slices]): keys = tuple(slices[i] for slices, i in zip(all_slices, index)) if masked: target[keys] = array[keys].masked_array()...
def count(a, axis=None): """ Count the non-masked elements of the array along the given axis. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The a...
last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. :type axis: None, or int, or iterable of ints. :return: The Array representing the requested mean. :rtype: Array """ axes = _normalise_axis(axis, a) if axes is None or len(axes) != 1: msg = "This operation is currently li...
_Aggregation(a, axes[0], _CountStreamsHandler, _CountMaskedStreamsHandler, np.dtype('i'), {})
def min(a, axis=None): """ Request the minimum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose minimum is to be found. axis : None, or int, or iterable of ints Axis or axes along which the operation is performed. The...
operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. Returns ------- out : Array The Array representing the requested mean. """ axes = _normalise_axis(axis, a) a...
1 return _Aggregation(a, axes[0], _MinStreamsHandler, _MinMaskedStreamsHandler, a.dtype, {})
def max(a, axis=None): """ Request the maximum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose maximum is to be found. axis : None, or int, or iterable of ints Axis or axes along which the operation is performed. The...
operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. Returns ------- out : Array The Array representing the requested max. """ axes = _normalise_axis(axis, a) as...
1 return _Aggregation(a, axes[0], _MaxStreamsHandler, _MaxMaskedStreamsHandler, a.dtype, {})
def sum(a, axis=None): """ Request the sum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose summation is to be found. axis : None, or int, or iterable of ints Axis or axes along which the operation is performed. The d...
operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. Returns ------- out : Array The Array representing the requested sum. """ axes = _normalise_axis(axis, a) as...
1 return _Aggregation(a, axes[0], _SumStreamsHandler, _SumMaskedStreamsHandler, a.dtype, {})
def mean(a, axis=None, mdtol=1): """ Request the mean of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis...
the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. :type axis: None, or int, or iterable of ints. :param float mdtol: Tolerance of missing data. The value in each element of the resulting array will be masked if the fraction of masked data contributing to that element...
data is tolerated while mdtol=1 will mean the resulting element will be masked if and only if all the contributing elements of the source array are masked. Defaults to 1. :return: The Array representing the requested mean. :rtype: Array """ axes = _normalise_axis(axis, a) if axes is None or len(axes) != 1: msg = "This ...
AxisSupportError(msg) dtype = (np.array([0], dtype=a.dtype) / 1.).dtype kwargs = dict(mdtol=mdtol) return _Aggregation(a, axes[0], _MeanStreamsHandler, _MeanMaskedStreamsHandler, dtype, kwargs)
def std(a, axis=None, ddof=0): """ Request the standard deviation of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input arr...
from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. :type axis: None, or int, or iterable of ints. :param int ddof: Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. :return:...
standard deviation. :rtype: Array """ axes = _normalise_axis(axis, a) if axes is None or len(axes) != 1: msg = "This operation is currently limited to a single axis" raise AxisSupportError(msg) dtype = (np.array([0], dtype=a.dtype) / 1.).dtype return _Aggregation(a, axes[0], _StdStreamsHandler, _StdMaskedStreamsHandler...
def var(a, axis=None, ddof=0): """ Request the variance of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The ax...
the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. :type axis: None, or int, or iterable of ints. :param int ddof: Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. :return: The ...
:rtype: Array """ axes = _normalise_axis(axis, a) if axes is None or len(axes) != 1: msg = "This operation is currently limited to a single axis" raise AxisSupportError(msg) dtype = (np.array([0], dtype=a.dtype) / 1.).dtype return _Aggregation(a, axes[0], _VarStreamsHandler, _VarMaskedStreamsHandler, dtype, dict(ddof=d...
def _ufunc_wrapper(ufunc, name=None): """ A function to generate the top level biggus ufunc wrappers. """ if not isinstance(ufunc, np.ufunc): raise TypeError('{} is not a ufunc'.format(ufunc)) ufunc_name = ufunc.__name__ # Get hold of the masked array equivalent, if it exists. ma_ufunc = getattr(np.ma, ufunc_name, None...
== 1: func = _unary_fn_wrapper('np.{}'.format(ufunc_name), ufunc, ma_ufunc, name) else: raise ValueError('Unsupported ufunc {!r} with {} input arrays & {} ' 'output arrays.'.format(ufunc_name, ufunc.nin, ufunc.nout)) return func
def _sliced_shape(shape, keys): """ Returns the shape that results from slicing an array of the given shape by the given keys. >>> _sliced_shape(shape=(52350, 70, 90, 180), ... keys=(np.newaxis, slice(None, 10), 3, ... slice(None), slice(2, 3))) (1, 10, 90, 1) """ keys = _full_keys(keys, len(shape)) sliced_shape = [] s...
= len(range(*key.indices(shape[shape_dim]))) sliced_shape.append(size) elif isinstance(key, np.ndarray) and key.dtype == np.dtype('bool'): # Numpy boolean indexing. sliced_shape.append(builtins.sum(key)) elif isinstance(key, (tuple, np.ndarray)): sliced_shape.append(len(key)) elif key is np.newaxis: shape_dim -= 1 slic...
def _full_keys(keys, ndim): """ Given keys such as those passed to ``__getitem__`` for an array of ndim, return a fully expanded tuple of keys. In all instances, the result of this operation should follow: array[keys] == array[_full_keys(keys, array.ndim)] """ if not isinstance(keys, tuple): keys = (keys,) # Make keys ...
actually slice a dimension. n_keys_non_newaxis = len([key for key in keys if key is not np.newaxis]) # Numpy allows an extra dimension to be an Ellipsis, we remove it here # if Ellipsis is in keys, if this doesn't trigger we will raise an # IndexError. is_ellipsis = [key is Ellipsis for key in keys] if n_keys_non_newax...
Remove the left-most Ellipsis, as numpy does. keys.pop(is_ellipsis.index(True)) n_keys_non_newaxis -= 1 if n_keys_non_newaxis > ndim: raise IndexError('Dimensions are over specified for indexing.') lh_keys = [] # Keys, with the last key first. rh_keys = [] take_from_left = True while keys: if take_from_left: next_key =...
not take_from_left keys_list.append(next_key) middle = [slice(None)] * (ndim - n_keys_non_newaxis) return tuple(lh_keys + middle + rh_keys[::-1])
def ensure_array(array): """ Assert that the given array is an Array subclass (or numpy array). If the given array is a numpy.ndarray an appropriate NumpyArrayAdapter instance is created, otherwise the passed array must be a subclass of :class:`Array` else a TypeError will be raised. """ if not isinstance(array, Array)...
given array should be a `biggus.Array` ' 'instance, got {}.'.format(type(array))) return array
def size(array): """ Return a human-readable description of the number of bytes required to store the data of the given array. For example:: >>> array.nbytes 14000000 >> biggus.size(array) '13.35 MiB' Parameters ---------- array : array-like object The array object must provide an `nbytes` property. Returns ------- out...
10): size = '{} B'.format(nbytes) elif nbytes < (1 << 20): size = '{:.02f} KiB'.format(nbytes / (1 << 10)) elif nbytes < (1 << 30): size = '{:.02f} MiB'.format(nbytes / (1 << 20)) elif nbytes < (1 << 40): size = '{:.02f} GiB'.format(nbytes / (1 << 30)) else: size = '{:.02f} TiB'.format(nbytes / (1 << 40)) return size
def output(self, chunk): """ Dispatch the given Chunk onto all the registered output queues. If the chunk is None, it is silently ignored. """ if chunk is not None: for queue in self.output_queues: queue.put(chunk)
def run(self): """ Emit the Chunk instances which cover the underlying Array. The Array is divided into chunks with a size limit of MAX_CHUNK_SIZE which are emitted into all registered output queues. """ try: chunk_index = self.chunk_index_gen(self.array.shape, self.iteration_order) for key in chunk_index: # Now we hav...
:, :]`. # Simply "realise" the data for that region and emit it # as a Chunk to all registered output queues. if self.masked: data = self.array[key].masked_array() else: data = self.array[key].ndarray() output_chunk = Chunk(key, data) self.output(output_chunk) except: self.abort() raise else: for queue in self.output_q...
def add_input_nodes(self, input_nodes): """ Set the given nodes as inputs for this node. Creates a limited-size queue.Queue for each input node and registers each queue as an output of its corresponding node. """ self.input_queues = [queue.Queue(maxsize=3) for _ in input_nodes] for input_node, input_queue in zip(input_...
def run(self): """ Process the input queues in lock-step, and push any results to the registered output queues. """ try: while True: input_chunks = [input.get() for input in self.input_queues] for input in self.input_queues: input.task_done() if any(chunk is QUEUE_ABORT for chunk in input_chunks): self.abort() return i...
# but the last chunk). self.output(self.finalise()) except: self.abort() raise else: for queue in self.output_queues: queue.put(QUEUE_FINISHED)
def process_chunks(self, chunks): """ Store the incoming chunk at the corresponding position in the result array. """ chunk, = chunks if chunk.keys: self.result[chunk.keys] = chunk.data else: self.result[...] = chunk.data
def _cleanup_new_key(self, key, size, axis): """ Return a key of type int, slice, or tuple that is guaranteed to be valid for the given dimension size. Raises IndexError/TypeError for invalid keys. """ if _is_scalar(key): if key >= size or key < -size: msg = 'index {0} is out of bounds for axis {1} with' \ ' size {2}'....