code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if callable(updater):
state_change = updater(self)
elif updater is not None:
state_change = updater
else:
state_change = kwargs
return [callback_result
for k, v in state_change.items()
for callback_result in se... | def set_state(self, updater=None, **kwargs) | Update the datastore.
:param func|dict updater: (state) => state_change or dict state_change
:rtype: Iterable[tornado.concurrent.Future] | 3.765321 | 3.451829 | 1.090819 |
if key_value_pairs is None:
key_value_pairs = kwargs
return [self.set(k, v)
for k, v in key_value_pairs.items()
if k not in self] | def init(self, key_value_pairs=None, **kwargs) | Initialize datastore.
Only sets values for keys that are not in the datastore already.
:param dict key_value_pairs:
A set of key value pairs to use to initialize the datastore.
:rtype: Iterable[tornado.concurrent.Future] | 2.679723 | 2.721815 | 0.984535 |
# remove callbacks
Datastore.stores[self.domain].remove(self)
# delete data after the last instance is gone
if self.release_storage and not Datastore.stores[self.domain]:
del Datastore.global_data[self.domain]
del self | def close(self) | Close and delete instance. | 10.616697 | 9.309967 | 1.140358 |
plots_dirpath = join(output_dir, 'plots')
individual_report_fpaths = [s.qualimap_html_fpath for s in samples]
if isdir(plots_dirpath) and not any(
not can_reuse(join(plots_dirpath, f), individual_report_fpaths)
for f in listdir(plots_dirpath) if not f.startswith('.')):
d... | def run_multisample_qualimap(output_dir, work_dir, samples, targqc_full_report) | 1. Generates Qualimap2 plots and put into plots_dirpath
2. Adds records to targqc_full_report.plots | 4.009731 | 3.850242 | 1.041423 |
r
km = (2 * np.pi * nm) / res
ri = nm * np.sqrt(f / km**2 + 1)
# Always take the positive root as the refractive index.
# Because f can be imaginary, numpy cannot return the correct
# positive root of f. However, we know that *ri* must be postive and
# thus we take the absolute value of ri.
... | def odt_to_ri(f, res, nm) | r"""Convert the ODT object function to refractive index
In :abbr:`ODT (Optical Diffraction Tomography)`, the object function
is defined by the Helmholtz equation
.. math::
f(\mathbf{r}) = k_\mathrm{m}^2 \left[
\left( \frac{n(\mathbf{r})}{n_\mathrm{m}} \right)^2 - 1
\righ... | 13.109139 | 11.620123 | 1.128141 |
r
ri = nm + f / (2 * np.pi) * res
return ri | def opt_to_ri(f, res, nm) | r"""Convert the OPT object function to refractive index
In :abbr:`OPT (Optical Projection Tomography)`, the object function
is computed from the raw phase data. This method converts phase data
to refractive index data.
.. math::
n(\mathbf{r}) = n_\mathrm{m} +
\frac{f(\mathbf{r}) ... | 16.763319 | 26.399416 | 0.634988 |
if expressions is None:
expressions = ['']
if isinstance(burn_values, (int, float)):
burn_values = [burn_values]
if len(expressions) != len(burn_values):
raise RuntimeError('expressions and burn_values of different length')
failed = []
for exp in expressions:
... | def rasterize(vectorobject, reference, outname=None, burn_values=1, expressions=None, nodata=0, append=False) | rasterize a vector object
Parameters
----------
vectorobject: Vector
the vector object to be rasterized
reference: Raster
a reference Raster object to retrieve geo information and extent from
outname: str or None
the name of the GeoTiff output file; if None, an in-memory obj... | 1.923721 | 1.997805 | 0.962917 |
if isinstance(rasterobject, str):
rasterobject = Raster(rasterobject)
if not isinstance(rasterobject, Raster):
raise RuntimeError('rasterobject must be of type Raster or str')
if isinstance(reference, (Raster, Vector)):
projection = reference.projection
if targetres is n... | def reproject(rasterobject, reference, outname, targetres=None, resampling='bilinear', format='GTiff') | reproject a raster file
Parameters
----------
rasterobject: Raster or str
the raster image to be reprojected
reference: Raster, Vector, str, int or osr.SpatialReference
either a projection string or a spatial object with an attribute 'projection'
outname: str
the name of the... | 2.328393 | 2.155846 | 1.080036 |
statcollect = []
for x in self.layers():
try:
stats = x.ComputeStatistics(approximate)
except RuntimeError:
stats = None
stats = dict(zip(['min', 'max', 'mean', 'sdev'], stats))
statcollect.append(stats)
ret... | def allstats(self, approximate=False) | Compute some basic raster statistics
Parameters
----------
approximate: bool
approximate statistics from overviews or a subset of all tiles?
Returns
-------
list of dicts
a list with a dictionary of statistics for each band. Keys: `min`, `max`, `... | 4.480914 | 3.659894 | 1.224329 |
if self.bands == 1:
return self.matrix()
else:
arr = self.raster.ReadAsArray().transpose(1, 2, 0)
if isinstance(self.nodata, list):
for i in range(0, self.bands):
arr[:, :, i][arr[:, :, i] == self.nodata[i]] = np.nan
... | def array(self) | read all raster bands into a numpy ndarray
Returns
-------
numpy.ndarray
the array containing all raster data | 2.70253 | 2.578717 | 1.048013 |
if not isinstance(names, list):
raise TypeError('the names to be set must be of type list')
if len(names) != self.bands:
raise ValueError(
'length mismatch of names to be set ({}) and number of bands ({})'.format(len(names), self.bands))
self.__ba... | def bandnames(self, names) | set the names of the raster bands
Parameters
----------
names: list of str
the names to be set; must be of same length as the number of bands
Returns
------- | 3.280927 | 3.114379 | 1.053477 |
if outname is None:
return bbox(self.geo, self.proj4)
else:
bbox(self.geo, self.proj4, outname=outname, format=format, overwrite=overwrite) | def bbox(self, outname=None, format='ESRI Shapefile', overwrite=True) | Parameters
----------
outname: str or None
the name of the file to write; If `None`, the bounding box is returned as vector object
format: str
The file format to write
overwrite: bool
overwrite an already existing file?
Returns
-------... | 2.775718 | 3.234741 | 0.858096 |
if not self.geo['xmin'] <= px <= self.geo['xmax']:
raise RuntimeError('px is out of bounds')
if not self.geo['ymin'] <= py <= self.geo['ymax']:
raise RuntimeError('py is out of bounds')
if nodata is None:
nodata = self.nodata
... | def extract(self, px, py, radius=1, nodata=None) | extract weighted average of pixels intersecting with a defined radius to a point.
Parameters
----------
px: int or float
the x coordinate in units of the Raster SRS
py: int or float
the y coordinate in units of the Raster SRS
radius: int or float
... | 2.320436 | 2.339964 | 0.991654 |
out = dict(zip(['xmin', 'xres', 'rotation_x', 'ymax', 'rotation_y', 'yres'],
self.raster.GetGeoTransform()))
# note: yres is negative!
out['xmax'] = out['xmin'] + out['xres'] * self.cols
out['ymin'] = out['ymax'] + out['yres'] * self.rows
... | def geo(self) | General image geo information.
Returns
-------
dict
a dictionary with keys `xmin`, `xmax`, `xres`, `rotation_x`, `ymin`, `ymax`, `yres`, `rotation_y` | 4.027359 | 3.567437 | 1.128922 |
for i in range(self.raster.RasterCount):
try:
checksum = self.raster.GetRasterBand(i + 1).Checksum()
except RuntimeError:
return False
return True | def is_valid(self) | Check image integrity.
Tries to compute the checksum for each raster layer and returns False if this fails.
See this forum entry:
`How to check if image is valid? <https://lists.osgeo.org/pipermail/gdal-dev/2013-November/037520.html>`_.
Returns
-------
bool
i... | 4.878992 | 3.148273 | 1.549736 |
for i in range(1, self.bands + 1):
self.__data[i - 1] = self.matrix(i) | def load(self) | load all raster data to internal memory arrays.
This shortens the read time of other methods like :meth:`matrix`. | 7.563069 | 4.483136 | 1.687004 |
mat = self.__data[band - 1]
if mat is None:
mat = self.raster.GetRasterBand(band).ReadAsArray()
if mask_nan:
if isinstance(self.nodata, list):
nodata = self.nodata[band - 1]
else:
nodata = s... | def matrix(self, band=1, mask_nan=True) | read a raster band (subset) into a numpy ndarray
Parameters
----------
band: int
the band to read the matrix from; 1-based indexing
mask_nan: bool
convert nodata values to :obj:`numpy.nan`? As :obj:`numpy.nan` requires at least float values, any integer array is ... | 2.215632 | 2.361388 | 0.938275 |
return (abs(float(self.geo['xres'])), abs(float(self.geo['yres']))) | def res(self) | the raster resolution in x and y direction
Returns
-------
tuple
(xres, yres) | 8.009834 | 6.116179 | 1.309614 |
if self.bands != 1:
raise ValueError('only single band images are currently supported')
# load array
mat = self.matrix()
# scale values
scaled = fun(mat)
# assign newly computed array to raster object
self.assign(sca... | def rescale(self, fun) | perform raster computations with custom functions and assign them to the existing raster object in memory
Parameters
----------
fun: function
the custom function to compute on the data
Examples
--------
>>> with Raster('filename') as ras:
>>> ras... | 9.375743 | 9.080552 | 1.032508 |
if os.path.isfile(outname) and not overwrite:
raise RuntimeError('target file already exists')
if format == 'GTiff' and not re.search(r'\.tif[f]*$', outname):
outname += '.tif'
dtype = Dtype(self.dtype if dtype == 'default' else dtype).... | def write(self, outname, dtype='default', format='ENVI', nodata='default', compress_tif=False, overwrite=False) | write the raster object to a file.
Parameters
----------
outname: str
the file to be written
dtype: str
the data type of the written file;
data type notations of GDAL (e.g. `Float32`) and numpy (e.g. `int8`) are supported.
format: str
... | 2.591933 | 2.608878 | 0.993505 |
if not hasattr(self, '__numpy2gdalint'):
tmap = {}
for group in ['int', 'uint', 'float', 'complex']:
for dtype in np.sctypes[group]:
code = gdal_array.NumericTypeCodeToGDALTypeCode(dtype)
if code is not None:
... | def numpy2gdalint(self) | create a dictionary for mapping numpy data types to GDAL data type codes
Returns
-------
dict
the type map | 3.67629 | 3.477102 | 1.057285 |
if static is None:
return
if isinstance(static, dict):
static = static.items()
for group in static:
if not isinstance(group, dict):
yield group
continue
for item in group.items():
yield it... | def static_parser(static) | Parse object describing static routes.
Might be a list, a dict or a list of dicts. | 3.595045 | 3.410774 | 1.054026 |
f_config = os.path.join(self.analyses_path, 'index.yaml')
tornado.autoreload.watch(f_config)
with io.open(f_config, 'r', encoding='utf8') as f:
config = yaml.safe_load(f)
self.info.update(config)
if self.debug:
self.info['version'] += '.debug-... | def analyses_info(self) | Add analyses from the analyses folder. | 3.397502 | 3.349262 | 1.014403 |
# concatenate some attributes to global lists:
aggregated = {'build': [], 'watch': []}
for attribute, values in aggregated.items():
for info in self.info['analyses'] + [self.info]:
if attribute in info:
values.append(info[attribute])
... | def register_metas(self) | register metas | 4.329686 | 4.276313 | 1.012481 |
for cmd in self.build_cmds:
log.info('building command: {}'.format(cmd))
full_cmd = 'cd {}; {}'.format(self.analyses_path, cmd)
log.debug('full command: {}'.format(full_cmd))
subprocess.call(full_cmd, shell=True)
log.info('build done') | def build(self) | Run the build command specified in index.yaml. | 3.419823 | 3.189525 | 1.072204 |
return self.render(
'index.html',
databench_version=DATABENCH_VERSION,
meta_infos=self.meta_infos(),
**self.info
) | def get(self) | Render the List-of-Analyses overview page. | 8.686934 | 6.584942 | 1.319212 |
' Reset Axis and set default parameters for H-bridge '
spi.SPI_write_byte(self.CS, 0xC0) # reset
# spi.SPI_write_byte(self.CS, 0x14) # Stall Treshold setup
# spi.SPI_write_byte(self.CS, 0xFF)
# spi.SPI_write_byte(self.CS, 0x13) # Over Current Treshold setup
# ... | def Reset(self) | Reset Axis and set default parameters for H-bridge | 2.151048 | 2.033713 | 1.057695 |
# Using a dictionary is not strictly necessary. You can also
# use global variables.
mprotate_dict["X"] = X
mprotate_dict["X_shape"] = X_shape
mprotate_dict["X_dtype"] = X_dtype | def _init_worker(X, X_shape, X_dtype) | Initializer for pool for _mprotate | 5.512753 | 4.586375 | 1.201985 |
targ_args = list()
slsize = np.int(np.floor(lny / ncores))
for t in range(ncores):
ymin = t * slsize
ymax = (t + 1) * slsize
if t == ncores - 1:
ymax = lny
targ_args.append((ymin, ymax, ang, order))
pool.map(_rotate, targ_args) | def _mprotate(ang, lny, pool, order) | Uses multiprocessing to wrap around _rotate
4x speedup on an intel i7-3820 CPU @ 3.60GHz with 8 cores.
The function calls _rotate which accesses the `mprotate_dict`.
Data is rotated in-place.
Parameters
----------
ang: float
rotation angle in degrees
lny: int
total number ... | 3.470879 | 3.705581 | 0.936663 |
# copy and modulo np.pi
# This is an array with values in [0, np.pi)
angles = (angles.flatten() - angles.min()) % (np.pi)
# sort the array
sortargs = np.argsort(angles)
sortangl = angles[sortargs]
# compute weights for sorted angles
da = (np.roll(sortangl, -1) - np.roll(sortangl, 1)... | def compute_angle_weights_1d(angles) | Compute the weight for each angle according to the distance between its
neighbors.
Parameters
----------
angles: 1d ndarray of length A
Angles in radians
Returns
-------
weights: 1d ndarray of length A
The weights for each angle
Notes
-----
To compute the weights,... | 4.765389 | 4.550783 | 1.047158 |
Device.initialize(self)
for child in iter(self.children.values()):
child.initialize() | def initialize(self) | See :meth:`pymlab.sensors.Device.initialize` for more information.
Calls `initialize()` on all devices connected to the bus. | 6.216535 | 6.982704 | 0.890276 |
LOGGER.debug("Writing byte %s to device %s!", bin(value), hex(address))
return self.driver.write_byte(address, value) | def write_byte(self, address, value) | Writes the byte to unaddressed register in a device. | 6.359728 | 5.739902 | 1.107985 |
LOGGER.debug("Reading byte from device %s!", hex(address))
return self.driver.read_byte(address) | def read_byte(self, address) | Reads unadressed byte from a device. | 7.881412 | 7.112104 | 1.108169 |
LOGGER.debug("Writing byte data %s to register %s on device %s",
bin(value), hex(register), hex(address))
return self.driver.write_byte_data(address, register, value) | def write_byte_data(self, address, register, value) | Write a byte value to a device's register. | 3.958703 | 3.963178 | 0.998871 |
warnings.warn("write_wdata() is deprecated and will be removed in future versions replace with write_word_data()", DeprecationWarning)
LOGGER.debug("Writing word data %s to register %s on device %s",
bin(value), hex(register), hex(address))
return self.driver.write_word_data... | def write_wdata(self, address, register, value) | Write a word (two bytes) value to a device's register. | 4.502042 | 4.267744 | 1.0549 |
try:
response.raise_for_status()
except aiohttp.ClientResponseError as exc:
reason = response.reason
spacetrack_error_msg = None
try:
json = await response.json()
if isinstance(json, Mapping):
spacetrack_error_msg = json['error']
... | async def _raise_for_status(response) | Raise an appropriate error for a given response.
Arguments:
response (:py:class:`aiohttp.ClientResponse`): The API response.
Raises:
:py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate
error for the response's status.
This function was taken from the aslack project and m... | 3.392078 | 3.392432 | 0.999895 |
await self.authenticate()
url = ('{0}{1}/modeldef/class/{2}'
.format(self.base_url, controller, class_))
resp = await self._ratelimited_get(url)
await _raise_for_status(resp)
resp_json = await resp.json()
return resp_json['data'] | async def _download_predicate_data(self, class_, controller) | Get raw predicate information for given request class, and cache for
subsequent calls. | 5.023399 | 4.821483 | 1.041879 |
num_chars = ['.', '+', '-']
number = ''
for c in string_value:
if c.isdigit() or c in num_chars:
number += c
return number | def get_numeric_value(string_value) | parses string_value and returns only number-like part | 4.421899 | 3.53083 | 1.252368 |
kwargs.update({
'analysis': analysis,
'path': path,
'name': name,
'info': info,
})
main(**kwargs) | def run(analysis, path=None, name=None, info=None, **kwargs) | Run a single analysis.
:param Analysis analysis: Analysis class to run.
:param str path: Path of analysis. Can be `__file__`.
:param str name: Name of the analysis.
:param dict info: Optional entries are ``version``, ``title``,
``readme``, ...
:param dict static: Map[url regex, root-folder]... | 2.897274 | 5.122572 | 0.56559 |
if isinstance(value, bool):
return str(value).lower()
elif isinstance(value, Sequence) and not isinstance(value, six.string_types):
return ','.join(_stringify_predicate_value(x) for x in value)
elif isinstance(value, datetime.datetime):
return value.isoformat(sep=' ')
elif i... | def _stringify_predicate_value(value) | Convert Python objects to Space-Track compatible strings
- Booleans (``True`` -> ``'true'``)
- Sequences (``[25544, 34602]`` -> ``'25544,34602'``)
- dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)
- ``None`` -> ``'null-val'`` | 2.038641 | 1.704363 | 1.196131 |
items = [repr(a) for a in args]
items += ["%s = %r" % (k, v) for k, v in iter(kwargs.items())]
return ", ".join(items) | def args_repr(*args, **kwargs) | Returns human-readable string representation of both positional and
keyword arguments passed to the function.
This function uses the built-in :func:`repr()` function to convert
individual arguments to string.
>>> args_repr("a", (1, 2), some_keyword = list("abc"))
"'a', (1, 2), some_keyword = ['a',... | 2.751828 | 3.117176 | 0.882795 |
cls_name = type(obj).__name__
return "%s(%s)" % (cls_name, args_repr(*args, **kwargs), ) | def obj_repr(obj, *args, **kwargs) | Returns human-readable string representation of an object given that it has
been created by calling constructor with the specified positional and
keyword arguments.
This is a convenience function to help implement custom `__repr__()`
methods. For example:
>>> class Animal(object):
... def _... | 3.520177 | 4.81904 | 0.730473 |
if text is not None:
text = text.decode(encoding, errors='ignore')
printable = set(string.printable)
text = filter(lambda x: x in printable, text)
return ''.join(list(text))
else:
return None | def decode_filter(text, encoding='utf-8') | decode a binary object to str and filter out non-printable characters
Parameters
----------
text: bytes
the binary object to be decoded
encoding: str
the encoding to be used
Returns
-------
str
the decoded and filtered string | 2.769494 | 3.128008 | 0.885386 |
z = x.copy()
z.update(y)
return z | def dictmerge(x, y) | merge two dictionaries | 2.972135 | 3.306846 | 0.898783 |
out = []
for i in inlist:
i = list(i) if isinstance(i, tuple) else i
out.extend(dissolve(i)) if isinstance(i, list) else out.append(i)
return out | def dissolve(inlist) | list and tuple flattening
Parameters
----------
inlist: list
the list with sub-lists or tuples to be flattened
Returns
-------
list
the flattened result
Examples
--------
>>> dissolve([[1, 2], [3, 4]])
[1, 2, 3, 4]
>>> dissolve([(1, 2, (3, ... | 2.692865 | 2.850223 | 0.944791 |
if foldermode not in [0, 1, 2]:
raise ValueError("'foldermode' must be either 0, 1 or 2")
# match patterns
if isinstance(target, str):
pattern = r'|'.join(matchlist if regex else [fnmatch.translate(x) for x in matchlist])
if os.path.isdir(target):
... | def finder(target, matchlist, foldermode=0, regex=False, recursive=True) | function for finding files/folders in folders and their subdirectories
Parameters
----------
target: str or list of str
a directory, zip- or tar-archive or a list of them to be searched
matchlist: list
a list of search patterns
foldermode: int
* 0: only files
* 1: fi... | 1.886436 | 1.87971 | 1.003578 |
if isinstance(x, list):
return [parse_literal(y) for y in x]
elif isinstance(x, (bytes, str)):
try:
return int(x)
except ValueError:
try:
return float(x)
except ValueError:
return x
else:
raise TypeError... | def parse_literal(x) | return the smallest possible data type for a string or list of strings
Parameters
----------
x: str or list
a string to be parsed
Returns
-------
int, float or str
the parsing result
Examples
--------
>>> isinstance(parse_literal('1.5'), float)
True
... | 2.284694 | 2.471384 | 0.924459 |
OldMax = max(inlist)
OldMin = min(inlist)
if OldMin == OldMax:
raise RuntimeError('list contains of only one unique value')
OldRange = OldMax - OldMin
NewRange = newrange[1] - newrange[0]
result = [(((float(x) - OldMin) * NewRange) / OldRange) + newrange[0] for x in inlist... | def rescale(inlist, newrange=(0, 1)) | rescale the values in a list between the values in newrange (a tuple with the new minimum and maximum) | 2.57109 | 2.500899 | 1.028066 |
cmd = [str(x) for x in dissolve(cmd)]
if outdir is None:
outdir = os.getcwd()
log = sp.PIPE if logfile is None else open(logfile, 'a')
proc = sp.Popen(cmd, stdin=sp.PIPE, stdout=log, stderr=sp.PIPE, cwd=outdir, env=env)
instream = None if inlist is None \
else ''.join([str(x) + ... | def run(cmd, outdir=None, logfile=None, inlist=None, void=True, errorpass=False, env=None) | | wrapper for subprocess execution including logfile writing and command prompt piping
| this is a convenience wrapper around the :mod:`subprocess` module and calls
its class :class:`~subprocess.Popen` internally.
Parameters
----------
cmd: list
the command arguments
outdir: str
... | 3.026914 | 3.086619 | 0.980657 |
address_parse = urlparse(url)
return urlunparse(address_parse._replace(query=urlencode(querydict))) | def urlQueryParser(url, querydict) | parse a url query | 3.998081 | 4.41884 | 0.904781 |
if isinstance(x, list):
for item in x:
self.stack.append(item)
else:
self.stack.append(x) | def push(self, x) | append items to the stack; input can be a single value or a list | 2.498833 | 1.944373 | 1.285161 |
if not self.empty():
val = self.stack[-1]
del self.stack[-1]
return val | def pop(self) | return the last stack element and delete it from the list | 3.536644 | 2.720644 | 1.299929 |
reg, self._scale = self.SCALES[self._gauss]
x = self.bus.read_int16_data(self.address, self.HMC5883L_DXRA)
if x == -4096: x = OVERFLOW
y = self.bus.read_int16_data(self.address, self.HMC5883L_DYRA)
if y == -4096: y = OVERFLOW
z = self.bus.read_int16_data(self.ad... | def axes(self, offset = False) | returns measured value in miligauss | 3.126365 | 2.863641 | 1.091745 |
# Some cross-language values for primitives. This is tested in
# jsontemplate_test.py.
if x is None:
return 'null'
if isinstance(x, six.string_types):
return x
return pprint.pformat(x) | def _ToString(x) | The default default formatter!. | 7.756447 | 7.689049 | 1.008766 |
keys = sorted(data)
return [{'@key': k, '@value': data[k]} for k in keys] | def _Pairs(data) | dictionary -> list of pairs | 5.548721 | 4.976585 | 1.114966 |
if len(args) == 0:
s, p = '', 's'
elif len(args) == 1:
s, p = '', args[0]
elif len(args) == 2:
s, p = args
else:
# Should have been checked at compile time
raise AssertionError
if value > 1:
return p
else:
return s | def _Pluralize(value, unused_context, args) | Formatter to pluralize words. | 2.893903 | 2.745063 | 1.054221 |
time_tuple = time.gmtime(value)
return _StrftimeHelper(args, time_tuple) | def _StrftimeGm(value, unused_context, args) | Convert a timestamp in seconds to a string based on the format string.
Returns GM time. | 5.491466 | 7.490142 | 0.733159 |
time_tuple = time.localtime(value)
return _StrftimeHelper(args, time_tuple) | def _StrftimeLocal(value, unused_context, args) | Convert a timestamp in seconds to a string based on the format string.
Returns local time. | 5.294186 | 7.182052 | 0.737141 |
try:
name = args[0]
except IndexError:
raise EvaluationError('The "template" predicate requires an argument.')
return context.HasTemplate(name) | def _TemplateExists(unused_value, context, args) | Returns whether the given name is in the current Template's template group. | 6.2857 | 5.778625 | 1.08775 |
n = len(meta)
if n % 2 == 1:
raise ConfigurationError(
'%r has an odd number of metacharacters' % meta)
return meta[:n // 2], meta[n // 2:] | def SplitMeta(meta) | Split and validate metacharacters.
Example: '{}' -> ('{', '}')
This is public so the syntax highlighter and other tools can use it. | 3.840175 | 3.5229 | 1.090061 |
key = meta_left, meta_right
if key not in _token_re_cache:
# - Need () grouping for re.split
# - The first character must be a non-space. This allows us to ignore
# literals like function() { return 1; } when
# - There must be at least one (non-space) character inside {}
... | def MakeTokenRegex(meta_left, meta_right) | Return a (compiled) regular expression for tokenization.
Args:
meta_left, meta_right: e.g. '{' and '}'
- The regular expressions are memoized.
- This function is public so the syntax highlighter can use it. | 4.756761 | 4.752818 | 1.00083 |
# Tokens below must start with '.'
if token.startswith('.'):
token = token[1:]
else:
return None, None
if token == 'end':
return END_TOKEN, None
if token == 'alternates with':
return ALTERNATES_TOKEN, token
if token.startswith('or'):
if... | def _MatchDirective(token) | Helper function for matching certain directives. | 2.991111 | 3.016637 | 0.991538 |
trimlen = len(meta_left)
token_re = MakeTokenRegex(meta_left, meta_right)
do_strip = (whitespace == 'strip-line') # Do this outside loop
do_strip_part = False
for line in template_str.splitlines(True): # retain newlines
if do_strip or do_strip_part:
line = line.s... | def _Tokenize(template_str, meta_left, meta_right, whitespace) | Yields tokens, which are 2-tuples (TOKEN_TYPE, token_string). | 3.637821 | 3.60746 | 1.008416 |
f = StringIO.StringIO(s)
return FromFile(f, **kwargs) | def FromString(s, **kwargs) | Like FromFile, but takes a string. | 5.051983 | 3.750318 | 1.347081 |
_constructor = _constructor or Template
options = {}
# Parse lines until the first one that doesn't look like an option
while 1:
line = f.readline()
match = _OPTION_RE.match(line)
if match:
name, value = match.group(1), match.group(2)
... | def FromFile(f, more_formatters=lambda x: None, more_predicates=lambda x: None,
_constructor=None) | Parse a template from a file, using a simple file format.
This is useful when you want to include template options in a data file,
rather than in the source code.
The format is similar to HTTP or E-mail headers. The first lines of the file
can specify template options, such as the metacharacters to use. One... | 4.352797 | 4.212609 | 1.033278 |
group = {}
for statement in root_section.Statements():
if isinstance(statement, six.string_types):
continue
func, args = statement
# here the function acts as ID for the block type
if func is _DoDef and isinstance(args, _Section):
section = args
... | def _MakeGroupFromRootSection(root_section, undefined_str) | Construct a dictinary { template name -> Template() instance }
Args:
root_section: _Section instance -- root of the original parse tree | 9.818112 | 8.926084 | 1.099935 |
try:
return ''.join(tokens)
except UnicodeDecodeError:
# This can still raise UnicodeDecodeError if that data isn't utf-8.
return ''.join(t.decode('utf-8') for t in tokens) | def JoinTokens(tokens) | Join tokens (which may be a mix of unicode and str values).
See notes on unicode at the top. This function allows mixing encoded utf-8
byte string tokens with unicode tokens. (Python's default encoding is ASCII,
and we don't want to change that.)
We also want to support pure byte strings, so we can't get ri... | 4.460908 | 5.064925 | 0.880745 |
block = args
items = context.PushSection(block.section_name, block.pre_formatters)
if items:
if not isinstance(items, list):
raise EvaluationError('Expected a list; got %s' % type(items))
last_index = len(items) - 1
statements = block.Statements()
... | def _DoRepeatedSection(args, context, callback, trace) | {.repeated section foo} | 5.221817 | 5.451462 | 0.957875 |
block = args
# If a section present and "true", push the dictionary onto the stack as the
# new context, and show it
if context.PushSection(block.section_name, block.pre_formatters):
_Execute(block.Statements(), context, callback, trace)
context.Pop()
else: # missing or "false"... | def _DoSection(args, context, callback, trace) | {.section foo} | 11.342546 | 12.212712 | 0.928749 |
block = args
value = context.Lookup('@')
for (predicate, args, func_type), statements in block.clauses:
if func_type == ENHANCED_FUNC:
do_clause = predicate(value, context, args)
else:
do_clause = predicate(value)
if do_clause:
if tra... | def _DoPredicates(args, context, callback, trace) | {.predicate?}
Here we execute the first clause that evaluates to true, and then stop. | 5.63473 | 6.297456 | 0.894763 |
name, formatters = args
if name is None:
value = context.Root() # don't use the cursor
else:
try:
value = context.Lookup(name)
except TypeError as e:
raise EvaluationError(
'Error evaluating %r in context %r: %r' % (name, context, e)... | def _DoSubstitute(args, context, callback, trace) | Variable substitution, i.e. {foo}
We also implement template formatters here, i.e. {foo|template bar} as well
as {.template FOO} for templates that operate on the root of the data dict
rather than a subtree. | 5.220484 | 5.229506 | 0.998275 |
# Every time we call _Execute, increase this depth
if trace:
trace.exec_depth += 1
for i, statement in enumerate(statements):
if isinstance(statement, six.string_types):
callback(statement)
else:
# In the case of a substitution, args is a pair (name, form... | def _Execute(statements, context, callback, trace) | Execute a bunch of template statements in a ScopedContext.
Args:
callback: Strings are "written" to this callback function.
trace: Trace object, or None
This is called in a mutually recursive fashion. | 6.029408 | 5.983787 | 1.007624 |
t = Template(template_str, **kwargs)
return t.expand(dictionary) | def expand(template_str, dictionary, **kwargs) | Free function to expands a template string with a data dictionary.
This is useful for cases where you don't care about saving the result of
compilation (similar to re.match('.*', s) vs DOT_STAR.match(s)) | 3.613772 | 5.003092 | 0.722308 |
for t in tokens:
if isinstance(t, six.string_types):
callback(t)
else:
_FlattenToCallback(t, callback) | def _FlattenToCallback(tokens, callback) | Takes a nested list structure and flattens it.
['a', ['b', 'c']] -> callback('a'); callback('b'); callback('c'); | 2.073264 | 2.709738 | 0.765116 |
try:
body_data = data[body_subtree]
except KeyError:
raise EvaluationError('Data dictionary has no subtree %r' % body_subtree)
tokens_body = []
template.execute(body_data, tokens_body.append)
data[body_subtree] = tokens_body
tokens = []
style.execute(data, tokens.append)... | def execute_with_style_LEGACY(template, style, data, callback, body_subtree='body') | OBSOLETE old API. | 4.726099 | 4.628937 | 1.02099 |
if template.has_defines:
return template.expand(data, style=style)
else:
tokens = []
execute_with_style_LEGACY(template, style, data, tokens.append,
body_subtree=body_subtree)
return JoinTokens(tokens) | def expand_with_style(template, style, data, body_subtree='body') | Expand a data dictionary with a template AND a style.
DEPRECATED -- Remove this entire function in favor of expand(d, style=style)
A style is a Template instance that factors out the common strings in several
"body" templates.
Args:
template: Template instance for the inner "page content"
style: Temp... | 6.605961 | 9.165355 | 0.720753 |
prefix = 'template '
ref = None # fail the lookup by default
if user_str.startswith(prefix):
name = user_str[len(prefix):]
if name == 'SELF':
# we can resolve this right away
ref = _TemplateRef(template=self.owner) # special valu... | def LookupWithType(self, user_str) | Returns:
ref: Either a template instance (itself) or _TemplateRef | 10.11159 | 8.514377 | 1.18759 |
formatter, args, func_type = self.formatters.LookupWithType(format_str)
if formatter:
return formatter, args, func_type
else:
raise BadFormatter('%r is not a valid formatter' % format_str) | def _GetFormatter(self, format_str) | The user's formatters are consulted first, then the default formatters. | 5.290827 | 4.744035 | 1.115259 |
predicate, args, func_type = self.predicates.LookupWithType(pred_str)
if predicate:
pred = predicate, args, func_type
else:
# Nicer syntax, {.debug?} is shorthand for {.if test debug}.
# Currently there is not if/elif chain; just use
# {.i... | def _GetPredicate(self, pred_str, test_attr=False) | The user's predicates are consulted first, then the default predicates. | 10.962292 | 10.747262 | 1.020008 |
pre_formatters = [self._GetFormatter(f) for f in pre_formatters]
# TODO: Consider getting rid of this dispatching, and turn _Do* into methods
if token_type == REPEATED_SECTION_TOKEN:
new_block = _RepeatedSection(section_name, pre_formatters)
func = _DoRe... | def NewSection(self, token_type, section_name, pre_formatters) | For sections or repeated sections. | 3.261928 | 3.056439 | 1.067232 |
if pred_str:
pred = self._GetPredicate(pred_str, test_attr=False)
else:
pred = None
self.current_section.NewOrClause(pred) | def NewOrClause(self, pred_str) | {.or ...} Can appear inside predicate blocks or section blocks, with
slightly different meaning. | 5.335613 | 5.057838 | 1.05492 |
pred = self._GetPredicate(pred_str, test_attr=test_attr)
block = _PredicateSection()
block.NewOrClause(pred)
self._NewSection(_DoPredicates, block) | def NewPredicateSection(self, pred_str, test_attr=False) | For chains of predicate clauses. | 9.798177 | 9.00961 | 1.087525 |
if name == '@':
value = self.stack[-1].context
else:
value = self.stack[-1].context.get(name)
# Apply pre-formatters
for i, (f, args, formatter_type) in enumerate(pre_formatters):
if formatter_type == ENHANCED_FUNC:
va... | def PushSection(self, name, pre_formatters) | Given a section name, push it on the top of the stack.
Returns:
The new section, or None if there is no such section. | 3.673743 | 3.672635 | 1.000302 |
stacktop = self.stack[-1]
# Now we're iterating -- push a new mutable object onto the stack
if stacktop.index == -1:
stacktop = _Frame(None, index=0)
self.stack.append(stacktop)
context_array = self.stack[-2].context
if ... | def Next(self) | Advance to the next item in a repeated section.
Raises:
StopIteration if there are no more elements | 5.108389 | 5.558584 | 0.919009 |
i = len(self.stack) - 1
while 1:
frame = self.stack[i]
if name == '@index':
if frame.index != -1: # -1 is undefined
return frame.index # @index is 1-based
else:
context = frame.context
if h... | def _LookUpStack(self, name) | Look up the stack for the given name. | 5.186105 | 5.097429 | 1.017396 |
if name == '@':
return self.stack[-1].context
parts = name.split('.')
value = self._LookUpStack(parts[0])
# Now do simple lookups of the rest of the parts
for part in parts[1:]:
try:
value = value[part]
... | def Lookup(self, name) | Get the value associated with a name in the current context.
The current context could be an dictionary in a list, or a dictionary
outside a list.
Args:
name: name to lookup, e.g. 'foo' or 'foo.bar.baz'
Returns:
The value, or self.undefined_str
Raises:
UndefinedVariable if self... | 5.321313 | 5.698227 | 0.933854 |
# First try the passed in version, then the one set by _SetTemplateGroup. May
# be None. Only one of these should be set.
group = group or self.group
context = _ScopedContext(data_dict, self.undefined_str, group=group)
_Execute(self._program.Statements(), context, call... | def execute(self, data_dict, callback, group=None, trace=None) | Low level method to expand the template piece by piece.
Args:
data_dict: The JSON data dictionary.
callback: A callback which should be called with each expanded token.
group: Dictionary of name -> Template instance (for styles)
Example: You can pass 'f.write' as the callback to write direct... | 14.117752 | 15.907851 | 0.887471 |
if args:
if len(args) == 1:
data_dict = args[0]
trace = kwargs.get('trace')
style = kwargs.get('style')
else:
raise TypeError(
'expand() only takes 1 positional argument (got %s)' % args)
... | def expand(self, *args, **kwargs) | Expands the template with the given data dictionary, returning a string.
This is a small wrapper around execute(), and is the most convenient
interface.
Args:
data_dict: The JSON data dictionary. Like the builtin dict() constructor,
it can take a single dictionary as a positional argument... | 6.841718 | 5.933526 | 1.153061 |
tokens = []
self.execute(data_dict, tokens.append)
for token in tokens:
yield token | def tokenstream(self, data_dict) | Yields a list of tokens resulting from expansion.
This may be useful for WSGI apps. NOTE: In the current implementation, the
entire expanded template must be stored memory.
NOTE: This is a generator, but JavaScript doesn't have generators. | 5.980173 | 4.844305 | 1.234475 |
samples = []
if len(sino.shape) == 2:
# 2D
# take 1D samples at beginning and end of array
samples.append(sino[:, 0])
samples.append(sino[:, 1])
samples.append(sino[:, 2])
samples.append(sino[:, -1])
samples.append(sino[:, -2])
elif len(sino.shap... | def align_unwrapped(sino) | Align an unwrapped phase array to zero-phase
All operations are performed in-place. | 3.059851 | 3.091763 | 0.989678 |
q, r = divmod(a, b)
# make sure r is close to zero
sr = np.sign(r)
if np.abs(r) > b/2:
q += sr
r -= b * sr
return q, r | def divmod_neg(a, b) | Return divmod with closest result to zero | 4.321691 | 4.179881 | 1.033927 |
r
ndims = len(uSin.shape)
if ndims == 2:
# unwrapping is very important
phiR = np.unwrap(np.angle(uSin), axis=-1)
else:
# Unwrap gets the dimension of the problem from the input
# data. Since we have a sinogram, we need to pass it the
# slices one by one.
... | def sinogram_as_radon(uSin, align=True) | r"""Compute the phase from a complex wave field sinogram
This step is essential when using the ray approximation before
computation of the refractive index with the inverse Radon
transform.
Parameters
----------
uSin: 2d or 3d complex ndarray
The background-corrected sinogram of the co... | 5.588118 | 6.892612 | 0.81074 |
r
ndims = len(uSin.shape)
# imaginary part of the complex Rytov phase
phiR = np.angle(uSin / u0)
# real part of the complex Rytov phase
lna = np.log(np.absolute(uSin / u0))
if ndims == 2:
# unwrapping is very important
phiR[:] = np.unwrap(phiR, axis=-1)
else:
#... | def sinogram_as_rytov(uSin, u0=1, align=True) | r"""Convert the complex wave field sinogram to the Rytov phase
This method applies the Rytov approximation to the
recorded complex wave sinogram. To achieve this, the following
filter is applied:
.. math::
u_\mathrm{B}(\mathbf{r}) = u_\mathrm{0}(\mathbf{r})
\ln\!\left(
... | 6.383549 | 7.019726 | 0.909373 |
if np is not None and hasattr(obj, 'size') and hasattr(obj, 'dtype'):
if obj.size == 1:
if np.issubdtype(obj.dtype, np.integer):
return int(obj)
elif np.issubdtype(obj.dtype, np.floating):
return float(obj)
if isinstance(obj, set):
re... | def json_encoder_default(obj) | Handle more data types than the default JSON encoder.
Specifically, it treats a `set` and a `numpy.array` like a `list`.
Example usage: ``json.dumps(obj, default=json_encoder_default)`` | 2.73033 | 2.789718 | 0.978712 |
if image_format == 'png':
f = io.BytesIO()
figure.savefig(f, format=image_format, dpi=dpi)
f.seek(0)
return png_to_src(f.read())
elif image_format == 'svg':
f = io.StringIO()
figure.savefig(f, format=image_format, dpi=dpi)
f.seek(0)
return sv... | def fig_to_src(figure, image_format='png', dpi=80) | Convert a matplotlib figure to an inline HTML image.
:param matplotlib.figure.Figure figure: Figure to display.
:param str image_format: png (default) or svg
:param int dpi: dots-per-inch for raster graphics.
:rtype: str | 1.681082 | 1.767514 | 0.9511 |
' Reset Axis and set default parameters for H-bridge '
spi.SPI_write(self.CS, [0xC0, 0x60]) # reset
# spi.SPI_write(self.CS, [0x14, 0x14]) # Stall Treshold setup
# spi.SPI_write(self.CS, [0xFF, 0xFF])
# spi.SPI_write(self.CS, [0x13, 0x13]) # Over Current Treshold se... | def Reset(self) | Reset Axis and set default parameters for H-bridge | 2.070942 | 1.964035 | 1.054433 |
' Setup of maximum speed '
spi.SPI_write(self.CS, [0x07, 0x07]) # Max Speed setup
spi.SPI_write(self.CS, [0x00, 0x00])
spi.SPI_write(self.CS, [speed, speed]) | def MaxSpeed(self, speed) | Setup of maximum speed | 5.421322 | 5.050744 | 1.073371 |
' Go away from Limit Switch '
while self.ReadStatusBit(2) == 1: # is Limit Switch ON ?
spi.SPI_write(self.CS, [0x92, 0x92] | (~self.Dir & 1)) # release SW
while self.IsBusy():
pass
self.MoveWait(10) | def ReleaseSW(self) | Go away from Limit Switch | 19.409657 | 13.83429 | 1.403011 |
' Move some distance units from current position '
steps = units * self.SPU # translate units to steps
if steps > 0: # look for direction
spi.SPI_write(self.CS, [0x40 | (~self.Dir & 1), 0x40 | (~self.Dir & 1)])
else:
... | def Move(self, units) | Move some distance units from current position | 3.126061 | 3.008705 | 1.039005 |
srs = crsConvert(crs, 'osr')
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(coordinates['xmin'], coordinates['ymin'])
ring.AddPoint(coordinates['xmin'], coordinates['ymax'])
ring.AddPoint(coordinates['xmax'], coordinates['ymax'])
ring.AddPoint(coordinates['xmax'], coordinate... | def bbox(coordinates, crs, outname=None, format='ESRI Shapefile', overwrite=True) | create a bounding box vector object or shapefile from coordinates and coordinate reference system.
The CRS can be in either WKT, EPSG or PROJ4 format
Parameters
----------
coordinates: dict
a dictionary containing numerical variables with keys `xmin`, `xmax`, `ymin` and `ymax`
crs: int,... | 2.4256 | 2.367055 | 1.024733 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.