idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
5,100
def _fail ( self , event , message = 'Invalid credentials' ) : notification = { 'component' : 'auth' , 'action' : 'fail' , 'data' : message } ip = event . sock . getpeername ( ) [ 0 ] self . failing_clients [ ip ] = event Timer ( 3 , Event . create ( 'notify_fail' , event . clientuuid , notification , ip ) ) . register...
Sends a failure message to the requesting client
5,101
def _login ( self , event , user_account , user_profile , client_config ) : user_account . lastlogin = std_now ( ) user_account . save ( ) user_account . passhash = "" self . fireEvent ( authentication ( user_account . name , ( user_account , user_profile , client_config ) , event . clientuuid , user_account . uuid , e...
Send login notification to client
5,102
def _handle_autologin ( self , event ) : self . log ( "Verifying automatic login request" ) try : client_config = objectmodels [ 'client' ] . find_one ( { 'uuid' : event . requestedclientuuid } ) except Exception : client_config = None if client_config is None or client_config . autologin is False : self . log ( "Autol...
Automatic logins for client configurations that allow it
5,103
def _handle_login ( self , event ) : self . log ( "Auth request for " , event . username , 'client:' , event . clientuuid ) if ( len ( event . username ) < 1 ) or ( len ( event . password ) < 5 ) : self . log ( "Illegal username or password received, login cancelled" , lvl = warn ) self . _fail ( event , 'Password or u...
Manual password based login
5,104
def _get_profile ( self , user_account ) : try : user_profile = objectmodels [ 'profile' ] . find_one ( { 'owner' : str ( user_account . uuid ) } ) self . log ( "Profile: " , user_profile , user_account . uuid , lvl = debug ) except Exception as e : self . log ( "No profile due to error: " , e , type ( e ) , lvl = erro...
Retrieves a user s profile
5,105
def _parse ( self , bus , data ) : sen_time = time . time ( ) try : if isinstance ( data , bytes ) : data = data . decode ( 'ascii' ) dirtysentences = data . split ( "\n" ) sentences = [ ( sen_time , x ) for x in dirtysentences if x ] def unique ( it ) : s = set ( ) for el in it : if el not in s : s . add ( el ) yield ...
Called when a sensor sends a new raw data to this serial connector .
5,106
def main ( ) : 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' , 'apex' , 'qd' , 'mlt' ] , help = 'Convert from {geo, apex, qd, mlt}' ) parser . a...
Entry point for the script
5,107
def run_process ( cwd , args ) : try : process = check_output ( args , cwd = cwd , stderr = STDOUT ) return process except CalledProcessError as e : log ( 'Uh oh, the teapot broke again! Error:' , e , type ( e ) , lvl = verbose , pretty = True ) log ( e . cmd , e . returncode , e . output , lvl = verbose ) return e . o...
Executes an external process via subprocess . Popen
5,108
def _ask_password ( ) : password = "Foo" password_trial = "" while password != password_trial : password = getpass . getpass ( ) password_trial = getpass . getpass ( prompt = "Repeat:" ) if password != password_trial : print ( "\nPasswords do not match!" ) return password
Securely and interactively ask for a password
5,109
def _get_credentials ( username = None , password = None , dbhost = None ) : system_config = dbhost . objectmodels [ 'systemconfig' ] . find_one ( { 'active' : True } ) try : salt = system_config . salt . encode ( 'ascii' ) except ( KeyError , AttributeError ) : log ( 'No systemconfig or it is without a salt! ' 'Reinst...
Obtain user credentials by arguments or asking the user
5,110
def _ask ( question , default = None , data_type = 'str' , show_hint = False ) : data = default if data_type == 'bool' : data = None default_string = "Y" if default else "N" while data not in ( 'Y' , 'J' , 'N' , '1' , '0' ) : data = input ( "%s? [%s]: " % ( question , default_string ) ) . upper ( ) if data == '' : retu...
Interactively ask the user for data
5,111
def getsinIm ( alat ) : alat = np . float64 ( alat ) return 2 * np . sin ( np . radians ( alat ) ) / np . sqrt ( 4 - 3 * np . cos ( np . radians ( alat ) ) ** 2 )
Computes sinIm from modified apex latitude .
5,112
def getcosIm ( alat ) : alat = np . float64 ( alat ) return np . cos ( np . radians ( alat ) ) / np . sqrt ( 4 - 3 * np . cos ( np . radians ( alat ) ) ** 2 )
Computes cosIm from modified apex latitude .
5,113
def gc2gdlat ( gclat ) : WGS84_e2 = 0.006694379990141317 return np . rad2deg ( - np . arctan ( np . tan ( np . deg2rad ( gclat ) ) / ( WGS84_e2 - 1 ) ) )
Converts geocentric latitude to geodetic latitude using WGS84 .
5,114
def subsol ( datetime ) : year = datetime . year doy = datetime . timetuple ( ) . tm_yday ut = datetime . hour * 3600 + datetime . minute * 60 + datetime . second if not 1601 <= year <= 2100 : raise ValueError ( 'Year must be in [1601, 2100]' ) yr = year - 2000 nleap = int ( np . floor ( ( year - 1601.0 ) / 4.0 ) ) nle...
Finds subsolar geocentric latitude and longitude .
5,115
def make_auth_headers ( ) : if not os . path . exists ( ".appveyor.token" ) : raise RuntimeError ( "Please create a file named `.appveyor.token` in the current directory. " "You can get the token from https://ci.appveyor.com/api-token" ) with open ( ".appveyor.token" ) as f : token = f . read ( ) . strip ( ) headers = ...
Make the authentication headers needed to use the Appveyor API .
5,116
def get_project_build ( account_project ) : url = make_url ( "/projects/{account_project}" , account_project = account_project ) response = requests . get ( url , headers = make_auth_headers ( ) ) return response . json ( )
Get the details of the latest Appveyor build .
5,117
def download_url ( url , filename , headers ) : ensure_dirs ( filename ) response = requests . get ( url , headers = headers , stream = True ) if response . status_code == 200 : with open ( filename , 'wb' ) as f : for chunk in response . iter_content ( 16 * 1024 ) : f . write ( chunk )
Download a file from url to filename .
5,118
def cli_schemata_list ( self , * args ) : self . log ( 'Registered schemata languages:' , "," . join ( sorted ( l10n_schemastore . keys ( ) ) ) ) self . log ( 'Registered Schemata:' , "," . join ( sorted ( schemastore . keys ( ) ) ) ) if '-c' in args or '-config' in args : self . log ( 'Registered Configuration Schemat...
Display a list of registered schemata
5,119
def cli_form ( self , * args ) : if args [ 0 ] == '*' : for schema in schemastore : self . log ( schema , ':' , schemastore [ schema ] [ 'form' ] , pretty = True ) else : self . log ( schemastore [ args [ 0 ] ] [ 'form' ] , pretty = True )
Display a schemata s form definition
5,120
def cli_schema ( self , * args ) : key = None if len ( args ) > 1 : key = args [ 1 ] args = list ( args ) if '-config' in args or '-c' in args : store = configschemastore try : args . remove ( '-c' ) args . remove ( '-config' ) except ValueError : pass else : store = schemastore def output ( schema ) : self . log ( "%s...
Display a single schema definition
5,121
def cli_forms ( self , * args ) : forms = [ ] missing = [ ] for key , item in schemastore . items ( ) : if 'form' in item and len ( item [ 'form' ] ) > 0 : forms . append ( key ) else : missing . append ( key ) self . log ( 'Schemata with form:' , forms ) self . log ( 'Missing forms:' , missing )
List all available form definitions
5,122
def cli_default_perms ( self , * args ) : for key , item in schemastore . items ( ) : if item [ 'schema' ] . get ( 'no_perms' , False ) : self . log ( 'Schema without permissions:' , key ) continue try : perms = item [ 'schema' ] [ 'properties' ] [ 'perms' ] [ 'properties' ] if perms == { } : self . log ( 'Schema:' , i...
Show default permissions for all schemata
5,123
def all ( self , event ) : self . log ( "Schemarequest for all schemata from" , event . user , lvl = debug ) response = { 'component' : 'hfos.events.schemamanager' , 'action' : 'all' , 'data' : l10n_schemastore [ event . client . language ] } self . fireEvent ( send ( event . client . uuid , response ) )
Return all known schemata to the requesting client
5,124
def get ( self , event ) : self . log ( "Schemarequest for" , event . data , "from" , event . user , lvl = debug ) if event . data in schemastore : response = { 'component' : 'hfos.events.schemamanager' , 'action' : 'get' , 'data' : l10n_schemastore [ event . client . language ] [ event . data ] } self . fireEvent ( se...
Return a single schema
5,125
def configuration ( self , event ) : try : self . log ( "Schemarequest for all configuration schemata from" , event . user . account . name , lvl = debug ) response = { 'component' : 'hfos.events.schemamanager' , 'action' : 'configuration' , 'data' : configschemastore } self . fireEvent ( send ( event . client . uuid ,...
Return all configurable components schemata
5,126
def uuid_object ( title = "Reference" , description = "Select an object" , default = None , display = True ) : uuid = { 'pattern' : '^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{' '4}-[' 'a-fA-F0-9]{4}-[a-fA-F0-9]{12}$' , 'type' : 'string' , 'title' : title , 'description' : description , } if not display : uuid [ 'x-sch...
Generates a regular expression controlled UUID field
5,127
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_create = None , all_roles = None ) : base_schema = { 'id' : '#' + name , 'type' : 'object' , 'name' : name , 'properties' : { } } if not no_perms : if a...
Generates a basic object with RBAC properties
5,128
def sensordata ( self , event ) : if len ( self . datatypes ) == 0 : return data = event . data timestamp = event . timestamp self . log ( "New incoming navdata:" , data , lvl = verbose ) for name , value in data . items ( ) : if name in self . datatypes : ref = self . datatypes [ name ] self . sensed [ name ] = ref if...
Generates a new reference frame from incoming sensordata
5,129
def db_export ( schema , uuid , object_filter , export_format , filename , pretty , all_schemata , omit ) : internal_backup ( schema , uuid , object_filter , export_format , filename , pretty , all_schemata , omit )
Export stored objects
5,130
def db_import ( ctx , schema , uuid , object_filter , import_format , filename , all_schemata , dry ) : import_format = import_format . upper ( ) with open ( filename , 'r' ) as f : json_data = f . read ( ) data = json . loads ( json_data ) if schema is None : if all_schemata is False : log ( 'No schema given. Read the...
Import objects from file
5,131
def _page_update ( self , event ) : try : if event . schema == 'wikipage' : self . _update_index ( ) except Exception as e : self . log ( "Page creation notification error: " , event , e , type ( e ) , lvl = error )
Checks if the newly created object is a wikipage .. If so rerenders the automatic index .
5,132
def construct_graph ( args ) : app = Core ( args ) setup_root ( app ) if args [ 'debug' ] : from circuits import Debugger hfoslog ( "Starting circuits debugger" , lvl = warn , emitter = 'GRAPH' ) dbg = Debugger ( ) . register ( app ) dbg . IgnoreEvents . extend ( [ "read" , "_read" , "write" , "_write" , "stream_succes...
Preliminary HFOS application Launcher
5,133
def launch ( run = True , ** args ) : verbosity [ 'console' ] = args [ 'log' ] if not args [ 'quiet' ] else 100 verbosity [ 'global' ] = min ( args [ 'log' ] , args [ 'logfileverbosity' ] ) verbosity [ 'file' ] = args [ 'logfileverbosity' ] if args [ 'dolog' ] else 100 set_logfile ( args [ 'logfilepath' ] , args [ 'ins...
Bootstrap basics assemble graph and hand over control to the Core component
5,134
def ready ( self , source ) : from hfos . database import configschemastore configschemastore [ self . name ] = self . configschema self . _start_server ( ) if not self . insecure : self . _drop_privileges ( ) self . fireEvent ( cli_register_event ( 'components' , cli_components ) ) self . fireEvent ( cli_register_even...
All components have initialized set up the component configuration schema - store run the local server and drop privileges
5,135
def trigger_frontend_build ( self , event ) : from hfos . database import instance install_frontend ( instance = instance , forcerebuild = event . force , install = event . install , development = self . development )
Event hook to trigger a new frontend build
5,136
def cli_reload ( self , event ) : self . log ( 'Reloading all components.' ) self . update_components ( forcereload = True ) initialize ( ) from hfos . debugger import cli_compgraph self . fireEvent ( cli_compgraph ( ) )
Experimental call to reload the component tree
5,137
def cli_info ( self , event ) : self . log ( 'Instance:' , self . instance , 'Dev:' , self . development , 'Host:' , self . host , 'Port:' , self . port , 'Insecure:' , self . insecure , 'Frontend:' , self . frontendtarget )
Provides information about the running instance
5,138
def _start_server ( self , * args ) : 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 ( "Running insecure server without SSL. Do not use without SSL proxy in production!" , lvl = warn ) try ...
Run the node local server
5,139
def update_components ( self , forcereload = False , forcerebuild = False , forcecopy = True , install = False ) : self . log ( "Updating components" ) components = { } if True : from pkg_resources import iter_entry_points entry_point_tuple = ( iter_entry_points ( group = 'hfos.base' , name = None ) , iter_entry_points...
Check all known entry points for components . If necessary manage configuration updates
5,140
def _start_frontend ( self , restart = False ) : self . log ( self . config , self . config . frontendenabled , lvl = verbose ) if self . config . frontendenabled and not self . frontendrunning or restart : self . log ( "Restarting webfrontend services on" , self . frontendtarget ) self . static = Static ( "/" , docroo...
Check if it is enabled and start the frontend http & websocket
5,141
def _instantiate_components ( self , clear = True ) : if clear : import objgraph from copy import deepcopy from circuits . tools import kill from circuits import Component for comp in self . runningcomponents . values ( ) : self . log ( comp , type ( comp ) , isinstance ( comp , Component ) , pretty = True ) kill ( com...
Inspect all loadable components and run them
5,142
def _create_user ( ctx ) : username , passhash = _get_credentials ( ctx . obj [ 'username' ] , ctx . obj [ 'password' ] , ctx . obj [ 'db' ] ) if ctx . obj [ 'db' ] . objectmodels [ 'user' ] . count ( { 'name' : username } ) > 0 : raise KeyError ( ) new_user = ctx . obj [ 'db' ] . objectmodels [ 'user' ] ( { 'uuid' : s...
Internal method to create a normal user
5,143
def create_user ( ctx ) : try : new_user = _create_user ( ctx ) new_user . save ( ) log ( "Done" ) except KeyError : log ( 'User already exists' , lvl = warn )
Creates a new local user
5,144
def create_admin ( ctx ) : try : admin = _create_user ( ctx ) admin . roles . append ( 'admin' ) admin . save ( ) log ( "Done" ) except KeyError : log ( 'User already exists' , lvl = warn )
Creates a new local user and assigns admin role
5,145
def delete_user ( ctx , yes ) : 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 ( 'Confirm deletion' , default = False , data_type = '...
Delete a local user
5,146
def change_password ( ctx ) : username , passhash = _get_credentials ( ctx . obj [ 'username' ] , ctx . obj [ 'password' ] , ctx . obj [ 'db' ] ) change_user = ctx . obj [ 'db' ] . objectmodels [ 'user' ] . find_one ( { 'name' : username } ) if change_user is None : log ( 'No such user' , lvl = warn ) return change_use...
Change password of an existing user
5,147
def list_users ( ctx , search , uuid , active ) : users = ctx . obj [ 'db' ] . objectmodels [ 'user' ] for found_user in users . find ( ) : if not search or ( search and search in found_user . name ) : print ( found_user . name , end = ' ' if active or uuid else '\n' ) if uuid : print ( found_user . uuid , end = ' ' if...
List all locally known users
5,148
def disable ( ctx ) : 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_user . active = False change_user . save ( ) log ( 'Done' )
Disable an existing user
5,149
def enable ( ctx ) : 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_user . active = True change_user . save ( ) log ( 'Done' )
Enable an existing user
5,150
def add_role ( ctx , role ) : 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' ] . objectmodels [ 'user' ] . find_one ( { 'name' : ctx . obj [ 'username' ] } ) if role not in change_...
Grant a role to an existing user
5,151
def _get_future_tasks ( self ) : 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 ( self . alerts ) , 'future tasks' )
Assemble a list of future alerts
5,152
def cmdmap ( xdot ) : from copy import copy def print_commands ( command , map_output , groups = None , depth = 0 ) : if groups is None : groups = [ ] if 'commands' in command . __dict__ : if len ( groups ) > 0 : if xdot : line = " %s -> %s [weight=1.0];\n" % ( groups [ - 1 ] , command . name ) else : line = " " ...
Generates a command map
5,153
def format_template ( template , content ) : import pystache result = u"" if True : result = pystache . render ( template , content , string_encoding = 'utf-8' ) return result
Render a given pystache template with given content
5,154
def format_template_file ( filename , content ) : with open ( filename , 'r' ) as f : template = f . read ( ) if type ( template ) != str : template = template . decode ( 'utf-8' ) return format_template ( template , content )
Render a given pystache template file with given content
5,155
def write_template_file ( source , target , content ) : print ( target ) data = format_template_file ( source , content ) with open ( target , 'w' ) as f : for line in data : if type ( line ) != str : line = line . encode ( 'utf-8' ) f . write ( line )
Write a new file from a given pystache template file and content
5,156
def insert_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 . readlines ( ) ) pprint ( old_config ) if definition in old_config : print ( "Service definition already inserted" ) ...
Insert a new nginx service definition
5,157
def add_action_role ( ctx ) : 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 for this to work.' , lvl = warn ) return for item in objects : if role not in item . perm...
Adds a role to an action on objects
5,158
def del_action_role ( ctx ) : 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 for this to work.' , lvl = warn ) return for item in objects : if role in item . perms [ ...
Deletes a role from an action on objects
5,159
def change_owner ( ctx , owner , uuid ) : objects = ctx . obj [ 'objects' ] database = ctx . obj [ 'db' ] if uuid is True : owner_filter = { 'uuid' : owner } else : owner_filter = { 'name' : owner } owner = database . objectmodels [ 'user' ] . find_one ( owner_filter ) if owner is None : log ( 'User unknown.' , lvl = e...
Changes the ownership of objects
5,160
def notify ( self , event ) : self . log ( 'Got a notification event!' ) self . log ( event , pretty = True ) self . log ( event . __dict__ )
Notify a user
5,161
def getlist ( self , event ) : try : componentlist = model_factory ( Schema ) . find ( { } ) data = [ ] for comp in componentlist : try : data . append ( { 'name' : comp . name , 'uuid' : comp . uuid , 'class' : comp . componentclass , 'active' : comp . active } ) except AttributeError : self . log ( 'Bad component wit...
Processes configuration list requests
5,162
def put ( self , event ) : self . log ( "Configuration put request " , event . user ) try : component = model_factory ( Schema ) . find_one ( { 'uuid' : event . data [ 'uuid' ] } ) component . update ( event . data ) component . save ( ) response = { 'component' : 'hfos.ui.configurator' , 'action' : 'put' , 'data' : Tr...
Store a given configuration
5,163
def get ( self , event ) : try : comp = event . data [ 'uuid' ] except KeyError : comp = None if not comp : self . log ( 'Invalid get request without schema or component' , lvl = error ) return self . log ( "Config data get request for " , event . data , "from" , event . user ) component = model_factory ( Schema ) . f...
Get a stored configuration
5,164
def rec ( self ) : try : self . _snapshot ( ) except Exception as e : self . log ( "Timer error: " , e , type ( e ) , lvl = error )
Records a single snapshot
5,165
def _toggle_filming ( self ) : if self . _filming : self . log ( "Stopping operation" ) self . _filming = False self . timer . stop ( ) else : self . log ( "Starting operation" ) self . _filming = True self . timer . start ( )
Toggles the camera system recording state
5,166
def client_disconnect ( self , event ) : self . log ( "Removing disconnected client from subscriptions" , lvl = debug ) client_uuid = event . clientuuid self . _unsubscribe ( client_uuid )
A client has disconnected update possible subscriptions accordingly .
5,167
def get ( self , event ) : try : data , schema , user , client = self . _get_args ( event ) except AttributeError : return object_filter = self . _get_filter ( event ) if 'subscribe' in data : do_subscribe = data [ 'subscribe' ] is True else : do_subscribe = False try : uuid = str ( data [ 'uuid' ] ) except ( KeyError ...
Get a specified object
5,168
def objectlist ( self , event ) : 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 ( event ) self . log ( 'Object list for' , schema , 'requested from' , user . account . name , l...
Get a list of objects
5,169
def change ( self , event ) : try : data , schema , user , client = self . _get_args ( event ) except AttributeError : return try : uuid = data [ 'uuid' ] change = data [ 'change' ] field = change [ 'field' ] new_data = change [ 'value' ] except KeyError as e : self . log ( "Update request with missing arguments!" , da...
Change an existing object
5,170
def put ( self , event ) : try : data , schema , user , client = self . _get_args ( event ) except AttributeError : return try : clientobject = data [ 'obj' ] uuid = clientobject [ 'uuid' ] except KeyError as e : self . log ( "Put request with missing arguments!" , e , data , lvl = critical ) return try : model = objec...
Put an object
5,171
def delete ( self , event ) : try : data , schema , user , client = self . _get_args ( event ) except AttributeError : return try : uuids = data [ 'uuid' ] if not isinstance ( uuids , list ) : uuids = [ uuids ] if schema not in objectmodels . keys ( ) : self . log ( "Unknown schema encountered: " , schema , lvl = warn ...
Delete an existing object
5,172
def subscribe ( self , event ) : uuids = event . data if not isinstance ( uuids , list ) : uuids = [ uuids ] subscribed = [ ] for uuid in uuids : try : self . _add_subscription ( uuid , event ) subscribed . append ( uuid ) except KeyError : continue result = { 'component' : 'hfos.events.objectmanager' , 'action' : 'sub...
Subscribe to an object s future changes
5,173
def unsubscribe ( self , event ) : uuids = event . data if not isinstance ( uuids , list ) : uuids = [ uuids ] result = [ ] for uuid in uuids : if uuid in self . subscriptions : self . subscriptions [ uuid ] . pop ( event . client . uuid ) if len ( self . subscriptions [ uuid ] ) == 0 : del ( self . subscriptions [ uui...
Unsubscribe from an object s future changes
5,174
def all_languages ( ) : 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 ) : if base != 'all' : rv . append ( lang ) rv . sort ( ) rv . append ( 'en' ) l10n_log ( 'Registered ...
Compile a list of all available language translations
5,175
def language_token_to_name ( languages ) : result = { } with open ( os . path . join ( localedir , 'languages.json' ) , 'r' ) as f : language_lookup = json . load ( f ) for language in languages : language = language . lower ( ) try : result [ language ] = language_lookup [ language ] except KeyError : l10n_log ( 'Lang...
Get a descriptive title for all languages
5,176
def print_messages ( domain , msg ) : domain = Domain ( domain ) for lang in all_languages ( ) : print ( lang , ':' , domain . get ( lang , msg ) )
Debugging function to print all message language variants
5,177
def i18n ( msg , event = None , lang = 'en' , domain = 'backend' ) : if event is not None : language = event . client . language else : language = lang domain = Domain ( domain ) return domain . get ( language , msg )
Gettext function wrapper to return a message in a specified language by domain
5,178
def std_human_uid ( kind = None ) : kind_list = alphabet if kind == 'animal' : kind_list = animals elif kind == 'place' : kind_list = places name = "{color} {adjective} {kind} of {attribute}" . format ( color = choice ( colors ) , adjective = choice ( adjectives ) , kind = choice ( kind_list ) , attribute = choice ( at...
Return a random generated human - friendly phrase as low - probability unique id
5,179
def std_table ( 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 ] ] , key = lambda x : len ( str ( x ) ) ) ) ) formats = [ ] hformats = [ ] for i in range ( len ( rows [ 0 ]...
Return a formatted table of given rows
5,180
def _get_translation ( self , lang ) : try : return self . _translations [ lang ] except KeyError : rv = self . _translations [ lang ] = gettext . translation ( self . _domain , localedir = localedir , languages = [ lang ] , fallback = True ) return rv
Add a new translation language to the live gettext translator
5,181
def handler ( * names , ** kwargs ) : def wrapper ( f ) : if names and isinstance ( names [ 0 ] , bool ) and not names [ 0 ] : f . handler = False return f if len ( names ) > 0 and inspect . isclass ( names [ 0 ] ) and issubclass ( names [ 0 ] , hfosEvent ) : f . names = ( str ( names [ 0 ] . realname ( ) ) , ) else : ...
Creates an Event Handler
5,182
def log ( self , * args , ** kwargs ) : func = inspect . currentframe ( ) . f_back . f_code if 'exc' in kwargs and kwargs [ 'exc' ] is True : exc_type , exc_obj , exc_tb = exc_info ( ) line_no = exc_tb . tb_lineno args += traceback . extract_tb ( exc_tb ) , else : line_no = func . co_firstlineno sourceloc = "[%.10s@%s:...
Log a statement from this component
5,183
def register ( self , * args ) : super ( ConfigurableMeta , self ) . register ( * args ) from hfos . database import configschemastore configschemastore [ self . name ] = self . configschema
Register a configurable component in the configuration schema store
5,184
def unregister ( self ) : self . names . remove ( self . uniquename ) super ( ConfigurableMeta , self ) . unregister ( )
Removes the unique name from the systems unique name list
5,185
def _read_config ( self ) : try : self . config = self . componentmodel . find_one ( { 'name' : self . uniquename } ) except ServerSelectionTimeoutError : self . log ( "No database access! Check if mongodb is running " "correctly." , lvl = critical ) if self . config : self . log ( "Configuration read." , lvl = verbose...
Read this component s configuration from the database
5,186
def _write_config ( self ) : if not self . config : self . log ( "Unable to write non existing configuration" , lvl = error ) return self . config . save ( ) self . log ( "Configuration stored." )
Write this component s configuration back to the database
5,187
def _set_config ( self , config = None ) : if not config : config = { } try : self . config = self . componentmodel ( config ) try : name = self . config . name self . log ( "Name set to: " , name , lvl = verbose ) except ( AttributeError , KeyError ) : self . log ( "Has no name." , lvl = verbose ) try : self . config ...
Set this component s initial configuration
5,188
def reload_configuration ( self , event ) : if event . target == self . uniquename : self . log ( 'Reloading configuration' ) self . _read_config ( )
Event triggered configuration reload
5,189
def _augment_info ( info ) : info [ 'description_header' ] = "=" * len ( info [ 'description' ] ) info [ 'component_name' ] = info [ 'plugin_name' ] . capitalize ( ) info [ 'year' ] = time . localtime ( ) . tm_year info [ 'license_longtext' ] = '' info [ 'keyword_list' ] = u"" for keyword in info [ 'keywords' ] . split...
Fill out the template information
5,190
def _construct_module ( info , target ) : for path in paths : real_path = os . path . abspath ( os . path . join ( target , path . format ( ** info ) ) ) log ( "Making directory '%s'" % real_path ) os . makedirs ( real_path ) for item in templates . values ( ) : source = os . path . join ( 'dev/templates' , item [ 0 ] ...
Build a module from templates and user supplied information
5,191
def _ask_questionnaire ( ) : answers = { } print ( info_header ) pprint ( questions . items ( ) ) for question , default in questions . items ( ) : response = _ask ( question , default , str ( type ( default ) ) , show_hint = True ) if type ( default ) == unicode and type ( response ) != str : response = response . dec...
Asks questions to fill out a HFOS plugin template
5,192
def create_module ( clear_target , target ) : if os . path . exists ( target ) : if clear_target : shutil . rmtree ( target ) else : log ( "Target exists! Use --clear to delete it first." , emitter = 'MANAGE' ) sys . exit ( 2 ) done = False info = None while not done : info = _ask_questionnaire ( ) pprint ( info ) done...
Creates a new template HFOS plugin module
5,193
def lookup_field ( key , lookup_type = None , placeholder = None , html_class = "div" , select_type = "strapselect" , mapping = "uuid" ) : if lookup_type is None : lookup_type = key if placeholder is None : placeholder = "Select a " + lookup_type result = { 'key' : key , 'htmlClass' : html_class , 'type' : select_type ...
Generates a lookup field for form definitions
5,194
def fieldset ( title , items , options = None ) : result = { 'title' : title , 'type' : 'fieldset' , 'items' : items } if options is not None : result . update ( options ) return result
A field set with a title and sub items
5,195
def section ( rows , columns , items , label = None ) : sections = [ ] column_class = "section-column col-sm-%i" % ( 12 / columns ) for vertical in range ( columns ) : column_items = [ ] for horizontal in range ( rows ) : try : item = items [ horizontal ] [ vertical ] column_items . append ( item ) except IndexError : ...
A section consisting of rows and columns
5,196
def emptyArray ( key , add_label = None ) : result = { 'key' : key , 'startEmpty' : True } if add_label is not None : result [ 'add' ] = add_label result [ 'style' ] = { 'add' : 'btn-success' } return result
An array that starts empty
5,197
def tabset ( titles , contents ) : tabs = [ ] for no , title in enumerate ( titles ) : tab = { 'title' : title , } content = contents [ no ] if isinstance ( content , list ) : tab [ 'items' ] = content else : tab [ 'items' ] = [ content ] tabs . append ( tab ) result = { 'type' : 'tabs' , 'tabs' : tabs } return result
A tabbed container widget
5,198
def timed_connectivity_check ( self , event ) : self . status = self . _can_connect ( ) self . log ( 'Timed connectivity check:' , self . status , lvl = verbose ) if self . status : if not self . old_status : self . log ( 'Connectivity gained' ) self . fireEvent ( backend_nodestate_toggle ( STATE_UUID_CONNECTIVITY , on...
Tests internet connectivity in regular intervals and updates the nodestate accordingly
5,199
def activityrequest ( self , event ) : try : action = event . action data = event . data self . log ( "Activityrequest: " , action , data ) except Exception as e : self . log ( "Error: '%s' %s" % ( e , type ( e ) ) , lvl = error )
ActivityMonitor event handler for incoming events