text stringlengths 81 112k |
|---|
Puts multiple objects of the same type into the data sink. The objects may be transformed into a new type for insertion if necessary.
Args:
items: An iterable (e.g. list) of objects to be inserted into the data pipeline.
def put_many(self, type: Type[T], items: Iterable[T]) -> None:
"""Put... |
A crude way of output the errors for now. This needs to be
cleaned up into something better.
def print_error(self, wrapper):
""" A crude way of output the errors for now. This needs to be
cleaned up into something better.
"""
level = 0
parent = wrapper.parent
whi... |
Refracts the given value.
>>> refract('string')
String(content='string')
>>> refract(1)
Number(content=1)
>>> refract(True)
Boolean(content=True)
>>> refract(None)
Null()
>>> refract([1, 2])
Array(content=[Number(content=1), Number(content=2)])
>>> refract({'name': 'Doe... |
Serialises the given element into JSON.
>>> JSONSerialiser().serialise(String(content='Hello'))
'{"element": "string", "content": "Hello"}'
def serialise(self, element: Element, **kwargs) -> str:
"""
Serialises the given element into JSON.
>>> JSONSerialiser().serialise(String... |
Deserialises the given JSON into an element.
>>> json = '{"element": "string", "content": "Hello"'
>>> JSONDeserialiser().deserialise(json)
String(content='Hello')
def deserialise(self, element_json: str) -> Element:
"""
Deserialises the given JSON into an element.
>>>... |
Serialises the given element into Compact JSON.
>>> CompactJSONSerialiser().serialise(String(content='Hello'))
'["string", null, null, "Hello"]'
def serialise(self, element: Element) -> str:
"""
Serialises the given element into Compact JSON.
>>> CompactJSONSerialiser().serial... |
Deserialises the given compact JSON into an element.
>>> deserialiser = CompactJSONDeserialiser()
>>> deserialiser.deserialise('["string", null, null, "Hi"]')
String(content='Hi')
def deserialise(self, content) -> Element:
"""
Deserialises the given compact JSON into an element... |
Method to force the combination of parallel coverage reports.
def combine_coverage_reports(self, omit, parallel):
""" Method to force the combination of parallel coverage reports."""
tmp_cov = coverage.coverage(omit=omit, data_suffix=parallel)
tmp_cov.load()
tmp_cov.combine()
tm... |
The available data transformers.
def transforms(self) -> Mapping[Type, Iterable[Type]]:
"""The available data transformers."""
try:
return getattr(self.__class__, "transform")._transforms
except AttributeError:
return {} |
Transforms an object to a new type.
Args:
target_type: The type to be converted to.
value: The object to be transformed.
context: The context of the transformation (mutable).
def transform(self, target_type: Type[T], value: F, context: PipelineContext = None) -> T:
... |
Serializes the CaseWrapper object for collection.
Warning, this will only grab the available information.
It is strongly that you only call this once all specs and
tests have completed.
def serialize(self):
""" Serializes the CaseWrapper object for collection.
Warning, this wi... |
Serializes the Spec/Describe object for collection.
Warning, this will only grab the available information.
It is strongly that you only call this once all specs and
tests have completed.
def serialize(self):
""" Serializes the Spec/Describe object for collection.
Warning, thi... |
Calls any registered hooks providing the current state.
def _run_hooks(self):
"""Calls any registered hooks providing the current state."""
for hook in self.hooks:
getattr(self, hook)(self._state) |
Append an element onto the array.
>>> array = Array()
>>> array.append('test')
def append(self, element):
"""
Append an element onto the array.
>>> array = Array()
>>> array.append('test')
"""
from refract.refraction import refract
self.content... |
Insert an element at a given position.
>>> array = Array()
>>> array.insert(0, Element())
def insert(self, index: int, element):
"""
Insert an element at a given position.
>>> array = Array()
>>> array.insert(0, Element())
"""
from refract.refraction i... |
Return the index in the array of the first item whose value is element.
It is an error if there is no such item.
>>> element = String('hello')
>>> array = Array(content=[element])
>>> array.index(element)
0
def index(self, element: Element) -> int:
"""
Return th... |
The types of objects the data store provides.
def provides(self): # type: Union[Iterable[Type[T]], Type[Any]]
"""The types of objects the data store provides."""
types = set()
any_dispatch = False
try:
types.update(getattr(self.__class__, "get")._provides)
any_d... |
Gets a query from the data source.
Args:
query: The query being requested.
context: The context for the extraction (mutable).
Returns:
The requested object.
def get(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> T:
"""Get... |
Gets a query from the data source, which contains a request for multiple objects.
Args:
query: The query being requested (contains a request for multiple objects).
context: The context for the extraction (mutable).
Returns:
The requested objects.
def get_many(self,... |
Will automatically not subscribe reporters that are not parallel
or serial depending on the current mode.
def subscribe_all_to_spec(self, spec):
""" Will automatically not subscribe reporters that are not parallel
or serial depending on the current mode.
"""
for reporter in self... |
Alias for print_indent_msg with color determined by status.
def output(self, msg, indent, status=None):
""" Alias for print_indent_msg with color determined by status."""
color = None
if self.use_color:
color = get_color_from_status(status)
print_indent_msg(msg, indent, colo... |
An unfortunate evil... All because Python's traceback cannot
determine where my executed code is coming from...
def get_real_last_traceback(exception):
""" An unfortunate evil... All because Python's traceback cannot
determine where my executed code is coming from...
"""
traceback_blocks = []
_... |
Returns the assets in the transaction.
def assets(self) -> List[Asset]:
"""
Returns the assets in the transaction.
"""
return list(filter(is_element(Asset), self.content)) |
Decompiles an AST into Python code.
Arguments:
- ast: code to decompile, using AST objects as generated by the standard library ast module
- indentation: indentation level of lines
- line_length: if lines become longer than this length, ast_decompiler will try to break them up
(but it will not ne... |
Writes a list of nodes, separated by separator.
If allow_newlines, will write the expression over multiple lines if necessary to say within
max_line_length. If need_parens, will surround the expression with parentheses in this case.
If final_separator_if_multiline, will write a separator at the... |
Returns the underlying (unrefracted) value of element
>>> Element(content='Hello').defract
'Hello'
>>> Element(content=Element(content='Hello')).defract
'Hello'
>>> Element(content=[Element(content='Hello')]).defract
['Hello']
def defract(self):
"""
Re... |
Returns all of the children elements.
def children(self):
"""
Returns all of the children elements.
"""
if isinstance(self.content, list):
return self.content
elif isinstance(self.content, Element):
return [self.content]
else:
return ... |
Generator returning all recursive children elements.
def recursive_children(self):
"""
Generator returning all recursive children elements.
"""
for child in self.children:
yield child
for recursive_child in child.recursive_children:
yield recurs... |
Primary method for test assertions in Specter
:param obj: The evaluated target object
:param caller_args: Is only used when using expecting a raised Exception
def expect(obj, caller_args=[]):
"""Primary method for test assertions in Specter
:param obj: The evaluated target object
:param caller_ar... |
Primary method for test assertions in Specter
:param obj: The evaluated target object
:param caller_args: Is only used when using expecting a raised Exception
def require(obj, caller_args=[]):
"""Primary method for test assertions in Specter
:param obj: The evaluated target object
:param caller_a... |
The skip decorator allows for you to always bypass a test.
:param reason: Expects a string
def skip(reason):
"""The skip decorator allows for you to always bypass a test.
:param reason: Expects a string
"""
def decorator(test_func):
if not isinstance(test_func, (type, ClassObjType)):
... |
The skip_if decorator allows for you to bypass a test on conditions
:param condition: Expects a boolean
:param reason: Expects a string
def skip_if(condition, reason=None):
"""The skip_if decorator allows for you to bypass a test on conditions
:param condition: Expects a boolean
:param reason: Ex... |
The incomplete decorator behaves much like a normal skip; however,
tests that are marked as incomplete get tracked under a different metric.
This allows for you to create a skeleton around all of your features and
specifications, and track what tests have been written and what
tests are left outstanding... |
The metadata decorator allows for you to tag specific tests with
key/value data for run-time processing or reporting. The common use case
is to use metadata to tag a test as a positive or negative test type.
.. code-block:: python
# Example of using the metadata decorator
@metadata(type='n... |
Serializes the ExpectAssert object for collection.
Warning, this will only grab the available information.
It is strongly that you only call this once all specs and
tests have completed.
def serialize(self):
"""Serializes the ExpectAssert object for collection.
Warning, this w... |
The types of objects the data sink can store.
def accepts(self): # type: Union[Iterable[Type[T]], Type[Any]]
"""The types of objects the data sink can store."""
types = set()
any_dispatch = False
try:
types.update(getattr(self.__class__, "put")._accepts)
any_dis... |
Puts multiple objects of the same type into the data sink.
Args:
type: The type of the objects being inserted.
items: The objects to be inserted.
context: The context of the insertion (mutable).
def put_many(self, type: Type[T], items: Iterable[T], context: PipelineContext ... |
Shorthand for WARCFile(filename, mode).
Auto detects file and opens it.
def open(filename, mode="rb", format = None):
"""Shorthand for WARCFile(filename, mode).
Auto detects file and opens it.
"""
if format == "auto" or format == None:
format = detect_format(filename)
if format == "... |
Initializes important headers to default values, if not already specified.
The WARC-Record-ID header is set to a newly generated UUID.
The WARC-Date header is set to the current datetime.
The Content-Type is set based on the WARC-Type header.
The Content-Length is initialized to... |
Writes this header to a file, in the format specified by WARC.
def write_to(self, f):
"""Writes this header to a file, in the format specified by WARC.
"""
f.write(self.version + "\r\n")
for name, value in self.items():
name = name.title()
# Use standard forms fo... |
Creates a WARCRecord from given response object.
This must be called before reading the response. The response can be
read after this method is called.
:param response: An instance of :class:`requests.models.Response`.
def from_response(response):
"""Creates a WARCRecord from... |
Adds a warc record to this WARC file.
def write_record(self, warc_record):
"""Adds a warc record to this WARC file.
"""
warc_record.write_to(self.fileobj)
# Each warc record is written as separate member in the gzip file
# so that each record can be read independetly.
if... |
Utility to browse through the records in the warc file.
This returns an iterator over (record, offset, size) for each record in
the file. If the file is gzip compressed, the offset and size will
corresponds to the compressed file.
The payload of each record is limite... |
Returns the file offset. If this is a compressed file, then the
offset in the compressed file is returned.
def tell(self):
"""Returns the file offset. If this is a compressed file, then the
offset in the compressed file is returned.
"""
if isinstance(self.fileobj, gzip2.GzipFi... |
Closes the current member being written.
def close_member(self):
"""Closes the current member being written.
"""
# The new member is not yet started, no need to close
if self._new_member:
return
self.fileobj.write(self.compress.flush())
write32u(... |
Starts writing a new member if required.
def _start_member(self):
"""Starts writing a new member if required.
"""
if self._new_member:
self._init_write(self.name)
self._write_gzip_header()
self._new_member = False |
Closes the gzip with care to handle multiple members.
def close(self):
"""Closes the gzip with care to handle multiple members.
"""
if self.fileobj is None:
return
if self.mode == WRITE:
self.close_member()
self.fileobj = None
elif self.mode =... |
Returns a file-like object to read one member from the gzip file.
def read_member(self):
"""Returns a file-like object to read one member from the gzip file.
"""
if self._member_lock is False:
self._member_lock = True
if self._new_member:
try:
# ... |
Writes the given data as one gzip member.
The data can be a string, an iterator that gives strings or a file-like object.
def write_member(self, data):
"""Writes the given data as one gzip member.
The data can be a string, an iterator that gives strings or a file-like object.
... |
Writes out the arc header to the file like object `f`.
If the version field is 1, it writes out an arc v1 header,
otherwise (and this is default), it outputs a v2 header.
def write_to(self, f, version = None):
"""
Writes out the arc header to the file like object `f`.
If the... |
Constructs an ARC record from a string and returns it.
TODO: It might be best to merge this with the _read_arc_record
function rather than reimplement the functionality here.
def from_string(cls, string, version):
"""
Constructs an ARC record from a string and returns it.
... |
Writes out an ARC header
def _write_header(self):
"Writes out an ARC header"
if "org" not in self.file_headers:
warnings.warn("Using 'unknown' for Archiving organisation name")
self.file_headers['org'] = "Unknown"
if "date" not in self.file_headers:
now = dat... |
Writes out the given arc record to the file
def write(self, arc_record):
"Writes out the given arc record to the file"
if not self.version:
self.version = 2
if not self.header_written:
self.header_written = True
self._write_header()
arc_record.write_t... |
Reads out the file header for the arc file. If version was
not provided, this will autopopulate it.
def _read_file_header(self):
"""Reads out the file header for the arc file. If version was
not provided, this will autopopulate it."""
header = self.fileobj.readline()
payload1 = ... |
Reads out an arc record, formats it and returns it
def _read_arc_record(self):
"Reads out an arc record, formats it and returns it"
#XXX:Noufal Stream payload here rather than just read it
# r = self.fileobj.readline() # Drop the initial newline
# if r == "":
# return None
... |
Create a new BIC object from country- and bank-code.
Examples:
>>> bic = BIC.from_bank_code('DE', '20070000')
>>> bic.country_code
'DE'
>>> bic.bank_code
'DEUT'
>>> bic.location_code
'HH'
>>> BIC.from_bank_code('DE... |
str: The BIC separated in the blocks bank-, country- and location-code.
def formatted(self):
"""str: The BIC separated in the blocks bank-, country- and location-code."""
formatted = ' '.join([self.bank_code, self.country_code, self.location_code])
if self.branch_code:
formatted += ... |
str or None: The country specific bank-code associated with the BIC.
def country_bank_code(self):
"""str or None: The country specific bank-code associated with the BIC."""
entry = registry.get('bic').get(self.compact)
if entry:
return entry.get('bank_code') |
str or None: The name of the bank associated with the BIC.
def bank_name(self):
"""str or None: The name of the bank associated with the BIC."""
entry = registry.get('bic').get(self.compact)
if entry:
return entry.get('name') |
str or None: The short name of the bank associated with the BIC.
def bank_short_name(self):
"""str or None: The short name of the bank associated with the BIC."""
entry = registry.get('bic').get(self.compact)
if entry:
return entry.get('short_name') |
Generate an IBAN from it's components.
If the bank-code and/or account-number have less digits than required by their
country specific representation, the respective component is padded with zeros.
Examples:
To generate an IBAN do the following::
>>> bank_code = '... |
str: The IBAN formatted in blocks of 4 digits.
def formatted(self):
"""str: The IBAN formatted in blocks of 4 digits."""
return ' '.join(self.compact[i:i + 4] for i in range(0, len(self.compact), 4)) |
Convert .tdms datasets to the hdf5-based .rtdc file format
def tdms2rtdc():
"""Convert .tdms datasets to the hdf5-based .rtdc file format"""
parser = tdms2rtdc_parser()
args = parser.parse_args()
path_tdms = pathlib.Path(args.tdms_path).resolve()
path_rtdc = pathlib.Path(args.rtdc_path)
# Det... |
Perform checks on experimental datasets
def verify_dataset():
"""Perform checks on experimental datasets"""
parser = verify_dataset_parser()
args = parser.parse_args()
path_in = pathlib.Path(args.path).resolve()
viol, aler, info = load.check_dataset(path_in)
print_info("Checking {}".format(path... |
Load the configuration from a file
Parameters
----------
cfg_file: str
Path to configuration file
Returns
-------
cfg : CaseInsensitiveDict
Dictionary with configuration parameters
def load_from_file(cfg_file):
"""Load the configuration from a file
Parameters
-... |
Convert a variable from a string to its correct type
Parameters
----------
var: str
The variable name
val: str
The value of the variable represented as a string
Returns
-------
varout: str
Stripped lowercase `var`
valout: any type
The value converted fro... |
Convert a variable to a string
Parameters
----------
var: str
The variable name
val: any type
The value of the variable
Returns
-------
varout: str
Stripped lowercase `var`
valout: any type
The value converted to a useful string representation
See A... |
Set default initial values
The default values are hard-coded for backwards compatibility
and for several functionalities in dclab.
def _init_default_values(self):
"""Set default initial values
The default values are hard-coded for backwards compatibility
and for several functi... |
Save the configuration to a file
def save(self, filename):
"""Save the configuration to a file"""
filename = pathlib.Path(filename)
out = []
keys = sorted(list(self.keys()))
for key in keys:
out.append("[{}]".format(key))
section = self[key]
i... |
Update current config with a dictionary
def update(self, newcfg):
"""Update current config with a dictionary"""
for key in newcfg.keys():
if key not in self._cfg:
self._cfg[key] = CaseInsensitiveDict()
for skey in newcfg[key]:
self._cfg[key][skey]... |
convert area-deformation-emodulus triplet
The conversion formula is described in :cite:`Mietke2015`.
Parameters
----------
area_um: ndarray
Convex cell area [µm²]
deform: ndarray
Deformation
emodulus: ndarray
Young's Modulus [kPa]
channel_width_in: float
Ori... |
Deformation correction term for pixelation effects
The contour in RT-DC measurements is computed on a
pixelated grid. Due to sampling problems, the measured
deformation is overestimated and must be corrected.
The correction formula is described in :cite:`Herold2017`.
Parameters
----------
... |
Compute apparent Young's modulus using a look-up table
Parameters
----------
area_um: float or ndarray
Apparent (2D image) area [µm²] of the event(s)
deform: float or ndarray
The deformation (1-circularity) of the event(s)
medium: str or float
The medium to compute the visco... |
Search API.
def search(request):
"""Search API."""
empty_response = json.dumps({
u'query': {
u'limits': [],
u'per_page': DEFAULT_PER_PAGE,
u'page': 1,
},
u'results': {
u'items': [],
u'total': 0,
u'limits': [],
... |
Creates an exception for a given method, and RpcError.
def make_exception(method, e):
"""Creates an exception for a given method, and RpcError."""
x = e.details()
name = x[:x.find(':')].split('.')[-1]
if name in globals():
cls = globals()[name]
else:
cls = UnknownRpcException # noq... |
Convert text to int, raising exeception on invalid input
def text_to_int(text, default_base="hex"):
""" Convert text to int, raising exeception on invalid input
"""
if text.startswith("0x"):
value = int(text[2:], 16)
elif text.startswith("$"):
value = int(text[1:], 16)
elif text.sta... |
Map out the sectors and link the sectors together
raises NotEnoughSpaceOnDisk if the whole file won't fit. It will not
allow partial writes.
def assign_sector_numbers(self, dirent, sector_list):
""" Map out the sectors and link the sectors together
raises NotEnoughSpaceOnDisk if the w... |
Downsampling by randomly removing points
Parameters
----------
a: 1d ndarray
The input array to downsample
samples: int
The desired number of samples
remove_invalid: bool
Remove nan and inf values before downsampling
ret_idx: bool
Also return a boolean array that... |
Content-based downsampling for faster visualization
The arrays `a` and `b` make up a 2D scatter plot with high
and low density values. This method takes out points at
indices with high density.
Parameters
----------
a, b: 1d ndarrays
The input arrays to downsample
samples: int
... |
Check whether `a` and `b` are not inf or nan
def valid(a, b):
"""Check whether `a` and `b` are not inf or nan"""
return ~(np.isnan(a) | np.isinf(a) | np.isnan(b) | np.isinf(b)) |
Normalize `a` with min/max values of `ref1`, using all elements of
`ref1` where the `ref1` and `ref2` are not nan or inf
def norm(a, ref1, ref2):
"""
Normalize `a` with min/max values of `ref1`, using all elements of
`ref1` where the `ref1` and `ref2` are not nan or inf"""
ref = ref1[valid(ref1, re... |
Gaussian Kernel for continuous variables
Parameters
----------
h : 1-D ndarray, shape (K,)
The bandwidths used to estimate the value of the kernel function.
Xi : 1-D ndarray, shape (K,)
The value of the training set.
x : 1-D ndarray, shape (K,)
The value at which the kernel d... |
Parse the RT-DC configuration of an hdf5 file
def parse_config(h5path):
"""Parse the RT-DC configuration of an hdf5 file"""
with h5py.File(h5path, mode="r") as fh5:
h5attrs = dict(fh5.attrs)
# Convert byte strings to unicode strings
# https://github.com/h5py/h5py/issues/379... |
Hash value based on file name and content
def hash(self):
"""Hash value based on file name and content"""
if self._hash is None:
tohash = [self.path.name]
# Hash a maximum of ~1MB of the hdf5 file
tohash.append(hashfile(self.path, blocksize=65536, count=20))
... |
Compute number of bins based on Doane's formula
def bin_num_doane(a):
"""Compute number of bins based on Doane's formula"""
bad = np.isnan(a) | np.isinf(a)
data = a[~bad]
acc = bin_width_doane(a)
num = np.int(np.round((data.max() - data.min()) / acc))
return num |
Compute accuracy (bin width) based on Doane's formula
References
----------
- `<https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width>`_
- `<https://stats.stackexchange.com/questions/55134/
doanes-formula-for-histogram-binning>`_
def bin_width_doane(a):
"""Compute accuracy (bin wi... |
Ignores nans and infs from the input data
Invalid positions in the resulting density are set to nan.
def ignore_nan_inf(kde_method):
"""Ignores nans and infs from the input data
Invalid positions in the resulting density are set to nan.
"""
def new_kde_method(events_x, events_y, xout=None, yout=N... |
Gaussian Kernel Density Estimation
Parameters
----------
events_x, events_y: 1D ndarray
The input points for kernel density estimation. Input
is flattened automatically.
xout, yout: ndarray
The coordinates at which the KDE should be computed.
If set to none, input coordi... |
Histogram-based Kernel Density Estimation
Parameters
----------
events_x, events_y: 1D ndarray
The input points for kernel density estimation. Input
is flattened automatically.
xout, yout: ndarray
The coordinates at which the KDE should be computed.
If set to none, input... |
No Kernel Density Estimation
Parameters
----------
events_x, events_y: 1D ndarray
The input points for kernel density estimation. Input
is flattened automatically.
xout, yout: ndarray
The coordinates at which the KDE should be computed.
If set to none, input coordinates ... |
Multivariate Kernel Density Estimation
Parameters
----------
events_x, events_y: 1D ndarray
The input points for kernel density estimation. Input
is flattened automatically.
bw: tuple (bwx, bwy) or None
The bandwith for kernel density estimation.
xout, yout: ndarray
... |
Redirect from legacy /content/id/version to new /contents/uuid@version.
Handles collection context (book) as well.
def redirect_legacy_content(request):
"""Redirect from legacy /content/id/version to new /contents/uuid@version.
Handles collection context (book) as well.
"""
routing_args = request... |
Convenience method for population self._data
def _add(self, isoel, col1, col2, method, meta):
"""Convenience method for population self._data"""
self._data[method][col1][col2]["isoelastics"] = isoel
self._data[method][col1][col2]["meta"] = meta
# Use advanced slicing to flip the data c... |
Add isoelastics
Parameters
----------
isoel: list of ndarrays
Each list item resembles one isoelastic line stored
as an array of shape (N,3). The last column contains
the emodulus data.
col1: str
Name of the first feature of all isoelastic... |
Undo pixelation correction
Isoelasticity lines are already corrected for pixelation
effects as described in
Mapping of Deformation to Apparent Young's Modulus
in Real-Time Deformability Cytometry
Christoph Herold, arXiv:1704.00572 [cond-mat.soft] (2017)
https://arxiv.or... |
Convert isoelastics in area_um-deform space
Parameters
----------
isoel: list of 2d ndarrays of shape (N, 3)
Each item in the list corresponds to one isoelasticity
line. The first column is defined by `col1`, the second
by `col2`, and the third column is the ... |
Get isoelastics
Parameters
----------
col1: str
Name of the first feature of all isoelastics
(e.g. isoel[0][:,0])
col2: str
Name of the second feature of all isoelastics
(e.g. isoel[0][:,1])
method: str
The method used ... |
Convenience method that extracts the metadata from RTDCBase
Parameters
----------
col1: str
Name of the first feature of all isoelastics
(e.g. isoel[0][:,0])
col2: str
Name of the second feature of all isoelastics
(e.g. isoel[0][:,1])
... |
Load isoelastics from a text file
The text file is loaded with `numpy.loadtxt` and must have
three columns, representing the two data columns and the
elastic modulus with units defined in `definitions.py`.
The file header must have a section defining meta data of the
content lik... |
Return a simple "don't index me" robots.txt file.
def robots(request):
"""Return a simple "don't index me" robots.txt file."""
resp = request.response
resp.status = '200 OK'
resp.content_type = 'text/plain'
resp.body = """
User-Agent: *
Disallow: /
"""
return resp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.