text stringlengths 81 112k |
|---|
Handling of Exceptions.
Parameters
----------
exc : list, tuple
Information of the exception of the format (type, value, traceback).
Uses the return value of sys.exc_info().
def handle_err(self, exc):
'''Handling of Exceptions.
Parameters
------... |
Returns the configuration for a given module ID.
The working directory is searched for a file matching the module_id with the
given run number. If no run number is defined the last successfull run defines
the run number.
def get_configuration(self, module_id, run_number=None):
''' Retu... |
Select module and give access to the module.
def select_module(self, module_id):
''' Select module and give access to the module.
'''
if not isinstance(module_id, basestring) and isinstance(module_id, Iterable) and set(module_id) - set(self._modules):
raise ValueError('Module IDs in... |
Deselect module and cleanup.
def deselect_module(self):
''' Deselect module and cleanup.
'''
self._enabled_fe_channels = [] # ignore any RX sync errors
self._readout_fifos = []
self._filter = []
self._converter = []
self.dut['TX']['OUTPUT_ENABLE'] = 0
se... |
Waiting for all threads to appear, then continue.
def enter_sync(self):
''' Waiting for all threads to appear, then continue.
'''
if self._scan_threads and self.current_module_handle not in [t.name for t in self._scan_threads]:
raise RuntimeError('Thread name "%s" is not valid.')
... |
Waiting for all threads to appear, then continue.
def exit_sync(self):
''' Waiting for all threads to appear, then continue.
'''
if self._scan_threads and self.current_module_handle not in [t.name for t in self._scan_threads]:
raise RuntimeError('Thread name "%s" is not valid.')
... |
Running the FIFO readout while executing other statements.
Starting and stopping of the FIFO readout is synchronized between the threads.
def readout(self, *args, **kwargs):
''' Running the FIFO readout while executing other statements.
Starting and stopping of the FIFO readout is synchronize... |
Starting the FIFO readout.
Starting of the FIFO readout is executed only once by a random thread.
Starting of the FIFO readout is synchronized between all threads reading out the FIFO.
def start_readout(self, *args, **kwargs):
''' Starting the FIFO readout.
Starting of the FIFO readou... |
Stopping the FIFO readout.
Stopping of the FIFO readout is executed only once by a random thread.
Stopping of the FIFO readout is synchronized between all threads reading out the FIFO.
def stop_readout(self, timeout=10.0):
''' Stopping the FIFO readout.
Stopping of the FIFO readout is... |
Interpolatet the TDC calibration for each pixel from 0 to max_tdc
def get_charge(max_tdc, tdc_calibration_values, tdc_pixel_calibration): # Return the charge from calibration
''' Interpolatet the TDC calibration for each pixel from 0 to max_tdc'''
charge_calibration = np.zeros(shape=(80, 336, max_tdc))
fo... |
Open the hit or calibration file and return the calibration per pixel
def get_charge_calibration(calibation_file, max_tdc):
''' Open the hit or calibration file and return the calibration per pixel'''
with tb.open_file(calibation_file, mode="r") as in_file_calibration_h5:
tdc_calibration = in_file_cali... |
Add the `Plot pyBAR data`. entry to `Dataset` menu.
def addEntry(self):
"""Add the `Plot pyBAR data`. entry to `Dataset` menu.
"""
export_icon = QtGui.QIcon()
pixmap = QtGui.QPixmap(os.path.join(PLUGINSDIR,
'csv/icons/document-export.png'))
... |
Update the `export` QAction when the Dataset menu is pulled down.
This method is a slot. See class ctor for details.
def updateDatasetMenu(self):
"""Update the `export` QAction when the Dataset menu is pulled down.
This method is a slot. See class ctor for details.
"""
enabled... |
Export a given dataset to a `CSV` file.
This method is a slot connected to the `export` QAction. See the
:meth:`addEntry` method for details.
def plot(self):
"""Export a given dataset to a `CSV` file.
This method is a slot connected to the `export` QAction. See the
:meth:`addE... |
Brief description of the plugin.
def helpAbout(self):
"""Brief description of the plugin.
"""
# Text to be displayed
about_text = translate('pyBarPlugin',
"""<qt>
<p>Data plotting plug-in for pyBAR.
</qt>""",
... |
Sends the config via ZeroMQ to a specified socket. Is called at the beginning of a run and when the config changes. Conf can be any config dictionary.
def send_meta_data(socket, conf, name):
'''Sends the config via ZeroMQ to a specified socket. Is called at the beginning of a run and when the config changes. Conf ... |
Sends the data of every read out (raw data and meta data) via ZeroMQ to a specified socket
def send_data(socket, data, scan_parameters={}, name='ReadoutData'):
'''Sends the data of every read out (raw data and meta data) via ZeroMQ to a specified socket
'''
if not scan_parameters:
scan_parameters =... |
Mimics pytables.open_file() and stores the configuration and run configuration
Returns:
RawDataFile Object
Examples:
with open_raw_data_file(filename = self.scan_data_filename, title=self.scan_id, scan_parameters=[scan_parameter]) as raw_data_file:
# do something here
raw_data_file.app... |
Writing raw data file from data queue
If you need to write raw data once in a while this function may make it easy for you.
def save_raw_data_from_data_queue(data_queue, filename, mode='a', title='', scan_parameters=None): # mode="r+" to append data, raw_data_file_h5 must exist, "w" to overwrite raw_data_file_h5... |
Metascript that calls other scripts to tune the FE.
Parameters
----------
cfg_name : string
Name of the config to be created. This config holds the tuning results.
target_threshold : int
The target threshold value in PlsrDAC.
target_charge : int
... |
Takes point data (x,y) with errors(x,y) and fits a straight line. The deviation to this line is also plotted, showing the offset.
Parameters
----------
x, y, x_err, y_err: iterable
filename: string, PdfPages object or None
PdfPages file object: plot is appended to the pdf
stri... |
Takes 2D point data (x,y) and creates a profile histogram similar to the TProfile in ROOT. It calculates
the y mean for every bin at the bin center and gives the y mean error as error bars.
Parameters
----------
x : array like
data x positions
y : array like
data y positions... |
Rounding up to the nearest multiple of any positive integer
Parameters
----------
number : int, float
Input number.
multiple : int
Round up to multiple of multiple. Will be converted to int. Must not be equal zero.
Returns
-------
ceil_mod_number : int
Rou... |
Calculate quantiles from histograms, cuts off hist below and above given quantile. This function will not cut off more than the given values.
Parameters
----------
hist : array_like, iterable
Input histogram with dimension at most 1.
prob : float, list, tuple
List of quantiles to... |
Find the last nonzero index and mask the remaining entries.
Parameters
----------
hist : array_like, iterable
Input histogram with dimension at most 1.
return_index : bool, optional
If true, return the index.
copy : bool, optional
Whether to copy the input data (Tru... |
Readout thread continuously reading FIFO.
Readout thread, which uses read_raw_data_from_fifo() and appends data to self._fifo_data_deque (collection.deque).
def readout(self, fifo, no_data_timeout=None):
'''Readout thread continuously reading FIFO.
Readout thread, which uses read_raw_dat... |
Worker thread continuously filtering and converting data when data becomes available.
def worker(self, fifo):
'''Worker thread continuously filtering and converting data when data becomes available.
'''
logging.debug('Starting worker thread for %s', fifo)
self._fifo_conditions[fifo]... |
Writer thread continuously calling callback function for writing data when data becomes available.
def writer(self, index, no_data_timeout=None):
'''Writer thread continuously calling callback function for writing data when data becomes available.
'''
is_fe_data_header = logical_and(is_fe_wo... |
Reads local data buffer and returns data and meta data list.
Returns
-------
data : list
List of data and meta data dicts.
def get_data_from_buffer(self, filter_func=None, converter_func=None):
'''Reads local data buffer and returns data and meta data list.
... |
Reads local data buffer and returns raw data array.
Returns
-------
data : np.array
An array containing data words from the local data buffer.
def get_raw_data_from_buffer(self, filter_func=None, converter_func=None):
'''Reads local data buffer and returns raw data ar... |
Reads FIFO data and returns raw data array.
Returns
-------
data : np.array
An array containing FIFO data words.
def read_raw_data_from_fifo(self, fifo, filter_func=None, converter_func=None):
'''Reads FIFO data and returns raw data array.
Returns
... |
Attempts to retrieve an item from the queue Q. If Q is
empty, None is returned.
Blocks for 'timeout' seconds in case the queue is empty,
so don't use this method for speedy retrieval of multiple
items (use get_all_from_queue for that).
def get_item_from_queue(Q, timeout=0.01):
... |
Return a list of elements of seq[i] with the lowest
func(seq[i]) scores.
>>> argmin_list(['one', 'to', 'three', 'or'], len)
['to', 'or']
def argmin_list(seq, func):
""" Return a list of elements of seq[i] with the lowest
func(seq[i]) scores.
>>> argmin_list(['one', 'to... |
flatten iterable, but leaves out strings
[[[1, 2, 3], [4, 5]], 6] -> [1, 2, 3, 4, 5, 6]
def flatten_iterable(iterable):
"""flatten iterable, but leaves out strings
[[[1, 2, 3], [4, 5]], 6] -> [1, 2, 3, 4, 5, 6]
"""
for item in iterable:
if isinstance(item, collections.Iterable) ... |
generate iterable from item, but leaves out strings
def iterable(item):
"""generate iterable from item, but leaves out strings
"""
if isinstance(item, collections.Iterable) and not isinstance(item, basestring):
return item
else:
return [item] |
Returns a copy of seq, sorted by natural string sort.
def natsorted(seq, cmp=natcmp):
"Returns a copy of seq, sorted by natural string sort."
import copy
temp = copy.copy(seq)
natsort(temp, cmp)
return temp |
returns time as ISO string, mapping to and from datetime in ugly way
convert to string with str()
def get_iso_time():
'''returns time as ISO string, mapping to and from datetime in ugly way
convert to string with str()
'''
t1 = time.time()
t2 = datetime.datetime.fromtimestamp(t1)
... |
returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's
def get_float_time():
'''returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's
'''
t1 = time.time()
t2 = datetime.datetime.fromtimestamp(t1)
ret... |
Group dict of dicts by key.
def groupby_dict(dictionary, key):
''' Group dict of dicts by key.
'''
return dict((k, list(g)) for k, g in itertools.groupby(sorted(dictionary.keys(), key=lambda name: dictionary[name][key]), key=lambda name: dictionary[name][key])) |
Zipping iterables without fillvalue.
Note: https://stackoverflow.com/questions/38054593/zip-longest-without-fillvalue
def zip_nofill(*iterables):
'''Zipping iterables without fillvalue.
Note: https://stackoverflow.com/questions/38054593/zip-longest-without-fillvalue
'''
return (tuple([entr... |
Finding file in directory upwards.
def find_file_dir_up(filename, path=None, n=None):
'''Finding file in directory upwards.
'''
if path is None:
path = os.getcwd()
i = 0
while True:
current_path = path
for _ in range(i):
current_path = os.path.split(curr... |
Loading configuration from text files to register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string
Full path (directory and filename) of the configuration file. If name is not given, reload configuration from file.
def load_configuration_from... |
Loading configuration from HDF5 file to register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string, file
Filename of the HDF5 configuration file or file object.
node : string
Additional identifier (subgroup). Useful when more than... |
Saving configuration to text files from register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string
Filename of the configuration file.
def save_configuration_to_text_file(register, configuration_file):
'''Saving configuration to text file... |
Saving configuration to HDF5 file from register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string, file
Filename of the HDF5 configuration file or file object.
name : string
Additional identifier (subgroup). Useful when storing mo... |
Loading configuration
Parameters
----------
configuration_file : string
Path to the configuration file (text or HDF5 file).
def load_configuration(self, configuration_file):
'''Loading configuration
Parameters
----------
configuration_file... |
Saving configuration
Parameters
----------
configuration_file : string
Filename of the configuration file.
def save_configuration(self, configuration_file):
'''Saving configuration
Parameters
----------
configuration_file : string
... |
get fe_command from command name and keyword arguments
wrapper for build_commands()
implements FEI4 specific behavior
def get_commands(self, command_name, **kwargs):
"""get fe_command from command name and keyword arguments
wrapper for build_commands()
implements FEI4 s... |
build command from command_name and keyword values
Returns
-------
command_bitvector : list
List of bitarrays.
Usage
-----
Receives: command name as defined inside xml file, key-value-pairs as defined inside bit stream filed for each command
def bu... |
Calculating register numbers from register names.
Usage: get_global_register_attributes("attribute_name", name = [regname_1, regname_2, ...], addresses = 2)
Receives: attribute name to be returned, dictionaries (kwargs) of register attributes and values for making cuts
Returns: list of attr... |
Generate register objects (list) from register name list
Usage: get_global_register_objects(name = ["Amp2Vbn", "GateHitOr", "DisableColumnCnfg"], address = [2, 3])
Receives: keyword lists of register names, addresses,... for making cuts
Returns: list of register objects
def get_global_regi... |
Calculating register bitsets from register addresses.
Usage: get_global_register_bitsets([regaddress_1, regaddress_2, ...])
Receives: list of register addresses
Returns: list of register bitsets
def get_global_register_bitsets(self, register_addresses): # TOTO: add sorting
"""Cal... |
Generate register objects (list) from register name list
Usage: get_pixel_register_objects(name = ["TDAC", "FDAC"])
Receives: keyword lists of register names, addresses,...
Returns: list of register objects
def get_pixel_register_objects(self, do_sort=None, reverse=False, **kwargs):
... |
Calculating pixel register bitsets from pixel register addresses.
Usage: get_pixel_register_bitset(object, bit_number, double_column_number)
Receives: register object, bit number, double column number
Returns: double column bitset
def get_pixel_register_bitset(self, register_object, bit_no... |
Creating a configuration restore point.
Parameters
----------
name : str
Name of the restore point. If not given, a md5 hash will be generated.
def create_restore_point(self, name=None):
'''Creating a configuration restore point.
Parameters
-------... |
Restoring a configuration restore point.
Parameters
----------
name : str
Name of the restore point. If not given, a md5 hash will be generated.
keep : bool
Keeping restore point for later use.
last : bool
If name is not given, the la... |
Deleting all/a configuration restore points/point.
Parameters
----------
name : str
Name of the restore point to be deleted. If not given, all restore points will be deleted.
def clear_restore_points(self, name=None):
'''Deleting all/a configuration restore points/poi... |
Stores any configuration dictionary to HDF5 file.
Parameters
----------
h5_file : string, file
Filename of the HDF5 configuration file or file object.
configuation_name : str
Configuration name. Will be used for table name.
configuration : dict
Configuration diction... |
Filter and convert raw data numpy array (numpy.ndarray).
Parameters
----------
array : numpy.array
Raw data array.
filter_func : function
Function that takes array and returns true or false for each item in array.
converter_func : function
Function that takes array ... |
Convert raw data in data iterable.
Parameters
----------
data_iterable : iterable
Iterable where each element is a tuple with following content: (raw data, timestamp_start, timestamp_stop, status).
filter_func : function
Function that takes array and returns true or false for eac... |
Convert data iterable to raw data numpy array.
Parameters
----------
data_iterable : iterable
Iterable where each element is a tuple with following content: (raw data, timestamp_start, timestamp_stop, status).
Returns
-------
data_array : numpy.array
concatenated data... |
Converts TDC words at a given channel to common TDC header (0x4).
def convert_tdc_to_channel(channel):
''' Converts TDC words at a given channel to common TDC header (0x4).
'''
def f(value):
filter_func = logical_and(is_tdc_word, is_tdc_from_channel(channel))
select = filter_func(value... |
Selecting FE data from given channel.
Parameters
----------
channel : int
Channel number (4 is default channel on Single Chip Card).
Returns
-------
Function.
Usage:
1 Selecting FE data from channel 4 (combine with is_fe_word):
filter_fe_data_from_channel_... |
Logical and from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function.
Usage:
filter_func=logical_and(is_data_record, is_data_from_channel(4)) # new filter function
... |
Logical or from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function.
def logical_or(f1, f2): # function factory
'''Logical or from functions.
Parameters
-----... |
Logical not from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function.
def logical_not(f): # function factory
'''Logical not from functions.
Parameters
-------... |
Logical xor from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function.
def logical_xor(f1, f2): # function factory
'''Logical xor from functions.
Parameters
--... |
Returns 31bit trigger counter (mode=0), 31bit timestamp (mode=1), 15bit timestamp and 16bit trigger counter (mode=2)
def get_trigger_data(value, mode=0):
'''Returns 31bit trigger counter (mode=0), 31bit timestamp (mode=1), 15bit timestamp and 16bit trigger counter (mode=2)
'''
if mode == 2:
ret... |
Convert raw data array to column, row, and ToT array.
Parameters
----------
array : numpy.array
Raw data array.
Returns
-------
Tuple of arrays.
def get_col_row_tot_array_from_data_record_array(array): # TODO: max ToT
'''Convert raw data array to column, row, and ToT ar... |
Takes the pixel raw data and interprets them. This includes consistency checks and pixel/data matching.
The data has to come from one double column only but can have more than one pixel bit (e.g. TDAC = 5 bit).
Parameters
----------
data : numpy.ndarray
The raw data words.
dc : int
... |
Set all settings to their standard values.
def set_standard_settings(self):
'''Set all settings to their standard values.
'''
if self.is_open(self.out_file_h5):
self.out_file_h5.close()
self.out_file_h5 = None
self._setup_clusterizer()
self.chunk_size = 30000... |
Set the numbers of BCIDs (usually 16) of one event.
def trig_count(self, value):
"""Set the numbers of BCIDs (usually 16) of one event."""
self._trig_count = 16 if value == 0 else value
self.interpreter.set_trig_count(self._trig_count) |
Set maximum ToT value that is considered to be a hit
def max_tot_value(self, value):
"""Set maximum ToT value that is considered to be a hit"""
self._max_tot_value = value
self.interpreter.set_max_tot(self._max_tot_value)
self.histogram.set_max_tot(self._max_tot_value)
self.clus... |
Interprets the raw data word table of all given raw data files with the c++ library.
Creates the h5 output file and PDF plots.
Parameters
----------
analyzed_data_file : string
The file name of the output analyzed data file. If None, the output analyzed data file
... |
Analyzes a hit table with the c++ histogrammming/clusterizer.
Parameters
----------
analyzed_data_file : string
The filename of the analyzed data file. If None, the analyzed data file
specified during initialization is taken.
Filename extension (.h5) does not... |
Tries to get the scan parameters needed for analysis from the raw data file
def _deduce_settings_from_file(self, opened_raw_data_file): # TODO: parse better
'''Tries to get the scan parameters needed for analysis from the raw data file
'''
try: # take infos raw data files (not avalable in old... |
Takes the PlsrDAC calibration and the stored C-high/C-low mask to calculate the charge from the PlsrDAC array on a pixel basis
def _get_plsr_dac_charge(self, plsr_dac_array, no_offset=False):
'''Takes the PlsrDAC calibration and the stored C-high/C-low mask to calculate the charge from the PlsrDAC array on a p... |
If Schema access, parse fields and build respective lists
def _parse_fields(self, result, field_name):
""" If Schema access, parse fields and build respective lists
"""
field_list = []
for key, value in result.get('schema', {}).get(field_name, {}).items():
if key not in fiel... |
Builds a list of valid fields
def _build_fields(self):
""" Builds a list of valid fields
"""
declared_fields = self.solr._send_request('get', ADMIN_URL)
result = decoder.decode(declared_fields)
self.field_list = self._parse_fields(result, 'fields')
# Build regular expre... |
Reformats the given document before insertion into Solr.
This method reformats the document in the following ways:
- removes extraneous fields that aren't defined in schema.xml
- unwinds arrays in order to find and later flatten sub-documents
- flattens the document so that there ... |
Override DocManagerBase.apply_update to have flat documents.
def apply_update(self, doc, update_spec):
"""Override DocManagerBase.apply_update to have flat documents."""
# Replace a whole document
if not '$set' in update_spec and not '$unset' in update_spec:
# update_spec contains t... |
Apply updates given in update_spec to the document whose id
matches that of doc.
def update(self, document_id, update_spec, namespace, timestamp):
"""Apply updates given in update_spec to the document whose id
matches that of doc.
"""
# Commit outstanding changes so that the do... |
Update or insert a document into Solr
This method should call whatever add/insert/update method exists for
the backend engine and add the document in there. The input will
always be one mongo document, represented as a Python dictionary.
def upsert(self, doc, namespace, timestamp):
"""... |
Update or insert multiple documents into Solr
docs may be any iterable
def bulk_upsert(self, docs, namespace, timestamp):
"""Update or insert multiple documents into Solr
docs may be any iterable
"""
if self.auto_commit_interval is not None:
add_kwargs = {
... |
Removes documents from Solr
The input is a python dictionary that represents a mongo document.
def remove(self, document_id, namespace, timestamp):
"""Removes documents from Solr
The input is a python dictionary that represents a mongo document.
"""
self.solr.delete(id=u(docum... |
Helper method for iterating over Solr search results.
def _stream_search(self, query):
"""Helper method for iterating over Solr search results."""
for doc in self.solr.search(query, rows=100000000):
if self.unique_key != "_id":
doc["_id"] = doc.pop(self.unique_key)
... |
Called to query Solr for documents in a time range.
def search(self, start_ts, end_ts):
"""Called to query Solr for documents in a time range."""
query = '_ts: [%s TO %s]' % (start_ts, end_ts)
return self._stream_search(query) |
Returns the last document stored in the Solr engine.
def get_last_doc(self):
"""Returns the last document stored in the Solr engine.
"""
#search everything, sort by descending timestamp, return 1 row
try:
result = self.solr.search('*:*', sort='_ts desc', rows=1)
exce... |
Returns the result of the Password-Based Key Derivation Function 2 with
a single iteration (i.e. count = 1).
prf - a psuedorandom function
See http://en.wikipedia.org/wiki/PBKDF2
def pbkdf2_single(password, salt, key_length, prf):
'''Returns the result of the Password-Based Key Derivation Fu... |
Salsa 20/8 stream cypher; Used by BlockMix. See http://en.wikipedia.org/wiki/Salsa20
def salsa20_8(B):
'''Salsa 20/8 stream cypher; Used by BlockMix. See http://en.wikipedia.org/wiki/Salsa20'''
# Create a working copy
x = B[:]
# Expanded form of this code. The expansion is significantly faster but
... |
Blockmix; Used by SMix.
def blockmix_salsa8(BY, Yi, r):
'''Blockmix; Used by SMix.'''
start = (2 * r - 1) * 16
X = BY[start:start + 16] # BlockMix - 1
for i in xrange(0, 2 * r): # BlockMix - 2
for xi in xrange(0, 16): ... |
SMix; a specific case of ROMix. See scrypt.pdf in the links above.
def smix(B, Bi, r, N, V, X):
'''SMix; a specific case of ROMix. See scrypt.pdf in the links above.'''
X[:32 * r] = B[Bi:Bi + 32 * r] # ROMix - 1
for i in xrange(0, N): # ROMix - 2
aod = ... |
Returns the result of the scrypt password-based key derivation function.
Constraints:
r * p < (2 ** 30)
dkLen <= (((2 ** 32) - 1) * 32
N must be a power of 2 greater than 1 (eg. 2, 4, 8, 16, 32...)
N, r, p must be positive
def hash(password, salt, N, r, p, dkLen):
"""Ret... |
Return an internal attribute after ensuring the headers is loaded if necessary.
def _load_get_attr(self, name):
'Return an internal attribute after ensuring the headers is loaded if necessary.'
if self._mode in _allowed_read and self._N is None:
self._read_header()
return getattr(se... |
Close the underlying file.
Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
def close(sel... |
Returns whether a scrypt encrypted file is valid.
def verify_file(fp, password):
'Returns whether a scrypt encrypted file is valid.'
sf = ScryptFile(fp = fp, password = password)
for line in sf: pass
sf.close()
return sf.valid |
Next line from the decrypted file, as a string.
Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
def readline(self, size = None):
'''Next line from the decrypted file, as... |
Read and parse the header and calculate derived keys.
def _read_header(self):
'''Read and parse the header and calculate derived keys.'''
try:
# Read the entire header
header = self._fp.read(96)
if len(header) != 96:
raise InvalidScryptFileFormat("In... |
Read at most size bytes, returned as a string.
If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
def read(self, size = None):
'''Read at ... |
Writes the header to the underlying file object.
def _write_header(self):
'Writes the header to the underlying file object.'
header = b'scrypt' + CHR0 + struct.pack('>BII', int(math.log(self.N, 2)), self.r, self.p) + self.salt
# Add the header checksum to the header
checksum = hashlib... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.