code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
url = self.base_url + '/%s/resubmit' % str(job_id)
return self.put(url) | def resubmit(self, job_id) | Resubmits the given ``job_id``.
https://app.zencoder.com/docs/api/jobs/resubmit | 3.830128 | 4.305451 | 0.8896 |
if self.version == 'v1':
verb = self.get
else:
verb = self.put
url = self.base_url + '/%s/cancel' % str(job_id)
return verb(url) | def cancel(self, job_id) | Cancels the given ``job_id``.
https://app.zencoder.com/docs/api/jobs/cancel | 4.501625 | 4.894418 | 0.919747 |
data = self.__format(start_date, end_date)
url = self.base_url + '/minutes'
return self.get(url, data=data) | def minutes(self, start_date=None, end_date=None, grouping=None) | Gets a detailed Report of encoded minutes and billable minutes for a
date range.
**Warning**: ``start_date`` and ``end_date`` must be ``datetime.date`` objects.
Example::
import datetime
start = datetime.date(2012, 12, 31)
end = datetime.today()
... | 5.086203 | 6.707022 | 0.75834 |
def decorator(fn):
fn = describe(**kwargs)(fn)
transmute_func = TransmuteFunction(fn)
routes, handler = create_routes_and_handler(transmute_func, context)
for r in routes:
# push swagger info.
if not hasattr(app_or_blueprint, SWAGGER_ATTR_NAME):
... | def route(app_or_blueprint, context=default_context, **kwargs) | attach a transmute route. | 3.717078 | 3.442709 | 1.079696 |
'''
Stub an object. If attr is not None, will attempt to stub that
attribute on the object. Only required for modules and other rare
cases where we can't determine the binding from the object.
'''
s = stub(obj, attr)
if s not in self._stubs:
self._stub... | def stub(self, obj, attr=None) | Stub an object. If attr is not None, will attempt to stub that
attribute on the object. Only required for modules and other rare
cases where we can't determine the binding from the object. | 7.215816 | 2.187511 | 3.298642 |
'''
Return a mock object.
'''
rval = Mock(**kwargs)
if obj is not None and attr is not None:
rval._object = obj
rval._attr = attr
if hasattr(obj, attr):
orig = getattr(obj, attr)
self._mocks.append((obj, attr, o... | def mock(self, obj=None, attr=None, **kwargs) | Return a mock object. | 2.844505 | 2.690857 | 1.0571 |
errors = []
def flatten(error, path=""):
if isinstance(error, halogen.exceptions.ValidationError):
if not path.endswith("/"):
path += "/"
if error.attr is not None:
path += error.attr
elif error... | def from_validation_exception(cls, exception, **kwargs) | Create an error from validation exception. | 2.921638 | 2.824702 | 1.034317 |
try:
return yaml.load(raw_bytes)
except yaml.scanner.ScannerError as e:
raise SerializationException(str(e)) | def load(raw_bytes) | given a bytes object, should return a base python data
structure that represents the object. | 3.666821 | 3.400523 | 1.078311 |
if len(args) == 1:
fn = args[0]
elif len(args) == 3:
methods, paths, fn = args
fn = describe(methods=methods, paths=paths)(fn)
else:
raise ValueError(
"expected one or three arguments for add_transmute_route!"
)... | def add_transmute_route(self, *args) | two formats are accepted, for transmute routes. One allows
for a more traditional aiohttp syntax, while the other
allows for a flask-like variant.
.. code-block:: python
# if the path and method are not added in describe.
add_transmute_route("GET", "/route", fn)
... | 4.312891 | 3.855535 | 1.118623 |
# cattrs uses a Singledispatch like function
# under the hood.
f = self._cattrs_converter._structure_func.dispatch(cls)
return f != self._cattrs_converter._structure_default | def can_handle(self, cls) | this will theoretically be compatible with everything,
as cattrs can handle many basic types as well. | 15.938093 | 10.676134 | 1.492871 |
try:
return self._cattrs_converter.structure(value, model)
except (ValueError, TypeError) as e:
raise SerializationException(str(e)) | def load(self, model, value) | Converts unstructured data into structured data, recursively. | 7.989237 | 7.337708 | 1.088792 |
try:
return self._cattrs_converter.unstructure(value)
except (ValueError, TypeError) as e:
raise SerializationException(str(e)) | def dump(self, model, value) | Convert attrs data into unstructured data with basic types, recursively:
- attrs classes => dictionaries
- Enumeration => values
- Other types are let through without conversion,
such as, int, boolean, dict, other classes. | 7.028683 | 6.118838 | 1.148696 |
init_pos = fp.tell()
try:
sample = fp.read(
current_app.config.get('PREVIEWER_CHARDET_BYTES', 1024))
# Result contains 'confidence' and 'encoding'
result = cchardet.detect(sample)
threshold = current_app.config.get('PREVIEWER_CHARDET_CONFIDENCE', 0.9)
if ... | def detect_encoding(fp, default=None) | Detect the cahracter encoding of a file.
:param fp: Open Python file pointer.
:param default: Fallback encoding to use.
:returns: The detected encoding.
.. note:: The file pointer is returned at its original read position. | 3.208118 | 3.334774 | 0.96202 |
for validator in self.validators:
validator.validate(value, **kwargs)
return value | def deserialize(self, value, **kwargs) | Deserialization of value.
:return: Deserialized value.
:raises: :class:`halogen.exception.ValidationError` exception if value is not valid. | 5.332879 | 6.165674 | 0.86493 |
if isinstance(value, type):
return issubclass(value, Type)
return isinstance(value, Type) | def is_type(value) | Determine if value is an instance or subclass of the class Type. | 4.353897 | 2.954556 | 1.473621 |
return [self.item_type.serialize(val, **kwargs) for val in value] | def serialize(self, value, **kwargs) | Serialize every item of the list. | 5.400841 | 3.755193 | 1.438232 |
if self.allow_scalar and not isinstance(value, (list, tuple)):
value = [value]
value = super(List, self).deserialize(value)
result = []
errors = []
for index, val in enumerate(value):
try:
result.append(self.item_type.deserialize(... | def deserialize(self, value, **kwargs) | Deserialize every item of the list. | 2.45631 | 2.320861 | 1.058362 |
if isinstance(value, datetime.datetime):
if value.tzinfo is not None:
value = value.astimezone(pytz.UTC)
value = value.replace(microsecond=0)
return value.isoformat().replace('+00:00', 'Z') | def format_as_utc(self, value) | Format UTC times. | 2.129312 | 2.06725 | 1.030022 |
currency, amount = (
amount.as_quantized(digits=2).as_tuple()
if not isinstance(amount, dict)
else (amount["currency"], amount["amount"])
)
if currency not in self.currencies:
raise ValueError(self.err_unknown_currency.format(currency=curr... | def amount_object_to_dict(self, amount) | Return the dictionary representation of an Amount object.
Amount object must have amount and currency properties and as_tuple method which will return (currency, amount)
and as_quantized method to quantize amount property.
:param amount: instance of Amount object
:return: dict with am... | 3.632802 | 3.693232 | 0.983638 |
if value is None:
return None
if isinstance(value, six.string_types):
currency = value[:3]
amount = value[3:]
elif isinstance(value, dict):
if set(value.keys()) != set(("currency", "amount")):
raise ValueError("Amount obje... | def deserialize(self, value, **kwargs) | Deserialize the amount.
:param value: Amount in CURRENCYAMOUNT or {"currency": CURRENCY, "amount": AMOUNT} format. For example EUR35.50
or {"currency": "EUR", "amount": "35.50"}
:return: A paylogic Amount object.
:raises ValidationError: when amount can"t be deserialzied
:r... | 2.614743 | 2.413493 | 1.083385 |
try:
if not isinstance(raw_bytes, string_type):
raw_bytes = raw_bytes.decode()
return json.loads(raw_bytes)
except ValueError as e:
raise SerializationException(str(e)) | def load(raw_bytes) | given a bytes object, should return a base python data
structure that represents the object. | 2.955243 | 2.925522 | 1.010159 |
transmute_func = TransmuteFunction(
fn,
args_not_from_request=["request"]
)
handler = create_handler(transmute_func, context=context)
get_swagger_spec(app).add_func(transmute_func, context)
for p in transmute_func.paths:
aiohttp_path = _convert_to_aiohttp_path(p)
... | def add_route(app, fn, context=default_context) | a decorator that adds a transmute route to the application. | 4.542047 | 4.180024 | 1.086608 |
# Get file from record
fileobj = current_previewer.record_file_factory(
pid, record, request.view_args.get(
'filename', request.args.get('filename', type=str))
)
if not fileobj:
abort(404)
# Try to see if specific previewer is requested?
try:
file_previe... | def preview(pid, record, template=None, **kwargs) | Preview file for given record.
Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration:
.. code-block:: python
RECORDS_UI_ENDPOINTS = dict(
recid=dict(
# ...
route='/records/<pid_value/preview/<path:filename>',
view_imp='invenio_pr... | 3.766805 | 3.589477 | 1.049402 |
if template not in TEMPLATES:
raise ValueError("Template argument must be one of the followings: {}"
.format(", ".join(TEMPLATES)))
if target is not None and target not in TARGETS.keys():
raise ValueError("Target argument must be one of the followings: {}"
... | def new(template, target=None, name=None) | Function for creating a template script or tool.
:param template: template to be used ; one of TEMPLATES
:param target: type of script/tool to be created
:param name: name of the new script/tool | 3.316321 | 3.287184 | 1.008864 |
app.route(json_route)(create_swagger_json_handler(app, **kwargs))
add_swagger_api_route(app, html_route, json_route) | def add_swagger(app, json_route, html_route, **kwargs) | a convenience method for both adding a swagger.json route,
as well as adding a page showing the html documentation | 4.018682 | 4.106468 | 0.978623 |
static_root = get_swagger_static_root()
swagger_body = generate_swagger_html(
STATIC_ROOT, swagger_json_route
).encode("utf-8")
def swagger_ui():
return Response(swagger_body, content_type="text/html")
blueprint = Blueprint('swagger', __name__,
static... | def add_swagger_api_route(app, target_route, swagger_json_route) | mount a swagger statics page.
app: the flask app object
target_route: the path to mount the statics page.
swagger_json_route: the path where the swagger json definitions is
expected to be. | 3.049081 | 3.216304 | 0.948008 |
spec = getattr(app, SWAGGER_ATTR_NAME, SwaggerSpec())
_add_blueprint_specs(app, spec)
spec_dict = spec.swagger_definition(**kwargs)
encoded_spec = json.dumps(spec_dict).encode("UTF-8")
def swagger():
return Response(
encoded_spec,
# we allow CORS, so this can b... | def create_swagger_json_handler(app, **kwargs) | Create a handler that returns the swagger definition
for an application.
This method assumes the application is using the
TransmuteUrlDispatcher as the router. | 4.806405 | 4.81538 | 0.998136 |
temp_path = os.path.join(os.path.dirname(__file__), 'temp')
demo_files_path = os.path.join(os.path.dirname(__file__), 'demo_files')
# Create location
loc = Location(name='local', uri=temp_path, default=True)
db.session.add(loc)
db.session.commit()
# Example files from the data folder
... | def fixtures() | Command for working with test data. | 3.471784 | 3.464906 | 1.001985 |
with file.open() as fp:
encoding = detect_encoding(fp, default='utf-8')
result = mistune.markdown(fp.read().decode(encoding))
return result | def render(file) | Render HTML from Markdown file content. | 4.346399 | 4.621603 | 0.940453 |
try:
length = len(value)
except TypeError:
length = 0
if self.min_length is not None:
min_length = self.min_length() if callable(self.min_length) else self.min_length
if length < min_length:
raise exceptions.ValidationErro... | def validate(self, value) | Validate the length of a list.
:param value: List of values.
:raises: :class:`halogen.exception.ValidationError` exception when length of the list is less than
minimum or greater than maximum. | 1.696276 | 1.718068 | 0.987316 |
if self.min is not None:
min_value = self.min() if callable(self.min) else self.min
if value < min_value:
raise exceptions.ValidationError(self.min_err.format(val=value, min=min_value))
if self.max is not None:
max_value = self.max() if calla... | def validate(self, value) | Validate value.
:param value: Value which should be validated.
:raises: :class:`halogen.exception.ValidationError` exception when either if value less than min in case when
min is not None or if value greater than max in case when max is not None. | 1.70605 | 1.802149 | 0.946675 |
__parsers[proxy_parser] = real_parser
for method, safe, args, kwargs, proxy_subparser in proxy_parser.calls:
args = (__proxy_to_real_parser(v) for v in args)
kwargs = {k: __proxy_to_real_parser(v) for k, v in kwargs.items()}
real_subparser = getattr(real_parser, method)(*args, **kwa... | def __get_calls_from_parser(proxy_parser, real_parser) | This actually executes the calls registered in the ProxyArgumentParser.
:param proxy_parser: ProxyArgumentParser instance
:param real_parser: ArgumentParser instance | 2.833107 | 3.119922 | 0.90807 |
if isinstance(value, ProxyArgumentParser):
return __parsers[value]
elif any(isinstance(value, t) for t in [list, tuple]):
new_value = []
for subvalue in iter(value):
new_value.append(__proxy_to_real_parser(subvalue))
return new_value
return value | def __proxy_to_real_parser(value) | This recursively converts ProxyArgumentParser instances to actual parsers.
Use case: defining subparsers with a parent
>>> [...]
>>> parser.add_argument(...) # argument common to all subparsers
>>> subparsers = parser.add_subparsers()
>>> subparsers.add_parser(..., parents=[parent])
... | 3.269436 | 3.05814 | 1.069093 |
locals().update(glob) # allows to import user-defined objects from glob
# into the local scope
if glob['args'] is None or glob['logger'] is None:
return
exit_app = False
for check in arg_checks:
check = check + (None, ) * (4 - len(check))
param, ... | def validate(glob, *arg_checks) | Function for validating group of arguments ; each argument is represented as
a 4-tuple like follows:
(argument_name, fail_condition, error_message, default)
- argument_name: the name of the argument like entered in add_argument()
- fail_condition: condition in Python code with the argumen... | 4.207149 | 3.539879 | 1.188501 |
buf_ = x - xhat
np.square(buf_, out=buf_) # square in-place
sum_ = np.sum(buf_)
sum_ /= x.size # divide in-place
return sum_ | def mse(x, xhat) | Calcualte mse between vector or matrix x and xhat | 4.910779 | 5.059971 | 0.970515 |
try:
u, s, v = np.linalg.svd(A, full_matrices=False)
except np.linalg.LinAlgError as e:
print('Matrix:', A)
print('Matrix rank:', np.linalg.matrix_rank(A))
raise
Ar = np.zeros((len(u), len(v)), dtype=u.dtype)
buf_ = np.empty_like(Ar)
sc_vec_ = np.empty((v.shape[... | def low_rank_approximation(A, r) | Returns approximation of A of rank r in least-squares sense. | 2.881403 | 2.844695 | 1.012904 |
N = G.shape[0]
lamda, u = np.linalg.eig(G)
# test decomposition of G.
#G_hat = np.dot(np.dot(u, np.diag(lamda)), u.T)
#assert np.linalg.norm(G_hat - G) < 1e-10, 'decomposition not exact: err {}'.format(np.linalg.norm(G_hat - G))
# sort the eigenvalues in decreasing order
lamda = np.rea... | def eigendecomp(G, d) | Computes sorted eigendecomposition of G.
:param G: Matrix
:param d: rank
:return factor: vector of square root d of eigenvalues (biggest to smallest).
:return u: matrix with colums equal to the normalized eigenvectors corresponding to sorted eigenvalues. | 3.112028 | 3.051543 | 1.019821 |
A_pseudoinv = pseudo_inverse(A)
tmp_ = A.dot(x)
tmp_ -= b
x_hat = A_pseudoinv.dot(tmp_)
np.subtract(x, x_hat, out=x_hat)
cost = mse(x_hat, x)
A.dot(x_hat, out=tmp_)
constraints_error = mse(tmp_, b)
return x_hat, cost, constraints_error | def projection(x, A, b) | Returns the vector xhat closest to x in 2-norm, satisfying A.xhat =b.
:param x: vector
:param A, b: matrix and array characterizing the constraints on x (A.x = b)
:return x_hat: optimum angle vector, minimizing cost.
:return cost: least square error of xhat, x
:return constraints_error: mse of co... | 4.023836 | 3.29808 | 1.220054 |
'''
All of the comparators that can be used for arguments.
'''
comparators = []
for item in values_or_types:
if isinstance(item, Comparator):
comparators.append(item)
elif isinstance(item, type):
# If you are passing around a type you will have to build a Equa... | def build_comparators(*values_or_types) | All of the comparators that can be used for arguments. | 4.569099 | 3.489729 | 1.309299 |
build.packages.install("gitchangelog")
changelog_text = subprocess.check_output(["gitchangelog", "HEAD...v0.2.9"])
with open(os.path.join(build.root, "CHANGELOG"), "wb+") as fh:
fh.write(changelog_text) | def changelog(build) | create a changelog | 4.482615 | 4.192925 | 1.06909 |
self._any_args = False
self._arguments_rule.set_args(*args, **kwargs)
return self | def args(self, *args, **kwargs) | Creates a ArgumentsExpectationRule and adds it to the expectation | 9.712469 | 6.959831 | 1.395504 |
if self._raises:
# Handle exceptions
if inspect.isclass(self._raises):
raise self._raises()
else:
raise self._raises
else:
if isinstance(self._returns, tuple):
return tuple([x.value if isinstance(x, ... | def return_value(self) | Returns the value for this expectation or raises the proper exception. | 2.95782 | 2.826047 | 1.046628 |
return self._any_args or \
self._arguments_rule.validate(*args, **kwargs) | def match(self, *args, **kwargs) | Check the if these args match this expectation. | 21.405588 | 14.114262 | 1.516593 |
try:
get_distribution('invenio-records-files')
from invenio_records_files.utils import record_file_factory
default = record_file_factory
except DistributionNotFound:
def default(pid, record, filename):
return None
return l... | def record_file_factory(self) | Load default record file factory. | 4.710822 | 4.402397 | 1.070058 |
if name in self.previewers:
assert name not in self.previewers, \
"Previewer with same name already registered"
self.previewers[name] = previewer
if hasattr(previewer, 'previewable_extensions'):
self._previewable_extensions |= set(
... | def register_previewer(self, name, previewer) | Register a previewer in the system. | 3.02011 | 3.146765 | 0.959751 |
if self.entry_point_group is not None:
self.load_entry_point_group(self.entry_point_group)
self.entry_point_group = None
previewers = previewers or \
self.app.config.get('PREVIEWER_PREFERENCE', [])
for item in previewers:
if item in self... | def iter_previewers(self, previewers=None) | Get previewers ordered by PREVIEWER_PREVIEWERS_ORDER. | 3.430974 | 3.488821 | 0.983419 |
self.init_config(app)
app.register_blueprint(blueprint)
state = _InvenioPreviewerState(
app,
entry_point_group=entry_point_group)
app.extensions['invenio-previewer'] = state
return state | def init_app(self, app, entry_point_group='invenio_previewer.previewers') | Flask application initialization. | 3.062964 | 2.878713 | 1.064004 |
self.validate_packet(data)
id_ = self.dump_hex(data[4:6])
# channel = data[5] TBC
humidity = data[6]
humidity_status = self._extract_humidity_status(data[7])
sensor_specific = {
'id': id_,
# 'channel': channel, TBC
'humidit... | def parse(self, data) | Parse a 9 bytes packet in the Humidity format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 8,
'packet_type': 81,
... | 5.575874 | 4.755991 | 1.172389 |
if name not in self.factories:
raise KeyError(Errors.E002.format(name=name))
factory = self.factories[name]
return factory(self, **config) | def create_tokenizer(self, name, config=dict()) | Create a pipeline component from a factory.
name (unicode): Factory name to look up in `Language.factories`.
config (dict): Configuration parameters to initialise component.
RETURNS (callable): Pipeline component. | 3.738769 | 3.803821 | 0.982898 |
class ErrorsWithCodes(object):
def __getattribute__(self, code):
msg = getattr(err_cls, code)
return '[{code}] {msg}'.format(code=code, msg=msg)
return ErrorsWithCodes() | def add_codes(err_cls) | Add error codes to string messages via class attribute names. | 3.741616 | 3.13654 | 1.192912 |
w_id = message.split('[', 1)[1].split(']', 1)[0] # get ID from string
if warn_type in SPACY_WARNING_TYPES and w_id not in SPACY_WARNING_IGNORE:
category = WARNINGS[warn_type]
stack = inspect.stack()[-1]
with warnings.catch_warnings():
if SPACY_WARNING_FILTER:
... | def _warn(message, warn_type='user') | message (unicode): The message to display.
category (Warning): The Warning to show. | 4.012228 | 3.786445 | 1.059629 |
if model is None:
model = about.__default_corpus__
if direct:
dl = download_model('{m}/{m}.tar.gz#egg={m}'.format(m=model), pip_args)
else:
shortcuts = get_json(about.__shortcuts__, "available shortcuts")
model_name = shortcuts.get(model, model)
compatibility = ... | def download(model=None, direct=False, *pip_args) | Download compatible model from default download path using pip. Model
can be shortcut, model name or, if --direct flag is set, full model name
with version. | 6.062151 | 6.026377 | 1.005936 |
if util.is_package(origin):
model_path = util.get_package_path(origin)
else:
model_path = Path(origin) if model_path is None else Path(model_path)
if not model_path.exists():
prints(Messages.M009.format(path=path2str(model_path)),
title=Messages.M008, exits=1)
... | def link(origin, link_name, force=False, model_path=None) | Create a symlink for models within the spacy/data directory. Accepts
either the name of a pip package, or the local path to the model data
directory. Linking models allows loading them via spacy.load(link_name). | 3.271638 | 3.171528 | 1.031565 |
from .tokenizer_loader import TokenizerLoader
if not meta:
meta = get_model_meta(model_path)
tokenizer_loader = TokenizerLoader(meta=meta, **overrides)
tokenizers = meta.get('tokenizers', [])
disable = overrides.get('disable', [])
if tokenizers is True:
tokenizers = Tokeniz... | def load_model_from_path(model_path, meta=False, **overrides) | Load a model from a data directory path. Creates Language class with
pipeline from meta.json and then calls from_disk() with path. | 3.197779 | 2.926739 | 1.092608 |
name = name.lower() # compare package name against lowercase name
packages = pkg_resources.working_set.by_key.keys()
for package in packages:
if package.lower().replace('-', '_') == name:
return True
return False | def is_package(name) | Check if string maps to a package installed via pip.
name (unicode): Name of package.
RETURNS (bool): True if installed package, False if not. | 3.789176 | 4.390295 | 0.86308 |
def clip(value):
return max(value, stop) if (start > stop) else min(value, stop)
nr_upd = 1.
while True:
yield clip(start * 1./(1. + decay * nr_upd))
nr_upd += 1 | def decaying(start, stop, decay) | Yield an infinite series of linearly decaying values. | 4.633789 | 4.767657 | 0.971921 |
location = ensure_path(location)
with location.open('r', encoding='utf8') as f:
return ujson.load(f) | def read_json(location) | Open and load JSON from file.
location (Path): Path to JSON file.
RETURNS (dict): Loaded JSON content. | 3.724319 | 5.799603 | 0.642168 |
additional = ' (default: %s)' % default if default else ''
prompt = ' %s%s: ' % (description, additional)
user_input = input_(prompt)
return user_input | def get_raw_input(description, default=False) | Get user input from the command line via raw_input / input.
description (unicode): Text to display before prompt.
default (unicode or False/None): Default value to display with prompt.
RETURNS (unicode): User input. | 3.751922 | 4.79555 | 0.782376 |
if isinstance(data, dict):
data = list(data.items())
tpl_row = ' {:<15}' * len(data[0])
table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data])
if title:
print('\n \033[93m{}\033[0m'.format(title))
print('\n{}\n'.format(table)) | def print_table(data, title=None) | Print data in table format.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be printed above. | 3.321593 | 3.355445 | 0.989911 |
def excl_value(value):
# contains path, i.e. personal info
return isinstance(value, basestring_) and Path(value).exists()
if isinstance(data, dict):
data = list(data.items())
markdown = ["* **{}:** {}".format(l, unicode_(v))
for l, v in data if not excl_value(v)... | def print_markdown(data, title=None) | Print data in GitHub-flavoured Markdown format for issues etc.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be rendered as headline 2. | 6.068354 | 5.769735 | 1.051756 |
exits = kwargs.get('exits', None)
title = kwargs.get('title', None)
title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else ''
message = '\n\n'.join([_wrap(text) for text in texts])
print('\n{}{}\n'.format(title, message))
if exits is not None:
sys.exit(exits) | def prints(*texts, **kwargs) | Print formatted message (manual ANSI escape sequences to avoid
dependency)
*texts (unicode): Texts to print. Each argument is rendered as paragraph.
**kwargs: 'title' becomes coloured headline. exits=True performs sys exit. | 2.760792 | 2.593373 | 1.064557 |
indent = indent * ' '
wrap_width = wrap_max - len(indent)
if isinstance(text, Path):
text = path2str(text)
return textwrap.fill(text, width=wrap_width, initial_indent=indent,
subsequent_indent=indent, break_long_words=False,
break_on_hyphens... | def _wrap(text, wrap_max=80, indent=4) | Wrap text at given width using textwrap module.
text (unicode): Text to wrap. If it's a Path, it's converted to string.
wrap_max (int): Maximum line length (indent is deducted).
indent (int): Number of spaces for indentation.
RETURNS (unicode): Wrapped text. | 2.439053 | 2.382745 | 1.023631 |
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
text = text.replace('"', '"')
return text | def escape_html(text) | Replace <, >, &, " with their HTML encoded representation. Intended to
prevent HTML errors in rendered displaCy markup.
text (unicode): The original text.
RETURNS (unicode): Equivalent text to be safely used within HTML. | 1.474661 | 1.92775 | 0.764965 |
new = {}
for key, value in old.items():
if isinstance(key, bytes_):
new[key.decode('utf8')] = value
else:
new[key] = value
return new | def normalize_string_keys(old) | Given a dictionary, make sure keys are unicode strings, not bytes. | 2.31783 | 2.050537 | 1.130353 |
'''
Mangle non-supported characters, for savages with ascii terminals.
'''
encoding = locale.getpreferredencoding()
string = string.encode(encoding, errors).decode('utf8')
return string | def locale_escape(string, errors='replace') | Mangle non-supported characters, for savages with ascii terminals. | 11.359653 | 3.338427 | 3.402696 |
pronunciations = list()
for line in cmufh:
line = line.strip().decode('utf-8')
if line.startswith(';'):
continue
word, phones = line.split(" ", 1)
pronunciations.append((word.split('(', 1)[0].lower(), phones))
return pronunciations | def parse_cmu(cmufh) | Parses an incoming file handle as a CMU pronouncing dictionary file.
(Most end-users of this module won't need to call this function explicitly,
as it's called internally by the :func:`init_cmu` function.)
:param cmufh: a filehandle with CMUdict-formatted data
:returns: a list of 2-tuples pairing a wo... | 2.74857 | 2.919045 | 0.941599 |
global pronunciations, lookup, rhyme_lookup
if pronunciations is None:
if filehandle is None:
filehandle = cmudict.dict_stream()
pronunciations = parse_cmu(filehandle)
filehandle.close()
lookup = collections.defaultdict(list)
for word, phones in pronuncia... | def init_cmu(filehandle=None) | Initialize the module's pronunciation data.
This function is called automatically the first time you attempt to use
another function in the library that requires loading the pronunciation
data from disk. You can call this function manually to control when and
how the pronunciation data is loaded (e.g.,... | 2.454376 | 2.680912 | 0.915501 |
phones_list = phones.split()
for i in range(len(phones_list) - 1, 0, -1):
if phones_list[i][-1] in '12':
return ' '.join(phones_list[i:])
return phones | def rhyming_part(phones) | Get the "rhyming part" of a string with CMUdict phones.
"Rhyming part" here means everything from the vowel in the stressed
syllable nearest the end of the word up to the end of the word.
.. doctest::
>>> import pronouncing
>>> phones = pronouncing.phones_for_word("purple")
>>> pr... | 2.441521 | 2.828225 | 0.86327 |
init_cmu()
regexp = re.compile(r"\b" + pattern + r"\b")
return [word
for word, phones in pronunciations
if regexp.search(phones)] | def search(pattern) | Get words whose pronunciation matches a regular expression.
This function Searches the CMU dictionary for pronunciations matching a
given regular expression. (Word boundary anchors are automatically added
before and after the pattern.)
.. doctest::
>>> import pronouncing
>>> 'interpol... | 7.001295 | 6.097569 | 1.148211 |
init_cmu()
regexp = re.compile(pattern)
return [word
for word, phones in pronunciations
if regexp.search(stresses(phones))] | def search_stresses(pattern) | Get words whose stress pattern matches a regular expression.
This function is a special case of :func:`search` that searches only the
stress patterns of each pronunciation in the dictionary. You can get
stress patterns for a word using the :func:`stresses_for_word` function.
.. doctest::
>>> ... | 10.619735 | 9.626386 | 1.10319 |
phones = phones_for_word(word)
combined_rhymes = []
if phones:
for element in phones:
combined_rhymes.append([w for w in rhyme_lookup.get(rhyming_part(
element), []) if w != word])
combined_rhymes = list(chain.from_iterable(combined_rhymes... | def rhymes(word) | Get words rhyming with a given word.
This function may return an empty list if no rhyming words are found in
the dictionary, or if the word you pass to the function is itself not
found in the dictionary.
.. doctest::
>>> import pronouncing
>>> pronouncing.rhymes("conditioner")
... | 3.1585 | 3.544275 | 0.891156 |
self.set_zoom()
ds9_settings = config.read("DS9."+level)
for key in ds9_settings.keys():
value = ds9_settings[key]
cmd = key.replace("_", " ")
self.ds9.set("{} {}".format(cmd, value)) | def set_ds9(self, level="PREF") | Set the default values on the ds9 display. | 4.191242 | 4.123302 | 1.016477 |
radius = min(90, max(width, height) / 2.0)
query = ("SELECT "
"COORD1(CENTROID(Plane.position_bounds)) AS RAJ2000,"
"COORD2(CENTROID(Plane.position_bounds)) AS DEJ2000,"
"target_name "
"FROM "
"caom2.Observation as o "
"JOIN ca... | def cfht_megacam_tap_query(ra_deg=180.0, dec_deg=0.0, width=1, height=1, date=None) | Do a query of the CADC Megacam table.
Get all observations inside the box (right now it turns width/height into a radius, should not do this).
@rtype : Table
@param ra_deg: center of search region, in degrees
@param dec_deg: center of search region in degrees
@param width: width of search region i... | 4.191406 | 4.438393 | 0.944352 |
msg = 'scale and array size must match, ' \
'but were scale: {self.scale.n_bands}, array size: {size}'
if size != len(self.scale):
raise ValueError(msg.format(**locals())) | def validate(self, size) | Ensure that the size of the dimension matches the number of bands in the
scale
Raises:
ValueError: when the dimension size and number of bands don't match | 9.319243 | 7.285977 | 1.279066 |
class Resampled(BaseModel):
meta = JSONFeature(
MetaData,
store=True,
encoder=AudioMetaDataEncoder)
raw = ByteStreamFeature(
ByteStream,
chunksize=chunksize_bytes,
needs=meta,
store=False)
ogg = OggVo... | def resampled(
chunksize_bytes=DEFAULT_CHUNK_SIZE,
resample_to=SR44100(),
store_resampled=False) | Create a basic processing pipeline that can resample all incoming audio
to a normalized sampling rate for downstream processing, and store a
convenient, compressed version for playback
:param chunksize_bytes: The number of bytes from the raw stream to process
at once
:param resample_to: The new, no... | 4.03288 | 4.320773 | 0.93337 |
band = FrequencyBand(20, resample_to.nyquist)
class AudioGraph(BaseModel):
meta = JSONFeature(
MetaData,
store=True,
encoder=AudioMetaDataEncoder)
raw = ByteStreamFeature(
ByteStream,
chunksize=chunksize_bytes,
needs... | def audio_graph(
chunksize_bytes=DEFAULT_CHUNK_SIZE,
resample_to=SR44100(),
store_fft=False) | Produce a base class suitable as a starting point for many audio processing
pipelines. This class resamples all audio to a common sampling rate, and
produces a bark band spectrogram from overlapping short-time fourier
transform frames. It also compresses the audio into ogg vorbis format for
compact st... | 3.090024 | 3.124878 | 0.988846 |
class Onsets(BaseModel):
onset_prep = ArrayWithUnitsFeature(
SlidingWindow,
needs=fft_feature,
wscheme=HalfLapped() * Stride(frequency=1, duration=3),
store=False)
complex_domain = ArrayWithUnitsFeature(
ComplexDomain,
ne... | def with_onsets(fft_feature) | Produce a mixin class that extracts onsets
:param fft_feature: The short-time fourier transform feature
:return: A mixin class that extracts onsets | 6.453691 | 6.507323 | 0.991758 |
seps = {'dra': 0., 'ddec': 0.}
for kbo in kbos:
ra = kbo.ra
dec = kbo.dec
kbo.compute(date)
seps['dra'] += kbo.ra - ra
seps['ddec'] += kbo.dec - dec
seps['dra'] /= float(len(kbos))
seps['ddec'] /= float(len(kbos))
print date, seps, len(kbos)
for id... | def keplerian_sheared_field_locations(ax, kbos, date, ras, decs, names, elongation=False, plot=False) | Shift fields from the discovery set to the requested date by the average motion of L7 kbos in the discovery field.
:param ras:
:param decs:
:param plot:
:param ax:
:param kbos: precomputed at the discovery date for that block. e.g. Oct new moon for 13B
:param date:
:param names:
:param e... | 2.505895 | 2.531316 | 0.989958 |
sun = ephem.Sun()
sun.compute(date)
sep = ephem.separation((ra, dec), sun)
retval = 180. - math.degrees(sep)
return retval | def field_elongation(ra, dec, date) | For a given field, calculate the solar elongation at the given date.
:param ra: field's right ascension. unit="h" format="RAh:RAm:RAs"
:param dec: field's declination. degrees
:param date: date at which to calculate elongation
:return: elongation from the Sun in degrees | 3.970578 | 4.776763 | 0.831228 |
def timedelta_kwargs(data: DictStrInt) -> DictStrInt:
seconds = data.get('seconds', 0)
seconds += data.get('day_hours', 0) * 3600
seconds += data.pop('hour_minutes', 0) * 60
seconds += data.pop('minute_seconds', 0)
seconds += data.pop('week_days', 0) * SECONDS_P... | def str_to_timedelta(value: str,
fmt: str = None) -> Optional[datetime.timedelta] | Convert string value to timedelta instance according to the given format.
If format not set function tries to load timedelta using default
``TIMEDELTA_FORMAT`` and then both of magic "full" formats.
You should also specify list of formats and function tries to convert
to timedelta using each of format... | 2.716321 | 2.677222 | 1.014604 |
r
if isinstance(values[0], (list, tuple)):
values = values[0]
return sum(values, datetime.timedelta()) // len(values) | def timedelta_average(*values: datetime.timedelta) -> datetime.timedelta | r"""Compute the arithmetic mean for timedeltas list.
:param \*values: Timedelta instances to process. | 4.782449 | 5.496922 | 0.870023 |
first_seconds = timedelta_seconds(first)
second_seconds = timedelta_seconds(second)
if not second_seconds:
return None
return first_seconds / second_seconds | def timedelta_div(first: datetime.timedelta,
second: datetime.timedelta) -> Optional[float] | Implement divison for timedelta instances.
:param first: First timedelta instance.
:param second: Second timedelta instance. | 2.461768 | 3.481646 | 0.70707 |
return SECONDS_PER_DAY * value.days + value.seconds | def timedelta_seconds(value: datetime.timedelta) -> int | Return full number of seconds from timedelta.
By default, Python returns only one day seconds, not all timedelta seconds.
:param value: Timedelta instance. | 7.339242 | 10.020985 | 0.732387 |
if self.func is None:
return random.uniform(self.min, self.max)
if self._dist is None:
x = numpy.arange(self.min, self.max, (self.max-self.min)/1000.0)
p = self.func(x).cumsum()
p -= p.min()
p /= p.max()
self._dist = interp... | def dist(self) | How should the values in range be sampled, uniformly or via some function.
:return: | 2.59136 | 2.568457 | 1.008917 |
# x y mag pix rate angle ''/h rate id
# 912.48 991.06 22.01 57.32 -45.23 10.60 0
self._n -= 1
if self._n < 0:
raise StopIteration()
return {'x': self.x(), 'y': self.y(), 'mag': self.mag(), 'sky_ra... | def next(self) | :return: a set of values that can be used for an planted object builder. | 8.710383 | 8.516628 | 1.02275 |
'''
Send command to foscam.
'''
paramstr = ''
if params:
paramstr = urlencode(params)
paramstr = '&' + paramstr if paramstr else ''
cmdurl = 'http://%s/cgi-bin/CGIProxy.fcgi?usr=%s&pwd=%s&cmd=%s%s' % (
... | def send_command(self, cmd, params=None, raw=False) | Send command to foscam. | 3.001226 | 2.921981 | 1.02712 |
'''
Execute a command and return a parsed response.
'''
def execute_with_callbacks(cmd, params=None, callback=None, raw=False):
code, params = self.send_command(cmd, params, raw)
if callback:
callback(code, params)
return code, params
... | def execute_command(self, cmd, params=None, callback=None, raw=False) | Execute a command and return a parsed response. | 2.528801 | 2.376543 | 1.064067 |
'''
isDHCP: 0(False), 1(True)
System will reboot automatically to take effect after call this CGI command.
'''
params = {'isDHCP': is_dhcp,
'ip': ip,
'gate': gate,
'mask': mask,
'dns1': dns1,
... | def set_ip_info(self, is_dhcp, ip='', gate='', mask='',
dns1='', dns2='', callback=None) | isDHCP: 0(False), 1(True)
System will reboot automatically to take effect after call this CGI command. | 4.430581 | 2.06903 | 2.141381 |
'''
Set http port and media port of camera.
'''
params = {'webPort' : webport,
'mediaPort' : mediaport,
'httpsPort' : httpsport,
'onvifPort' : onvifport,
}
return self.execute_command('setPortInfo', params, ... | def set_port_info(self, webport, mediaport, httpsport,
onvifport, callback=None) | Set http port and media port of camera. | 3.170069 | 2.356819 | 1.345063 |
'''
Get the aps around after refreshWifiList.
Note: Only 10 aps will be returned one time.
'''
params = {'startNo': startno}
return self.execute_command('getWifiList', params, callback=callback) | def get_wifi_list(self, startno, callback=None) | Get the aps around after refreshWifiList.
Note: Only 10 aps will be returned one time. | 10.079037 | 2.594261 | 3.885128 |
'''
Set wifi config.
Camera will not connect to AP unless you enject your cable.
'''
params = {'isEnable' : isenable,
'isUseWifi' : isusewifi,
'ssid' : ssid,
'netType' : nettype,
'encryptType': en... | def set_wifi_setting(self, ssid, psk, isenable, isusewifi, nettype,
encryptype, authmode, keyformat, defaultkey,
key1='', key2='', key3='', key4='',
key1len=64, key2len=64, key3len=64, key4len=64,
callback=No... | Set wifi config.
Camera will not connect to AP unless you enject your cable. | 2.038578 | 1.516909 | 1.343902 |
'''
Set UPnP config
'''
params = {'isEnable': isenable}
return self.execute_command('setUPnPConfig', params, callback=callback) | def set_upnp_config(self, isenable, callback=None) | Set UPnP config | 4.80841 | 3.873582 | 1.241334 |
'''
Set DDNS config.
'''
params = {'isEnable': isenable,
'hostName': hostname,
'ddnsServer': ddnsserver,
'user': user,
'password': password,
}
return self.execute_command('setDDNSConfig', par... | def set_ddns_config(self, isenable, hostname, ddnsserver,
user, password, callback=None) | Set DDNS config. | 2.623562 | 2.43011 | 1.079606 |
'''
Set the stream fromat of sub stream.
Supported format: (1) H264 : 0
(2) MotionJpeg 1
'''
params = {'format': format}
return self.execute_command('setSubVideoStreamType',
params, callback=callback) | def set_sub_video_stream_type(self, format, callback=None) | Set the stream fromat of sub stream.
Supported format: (1) H264 : 0
(2) MotionJpeg 1 | 10.228519 | 3.048554 | 3.355203 |
'''
Set the stream fromat of sub stream????
'''
params = {'format': format}
return self.execute_command('setSubStreamFormat',
params, callback=callback) | def set_sub_stream_format(self, format, callback=None) | Set the stream fromat of sub stream???? | 11.784999 | 4.575273 | 2.575802 |
'''
Set the stream type of main stream
'''
params = {'streamType': streamtype}
return self.execute_command('setMainVideoStreamType',
params, callback=callback) | def set_main_video_stream_type(self, streamtype, callback=None) | Set the stream type of main stream | 5.218417 | 4.192949 | 1.244569 |
'''
Set the video stream param of stream N
streamtype(0~3): Stream N.
resolution(0~4): 0 720P,
1 VGA(640*480),
2 VGA(640*360),
3 QVGA(320*240),
4 QVGA(320*180).
bitrate: Bit rate o... | def set_video_stream_param(self, streamtype, resolution, bitrate,
framerate, gop, isvbr, callback=None) | Set the video stream param of stream N
streamtype(0~3): Stream N.
resolution(0~4): 0 720P,
1 VGA(640*480),
2 VGA(640*360),
3 QVGA(320*240),
4 QVGA(320*180).
bitrate: Bit rate of stream type N(2048... | 4.209852 | 1.442949 | 2.917533 |
'''
Mirror video
``is_mirror``: 0 not mirror, 1 mirror
'''
params = {'isMirror': is_mirror}
return self.execute_command('mirrorVideo', params, callback=callback) | def mirror_video(self, is_mirror, callback=None) | Mirror video
``is_mirror``: 0 not mirror, 1 mirror | 5.799059 | 3.311366 | 1.751259 |
'''
Flip video
``is_flip``: 0 Not flip, 1 Flip
'''
params = {'isFlip': is_flip }
return self.execute_command('flipVideo', params, callback=callback) | def flip_video(self, is_flip, callback=None) | Flip video
``is_flip``: 0 Not flip, 1 Flip | 6.215559 | 3.849514 | 1.614635 |
'''
Change user name.
'''
params = {'usrName': usrname,
'newUsrName': newusrname,
}
return self.execute_command('changeUserName', params, callback=callback) | def change_user_name(self, usrname, newusrname, callback=None) | Change user name. | 3.674042 | 3.578819 | 1.026608 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.