text stringlengths 18 773k |
|---|
def iterativeEMDS(X0, N, d, C, b, max_it=10, print_out=False, **kwargs):
""" Find the set of points from an edge kernel with geometric constraints, using iterative projection
"""
from pylocus.basics import mse, projection
KE = kwargs.get('KE', None)
KE_projected = KE.copy()
d = len(X0)
for ... |
def relaxedEMDS(X0, N, d, C, b, KE, print_out=False, lamda=10):
""" Find the set of points from an edge kernel with geometric constraints, using convex rank relaxation.
"""
E = C.shape[1]
X = Variable((E, E), PSD=True)
constraints = [C[i, :] * X == b[i] for i in range(C.shape[0])]
obj = Minimi... |
def signedMDS(cdm, W=None):
""" Find the set of points from a cdm.
"""
N = cdm.shape[0]
D_sym = (cdm - cdm.T)
D_sym /= 2
if W is None:
x_est = np.mean(D_sym, axis=1)
x_est -= np.min(x_est)
return x_est
W_sub = W[1:, 1:]
sum_W = np.sum(W[1:, :], axis=1)
# ... |
def _stub_attr(obj, attr_name):
'''
Stub an attribute of an object. Will return an existing stub if
there already is one.
'''
# Annoying circular reference requires importing here. Would like to see
# this cleaned up. @AW
from .mock import Mock
# Check to see if this a property, this ch... |
def _stub_obj(obj):
'''
Stub an object directly.
'''
# Annoying circular reference requires importing here. Would like to see
# this cleaned up. @AW
from .mock import Mock
# Return an existing stub
if isinstance(obj, Stub):
return obj
# If a Mock object, stub its __call__
... |
def unmet_expectations(self):
'''
Assert that all expectations on the stub have been met.
'''
unmet = []
for exp in self._expectations:
if not exp.closed(with_counts=True):
unmet.append(ExpectationNotSatisfied(exp))
return unmet |
def teardown(self):
'''
Clean up all expectations and restore the original attribute of the
mocked object.
'''
if not self._torn:
self._expectations = []
self._torn = True
self._teardown() |
def expect(self):
'''
Add an expectation to this stub. Return the expectation.
'''
exp = Expectation(self)
self._expectations.append(exp)
return exp |
def spy(self):
'''
Add a spy to this stub. Return the spy.
'''
spy = Spy(self)
self._expectations.append(spy)
return spy |
def call_orig(self, *args, **kwargs):
'''
Calls the original function.
'''
if hasattr(self._obj, '__self__') and \
inspect.isclass(self._obj.__self__) and \
self._obj.__self__ is self._instance:
return self._obj.__func__(self._instance, *args, ... |
def _teardown(self):
'''
Put the original method back in place. This will also handle the
special case when it putting back a class method.
The following code snippet best describe why it fails using settar,
the class method would be replaced with a bound method not a class
... |
def _teardown(self):
'''
Replace the original method.
'''
if not self._was_object_method:
setattr(self._instance, self._attr, self._obj)
else:
delattr(self._instance, self._attr) |
def call_orig(self, *args, **kwargs):
'''
Calls the original function. Simulates __new__ and __init__ together.
'''
rval = super(StubNew, self).call_orig(self._type)
rval.__init__(*args, **kwargs)
return rval |
def _teardown(self):
'''
Overload so that we can clear out the cache after a test run.
'''
# __new__ is a super-special case in that even when stubbing a class
# which implements its own __new__ and subclasses object, the
# "Class.__new__" reference is a staticmethod and ... |
def call_orig(self, *args, **kwargs):
'''
Calls the original function.
'''
return self._orig(self._obj, *args, **kwargs) |
def _setup(self):
"""Performs the RFXtrx initialisation protocol in a Future.
Currently this is the rough workflow of the interactions with the
RFXtrx. We also do a few extra things - flush the buffer, and attach
readers/writers to the asyncio loop.
1. Write a RESET packet (wri... |
def do_callback(self, pkt):
"""Add the callback to the event loop, we use call soon because we just
want it to be called at some point, but don't care when particularly.
"""
callback, parser = self.get_callback_parser(pkt)
if asyncio.iscoroutinefunction(callback):
se... |
def read(self):
"""We have been called to read! As a consumer, continue to read for
the length of the packet and then pass to the callback.
"""
data = self.dev.read()
if len(data) == 0:
self.log.warning("READ : Nothing received")
return
if data ... |
def delete(self, url, params=None):
""" Executes an HTTP DELETE request for the given URL.
``params`` should be a dictionary
"""
response = self.http.delete(url,
params=params,
**self.requests_params)
re... |
def get(self, url, data=None):
""" Executes an HTTP GET request for the given URL.
``data`` should be a dictionary of url parameters
"""
response = self.http.get(url,
headers=self.headers,
params=data,
... |
def post(self, url, body=None):
""" Executes an HTTP POST request for the given URL. """
response = self.http.post(url,
headers=self.headers,
data=body,
**self.requests_params)
return self.proc... |
def put(self, url, data=None, body=None):
""" Executes an HTTP PUT request for the given URL. """
response = self.http.put(url,
headers=self.headers,
data=body,
params=data,
... |
def process(self, response):
""" Returns HTTP backend agnostic ``Response`` data. """
try:
code = response.status_code
# 204 - No Content
if code == 204:
body = None
# add an error message to 402 errors
elif code == 402:
... |
def create(self, email, tos=1, options=None):
""" Creates an account with Zencoder, no API Key necessary.
https://app.zencoder.com/docs/api/accounts/create
"""
data = {'email': email,
'terms_of_service': str(tos)}
if options:
data.update(options)
... |
def create(self, input=None, live_stream=False, outputs=None, options=None):
""" Creates a transcoding job. Here are some examples::
job.create('s3://zencodertesting/test.mov')
job.create(live_stream=True)
job.create(input='http://example.com/input.mov',
... |
def list(self, page=1, per_page=50):
""" Lists Jobs.
https://app.zencoder.com/docs/api/jobs/list
"""
data = {"page": page,
"per_page": per_page}
return self.get(self.base_url, data=data) |
def resubmit(self, job_id):
""" Resubmits the given ``job_id``.
https://app.zencoder.com/docs/api/jobs/resubmit
"""
url = self.base_url + '/%s/resubmit' % str(job_id)
return self.put(url) |
def cancel(self, job_id):
""" Cancels the given ``job_id``.
https://app.zencoder.com/docs/api/jobs/cancel
"""
if self.version == 'v1':
verb = self.get
else:
verb = self.put
url = self.base_url + '/%s/cancel' % str(job_id)
return verb(url... |
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... |
def route(app_or_blueprint, context=default_context, **kwargs):
""" attach a transmute route. """
def decorator(fn):
fn = describe(**kwargs)(fn)
transmute_func = TransmuteFunction(fn)
routes, handler = create_routes_and_handler(transmute_func, context)
for r in routes:
... |
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.
'''
s = stub(obj, attr)
if s not in sel... |
def mock(self, obj=None, attr=None, **kwargs):
'''
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)
... |
def from_validation_exception(cls, exception, **kwargs):
"""Create an error from validation exception."""
errors = []
def flatten(error, path=""):
if isinstance(error, halogen.exceptions.ValidationError):
if not path.endswith("/"):
path += "/"
... |
def load(raw_bytes):
"""
given a bytes object, should return a base python data
structure that represents the object.
"""
try:
return yaml.load(raw_bytes)
except yaml.scanner.ScannerError as e:
raise SerializationException(str(e)) |
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.
... |
def can_handle(self, cls):
"""
this will theoretically be compatible with everything,
as cattrs can handle many basic types as well.
"""
# cattrs uses a Singledispatch like function
# under the hood.
f = self._cattrs_converter._structure_func.dispatch(cls)
... |
def load(self, model, value):
"""
Converts unstructured data into structured data, recursively.
"""
try:
return self._cattrs_converter.structure(value, model)
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.
"""
... |
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.
"""
init_pos = fp.tell()
... |
def deserialize(self, value, **kwargs):
"""Deserialization of value.
:return: Deserialized value.
:raises: :class:`halogen.exception.ValidationError` exception if value is not valid.
"""
for validator in self.validators:
validator.validate(value, **kwargs)
r... |
def is_type(value):
"""Determine if value is an instance or subclass of the class Type."""
if isinstance(value, type):
return issubclass(value, Type)
return isinstance(value, Type) |
def serialize(self, value, **kwargs):
"""Serialize every item of the list."""
return [self.item_type.serialize(val, **kwargs) for val in value] |
def deserialize(self, value, **kwargs):
"""Deserialize every item of the list."""
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(v... |
def format_as_utc(self, value):
"""Format UTC times."""
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 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: inst... |
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 Validation... |
def load(raw_bytes):
"""
given a bytes object, should return a base python data
structure that represents the object.
"""
try:
if not isinstance(raw_bytes, string_type):
raw_bytes = raw_bytes.decode()
return json.loads(raw_bytes)
ex... |
def add_route(app, fn, context=default_context):
"""
a decorator that adds a transmute route to the application.
"""
transmute_func = TransmuteFunction(
fn,
args_not_from_request=["request"]
)
handler = create_handler(transmute_func, context=context)
get_swagger_spec(app).add... |
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/prev... |
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
"""
if template not in TEMPLATES:
... |
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
"""
app.route(json_route)(create_swagger_json_handler(app, **kwargs))
add_swagger_api_route(app, html_route, json_route) |
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.
"""
static_root = get_sw... |
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.
"""
spec = getattr(app, SWAGGER_ATTR_NAME, SwaggerSpec())
_add_blueprint_s... |
def fixtures():
"""Command for working with test data."""
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.se... |
def render(file):
"""Render HTML from Markdown file content."""
with file.open() as fp:
encoding = detect_encoding(fp, default='utf-8')
result = mistune.markdown(fp.read().decode(encoding))
return result |
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.
"""
try:
length = len(value)
... |
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.
... |
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
"""
__parsers[proxy_parser] = real_parser
for method, safe, args... |
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()
>>> subp... |
def initialize(glob,
sudo=False,
multi_level_debug=False,
add_config=False,
add_demo=False,
add_interact=False,
add_step=False,
add_time=False,
add_version=False,
add_wizard=False,
... |
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_conditi... |
def mse(x, xhat):
""" Calcualte mse between vector or matrix x and xhat """
buf_ = x - xhat
np.square(buf_, out=buf_) # square in-place
sum_ = np.sum(buf_)
sum_ /= x.size # divide in-place
return sum_ |
def low_rank_approximation(A, r):
""" Returns approximation of A of rank r in least-squares sense."""
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... |
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.
"""
... |
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
:re... |
def build_comparators(*values_or_types):
'''
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 ar... |
def changelog(build):
""" create a changelog """
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 args(self, *args, **kwargs):
"""
Creates a ArgumentsExpectationRule and adds it to the expectation
"""
self._any_args = False
self._arguments_rule.set_args(*args, **kwargs)
return self |
def return_value(self):
"""
Returns the value for this expectation or raises the proper exception.
"""
if self._raises:
# Handle exceptions
if inspect.isclass(self._raises):
raise self._raises()
else:
raise self._raises
... |
def match(self, *args, **kwargs):
"""
Check the if these args match this expectation.
"""
return self._any_args or \
self._arguments_rule.validate(*args, **kwargs) |
def record_file_factory(self):
"""Load default record file factory."""
try:
get_distribution('invenio-records-files')
from invenio_records_files.utils import record_file_factory
default = record_file_factory
except DistributionNotFound:
def default... |
def register_previewer(self, name, previewer):
"""Register a previewer in the system."""
if name in self.previewers:
assert name not in self.previewers, \
"Previewer with same name already registered"
self.previewers[name] = previewer
if hasattr(previewer, 'pr... |
def iter_previewers(self, previewers=None):
"""Get previewers ordered by PREVIEWER_PREVIEWERS_ORDER."""
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.... |
def init_app(self, app, entry_point_group='invenio_previewer.previewers'):
"""Flask application initialization."""
self.init_config(app)
app.register_blueprint(blueprint)
state = _InvenioPreviewerState(
app,
entry_point_group=entry_point_group)
app.extensi... |
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,
... |
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.
"""
i... |
def add_codes(err_cls):
"""Add error codes to string messages via class attribute names."""
class ErrorsWithCodes(object):
def __getattribute__(self, code):
msg = getattr(err_cls, code)
return '[{code}] {msg}'.format(code=code, msg=msg)
return ErrorsWithCodes() |
def _warn(message, warn_type='user'):
"""
message (unicode): The message to display.
category (Warning): The Warning to show.
"""
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 = WA... |
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.
"""
if model is None:
model = about.__default_corpus__
if direct:
... |
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).
"""
if util.is_packag... |
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."""
from .tokenizer_loader import TokenizerLoader
if not meta:
meta = get_model_meta(model_path)
... |
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.
"""
name = name.lower() # compare package name against lowercase name
packages = pkg_resources.working_set.by_key.keys()
f... |
def decaying(start, stop, decay):
"""Yield an infinite series of linearly decaying values."""
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 read_json(location):
"""Open and load JSON from file.
location (Path): Path to JSON file.
RETURNS (dict): Loaded JSON content.
"""
location = ensure_path(location)
with location.open('r', encoding='utf8') as f:
return ujson.load(f) |
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.
"""
additional = ' (default: ... |
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.
"""
if isinstance(data, dict):
data = list(data.items())
tpl_row = ' {:<15}' * len(data[0])
table = '\n'.join... |
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.
"""
def excl_value(value):
# contains path, i.e. personal info
re... |
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.
"""
exits = kwargs.get('exits', None)
... |
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 tex... |
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.
"""
text = text.replace('&', '&')
text =... |
def normalize_string_keys(old):
"""Given a dictionary, make sure keys are unicode strings, not bytes."""
new = {}
for key, value in old.items():
if isinstance(key, bytes_):
new[key.decode('utf8')] = value
else:
new[key] = value
return new |
def locale_escape(string, errors='replace'):
'''
Mangle non-supported characters, for savages with ascii terminals.
'''
encoding = locale.getpreferredencoding()
string = string.encode(encoding, errors).decode('utf8')
return string |
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 ... |
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 t... |
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_... |
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 prono... |
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` func... |
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.rhym... |
def set_ds9(self, level="PREF"):
"""
Set the default values on the ds9 display.
"""
self.set_zoom()
ds9_settings = config.read("DS9."+level)
for key in ds9_settings.keys():
value = ds9_settings[key]
cmd = key.replace("_", " ")
self.ds9.... |
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
@... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.