text
stringlengths
81
112k
Sleep if rate limiting is required based on current time and last query. 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() - s...
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 single destination - waypoints are the points to be inserted between the ...
Return a Route from a GeoJSON dictionary, as returned by Route.geojson() 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 = proper...
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 modules from module_paths) :return: dict of external modules, where keys are ...
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 def discover_upnp_devices( self, st="upnp:rootdevice", timeout=2, mx=1, retries=1 ): """ sends an SSDP discovery packet to ...
returns a dict of devices that contain the given model name 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 upn...
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 multiprocessing.Pool.map, the iterator (here: data_generator) is not consumed at once bu...
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 multiprocessing.Pool.imap, the iterator (here: data_generator) is not consumed at once...
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. def update_variables(func): """ Use this decorator on Step.action implementation. Your action method should alw...
set the properties of the app model by the given data dict 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])
get long description from README.rst file 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()
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. async def roll_call_handler(service, action_type, payload, props, **kwds): """ This action handler responds to the "roll call" emitted by the api...
This query handler builds the dynamic picture of availible services. 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_se...
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 starts with a `+` then the order is acen...
Creates the example directory structure necessary for a model service. 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 = {...
Create the folder/directories for an ApiGateway service. 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) ...
Create the folder/directories for an Auth service. 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=contex...
Creates the example directory structure necessary for a connection service. 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...
This function returns the conventional action designator for a given model. 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)
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. def build_native_type_dictionary(fields, respect_required=False, wrap_field=True, name=''): """ This function ...
This function provides the standard form for crud mutations. 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...
This function starts the brokers interaction with the kafka stream 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()) se...
This method stops the brokers interaction with the kafka stream 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 ...
This method sends a message over the kafka stream. 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 ...
This function returns the conventional form of the actions. 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 ) ...
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 field names to graphql types ...
Create an SQL Alchemy table that connects the provides services 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 field...
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 create when the action received. Retur...
Equality checks are overwitten to perform the actual check in a semantic way. 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 l...
This method performs a depth-first search for the given uid in the dictionary of results. 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):...
Returns a builder inserting a new block before the current block 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)
Returns a builder inserting a new block after the current block 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)
Creates a comment block Args: text (str): content of comment without # comment_prefix (str): character indicating start of comment Returns: self for chaining def comment(self, text, comment_prefix='#'): """Creates a comment block Args: ...
Creates a section block Args: section (str or :class:`Section`): name of section or object Returns: self for chaining def section(self, section): """Creates a section block Args: section (str or :class:`Section`): name of section or object ...
Creates a vertical space of newlines Args: newlines (int): number of empty lines Returns: self for chaining def space(self, newlines=1): """Creates a vertical space of newlines Args: newlines (int): number of empty lines Returns: ...
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 chaining def option(self, key, value=None, **kwargs): ...
Add a Comment object to the section Used during initial parsing mainly Args: line (str): one line in the comment def add_comment(self, line): """Add a Comment object to the section Used during initial parsing mainly Args: line (str): one line in the c...
Add a Space object to the section Used during initial parsing mainly Args: line (str): one line that defines the space, maybe whitespaces def add_space(self, line): """Add a Space object to the section Used during initial parsing mainly Args: line (st...
Transform to dictionary Returns: dict: dictionary with same content def to_dict(self): """Transform to dictionary Returns: dict: dictionary with same content """ return {key: self.__getitem__(key).value for key in self.options()}
Set an option for chaining. Args: option (str): option name value (str): value, default None def set(self, option, value=None): """Set an option for chaining. Args: option (str): option name value (str): value, default None """ o...
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 of line separator def set_values(self, values, separator='\n', indent...
Read and parse a filename. Args: filename (str): path to file encoding (str): encoding of file, default None def read(self, filename, encoding=None): """Read and parse a filename. Args: filename (str): path to file encoding (str): encoding of fi...
Update the read-in configuration file. 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)
Call ConfigParser to validate config Args: kwargs: are passed to :class:`configparser.ConfigParser` def validate_format(self, **kwargs): """Call ConfigParser to validate config Args: kwargs: are passed to :class:`configparser.ConfigParser` """ args = di...
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 add_section(self, section): """Create a new sect...
Returns list of configuration options for the named section. Args: section (str): name of section Returns: list: list of option names def options(self, section): """Returns list of configuration options for the named section. Args: section (str): n...
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 def get(self, section, option): """Gets an option value for a given section. Args: ...
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. Args: section (str): optiona...
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 def has_option(self, section, option): """Checks for the existence...
Set an option. Args: section (str): section name option (str): option name value (str): value, default None def set(self, section, option, value=None): """Set an option. Args: section (str): section name option (str): option name ...
Remove an option. Args: section (str): section name option (str): option name Returns: bool: whether the option was actually removed def remove_option(self, section, option): """Remove an option. Args: section (str): section name ...
Remove a file section. Args: name: name of the section Returns: bool: whether the section was actually removed def remove_section(self, name): """Remove a file section. Args: name: name of the section Returns: bool: whether the...
Transform to dictionary Returns: dict: dictionary with same content 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()}
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 (string) : the name of the output directory context (dict) : the ...
Publish a message with the specified action_type and payload over the event system. Useful for debugging. def publish(type, payload): """ Publish a message with the specified action_type and payload over the event system. Useful for debugging. """ async def _produce(): # fir...
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 delete when the action received. Retur...
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 received. Returns: function(type, payloa...
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): The model to delete when the action receive...
Publish a message with the specified action_type and payload over the event system. Useful for debugging. 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 ...
This method converts a type into a dict. 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.a...
This function traverses a query and collects the corresponding information in a dictionary. 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 ...
This action handler interprets the payload as a query to be executed by the api gateway service. 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 th...
This function returns the standard summary for mutations inputs and outputs 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=...
This function returns the name of a mutation that performs the specified crud action on the given model service 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...
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. def create_mutation_inputs(service): """ Args: service : The service being created...
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 def update_mutation_inputs(service): """ Args: service : The s...
Args: service : The service being deleted by the mutation Returns: ([str]): the only input for delete is the pk of the service. def delete_mutation_inputs(service): """ Args: service : The service being deleted by the mutation Returns: ([str]...
This function create the actual mutation io summary corresponding to the model 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...
This function returns the summary for a given model 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 { ...
This function combines the given action handlers into a single function which will call all of them. 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 han...
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 update when the action received. Retur...
This function returns a graphql mutation corresponding to the provided summary. 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 = sum...
This function takes a series of ditionaries and creates an argument string for a graphql query 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 = { ...
This function creates a graphql schema that provides a single model 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) # gr...
the name of a service that manages the connection between services 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(servi...
This function verifies the token using the secret key and returns its contents. 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=...
The default action Handler has no action. 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 ...
This method is used to announce the existence of the 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(), ...
This function starts the service's network intefaces. Args: port (int): The port for the http server. def run(self, host="localhost", port=8000, shutdown_timeout=60.0, **kwargs): """ This function starts the service's network intefaces. Args: ...
This function is called when the service has finished running regardless of intentionally or not. def cleanup(self): """ This function is called when the service has finished running regardless of intentionally or not. """ # if an event broker has been creat...
This method provides a programatic way of added invidual routes to the http server. Args: url (str): the url to be handled by the request_handler request_handler (nautilus.network.RequestHandler): The request handler def add_http_endpoint(self, url, request_hand...
This method provides a decorator for adding endpoints to the http server. Args: route (str): The url to be handled by the RequestHandled config (dict): Configuration for the request handler Example: .. code-block:: python ...
This function generates a session token signed by the secret key which can be used to extract the user credentials in a verifiable way. def generate_session_token(secret_key, **payload): """ This function generates a session token signed by the secret key which can be used to extract the us...
This function provides a standard representation of mutations to be used when services announce themselves def summarize_mutation(mutation_name, event, inputs, outputs, isAsync=False): """ This function provides a standard representation of mutations to be used when services announce themse...
Creates a PasswordHash from the given password. def new(cls, password, rounds): """Creates a PasswordHash from the given password.""" if isinstance(password, str): password = password.encode('utf-8') return cls(cls._new(password, rounds))
Ensure that loaded values are PasswordHashes. def coerce(cls, key, value): """Ensure that loaded values are PasswordHashes.""" if isinstance(value, PasswordHash): return value return super(PasswordHash, cls).coerce(key, value)
Recreates the internal hash. def rehash(self, password): """Recreates the internal hash.""" self.hash = self._new(password, self.desired_rounds) self.rounds = self.desired_rounds
This function configures the database used for models to make the configuration parameters. def init_db(self): """ This function configures the database used for models to make the configuration parameters. """ # get the database url from the configuration ...
This attribute provides the mapping of services to their auth requirement Returns: (dict) : the mapping from services to their auth requirements. def auth_criteria(self): """ This attribute provides the mapping of services to their auth requirement Returns:...
This function handles the registration of the given user credentials in the database async def login_user(self, password, **kwds): """ This function handles the registration of the given user credentials in the database """ # find the matching user with the given email user_...
This function is used to provide a sessionToken for later requests. Args: uid (str): The async def register_user(self, password, **kwds): """ This function is used to provide a sessionToken for later requests. Args: uid (str): The ""...
This function resolves a given object in the remote backend services async def object_resolver(self, object_name, fields, obey_auth=False, current_user=None, **filters): """ This function resolves a given object in the remote backend services """ try: # check if an obje...
the default behavior for mutations is to look up the event, publish the correct event type with the args as the body, and return the fields contained in the result async def mutation_resolver(self, mutation_name, args, fields): """ the default behavior for mutations is to lo...
This function checks if there is a user with the same uid in the remote user service Args: **kwds : the filters of the user to check for Returns: (bool): wether or not there is a matching user async def _check_for_matching_user(self, **user_filters): ...
This method creates a service record in the remote user service with the given email. Args: uid (str): the user identifier to create Returns: (dict): a summary of the user that was created async def _create_remote_user(self, **payload): """ ...
Calculation of WER with Levenshtein distance. Works only for iterables up to 254 elements (uint8). O(nm) time and space complexity. >>> calculate_wer("who is there".split(), "is there".split()) 1 >>> calculate_wer("who is there".split(), "".split()) 3 >>> calcula...
Get a parser object def get_parser(): """Get a parser object""" from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("-s1", dest="s1", help="sequence...
Perform a GET web request and return a bs4 parser async def _async_request_soup(url): ''' Perform a GET web request and return a bs4 parser ''' from bs4 import BeautifulSoup import aiohttp _LOGGER.debug('GET %s', url) async with aiohttp.ClientSession() as session: resp = await sessi...
Check whether the current channel is correct. If not try to determine it using fuzzywuzzy async def async_determine_channel(channel): ''' Check whether the current channel is correct. If not try to determine it using fuzzywuzzy ''' from fuzzywuzzy import process channel_data = await async_g...
Get channel list and corresponding urls async def async_get_channels(no_cache=False, refresh_interval=4): ''' Get channel list and corresponding urls ''' # Check cache now = datetime.datetime.now() max_cache_age = datetime.timedelta(hours=refresh_interval) if not no_cache and 'channels' in ...