_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q274800 | CAM.flush | test | def flush(self):
"""Flush incomming socket messages."""
debug('flushing incomming socket messages')
try:
while True:
| python | {
"resource": ""
} |
q274801 | CAM.enable | test | def enable(self, slide=0, wellx=1, welly=1, fieldx=1, fieldy=1):
"""Enable a given scan field."""
# pylint: disable=too-many-arguments
cmd = [
('cmd', 'enable'),
('slide', str(slide)),
('wellx', str(wellx)),
| python | {
"resource": ""
} |
q274802 | CAM.save_template | test | def save_template(self, filename="{ScanningTemplate}leicacam.xml"):
"""Save scanning template to filename."""
cmd = [
('sys', '0'),
| python | {
"resource": ""
} |
q274803 | CAM.load_template | test | def load_template(self, filename="{ScanningTemplate}leicacam.xml"):
"""Load scanning template from filename.
Template needs to exist in database, otherwise it will not load.
Parameters
----------
filename : str
Filename to template to load. Filename may contain path also, in
such case, the basename will be used. '.xml' will be stripped
from the filename if it exists because of a bug; LASAF implicit
add '.xml'. If '{ScanningTemplate}' is omitted, it will be added.
Returns
-------
collections.OrderedDict
| python | {
"resource": ""
} |
q274804 | CAM.get_information | test | def get_information(self, about='stage'):
"""Get information about given keyword. Defaults to stage."""
cmd = [
('cmd', 'getinfo'),
| python | {
"resource": ""
} |
q274805 | incfile | test | def incfile(fname, fpointer, lrange="1,6-", sdir=None):
r"""
Include a Python source file in a docstring formatted in reStructuredText.
:param fname: File name, relative to environment variable
:bash:`${TRACER_DIR}`
:type fname: string
:param fpointer: Output function pointer. Normally is :code:`cog.out` but
:code:`print` or other functions can be used for
debugging
:type fpointer: function object
:param lrange: Line range to include, similar to Sphinx
`literalinclude <http://sphinx-doc.org/markup/code.html
#directive-literalinclude>`_ directive
:type lrange: string
:param sdir: Source file directory. If None the :bash:`${TRACER_DIR}`
environment variable is used if it is defined, otherwise
the directory where the :code:`docs.support.incfile` module
is located is used
:type sdir: string
For example:
.. code-block:: python
def func():
\"\"\"
This is a docstring. This file shows how to use it:
.. =[=cog
.. import docs.support.incfile
.. docs.support.incfile.incfile('func_example.py', cog.out)
.. =]=
.. code-block:: python
# func_example.py
if __name__ == '__main__':
func()
.. =[=end=]=
\"\"\"
return 'This is func output'
"""
# Read file
file_dir = (
sdir
if sdir
else os.environ.get("TRACER_DIR", os.path.abspath(os.path.dirname(__file__)))
)
| python | {
"resource": ""
} |
q274806 | locate_package_json | test | def locate_package_json():
"""
Find and return the location of package.json.
"""
directory = settings.SYSTEMJS_PACKAGE_JSON_DIR
if not directory:
raise ImproperlyConfigured(
"Could not locate 'package.json'. Set SYSTEMJS_PACKAGE_JSON_DIR "
"to the directory that holds 'package.json'."
)
| python | {
"resource": ""
} |
q274807 | parse_package_json | test | def parse_package_json():
"""
Extract the JSPM configuration from package.json.
"""
| python | {
"resource": ""
} |
q274808 | _handle_api_error_with_json | test | def _handle_api_error_with_json(http_exc, jsondata, response):
"""Handle YOURLS API errors.
requests' raise_for_status doesn't show the user the YOURLS json response,
so we parse that here and raise nicer exceptions.
"""
if 'code' in jsondata and 'message' in jsondata:
code = jsondata['code']
| python | {
"resource": ""
} |
q274809 | _validate_yourls_response | test | def _validate_yourls_response(response, data):
"""Validate response from YOURLS server."""
try:
response.raise_for_status()
except HTTPError as http_exc:
# Collect full HTTPError information so we can reraise later if required.
http_error_info = sys.exc_info()
# We will reraise outside of try..except block to prevent exception
# chaining showing wrong traceback when we try and parse JSON response.
reraise = False
try:
jsondata = response.json()
except ValueError:
reraise = True
else:
logger.debug('Received error {response} with JSON {json}',
response=response, json=jsondata)
_handle_api_error_with_json(http_exc, jsondata, response)
if reraise:
six.reraise(*http_error_info)
else:
# We have a valid HTTP response, but we need to check what the API says
# about the request.
jsondata = response.json()
logger.debug('Received {response} with JSON {json}', response=response,
json=jsondata)
if {'status', 'code', 'message'} <= set(jsondata.keys()):
status = jsondata['status']
| python | {
"resource": ""
} |
q274810 | _homogenize_waves | test | def _homogenize_waves(wave_a, wave_b):
"""
Generate combined independent variable vector.
The combination is from two waveforms and the (possibly interpolated)
dependent variable vectors of these two waveforms
"""
indep_vector = _get_indep_vector(wave_a, | python | {
"resource": ""
} |
q274811 | _interp_dep_vector | test | def _interp_dep_vector(wave, indep_vector):
"""Create new dependent variable vector."""
dep_vector_is_int = wave.dep_vector.dtype.name.startswith("int")
dep_vector_is_complex = wave.dep_vector.dtype.name.startswith("complex")
if (wave.interp, wave.indep_scale) == ("CONTINUOUS", "LOG"):
wave_interp_func = scipy.interpolate.interp1d(
np.log10(wave.indep_vector), wave.dep_vector
)
ret = wave_interp_func(np.log10(indep_vector))
elif (wave.interp, wave.indep_scale) == ("CONTINUOUS", "LINEAR"):
dep_vector = (
wave.dep_vector.astype(np.float64)
| python | {
"resource": ""
} |
q274812 | _get_indep_vector | test | def _get_indep_vector(wave_a, wave_b):
"""Create new independent variable vector."""
exobj = pexdoc.exh.addex(RuntimeError, "Independent variable ranges do not overlap")
min_bound = max(np.min(wave_a.indep_vector), np.min(wave_b.indep_vector))
max_bound = min(np.max(wave_a.indep_vector), np.max(wave_b.indep_vector))
exobj(bool(min_bound > max_bound))
| python | {
"resource": ""
} |
q274813 | _verify_compatibility | test | def _verify_compatibility(wave_a, wave_b, check_dep_units=True):
"""Verify that two waveforms can be combined with various mathematical functions."""
exobj = pexdoc.exh.addex(RuntimeError, "Waveforms are not compatible")
ctuple = (
bool(wave_a.indep_scale != wave_b.indep_scale),
bool(wave_a.dep_scale != wave_b.dep_scale),
| python | {
"resource": ""
} |
q274814 | SystemJSManifestStaticFilesMixin.load_systemjs_manifest | test | def load_systemjs_manifest(self):
"""
Load the existing systemjs manifest and remove any entries that no longer
exist on the storage.
"""
# backup the original name
_manifest_name = self.manifest_name
# load the custom bundle manifest
self.manifest_name = self.systemjs_manifest_name
bundle_files = self.load_manifest()
# reset the manifest name
self.manifest_name = | python | {
"resource": ""
} |
q274815 | trace_pars | test | def trace_pars(mname):
"""Define trace parameters."""
pickle_fname = os.path.join(os.path.dirname(__file__), "{0}.pkl".format(mname))
ddir = os.path.dirname(os.path.dirname(__file__))
moddb_fname = os.path.join(ddir, "moddb.json")
in_callables_fname = moddb_fname if os.path.exists(moddb_fname) else None
out_callables_fname = os.path.join(ddir, "{0}.json".format(mname))
noption = os.environ.get("NOPTION", None)
exclude = ["_pytest", "execnet"]
partuple = collections.namedtuple(
| python | {
"resource": ""
} |
q274816 | run_trace | test | def run_trace(
mname,
fname,
module_prefix,
callable_names,
no_print,
module_exclude=None,
callable_exclude=None,
debug=False,
):
"""Run module tracing."""
# pylint: disable=R0913
module_exclude = [] if module_exclude is None else module_exclude
callable_exclude = [] if callable_exclude is None else callable_exclude
par = trace_pars(mname)
start_time = datetime.datetime.now()
with pexdoc.exdoc.ExDocCxt(
exclude=par.exclude + module_exclude,
pickle_fname=par.pickle_fname,
in_callables_fname=par.in_callables_fname,
out_callables_fname=par.out_callables_fname,
_no_print=no_print,
) as exdoc_obj:
fname = os.path.realpath(
os.path.join(
os.path.dirname(__file__),
| python | {
"resource": ""
} |
q274817 | YOURLSAPIMixin.shorten | test | def shorten(self, url, keyword=None, title=None):
"""Shorten URL with optional keyword and title.
Parameters:
url: URL to shorten.
keyword: Optionally choose keyword for short URL, otherwise automatic.
title: Optionally choose title, otherwise taken from web page.
Returns:
ShortenedURL: Shortened URL and associated data.
Raises:
~yourls.exceptions.YOURLSKeywordExistsError: The passed keyword
already exists.
.. note::
This exception has a ``keyword`` attribute.
~yourls.exceptions.YOURLSURLExistsError: The URL has already been
shortened.
.. note::
This exception has a ``url`` attribute, which is an instance
of :py:class:`ShortenedURL` for the existing short URL.
~yourls.exceptions.YOURLSNoURLError: URL missing.
~yourls.exceptions.YOURLSNoLoopError: Cannot shorten a | python | {
"resource": ""
} |
q274818 | YOURLSAPIMixin.expand | test | def expand(self, short):
"""Expand short URL or keyword to long URL.
Parameters:
short: Short URL (``http://example.com/abc``) or keyword (abc).
:return: Expanded/long URL, e.g.
``https://www.youtube.com/watch?v=dQw4w9WgXcQ``
Raises:
~yourls.exceptions.YOURLSHTTPError: HTTP error with response from
| python | {
"resource": ""
} |
q274819 | YOURLSAPIMixin.url_stats | test | def url_stats(self, short):
"""Get stats for short URL or keyword.
Parameters:
short: Short URL (http://example.com/abc) or keyword (abc).
Returns:
ShortenedURL: Shortened URL and associated data.
Raises:
~yourls.exceptions.YOURLSHTTPError: HTTP error with response from
| python | {
"resource": ""
} |
q274820 | YOURLSAPIMixin.stats | test | def stats(self, filter, limit, start=None):
"""Get stats about links.
Parameters:
filter: 'top', 'bottom', 'rand', or 'last'.
limit: Number of links to return from filter.
start: Optional start number.
Returns:
Tuple containing list of ShortenedURLs and DBStats.
Example:
.. code-block:: python
links, stats = yourls.stats(filter='top', limit=10)
Raises:
ValueError: Incorrect value for filter parameter.
requests.exceptions.HTTPError: Generic HTTP Error
| python | {
"resource": ""
} |
q274821 | YOURLSAPIMixin.db_stats | test | def db_stats(self):
"""Get database statistics.
Returns:
DBStats: Total clicks and links statistics.
Raises:
requests.exceptions.HTTPError: Generic HTTP Error
"""
data = dict(action='db-stats')
jsondata = self._api_request(params=data)
| python | {
"resource": ""
} |
q274822 | ste | test | def ste(command, nindent, mdir, fpointer):
r"""
Echo terminal output.
Print STDOUT resulting from a given Bash shell command (relative to the
package :code:`pypkg` directory) formatted in reStructuredText
:param command: Bash shell command, relative to
:bash:`${PMISC_DIR}/pypkg`
:type command: string
:param nindent: Indentation level
:type nindent: integer
:param mdir: Module directory
:type mdir: string
:param fpointer: Output function pointer. Normally is :code:`cog.out` but
:code:`print` or other functions can be used for
debugging
:type fpointer: function object
For example::
.. This is a reStructuredText file snippet
.. [[[cog
.. import os, sys
.. from docs.support.term_echo import term_echo
.. file_name = sys.modules['docs.support.term_echo'].__file__
.. mdir = os.path.realpath(
.. os.path.dirname(
.. | python | {
"resource": ""
} |
q274823 | term_echo | test | def term_echo(command, nindent=0, env=None, fpointer=None, cols=60):
"""
Print STDOUT resulting from a Bash shell command formatted in reStructuredText.
:param command: Bash shell command
:type command: string
:param nindent: Indentation level
:type nindent: integer
:param env: Environment variable replacement dictionary. The Bash
command is pre-processed and any environment variable
represented in the full notation (:bash:`${...}`) is replaced.
The dictionary key is the environment variable name and the
dictionary value is the replacement value. For example, if
**command** is :code:`'${PYTHON_CMD} -m "x=5"'` and **env**
is :code:`{'PYTHON_CMD':'python3'}` the actual command issued
is :code:`'python3 -m "x=5"'`
:type env: dictionary
:param fpointer: Output function pointer. Normally is :code:`cog.out` but
:code:`print` or other functions can be used for
debugging
:type fpointer: function object
:param cols: Number of columns of output
:type cols: integer
"""
# pylint: disable=R0204
# Set argparse width so that output does not need horizontal scroll
# bar in narrow windows or displays
os.environ["COLUMNS"] = str(cols)
command_int = command
if env:
for var, repl in env.items():
| python | {
"resource": ""
} |
q274824 | Command.log | test | def log(self, msg, level=2):
"""
Small log helper
"""
if | python | {
"resource": ""
} |
q274825 | cached | test | def cached(method) -> property:
"""alternative to reify and property decorators. caches the value when it's
generated. It cashes it as instance._name_of_the_property.
"""
name = "_" + method.__name__
@property
def wrapper(self):
try:
| python | {
"resource": ""
} |
q274826 | chunkiter | test | def chunkiter(iterable, chunksize):
"""break an iterable into chunks and yield those chunks as lists
until there's nothing left to yeild.
"""
iterator = iter(iterable)
| python | {
"resource": ""
} |
q274827 | chunkprocess | test | def chunkprocess(func):
"""take a function that taks an iterable as the first argument.
return a wrapper that will break an iterable into chunks using
chunkiter and run each chunk in function, | python | {
"resource": ""
} |
q274828 | flatten | test | def flatten(iterable, map2iter=None):
"""recursively flatten nested objects"""
if map2iter and isinstance(iterable):
iterable = map2iter(iterable)
for item in iterable:
| python | {
"resource": ""
} |
q274829 | quietinterrupt | test | def quietinterrupt(msg=None):
"""add a handler for SIGINT that optionally prints a given message.
For stopping scripts without having to see the stacktrace.
"""
def handler():
if msg:
| python | {
"resource": ""
} |
q274830 | printtsv | test | def printtsv(table, sep="\t", file=sys.stdout):
"""stupidly print an iterable of iterables in TSV format"""
| python | {
"resource": ""
} |
q274831 | mkdummy | test | def mkdummy(name, **attrs):
"""Make a placeholder object that uses its own name for its repr"""
return type(
| python | {
"resource": ""
} |
q274832 | PBytes.from_str | test | def from_str(cls, human_readable_str, decimal=False, bits=False):
"""attempt to parse a size in bytes from a human-readable string."""
divisor = 1000 if decimal else 1024
num = []
c = ""
for c in human_readable_str:
if c not in cls.digits:
break
num.append(c)
num = "".join(num)
try:
| python | {
"resource": ""
} |
q274833 | cli | test | def cli(ctx, apiurl, signature, username, password):
"""Command line interface for YOURLS.
Configuration parameters can be passed as switches or stored in .yourls or
~/.yourls.
If your YOURLS server requires authentication, please provide one of the
following:
\b
• apiurl and signature
• apiurl, username, and password
| python | {
"resource": ""
} |
q274834 | trace_module | test | def trace_module(no_print=True):
"""Trace eng wave module exceptions."""
mname = "wave_core"
fname = "peng"
module_prefix = "peng.{0}.Waveform.".format(mname)
callable_names = ("__init__",) | python | {
"resource": ""
} |
q274835 | def_links | test | def def_links(mobj):
"""Define Sphinx requirements links."""
fdict = json_load(os.path.join("data", "requirements.json"))
sdeps = sorted(fdict.keys())
olines = []
for item in sdeps:
olines.append(
| python | {
"resource": ""
} |
q274836 | make_common_entry | test | def make_common_entry(plist, pyver, suffix, req_ver):
"""Generate Python interpreter version entries for 2.x or 3.x series."""
prefix = "Python | python | {
"resource": ""
} |
q274837 | make_multi_entry | test | def make_multi_entry(plist, pkg_pyvers, ver_dict):
"""Generate Python interpreter version entries."""
for pyver in pkg_pyvers:
pver = | python | {
"resource": ""
} |
q274838 | ops_to_words | test | def ops_to_words(item):
"""Translate requirement specification to words."""
unsupp_ops = ["~=", "==="]
# Ordered for "pleasant" word specification
supp_ops = [">=", ">", "==", "<=", "<", "!="]
tokens = sorted(item.split(","), reverse=True)
actual_tokens = []
for req in tokens:
for op in unsupp_ops:
if req.startswith(op):
raise RuntimeError("Unsupported version specification: {0}".format(op))
for op in supp_ops:
if req.startswith(op):
actual_tokens.append(op)
break
else:
| python | {
"resource": ""
} |
q274839 | _chunk_noise | test | def _chunk_noise(noise):
"""Chunk input noise data into valid Touchstone file rows."""
data = zip(
noise["freq"],
| python | {
"resource": ""
} |
q274840 | _chunk_pars | test | def _chunk_pars(freq_vector, data_matrix, pformat):
"""Chunk input data into valid Touchstone file rows."""
pformat = pformat.upper()
length = 4
for freq, data in zip(freq_vector, data_matrix):
data = data.flatten()
for index in range(0, data.size, length):
fpoint = [freq] if not index else [None]
cdata = data[index : index + length]
if pformat == "MA":
| python | {
"resource": ""
} |
q274841 | write_touchstone | test | def write_touchstone(fname, options, data, noise=None, frac_length=10, exp_length=2):
r"""
Write a `Touchstone`_ file.
Parameter data is first resized to an :code:`points` x :code:`nports` x
:code:`nports` where :code:`points` represents the number of frequency
points and :code:`nports` represents the number of ports in the file; then
parameter data is written to file in scientific notation
:param fname: Touchstone file name
:type fname: `FileNameExists <https://pexdoc.readthedocs.io/en/stable/
ptypes.html#filenameexists>`_
:param options: Touchstone file options
:type options: :ref:`TouchstoneOptions`
:param data: Touchstone file parameter data
:type data: :ref:`TouchstoneData`
:param noise: Touchstone file parameter noise data (only supported in
two-port files)
:type noise: :ref:`TouchstoneNoiseData`
:param frac_length: Number of digits to use in fractional part of data
:type frac_length: non-negative integer
:param exp_length: Number of digits to use in exponent
:type exp_length: positive integer
.. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.touchstone.write_touchstone
:raises:
* RuntimeError (Argument \`data\` is not valid)
* RuntimeError (Argument \`exp_length\` is not valid)
* RuntimeError (Argument \`fname\` is not valid)
* RuntimeError (Argument \`frac_length\` is not valid)
* RuntimeError (Argument \`noise\` is not valid)
* RuntimeError (Argument \`options\` is not valid)
* RuntimeError (File *[fname]* does | python | {
"resource": ""
} |
q274842 | _bound_waveform | test | def _bound_waveform(wave, indep_min, indep_max):
"""Add independent variable vector bounds if they are not in vector."""
indep_min, indep_max = _validate_min_max(wave, indep_min, indep_max)
indep_vector = copy.copy(wave._indep_vector)
if (
isinstance(indep_min, float) or isinstance(indep_max, float)
) and indep_vector.dtype.name.startswith("int"):
indep_vector = indep_vector.astype(float)
min_pos = np.searchsorted(indep_vector, indep_min)
if not np.isclose(indep_min, indep_vector[min_pos], FP_RTOL, FP_ATOL):
indep_vector = np.insert(indep_vector, min_pos, indep_min)
| python | {
"resource": ""
} |
q274843 | _build_units | test | def _build_units(indep_units, dep_units, op):
"""Build unit math operations."""
if (not dep_units) and (not indep_units):
return ""
if dep_units and (not indep_units):
return dep_units
if (not dep_units) and indep_units:
return (
remove_extra_delims("1{0}({1})".format(op, indep_units))
| python | {
"resource": ""
} |
q274844 | _operation | test | def _operation(wave, desc, units, fpointer):
"""Perform generic operation on a waveform object."""
ret = | python | {
"resource": ""
} |
q274845 | _running_area | test | def _running_area(indep_vector, dep_vector):
"""Calculate running area under curve."""
rect_height = np.minimum(dep_vector[:-1], dep_vector[1:])
rect_base = np.diff(indep_vector)
rect_area = np.multiply(rect_height, rect_base)
triang_height = np.abs(np.diff(dep_vector))
| python | {
"resource": ""
} |
q274846 | _validate_min_max | test | def _validate_min_max(wave, indep_min, indep_max):
"""Validate min and max bounds are within waveform's independent variable vector."""
imin, imax = False, False
if indep_min is None:
indep_min = wave._indep_vector[0]
imin = True
if indep_max is None:
indep_max = wave._indep_vector[-1]
imax = True
if imin and imax:
return indep_min, indep_max
exminmax = pexdoc.exh.addex(
| python | {
"resource": ""
} |
q274847 | acos | test | def acos(wave):
r"""
Return the arc cosine of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.acos
:raises:
* RuntimeError (Argument \`wave\` is not valid)
* ValueError | python | {
"resource": ""
} |
q274848 | acosh | test | def acosh(wave):
r"""
Return the hyperbolic arc cosine of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.acosh
:raises:
* RuntimeError (Argument \`wave\` is not valid)
| python | {
"resource": ""
} |
q274849 | asin | test | def asin(wave):
r"""
Return the arc sine of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.asin
:raises:
* RuntimeError (Argument \`wave\` is not valid)
* ValueError (Math | python | {
"resource": ""
} |
q274850 | atanh | test | def atanh(wave):
r"""
Return the hyperbolic arc tangent of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.atanh
:raises:
* RuntimeError (Argument \`wave\` is not valid)
| python | {
"resource": ""
} |
q274851 | average | test | def average(wave, indep_min=None, indep_max=None):
r"""
Return the running average of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.average
:raises:
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\`
| python | {
"resource": ""
} |
q274852 | db | test | def db(wave):
r"""
Return a waveform's dependent variable vector expressed in decibels.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for peng.wave_functions.db
:raises:
* RuntimeError (Argument \`wave\` is not valid)
* ValueError (Math domain error)
| python | {
"resource": ""
} |
q274853 | derivative | test | def derivative(wave, indep_min=None, indep_max=None):
r"""
Return the numerical derivative of a waveform's dependent variable vector.
The method used is the `backwards differences
<https://en.wikipedia.org/wiki/
Finite_difference#Forward.2C_backward.2C_and_central_differences>`_ method
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: float
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.derivative
:raises:
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\` | python | {
"resource": ""
} |
q274854 | ffti | test | def ffti(wave, npoints=None, indep_min=None, indep_max=None):
r"""
Return the imaginary part of the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size of the independent variable vector
the waveform is truncated; if **npoints** is greater than
the size of the independent variable vector, the waveform
is zero-padded
:type npoints: positive integer
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
| python | {
"resource": ""
} |
q274855 | fftm | test | def fftm(wave, npoints=None, indep_min=None, indep_max=None):
r"""
Return the magnitude of the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size of the independent variable vector
the waveform is truncated; if **npoints** is greater than
the size of the independent variable vector, the waveform
is zero-padded
:type npoints: positive integer
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
| python | {
"resource": ""
} |
q274856 | fftp | test | def fftp(wave, npoints=None, indep_min=None, indep_max=None, unwrap=True, rad=True):
r"""
Return the phase of the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size of the independent variable vector
the waveform is truncated; if **npoints** is greater than
the size of the independent variable vector, the waveform
is zero-padded
:type npoints: positive integer
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type | python | {
"resource": ""
} |
q274857 | fftr | test | def fftr(wave, npoints=None, indep_min=None, indep_max=None):
r"""
Return the real part of the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size of the independent variable vector
the waveform is truncated; if **npoints** is greater than
the size of the independent variable vector, the waveform
is zero-padded
:type npoints: positive integer
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
| python | {
"resource": ""
} |
q274858 | ifftdb | test | def ifftdb(wave, npoints=None, indep_min=None, indep_max=None):
r"""
Return the inverse Fast Fourier Transform of a waveform.
The dependent variable vector of the returned waveform is expressed in decibels
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size of the independent variable vector
the waveform is truncated; if **npoints** is greater than
the size of the independent variable vector, the waveform
is zero-padded
:type npoints: positive integer
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: :py:class:`peng.eng.Waveform`
.. | python | {
"resource": ""
} |
q274859 | iffti | test | def iffti(wave, npoints=None, indep_min=None, indep_max=None):
r"""
Return the imaginary part of the inverse Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size of the independent variable vector
the waveform is truncated; if **npoints** is greater than
the size of the independent variable vector, the waveform
is zero-padded
:type npoints: positive integer
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for | python | {
"resource": ""
} |
q274860 | ifftm | test | def ifftm(wave, npoints=None, indep_min=None, indep_max=None):
r"""
Return the magnitude of the inverse Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size of the independent variable vector
the waveform is truncated; if **npoints** is greater than
the size of the independent variable vector, the waveform
is zero-padded
:type npoints: positive integer
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
| python | {
"resource": ""
} |
q274861 | ifftp | test | def ifftp(wave, npoints=None, indep_min=None, indep_max=None, unwrap=True, rad=True):
r"""
Return the phase of the inverse Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size of the independent variable vector
the waveform is truncated; if **npoints** is greater than
the size of the independent variable vector, the waveform
is zero-padded
:type npoints: positive integer
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type | python | {
"resource": ""
} |
q274862 | ifftr | test | def ifftr(wave, npoints=None, indep_min=None, indep_max=None):
r"""
Return the real part of the inverse Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size of the independent variable vector
the waveform is truncated; if **npoints** is greater than
the size of the independent variable vector, the waveform
is zero-padded
:type npoints: positive integer
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
| python | {
"resource": ""
} |
q274863 | integral | test | def integral(wave, indep_min=None, indep_max=None):
r"""
Return the running integral of a waveform's dependent variable vector.
The method used is the `trapezoidal
<https://en.wikipedia.org/wiki/Trapezoidal_rule>`_ method
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.integral
:raises:
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`wave\` is | python | {
"resource": ""
} |
q274864 | group_delay | test | def group_delay(wave):
r"""
Return the group delay of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
| python | {
"resource": ""
} |
q274865 | log | test | def log(wave):
r"""
Return the natural logarithm of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for peng.wave_functions.log
:raises:
* RuntimeError (Argument \`wave\` is not valid)
* | python | {
"resource": ""
} |
q274866 | naverage | test | def naverage(wave, indep_min=None, indep_max=None):
r"""
Return the numerical average of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: :py:class:`peng.eng.Waveform`
| python | {
"resource": ""
} |
q274867 | nintegral | test | def nintegral(wave, indep_min=None, indep_max=None):
r"""
Return the numerical integral of a waveform's dependent variable vector.
The method used is the `trapezoidal
<https://en.wikipedia.org/wiki/Trapezoidal_rule>`_ method
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of | python | {
"resource": ""
} |
q274868 | nmax | test | def nmax(wave, indep_min=None, indep_max=None):
r"""
Return the maximum of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: float
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.nmax
| python | {
"resource": ""
} |
q274869 | nmin | test | def nmin(wave, indep_min=None, indep_max=None):
r"""
Return the minimum of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: float
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.nmin
| python | {
"resource": ""
} |
q274870 | phase | test | def phase(wave, unwrap=True, rad=True):
r"""
Return the phase of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param unwrap: Flag that indicates whether phase should change phase shifts
to their :code:`2*pi` complement (True) or not (False)
:type unwrap: boolean
:param rad: Flag that indicates whether phase should be returned in radians
(True) or degrees (False)
:type rad: boolean
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.phase
:raises:
* RuntimeError (Argument \`rad\` is not valid)
* RuntimeError (Argument \`unwrap\` is not valid)
| python | {
"resource": ""
} |
q274871 | round | test | def round(wave, decimals=0):
r"""
Round a waveform's dependent variable vector to a given number of decimal places.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param decimals: Number of decimals to round to
:type decimals: integer
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.round
:raises:
* RuntimeError (Argument \`decimals\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
.. [[[end]]]
"""
# pylint: disable=W0622
pexdoc.exh.addex(
| python | {
"resource": ""
} |
q274872 | sqrt | test | def sqrt(wave):
r"""
Return the square root of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.sqrt | python | {
"resource": ""
} |
q274873 | subwave | test | def subwave(wave, dep_name=None, indep_min=None, indep_max=None, indep_step=None):
r"""
Return a waveform that is a sub-set of a waveform, potentially re-sampled.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param dep_name: Independent variable name
:type dep_name: `NonNullString <https://pexdoc.readthedocs.io/en/stable/
ptypes.html#nonnullstring>`_
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:param indep_step: Independent vector step
:type indep_step: integer or float
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.subwave
:raises:
* RuntimeError (Argument \`dep_name\` is not valid)
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`indep_step\` is greater than independent
vector range)
* RuntimeError (Argument \`indep_step\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\`
arguments)
.. [[[end]]]
"""
ret = copy.copy(wave)
if dep_name | python | {
"resource": ""
} |
q274874 | wcomplex | test | def wcomplex(wave):
r"""
Convert a waveform's dependent variable vector to complex.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.wcomplex | python | {
"resource": ""
} |
q274875 | wfloat | test | def wfloat(wave):
r"""
Convert a waveform's dependent variable vector to float.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.wfloat
:raises:
* RuntimeError (Argument \`wave\` is not valid)
* TypeError (Cannot convert | python | {
"resource": ""
} |
q274876 | wint | test | def wint(wave):
r"""
Convert a waveform's dependent variable vector to integer.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.wint
:raises:
* RuntimeError (Argument \`wave\` is not valid)
* TypeError (Cannot convert | python | {
"resource": ""
} |
q274877 | wvalue | test | def wvalue(wave, indep_var):
r"""
Return the dependent variable value at a given independent variable point.
If the independent variable point is not in the independent variable vector
the dependent variable value is obtained by linear interpolation
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param indep_var: Independent variable point for which the dependent
variable is to be obtained
:type indep_var: integer or float
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.wvalue
:raises:
* RuntimeError (Argument \`indep_var\` is not valid)
| python | {
"resource": ""
} |
q274878 | SystemFinder.find | test | def find(self, path, all=False):
"""
Only allow lookups for jspm_packages.
# TODO: figure out the 'jspm_packages' dir from packag.json.
"""
bits = path.split('/')
dirs_to_serve = ['jspm_packages', settings.SYSTEMJS_OUTPUT_DIR]
| python | {
"resource": ""
} |
q274879 | get_short_desc | test | def get_short_desc(long_desc):
"""Get first sentence of first paragraph of long description."""
found = False
olines = []
for line in [item.rstrip() for item in long_desc.split("\n")]:
if found and (((not line) and (not olines)) or (line and olines)):
olines.append(line)
| python | {
"resource": ""
} |
q274880 | _build_expr | test | def _build_expr(tokens, higher_oplevel=-1, ldelim="(", rdelim=")"):
"""Build mathematical expression from hierarchical list."""
# Numbers
if isinstance(tokens, str):
return tokens
# Unary operators
if len(tokens) == 2:
return "".join(tokens)
# Multi-term operators
oplevel = _get_op_level(tokens[1])
stoken = ""
for num, item in enumerate(tokens):
if num % 2 | python | {
"resource": ""
} |
q274881 | _next_rdelim | test | def _next_rdelim(items, pos):
"""Return position of next matching closing delimiter."""
for num, item in enumerate(items):
if item > pos:
break
else:
| python | {
"resource": ""
} |
q274882 | _get_functions | test | def _get_functions(expr, ldelim="(", rdelim=")"):
"""Parse function calls."""
tpars = _pair_delims(expr, ldelim=ldelim, rdelim=rdelim)
alphas = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
fchars = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "_"
tfuncs = []
for lnum, rnum in tpars:
if lnum and expr[lnum - 1] in fchars:
for cnum, char in enumerate(reversed(expr[:lnum])):
if char not in fchars:
break
else:
cnum = lnum
tfuncs.append(
{
"fname": expr[lnum - cnum : lnum],
| python | {
"resource": ""
} |
q274883 | _pair_delims | test | def _pair_delims(expr, ldelim="(", rdelim=")"):
"""Pair delimiters."""
# Find where remaining delimiters are
lindex = reversed([num for num, item in enumerate(expr) if item == ldelim])
rindex = [num for num, item in | python | {
"resource": ""
} |
q274884 | _parse_expr | test | def _parse_expr(text, ldelim="(", rdelim=")"):
"""Parse mathematical expression using PyParsing."""
var = pyparsing.Word(pyparsing.alphas + "_", pyparsing.alphanums + "_")
point = pyparsing.Literal(".")
exp = pyparsing.CaselessLiteral("E")
number = pyparsing.Combine(
pyparsing.Word("+-" + pyparsing.nums, pyparsing.nums)
+ pyparsing.Optional(point + pyparsing.Optional(pyparsing.Word(pyparsing.nums)))
+ pyparsing.Optional(
exp + pyparsing.Word("+-" + pyparsing.nums, pyparsing.nums)
)
)
atom = var | number
oplist = [
(pyparsing.Literal("**"), 2, pyparsing.opAssoc.RIGHT),
(pyparsing.oneOf("+ - ~"), 1, pyparsing.opAssoc.RIGHT),
(pyparsing.oneOf("* / // %"), 2, pyparsing.opAssoc.LEFT),
| python | {
"resource": ""
} |
q274885 | _remove_consecutive_delims | test | def _remove_consecutive_delims(expr, ldelim="(", rdelim=")"):
"""Remove consecutive delimiters."""
tpars = _pair_delims(expr, ldelim=ldelim, rdelim=rdelim)
# Flag superfluous delimiters
ddelim = []
for ctuple, ntuple in zip(tpars, tpars[1:]):
if ctuple == (ntuple[0] - 1, ntuple[1] + 1):
ddelim.extend(ntuple)
| python | {
"resource": ""
} |
q274886 | _split_every | test | def _split_every(text, sep, count, lstrip=False, rstrip=False):
"""
Return list of the words in the string, using count of a separator as delimiter.
:param text: String to split
:type text: string
:param sep: Separator
:type sep: string
:param count: Number of separators to use as delimiter
:type count: integer
:param lstrip: Flag that indicates whether whitespace is removed
from the beginning of each list item (True) or not
(False)
:type lstrip: boolean
:param rstrip: Flag that indicates whether whitespace is removed
| python | {
"resource": ""
} |
q274887 | _to_eng_tuple | test | def _to_eng_tuple(number):
"""
Return tuple with mantissa and exponent of number formatted in engineering notation.
:param number: Number
:type number: integer or float
:rtype: tuple
"""
# pylint: disable=W0141
# Helper function: split integer and fractional part of mantissa
# + ljust ensures that integer part in engineering notation has
| python | {
"resource": ""
} |
q274888 | no_exp | test | def no_exp(number):
r"""
Convert number to string guaranteeing result is not in scientific notation.
:param number: Number to convert
:type number: integer or float
:rtype: string
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for peng.functions.no_exp
:raises: RuntimeError (Argument \`number\` is not valid)
.. [[[end]]]
"""
mant, exp = to_scientific_tuple(number)
if not exp:
return str(number)
floating_mant = "." in mant
mant = mant.replace(".", "")
if exp < 0:
| python | {
"resource": ""
} |
q274889 | peng | test | def peng(number, frac_length, rjust=True):
r"""
Convert a number to engineering notation.
The absolute value of the number (if it is not exactly zero) is bounded to
the interval [1E-24, 1E+24)
:param number: Number to convert
:type number: integer or float
:param frac_length: Number of digits of fractional part
:type frac_length: `NonNegativeInteger
<https://pexdoc.readthedocs.io/en/stable/
ptypes.html#nonnegativeinteger>`_
:param rjust: Flag that indicates whether the number is
right-justified (True) or not (False)
:type rjust: boolean
:rtype: string
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for peng.functions.peng
:raises:
* RuntimeError (Argument \`frac_length\` is not valid)
* RuntimeError (Argument \`number\` is not valid)
* RuntimeError (Argument \`rjust\` is not valid)
.. [[[end]]]
The supported engineering suffixes are:
+----------+-------+--------+
| Exponent | Name | Suffix |
+==========+=======+========+
| 1E-24 | yocto | y |
+----------+-------+--------+
| 1E-21 | zepto | z |
+----------+-------+--------+
| 1E-18 | atto | a |
+----------+-------+--------+
| 1E-15 | femto | f |
+----------+-------+--------+
| 1E-12 | pico | p |
+----------+-------+--------+
| 1E-9 | nano | n |
+----------+-------+--------+
| 1E-6 | micro | u |
+----------+-------+--------+
| 1E-3 | milli | m |
+----------+-------+--------+
| 1E+0 | | |
+----------+-------+--------+
| 1E+3 | kilo | k |
+----------+-------+--------+
| 1E+6 | mega | M |
+----------+-------+--------+
| 1E+9 | giga | G |
+----------+-------+--------+
| 1E+12 | tera | T |
+----------+-------+--------+
| 1E+15 | peta | P |
+----------+-------+--------+
| 1E+18 | exa | E |
+----------+-------+--------+
| 1E+21 | zetta | Z |
+----------+-------+--------+
| 1E+24 | yotta | Y |
+----------+-------+--------+
For example:
>>> import peng
>>> peng.peng(1235.6789E3, 3, False)
'1.236M'
"""
# The decimal module has a to_eng_string() function, but it does not seem
# to work well in all cases. For example:
# >>> decimal.Decimal('34.5712233E8').to_eng_string()
# '3.45712233E+9'
# >>> decimal.Decimal('34.57122334E8').to_eng_string()
# '3457122334'
# It seems that the conversion function does not work in all cases
#
# Return formatted zero if number is zero, easier to not deal with this
# special case through the rest of the algorithm
if number == 0:
number = "0.{zrs}".format(zrs="0" * frac_length) if frac_length else "0"
# Engineering notation numbers can have | python | {
"resource": ""
} |
q274890 | peng_float | test | def peng_float(snum):
r"""
Return floating point equivalent of a number represented in engineering notation.
:param snum: Number
:type snum: :ref:`EngineeringNotationNumber`
:rtype: string
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.functions.peng_float
:raises: RuntimeError (Argument \`snum\` is not valid)
.. [[[end]]]
For example:
>>> import peng
>>> peng.peng_float(peng.peng(1235.6789E3, 3, False))
1236000.0
"""
# This can be coded | python | {
"resource": ""
} |
q274891 | peng_frac | test | def peng_frac(snum):
r"""
Return the fractional part of a number represented in engineering notation.
:param snum: Number
:type snum: :ref:`EngineeringNotationNumber`
:rtype: integer
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.functions.peng_frac
:raises: RuntimeError (Argument \`snum\` is not valid)
.. [[[end]]]
For example:
| python | {
"resource": ""
} |
q274892 | peng_mant | test | def peng_mant(snum):
r"""
Return the mantissa of a number represented in engineering notation.
:param snum: Number
:type snum: :ref:`EngineeringNotationNumber`
:rtype: float
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.functions.peng_mant
:raises: RuntimeError (Argument \`snum\` is not valid)
.. [[[end]]]
| python | {
"resource": ""
} |
q274893 | peng_power | test | def peng_power(snum):
r"""
Return engineering suffix and its floating point equivalent of a number.
:py:func:`peng.peng` lists the correspondence between suffix and floating
point exponent.
:param snum: Number
:type snum: :ref:`EngineeringNotationNumber`
:rtype: named tuple in which the first item is the engineering suffix and
the second item is the floating point equivalent of the suffix
when the number is represented in engineering notation.
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
| python | {
"resource": ""
} |
q274894 | peng_suffix_math | test | def peng_suffix_math(suffix, offset):
r"""
Return engineering suffix from a starting suffix and an number of suffixes offset.
:param suffix: Engineering suffix
:type suffix: :ref:`EngineeringNotationSuffix`
:param offset: Engineering suffix offset
:type offset: integer
:rtype: string
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.functions.peng_suffix_math
:raises:
* RuntimeError (Argument \`offset\` is not valid)
* RuntimeError (Argument \`suffix\` is not valid)
* ValueError (Argument \`offset\` is not valid)
.. [[[end]]]
For example:
| python | {
"resource": ""
} |
q274895 | remove_extra_delims | test | def remove_extra_delims(expr, ldelim="(", rdelim=")"):
r"""
Remove unnecessary delimiters in mathematical expressions.
Delimiters (parenthesis, brackets, etc.) may be removed either because
there are multiple consecutive delimiters enclosing a single expressions or
because the delimiters are implied by operator precedence rules. Function
names must start with a letter and then can contain alphanumeric characters
and a maximum of one underscore
:param expr: Mathematical expression
:type expr: string
:param ldelim: Single character left delimiter
:type ldelim: string
:param rdelim: Single character right delimiter
:type rdelim: string
:rtype: string
:raises:
* RuntimeError (Argument \`expr\` is not valid)
* RuntimeError (Argument \`ldelim\` is not valid)
* RuntimeError (Argument \`rdelim\` is not valid)
* RuntimeError (Function name `*[function_name]*` is not valid)
* RuntimeError (Mismatched delimiters)
"""
op_group = ""
for item1 in _OP_PREC:
if isinstance(item1, list):
for item2 in item1:
op_group += item2
else:
op_group += item1
iobj = zip([expr, ldelim, rdelim], ["expr", "ldelim", "rdelim"])
for item, desc in iobj:
if not isinstance(item, str):
| python | {
"resource": ""
} |
q274896 | to_scientific_string | test | def to_scientific_string(number, frac_length=None, exp_length=None, sign_always=False):
"""
Convert number or number string to a number string in scientific notation.
Full precision is maintained if the number is represented as a string
:param number: Number to convert
:type number: number or string
:param frac_length: Number of digits of fractional part, None indicates
that the fractional part of the number should not be
limited
:type frac_length: integer or None
:param exp_length: Number of digits of the exponent; the actual length of
the exponent takes precedence if it is longer
:type exp_length: integer or None
:param sign_always: Flag that indicates whether the sign always
precedes the number for both non-negative and negative
numbers (True) or only for negative numbers (False)
:type sign_always: boolean
:rtype: string
For example:
>>> import peng
>>> peng.to_scientific_string(333)
'3.33E+2'
>>> peng.to_scientific_string(0.00101)
'1.01E-3'
>>> peng.to_scientific_string(99.999, 1, 2, True)
'+1.0E+02'
"""
# pylint: disable=W0702
try:
number = -1e20 if np.isneginf(number) else number
except:
pass
try:
number = +1e20 if np.isposinf(number) else number
except:
pass
exp_length | python | {
"resource": ""
} |
q274897 | to_scientific_tuple | test | def to_scientific_tuple(number):
"""
Return mantissa and exponent of a number in scientific notation.
Full precision is maintained if the number is represented as a string
:param number: Number
:type number: integer, float or string
:rtype: named tuple in which the first item is the mantissa (*string*)
and the second item is the exponent (*integer*) of the number
when expressed in scientific notation
For example:
>>> import peng
>>> peng.to_scientific_tuple('135.56E-8')
NumComp(mant='1.3556', exp=-6)
>>> peng.to_scientific_tuple(0.0000013556)
NumComp(mant='1.3556', exp=-6)
"""
| python | {
"resource": ""
} |
q274898 | find_sourcemap_comment | test | def find_sourcemap_comment(filepath, block_size=100):
"""
Seeks and removes the sourcemap comment. If found, the sourcemap line is
returned.
Bundled output files can have massive amounts of lines, and the sourceMap
comment is always at the end. So, to extract it efficiently, we read out the
lines of the file starting from the end. We look back at most 2 lines.
:param:filepath: path to output bundle file containing the sourcemap comment
:param:blocksize: integer saying how many bytes to read at once
:return:string with the sourcemap comment or None
"""
MAX_TRACKBACK = 2 # look back at most 2 lines, catching potential blank line at the end
block_number = -1
# blocks of size block_size, in reverse order starting from the end of the file
blocks = []
sourcemap = None
try:
# open file in binary read+write mode, so we can seek with negative offsets
of = io.open(filepath, 'br+')
# figure out what's the end byte
of.seek(0, os.SEEK_END)
block_end_byte = of.tell()
# track back for maximum MAX_TRACKBACK lines and while we can track back
while block_end_byte > 0 and MAX_TRACKBACK > 0:
if (block_end_byte - block_size > 0):
# read the last block we haven't yet read
of.seek(block_number*block_size, os.SEEK_END)
blocks.append(of.read(block_size))
else:
# file too small, start from begining
of.seek(0, os.SEEK_SET)
# only read what was not read
blocks = [of.read(block_end_byte)]
# update variables that control while loop
content = b''.join(reversed(blocks))
lines_found = content.count(b'\n')
MAX_TRACKBACK -= lines_found
block_end_byte -= block_size
block_number -= 1
# early check and | python | {
"resource": ""
} |
q274899 | SystemBundle.needs_ext | test | def needs_ext(self):
"""
Check whether `self.app` is missing the '.js' extension and if it needs it.
"""
if settings.SYSTEMJS_DEFAULT_JS_EXTENSIONS:
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.