Search is not available for this dataset
text stringlengths 75 104k |
|---|
def set_display(self, brightness=100, brightness_mode="auto"):
"""
allows to modify display state (change brightness)
:param int brightness: display brightness [0, 100] (default: 100)
:param str brightness_mode: the brightness mode of the display
[aut... |
def set_screensaver(
self, mode, is_mode_enabled, start_time=None, end_time=None,
is_screensaver_enabled=True
):
"""
set the display's screensaver mode
:param str mode: mode of the screensaver
[when_dark, time_based]
:param bool is_mode_enabl... |
def get_volume(self):
"""
returns the current volume
"""
log.debug("getting volumne...")
cmd, url = DEVICE_URLS["get_volume"]
return self._exec(cmd, url) |
def set_volume(self, volume=50):
"""
allows to change the volume
:param int volume: volume to be set for the current device
[0..100] (default: 50)
"""
assert(volume in range(101))
log.debug("setting volume...")
cmd, url = DEVICE_URLS[... |
def get_bluetooth_state(self):
"""
returns the bluetooth state
"""
log.debug("getting bluetooth state...")
cmd, url = DEVICE_URLS["get_bluetooth_state"]
return self._exec(cmd, url) |
def set_bluetooth(self, active=None, name=None):
"""
allows to activate/deactivate bluetooth and change the name
"""
assert(active is not None or name is not None)
log.debug("setting bluetooth state...")
cmd, url = DEVICE_URLS["set_bluetooth"]
json_data = {}
... |
def get_wifi_state(self):
"""
returns the current Wi-Fi state the device is connected to
"""
log.debug("getting wifi state...")
cmd, url = DEVICE_URLS["get_wifi_state"]
return self._exec(cmd, url) |
def set_apps_list(self):
"""
gets installed apps and puts them into the available_apps list
"""
log.debug("getting apps and setting them in the internal app list...")
cmd, url = DEVICE_URLS["get_apps_list"]
result = self._exec(cmd, url)
self.available_apps = [
... |
def switch_to_app(self, package):
"""
activates an app that is specified by package. Selects the first
app it finds in the app list
:param package: name of package/app
:type package: str
:return: None
:rtype: None
"""
log.debug("switching to app '... |
def switch_to_next_app(self):
"""
switches to the next app
"""
log.debug("switching to next app...")
cmd, url = DEVICE_URLS["switch_to_next_app"]
self.result = self._exec(cmd, url) |
def activate_widget(self, package):
"""
activate the widget of the given package
:param str package: name of the package
"""
cmd, url = DEVICE_URLS["activate_widget"]
# get widget id for the package
widget_id = self._get_widget_id(package)
url = url.form... |
def _app_exec(self, package, action, params=None):
"""
meta method for all interactions with apps
:param package: name of package/app
:type package: str
:param action: the action to be executed
:type action: str
:param params: optional parameters for this action
... |
def alarm_set(self, time, wake_with_radio=False):
"""
set the alarm clock
:param str time: time of the alarm (format: %H:%M:%S)
:param bool wake_with_radio: if True, radio will be used for the alarm
instead of beep sound
"""
# TODO: c... |
def alarm_disable(self):
"""
disable the alarm
"""
log.debug("alarm => disable...")
params = {"enabled": False}
self._app_exec("com.lametric.clock", "clock.alarm", params=params) |
def countdown_set(self, duration, start_now):
"""
set the countdown
:param str duration:
:param str start_now:
"""
log.debug("countdown => set...")
params = {'duration': duration, 'start_now': start_now}
self._app_exec(
"com.lametric.countdown... |
def action(self, includes: dict, variables: dict) -> tuple:
"""
Call external script.
:param includes: testcase's includes
:param variables: variables
:return: script's output
"""
json_args = fill_template_str(json.dumps(self.data), variables)
p = subproc... |
def set_credentials(self, client_id=None, client_secret=None):
"""
set given credentials and reset the session
"""
self._client_id = client_id
self._client_secret = client_secret
# make sure to reset session due to credential change
self._session = None |
def init_session(self, get_token=True):
"""
init a new oauth2 session that is required to access the cloud
:param bool get_token: if True, a token will be obtained, after
the session has been created
"""
if (self._client_id is None) or (self._clien... |
def get_token(self):
"""
get current oauth token
"""
self.token = self._session.fetch_token(
token_url=CLOUD_URLS["get_token"][1],
client_id=self._client_id,
client_secret=self._client_secret
) |
def simple_input(self, variables):
"""
Use this method to get simple input as python object, with all
templates filled in
:param variables:
:return: python object
"""
json_args = fill_template_str(json.dumps(self.data), variables)
return try_get_objects(... |
def create(self):
"""
creates an empty configuration file
"""
if not self.exists():
# create new empyt config file based on template
self.config.add_section("lametric")
self.config.set("lametric", "client_id", "")
self.config.set("lametric"... |
def save(self):
"""
save current config to the file
"""
with open(self._filename, "w") as f:
self.config.write(f) |
def rate_limit_wait(self):
"""
Sleep if rate limiting is required based on current time and last
query.
"""
if self._rate_limit_dt and self._last_query is not None:
dt = time.time() - self._last_query
wait = self._rate_limit_dt - dt
if wait > ... |
def route(self, arg, destination=None, waypoints=None, raw=False, **kwargs):
"""
Query a route.
route(locations): points can be
- a sequence of locations
- a Shapely LineString
route(origin, destination, waypoints=None)
- origin and destination are a... |
def from_geojson(cls, data):
"""
Return a Route from a GeoJSON dictionary, as returned by Route.geojson()
"""
properties = data['properties']
distance = properties.pop('distance')
duration = properties.pop('duration')
maneuvers = []
for feature in data['... |
def prepare_modules(module_paths: list, available: dict) -> dict:
"""
Scan all paths for external modules and form key-value dict.
:param module_paths: list of external modules (either python packages or third-party scripts)
:param available: dict of all registered python modules (can contain python mod... |
def discover_upnp_devices(
self, st="upnp:rootdevice", timeout=2, mx=1, retries=1
):
"""
sends an SSDP discovery packet to the network and collects
the devices that replies to it. A dictionary is returned
using the devices unique usn as key
"""
# prepare UDP s... |
def get_filtered_devices(
self, model_name, device_types="upnp:rootdevice", timeout=2
):
"""
returns a dict of devices that contain the given model name
"""
# get list of all UPNP devices in the network
upnp_devices = self.discover_upnp_devices(st=device_types)
... |
def lazy_map(data_processor, data_generator, n_cpus=1, stepsize=None):
"""A variant of multiprocessing.Pool.map that supports lazy evaluation
As with the regular multiprocessing.Pool.map, the processes are spawned off
asynchronously while the results are returned in order. In contrast to
multiprocessin... |
def lazy_imap(data_processor, data_generator, n_cpus=1, stepsize=None):
"""A variant of multiprocessing.Pool.imap that supports lazy evaluation
As with the regular multiprocessing.Pool.imap, the processes are spawned
off asynchronously while the results are returned in order. In contrast to
multiproces... |
def update_variables(func):
"""
Use this decorator on Step.action implementation.
Your action method should always return variables, or
both variables and output.
This decorator will update variables with output.
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
result = f... |
def _set_properties(self, data):
"""
set the properties of the app model by the given data dict
"""
for property in data.keys():
if property in vars(self):
setattr(self, property, data[property]) |
def get_long_description():
"""
get long description from README.rst file
"""
with codecs.open(os.path.join(here, "README.rst"), "r", "utf-8") as f:
return f.read() |
async def roll_call_handler(service, action_type, payload, props, **kwds):
"""
This action handler responds to the "roll call" emitted by the api
gateway when it is brought up with the normal summary produced by
the service.
"""
# if the action type corresponds to a roll call
if ... |
async def flexible_api_handler(service, action_type, payload, props, **kwds):
"""
This query handler builds the dynamic picture of availible services.
"""
# if the action represents a new service
if action_type == intialize_service_action():
# the treat the payload like json if its a str... |
def _parse_order_by(model, order_by):
"""
This function figures out the list of orderings for the given model and
argument.
Args:
model (nautilus.BaseModel): The model to compute ordering against
order_by (list of str): the list of fields to order_by. If the field
... |
def model(model_names):
"""
Creates the example directory structure necessary for a model service.
"""
# for each model name we need to create
for model_name in model_names:
# the template context
context = {
'name': model_name,
}
# render the model t... |
def api():
"""
Create the folder/directories for an ApiGateway service.
"""
# the template context
context = {
'name': 'api',
'secret_key': random_string(32)
}
render_template(template='common', context=context)
render_template(template='api', context=context) |
def auth():
"""
Create the folder/directories for an Auth service.
"""
# the template context
context = {
'name': 'auth',
}
render_template(template='common', context=context)
render_template(template='auth', context=context) |
def connection(model_connections):
"""
Creates the example directory structure necessary for a connection
service.
"""
# for each connection group
for connection_str in model_connections:
# the services to connect
services = connection_str.split(':')
services.so... |
def get_model_string(model):
"""
This function returns the conventional action designator for a given model.
"""
name = model if isinstance(model, str) else model.__name__
return normalize_string(name) |
def build_native_type_dictionary(fields, respect_required=False, wrap_field=True, name=''):
"""
This function takes a list of type summaries and builds a dictionary
with native representations of each entry. Useful for dynamically
building native class records from summaries.
"""
# a... |
def summarize_crud_mutation(method, model, isAsync=False):
"""
This function provides the standard form for crud mutations.
"""
# create the approrpriate action type
action_type = get_crud_action(method=method, model=model)
# the name of the mutation
name = crud_mutation_name(model=mode... |
def start(self):
"""
This function starts the brokers interaction with the kafka stream
"""
self.loop.run_until_complete(self._consumer.start())
self.loop.run_until_complete(self._producer.start())
self._consumer_task = self.loop.create_task(self._consume_event_callba... |
def stop(self):
"""
This method stops the brokers interaction with the kafka stream
"""
self.loop.run_until_complete(self._consumer.stop())
self.loop.run_until_complete(self._producer.stop())
# attempt
try:
# to cancel the service
self... |
async def send(self, payload='', action_type='', channel=None, **kwds):
"""
This method sends a message over the kafka stream.
"""
# use a custom channel if one was provided
channel = channel or self.producer_channel
# serialize the action type for the
messag... |
def serialize_action(action_type, payload, **extra_fields):
"""
This function returns the conventional form of the actions.
"""
action_dict = dict(
action_type=action_type,
payload=payload,
**extra_fields
)
# return a serializable version
return json.dumps(action... |
def fields_for_model(model):
"""
This function returns the fields for a schema that matches the provided
nautilus model.
Args:
model (nautilus.model.BaseModel): The model to base the field list on
Returns:
(dict<field_name: str, graphqlType>): A mapping of f... |
def create_connection_model(service):
""" Create an SQL Alchemy table that connects the provides services """
# the services connected
services = service._services
# the mixins / base for the model
bases = (BaseModel,)
# the fields of the derived
attributes = {model_service_name(service): f... |
def create_handler(Model, name=None, **kwds):
"""
This factory returns an action handler that creates a new instance of
the specified model when a create action is recieved, assuming the
action follows nautilus convetions.
Args:
Model (nautilus.BaseModel): The model to c... |
async def _has_id(self, *args, **kwds):
"""
Equality checks are overwitten to perform the actual check in a
semantic way.
"""
# if there is only one positional argument
if len(args) == 1:
# parse the appropriate query
result = await parse_s... |
def _find_id(self, result, uid):
"""
This method performs a depth-first search for the given uid in the dictionary of results.
"""
# if the result is a list
if isinstance(result, list):
# if the list has a valid entry
if any([self._find_id(value, uid) ... |
def add_before(self):
"""Returns a builder inserting a new block before the current block"""
idx = self._container.structure.index(self)
return BlockBuilder(self._container, idx) |
def add_after(self):
"""Returns a builder inserting a new block after the current block"""
idx = self._container.structure.index(self)
return BlockBuilder(self._container, idx+1) |
def comment(self, text, comment_prefix='#'):
"""Creates a comment block
Args:
text (str): content of comment without #
comment_prefix (str): character indicating start of comment
Returns:
self for chaining
"""
comment = Comment(self._containe... |
def section(self, section):
"""Creates a section block
Args:
section (str or :class:`Section`): name of section or object
Returns:
self for chaining
"""
if not isinstance(self._container, ConfigUpdater):
raise ValueError("Sections can only be... |
def space(self, newlines=1):
"""Creates a vertical space of newlines
Args:
newlines (int): number of empty lines
Returns:
self for chaining
"""
space = Space()
for line in range(newlines):
space.add_line('\n')
self._container.... |
def option(self, key, value=None, **kwargs):
"""Creates a new option inside a section
Args:
key (str): key of the option
value (str or None): value of the option
**kwargs: are passed to the constructor of :class:`Option`
Returns:
self for chainin... |
def add_comment(self, line):
"""Add a Comment object to the section
Used during initial parsing mainly
Args:
line (str): one line in the comment
"""
if not isinstance(self.last_item, Comment):
comment = Comment(self._structure)
self._structur... |
def add_space(self, line):
"""Add a Space object to the section
Used during initial parsing mainly
Args:
line (str): one line that defines the space, maybe whitespaces
"""
if not isinstance(self.last_item, Space):
space = Space(self._structure)
... |
def to_dict(self):
"""Transform to dictionary
Returns:
dict: dictionary with same content
"""
return {key: self.__getitem__(key).value for key in self.options()} |
def set(self, option, value=None):
"""Set an option for chaining.
Args:
option (str): option name
value (str): value, default None
"""
option = self._container.optionxform(option)
if option in self.options():
self.__getitem__(option).value = v... |
def set_values(self, values, separator='\n', indent=4*' '):
"""Sets the value to a given list of options, e.g. multi-line values
Args:
values (list): list of values
separator (str): separator for values, default: line separator
indent (str): indentation depth in case... |
def read(self, filename, encoding=None):
"""Read and parse a filename.
Args:
filename (str): path to file
encoding (str): encoding of file, default None
"""
with open(filename, encoding=encoding) as fp:
self._read(fp, filename)
self._filename ... |
def update_file(self):
"""Update the read-in configuration file.
"""
if self._filename is None:
raise NoConfigFileReadError()
with open(self._filename, 'w') as fb:
self.write(fb) |
def validate_format(self, **kwargs):
"""Call ConfigParser to validate config
Args:
kwargs: are passed to :class:`configparser.ConfigParser`
"""
args = dict(
dict_type=self._dict,
allow_no_value=self._allow_no_value,
inline_comment_prefixes... |
def add_section(self, section):
"""Create a new section in the configuration.
Raise DuplicateSectionError if a section by the specified name
already exists. Raise ValueError if name is DEFAULT.
Args:
section (str or :class:`Section`): name or Section type
"""
... |
def options(self, section):
"""Returns list of configuration options for the named section.
Args:
section (str): name of section
Returns:
list: list of option names
"""
if not self.has_section(section):
raise NoSectionError(section) from None... |
def get(self, section, option):
"""Gets an option value for a given section.
Args:
section (str): section name
option (str): option name
Returns:
:class:`Option`: Option object holding key/value pair
"""
if not self.has_section(section):
... |
def items(self, section=_UNSET):
"""Return a list of (name, value) tuples for options or sections.
If section is given, return a list of tuples with (name, value) for
each option in the section. Otherwise, return a list of tuples with
(section_name, section_type) for each section.
... |
def has_option(self, section, option):
"""Checks for the existence of a given option in a given section.
Args:
section (str): name of section
option (str): name of option
Returns:
bool: whether the option exists in the given section
"""
if se... |
def set(self, section, option, value=None):
"""Set an option.
Args:
section (str): section name
option (str): option name
value (str): value, default None
"""
try:
section = self.__getitem__(section)
except KeyError:
ra... |
def remove_option(self, section, option):
"""Remove an option.
Args:
section (str): section name
option (str): option name
Returns:
bool: whether the option was actually removed
"""
try:
section = self.__getitem__(section)
... |
def remove_section(self, name):
"""Remove a file section.
Args:
name: name of the section
Returns:
bool: whether the section was actually removed
"""
existed = self.has_section(name)
if existed:
idx = self._get_section_idx(name)
... |
def to_dict(self):
"""Transform to dictionary
Returns:
dict: dictionary with same content
"""
return {sect: self.__getitem__(sect).to_dict()
for sect in self.sections()} |
def render_template(template, out_dir='.', context=None):
'''
This function renders the template desginated by the argument to the
designated directory using the given context.
Args:
template (string) : the source template to use (relative to ./templates)
out_dir (st... |
def publish(type, payload):
"""
Publish a message with the specified action_type and payload over the
event system. Useful for debugging.
"""
async def _produce():
# fire an action with the given values
await producer.send(action_type=type, payload=payload)
# notify t... |
def delete_handler(Model, name=None, **kwds):
"""
This factory returns an action handler that deletes a new instance of
the specified model when a delete action is recieved, assuming the
action follows nautilus convetions.
Args:
Model (nautilus.BaseModel): The model to d... |
def read_handler(Model, name=None, **kwds):
"""
This factory returns an action handler that responds to read requests
by resolving the payload as a graphql query against the internal schema.
Args:
Model (nautilus.BaseModel): The model to delete when the action
r... |
def crud_handler(Model, name=None, **kwds):
"""
This action handler factory reaturns an action handler that
responds to actions with CRUD types (following nautilus conventions)
and performs the necessary mutation on the model's database.
Args:
Model (nautilus.BaseModel):... |
def ask(type, payload):
"""
Publish a message with the specified action_type and payload over the
event system. Useful for debugging.
"""
async def _produce():
# notify the user that we were successful
print("Dispatching action with type {}...".format(type))
# fire an... |
def _from_type(self, config):
"""
This method converts a type into a dict.
"""
def is_user_attribute(attr):
return (
not attr.startswith('__') and
not isinstance(getattr(config, attr), collections.abc.Callable)
)
return... |
async def walk_query(obj, object_resolver, connection_resolver, errors, current_user=None, __naut_name=None, obey_auth=True, **filters):
"""
This function traverses a query and collects the corresponding
information in a dictionary.
"""
# if the object has no selection set
if not hasattr... |
async def query_handler(service, action_type, payload, props, **kwds):
"""
This action handler interprets the payload as a query to be executed
by the api gateway service.
"""
# check that the action type indicates a query
if action_type == query_action_type():
print('encountered... |
def summarize_mutation_io(name, type, required=False):
"""
This function returns the standard summary for mutations inputs
and outputs
"""
return dict(
name=name,
type=type,
required=required
) |
def crud_mutation_name(action, model):
"""
This function returns the name of a mutation that performs the specified
crud action on the given model service
"""
model_string = get_model_string(model)
# make sure the mutation name is correctly camelcases
model_string = model_string[0].u... |
def create_mutation_inputs(service):
"""
Args:
service : The service being created by the mutation
Returns:
(list) : a list of all of the fields availible for the service,
with the required ones respected.
"""
# grab the default list of field summaries... |
def update_mutation_inputs(service):
"""
Args:
service : The service being updated by the mutation
Returns:
(list) : a list of all of the fields availible for the service. Pk
is a required field in order to filter the results
"""
# grab the default lis... |
def delete_mutation_inputs(service):
"""
Args:
service : The service being deleted by the mutation
Returns:
([str]): the only input for delete is the pk of the service.
"""
from nautilus.api.util import summarize_mutation_io
# the only input for delete events is... |
def _summarize_o_mutation_type(model):
"""
This function create the actual mutation io summary corresponding to the model
"""
from nautilus.api.util import summarize_mutation_io
# compute the appropriate name for the object
object_type_name = get_model_string(model)
# return a mutation ... |
def _summarize_object_type(model):
"""
This function returns the summary for a given model
"""
# the fields for the service's model
model_fields = {field.name: field for field in list(model.fields())}
# summarize the model
return {
'fields': [{
'name': key,
... |
def combine_action_handlers(*handlers):
"""
This function combines the given action handlers into a single function
which will call all of them.
"""
# make sure each of the given handlers is callable
for handler in handlers:
# if the handler is not a function
if not (isco... |
def update_handler(Model, name=None, **kwds):
"""
This factory returns an action handler that updates a new instance of
the specified model when a update action is recieved, assuming the
action follows nautilus convetions.
Args:
Model (nautilus.BaseModel): The model to u... |
def graphql_mutation_from_summary(summary):
"""
This function returns a graphql mutation corresponding to the provided
summary.
"""
# get the name of the mutation from the summary
mutation_name = summary['name']
# print(summary)
# the treat the "type" string as a gra
input_... |
def arg_string_from_dict(arg_dict, **kwds):
"""
This function takes a series of ditionaries and creates an argument
string for a graphql query
"""
# the filters dictionary
filters = {
**arg_dict,
**kwds,
}
# return the correctly formed string
return ", ".join(... |
def create_model_schema(target_model):
""" This function creates a graphql schema that provides a single model """
from nautilus.database import db
# create the schema instance
schema = graphene.Schema(auto_camelcase=False)
# grab the primary key from the model
primary_key = target_model.prim... |
def connection_service_name(service, *args):
''' the name of a service that manages the connection between services '''
# if the service is a string
if isinstance(service, str):
return service
return normalize_string(type(service).__name__) |
def read_session_token(secret_key, token):
"""
This function verifies the token using the secret key and returns its
contents.
"""
return jwt.decode(token.encode('utf-8'), secret_key,
algorithms=[token_encryption_algorithm()]
) |
async def handle_action(self, action_type, payload, **kwds):
"""
The default action Handler has no action.
"""
# if there is a service attached to the action handler
if hasattr(self, 'service'):
# handle roll calls
await roll_call_handler(self.service,... |
async def announce(self):
"""
This method is used to announce the existence of the service
"""
# send a serialized event
await self.event_broker.send(
action_type=intialize_service_action(),
payload=json.dumps(self.summarize())
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.