text stringlengths 81 112k |
|---|
Read config file and initialize providers
def _initialize_providers(self):
"""Read config file and initialize providers"""
configured_providers = active_config.DATABASES
provider_objects = {}
if not isinstance(configured_providers, dict) or configured_providers == {}:
raise... |
Fetch provider with the name specified in Configuration file
def get_provider(self, provider_name='default'):
"""Fetch provider with the name specified in Configuration file"""
try:
if self._providers is None:
self._providers = self._initialize_providers()
return... |
Fetch connection from Provider
def get_connection(self, provider_name='default'):
"""Fetch connection from Provider"""
try:
return self._providers[provider_name].get_connection()
except KeyError:
raise AssertionError(f'No Provider registered with name {provider_name}') |
Update the default settings for an extension from an object
def update_defaults(self, ext_config):
""" Update the default settings for an extension from an object"""
for setting in dir(ext_config):
if setting.isupper() and not hasattr(self, setting):
setattr(self, setting, g... |
Example 1: dosomething needs to run until completion condition
without needing to have a loop in its code. Also, when error
happens, we should NOT terminate execution
>>> from deeputil import AttrDict
>>> @keeprunning(wait_secs=1)
... def dosomething(state):
... state.i += 1
... pri... |
Util Method to fetch an Entity class from an entity's name
def fetch_entity_cls_from_registry(entity):
"""Util Method to fetch an Entity class from an entity's name"""
# Defensive check to ensure we only process if `to_cls` is a string
if isinstance(entity, str):
try:
return repo_factor... |
Register the given model with the factory
:param entity_cls: Entity class to be registered
:param provider: Optional provider to associate with Entity class
def register(self, entity_cls, provider_name=None):
""" Register the given model with the factory
:param entity_cls: Entity class ... |
Fetch by Entity Name in values
def _find_entity_in_records_by_class_name(self, entity_name):
"""Fetch by Entity Name in values"""
records = {
key: value for (key, value)
in self._registry.items()
if value.name == entity_name
}
# If more than one recor... |
Fetch Entity record with Entity class details
def _get_entity_by_class(self, entity_cls):
"""Fetch Entity record with Entity class details"""
entity_qualname = fully_qualified_name(entity_cls)
if entity_qualname in self._registry:
return self._registry[entity_qualname]
else:... |
Fetch Entity record with an Entity name
def _get_entity_by_name(self, entity_name):
"""Fetch Entity record with an Entity name"""
if entity_name in self._registry:
return self._registry[entity_name]
else:
return self._find_entity_in_records_by_class_name(entity_name) |
Validate that Entity is a valid class
def _validate_entity_cls(self, entity_cls):
"""Validate that Entity is a valid class"""
# Import here to avoid cyclic dependency
from protean.core.entity import Entity
if not issubclass(entity_cls, Entity):
raise AssertionError(
... |
Retrieve Model class connected to Entity
def get_model(self, entity_cls):
"""Retrieve Model class connected to Entity"""
entity_record = self._get_entity_by_class(entity_cls)
model_cls = None
if entity_record.model_cls:
model_cls = entity_record.model_cls
else:
... |
Retrieve a Repository for the Model with a live connection
def get_repository(self, entity_cls):
"""Retrieve a Repository for the Model with a live connection"""
entity_record = self._get_entity_by_class(entity_cls)
provider = self.get_provider(entity_record.provider_name)
return provi... |
Set heater values from heater data
async def set_heater_values(heater_data, heater):
"""Set heater values from heater data"""
heater.current_temp = heater_data.get('currentTemp')
heater.device_status = heater_data.get('deviceStatus')
heater.available = heater.device_status == 0
heater.name = heater... |
Connect to Mill.
async def connect(self, retry=2):
"""Connect to Mill."""
# pylint: disable=too-many-return-statements
url = API_ENDPOINT_1 + 'login'
headers = {
"Content-Type": "application/x-zc-object",
"Connection": "Keep-Alive",
"X-Zc-Major-Domain... |
Close the Mill connection.
def sync_connect(self):
"""Close the Mill connection."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.connect())
loop.run_until_complete(task) |
Close the Mill connection.
def sync_close_connection(self):
"""Close the Mill connection."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.close_connection())
loop.run_until_complete(task) |
Request data.
async def request(self, command, payload, retry=3):
"""Request data."""
# pylint: disable=too-many-return-statements
if self._token is None:
_LOGGER.error("No token")
return None
_LOGGER.debug(command, payload)
nonce = ''.join(random.choi... |
Request data.
def sync_request(self, command, payload, retry=2):
"""Request data."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.request(command, payload, retry))
return loop.run_until_complete(task) |
Request data.
async def update_rooms(self):
"""Request data."""
homes = await self.get_home_list()
for home in homes:
payload = {"homeId": home.get("homeId"), "timeZoneNum": "+01:00"}
data = await self.request("selectRoombyHome", payload)
rooms = data.get('ro... |
Request data.
def sync_update_rooms(self):
"""Request data."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.update_rooms())
return loop.run_until_complete(task) |
Set room temps by name.
async def set_room_temperatures_by_name(self, room_name, sleep_temp=None,
comfort_temp=None, away_temp=None):
"""Set room temps by name."""
if sleep_temp is None and comfort_temp is None and away_temp is None:
return
... |
Set room temps.
async def set_room_temperatures(self, room_id, sleep_temp=None,
comfort_temp=None, away_temp=None):
"""Set room temps."""
if sleep_temp is None and comfort_temp is None and away_temp is None:
return
room = self.rooms.get(room_id)
... |
Request data.
async def update_heaters(self):
"""Request data."""
homes = await self.get_home_list()
for home in homes:
payload = {"homeId": home.get("homeId")}
data = await self.request("getIndependentDevices", payload)
if data is None:
conti... |
Request data.
def sync_update_heaters(self):
"""Request data."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.update_heaters())
loop.run_until_complete(task) |
Throttle update device.
async def throttle_update_heaters(self):
"""Throttle update device."""
if (self._throttle_time is not None
and dt.datetime.now() - self._throttle_time < MIN_TIME_BETWEEN_UPDATES):
return
self._throttle_time = dt.datetime.now()
await se... |
Throttle update all devices and rooms.
async def throttle_update_all_heaters(self):
"""Throttle update all devices and rooms."""
if (self._throttle_all_time is not None
and dt.datetime.now() - self._throttle_all_time
< MIN_TIME_BETWEEN_UPDATES):
return
... |
Set heater temps.
async def heater_control(self, device_id, fan_status=None,
power_status=None):
"""Set heater temps."""
heater = self.heaters.get(device_id)
if heater is None:
_LOGGER.error("No such device")
return
if fan_status is N... |
Set heater temps.
def sync_heater_control(self, device_id, fan_status=None,
power_status=None):
"""Set heater temps."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.heater_control(device_id,
fan_stat... |
Set heater temp.
async def set_heater_temp(self, device_id, set_temp):
"""Set heater temp."""
payload = {"homeType": 0,
"timeZoneNum": "+02:00",
"deviceId": device_id,
"value": int(set_temp),
"key": "holidayTemp"}
await... |
Set heater temps.
def sync_set_heater_temp(self, device_id, set_temp):
"""Set heater temps."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.set_heater_temp(device_id, set_temp))
loop.run_until_complete(task) |
Transform csv as below.
"title1","/path1","a=1&b=2","header1=1&header2=2"
"title2","/path2","c=1"
"title3","/path3",,"header1=1&header2=2"
"title4","/path4"
Exception:
ValueError: If fomat is invalid.
def exec(self, payload: Log2ReqsAddOnPayload) -> ... |
coroutine: This method is called by Transport
implementation to handle the actual request.
It returns a webtype.Response object.
async def handle_request(self, request: Request) -> Response:
"""
coroutine: This method is called by Transport
implementation to handle the actual re... |
Create an echo
:param params:
:param source:
:param delay:
:param strength:
:return:
def echo(params, source, delay, strength):
'''
Create an echo
:param params:
:param source:
:param delay:
:param strength:
:return:
'''
source = create_buffer(params, source)
... |
Return a copy of the current QuerySet.
def _clone(self):
"""
Return a copy of the current QuerySet.
"""
clone = self.__class__(self._entity_cls, criteria=self._criteria,
offset=self._offset, limit=self._limit,
order_by=self._... |
Add a Q-object to the current filter.
def _add_q(self, q_object):
"""Add a Q-object to the current filter."""
self._criteria = self._criteria._combine(q_object, q_object.connector) |
Limit number of records
def limit(self, limit):
"""Limit number of records"""
clone = self._clone()
if isinstance(limit, int):
clone._limit = limit
return clone |
Fetch results after `offset` value
def offset(self, offset):
"""Fetch results after `offset` value"""
clone = self._clone()
if isinstance(offset, int):
clone._offset = offset
return clone |
Update order_by setting for filter set
def order_by(self, order_by: Union[set, str]):
"""Update order_by setting for filter set"""
clone = self._clone()
if isinstance(order_by, str):
order_by = {order_by}
clone._order_by = clone._order_by.union(order_by)
return clo... |
Primary method to fetch data based on filters
Also trigged when the QuerySet is evaluated by calling one of the following methods:
* len()
* bool()
* list()
* Iteration
* Slicing
def all(self):
"""Primary method to fetch data based on filters... |
Updates all objects with details given if they match a set of conditions supplied.
This method updates each object individually, to fire callback methods and ensure
validations are run.
Returns the number of objects matched (which may not be equal to the number of objects
updated i... |
Runs raw query directly on the database and returns Entity objects
Note that this method will raise an exception if the returned objects
are not of the Entity type.
`query` is not checked for correctness or validity, and any errors thrown by the plugin or
database are passed as... |
Deletes matching objects from the Repository
Does not throw error if no objects are matched.
Returns the number of objects matched (which may not be equal to the number of objects
deleted if objects rows already have the new value).
def delete(self):
"""Deletes matching objects fr... |
Updates all objects with details given if they match a set of conditions supplied.
This method forwards filters and updates directly to the repository. It does not
instantiate entities and it does not trigger Entity callbacks or validations.
Update values can be specified either as a dict, or ... |
Deletes objects that match a set of conditions supplied.
This method forwards filters directly to the repository. It does not instantiate entities and
it does not trigger Entity callbacks or validations.
Returns the number of objects matched and deleted.
def delete_all(self, *args, **kwargs):... |
Return the total number of records
def total(self):
"""Return the total number of records"""
if self._result_cache:
return self._result_cache.total
return self.all().total |
Return result values
def items(self):
"""Return result values"""
if self._result_cache:
return self._result_cache.items
return self.all().items |
Return the first result
def first(self):
"""Return the first result"""
if self._result_cache:
return self._result_cache.first
return self.all().first |
Return True if there are more values present
def has_next(self):
"""Return True if there are more values present"""
if self._result_cache:
return self._result_cache.has_next
return self.all().has_next |
Return True if there are previous values present
def has_prev(self):
"""Return True if there are previous values present"""
if self._result_cache:
return self._result_cache.has_prev
return self.all().has_prev |
Load an email backend and return an instance of it.
If backend is None (default), use settings.EMAIL_BACKEND.
Both fail_silently and other keyword arguments are used in the
constructor of the backend.
def get_connection(backend=None, fail_silently=False, **kwargs):
"""Load an email backend and return a... |
Easy wrapper for sending a single message to a recipient list. All members
of the recipient list will see the other recipients in the 'To' field.
def send_mail(subject, message, recipient_list, from_email=None,
fail_silently=False, auth_user=None, auth_password=None,
connection=None, **... |
Given a data_tuple of (subject, message, from_email, recipient_list), send
each message to each recipient list. Return the number of emails sent.
If from_email is None, use the DEFAULT_FROM_EMAIL setting.
def send_mass_mail(data_tuple, fail_silently=False, auth_user=None,
auth_password=None,... |
Utility method to retrieve Response Object information
def value(self):
"""Utility method to retrieve Response Object information"""
# Set the code to the status value
if isinstance(self.code, Status):
code = self.code.value
else:
code = self.code
return ... |
Utility method to build a new Resource Error object.
Can be used to build all kinds of error messages.
def build_response(cls, code=Status.SYSTEM_ERROR, errors=None):
"""Utility method to build a new Resource Error object.
Can be used to build all kinds of error messages.
"""
er... |
Utility method to build a new Error object from parameters.
Typically used to build HTTP 422 error response.
def build_from_invalid_request(cls, invalid_request_object):
"""Utility method to build a new Error object from parameters.
Typically used to build HTTP 422 error response."""
er... |
Utility method to build a HTTP 404 Resource Error response
def build_not_found(cls, errors=None):
"""Utility method to build a HTTP 404 Resource Error response"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.NOT_FOUND, errors) |
Utility method to build a HTTP 500 System Error response
def build_system_error(cls, errors=None):
"""Utility method to build a HTTP 500 System Error response"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.SYSTEM_ERROR, errors) |
Utility method to build a HTTP 400 Parameter Error response
def build_parameters_error(cls, errors=None):
"""Utility method to build a HTTP 400 Parameter Error response"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.PARAMETERS_ERROR, errors) |
Utility method to build a HTTP 422 Parameter Error object
def build_unprocessable_error(cls, errors=None):
"""Utility method to build a HTTP 422 Parameter Error object"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.UNPROCESSABLE_ENTITY, errors) |
Signal starts at start value, ramps linearly up to end value
:param params: buffer parameters, controls length of signal created
:param start: start value (number)
:param end: end value (number)
:return: array of resulting signal
def linseg(params, start=0, end=1):
'''
Signal starts at start va... |
Signal starts at min value, ramps linearly up to max value during the
attack time, than ramps back down to min value over remaining time
:param params: buffer parameters, controls length of signal created
:param attack: attack time, in samples
:param start: start value (number)
:param peak: peak val... |
Set the current value and optionally maintain it for a period
:param value: New current value
:param samples: Add current value for this number of samples (if not zero)
:return:
def set(self, value, samples=0):
'''
Set the current value and optionally maintain it for a period
... |
Create a linear section moving from current value to new value over acertain number of
samples.
:param value: New value
:param samples: Length of segment in samples
:return:
def linseg(self, value, samples):
'''
Create a linear section moving from current value to new va... |
s should be a requests session
def oauth_flow(s, oauth_url, username=None, password=None, sandbox=False):
"""s should be a requests session"""
r = s.get(oauth_url)
if r.status_code >= 300:
raise RuntimeError(r.text)
params = urlparse.parse_qs(urlparse.urlparse(r.url).query)
data = {"un":u... |
Update a case in the database
Args:
adapter: Connection to database
variant_file(str): Path to variant file
sv_file(str): Path to sv variant file
family_file(str): Path to family file
family_type(str): Format of family file
skip_case_id(bool):... |
legacy crossroad implementation. deprecated
def make_crossroad_router(source, drain=False):
''' legacy crossroad implementation. deprecated
'''
sink_observer = None
def on_sink_subscribe(observer):
nonlocal sink_observer
sink_observer = observer
def dispose():
nonl... |
Creates an error router
An error router takes a higher order observable a input and returns two
observables: One containing the flattened items of the input observable
and another one containing the flattened errors of the input observable.
.. image:: ../docs/asset/error_router.png
:scale: 60%... |
Load the variants of a case
A variant is loaded if it is observed in any individual of a case
If no family file is provided all individuals in vcf file will be considered.
def load(ctx, variant_file, sv_variants, family_file, family_type, skip_case_id, gq_treshold,
case_id, ensure_index, max_window, ... |
Wipe the whole database
def wipe_db(self):
"""Wipe the whole database"""
logger.warning("Wiping the whole database")
self.client.drop_database(self.db_name)
logger.debug("Database wiped") |
Check if the indexes exists
def check_indexes(self):
"""Check if the indexes exists"""
for collection_name in INDEXES:
existing_indexes = self.indexes(collection_name)
indexes = INDEXES[collection_name]
for index in indexes:
index_name = index.documen... |
Update the indexes
def ensure_indexes(self):
"""Update the indexes"""
for collection_name in INDEXES:
existing_indexes = self.indexes(collection_name)
indexes = INDEXES[collection_name]
for index in indexes:
index_name = index.document.get('name')
... |
Format the info field for SNV variants
Args:
variant(dict)
variant_type(str): snv or sv
Returns:
vcf_info(str): A VCF formated info field
def format_info(variant, variant_type='snv'):
"""Format the info field for SNV variants
Args:
variant(dict)
va... |
Convert variant information to a VCF formated string
Args:
variant(dict)
variant_type(str)
Returns:
vcf_variant(str)
def format_variant(variant, variant_type='snv'):
"""Convert variant information to a VCF formated string
Args:
variant(dict)
varian... |
Creates an objective function and its derivative for M, given W and X
Args:
w (array): clusters x cells
X (array): genes x cells
def _create_m_objective(w, X):
"""
Creates an objective function and its derivative for M, given W and X
Args:
w (array): clusters x cells
X... |
Creates a weight initialization matrix from Poisson clustering assignments.
Args:
assignments (array): 1D array of integers, of length cells
k (int): number of states/clusters
max_assign_weight (float, optional): between 0 and 1 - how much weight to assign to the highest cluster. Default: 0... |
Initializes the M matrix given the data and a set of cluster labels.
Cluster centers are set to the mean of each cluster.
Args:
data (array): genes x cells
clusters (array): 1d array of ints (0...k-1)
k (int): number of clusters
def initialize_means(data, clusters, k):
"""
Init... |
Initializes the weights with a nearest-neighbor approach using the means.
def initialize_weights_nn(data, means, lognorm=True):
"""
Initializes the weights with a nearest-neighbor approach using the means.
"""
# TODO
genes, cells = data.shape
k = means.shape[1]
if lognorm:
data = lo... |
Generates initial means and weights for state estimation.
def initialize_means_weights(data, clusters, init_means=None, init_weights=None, initialization='tsvd', max_assign_weight=0.75):
"""
Generates initial means and weights for state estimation.
"""
genes, cells = data.shape
if init_means is Non... |
Uses a Poisson Covex Mixture model to estimate cell states and
cell state mixing weights.
To lower computational costs, use a sparse matrix, set disp to False, and set tol to 0.
Args:
data (array): genes x cells array or sparse matrix.
clusters (int): number of mixture components
i... |
This returns a new M matrix that contains all genes, given an M that was
created from running state estimation with a subset of genes.
Args:
data (sparse matrix or dense array): data matrix of shape (genes, cells), containing all genes
old_M (array): shape is (selected_genes, k)
old_W (... |
Set up the VeSync component.
def setup(hass, config):
"""Set up the VeSync component."""
from pyvesync.vesync import VeSync
conf = config[DOMAIN]
manager = VeSync(conf.get(CONF_USERNAME), conf.get(CONF_PASSWORD),
time_zone=conf.get(CONF_TIME_ZONE))
if not manager.login():
... |
Runs an ensemble method on the list of M results...
Args:
data: genes x cells array
k: number of classes
n_runs (optional): number of random initializations of state estimation
M_list (optional): list of M arrays from state estimation
se_params (optional): optional poisson_e... |
Runs an ensemble method on the list of NMF W matrices...
Args:
data: genes x cells array (should be log + cell-normalized)
k: number of classes
n_runs (optional): number of random initializations of state estimation
M_list (optional): list of M arrays from state estimation
s... |
Runs K-fold ensemble topic modeling (Belford et al. 2017)
def nmf_kfold(data, k, n_runs=10, **nmf_params):
"""
Runs K-fold ensemble topic modeling (Belford et al. 2017)
"""
# TODO
nmf = NMF(k)
W_list = []
kf = KFold(n_splits=n_runs, shuffle=True)
# TODO: randomly divide data into n_runs... |
runs enhanced NMF initialization from clusterings (Gong 2013)
There are 3 options for init:
enhanced - uses EIn-NMF from Gong 2013
basic - uses means for W, assigns H such that the chosen cluster for a given cell has value 0.75 and all others have 0.25/(k-1).
nmf - uses means for W, and ass... |
runs tsne-consensus-NMF
1. run a bunch of NMFs, get W and H
2. run tsne + km on all WH matrices
3. run consensus clustering on all km results
4. use consensus clustering as initialization for a new run of NMF
5. return the W and H from the resulting NMF run
def nmf_tsne(data, k, n_runs=10, init='e... |
Initializes state estimation using a consensus of several
fast clustering/dimensionality reduction algorithms.
It does a consensus of 8 truncated SVD - k-means rounds, and uses the
basic nmf_init to create starting points.
def poisson_se_multiclust(data, k, n_runs=10, **se_params):
"""
Initializes... |
Initializes Poisson State Estimation using a consensus Poisson clustering.
def poisson_consensus_se(data, k, n_runs=10, **se_params):
"""
Initializes Poisson State Estimation using a consensus Poisson clustering.
"""
clusters = []
for i in range(n_runs):
assignments, means = poisson_cluste... |
Runs L-EnsNMF on the data. (Suh et al. 2016)
def lensNMF(data, k, ks=1):
"""
Runs L-EnsNMF on the data. (Suh et al. 2016)
"""
# TODO: why is this not working
n_rounds = k/ks
R_i = data.copy()
nmf = NMF(ks)
nmf2 = NMF(ks, init='custom')
w_is = []
h_is = []
rs = []
w_i = n... |
Return ped_parser case from a family file
Create a dictionary with case data. If no family file is given create from VCF
Args:
family_lines (iterator): The family lines
family_type (str): The format of the family lines
vcf_path(str): Path to VCF
Returns:
family... |
Update an existing case
This will add paths to VCF files, individuals etc
Args:
case_obj(models.Case)
existing_case(models.Case)
Returns:
updated_case(models.Case): Updated existing case
def update_case(case_obj, existing_case):
"""Update an existing case
... |
Usage: print_sedml input-filename
def main (args):
"""Usage: print_sedml input-filename
"""
if len(args) != 2:
print(main.__doc__)
sys.exit(1)
doc = libsedml.readSedML(args[1]);
if ( doc.getErrorLog().getNumFailsWithSeverity(libsedml.LIBSEDML_SEV_ERROR) > 0):
print doc.getErrorLog().toString()... |
Login to the profile.
async def login(self, email: str, password: str) -> bool:
"""Login to the profile."""
login_resp = await self._request(
'post',
API_URL_USER,
json={
'version': '1.0',
'method': 'Signin',
'param': {... |
Get the list of packages associated with the account.
async def packages(
self, package_state: Union[int, str] = '',
show_archived: bool = False) -> list:
"""Get the list of packages associated with the account."""
packages_resp = await self._request(
'post',
... |
Get a quick summary of how many packages are in an account.
async def summary(self, show_archived: bool = False) -> dict:
"""Get a quick summary of how many packages are in an account."""
summary_resp = await self._request(
'post',
API_URL_BUYER,
json={
... |
Set up the VeSync switch platform.
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the VeSync switch platform."""
if discovery_info is None:
return
switches = []
manager = hass.data[DOMAIN]['manager']
if manager.outlets is not None and manager.outlets:
... |
Return the state attributes of the device.
def device_state_attributes(self):
"""Return the state attributes of the device."""
attr = {}
attr['active_time'] = self.smartplug.active_time
attr['voltage'] = self.smartplug.voltage
attr['active_time'] = self.smartplug.active_time
... |
Convert a variant to a proper update
Args:
variant(dict)
Returns:
update(dict)
def _get_update(self, variant):
"""Convert a variant to a proper update
Args:
variant(dict)
Returns:
update(dict)
... |
Add a variant to the variant collection
If the variant exists we update the count else we insert a new variant object.
Args:
variant (dict): A variant dictionary
def add_variant(self, variant):
"""Add a variant to the variant collection
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.