code
stringlengths
1
18.2k
parser.add_argument('--height', dest='height', default=0, metavar='HEIGHT', type=float, help='height for conversion') parser.add_argument('--refh', dest='refh', metavar='REFH', type=float, default=0, help='reference height for modified apex coordinates') parser.add_argument('-i', '--input', dest='file_in', metavar='FIL...
required for MLT calculations' raise ValueError(desc) if 9 <= len(args.date) <= 13: desc = 'full date/time must be given as YYYYMMDDHHMMSS, not ' + \ 'YYYYMMDDHHMMSS'[:len(args.date)] raise ValueError(desc) datetime = dt.datetime.strptime(args.date, '%Y%m%d%H%M%S'[:len(args.date)-2]) A = apexpy.Apex(date=datetime, refh...
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:', e, type(e), lvl=verbose, pretty=True) log(e.cmd, e.returncode, e.output, lvl=verbose) ...
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 password != password_trial: print("\nPasswords do not match!") return password
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: salt = system_config.salt.encode('ascii') except (KeyError, AttributeError): log('No system...
password is None: password = _ask_password() else: password = password try: password = password.encode('utf-8') except UnicodeDecodeError: password = password passhash = hashlib.sha512(password) passhash.update(salt) return username, passhash.hexdigest()
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'): data = input("%s? [%s]: " % (question, default_string)).upper() if data =...
msg = "%s? [%s] (%s): " % (question, default, data_type) else: msg = question data = input(msg) if len(data) == 0: data = default elif data_type == 'int': if show_hint: msg = "%s? [%s] (%s): " % (question, default, data_type) else: msg = question data = input(msg) if len(data) == 0: data = int(default) else: data = int...
def checklat(lat, name='lat'): """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 values just outside the ra...
far outside the range [-90, 90] """ if np.all(np.float64(lat) >= -90) and np.all(np.float64(lat) <= 90): return lat if np.isscalar(lat): if lat > 90 and np.isclose(lat, 90, rtol=0, atol=1e-4): lat = 90 return lat elif lat < -90 and np.isclose(lat, -90, rtol=0, atol=1e-4): lat = -90 return lat else: lat = np.float64(lat...
(np.isclose(lat, 90, rtol=0, atol=1e-4))] = 90 lat[(lat < -90) & (np.isclose(lat, -90, rtol=0, atol=1e-4))] = -90 if np.all(lat >= -90) and np.all(lat <= 90): return lat # we haven't returned yet, so raise exception raise ValueError(name + ' must be in [-90, 90]')
def getsinIm(alat): """Computes sinIm from modified apex latitude. Parameters ========== alat : array_like Modified apex latitude Returns ======= sinIm : ndarray or float """ alat = np.float64(alat) return 2*np.sin(np.radians(alat))/np.sqrt(4 - 3*np.cos(np.radians(alat))**2)
def getcosIm(alat): """Computes cosIm from modified apex latitude. Parameters ========== alat : array_like Modified apex latitude Returns ======= cosIm : ndarray or float """ alat = np.float64(alat) return np.cos(np.radians(alat))/np.sqrt(4 - 3*np.cos(np.radians(alat))**2)
def toYearFraction(date): """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/6451892/2978652 """ d...
= yearElapsed/yearDuration return date.year + fraction
def gc2gdlat(gclat): """Converts geocentric latitude to geodetic latitude using WGS84. Parameters ========== gclat : array_like Geocentric latitude Returns ======= gdlat : ndarray or float Geodetic latitude """ WGS84_e2 = 0.006694379990141317 # WGS84 first eccentricity squared return np.rad2deg(-np.arctan(np.tan(np.deg...
def subsol(datetime): """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 Almanac for the year 1996, p. C24. (...
degree latitude and 0.025 degrees longitude between years 1950 and 2050. Accuracy for other years has not been tested. Every day is assumed to have exactly 86400 seconds; thus leap seconds that sometimes occur on December 31 are ignored (their effect is below the accuracy threshold of the algorithm). After Fortran code...
# convert to year, day of year and seconds since midnight 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))...
- 1601.0) / 100.0)) ncent = 3 - ncent nleap = nleap + ncent l0 = -79.549 + (-0.238699 * (yr - 4.0 * nleap) + 3.08514e-2 * nleap) g0 = -2.472 + (-0.2558905 * (yr - 4.0 * nleap) - 3.79617e-2 * nleap) # Days (including fraction) since 12 UT on January 1 of IYR: df = (ut / 86400.0 - 1.5) +
doy # Mean longitude of Sun: lmean = l0 + 0.9856474 * df # Mean anomaly in radians: grad = np.radians(g0 + 0.9856003 * df) # Ecliptic longitude: lmrad = np.radians(lmean + 1.915 * np.sin(grad) + 0.020 * np.sin(2.0 * grad)) sinlm = np.sin(lmrad) # Obliquity of ecliptic in radians: epsrad = np.radians(23.439 - 4e-7 * (df...
Right ascension: alpha = np.degrees(np.arctan2(np.cos(epsrad) * sinlm, np.cos(lmrad))) # Declination, which is also the subsolar latitude: sslat = np.degrees(np.arcsin(np.sin(epsrad) * sinlm)) # Equation of time (degrees): etdeg = lmean - alpha nrot = round(etdeg / 360.0) etdeg = etdeg - 360.0 * nrot # Subsolar longitu...
= round(sslon / 360.0) sslon = sslon - 360.0 * nrot return sslat, sslon
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. " "You can get the token from https://ci.appveyor.com/api-token" ) with open(".appveyor.tok...
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()
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 chunk in response.iter_content(16 * 1024): f.write(chunk)
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 args or '-config' in args: self.log('Registered Configuration Schemata:'...
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]]['form'], pretty=True)
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: args.remove('-c') args.remove('-config') except ValueError: pass else: store = schemastore def output(schema): self.log(...
schema, 'has no role for creation', lvl=warn) try: self.log(store[schema]['schema']['properties']['perms']['properties'], pretty=True) except KeyError: self.log('Schema', schema, 'has no permissions', lvl=warn) else: self.log(store[schema]['schema'], pretty=True) if '*' in args: for schema in store: output(schema) else...
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: missing.append(key) self.log('Schemata with form:', forms) self.log('Missing forms:', missing)
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 permissions:', key) continue try: perms = item['schema']['properties']['perms']['properties'] if perm...
def ready(self): """Sets up the application after startup.""" self.log('Got', len(schemastore), 'data and', len(configschemastore), 'component schemata.', lvl=debug)
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', 'action': 'all', 'data': l10n_schemastore[event.client.language] } self.fireEvent(send(event.client.uuid, response)...
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', 'action': 'get', 'data': l10n_schemastore[event.client.language][event.data] } self.fireEvent(send(event.client...
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 = { 'component': 'hfos.events.schemamanager', 'action': 'configuration', 'data': configschemastore } self.fireEvent(send(even...
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}-[' 'a-fA-F0-9]{4}-[a-fA-F0-9]{12}$', 'type': 'string', 'title': title, 'description': descripti...
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): """Generates a basic object with RBAC properties""" base_schema = { 'id': '#' + name, 'type': 'object', 'name': name, 'properties': {} } if not no...
None: roles_read = ['admin'] if roles_list is None: roles_list = ['admin'] if roles_create is None: roles_create = ['admin'] if isinstance(roles_create, str): roles_create = [roles_create] if isinstance(roles_write, str): roles_write = [roles_write] if isinstance(roles_read, str): roles_read = [roles_read] if isinstanc...
'array', 'default': roles_write, 'items': { 'type': 'string', } }, 'read': { 'type': 'array', 'default': roles_read, 'items': { 'type': 'string', } }, 'list': { 'type': 'array', 'default': roles_list, 'items': { 'type': 'string', } } }, 'default': {}, 'x-schema-form': { 'condition': "false" } }, 'name': { 'type': 'stri...
owners as # well as special accounts like admin or even system perhaps # base_schema['required'] = base_schema.get('required', []) # base_schema['required'].append('owner') base_schema['properties'].update({ 'owner': uuid_object(title='Unique Owner ID', display=hide_owner) }) else: base_schema['no_perms'] = True # TODO...
def serial_ports(): """ 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 ) """ if sys.platform.startswith('win'): port...
else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException) as e: hfoslog('Could not open serial port:', port, e, type(e), exc=True, lvl=warn) return result
def sensordata(self, event): """ Generates a new reference frame from incoming sensordata :param event: new sensordata to be merged into referenceframe """ if len(self.datatypes) == 0: return data = event.data timestamp = event.timestamp # bus = event.bus # TODO: What about multiple busses? That is prepared, but how ex...
if name in self.datatypes: ref = self.datatypes[name] self.sensed[name] = ref if ref.lastvalue != str(value): # self.log("Reference outdated:", ref._fields) item = { 'value': value, 'timestamp': timestamp, 'type': name } self.referenceframe[name] = value self.referenceages[name] = timestamp # self.log("Subscriptions:",...
uuid, lvl=events) self.fireEvent(send(uuid, packet), 'hfosweb') # self.log("New item: ", item) sensordata = objectmodels['sensordata'](item) # self.log("Value entry:", sensordata._fields) if ref.record: self.log("Recording updated reference:", sensordata._fields) sensordata.save() ref.lastvalue = str(value) ref.timesta...
def navdatapush(self): """ Pushes the current :referenceframe: out to clients. :return: """ try: self.fireEvent(referenceframe({ 'data': self.referenceframe, 'ages': self.referenceages }), "navdata") self.intervalcount += 1 if self.intervalcount == self.passiveinterval and len( self.referenceframe) > 0: self.fireEvent(...
referenceframe: ", e, type(e), lvl=critical)
def db_export(schema, uuid, object_filter, export_format, filename, pretty, all_schemata, omit): """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!""" internal_backup(schema, uuid, object_filter,...
def db_import(ctx, schema, uuid, object_filter, import_format, filename, all_schemata, dry): """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!""" import_format = import_format.upper() with op...
schema given. Read the help', lvl=warn) return else: schemata = data.keys() else: schemata = [schema] from hfos import database database.initialize(ctx.obj['dbhost'], ctx.obj['dbname']) all_items = {} total = 0 for schema_item in schemata: model = database.objectmodels[schema_item] objects = data[schema_item] if uuid: ...
len(items) total += schema_total if dry: log('Would import', schema_total, 'items of', schema_item) all_items[schema_item] = items if dry: log('Would import', total, 'objects.') else: log('Importing', total, 'objects.') for schema_name, item_list in all_items.items(): log('Importing', len(item_list), 'objects of type',...
def _page_update(self, event): """ Checks if the newly created object is a wikipage.. If so, rerenders the automatic index. :param event: objectchange or objectcreation event """ try: if event.schema == 'wikipage': self._update_index() except Exception as e: self.log("Page creation notification error: ", event, e, type...
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 try: # Get the uid/gid from the name running_uid = pwd.getpwnam(uid_name).pw_uid running_gid = gr...
emitter='CORE') except Exception as e: hfoslog('Could not drop privileges:', e, type(e), exc=True, lvl=error, emitter='CORE')
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().register(app) # TODO: Make these configurable from modules, navdata is _very_ noisy # ...
"task_success", "task_done", # Thread completion "keepalive" # IRC Gateway ]) hfoslog("Beginning graph assembly.", emitter='GRAPH') if args['drawgraph']: from circuits.tools import graph graph(app) if args['opengui']: import webbrowser # TODO: Fix up that url: webbrowser.open("http://%s:%i/" % (args['host'], args['port...
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['logfileverbosity']) verbosity['file'] = args['logfileverbosity'] if args['dolog'] else 100 set_lo...
hfoslog("Warning! Using SSL without nginx is currently not broken!", lvl=critical, emitter='CORE') hfoslog("Initializing database access", emitter='CORE', lvl=debug) initialize(args['dbhost'], args['dbname'], args['instance']) server = construct_graph(args) if run and not args['norun']: server.run() return server
def ready(self, source): """All components have initialized, set up the component configuration schema-store, run the local server and drop privileges""" from hfos.database import configschemastore configschemastore[self.name] = self.configschema self._start_server() if not self.insecure: self._drop_privileges() self.f...
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.install, development=self.development )
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.fireEvent(cli_compgraph())
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, 'Insecure:', self.insecure, 'Frontend:', self.frontendtarget)
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("Running insecure server without SSL. Do not use without SSL proxy in production!", lvl=warn) try:...
def update_components(self, forcereload=False, forcerebuild=False, forcecopy=True, install=False): """Check all known entry points for components. If necessary, manage configuration updates""" # TODO: See if we can pull out major parts of the component handling. # They are also used in the manage tool to instantiate th...
iter_entry_points(group='hfos.base', name=None), iter_entry_points(group='hfos.sails', name=None), iter_entry_points(group='hfos.components', name=None) ) for iterator in entry_point_tuple: for entry_point in iterator: try: name = entry_point.name location = entry_point.dist.location loaded = entry_point.load() self.lo...
inspect entrypoint: ", e, type(e), entry_point, iterator, lvl=error, exc=True) # for name in components.keys(): # try: # self.log(self.loadable_components[name]) # configobject = { # 'type': 'object', # 'properties': # self.loadable_components[name].configprops # } # ComponentBaseConfigSchema['schema'][ # 'properties']...
Exception as e: # self.log("Error: ", e, type(e), lvl=error, exc=True) # return self.log("Checking component frontend bits in ", self.frontendroot, lvl=verbose) # pprint(self.config._fields) diff = set(components) ^ set(self.config.components) if diff or forcecopy and self.config.frontendenabled: self.log("Old componen...
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.frontendrunning or restart: self.log("Restarting webfrontend services on", self.frontendtarget) self....
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 Component for comp in self.runningcomponents.values(): self.log(comp, type(comp), isinstance(comp, Component), pretty...
filter=lambda x: type(x) not in [list, tuple, set], # highlight=lambda x: type(x) in [ConfigurableComponent], # filename='backref-graph_%s.png' % comp.uniquename) # del comp # del removables self.runningcomponents = {} self.log('Not running blacklisted components: ', self.component_blacklist, lvl=debug) running = set(s...
running: ", name, lvl=warn) else: runningcomponent = componentdata() runningcomponent.register(self) self.runningcomponents[name] = runningcomponent except Exception as e: self.log("Could not register component: ", name, e, type(e), lvl=error, exc=True)
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.log(len(AuthorizedEvents), "authorized event sources:", list(AuthorizedEvents.keys()), lv...
def user(ctx, username, password): """[GROUP] User management operations""" ctx.obj['username'] = username ctx.obj['password'] = password
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'].objectmodels['user'].count({'name': username}) > 0: raise KeyError() new_user = ctx.obj['db'].objectmodels['user']({ 'uuid': str(uuid4()), ...
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)
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)
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('Confirm deletion', default=False, data_type='bool'): try: del_use...
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['db'].objectmodels['user'].find_one({ 'name': username }) if change_user is None: log('No such user', lvl=warn) return change_user.pass...
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(found_user.name, end=' ' if active or uuid else '\n') if uuid: print(found_us...
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_user.active = False change_user.save() log('Done')
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_user.active = True change_user.save() log('Done')
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'].objectmodels['user'].find_one({ 'name': ctx.obj['username'] }) if role not in change_...
def check_expression(testing_framework, expression_dict): """ >>> 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 a...
""" expression_sub = get_expression_sub() for expression_type_name, expression_type in expression_dict.items(): for name, expression_object in expression_type.items(): if 'Matches' in expression_object.keys(): for test in expression_object['Matches'].split('|'): # Substitute and check to make sure that the entire strin...
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(self.alerts), 'future tasks')
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 about task now:', task) address = objectmodels['user'].find_one({'uuid': task.owner}).mail subject = "T...
def read(self, data): """Handles incoming raw sensor data and broadcasts it to specified udp servers and connected tcp clients :param data: NMEA raw sentences incoming data """ self.log('Received NMEA data:', data, lvl=debug) # self.log(data, pretty=True) if self._tcp_socket is not None and \ len(self._connected_tcp_en...
if self._udp_socket is not None and \ len(self.config.udp_endpoints) > 0: self.log('Publishing data to udp endpoints', lvl=debug) for endpoint in self.config.udp_endpoints: host, port = endpoint.split(":") self.log('Transmitting to', endpoint, lvl=verbose) self.fireEvent( write( (host, int(port)), bytes(data, 'ascii') ...
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__: if len(groups) > 0: if xdot: line = " %s -> %s [weight=1.0];\n" % (groups...
map_output.append(line) for item in command.commands.values(): subgroups = copy(groups) subgroups.append(command.name) print_commands(item, map_output, subgroups, depth + 1) else: if xdot: line = " %s -> %s [weight=%1.1f];\n" % (groups[-1], command.name, len(groups)) else: line = " " * (len(groups) - 3 + depth) + "%s %...
'w') as f: f.write('strict digraph {\n') f.writelines(sorted(output)) f.write('}') run_process('.', ['xdot', 'iso.dot']) else: print("".join(output))
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 (ValueError, KeyError) as e: # print("Templating error: %s %s" % (e, type(e))) # pprint(result) ret...
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') return format_template(template, 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 open(target, 'w') as f: for line in data: if type(line) != str: line = line.encode('utf-8'...
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.readlines()) pprint(old_config) if definition in old_config: print("...
open(config_file, "w") as f: f.write(parts[0]) f.write(splitter + "\n") f.write(parts[1]) for line in definition: f.write(line) f.write("\n " + splitter) f.write(parts[2]) except Exception as e: print("Error during Nginx configuration extension:", type(e), e)
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.exit() else: schemata = database.objectmodels.keys() else: schemata = [schema] th...
if len(things) == 0: log('No objects matched the criteria.', lvl=warn) sys.exit() ctx.obj['objects'] = things ctx.obj['action'] = action ctx.obj['role'] = role
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 for this to work.', lvl=warn) return for item in objects: if role not...