text
stringlengths
81
112k
Send an invitation mail to an open enrolment def _send_invitation(self, enrollment, event): """Send an invitation mail to an open enrolment""" self.log('Sending enrollment status mail to user') self._send_mail(self.config.invitation_subject, self.config.invitation_mail, enrollment, event)
Send an acceptance mail to an open enrolment def _send_acceptance(self, enrollment, password, event): """Send an acceptance mail to an open enrolment""" self.log('Sending acceptance status mail to user') if password is not "": password_hint = '\n\nPS: Your new password is ' + pass...
Connect to mail server and send actual email def _send_mail(self, subject, template, enrollment, event): """Connect to mail server and send actual email""" context = { 'name': enrollment.name, 'invitation_url': self.invitation_url, 'node_name': self.node_name, ...
Chat event handler for incoming events :param event: say-event with incoming chat message def say(self, event): """Chat event handler for incoming events :param event: say-event with incoming chat message """ try: userid = event.user.uuid recipient = sel...
Register event hook on reception of add_auth_hook-event def add_auth_hook(self, event): """Register event hook on reception of add_auth_hook-event""" self.log('Adding authentication hook for', event.authenticator_name) self.auth_hooks[event.authenticator_name] = event.event
Sends a failure message to the requesting client def _fail(self, event, message='Invalid credentials'): """Sends a failure message to the requesting client""" notification = { 'component': 'auth', 'action': 'fail', 'data': message } ip = event.sock....
Send login notification to client def _login(self, event, user_account, user_profile, client_config): """Send login notification to client""" user_account.lastlogin = std_now() user_account.save() user_account.passhash = "" self.fireEvent( authentication(user_accou...
Handles authentication requests from clients :param event: AuthenticationRequest with user's credentials def authenticationrequest(self, event): """Handles authentication requests from clients :param event: AuthenticationRequest with user's credentials """ if event.sock.getpeer...
Automatic logins for client configurations that allow it def _handle_autologin(self, event): """Automatic logins for client configurations that allow it""" self.log("Verifying automatic login request") # TODO: Check for a common secret # noinspection PyBroadException try: ...
Manual password based login def _handle_login(self, event): """Manual password based login""" # TODO: Refactor to simplify self.log("Auth request for ", event.username, 'client:', event.clientuuid) # TODO: Define the requirements for secure passwords etc. # T...
Retrieves a user's profile def _get_profile(self, user_account): """Retrieves a user's profile""" try: # TODO: Load active profile, not just any user_profile = objectmodels['profile'].find_one( {'owner': str(user_account.uuid)}) self.log("Profile: ",...
Called when a sensor sends a new raw data to this serial connector. The data is sanitized and sent to the registered protocol listeners as time/raw/bus sentence tuple. def _parse(self, bus, data): """ Called when a sensor sends a new raw data to this serial connector. The data...
Handles incoming raw sensor data :param data: raw incoming data def serial_packet(self, event): """Handles incoming raw sensor data :param data: raw incoming data """ self.log('Incoming serial packet:', event.__dict__, lvl=verbose) if self.scanning: pass ...
Entry point for the script def main(): """Entry point for the script""" desc = 'Converts between geodetic, modified apex, quasi-dipole and MLT' parser = argparse.ArgumentParser(description=desc, prog='apexpy') parser.add_argument('source', metavar='SOURCE', choices=['geo', 'ap...
Executes an external process via subprocess.Popen def run_process(cwd, args): """Executes an external process via subprocess.Popen""" try: process = check_output(args, cwd=cwd, stderr=STDOUT) return process except CalledProcessError as e: log('Uh oh, the teapot broke again! Error:'...
Securely and interactively ask for a password def _ask_password(): """Securely and interactively ask for a password""" password = "Foo" password_trial = "" while password != password_trial: password = getpass.getpass() password_trial = getpass.getpass(prompt="Repeat:") if pass...
Obtain user credentials by arguments or asking the user def _get_credentials(username=None, password=None, dbhost=None): """Obtain user credentials by arguments or asking the user""" # Database salt system_config = dbhost.objectmodels['systemconfig'].find_one({ 'active': True }) try: ...
Interactively ask the user for data def _ask(question, default=None, data_type='str', show_hint=False): """Interactively ask the user for data""" data = default if data_type == 'bool': data = None default_string = "Y" if default else "N" while data not in ('Y', 'J', 'N', '1', '0'...
Makes sure the latitude is inside [-90, 90], clipping close values (tolerance 1e-4). Parameters ========== lat : array_like latitude name : str, optional parameter name to use in the exception message Returns ======= lat : ndarray or float Same as input where va...
Computes sinIm from modified apex latitude. Parameters ========== alat : array_like Modified apex latitude Returns ======= sinIm : ndarray or float def getsinIm(alat): """Computes sinIm from modified apex latitude. Parameters ========== alat : array_like Modif...
Computes cosIm from modified apex latitude. Parameters ========== alat : array_like Modified apex latitude Returns ======= cosIm : ndarray or float def getcosIm(alat): """Computes cosIm from modified apex latitude. Parameters ========== alat : array_like Modif...
Converts :class:`datetime.date` or :class:`datetime.datetime` to decimal year. Parameters ========== date : :class:`datetime.date` or :class:`datetime.datetime` Returns ======= year : float Decimal year Notes ===== The algorithm is taken from http://stackoverflow.com/a...
Converts geocentric latitude to geodetic latitude using WGS84. Parameters ========== gclat : array_like Geocentric latitude Returns ======= gdlat : ndarray or float Geodetic latitude def gc2gdlat(gclat): """Converts geocentric latitude to geodetic latitude using WGS84. ...
Finds subsolar geocentric latitude and longitude. Parameters ========== datetime : :class:`datetime.datetime` Returns ======= sbsllat : float Latitude of subsolar point sbsllon : float Longitude of subsolar point Notes ===== Based on formulas in Astronomical Al...
Make the authentication headers needed to use the Appveyor API. def make_auth_headers(): """Make the authentication headers needed to use the Appveyor API.""" if not os.path.exists(".appveyor.token"): raise RuntimeError( "Please create a file named `.appveyor.token` in the current directory...
Get the details of the latest Appveyor build. def get_project_build(account_project): """Get the details of the latest Appveyor build.""" url = make_url("/projects/{account_project}", account_project=account_project) response = requests.get(url, headers=make_auth_headers()) return response.json()
Download a file from `url` to `filename`. def download_url(url, filename, headers): """Download a file from `url` to `filename`.""" ensure_dirs(filename) response = requests.get(url, headers=headers, stream=True) if response.status_code == 200: with open(filename, 'wb') as f: for ch...
Display a list of registered schemata def cli_schemata_list(self, *args): """Display a list of registered schemata""" self.log('Registered schemata languages:', ",".join(sorted(l10n_schemastore.keys()))) self.log('Registered Schemata:', ",".join(sorted(schemastore.keys()))) if '-c' in ...
Display a schemata's form definition def cli_form(self, *args): """Display a schemata's form definition""" if args[0] == '*': for schema in schemastore: self.log(schema, ':', schemastore[schema]['form'], pretty=True) else: self.log(schemastore[args[0]]['...
Display a single schema definition def cli_schema(self, *args): """Display a single schema definition""" key = None if len(args) > 1: key = args[1] args = list(args) if '-config' in args or '-c' in args: store = configschemastore try: ...
List all available form definitions def cli_forms(self, *args): """List all available form definitions""" forms = [] missing = [] for key, item in schemastore.items(): if 'form' in item and len(item['form']) > 0: forms.append(key) else: ...
Show default permissions for all schemata def cli_default_perms(self, *args): """Show default permissions for all schemata""" for key, item in schemastore.items(): # self.log(item, pretty=True) if item['schema'].get('no_perms', False): self.log('Schema without p...
Sets up the application after startup. def ready(self): """Sets up the application after startup.""" self.log('Got', len(schemastore), 'data and', len(configschemastore), 'component schemata.', lvl=debug)
Return all known schemata to the requesting client def all(self, event): """Return all known schemata to the requesting client""" self.log("Schemarequest for all schemata from", event.user, lvl=debug) response = { 'component': 'hfos.events.schemamanager', ...
Return a single schema def get(self, event): """Return a single schema""" self.log("Schemarequest for", event.data, "from", event.user, lvl=debug) if event.data in schemastore: response = { 'component': 'hfos.events.schemamanager', 'a...
Return all configurable components' schemata def configuration(self, event): """Return all configurable components' schemata""" try: self.log("Schemarequest for all configuration schemata from", event.user.account.name, lvl=debug) response = { ...
Generates a regular expression controlled UUID field def uuid_object(title="Reference", description="Select an object", default=None, display=True): """Generates a regular expression controlled UUID field""" uuid = { 'pattern': '^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{' '4}-[' ...
Generates a basic object with RBAC properties def base_object(name, no_perms=False, has_owner=True, hide_owner=True, has_uuid=True, roles_write=None, roles_read=None, roles_list=None, roles_c...
Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system Courtesy: Thomas ( http://stackoverflow.com/questions/12090503 /listing-available-com-ports-with-python ) def seri...
Generates a new reference frame from incoming sensordata :param event: new sensordata to be merged into referenceframe def sensordata(self, event): """ Generates a new reference frame from incoming sensordata :param event: new sensordata to be merged into referenceframe """ ...
Pushes the current :referenceframe: out to clients. :return: def navdatapush(self): """ Pushes the current :referenceframe: out to clients. :return: """ try: self.fireEvent(referenceframe({ 'data': self.referenceframe, 'ages': self.referenc...
Export stored objects Warning! This functionality is work in progress and you may destroy live data by using it! Be very careful when using the export/import functionality! def db_export(schema, uuid, object_filter, export_format, filename, pretty, all_schemata, omit): """Export stored objects Warnin...
Import objects from file Warning! This functionality is work in progress and you may destroy live data by using it! Be very careful when using the export/import functionality! def db_import(ctx, schema, uuid, object_filter, import_format, filename, all_schemata, dry): """Import objects from file Warn...
Checks if the newly created object is a wikipage.. If so, rerenders the automatic index. :param event: objectchange or objectcreation event def _page_update(self, event): """ Checks if the newly created object is a wikipage.. If so, rerenders the automatic index. :para...
Attempt to drop privileges and change user to 'hfos' user/group def drop_privileges(uid_name='hfos', gid_name='hfos'): """Attempt to drop privileges and change user to 'hfos' user/group""" if os.getuid() != 0: hfoslog("Not root, cannot drop privileges", lvl=warn, emitter='CORE') return tr...
Preliminary HFOS application Launcher def construct_graph(args): """Preliminary HFOS application Launcher""" app = Core(args) setup_root(app) if args['debug']: from circuits import Debugger hfoslog("Starting circuits debugger", lvl=warn, emitter='GRAPH') dbg = Debugger().regi...
Bootstrap basics, assemble graph and hand over control to the Core component def launch(run=True, **args): """Bootstrap basics, assemble graph and hand over control to the Core component""" verbosity['console'] = args['log'] if not args['quiet'] else 100 verbosity['global'] = min(args['log'], args...
All components have initialized, set up the component configuration schema-store, run the local server and drop privileges def ready(self, source): """All components have initialized, set up the component configuration schema-store, run the local server and drop privileges""" from hfos...
Event hook to trigger a new frontend build def trigger_frontend_build(self, event): """Event hook to trigger a new frontend build""" from hfos.database import instance install_frontend(instance=instance, forcerebuild=event.force, install=event....
Experimental call to reload the component tree def cli_reload(self, event): """Experimental call to reload the component tree""" self.log('Reloading all components.') self.update_components(forcereload=True) initialize() from hfos.debugger import cli_compgraph self.fi...
Provides information about the running instance def cli_info(self, event): """Provides information about the running instance""" self.log('Instance:', self.instance, 'Dev:', self.development, 'Host:', self.host, 'Port:', self.port, 'I...
Run the node local server def _start_server(self, *args): """Run the node local server""" self.log("Starting server", args) secure = self.certificate is not None if secure: self.log("Running SSL server with cert:", self.certificate) else: self.log("Runni...
Check all known entry points for components. If necessary, manage configuration updates def update_components(self, forcereload=False, forcerebuild=False, forcecopy=True, install=False): """Check all known entry points for components. If necessary, manage configuration...
Check if it is enabled and start the frontend http & websocket def _start_frontend(self, restart=False): """Check if it is enabled and start the frontend http & websocket""" self.log(self.config, self.config.frontendenabled, lvl=verbose) if self.config.frontendenabled and not self.frontendrunn...
Inspect all loadable components and run them def _instantiate_components(self, clear=True): """Inspect all loadable components and run them""" if clear: import objgraph from copy import deepcopy from circuits.tools import kill from circuits import Compon...
Sets up the application after startup. def started(self, component): """Sets up the application after startup.""" self.log("Running.") self.log("Started event origin: ", component, lvl=verbose) populate_user_events() from hfos.events.system import AuthorizedEvents self...
[GROUP] User management operations def user(ctx, username, password): """[GROUP] User management operations""" ctx.obj['username'] = username ctx.obj['password'] = password
Internal method to create a normal user def _create_user(ctx): """Internal method to create a normal user""" username, passhash = _get_credentials(ctx.obj['username'], ctx.obj['password'], ctx.obj['db']) if ctx.obj['db']....
Creates a new local user def create_user(ctx): """Creates a new local user""" try: new_user = _create_user(ctx) new_user.save() log("Done") except KeyError: log('User already exists', lvl=warn)
Creates a new local user and assigns admin role def create_admin(ctx): """Creates a new local user and assigns admin role""" try: admin = _create_user(ctx) admin.roles.append('admin') admin.save() log("Done") except KeyError: log('User already exists', lvl=warn)
Delete a local user def delete_user(ctx, yes): """Delete a local user""" if ctx.obj['username'] is None: username = _ask("Please enter username:") else: username = ctx.obj['username'] del_user = ctx.obj['db'].objectmodels['user'].find_one({'name': username}) if yes or _ask('Confir...
Change password of an existing user def change_password(ctx): """Change password of an existing user""" username, passhash = _get_credentials(ctx.obj['username'], ctx.obj['password'], ctx.obj['db']) change_user = ctx.obj[...
List all locally known users def list_users(ctx, search, uuid, active): """List all locally known users""" users = ctx.obj['db'].objectmodels['user'] for found_user in users.find(): if not search or (search and search in found_user.name): # TODO: Not 2.x compatible print(f...
Disable an existing user def disable(ctx): """Disable an existing user""" if ctx.obj['username'] is None: log('Specify the username with "iso db user --username ..."') return change_user = ctx.obj['db'].objectmodels['user'].find_one({ 'name': ctx.obj['username'] }) change...
Enable an existing user def enable(ctx): """Enable an existing user""" if ctx.obj['username'] is None: log('Specify the username with "iso db user --username ..."') return change_user = ctx.obj['db'].objectmodels['user'].find_one({ 'name': ctx.obj['username'] }) change_us...
Grant a role to an existing user def add_role(ctx, role): """Grant a role to an existing user""" if role is None: log('Specify the role with --role') return if ctx.obj['username'] is None: log('Specify the username with --username') return change_user = ctx.obj['db'].o...
>>> class mock_framework: ... def assertIn(self, item, list, msg="Failed asserting item is in list"): ... if item not in list: raise Exception(msg) ... def assertTrue(self, value, msg="Failed asserting true"): ... if not value: raise Exception(msg) ... def assertFalse(self, value, msg)...
Assemble a list of future alerts def _get_future_tasks(self): """Assemble a list of future alerts""" self.alerts = {} now = std_now() for task in objectmodels['task'].find({'alert_time': {'$gt': now}}): self.alerts[task.alert_time] = task self.log('Found', len(sel...
Periodical check to issue due alerts def check_alerts(self): """Periodical check to issue due alerts""" alerted = [] for alert_time, task in self.alerts.items(): task_time = dateutil.parser.parse(alert_time) if task_time < get_time(): self.log('Alerting...
Handles incoming raw sensor data and broadcasts it to specified udp servers and connected tcp clients :param data: NMEA raw sentences incoming data def read(self, data): """Handles incoming raw sensor data and broadcasts it to specified udp servers and connected tcp clients :par...
Generates a command map def cmdmap(xdot): """Generates a command map""" # TODO: Integrate the output into documentation from copy import copy def print_commands(command, map_output, groups=None, depth=0): if groups is None: groups = [] if 'commands' in command.__dict__: ...
Render a given pystache template with given content def format_template(template, content): """Render a given pystache template with given content""" import pystache result = u"" if True: # try: result = pystache.render(template, content, string_encoding='utf-8') # except (ValueEr...
Render a given pystache template file with given content def format_template_file(filename, content): """Render a given pystache template file with given content""" with open(filename, 'r') as f: template = f.read() if type(template) != str: template = template.decode('utf-8') ...
Write a new file from a given pystache template file and content def write_template_file(source, target, content): """Write a new file from a given pystache template file and content""" # print(formatTemplateFile(source, content)) print(target) data = format_template_file(source, content) with ope...
Insert a new nginx service definition def insert_nginx_service(definition): # pragma: no cover """Insert a new nginx service definition""" config_file = '/etc/nginx/sites-available/hfos.conf' splitter = "### SERVICE DEFINITIONS ###" with open(config_file, 'r') as f: old_config = "".join(f.re...
[GROUP] Role based access control def rbac(ctx, schema, object_filter, action, role, all_schemata): """[GROUP] Role based access control""" database = ctx.obj['db'] if schema is None: if all_schemata is False: log('No schema given. Read the RBAC group help', lvl=warn) sys....
Adds a role to an action on objects def add_action_role(ctx): """Adds a role to an action on objects""" objects = ctx.obj['objects'] action = ctx.obj['action'] role = ctx.obj['role'] if action is None or role is None: log('You need to specify an action or role to the RBAC command group fo...
Deletes a role from an action on objects def del_action_role(ctx): """Deletes a role from an action on objects""" objects = ctx.obj['objects'] action = ctx.obj['action'] role = ctx.obj['role'] if action is None or role is None: log('You need to specify an action or role to the RBAC comman...
Changes the ownership of objects def change_owner(ctx, owner, uuid): """Changes the ownership of objects""" objects = ctx.obj['objects'] database = ctx.obj['db'] if uuid is True: owner_filter = {'uuid': owner} else: owner_filter = {'name': owner} owner = database.objectmodels...
Notify a user def notify(self, event): """Notify a user""" self.log('Got a notification event!') self.log(event, pretty=True) self.log(event.__dict__)
Handler to deal with a possibly disconnected remote controlling client :param event: ClientDisconnect Event def clientdisconnect(self, event): """Handler to deal with a possibly disconnected remote controlling client :param event: ClientDisconnect Event """ try:...
Processes configuration list requests :param event: def getlist(self, event): """Processes configuration list requests :param event: """ try: componentlist = model_factory(Schema).find({}) data = [] for comp in componentlist: ...
Store a given configuration def put(self, event): """Store a given configuration""" self.log("Configuration put request ", event.user) try: component = model_factory(Schema).find_one({ 'uuid': event.data['uuid'] }) componen...
Get a stored configuration def get(self, event): """Get a stored configuration""" try: comp = event.data['uuid'] except KeyError: comp = None if not comp: self.log('Invalid get request without schema or component', lvl=error) ...
Records a single snapshot def rec(self): """Records a single snapshot""" try: self._snapshot() except Exception as e: self.log("Timer error: ", e, type(e), lvl=error)
Toggles the camera system recording state def _toggle_filming(self): """Toggles the camera system recording state""" if self._filming: self.log("Stopping operation") self._filming = False self.timer.stop() else: self.log("Starting operation") ...
A client has disconnected, update possible subscriptions accordingly. :param event: def client_disconnect(self, event): """ A client has disconnected, update possible subscriptions accordingly. :param event: """ self.log("Removing disconnected client from subscriptions...
Get a specified object def get(self, event): """Get a specified object""" try: data, schema, user, client = self._get_args(event) except AttributeError: return object_filter = self._get_filter(event) if 'subscribe' in data: do_subscribe = d...
Search for an object def search(self, event): """Search for an object""" try: data, schema, user, client = self._get_args(event) except AttributeError: return # object_filter['$text'] = {'$search': str(data['search'])} if data.get('fulltext', False) is ...
Get a list of objects def objectlist(self, event): """Get a list of objects""" self.log('LEGACY LIST FUNCTION CALLED!', lvl=warn) try: data, schema, user, client = self._get_args(event) except AttributeError: return object_filter = self._get_filter(even...
Change an existing object def change(self, event): """Change an existing object""" try: data, schema, user, client = self._get_args(event) except AttributeError: return try: uuid = data['uuid'] change = data['change'] field =...
Put an object def put(self, event): """Put an object""" try: data, schema, user, client = self._get_args(event) except AttributeError: return try: clientobject = data['obj'] uuid = clientobject['uuid'] except KeyError as e: ...
Delete an existing object def delete(self, event): """Delete an existing object""" try: data, schema, user, client = self._get_args(event) except AttributeError: return try: uuids = data['uuid'] if not isinstance(uuids, list): ...
Subscribe to an object's future changes def subscribe(self, event): """Subscribe to an object's future changes""" uuids = event.data if not isinstance(uuids, list): uuids = [uuids] subscribed = [] for uuid in uuids: try: self._add_subscr...
Unsubscribe from an object's future changes def unsubscribe(self, event): """Unsubscribe from an object's future changes""" # TODO: Automatic Unsubscription uuids = event.data if not isinstance(uuids, list): uuids = [uuids] result = [] for uuid in uuids: ...
OM event handler for to be stored and client shared objectmodels :param event: OMRequest with uuid, schema and object data def update_subscriptions(self, event): """OM event handler for to be stored and client shared objectmodels :param event: OMRequest with uuid, schema and object data ...
Project Importer for Github Repository Issues Argument REPOSITORY must be given as 'username/repository' Owner and project have to be UUIDs def GithubImporter(ctx, repository, all, owner, project, ignore_labels, no_tags, username, password): """Project Importer for Github Repository Issues Argument ...
Compile a list of all available language translations def all_languages(): """Compile a list of all available language translations""" rv = [] for lang in os.listdir(localedir): base = lang.split('_')[0].split('.')[0].split('@')[0] if 2 <= len(base) <= 3 and all(c.islower() for c in base)...
Get a descriptive title for all languages def language_token_to_name(languages): """Get a descriptive title for all languages""" result = {} with open(os.path.join(localedir, 'languages.json'), 'r') as f: language_lookup = json.load(f) for language in languages: language = language.l...
Debugging function to print all message language variants def print_messages(domain, msg): """Debugging function to print all message language variants""" domain = Domain(domain) for lang in all_languages(): print(lang, ':', domain.get(lang, msg))