_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | 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:
msg = self.socket.recv(self.buffer_size)
debug(b'< ' + msg)
except socket.error:
pass | 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)),
('welly', str(welly)),
('fieldx', str(fieldx)),
('fieldy', str(fieldy)),
('value', 'true')
]
self.send(cmd)
return self.wait_for(*cmd[0]) | python | {
"resource": ""
} |
q274802 | CAM.save_template | test | def save_template(self, filename="{ScanningTemplate}leicacam.xml"):
"""Save scanning template to filename."""
cmd = [
('sys', '0'),
('cmd', 'save'),
('fil', str(filename))
]
self.send(cmd)
return self.wait_for(*cmd[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
Response from LASAF in an ordered dict.
Example
-------
::
>>> # load {ScanningTemplate}leicacam.xml
>>> cam.load_template('leicacam')
>>> # load {ScanningTemplate}leicacam.xml
>>> cam.load_template('{ScanningTemplate}leicacam')
>>> # load {ScanningTemplate}leicacam.xml
>>> cam.load_template('/path/to/{ScanningTemplate}leicacam.xml')
"""
basename = os.path.basename(filename)
if basename[-4:] == '.xml':
basename = basename[:-4]
if basename[:18] != '{ScanningTemplate}':
basename = '{ScanningTemplate}' + basename
cmd = [
('sys', '0'),
('cmd', 'load'),
('fil', str(basename))
]
self.send(cmd)
return self.wait_for(*cmd[1]) | python | {
"resource": ""
} |
q274804 | CAM.get_information | test | def get_information(self, about='stage'):
"""Get information about given keyword. Defaults to stage."""
cmd = [
('cmd', 'getinfo'),
('dev', str(about))
]
self.send(cmd)
return self.wait_for(*cmd[1]) | 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__)))
)
fname = os.path.join(file_dir, fname)
with open(fname) as fobj:
lines = fobj.readlines()
# Parse line specification
tokens = [item.strip() for item in lrange.split(",")]
inc_lines = []
for token in tokens:
if "-" in token:
subtokens = token.split("-")
lmin, lmax = (
int(subtokens[0]),
int(subtokens[1]) if subtokens[1] else len(lines),
)
for num in range(lmin, lmax + 1):
inc_lines.append(num)
else:
inc_lines.append(int(token))
# Produce output
fpointer(".. code-block:: python\n")
fpointer("\n")
for num, line in enumerate(lines):
if num + 1 in inc_lines:
fpointer(" " + line.replace("\t", " ") if line.strip() else "\n")
fpointer("\n") | 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'."
)
path = os.path.join(directory, 'package.json')
if not os.path.isfile(path):
raise ImproperlyConfigured("'package.json' does not exist, tried looking in %s" % path)
return path | python | {
"resource": ""
} |
q274807 | parse_package_json | test | def parse_package_json():
"""
Extract the JSPM configuration from package.json.
"""
with open(locate_package_json()) as pjson:
data = json.loads(pjson.read())
return data | 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']
message = jsondata['message']
if code == 'error:noloop':
raise YOURLSNoLoopError(message, response=response)
elif code == 'error:nourl':
raise YOURLSNoURLError(message, response=response)
elif 'message' in jsondata:
message = jsondata['message']
raise YOURLSHTTPError(message, response=response)
http_error_message = http_exc.args[0]
raise YOURLSHTTPError(http_error_message, response=response) | 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']
code = jsondata['code']
message = jsondata['message']
if status == 'fail':
if code == 'error:keyword':
raise YOURLSKeywordExistsError(message, keyword=data['keyword'])
elif code == 'error:url':
url = _json_to_shortened_url(jsondata['url'], jsondata['shorturl'])
raise YOURLSURLExistsError(message, url=url)
else:
raise YOURLSAPIError(message)
else:
return jsondata
else:
# Without status, nothing special needs to be handled.
return jsondata | 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, wave_b)
dep_vector_a = _interp_dep_vector(wave_a, indep_vector)
dep_vector_b = _interp_dep_vector(wave_b, indep_vector)
return (indep_vector, dep_vector_a, dep_vector_b) | 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)
if not dep_vector_is_complex
else wave.dep_vector
)
wave_interp_func = scipy.interpolate.interp1d(wave.indep_vector, dep_vector)
ret = wave_interp_func(indep_vector)
else: # wave.interp == 'STAIRCASE'
wave_interp_func = scipy.interpolate.interp1d(
wave.indep_vector, wave.dep_vector, kind="zero"
)
# Interpolator does not return the right value for the last
# data point, it gives the previous "stair" value
ret = wave_interp_func(indep_vector)
eq_comp = np.all(
np.isclose(wave.indep_vector[-1], indep_vector[-1], FP_RTOL, FP_ATOL)
)
if eq_comp:
ret[-1] = wave.dep_vector[-1]
round_ret = np.round(ret, 0)
return (
round_ret.astype("int")
if (dep_vector_is_int and np.all(np.isclose(round_ret, ret, FP_RTOL, FP_ATOL)))
else ret
) | 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))
raw_range = np.unique(np.concatenate((wave_a.indep_vector, wave_b.indep_vector)))
return raw_range[np.logical_and(min_bound <= raw_range, raw_range <= 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),
bool(wave_a.indep_units != wave_b.indep_units),
(bool(wave_a.dep_units != wave_b.dep_units) if check_dep_units else False),
bool(wave_a.interp != wave_b.interp),
)
exobj(any(ctuple)) | 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 = _manifest_name
# check that the files actually exist, if not, remove them from the manifest
for file, hashed_file in bundle_files.copy().items():
if not self.exists(file) or not self.exists(hashed_file):
del bundle_files[file]
return bundle_files | 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(
"ParTuple",
[
"pickle_fname",
"in_callables_fname",
"out_callables_fname",
"noption",
"exclude",
],
)
return partuple(
pickle_fname, in_callables_fname, out_callables_fname, noption, exclude
) | 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__),
"..",
"..",
"tests",
"test_{0}.py".format(fname),
)
)
test_cmd = (
["--color=yes"]
+ (["-s", "-vv"] if debug else ["-q", "-q", "-q"])
+ ["--disable-warnings"]
+ ["-x"]
+ ([par.noption] if par.noption else [])
+ ["-m " + mname]
+ [fname]
)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=PytestWarning)
if pytest.main(test_cmd):
raise RuntimeError("Tracing did not complete successfully")
stop_time = datetime.datetime.now()
if not no_print:
print(
"Auto-generation of exceptions documentation time: {0}".format(
pmisc.elapsed_time_string(start_time, stop_time)
)
)
for callable_name in callable_names:
callable_name = module_prefix + callable_name
print("\nCallable: {0}".format(callable_name))
print(exdoc_obj.get_sphinx_doc(callable_name, exclude=callable_exclude))
print("\n")
return copy.copy(exdoc_obj) | 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 shortened URL.
~yourls.exceptions.YOURLSAPIError: Unhandled API error.
~yourls.exceptions.YOURLSHTTPError: HTTP error with response from
YOURLS API.
requests.exceptions.HTTPError: Generic HTTP error.
"""
data = dict(action='shorturl', url=url, keyword=keyword, title=title)
jsondata = self._api_request(params=data)
url = _json_to_shortened_url(jsondata['url'], jsondata['shorturl'])
return url | 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
YOURLS API.
requests.exceptions.HTTPError: Generic HTTP error.
"""
data = dict(action='expand', shorturl=short)
jsondata = self._api_request(params=data)
return jsondata['longurl'] | 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
YOURLS API.
requests.exceptions.HTTPError: Generic HTTP error.
"""
data = dict(action='url-stats', shorturl=short)
jsondata = self._api_request(params=data)
return _json_to_shortened_url(jsondata['link']) | 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
"""
# Normalise random to rand, even though it's accepted by API.
if filter == 'random':
filter = 'rand'
valid_filters = ('top', 'bottom', 'rand', 'last')
if filter not in valid_filters:
msg = 'filter must be one of {}'.format(', '.join(valid_filters))
raise ValueError(msg)
data = dict(action='stats', filter=filter, limit=limit, start=start)
jsondata = self._api_request(params=data)
stats = DBStats(total_clicks=int(jsondata['stats']['total_clicks']),
total_links=int(jsondata['stats']['total_links']))
links = []
if 'links' in jsondata:
for i in range(1, limit + 1):
key = 'link_{}'.format(i)
links.append(_json_to_shortened_url(jsondata['links'][key]))
return links, stats | 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)
stats = DBStats(total_clicks=int(jsondata['db-stats']['total_clicks']),
total_links=int(jsondata['db-stats']['total_links']))
return stats | 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(
.. os.path.dirname(os.path.dirname(file_name))
.. )
.. )
.. [[[cog ste('build_docs.py -h', 0, mdir, cog.out) ]]]
.. code-block:: bash
$ ${PMISC_DIR}/pypkg/build_docs.py -h
usage: build_docs.py [-h] [-d DIRECTORY] [-n NUM_CPUS]
...
.. ]]]
"""
term_echo(
"${{PMISC_DIR}}{sep}pypkg{sep}{cmd}".format(sep=os.path.sep, cmd=command),
nindent,
{"PMISC_DIR": mdir},
fpointer,
) | 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():
command_int = command_int.replace("${" + var + "}", repl)
tokens = command_int.split(" ")
# Add Python interpreter executable for Python scripts on Windows since
# the shebang does not work
if (platform.system().lower() == "windows") and (tokens[0].endswith(".py")):
tokens = [sys.executable] + tokens
proc = subprocess.Popen(tokens, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = proc.communicate()[0]
if sys.hexversion >= 0x03000000:
stdout = stdout.decode("utf-8")
stdout = stdout.split("\n")
indent = nindent * " "
fpointer("\n", dedent=False)
fpointer("{0}.. code-block:: bash\n".format(indent), dedent=False)
fpointer("\n", dedent=False)
fpointer("{0} $ {1}\n".format(indent, command), dedent=False)
for line in stdout:
if line.strip():
fpointer(indent + " " + line.replace("\t", " ") + "\n", dedent=False)
else:
fpointer("\n", dedent=False)
fpointer("\n", dedent=False) | python | {
"resource": ""
} |
q274824 | Command.log | test | def log(self, msg, level=2):
"""
Small log helper
"""
if self.verbosity >= level:
self.stdout.write(msg) | 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:
return getattr(self, name)
except AttributeError:
val = method(self)
setattr(self, name, val)
return val
return wrapper | 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)
for chunk in iter(lambda: list(itertools.islice(iterator, chunksize)), []):
yield chunk | 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, yielding the value of each
function call as an iterator.
"""
@functools.wraps(func)
def wrapper(iterable, chunksize, *args, **kwargs):
for chunk in chunkiter(iterable, chunksize):
yield func(chunk, *args, **kwargs)
return wrapper | 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:
if isinstance(item, str) or not isinstance(item, abc.Iterable):
yield item
else:
yield from flatten(item, map2iter) | 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:
print(msg, file=sys.stderr)
sys.exit(1)
signal.signal(signal.SIGINT, handler) | python | {
"resource": ""
} |
q274830 | printtsv | test | def printtsv(table, sep="\t", file=sys.stdout):
"""stupidly print an iterable of iterables in TSV format"""
for record in table:
print(*record, sep=sep, file=file) | python | {
"resource": ""
} |
q274831 | mkdummy | test | def mkdummy(name, **attrs):
"""Make a placeholder object that uses its own name for its repr"""
return type(
name, (), dict(__repr__=(lambda self: "<%s>" % name), **attrs)
)() | 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:
num = int(num)
except ValueError:
num = float(num)
if bits:
num /= 8
return cls(round(num * divisor ** cls.key[c.lower()])) | 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
Configuration file format:
\b
[yourls]
apiurl = http://example.com/yourls-api.php
signature = abcdefghij
"""
if apiurl is None:
raise click.UsageError("apiurl missing. See 'yourls --help'")
auth_params = dict(signature=signature, username=username, password=password)
try:
ctx.obj = YOURLSClient(apiurl=apiurl, **auth_params)
except TypeError:
raise click.UsageError("authentication paremeters overspecified. "
"See 'yourls --help'") | 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__",)
return docs.support.trace_support.run_trace(
mname, fname, module_prefix, callable_names, no_print
) | 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(
".. _{name}: {url}\n".format(
name=fdict[item]["name"], url=fdict[item]["url"]
)
)
ret = []
for line in olines:
wobj = textwrap.wrap(line, width=LINE_WIDTH, subsequent_indent=" ")
ret.append("\n".join([item for item in wobj]))
mobj.out("\n".join(ret)) | 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 {pyver}.x{suffix}".format(pyver=pyver, suffix=suffix)
plist.append("{prefix}{ver}".format(prefix=prefix, ver=ops_to_words(req_ver))) | 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 = pyver[2] + "." + pyver[3:]
plist.append("Python {0}: {1}".format(pver, ops_to_words(ver_dict[pyver]))) | 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:
raise RuntimeError("Illegal comparison operator: {0}".format(op))
if len(list(set(actual_tokens))) != len(actual_tokens):
raise RuntimeError("Multiple comparison operators of the same type")
if "!=" in actual_tokens:
return (
" and ".join([op_to_words(token) for token in tokens[:-1]])
+ " "
+ op_to_words(tokens[-1])
)
return " and ".join([op_to_words(token) for token in tokens]) | python | {
"resource": ""
} |
q274839 | _chunk_noise | test | def _chunk_noise(noise):
"""Chunk input noise data into valid Touchstone file rows."""
data = zip(
noise["freq"],
noise["nf"],
np.abs(noise["rc"]),
np.angle(noise["rc"]),
noise["res"],
)
for freq, nf, rcmag, rcangle, res in data:
yield freq, nf, rcmag, rcangle, res | 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":
vector1 = np.abs(cdata)
vector2 = np.rad2deg(np.angle(cdata))
elif pformat == "RI":
vector1 = np.real(cdata)
vector2 = np.imag(cdata)
else: # elif pformat == 'DB':
vector1 = 20.0 * np.log10(np.abs(cdata))
vector2 = np.rad2deg(np.angle(cdata))
sep_data = np.array([])
for item1, item2 in zip(vector1, vector2):
sep_data = np.concatenate((sep_data, np.array([item1, item2])))
ret = np.concatenate((np.array(fpoint), sep_data))
yield ret | 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 not have a valid extension)
* RuntimeError (Malformed data)
* RuntimeError (Noise data only supported in two-port files)
.. [[[end]]]
"""
# pylint: disable=R0913
# Exceptions definitions
exnports = pexdoc.exh.addex(
RuntimeError, "File *[fname]* does not have a valid extension"
)
exnoise = pexdoc.exh.addex(
RuntimeError, "Noise data only supported in two-port files"
)
expoints = pexdoc.exh.addex(RuntimeError, "Malformed data")
# Data validation
_, ext = os.path.splitext(fname)
ext = ext.lower()
nports_regexp = re.compile(r"\.s(\d+)p")
match = nports_regexp.match(ext)
exnports(not match, edata={"field": "fname", "value": fname})
nports = int(match.groups()[0])
exnoise(bool((nports != 2) and noise))
nums_per_freq = nports ** 2
expoints(data["points"] * nums_per_freq != data["pars"].size)
#
npoints = data["points"]
par_data = np.resize(np.copy(data["pars"]), (npoints, nports, nports))
if nports == 2:
par_data = np.transpose(par_data, (0, 2, 1))
units_dict = {"ghz": "GHz", "mhz": "MHz", "khz": "KHz", "hz": "Hz"}
options["units"] = units_dict[options["units"].lower()]
fspace = 2 + frac_length + (exp_length + 2)
# Format data
with open(fname, "w") as fobj:
fobj.write(
"# {units} {ptype} {pformat} R {z0}\n".format(
units=options["units"],
ptype=options["ptype"],
pformat=options["pformat"],
z0=options["z0"],
)
)
for row in _chunk_pars(data["freq"], par_data, options["pformat"]):
row_data = [
to_scientific_string(item, frac_length, exp_length, bool(num != 0))
if item is not None
else fspace * " "
for num, item in enumerate(row)
]
fobj.write(" ".join(row_data) + "\n")
if (nports == 2) and noise:
fobj.write("! Noise data\n")
for row in _chunk_noise(noise):
row_data = [
to_scientific_string(item, frac_length, exp_length, bool(num != 0))
for num, item in enumerate(row)
]
fobj.write(" ".join(row_data) + "\n") | 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)
max_pos = np.searchsorted(indep_vector, indep_max)
if not np.isclose(indep_max, indep_vector[max_pos], FP_RTOL, FP_ATOL):
indep_vector = np.insert(indep_vector, max_pos, indep_max)
dep_vector = _interp_dep_vector(wave, indep_vector)
wave._indep_vector = indep_vector[min_pos : max_pos + 1]
wave._dep_vector = dep_vector[min_pos : max_pos + 1] | 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))
if op == "/"
else remove_extra_delims("({0})".format(indep_units))
)
return remove_extra_delims("({0}){1}({2})".format(dep_units, op, indep_units)) | python | {
"resource": ""
} |
q274844 | _operation | test | def _operation(wave, desc, units, fpointer):
"""Perform generic operation on a waveform object."""
ret = copy.copy(wave)
ret.dep_units = units
ret.dep_name = "{0}({1})".format(desc, ret.dep_name)
ret._dep_vector = fpointer(ret._dep_vector)
return 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))
triang_area = 0.5 * np.multiply(triang_height, rect_base)
return np.cumsum(np.concatenate((np.array([0.0]), triang_area + rect_area))) | 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(
RuntimeError, "Incongruent `indep_min` and `indep_max` arguments"
)
exmin = pexdoc.exh.addai("indep_min")
exmax = pexdoc.exh.addai("indep_max")
exminmax(bool(indep_min >= indep_max))
exmin(
bool(
(indep_min < wave._indep_vector[0])
and (not np.isclose(indep_min, wave._indep_vector[0], FP_RTOL, FP_ATOL))
)
)
exmax(
bool(
(indep_max > wave._indep_vector[-1])
and (not np.isclose(indep_max, wave._indep_vector[-1], FP_RTOL, FP_ATOL))
)
)
return indep_min, indep_max | 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 (Math domain error)
.. [[[end]]]
"""
pexdoc.exh.addex(
ValueError,
"Math domain error",
bool((min(wave._dep_vector) < -1) or (max(wave._dep_vector) > 1)),
)
return _operation(wave, "acos", "rad", np.arccos) | 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)
* ValueError (Math domain error)
.. [[[end]]]
"""
pexdoc.exh.addex(ValueError, "Math domain error", bool(min(wave._dep_vector) < 1))
return _operation(wave, "acosh", "", np.arccosh) | 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 domain error)
.. [[[end]]]
"""
pexdoc.exh.addex(
ValueError,
"Math domain error",
bool((min(wave._dep_vector) < -1) or (max(wave._dep_vector) > 1)),
)
return _operation(wave, "asin", "rad", np.arcsin) | 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)
* ValueError (Math domain error)
.. [[[end]]]
"""
pexdoc.exh.addex(
ValueError,
"Math domain error",
bool((min(wave._dep_vector) < -1) or (max(wave._dep_vector) > 1)),
)
return _operation(wave, "atanh", "", np.arctanh) | 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\`
arguments)
.. [[[end]]]
"""
ret = copy.copy(wave)
_bound_waveform(ret, indep_min, indep_max)
area = _running_area(ret._indep_vector, ret._dep_vector)
area[0] = ret._dep_vector[0]
deltas = ret._indep_vector - ret._indep_vector[0]
deltas[0] = 1.0
ret._dep_vector = np.divide(area, deltas)
ret.dep_name = "average({0})".format(ret._dep_name)
return ret | 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)
.. [[[end]]]
"""
pexdoc.exh.addex(
ValueError, "Math domain error", bool((np.min(np.abs(wave._dep_vector)) <= 0))
)
ret = copy.copy(wave)
ret.dep_units = "dB"
ret.dep_name = "db({0})".format(ret.dep_name)
ret._dep_vector = 20.0 * np.log10(np.abs(ret._dep_vector))
return ret | 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\`
arguments)
.. [[[end]]]
"""
ret = copy.copy(wave)
_bound_waveform(ret, indep_min, indep_max)
delta_indep = np.diff(ret._indep_vector)
delta_dep = np.diff(ret._dep_vector)
delta_indep = np.concatenate((np.array([delta_indep[0]]), delta_indep))
delta_dep = np.concatenate((np.array([delta_dep[0]]), delta_dep))
ret._dep_vector = np.divide(delta_dep, delta_indep)
ret.dep_name = "derivative({0})".format(ret._dep_name)
ret.dep_units = _build_units(ret.indep_units, ret.dep_units, "/")
return ret | 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
.. peng.wave_functions.ffti
:raises:
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`npoints\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\`
arguments)
* RuntimeError (Non-uniform sampling)
.. [[[end]]]
"""
return imag(fft(wave, npoints, indep_min, indep_max)) | 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
.. peng.wave_functions.fftm
:raises:
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`npoints\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\`
arguments)
* RuntimeError (Non-uniform sampling)
.. [[[end]]]
"""
return abs(fft(wave, npoints, indep_min, indep_max)) | 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 indep_max: integer or float
: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(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.fftp
:raises:
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`npoints\` is not valid)
* RuntimeError (Argument \`rad\` is not valid)
* RuntimeError (Argument \`unwrap\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\`
arguments)
* RuntimeError (Non-uniform sampling)
.. [[[end]]]
"""
return phase(fft(wave, npoints, indep_min, indep_max), unwrap=unwrap, rad=rad) | 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
.. peng.wave_functions.fftr
:raises:
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`npoints\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\`
arguments)
* RuntimeError (Non-uniform sampling)
.. [[[end]]]
"""
return real(fft(wave, npoints, indep_min, indep_max)) | 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`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.ifftdb
:raises:
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`npoints\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\`
arguments)
* RuntimeError (Non-uniform frequency spacing)
.. [[[end]]]
"""
return db(ifft(wave, npoints, indep_min, indep_max)) | 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
.. peng.wave_functions.iffti
:raises:
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`npoints\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\`
arguments)
* RuntimeError (Non-uniform frequency spacing)
.. [[[end]]]
"""
return imag(ifft(wave, npoints, indep_min, indep_max)) | 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
.. peng.wave_functions.ifftm
:raises:
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`npoints\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\`
arguments)
* RuntimeError (Non-uniform frequency spacing)
.. [[[end]]]
"""
return abs(ifft(wave, npoints, indep_min, indep_max)) | 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 indep_max: integer or float
: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(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.ifftp
:raises:
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`npoints\` is not valid)
* RuntimeError (Argument \`rad\` is not valid)
* RuntimeError (Argument \`unwrap\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\`
arguments)
* RuntimeError (Non-uniform frequency spacing)
.. [[[end]]]
"""
return phase(ifft(wave, npoints, indep_min, indep_max), unwrap=unwrap, rad=rad) | 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
.. peng.wave_functions.ifftr
:raises:
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`npoints\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\`
arguments)
* RuntimeError (Non-uniform frequency spacing)
.. [[[end]]]
"""
return real(ifft(wave, npoints, indep_min, indep_max)) | 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 not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\`
arguments)
.. [[[end]]]
"""
ret = copy.copy(wave)
_bound_waveform(ret, indep_min, indep_max)
ret._dep_vector = _running_area(ret._indep_vector, ret._dep_vector)
ret.dep_name = "integral({0})".format(ret._dep_name)
ret.dep_units = _build_units(ret.indep_units, ret.dep_units, "*")
return ret | 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)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.group_delay
:raises: RuntimeError (Argument \`wave\` is not valid)
.. [[[end]]]
"""
ret = -derivative(phase(wave, unwrap=True) / (2 * math.pi))
ret.dep_name = "group_delay({0})".format(wave.dep_name)
ret.dep_units = "sec"
return ret | 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)
* ValueError (Math domain error)
.. [[[end]]]
"""
pexdoc.exh.addex(
ValueError, "Math domain error", bool((min(wave._dep_vector) <= 0))
)
return _operation(wave, "log", "", np.log) | 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`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.naverage
: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\`
arguments)
.. [[[end]]]
"""
ret = copy.copy(wave)
_bound_waveform(ret, indep_min, indep_max)
delta_x = ret._indep_vector[-1] - ret._indep_vector[0]
return np.trapz(ret._dep_vector, x=ret._indep_vector) / delta_x | 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 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.nintegral
: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\`
arguments)
.. [[[end]]]
"""
ret = copy.copy(wave)
_bound_waveform(ret, indep_min, indep_max)
return np.trapz(ret._dep_vector, ret._indep_vector) | 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
: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\`
arguments)
.. [[[end]]]
"""
ret = copy.copy(wave)
_bound_waveform(ret, indep_min, indep_max)
return np.max(ret._dep_vector) | 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
: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\`
arguments)
.. [[[end]]]
"""
ret = copy.copy(wave)
_bound_waveform(ret, indep_min, indep_max)
return np.min(ret._dep_vector) | 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)
* RuntimeError (Argument \`wave\` is not valid)
.. [[[end]]]
"""
ret = copy.copy(wave)
ret.dep_units = "rad" if rad else "deg"
ret.dep_name = "phase({0})".format(ret.dep_name)
ret._dep_vector = (
np.unwrap(np.angle(ret._dep_vector)) if unwrap else np.angle(ret._dep_vector)
)
if not rad:
ret._dep_vector = np.rad2deg(ret._dep_vector)
return ret | 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(
TypeError,
"Cannot convert complex to integer",
wave._dep_vector.dtype.name.startswith("complex"),
)
ret = copy.copy(wave)
ret.dep_name = "round({0}, {1})".format(ret.dep_name, decimals)
ret._dep_vector = np.round(wave._dep_vector, decimals)
return ret | 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
:raises: RuntimeError (Argument \`wave\` is not valid)
.. [[[end]]]
"""
dep_units = "{0}**0.5".format(wave.dep_units)
return _operation(wave, "sqrt", dep_units, np.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 is not None:
ret.dep_name = dep_name
_bound_waveform(ret, indep_min, indep_max)
pexdoc.addai("indep_step", bool((indep_step is not None) and (indep_step <= 0)))
exmsg = "Argument `indep_step` is greater than independent vector range"
cond = bool(
(indep_step is not None)
and (indep_step > ret._indep_vector[-1] - ret._indep_vector[0])
)
pexdoc.addex(RuntimeError, exmsg, cond)
if indep_step:
indep_vector = _barange(indep_min, indep_max, indep_step)
dep_vector = _interp_dep_vector(ret, indep_vector)
ret._set_indep_vector(indep_vector, check=False)
ret._set_dep_vector(dep_vector, check=False)
return ret | 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
:raises: RuntimeError (Argument \`wave\` is not valid)
.. [[[end]]]
"""
ret = copy.copy(wave)
ret._dep_vector = ret._dep_vector.astype(np.complex)
return ret | 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 complex to float)
.. [[[end]]]
"""
pexdoc.exh.addex(
TypeError,
"Cannot convert complex to float",
wave._dep_vector.dtype.name.startswith("complex"),
)
ret = copy.copy(wave)
ret._dep_vector = ret._dep_vector.astype(np.float)
return ret | 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 complex to integer)
.. [[[end]]]
"""
pexdoc.exh.addex(
TypeError,
"Cannot convert complex to integer",
wave._dep_vector.dtype.name.startswith("complex"),
)
ret = copy.copy(wave)
ret._dep_vector = ret._dep_vector.astype(np.int)
return ret | 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)
* RuntimeError (Argument \`wave\` is not valid)
* ValueError (Argument \`indep_var\` is not in the independent
variable vector range)
.. [[[end]]]
"""
close_min = np.isclose(indep_var, wave._indep_vector[0], FP_RTOL, FP_ATOL)
close_max = np.isclose(indep_var, wave._indep_vector[-1], FP_RTOL, FP_ATOL)
pexdoc.exh.addex(
ValueError,
"Argument `indep_var` is not in the independent variable vector range",
bool(
((indep_var < wave._indep_vector[0]) and (not close_min))
or ((indep_var > wave._indep_vector[-1]) and (not close_max))
),
)
if close_min:
return wave._dep_vector[0]
if close_max:
return wave._dep_vector[-1]
idx = np.searchsorted(wave._indep_vector, indep_var)
xdelta = wave._indep_vector[idx] - wave._indep_vector[idx - 1]
ydelta = wave._dep_vector[idx] - wave._dep_vector[idx - 1]
slope = ydelta / float(xdelta)
return wave._dep_vector[idx - 1] + slope * (indep_var - wave._indep_vector[idx - 1]) | 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]
if not bits or bits[0] not in dirs_to_serve:
return []
return super(SystemFinder, self).find(path, all=all) | 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)
elif found and olines and (not line):
return (" ".join(olines).split(".")[0]).strip()
found = line == ".. [[[end]]]" if not found else found
return "" | 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 == 0:
stoken += _build_expr(item, oplevel, ldelim=ldelim, rdelim=rdelim)
else:
stoken += item
if (oplevel < higher_oplevel) or (
(oplevel == higher_oplevel) and (oplevel in _OP_PREC_PAR)
):
stoken = ldelim + stoken + rdelim
return stoken | 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:
raise RuntimeError("Mismatched delimiters")
del items[num]
return item | 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],
"expr": expr[lnum + 1 : rnum],
"start": lnum - cnum,
"stop": rnum,
}
)
if expr[lnum - cnum] not in alphas:
raise RuntimeError(
"Function name `{0}` is not valid".format(expr[lnum - cnum : lnum])
)
return tfuncs | 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 enumerate(expr) if item == rdelim]
# Pair remaining delimiters
return [(lpos, _next_rdelim(rindex, lpos)) for lpos in lindex][::-1] | 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),
(pyparsing.oneOf("+ -"), 2, pyparsing.opAssoc.LEFT),
(pyparsing.oneOf("<< >>"), 2, pyparsing.opAssoc.LEFT),
(pyparsing.Literal("&"), 2, pyparsing.opAssoc.LEFT),
(pyparsing.Literal("^"), 2, pyparsing.opAssoc.LEFT),
(pyparsing.Literal("|"), 2, pyparsing.opAssoc.LEFT),
]
# Get functions
expr = pyparsing.infixNotation(
atom, oplist, lpar=pyparsing.Suppress(ldelim), rpar=pyparsing.Suppress(rdelim)
)
return expr.parseString(text)[0] | 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)
ddelim.sort()
# Actually remove delimiters from expression
for num, item in enumerate(ddelim):
expr = expr[: item - num] + expr[item - num + 1 :]
# Get functions
return expr | 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
from the end of each list item (True) or not (False)
:type rstrip: boolean
:rtype: tuple
"""
ltr = "_rl "[2 * lstrip + rstrip].strip()
func = lambda x: getattr(x, ltr + "strip")() if ltr != "_" else x
items = text.split(sep)
groups = zip_longest(*[iter(items)] * count, fillvalue="")
joints = (sep.join(group).rstrip(sep) for group in groups)
return tuple(func(joint) for joint in joints) | 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
# at most 3 digits (say if number given is 1E4)
# + rstrip ensures that there is no empty fractional part
split = lambda x, p: (x.ljust(3 + neg, "0")[:p], x[p:].rstrip("0"))
# Convert number to scientific notation, a "constant" format
mant, exp = to_scientific_tuple(number)
mant, neg = mant.replace(".", ""), mant.startswith("-")
# New values
new_mant = ".".join(filter(None, split(mant, 1 + (exp % 3) + neg)))
new_exp = int(3 * math.floor(exp / 3))
return NumComp(new_mant, new_exp) | 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:
return "0." + "0" * (-exp - 1) + mant
if not floating_mant:
return mant + "0" * exp + (".0" if isinstance(number, float) else "")
lfpart = len(mant) - 1
if lfpart < exp:
return (mant + "0" * (exp - lfpart)).rstrip(".")
return mant | 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 a sign, a 3-digit integer part,
# a period, and a fractional part of length frac_length, so the
# length of the number to the left of, and including, the period is 5
return "{0} ".format(number.rjust(5 + frac_length)) if rjust else number
# Low-bound number
sign = +1 if number >= 0 else -1
ssign = "-" if sign == -1 else ""
anumber = abs(number)
if anumber < 1e-24:
anumber = 1e-24
number = sign * 1e-24
# Round fractional part if requested frac_length is less than length
# of fractional part. Rounding method is to add a '5' at the decimal
# position just after the end of frac_length digits
exp = 3.0 * math.floor(math.floor(math.log10(anumber)) / 3.0)
mant = number / 10 ** exp
# Because exponent is a float, mantissa is a float and its string
# representation always includes a period
smant = str(mant)
ppos = smant.find(".")
if len(smant) - ppos - 1 > frac_length:
mant += sign * 5 * 10 ** (-frac_length - 1)
if abs(mant) >= 1000:
exp += 3
mant = mant / 1e3
smant = str(mant)
ppos = smant.find(".")
# Make fractional part have frac_length digits
bfrac_length = bool(frac_length)
flength = ppos - (not bfrac_length) + frac_length + 1
new_mant = smant[:flength].ljust(flength, "0")
# Upper-bound number
if exp > 24:
new_mant, exp = (
"{sign}999.{frac}".format(sign=ssign, frac="9" * frac_length),
24,
)
# Right-justify number, engineering notation numbers can have a sign,
# a 3-digit integer part and a period, and a fractional part of length
# frac_length, so the length of the number to the left of the
# period is 4
new_mant = new_mant.rjust(rjust * (4 + bfrac_length + frac_length))
# Format number
num = "{mant}{suffix}".format(
mant=new_mant, suffix=_POWER_TO_SUFFIX_DICT[exp] if exp else " " * bool(rjust)
)
return num | 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 as peng_mant(snum)*(peng_power(snum)[1]), but the
# "function unrolling" is about 4x faster
snum = snum.rstrip()
power = _SUFFIX_POWER_DICT[" " if snum[-1].isdigit() else snum[-1]]
return float(snum if snum[-1].isdigit() else snum[:-1]) * power | 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:
>>> import peng
>>> peng.peng_frac(peng.peng(1235.6789E3, 3, False))
236
"""
snum = snum.rstrip()
pindex = snum.find(".")
if pindex == -1:
return 0
return int(snum[pindex + 1 :] if snum[-1].isdigit() else snum[pindex + 1 : -1]) | 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]]]
For example:
>>> import peng
>>> peng.peng_mant(peng.peng(1235.6789E3, 3, False))
1.236
"""
snum = snum.rstrip()
return float(snum if snum[-1].isdigit() else snum[:-1]) | 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()) ]]]
.. Auto-generated exceptions documentation for
.. peng.functions.peng_power
:raises: RuntimeError (Argument \`snum\` is not valid)
.. [[[end]]]
For example:
>>> import peng
>>> peng.peng_power(peng.peng(1235.6789E3, 3, False))
EngPower(suffix='M', exp=1000000.0)
"""
suffix = " " if snum[-1].isdigit() else snum[-1]
return EngPower(suffix, _SUFFIX_POWER_DICT[suffix]) | 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:
>>> import peng
>>> peng.peng_suffix_math('u', 6)
'T'
"""
# pylint: disable=W0212
eobj = pexdoc.exh.addex(ValueError, "Argument `offset` is not valid")
try:
return _POWER_TO_SUFFIX_DICT[_SUFFIX_TO_POWER_DICT[suffix] + 3 * offset]
except KeyError:
eobj(True) | 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):
raise RuntimeError("Argument `{0}` is not valid".format(desc))
if (len(ldelim) != 1) or ((len(ldelim) == 1) and (ldelim in op_group)):
raise RuntimeError("Argument `ldelim` is not valid")
if (len(rdelim) != 1) or ((len(rdelim) == 1) and (rdelim in op_group)):
raise RuntimeError("Argument `rdelim` is not valid")
if expr.count(ldelim) != expr.count(rdelim):
raise RuntimeError("Mismatched delimiters")
if not expr:
return expr
vchars = (
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
".0123456789"
r"_()[]\{\}" + rdelim + ldelim + op_group
)
if any([item not in vchars for item in expr]) or ("__" in expr):
raise RuntimeError("Argument `expr` is not valid")
expr = _remove_consecutive_delims(expr, ldelim=ldelim, rdelim=rdelim)
expr = expr.replace(ldelim + rdelim, "")
return _remove_extra_delims(expr, ldelim=ldelim, rdelim=rdelim) | 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 = 0 if not exp_length else exp_length
mant, exp = to_scientific_tuple(number)
fmant = float(mant)
if (not frac_length) or (fmant == int(fmant)):
return "{sign}{mant}{period}{zeros}E{exp_sign}{exp}".format(
sign="+" if sign_always and (fmant >= 0) else "",
mant=mant,
period="." if frac_length else "",
zeros="0" * frac_length if frac_length else "",
exp_sign="-" if exp < 0 else "+",
exp=str(abs(exp)).rjust(exp_length, "0"),
)
rounded_mant = round(fmant, frac_length)
# Avoid infinite recursion when rounded mantissa is _exactly_ 10
if abs(rounded_mant) == 10:
rounded_mant = fmant = -1.0 if number < 0 else 1.0
frac_length = 1
exp = exp + 1
zeros = 2 + (1 if (fmant < 0) else 0) + frac_length - len(str(rounded_mant))
return "{sign}{mant}{zeros}E{exp_sign}{exp}".format(
sign="+" if sign_always and (fmant >= 0) else "",
mant=rounded_mant,
zeros="0" * zeros,
exp_sign="-" if exp < 0 else "+",
exp=str(abs(exp)).rjust(exp_length, "0"),
) | 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)
"""
# pylint: disable=W0632
convert = not isinstance(number, str)
# Detect zero and return, simplifies subsequent algorithm
if (convert and (number == 0)) or (
(not convert) and (not number.strip("0").strip("."))
):
return ("0", 0)
# Break down number into its components, use Decimal type to
# preserve resolution:
# sign : 0 -> +, 1 -> -
# digits: tuple with digits of number
# exp : exponent that gives null fractional part
sign, digits, exp = Decimal(str(number) if convert else number).as_tuple()
mant = (
"{sign}{itg}{frac}".format(
sign="-" if sign else "",
itg=digits[0],
frac=(
".{frac}".format(frac="".join([str(num) for num in digits[1:]]))
if len(digits) > 1
else ""
),
)
.rstrip("0")
.rstrip(".")
)
exp += len(digits) - 1
return NumComp(mant, exp) | 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 bail out if we found the sourcemap comment
if SOURCEMAPPING_URL_COMMENT in content:
offset = 0
# splitlines eats the last \n if its followed by a blank line
lines = content.split(b'\n')
for i, line in enumerate(lines):
if line.startswith(SOURCEMAPPING_URL_COMMENT):
offset = len(line)
sourcemap = line
break
while i+1 < len(lines):
offset += 1 # for the newline char
offset += len(lines[i+1])
i += 1
# track back until the start of the comment, and truncate the comment
if sourcemap:
offset += 1 # for the newline before the sourcemap comment
of.seek(-offset, os.SEEK_END)
of.truncate()
return force_text(sourcemap)
finally:
of.close()
return sourcemap | 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:
name, ext = posixpath.splitext(self.app)
if not ext:
return True
return False | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.