text
stringlengths
81
112k
Gettext function wrapper to return a message in a specified language by domain To use internationalization (i18n) on your messages, import it as '_' and use as usual. Do not forget to supply the client's language setting. def i18n(msg, event=None, lang='en', domain='backend'): """Gettext function wrapper ...
Generates a cryptographically strong (sha512) hash with this nodes salt added. def std_hash(word, salt): """Generates a cryptographically strong (sha512) hash with this nodes salt added.""" try: password = word.encode('utf-8') except UnicodeDecodeError: password = word word_ha...
Return a random generated human-friendly phrase as low-probability unique id def std_human_uid(kind=None): """Return a random generated human-friendly phrase as low-probability unique id""" kind_list = alphabet if kind == 'animal': kind_list = animals elif kind == 'place': kind_list =...
Return a formatted table of given rows def std_table(rows): """Return a formatted table of given rows""" result = "" if len(rows) > 1: headers = rows[0]._fields lens = [] for i in range(len(rows[0])): lens.append(len(max([x[i] for x in rows] + [headers[i]], ...
Generates a cryptographically sane salt of 'length' (default: 16) alphanumeric characters def std_salt(length=16, lowercase=True): """Generates a cryptographically sane salt of 'length' (default: 16) alphanumeric characters """ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" if lowercase is ...
Add a new translation language to the live gettext translator def _get_translation(self, lang): """Add a new translation language to the live gettext translator""" try: return self._translations[lang] except KeyError: # The fact that `fallback=True` is not the default i...
Creates an Event Handler This decorator can be applied to methods of classes derived from :class:`circuits.core.components.BaseComponent`. It marks the method as a handler for the events passed as arguments to the ``@handler`` decorator. The events are specified by their name. The decorated method...
Log a statement from this component def log(self, *args, **kwargs): """Log a statement from this component""" func = inspect.currentframe().f_back.f_code # Dump the message + the name of this function to the log. if 'exc' in kwargs and kwargs['exc'] is True: exc_type, exc_...
Register a configurable component in the configuration schema store def register(self, *args): """Register a configurable component in the configuration schema store""" super(ConfigurableMeta, self).register(*args) from hfos.database import configschemastore # self.log(...
Removes the unique name from the systems unique name list def unregister(self): """Removes the unique name from the systems unique name list""" self.names.remove(self.uniquename) super(ConfigurableMeta, self).unregister()
Read this component's configuration from the database def _read_config(self): """Read this component's configuration from the database""" try: self.config = self.componentmodel.find_one( {'name': self.uniquename}) except ServerSelectionTimeoutError: # pragma: no co...
Write this component's configuration back to the database def _write_config(self): """Write this component's configuration back to the database""" if not self.config: self.log("Unable to write non existing configuration", lvl=error) return self.config.save() se...
Set this component's initial configuration def _set_config(self, config=None): """Set this component's initial configuration""" if not config: config = {} try: # pprint(self.configschema) self.config = self.componentmodel(config) # self.log("Conf...
Event triggered configuration reload def reload_configuration(self, event): """Event triggered configuration reload""" if event.target == self.uniquename: self.log('Reloading configuration') self._read_config()
Fill out the template information def _augment_info(info): """Fill out the template information""" info['description_header'] = "=" * len(info['description']) info['component_name'] = info['plugin_name'].capitalize() info['year'] = time.localtime().tm_year info['license_longtext'] = '' info['...
Build a module from templates and user supplied information def _construct_module(info, target): """Build a module from templates and user supplied information""" for path in paths: real_path = os.path.abspath(os.path.join(target, path.format(**info))) log("Making directory '%s'" % real_path) ...
Asks questions to fill out a HFOS plugin template def _ask_questionnaire(): """Asks questions to fill out a HFOS plugin template""" answers = {} print(info_header) pprint(questions.items()) for question, default in questions.items(): response = _ask(question, default, str(type(default)), ...
Creates a new template HFOS plugin module def create_module(clear_target, target): """Creates a new template HFOS plugin module""" if os.path.exists(target): if clear_target: shutil.rmtree(target) else: log("Target exists! Use --clear to delete it first.", ...
Generates a lookup field for form definitions def lookup_field(key, lookup_type=None, placeholder=None, html_class="div", select_type="strapselect", mapping="uuid"): """Generates a lookup field for form definitions""" if lookup_type is None: lookup_type = key if placeholder is No...
A field set with a title and sub items def fieldset(title, items, options=None): """A field set with a title and sub items""" result = { 'title': title, 'type': 'fieldset', 'items': items } if options is not None: result.update(options) return result
A section consisting of rows and columns def section(rows, columns, items, label=None): """A section consisting of rows and columns""" # TODO: Integrate label sections = [] column_class = "section-column col-sm-%i" % (12 / columns) for vertical in range(columns): column_items = [] ...
An array that starts empty def emptyArray(key, add_label=None): """An array that starts empty""" result = { 'key': key, 'startEmpty': True } if add_label is not None: result['add'] = add_label result['style'] = {'add': 'btn-success'} return result
A tabbed container widget def tabset(titles, contents): """A tabbed container widget""" tabs = [] for no, title in enumerate(titles): tab = { 'title': title, } content = contents[no] if isinstance(content, list): tab['items'] = content else: ...
Provides a select box for country selection def country_field(key='country'): """Provides a select box for country selection""" country_list = list(countries) title_map = [] for item in country_list: title_map.append({'value': item.alpha_3, 'name': item.name}) widget = { 'key': ke...
Provides a select box for country selection def area_field(key='area'): """Provides a select box for country selection""" area_list = list(subdivisions) title_map = [] for item in area_list: title_map.append({'value': item.code, 'name': item.name}) widget = { 'key': key, '...
Tests internet connectivity in regular intervals and updates the nodestate accordingly def timed_connectivity_check(self, event): """Tests internet connectivity in regular intervals and updates the nodestate accordingly""" self.status = self._can_connect() self.log('Timed connectivity check:', ...
Tries to connect to the configured host:port and returns True if the connection was established def _can_connect(self): """Tries to connect to the configured host:port and returns True if the connection was established""" self.log('Trying to reach configured connectivity check endpoint', lvl=verbose) ...
Handles navigational reference frame updates. These are necessary to assign geo coordinates to alerts and other misc things. :param event with incoming referenceframe message def referenceframe(self, event): """Handles navigational reference frame updates. These are necessary t...
ActivityMonitor event handler for incoming events :param event with incoming ActivityMonitor message def activityrequest(self, event): """ActivityMonitor event handler for incoming events :param event with incoming ActivityMonitor message """ # self.log("Event: '%s'" % event....
Modify field values of objects def modify(ctx, schema, uuid, object_filter, field, value): """Modify field values of objects""" database = ctx.obj['db'] model = database.objectmodels[schema] obj = None if uuid: obj = model.find_one({'uuid': uuid}) elif object_filter: obj = mod...
Show stored objects def view(ctx, schema, uuid, object_filter): """Show stored objects""" database = ctx.obj['db'] if schema is None: log('No schema given. Read the help', lvl=warn) return model = database.objectmodels[schema] if uuid: obj = model.find({'uuid': uuid}) ...
Delete stored objects (CAUTION!) def delete(ctx, schema, uuid, object_filter, yes): """Delete stored objects (CAUTION!)""" database = ctx.obj['db'] if schema is None: log('No schema given. Read the help', lvl=warn) return model = database.objectmodels[schema] if uuid: co...
Validates all objects or all objects of a given schema. def validate(ctx, schema, all_schemata): """Validates all objects or all objects of a given schema.""" database = ctx.obj['db'] if schema is None: if all_schemata is False: log('No schema given. Read the help', lvl=warn) ...
Find fields in registered data models. def find_field(ctx, search, by_type, obj): """Find fields in registered data models.""" # TODO: Fix this to work recursively on all possible subschemes if search is not None: search = search else: search = _ask("Enter search term") database =...
Get distance between pairs of lat-lon points def Distance(lat1, lon1, lat2, lon2): """Get distance between pairs of lat-lon points""" az12, az21, dist = wgs84_geod.inv(lon1, lat1, lon2, lat2) return az21, dist
Display known details about a given client def client_details(self, *args): """Display known details about a given client""" self.log(_('Client details:', lang='de')) client = self._clients[args[0]] self.log('UUID:', client.uuid, 'IP:', client.ip, 'Name:', client.name, 'User:', self._...
Display a list of connected clients def client_list(self, *args): """Display a list of connected clients""" if len(self._clients) == 0: self.log('No clients connected') else: self.log(self._clients, pretty=True)
Display a list of connected users def users_list(self, *args): """Display a list of connected users""" if len(self._users) == 0: self.log('No users connected') else: self.log(self._users, pretty=True)
Display a list of all registered events def sourcess_list(self, *args): """Display a list of all registered events""" from pprint import pprint sources = {} sources.update(self.authorized_events) sources.update(self.anonymous_events) for source in sources: ...
Display a list of all registered events def events_list(self, *args): """Display a list of all registered events""" def merge(a, b, path=None): "merges b into a" if path is None: path = [] for key in b: if key in a: if isinstance(...
Display a table of connected users and clients def who(self, *args): """Display a table of connected users and clients""" if len(self._users) == 0: self.log('No users connected') if len(self._clients) == 0: self.log('No clients connected') return ...
Handles socket disconnections def disconnect(self, sock): """Handles socket disconnections""" self.log("Disconnect ", sock, lvl=debug) try: if sock in self._sockets: self.log("Getting socket", lvl=debug) sockobj = self._sockets[sock] ...
Log out a client and possibly associated user def _logoutclient(self, useruuid, clientuuid): """Log out a client and possibly associated user""" self.log("Cleaning up client of logged in user.", lvl=debug) try: self._users[useruuid].clients.remove(clientuuid) if len(sel...
Registers new sockets and their clients and allocates uuids def connect(self, *args): """Registers new sockets and their clients and allocates uuids""" self.log("Connect ", args, lvl=verbose) try: sock = args[0] ip = args[1] if sock not in self._sockets: ...
Sends a packet to an already known user or one of his clients by UUID def send(self, event): """Sends a packet to an already known user or one of his clients by UUID""" try: jsonpacket = json.dumps(event.packet, cls=ComplexEncoder) if event.sendtype == "user": ...
Broadcasts an event either to all users or clients, depending on event flag def broadcast(self, event): """Broadcasts an event either to all users or clients, depending on event flag""" try: if event.broadcasttype == "users": if len(self._users) > 0: ...
Checks if the user has in any role that allows to fire the event. def _checkPermissions(self, user, event): """Checks if the user has in any role that allows to fire the event.""" for role in user.account.roles: if role in event.roles: self.log('Access granted', lvl=verbose...
Isolated communication link for authorized events. def _handleAuthorizedEvents(self, component, action, data, user, client): """Isolated communication link for authorized events.""" try: if component == "debugger": self.log(component, action, data, user, client, lvl=info) ...
Handler for anonymous (public) events def _handleAnonymousEvents(self, component, action, data, client): """Handler for anonymous (public) events""" try: event = self.anonymous_events[component][action]['event'] self.log("Firing anonymous event: ", component, action, ...
Handler for authentication events def _handleAuthenticationEvents(self, requestdata, requestaction, clientuuid, sock): """Handler for authentication events""" # TODO: Move this stuff over to ./auth.py if requestaction in ("login", "autologin"): t...
Resets the list of flood offenders on event trigger def _reset_flood_offenders(self, *args): """Resets the list of flood offenders on event trigger""" offenders = [] # self.log('Resetting flood offenders') for offender, offence_time in self._flooding.items(): if time() - o...
Checks if any clients have been flooding the node def _check_flood_protection(self, component, action, clientuuid): """Checks if any clients have been flooding the node""" if clientuuid not in self._flood_counter: self._flood_counter[clientuuid] = 0 self._flood_counter[clientuuid]...
Handles raw client requests and distributes them to the appropriate components def read(self, *args): """Handles raw client requests and distributes them to the appropriate components""" self.log("Beginning new transaction: ", args, lvl=network) try: sock, msg = arg...
Links the client to the granted account and profile, then notifies the client def authentication(self, event): """Links the client to the granted account and profile, then notifies the client""" try: self.log("Authorization has been granted by DB check:", ...
Store client's selection of a new translation def selectlanguage(self, event): """Store client's selection of a new translation""" self.log('Language selection event:', event.client, pretty=True) if event.data not in all_languages(): self.log('Unavailable language selected:', even...
Compile and return a human readable list of registered translations def getlanguages(self, event): """Compile and return a human readable list of registered translations""" self.log('Client requests all languages.', lvl=verbose) result = { 'component': 'hfos.ui.clientmanager', ...
Perform a ping to measure client <-> node latency def ping(self, event): """Perform a ping to measure client <-> node latency""" self.log('Client ping received:', event.data, lvl=verbose) response = { 'component': 'hfos.ui.clientmanager', 'action': 'pong', '...
Converts between geodetic, modified apex, quasi-dipole and MLT. Parameters ========== lat : array_like Latitude lon : array_like Longitude/MLT source : {'geo', 'apex', 'qd', 'mlt'} Input coordinate system dest : {'geo', 'apex', 'qd', '...
Converts geodetic to modified apex coordinates. Parameters ========== glat : array_like Geodetic latitude glon : array_like Geodetic longitude height : array_like Altitude in km Returns ======= alat : ndarray or float ...
Converts modified apex to geodetic coordinates. Parameters ========== alat : array_like Modified apex latitude alon : array_like Modified apex longitude height : array_like Altitude in km precision : float, optional Precisi...
Converts geodetic to quasi-dipole coordinates. Parameters ========== glat : array_like Geodetic latitude glon : array_like Geodetic longitude height : array_like Altitude in km Returns ======= qlat : ndarray or float ...
Converts quasi-dipole to geodetic coordinates. Parameters ========== qlat : array_like Quasi-dipole latitude qlon : array_like Quasi-dipole longitude height : array_like Altitude in km precision : float, optional Precision ...
Convert from apex to quasi-dipole (not-vectorised) Parameters ----------- alat : (float) Apex latitude in degrees alon : (float) Apex longitude in degrees height : (float) Height in km Returns --------- qlat : (float) ...
Converts modified apex to quasi-dipole coordinates. Parameters ========== alat : array_like Modified apex latitude alon : array_like Modified apex longitude height : array_like Altitude in km Returns ======= qlat : nda...
Converts quasi-dipole to modified apex coordinates. Parameters ========== qlat : array_like Quasi-dipole latitude qlon : array_like Quasi-dipole longitude height : array_like Altitude in km Returns ======= alat : ndarr...
Computes the magnetic local time at the specified magnetic longitude and UT. Parameters ========== mlon : array_like Magnetic longitude (apex and quasi-dipole longitude are always equal) datetime : :class:`datetime.datetime` Date and time ...
Computes the magnetic longitude at the specified magnetic local time and UT. Parameters ========== mlt : array_like Magnetic local time datetime : :class:`datetime.datetime` Date and time ssheight : float, optional Altitude in km to us...
Performs mapping of points along the magnetic field to the closest or conjugate hemisphere. Parameters ========== glat : array_like Geodetic latitude glon : array_like Geodetic longitude height : array_like Source altitude in km ...
Performs mapping of electric field along the magnetic field. It is assumed that the electric field is perpendicular to B. Parameters ========== alat : (N,) array_like or float Modified apex latitude alon : (N,) array_like or float Modified apex longitude...
Performs mapping of electric drift velocity along the magnetic field. It is assumed that the electric field is perpendicular to B. Parameters ========== alat : (N,) array_like or float Modified apex latitude alon : (N,) array_like or float Modified apex ...
Returns quasi-dipole base vectors f1 and f2 at the specified coordinates. The vectors are described by Richmond [1995] [2]_ and Emmert et al. [2010] [3]_. The vector components are geodetic east and north. Parameters ========== lat : (N,) array_like or float ...
Returns base vectors in quasi-dipole and apex coordinates. The vectors are described by Richmond [1995] [4]_ and Emmert et al. [2010] [5]_. The vector components are geodetic east, north, and up (only east and north for `f1` and `f2`). Parameters ========== lat, lon : ...
Calculate apex height Parameters ----------- lat : (float) Latitude in degrees height : (float or NoneType) Height above the surface of the earth in km or NoneType to use reference height (default=None) Returns ---------- apex...
Updates the epoch for all subsequent conversions. Parameters ========== year : float Decimal year def set_epoch(self, year): """Updates the epoch for all subsequent conversions. Parameters ========== year : float Decimal year ""...
Basic ordered parser. def basic_parser(patterns, with_name=None): """ Basic ordered parser. """ def parse(line): output = None highest_order = 0 highest_pattern_name = None for pattern in patterns: results = pattern.findall(line) if results and any(re...
This parser is able to handle multiple different patterns finding stuff in text-- while removing matches that overlap. def alt_parser(patterns): """ This parser is able to handle multiple different patterns finding stuff in text-- while removing matches that overlap. """ from reparse.util i...
This parser_type simply outputs an array of [(tree, regex)] for use in another language. def build_tree_parser(patterns): """ This parser_type simply outputs an array of [(tree, regex)] for use in another language. """ def output(): for pattern in patterns: yield (patter...
A Reparse parser description. Simply provide the functions, patterns, & expressions to build. If you are using YAML for expressions + patterns, you can use ``expressions_yaml_path`` & ``patterns_yaml_path`` for convenience. The default parser_type is the basic ordered parser. def parse...
Translate KML file to geojson for import def _translate(self, input_filename, output_filename): """Translate KML file to geojson for import""" command = [ self.translate_binary, '-f', 'GeoJSON', output_filename, input_filename ] result = ...
Update a single specified guide def _update_guide(self, guide, update=False, clear=True): """Update a single specified guide""" kml_filename = os.path.join(self.cache_path, guide + '.kml') geojson_filename = os.path.join(self.cache_path, guide + '.geojson') if not os.path.exists(geojs...
Worker task to send out an email, which is a blocking process unless it is threaded def send_mail_worker(config, mail, event): """Worker task to send out an email, which is a blocking process unless it is threaded""" log = "" try: if config.get('ssl', True): server = SMTP_SSL(config['s...
Connect to mail server and send actual email def send_mail(self, event): """Connect to mail server and send actual email""" mime_mail = MIMEText(event.text) mime_mail['Subject'] = event.subject if event.account == 'default': account_name = self.config.default_account ...
Provision a system user def provision_system_user(items, database_name, overwrite=False, clear=False, skip_user_check=False): """Provision a system user""" from hfos.provisions.base import provisionList from hfos.database import objectmodels # TODO: Add a root user and make sure owner can access it l...
Group expressions using the OR character ``|`` >>> from collections import namedtuple >>> expr = namedtuple('expr', 'regex group_lengths run')('(1)', [1], None) >>> grouping = AlternatesGroup([expr, expr], lambda f: None, 'yeah') >>> grouping.regex # doctest: +IGNORE_UNICODE '(?:(1))|(?:(1))' >...
Group expressions together with ``inbetweens`` and with the output of a ``final_functions``. def Group(expressions, final_function, inbetweens, name=""): """ Group expressions together with ``inbetweens`` and with the output of a ``final_functions``. """ lengths = [] functions = [] regex = "" i...
Parse string, returning all outputs as parsed by functions def findall(self, string): """ Parse string, returning all outputs as parsed by functions """ output = [] for match in self.pattern.findall(string): if hasattr(match, 'strip'): match = [match] ...
Like findall, but also returning matching start and end string locations def scan(self, string): """ Like findall, but also returning matching start and end string locations """ return list(self._scanner_to_matches(self.pattern.scanner(string), self.run))
Run group functions over matches def run(self, matches): """ Run group functions over matches """ def _run(matches): group_starting_pos = 0 for current_pos, (group_length, group_function) in enumerate(zip(self.group_lengths, self.group_functions)): start_...
Specify logfile path def set_logfile(path, instance): """Specify logfile path""" global logfile logfile = os.path.normpath(path) + '/hfos.' + instance + '.log'
Checks if a logged event is to be muted for debugging purposes. Also goes through the solo list - only items in there will be logged! :param what: :return: def is_muted(what): """ Checks if a logged event is to be muted for debugging purposes. Also goes through the solo list - only items in ...
Logs all *what arguments. :param *what: Loggable objects (i.e. they have a string representation) :param lvl: Debug message level :param exc: Switch to better handle exceptions, use if logging in an except clause :param emitter: Optional log source, where this can't be determined ...
Return a list of tagged objects for a schema def get_tagged(self, event): """Return a list of tagged objects for a schema""" self.log("Tagged objects request for", event.data, "from", event.user, lvl=debug) if event.data in self.tags: tagged = self._get_tagged(event...
Provisions the default system vessel def provision_system_vessel(items, database_name, overwrite=False, clear=False, skip_user_check=False): """Provisions the default system vessel""" from hfos.provisions.base import provisionList from hfos.database import objectmodels vessel = objectmodels['vessel']...
Threadable function to retrieve map tiles from the internet :param url: URL of tile to get def get_tile(url): """ Threadable function to retrieve map tiles from the internet :param url: URL of tile to get """ log = "" connection = None try: if six.PY3: connection = ...
Checks and caches a requested tile to disk, then delivers it to client def tilecache(self, event, *args, **kwargs): """Checks and caches a requested tile to disk, then delivers it to client""" request, response = event.args[:2] self.log(request.path, lvl=verbose) try: ...
Convert from [+/-]DDD°MMM'SSS.SSSS" or [+/-]DDD°MMM.MMMM' to [+/-]DDD.DDDDD def todegdec(origin): """ Convert from [+/-]DDD°MMM'SSS.SSSS" or [+/-]DDD°MMM.MMMM' to [+/-]DDD.DDDDD """ # if the input is already a float (or can be converted to float) try: return float(origin) except ValueE...
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes) def tomindec(origin): """ Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes) """ origin = float(origin) degrees = int(origin) minutes = (origin % 1) * 60 return degrees, minutes
Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM.MMMM' def tomindecstr(origin): """ Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM.MMMM' """ degrees, minutes = tomindec(origin) return u'%d°%f\'' % (degrees, minutes)
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes, seconds) def todms(origin): """ Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes, seconds) """ degrees, minutes = tomindec(origin) seconds = (minutes % 1) * 60 return degrees, int(minutes), seconds
Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM'DDD.DDDDD" def todmsstr(origin): """ Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM'DDD.DDDDD" """ degrees, minutes, seconds = todms(origin) return u'%d°%d\'%f"' % (degrees, minutes, seconds)