INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Generate an inlier score for each test data example.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns:
-------
scores : array
A vector of length N, where each e... | def decision_function(self, X):
"""
Generate an inlier score for each test data example.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns:
-------
scores : ... |
Calculate accuracy score.
Needed because of bug in metrics.accuracy_score when comparing
list with numpy array. | def score(self, X, y):
"""
Calculate accuracy score.
Needed because of bug in metrics.accuracy_score when comparing
list with numpy array.
"""
predictions = self.predict(X)
true = 0.0
total = 0.0
for i in range(len(predictions)):
total... |
Calculate class probabilities for a sequence of data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are time frames, columns
are data dimensions)
A : class transition matrix, where A[i,j] contains p(y_t=j|y_{t-1}=i)
pi : vector o... | def predict_sequence(self, X, A, pi, inference='smoothing'):
"""
Calculate class probabilities for a sequence of data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are time frames, columns
are data dimensions)
A : class ... |
This is used only if websocket fails | def toggle_sensor(request, sensorname):
"""
This is used only if websocket fails
"""
if service.read_only:
service.logger.warning("Could not perform operation: read only mode enabled")
raise Http404
source = request.GET.get('source', 'main')
sensor = service.system.namespace[sens... |
For manual shortcut links to perform toggle actions | def toggle_value(request, name):
"""
For manual shortcut links to perform toggle actions
"""
obj = service.system.namespace.get(name, None)
if not obj or service.read_only:
raise Http404
new_status = obj.status = not obj.status
if service.redirect_from_setters:
return HttpRes... |
For manual shortcut links to perform set value actions | def set_value(request, name, value):
"""
For manual shortcut links to perform set value actions
"""
obj = service.system.namespace.get(name, None)
if not obj or service.read_only:
raise Http404
obj.status = value
if service.redirect_from_setters:
return HttpResponseRedirect(r... |
A read-only property that gives the object type as string; sensor, actuator, program, other.
Used by WEB interface templates. | def object_type(self):
"""
A read-only property that gives the object type as string; sensor, actuator, program, other.
Used by WEB interface templates.
"""
from .statusobject import AbstractSensor, AbstractActuator
from .program import Program
if isinsta... |
Get information about this object as a dictionary. Used by WebSocket interface to pass some
relevant information to client applications. | def get_as_datadict(self):
"""
Get information about this object as a dictionary. Used by WebSocket interface to pass some
relevant information to client applications.
"""
return dict(type=self.__class__.__name__, tags=list(self.tags)) |
Set system attribute and do some initialization. Used by System. | def setup_system(self, system, name_from_system='', **kwargs):
"""
Set system attribute and do some initialization. Used by System.
"""
if not self.system:
self.system = system
name, traits = self._passed_arguments
new_name = self.system.get_unique_name(s... |
Setup Callable attributes that belong to this object. | def setup_callables(self):
"""
Setup Callable attributes that belong to this object.
"""
defaults = self.get_default_callables()
for key, value in list(defaults.items()):
self._postponed_callables.setdefault(key, value)
for key in self.callables:
... |
Function to acqure the keyfile
SNS keys expire and Amazon does not promise they will use the same key
for all SNS requests. So we need to keep a copy of the cert in our
cache | def grab_keyfile(cert_url):
"""
Function to acqure the keyfile
SNS keys expire and Amazon does not promise they will use the same key
for all SNS requests. So we need to keep a copy of the cert in our
cache
"""
key_cache = caches[getattr(settings, 'BOUNCY_KEY_CACHE', 'default')]
pemfil... |
Function to verify notification came from a trusted source
Returns True if verfied, False if not verified | def verify_notification(data):
"""
Function to verify notification came from a trusted source
Returns True if verfied, False if not verified
"""
pemfile = grab_keyfile(data['SigningCertURL'])
cert = crypto.load_certificate(crypto.FILETYPE_PEM, pemfile)
signature = base64.decodestring(six.b(... |
Function to approve a SNS subscription with Amazon
We don't do a ton of verification here, past making sure that the endpoint
we're told to go to to verify the subscription is on the correct host | def approve_subscription(data):
"""
Function to approve a SNS subscription with Amazon
We don't do a ton of verification here, past making sure that the endpoint
we're told to go to to verify the subscription is on the correct host
"""
url = data['SubscribeURL']
domain = urlparse(url).netl... |
Return a datetime from the Amazon-provided datetime string | def clean_time(time_string):
"""Return a datetime from the Amazon-provided datetime string"""
# Get a timezone-aware datetime object from the string
time = dateutil.parser.parse(time_string)
if not settings.USE_TZ:
# If timezone support is not active, convert the time to UTC and
# remove... |
Validates fields are valid and maps pseudo-fields to actual fields
for a given model class. | def parse_selectors(model, fields=None, exclude=None, key_map=None, **options):
"""Validates fields are valid and maps pseudo-fields to actual fields
for a given model class.
"""
fields = fields or DEFAULT_SELECTORS
exclude = exclude or ()
key_map = key_map or {}
validated = []
for alia... |
Return the names of all locally defined fields on the model class. | def _get_local_fields(self, model):
"Return the names of all locally defined fields on the model class."
local = [f for f in model._meta.fields]
m2m = [f for f in model._meta.many_to_many]
fields = local + m2m
names = tuple([x.name for x in fields])
return {
... |
Returns the names of all related fields for model class. | def _get_related_fields(self, model):
"Returns the names of all related fields for model class."
reverse_fk = self._get_all_related_objects(model)
reverse_m2m = self._get_all_related_many_to_many_objects(model)
fields = tuple(reverse_fk + reverse_m2m)
names = tuple([x.get_access... |
Return HTML version of the table
This is a wrapper of the to_html method of the pandas dataframe.
:param bool index: do not include the index
:param bool escape: do not escape special characters
:param bool header: include header
:param bool collapse_table: long tables are shor... | def to_html(self, index=False, escape=False, header=True,
collapse_table=True, class_outer="table_outer", **kargs):
"""Return HTML version of the table
This is a wrapper of the to_html method of the pandas dataframe.
:param bool index: do not include the index
:param bool e... |
Change column content into HTML paragraph with background color
:param colname:
:param cmap: a colormap (matplotlib) or created using
colormap package (from pypi).
:param mode: type of normalisation in 'absmax', 'max', 'clip'
(see details below)
:param threshold:... | def add_bgcolor(self, colname, cmap='copper', mode='absmax',
threshold=2):
"""Change column content into HTML paragraph with background color
:param colname:
:param cmap: a colormap (matplotlib) or created using
colormap package (from pypi).
:param mode: type of ... |
Get object currently tracked and add a button to get back to it | def changelist_view(self, request, extra_context=None):
""" Get object currently tracked and add a button to get back to it """
extra_context = extra_context or {}
if 'object' in request.GET.keys():
value = request.GET['object'].split(':')
content_type = get_object_or_404... |
Get a list of configs.
:param filter: (optional) Filters to apply as a string list.
:param type: (optional) `union` or `inter` as string.
:param sort: (optional) Sort fields to apply as string list.
:param limit: (optional) Limit returned list length.
:param page: (optional) Pag... | def list(self, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=redefined-builtin
"""Get a list of configs.
:param filter: (optional) Filters to apply as a string list.
:param type: (optional) `union` or `inter` as string.
:param sort: (optional) Sort fields ... |
Get a list of configs. Whereas ``list`` fetches a single page of
configs according to its ``limit`` and ``page`` arguments,
``iter_list`` returns all configs by internally making
successive calls to ``list``.
:param args: Arguments that ``list`` takes.
:param kwargs: Optional a... | def iter_list(self, *args, **kwargs):
"""Get a list of configs. Whereas ``list`` fetches a single page of
configs according to its ``limit`` and ``page`` arguments,
``iter_list`` returns all configs by internally making
successive calls to ``list``.
:param args: Arguments that ... |
Get a config as plaintext.
:param id: Config ID as an int.
:rtype: string | def get_plaintext(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Get a config as plaintext.
:param id: Config ID as an int.
:rtype: string
"""
return self.service.get_id(self.base, id, params={'format': 'text'}).text |
Create a new config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config | def create(self, resource):
"""Create a new config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config
"""
schema = self.CREATE_SCHEMA
json = self.service.encode(schema,... |
Edit a config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config | def edit(self, resource):
"""Edit a config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config
"""
schema = self.EDIT_SCHEMA
json = self.service.encode(schema, resource)... |
Edit shares for a config.
:param id: Config ID as an int.
:param user_ids: User IDs as int list.
:return: :class:`cdrouter.Share <cdrouter.Share>` list | def edit_shares(self, id, user_ids): # pylint: disable=invalid-name,redefined-builtin
"""Edit shares for a config.
:param id: Config ID as an int.
:param user_ids: User IDs as int list.
:return: :class:`cdrouter.Share <cdrouter.Share>` list
"""
return self.service.edit_s... |
Process config contents with cdrouter-cli -check-config.
:param contents: Config contents as string.
:return: :class:`configs.CheckConfig <configs.CheckConfig>` object
:rtype: configs.CheckConfig | def check_config(self, contents):
"""Process config contents with cdrouter-cli -check-config.
:param contents: Config contents as string.
:return: :class:`configs.CheckConfig <configs.CheckConfig>` object
:rtype: configs.CheckConfig
"""
schema = CheckConfigSchema()
... |
Process config contents with cdrouter-cli -upgrade-config.
:param contents: Config contents as string.
:return: :class:`configs.UpgradeConfig <configs.UpgradeConfig>` object
:rtype: configs.UpgradeConfig | def upgrade_config(self, contents):
"""Process config contents with cdrouter-cli -upgrade-config.
:param contents: Config contents as string.
:return: :class:`configs.UpgradeConfig <configs.UpgradeConfig>` object
:rtype: configs.UpgradeConfig
"""
schema = UpgradeConfigSc... |
Process config contents with cdrouter-cli -print-networks-json.
:param contents: Config contents as string.
:return: :class:`configs.Networks <configs.Networks>` object
:rtype: configs.Networks | def get_networks(self, contents):
"""Process config contents with cdrouter-cli -print-networks-json.
:param contents: Config contents as string.
:return: :class:`configs.Networks <configs.Networks>` object
:rtype: configs.Networks
"""
schema = NetworksSchema()
re... |
Bulk copy a set of configs.
:param ids: Int list of config IDs.
:return: :class:`configs.Config <configs.Config>` list | def bulk_copy(self, ids):
"""Bulk copy a set of configs.
:param ids: Int list of config IDs.
:return: :class:`configs.Config <configs.Config>` list
"""
schema = self.GET_SCHEMA
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) |
Bulk edit a set of configs.
:param _fields: :class:`configs.Config <configs.Config>` object
:param ids: (optional) Int list of config IDs.
:param filter: (optional) String list of filters.
:param type: (optional) `union` or `inter` as string.
:param all: (optional) Apply to all ... | def bulk_edit(self, _fields, ids=None, filter=None, type=None, all=False, testvars=None): # pylint: disable=redefined-builtin
"""Bulk edit a set of configs.
:param _fields: :class:`configs.Config <configs.Config>` object
:param ids: (optional) Int list of config IDs.
:param filter: (opt... |
Bulk delete a set of configs.
:param ids: (optional) Int list of config IDs.
:param filter: (optional) String list of filters.
:param type: (optional) `union` or `inter` as string.
:param all: (optional) Apply to all if bool `True`. | def bulk_delete(self, ids=None, filter=None, type=None, all=False): # pylint: disable=redefined-builtin
"""Bulk delete a set of configs.
:param ids: (optional) Int list of config IDs.
:param filter: (optional) String list of filters.
:param type: (optional) `union` or `inter` as string.... |
Extract token from response and set it for the user.
:param remote: The remote application.
:param resp: The response.
:raises invenio_oauthclient.errors.OAuthClientError: If authorization with
remote service failed.
:raises invenio_oauthclient.errors.OAuthResponseError: In case of bad
... | def response_token_setter(remote, resp):
"""Extract token from response and set it for the user.
:param remote: The remote application.
:param resp: The response.
:raises invenio_oauthclient.errors.OAuthClientError: If authorization with
remote service failed.
:raises invenio_oauthclient.er... |
Set an OAuth1 token.
:param remote: The remote application.
:param resp: The response.
:param token_type: The token type. (Default: ``''``)
:param extra_data: Extra information. (Default: ``None``)
:returns: A :class:`invenio_oauthclient.models.RemoteToken` instance. | def oauth1_token_setter(remote, resp, token_type='', extra_data=None):
"""Set an OAuth1 token.
:param remote: The remote application.
:param resp: The response.
:param token_type: The token type. (Default: ``''``)
:param extra_data: Extra information. (Default: ``None``)
:returns: A :class:`inv... |
Set an OAuth2 token.
The refresh_token can be used to obtain a new access_token after
the old one is expired. It is saved in the database for long term use.
A refresh_token will be present only if `access_type=offline` is included
in the authorization code request.
:param remote: The remote applic... | def oauth2_token_setter(remote, resp, token_type='', extra_data=None):
"""Set an OAuth2 token.
The refresh_token can be used to obtain a new access_token after
the old one is expired. It is saved in the database for long term use.
A refresh_token will be present only if `access_type=offline` is include... |
Set token for user.
:param remote: The remote application.
:param token: The token to set.
:param token_type: The token type. (Default: ``''``)
:param extra_data: Extra information. (Default: ``None``)
:param user: The user owner of the remote token. If it's not defined,
the current user is... | def token_setter(remote, token, secret='', token_type='', extra_data=None,
user=None):
"""Set token for user.
:param remote: The remote application.
:param token: The token to set.
:param token_type: The token type. (Default: ``''``)
:param extra_data: Extra information. (Default: ... |
Retrieve OAuth access token.
Used by flask-oauthlib to get the access token when making requests.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default: ``''``)
:returns: The token. | def token_getter(remote, token=''):
"""Retrieve OAuth access token.
Used by flask-oauthlib to get the access token when making requests.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default... |
Remove OAuth access tokens from session.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default: ``''``)
:returns: The token. | def token_delete(remote, token=''):
"""Remove OAuth access tokens from session.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default: ``''``)
:returns: The token.
"""
session_key = t... |
Decorator to handle exceptions. | def oauth_error_handler(f):
"""Decorator to handle exceptions."""
@wraps(f)
def inner(*args, **kwargs):
# OAuthErrors should not happen, so they are not caught here. Hence
# they will result in a 500 Internal Server Error which is what we
# are interested in.
try:
... |
Store access token in session.
Default authorized handler.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response. | def authorized_default_handler(resp, remote, *args, **kwargs):
"""Store access token in session.
Default authorized handler.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response.
"""
response_token_setter(remote, resp)
db.session.commit()
re... |
Handle sign-in/up functionality.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response. | def authorized_signup_handler(resp, remote, *args, **kwargs):
"""Handle sign-in/up functionality.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response.
"""
# Remove any previously stored auto register session key
session.pop(token_session_key(remote.... |
Handle unlinking of remote account.
This default handler will just delete the remote account link. You may
wish to extend this module to perform clean-up in the remote service
before removing the link (e.g. removing install webhooks).
:param remote: The remote application.
:returns: Redirect respo... | def disconnect_handler(remote, *args, **kwargs):
"""Handle unlinking of remote account.
This default handler will just delete the remote account link. You may
wish to extend this module to perform clean-up in the remote service
before removing the link (e.g. removing install webhooks).
:param remo... |
Handle extra signup information.
:param remote: The remote application.
:returns: Redirect response or the template rendered. | def signup_handler(remote, *args, **kwargs):
"""Handle extra signup information.
:param remote: The remote application.
:returns: Redirect response or the template rendered.
"""
# User already authenticated so move on
if current_user.is_authenticated:
return redirect('/')
# Retriev... |
Remove all access tokens from session on logout. | def oauth_logout_handler(sender_app, user=None):
"""Remove all access tokens from session on logout."""
oauth = current_app.extensions['oauthlib.client']
for remote in oauth.remote_apps.values():
token_delete(remote)
db.session.commit() |
Make a handler for authorized and disconnect callbacks.
:param f: Callable or an import path to a callable | def make_handler(f, remote, with_response=True):
"""Make a handler for authorized and disconnect callbacks.
:param f: Callable or an import path to a callable
"""
if isinstance(f, six.string_types):
f = import_string(f)
@wraps(f)
def inner(*args, **kwargs):
if with_response:
... |
The decorator for ensuring thread-safe when current cache instance is concurrent status. | def _enable_lock(func):
"""
The decorator for ensuring thread-safe when current cache instance is concurrent status.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if self.is_concurrent:
only_read = kwargs.get('only_read')
if only_rea... |
Execute cleanup operation when the decorated function completed. | def _enable_cleanup(func):
"""
Execute cleanup operation when the decorated function completed.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
result = func(*args, **kwargs)
self.cleanup(self)
return result
return wrapper |
Use thread pool for executing a task if self.enable_thread_pool is True.
Return an instance of future when flag is_async is True otherwise will to
block waiting for the result until timeout then returns the result. | def _enable_thread_pool(func):
"""
Use thread pool for executing a task if self.enable_thread_pool is True.
Return an instance of future when flag is_async is True otherwise will to
block waiting for the result until timeout then returns the result.
"""
@functools.wraps(func)
def wrapper(*... |
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.put('a', 0)
>>> cache.put('b', 1)
>>> cache.size()
2
>>> cache.clear()
>>> cache.size()
0 | def clear(self, only_read=False):
"""
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.put('a', 0)
>>> cache.put('b', 1)
>>> cache.size()
2
>>> cache.clear()
>>> cache.size()
0
"""
self.cache_items.clear()
self.total_a... |
>>> cache = Cache(log_level=logging.WARNING)
>>> def evict(dict, evict_number=10): pass
>>> cache.replace_evict_func(evict)
True
>>> def evict_b(dict): pass
>>> cache.replace_evict_func(evict_b)
False
>>> def evict_c(dict, a, b): pass
>>> cache.replace_evi... | def replace_evict_func(self, func, only_read=False):
"""
>>> cache = Cache(log_level=logging.WARNING)
>>> def evict(dict, evict_number=10): pass
>>> cache.replace_evict_func(evict)
True
>>> def evict_b(dict): pass
>>> cache.replace_evict_func(evict_b)
Fals... |
>>> cache = Cache(log_level=logging.WARNING)
>>> def cleanup(self): pass
>>> cache.replace_cleanup_func(cleanup)
True
>>> def cleanup_b(self, other): pass
>>> cache.replace_cleanup_func(cleanup_b)
False | def replace_cleanup_func(self, func, only_read=False):
"""
>>> cache = Cache(log_level=logging.WARNING)
>>> def cleanup(self): pass
>>> cache.replace_cleanup_func(cleanup)
True
>>> def cleanup_b(self, other): pass
>>> cache.replace_cleanup_func(cleanup_b)
... |
>>> cache = Cache(log_level=logging.WARNING)
>>> def cache_loader(key): pass
>>> cache.with_cache_loader(cache_loader)
True
>>> def cache_loader_b(key, value): pass
>>> cache.with_cache_loader(cache_loader_b)
False | def with_cache_loader(self, func, only_read=False):
"""
>>> cache = Cache(log_level=logging.WARNING)
>>> def cache_loader(key): pass
>>> cache.with_cache_loader(cache_loader)
True
>>> def cache_loader_b(key, value): pass
>>> cache.with_cache_loader(cache_loader_b)... |
>>> cache = Cache(log_level=logging.WARNING)
>>> def cache_writer(key): pass
>>> cache.with_cache_writer(cache_writer)
False
>>> def cache_writer(key, value): pass
>>> cache.with_cache_writer(cache_writer)
True | def with_cache_writer(self, func, only_read=False):
"""
>>> cache = Cache(log_level=logging.WARNING)
>>> def cache_writer(key): pass
>>> cache.with_cache_writer(cache_writer)
False
>>> def cache_writer(key, value): pass
>>> cache.with_cache_writer(cache_writer)
... |
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.stop_regularly_cleanup()
True
>>> cache.stop_regularly_cleanup()
False | def stop_regularly_cleanup(self, only_read=False):
"""
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.stop_regularly_cleanup()
True
>>> cache.stop_regularly_cleanup()
False
"""
if hasattr(self, 'cleanup_supervisor') and self.cleanup_supervisor is n... |
>>> cache = Cache(regularly_cleanup=False, log_level=logging.ERROR)
>>> cache.start_regularly_cleanup()
True
>>> cache.start_regularly_cleanup()
False | def start_regularly_cleanup(self, regularly_cleanup_interval=None, only_read=False):
"""
>>> cache = Cache(regularly_cleanup=False, log_level=logging.ERROR)
>>> cache.start_regularly_cleanup()
True
>>> cache.start_regularly_cleanup()
False
"""
if not hasat... |
>>> cache = Cache(enable_thread_pool=False, log_level=logging.ERROR)
>>> cache.with_thread_pool()
True
>>> cache.with_thread_pool()
False | def with_thread_pool(self, init_func=None, only_read=False):
"""
>>> cache = Cache(enable_thread_pool=False, log_level=logging.ERROR)
>>> cache.with_thread_pool()
True
>>> cache.with_thread_pool()
False
"""
if not hasattr(self, 'thread_pool') or self.threa... |
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.unable_thread_pool()
True
>>> cache.unable_thread_pool()
False | def unable_thread_pool(self, only_read=False):
"""
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.unable_thread_pool()
True
>>> cache.unable_thread_pool()
False
"""
if self.enable_thread_pool and hasattr(self, 'thread_pool') and self.thread_pool is... |
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.shutdown_thread_pool()
True
>>> cache.unable_thread_pool()
True
>>> cache.shutdown_thread_pool()
False | def shutdown_thread_pool(self, only_read=False):
"""
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.shutdown_thread_pool()
True
>>> cache.unable_thread_pool()
True
>>> cache.shutdown_thread_pool()
False
"""
if self.enable_thread_poo... |
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.set_capacity(100)
>>> cache.capacity
100
>>> cache.set_capacity('haha')
>>> cache.capacity
100 | def set_capacity(self, new_capacity, only_read=False):
"""
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.set_capacity(100)
>>> cache.capacity
100
>>> cache.set_capacity('haha')
>>> cache.capacity
100
"""
if not isinstance(new_capac... |
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.set_expire(40)
>>> cache.expire
40
>>> cache.set_expire('haha')
>>> cache.expire
40 | def set_expire(self, new_expire, only_read=False):
"""
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.set_expire(40)
>>> cache.expire
40
>>> cache.set_expire('haha')
>>> cache.expire
40
"""
if not isinstance(new_expire, int) or new_... |
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.set_evict_number(10)
>>> cache.evict_number
10
>>> cache.set_evict_number('haha')
>>> cache.evict_number
10 | def set_evict_number(self, new_evict_number, only_read=False):
"""
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.set_evict_number(10)
>>> cache.evict_number
10
>>> cache.set_evict_number('haha')
>>> cache.evict_number
10
"""
if not... |
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.read_after_refresh_expire
True
>>> cache.with_read_after_refresh_expire(False)
>>> cache.read_after_refresh_expire
False
>>> cache.with_read_after_refresh_expire('haha')
>>> cache.read_after_refresh_expire
... | def with_read_after_refresh_expire(self, flag, only_read=False):
"""
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.read_after_refresh_expire
True
>>> cache.with_read_after_refresh_expire(False)
>>> cache.read_after_refresh_expire
False
>>> cache.w... |
Returns a list that each element is a dictionary of the statistic info of the cache item. | def statistic_record(self, desc=True, timeout=3, is_async=False, only_read=True, *keys):
"""
Returns a list that each element is a dictionary of the statistic info of the cache item.
"""
if len(keys) == 0:
records = self._generate_statistic_records()
else:
... |
The decorator for simplifying of use cache, it supports auto-update
cache(if parameter auto_update is True), load cache from other level cache
system or data source and writes back the update result to the
other level cache system or data source if cache miss.
The parameter key assigns ... | def access_cache(self, key=None, key_location_on_param=0, expire=None, auto_update=True,
cache_loader=None, cache_writer=None, timeout=1):
"""
The decorator for simplifying of use cache, it supports auto-update
cache(if parameter auto_update is True), load cache from other l... |
Test:
>>> import time
>>> cache = Cache(expire=2)
>>> cache.put(key='a', value=0)
>>> cache.put(key='b', value=1)
>>> cache.put(key='c',value= 2)
>>> cache.get('a')
0
>>> cache.get('b')
1
>>> cache.get('c')
2
>>> cache.get(... | def get(self, key, timeout=1, is_async=False, only_read=True):
"""
Test:
>>> import time
>>> cache = Cache(expire=2)
>>> cache.put(key='a', value=0)
>>> cache.put(key='b', value=1)
>>> cache.put(key='c',value= 2)
>>> cache.get('a')
0
>>> c... |
Test:
>>> cache = Cache(expire=2)
>>> cache.put('a', 0)
>>> cache.get('a')
0
>>> cache.put('a', 1)
>>> cache.get('a')
1 | def put(self, key, value, expire=None, timeout=1, is_async=True, only_read=False):
"""
Test:
>>> cache = Cache(expire=2)
>>> cache.put('a', 0)
>>> cache.get('a')
0
>>> cache.put('a', 1)
>>> cache.get('a')
1
"""
if key in self.cache... |
Test:
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.put('a', 0)
>>> cache.pop('a')
0
>>> cache.pop('b') == None
True | def pop(self, key, timeout=1, is_async=False, only_read=False):
"""
Test:
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.put('a', 0)
>>> cache.pop('a')
0
>>> cache.pop('b') == None
True
"""
if key not in self.cache_items:
... |
Not safe to use with secret keys or secret data.
See module docstring. This function should be used for testing only. | def signature_unsafe(m, sk, pk, hash_func=H):
"""
Not safe to use with secret keys or secret data.
See module docstring. This function should be used for testing only.
"""
h = hash_func(sk)
a = 2 ** (b - 2) + sum(2 ** i * bit(h, i) for i in range(3, b - 2))
r = Hint(bytearray([h[j] for j in... |
Not safe to use when any argument is secret.
See module docstring. This function should be used only for
verifying public signatures of public messages. | def checkvalid(s, m, pk):
"""
Not safe to use when any argument is secret.
See module docstring. This function should be used only for
verifying public signatures of public messages.
"""
if len(s) != b // 4:
raise ValueError("signature length is wrong")
if len(pk) != b // 8:
... |
Upgrade database. | def upgrade():
"""Upgrade database."""
op.create_table(
'oauthclient_remoteaccount',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('client_id', sa.String(length=255), nullable=False),
sa.Column(
'e... |
Upgrade database. | def upgrade():
"""Upgrade database."""
current_date = datetime.utcnow()
# Add 'created' and 'updated' columns to RemoteAccount
_add_created_updated_columns('oauthclient_remoteaccount', current_date)
# Add 'created' and 'updated' columns to RemoteToken
_add_created_updated_columns('oauthclient_... |
Downgrade database. | def downgrade():
"""Downgrade database."""
# Remove 'created' and 'updated' columns
op.drop_column('oauthclient_remoteaccount', 'created')
op.drop_column('oauthclient_remoteaccount', 'updated')
op.drop_column('oauthclient_remotetoken', 'created')
op.drop_column('oauthclient_remotetoken', 'updat... |
Compatibility with NLTK.
Returns the cmudict lexicon as a dictionary, whose keys are
lowercase words and whose values are lists of pronunciations. | def dict():
"""
Compatibility with NLTK.
Returns the cmudict lexicon as a dictionary, whose keys are
lowercase words and whose values are lists of pronunciations.
"""
default = defaultdict(list)
for key, value in entries():
default[key].append(value)
return default |
Return a list of symbols. | def symbols():
"""Return a list of symbols."""
symbols = []
for line in symbols_stream():
symbols.append(line.decode('utf-8').strip())
return symbols |
(internal) Determines the type of a given ``object``. Discriminates between
``Piper``, ``Worker``, ``FunctionType`` and ``Iterable`` instances. It
returns a ``tuple`` of boolean variables i.e: (is_piper, is_worker,
is_function, is_iterable_of_pipers, is_iterable_of_workers,
is_iterable_of_functi... | def _inspect(instance):
"""
(internal) Determines the type of a given ``object``. Discriminates between
``Piper``, ``Worker``, ``FunctionType`` and ``Iterable`` instances. It
returns a ``tuple`` of boolean variables i.e: (is_piper, is_worker,
is_function, is_iterable_of_pipers, is_iterable_of... |
(internal) Composes a sequence of functions in the global variable TASK. The
resulting composition is given the input "inbox" and arguments "args",
"kwargs". | def _comp_task(inbox, args, kwargs):
"""
(internal) Composes a sequence of functions in the global variable TASK. The
resulting composition is given the input "inbox" and arguments "args",
"kwargs".
"""
# Note. this function uses a global variable which must be defined on the
# remote... |
Custom compare function. Returns ``1`` if the first ``Piper`` instance
is upstream of the second ``Piper`` instance, ``-1`` if the first
``Piper`` is downstream of the second ``Piper`` and ``0`` if the two
``Pipers`` are independent.
Arguments:
- piper1(``P... | def children_after_parents(self, piper1, piper2):
"""
Custom compare function. Returns ``1`` if the first ``Piper`` instance
is upstream of the second ``Piper`` instance, ``-1`` if the first
``Piper`` is downstream of the second ``Piper`` and ``0`` if the two
``Pipers`` are in... |
Given a ``Piper`` instance or the ``id`` of the ``Piper``. Returns the
``Piper`` instance if it can be resolved else raises a ``DaggerError``
or returns ``False`` depending on the "forgive" argument.
Arguments:
- piper(``Piper`` or id(``Piper``)) a ``Piper`` instance or i... | def resolve(self, piper, forgive=False):
"""
Given a ``Piper`` instance or the ``id`` of the ``Piper``. Returns the
``Piper`` instance if it can be resolved else raises a ``DaggerError``
or returns ``False`` depending on the "forgive" argument.
Arguments:
... |
Connects ``Pipers`` in the order input -> output. See ``Piper.connect``.
According to the pipes (topology). If "datas" is given will connect the
input ``Pipers`` to the input data see: ``Dagger.connect_inputs``.
Argumensts:
- datas(sequence) [default: ``None``] valid ... | def connect(self, datas=None):
"""
Connects ``Pipers`` in the order input -> output. See ``Piper.connect``.
According to the pipes (topology). If "datas" is given will connect the
input ``Pipers`` to the input data see: ``Dagger.connect_inputs``.
Argumensts:
... |
Connects input ``Pipers`` to "datas" input data in the correct order
determined, by the ``Piper.ornament`` attribute and the ``Dagger._cmp``
function.
It is assumed that the input data is in the form of an iterator and
that all inputs have the same number of input items. A pipeline w... | def connect_inputs(self, datas):
"""
Connects input ``Pipers`` to "datas" input data in the correct order
determined, by the ``Piper.ornament`` attribute and the ``Dagger._cmp``
function.
It is assumed that the input data is in the form of an iterator and
that all inp... |
Given the pipeline topology disconnects ``Pipers`` in the order output
-> input. This also disconnects inputs. See ``Dagger.connect``,
``Piper.connect`` and ``Piper.disconnect``. If "forced" is ``True``
``NuMap`` instances will be emptied.
Arguments:
- forced... | def disconnect(self, forced=False):
"""
Given the pipeline topology disconnects ``Pipers`` in the order output
-> input. This also disconnects inputs. See ``Dagger.connect``,
``Piper.connect`` and ``Piper.disconnect``. If "forced" is ``True``
``NuMap`` instances will be emptied.... |
Given the pipeline topology starts ``Pipers`` in the order input ->
output. See ``Piper.start``. ``Pipers`` instances are started in two
stages, which allows them to share ``NuMaps``. | def start(self):
"""
Given the pipeline topology starts ``Pipers`` in the order input ->
output. See ``Piper.start``. ``Pipers`` instances are started in two
stages, which allows them to share ``NuMaps``.
"""
# top - > bottom of pipeline
pipers = self.p... |
Stops the ``Pipers`` according to pipeline topology. | def stop(self):
"""
Stops the ``Pipers`` according to pipeline topology.
"""
self.log.debug('%s begins stopping routine' % repr(self))
self.log.debug('%s triggers stopping in input pipers' % repr(self))
inputs = self.get_inputs()
for piper in inputs:
... |
Returns ``Piper`` instances, which are inputs to the pipeline i.e. have
no incoming pipes (outgoing dependency edges). | def get_inputs(self):
"""
Returns ``Piper`` instances, which are inputs to the pipeline i.e. have
no incoming pipes (outgoing dependency edges).
"""
start_p = [p for p in self.postorder() if not self.outgoing_edges(p)]
self.log.debug('%s got input pipers %s' % ... |
Returns ``Piper`` instances, which are outputs to the pipeline i.e. have
no outgoing pipes (incoming dependency edges). | def get_outputs(self):
"""
Returns ``Piper`` instances, which are outputs to the pipeline i.e. have
no outgoing pipes (incoming dependency edges).
"""
end_p = [p for p in self.postorder() if not self.incoming_edges(p)]
self.log.debug('%s got output pipers %s' % ... |
Adds a ``Piper`` instance to this ``Dagger``, but only if the ``Piper``
is not already there. Optionally creates a new ``Piper`` if the "piper"
argument is valid for the ``Piper`` constructor. Returns a ``tuple``
(new_piper_created, piper_instance) indicating whether a new ``Piper``
ha... | def add_piper(self, piper, xtra=None, create=True, branch=None):
"""
Adds a ``Piper`` instance to this ``Dagger``, but only if the ``Piper``
is not already there. Optionally creates a new ``Piper`` if the "piper"
argument is valid for the ``Piper`` constructor. Returns a ``tuple``
... |
Removes a ``Piper`` from the ``Dagger`` instance.
Arguments:
- piper(``Piper`` or id(``Piper``)) ``Piper`` instance or ``Piper``
instance id.
- forced(bool) [default: ``False``] If "forced" is ``True``, will not
raise a ``DaggerError`` if the ``Piper`` ha... | def del_piper(self, piper, forced=False):
"""
Removes a ``Piper`` from the ``Dagger`` instance.
Arguments:
- piper(``Piper`` or id(``Piper``)) ``Piper`` instance or ``Piper``
instance id.
- forced(bool) [default: ``False``] If "forced" is ``True``, wil... |
Adds a pipe (A, ..., N) which is an N-``tuple`` tuple of ``Pipers``
instances. Adding a pipe means to add all the ``Pipers`` and connect
them in the specified left to right order.
The direction of the edges in the ``DictGraph`` is reversed compared to
the left to right data-f... | def add_pipe(self, pipe, branch=None):
"""
Adds a pipe (A, ..., N) which is an N-``tuple`` tuple of ``Pipers``
instances. Adding a pipe means to add all the ``Pipers`` and connect
them in the specified left to right order.
The direction of the edges in the ``DictGraph`... |
Deletes a pipe (A, ..., N) which is an N-``tuple`` of ``Piper``
instances. Deleting a pipe means to delete all the connections between
``Pipers`` and to delete all the ``Pipers``. If "forced" is ``False``
only ``Pipers`` which are not used anymore (i.e. have not downstream
``Pipers``... | def del_pipe(self, pipe, forced=False):
"""
Deletes a pipe (A, ..., N) which is an N-``tuple`` of ``Piper``
instances. Deleting a pipe means to delete all the connections between
``Pipers`` and to delete all the ``Pipers``. If "forced" is ``False``
only ``Pipers`` which are no... |
Adds a sequence of ``Pipers`` instances to the ``Dagger`` in the
specified order. Takes optional arguments for ``Dagger.add_piper``.
Arguments:
- pipers(sequence of valid ``add_piper`` arguments) Sequence of
``Pipers`` or valid ``Dagger.add_piper`` arguments to ... | def add_pipers(self, pipers, *args, **kwargs):
"""
Adds a sequence of ``Pipers`` instances to the ``Dagger`` in the
specified order. Takes optional arguments for ``Dagger.add_piper``.
Arguments:
- pipers(sequence of valid ``add_piper`` arguments) Sequence of ... |
Deletes a sequence of ``Pipers`` instances from the ``Dagger`` in the
reverse of the specified order. Takes optional arguments for
``Dagger.del_piper``.
Arguments:
- pipers (sequence of valid ``del_piper`` arguments) Sequence of
``Pipers`` or valid ``Dag... | def del_pipers(self, pipers, *args, **kwargs):
"""
Deletes a sequence of ``Pipers`` instances from the ``Dagger`` in the
reverse of the specified order. Takes optional arguments for
``Dagger.del_piper``.
Arguments:
- pipers (sequence of valid ``del_pi... |
Adds a sequence of pipes to the ``Dagger`` in the specified order.
Takes optional arguments for ``Dagger.add_pipe``.
Arguments:
- pipes(sequence of valid ``add_pipe`` arguments) Sequence of pipes
or other valid ``Dagger.add_pipe`` arguments to be added to the
... | def add_pipes(self, pipes, *args, **kwargs):
"""
Adds a sequence of pipes to the ``Dagger`` in the specified order.
Takes optional arguments for ``Dagger.add_pipe``.
Arguments:
- pipes(sequence of valid ``add_pipe`` arguments) Sequence of pipes
o... |
Deletes a sequence of pipes from the ``Dagger`` in the specified order.
Takes optional arguments for ``Dagger.del_pipe``.
Arguments:
- pipes(sequence of valid ``del_pipe`` arguments) Sequence of pipes or
other valid ``Dagger.del_pipe`` arguments to be removed fr... | def del_pipes(self, pipes, *args, **kwargs):
"""
Deletes a sequence of pipes from the ``Dagger`` in the specified order.
Takes optional arguments for ``Dagger.del_pipe``.
Arguments:
- pipes(sequence of valid ``del_pipe`` arguments) Sequence of pipes or
... |
(internal) executes when last output piper raises ``StopIteration``. | def _finish(self, ispausing):
"""
(internal) executes when last output piper raises ``StopIteration``.
"""
if ispausing:
self.log.debug('%s paused' % repr(self))
else:
self._finished.set()
self.log.debug('%s finished' % repr(self)) |
(internal) calls the next method of weaved tasks until they are finished
or The ``Plumber`` instance is stopped see: ``Dagger.chinkup``. | def _plunge(tasks, pausing, finish):
"""
(internal) calls the next method of weaved tasks until they are finished
or The ``Plumber`` instance is stopped see: ``Dagger.chinkup``.
"""
# If no result received either not started or start & stop
# could have been called before... |
(internal) generates imports, code and runtime calls to save a pipeline. | def _code(self):
"""
(internal) generates imports, code and runtime calls to save a pipeline.
"""
icode, tcode = '', '' # imports, task code
icall, pcall = '', '' # imap calls, piper calls
tdone, idone = [], [] # task done, imap done
for piper in self:
... |
Saves pipeline as a Python source code file.
Arguments:
- filename(``path``) Path to save the pipeline source code. | def save(self, filename):
"""
Saves pipeline as a Python source code file.
Arguments:
- filename(``path``) Path to save the pipeline source code.
"""
handle = open(filename, 'wb')
handle.write(P_LAY % self._code())
handle.clo... |
Instanciates (loads) pipeline from a source code file.
Arguments:
- filename(``path``) location of the pipeline source code. | def load(self, filename):
"""
Instanciates (loads) pipeline from a source code file.
Arguments:
- filename(``path``) location of the pipeline source code.
"""
dir_name = os.path.dirname(filename)
mod_name = os.path.basename(filename)... |
Starts the pipeline by connecting the input ``Pipers`` of the pipeline
to the input data, connecting the pipeline and starting the ``NuMap``
instances.
The order of items in the "datas" argument sequence should correspond
to the order of the input ``Pipers`` defined by ``Dagge... | def start(self, datas):
"""
Starts the pipeline by connecting the input ``Pipers`` of the pipeline
to the input data, connecting the pipeline and starting the ``NuMap``
instances.
The order of items in the "datas" argument sequence should correspond
to the orde... |
Executes a started pipeline by pulling results from it's output
``Pipers``. Processing nodes i.e. ``Pipers`` with the ``track``
attribute set ``True`` will have their returned results stored within
the ``Dagger.stats['pipers_tracked']`` dictionary. A running pipeline
can be paused. | def run(self):
"""
Executes a started pipeline by pulling results from it's output
``Pipers``. Processing nodes i.e. ``Pipers`` with the ``track``
attribute set ``True`` will have their returned results stored within
the ``Dagger.stats['pipers_tracked']`` dictionary. A running... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.