INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
smoothed filled polygon
def smoothpolygon(document, coords): "smoothed filled polygon" element = document.createElement('path') path = [] points = [(coords[i], coords[i+1]) for i in range(0, len(coords), 2)] def pt(points): p = points n = len(points) for i in range(0, len(points)): a = p[(i-1) % n] b = p[i] c = p[(i...
circle/ ellipse
def oval(document, coords): "circle/ellipse" x1, y1, x2, y2 = coords # circle if x2-x1 == y2-y1: return setattribs(document.createElement('circle'), cx = (x1+x2)/2, cy = (y1+y2)/2, r = abs(x2-x1)/2, ) # ellipse else: return setattribs(document.createElement('ellipse'), cx = (x1+x2)/2, cy ...
arc pieslice ( filled ) arc with chord ( filled )
def arc(document, bounding_rect, start, extent, style): "arc, pieslice (filled), arc with chord (filled)" (x1, y1, x2, y2) = bounding_rect import math cx = (x1 + x2)/2.0 cy = (y1 + y2)/2.0 rx = (x2 - x1)/2.0 ry = (y2 - y1)/2.0 start = math.radians(float(start)) extent = math.radians(float(extent)) # fr...
returns Tk color in form #rrggbb or #rgb
def HTMLcolor(canvas, color): "returns Tk color in form '#rrggbb' or '#rgb'" if color: # r, g, b \in [0..2**16] r, g, b = ["%02x" % (c // 256) for c in canvas.winfo_rgb(color)] if (r[0] == r[1]) and (g[0] == g[1]) and (b[0] == b[1]): # shorter form #rgb return "#" + r[0] + g[0] + b[0] else: return ...
make arrow head at ( x1 y1 ) arrowshape is tuple ( d1 d2 d3 )
def arrow_head(document, x0, y0, x1, y1, arrowshape): "make arrow head at (x1,y1), arrowshape is tuple (d1, d2, d3)" import math dx = x1 - x0 dy = y1 - y0 poly = document.createElement('polygon') d = math.sqrt(dx*dx + dy*dy) if d == 0.0: # XXX: equal, no "close enough" return poly try: d1, d2, d3 = l...
actual font parameters
def font_actual(tkapp, font): "actual font parameters" tmp = tkapp.call('font', 'actual', font) return dict( (tmp[i][1:], tmp[i+1]) for i in range(0, len(tmp), 2) )
parse dash pattern specified with string
def parse_dash(string, width): "parse dash pattern specified with string" # DashConvert from {tk-sources}/generic/tkCanvUtil.c w = max(1, int(width + 0.5)) n = len(string) result = [] for i, c in enumerate(string): if c == " " and len(result): result[-1] += w + 1 elif c == "_": result.append(8*w) ...
Return altitude for given pressure.
def prof_altitude(pressure, p_coef=(-0.028389, -0.0493698, 0.485718, 0.278656, -17.5703, 48.0926)): """ Return altitude for given pressure. This function evaluates a polynomial at log10(pressure) values. Parameters ---------- pressure : array-like pr...
Return pressure for given altitude.
def prof_pressure(altitude, z_coef=(1.94170e-9, -5.14580e-7, 4.57018e-5, -1.55620e-3, -4.61994e-2, 2.99955)): """ Return pressure for given altitude. This function evaluates a polynomial at altitudes values. Parameters ---------- altitude : array-like ...
Iterate over model references for model_name and return a list of parent model specifications ( including those of model_name ordered from parent to child ).
def _find_references(model_name, references=None): """ Iterate over model references for `model_name` and return a list of parent model specifications (including those of `model_name`, ordered from parent to child). """ references = references or [] references.append(model_name) ref = M...
Get the grid specifications for a given model.
def _get_model_info(model_name): """ Get the grid specifications for a given model. Parameters ---------- model_name : string Name of the model. Supports multiple formats (e.g., 'GEOS5', 'GEOS-5' or 'GEOS_5'). Returns ------- specifications : dict Grid specifica...
Extract the list of files from a tar or zip archive.
def _get_archive_filelist(filename): # type: (str) -> List[str] """Extract the list of files from a tar or zip archive. Args: filename: name of the archive Returns: Sorted list of files in the archive, excluding './' Raises: ValueError: when the file is neither a zip nor a...
Checks if the newly created object is a book and only has an ISBN. If so tries to fetch the book data off the internet.
def _augment_book(self, uuid, event): """ Checks if the newly created object is a book and only has an ISBN. If so, tries to fetch the book data off the internet. :param uuid: uuid of book to augment :param client: requesting client """ try: if not is...
Lists serial port names
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-p...
Initiates communication with the remote controlled device.
def opened(self, *args): """Initiates communication with the remote controlled device. :param args: """ self._serial_open = True self.log("Opened: ", args, lvl=debug) self._send_command(b'l,1') # Saying hello, shortly self.log("Turning off engine, pump and neut...
Sets a new machine speed.
def on_machinerequest(self, event): """ Sets a new machine speed. :param event: """ self.log("Updating new machine power: ", event.controlvalue) self._handle_servo(self._machine_channel, event.controlvalue)
Sets a new rudder angle.
def on_rudderrequest(self, event): """ Sets a new rudder angle. :param event: """ self.log("Updating new rudder angle: ", event.controlvalue) self._handle_servo(self._rudder_channel, event.controlvalue)
Activates or deactivates a connected pump.
def on_pumprequest(self, event): """ Activates or deactivates a connected pump. :param event: """ self.log("Updating pump status: ", event.controlvalue) self._set_digital_pin(self._pump_channel, event.controlvalue)
Provisions a list of items according to their schema
def provisionList(items, database_name, overwrite=False, clear=False, skip_user_check=False): """Provisions a list of items according to their schema :param items: A list of provisionable items. :param database_object: A warmongo database object :param overwrite: Causes existing items to be overwritten...
Create a default field
def DefaultExtension(schema_obj, form_obj, schemata=None): """Create a default field""" if schemata is None: schemata = ['systemconfig', 'profile', 'client'] DefaultExtends = { 'schema': { "properties/modules": [ schema_obj ] }, 'form...
Copies a whole directory tree
def copytree(root_src_dir, root_dst_dir, hardlink=True): """Copies a whole directory tree""" for src_dir, dirs, files in os.walk(root_src_dir): dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1) if not os.path.exists(dst_dir): os.makedirs(dst_dir) for file_ in files: ...
Builds and installs the frontend
def install_frontend(instance='default', forcereload=False, forcerebuild=False, forcecopy=True, install=True, development=False, build_type='dist'): """Builds and installs the frontend""" hfoslog("Updating frontend components", emitter='BUILDER') components = {} loadable_components...
[ GROUP ] Configuration management operations
def config(ctx): """[GROUP] Configuration management operations""" from hfos import database database.initialize(ctx.obj['dbhost'], ctx.obj['dbname']) from hfos.schemata.component import ComponentConfigSchemaTemplate ctx.obj['col'] = model_factory(ComponentConfigSchemaTemplate)
Delete an existing component configuration. This will trigger the creation of its default configuration upon next restart.
def delete(ctx, componentname): """Delete an existing component configuration. This will trigger the creation of its default configuration upon next restart.""" col = ctx.obj['col'] if col.count({'name': componentname}) > 1: log('More than one component configuration of this name! Try ' ...
Show the stored active configuration of a component.
def show(ctx, component): """Show the stored, active configuration of a component.""" col = ctx.obj['col'] if col.count({'name': component}) > 1: log('More than one component configuration of this name! Try ' 'one of the uuids as argument. Get a list with "config ' 'list"')...
>>> separate_string ( test <2 > ) ( [ test ] [ 2 ] )
def separate_string(string): """ >>> separate_string("test <2>") (['test ', ''], ['2']) """ string_list = regex.split(r'<(?![!=])', regex.sub(r'>', '<', string)) return string_list[::2], string_list[1::2]
>>> overlapping ( 0 5 6 7 ) False >>> overlapping ( 1 2 0 4 ) True >>> overlapping ( 5 6 0 5 ) False
def overlapping(start1, end1, start2, end2): """ >>> overlapping(0, 5, 6, 7) False >>> overlapping(1, 2, 0, 4) True >>> overlapping(5,6,0,5) False """ return not ((start1 <= start2 and start1 <= end2 and end1 <= end2 and end1 <= start2) or (start1 >= start2 and start1...
>>> remove_lower_overlapping ( [] [ ( a 0 5 ) ] ) [ ( a 0 5 ) ] >>> remove_lower_overlapping ( [ ( z 0 4 ) ] [ ( a 0 5 ) ] ) [ ( a 0 5 ) ] >>> remove_lower_overlapping ( [ ( z 5 6 ) ] [ ( a 0 5 ) ] ) [ ( z 5 6 ) ( a 0 5 ) ]
def remove_lower_overlapping(current, higher): """ >>> remove_lower_overlapping([], [('a', 0, 5)]) [('a', 0, 5)] >>> remove_lower_overlapping([('z', 0, 4)], [('a', 0, 5)]) [('a', 0, 5)] >>> remove_lower_overlapping([('z', 5, 6)], [('a', 0, 5)]) [('z', 5, 6), ('a', 0, 5)] """ for (mat...
Handler for client - side debug requests
def debugrequest(self, event): """Handler for client-side debug requests""" try: self.log("Event: ", event.__dict__, lvl=critical) if event.data == "storejson": self.log("Storing received object to /tmp", lvl=critical) fp = open('/tmp/hfosdebugger...
read Event ( on channel stdin ) This is the event handler for read events specifically from the stdin channel. This is triggered each time stdin has data that it has read.
def stdin_read(self, data): """read Event (on channel ``stdin``) This is the event handler for ``read`` events specifically from the ``stdin`` channel. This is triggered each time stdin has data that it has read. """ data = data.strip().decode("utf-8") self.log("...
Registers a new command line interface event hook as command
def register_event(self, event): """Registers a new command line interface event hook as command""" self.log('Registering event hook:', event.cmd, event.thing, pretty=True, lvl=verbose) self.hooks[event.cmd] = event.thing
Generate a list of all registered authorized and anonymous events
def populate_user_events(): """Generate a list of all registered authorized and anonymous events""" global AuthorizedEvents global AnonymousEvents def inheritors(klass): """Find inheritors of a specified object class""" subclasses = {} subclasses_set = set() work = [kl...
[ GROUP ] Database management operations
def db(ctx): """[GROUP] Database management operations""" from hfos import database database.initialize(ctx.obj['dbhost'], ctx.obj['dbname']) ctx.obj['db'] = database
Clears an entire database collection irrevocably. Use with caution!
def clear(ctx, schema): """Clears an entire database collection irrevocably. Use with caution!""" response = _ask('Are you sure you want to delete the collection "%s"' % ( schema), default='N', data_type='bool') if response is True: host, port = ctx.obj['dbhost'].split(':') client ...
Provision a basic system configuration
def provision_system_config(items, database_name, overwrite=False, clear=False, skip_user_check=False): """Provision a basic system configuration""" from hfos.provisions.base import provisionList from hfos.database import objectmodels default_system_config_count = objectmodels['systemconfig'].count({ ...
Calendar Importer for iCal ( ics ) files
def ICALImporter(ctx, filename, all, owner, calendar, create_calendar, clear_calendar, dry, execfilter): """Calendar Importer for iCal (ics) files """ log('iCal importer running') objectmodels = ctx.obj['db'].objectmodels if objectmodels['user'].count({'name': owner}) > 0: owner_object =...
Create migration data for a specified schema
def make_migrations(schema=None): """Create migration data for a specified schema""" entrypoints = {} old = {} def apply_migrations(migrations, new_model): """Apply migration data to compile an up to date model""" def get_path(raw_path): """Get local path of schema definit...
Provides the newly authenticated user with a backlog and general channel status information
def userlogin(self, event): """Provides the newly authenticated user with a backlog and general channel status information""" try: user_uuid = event.useruuid user = objectmodels['user'].find_one({'uuid': user_uuid}) if user_uuid not in self.lastlogs: ...
Chat event handler for incoming events: param event: say - event with incoming chat message
def join(self, event): """Chat event handler for incoming events :param event: say-event with incoming chat message """ try: channel_uuid = event.data user_uuid = event.user.uuid if channel_uuid in self.chat_channels: self.log('User j...
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 = self._get_recipient(event) content = self._get_content(event) message = objec...
Builds and installs the complete HFOS documentation.
def install_docs(instance, clear_target): """Builds and installs the complete HFOS documentation.""" _check_root() def make_docs(): """Trigger a Sphinx make command to build the documentation.""" log("Generating HTML documentation") try: build = Popen( ...
Install variable data to/ var/ [ lib cache ]/ hfos
def var(ctx, clear_target, clear_all): """Install variable data to /var/[lib,cache]/hfos""" install_var(str(ctx.obj['instance']), clear_target, clear_all)
Install required folders in/ var
def install_var(instance, clear_target, clear_all): """Install required folders in /var""" _check_root() log("Checking frontend library and cache directories", emitter='MANAGE') uid = pwd.getpwnam("hfos").pw_uid gid = grp.getgrnam("hfos").gr_gid join = os.path.join # If these nee...
Install default provisioning data
def provisions(ctx, provision, clear_existing, overwrite, list_provisions): """Install default provisioning data""" install_provisions(ctx, provision, clear_existing, overwrite, list_provisions)
Install default provisioning data
def install_provisions(ctx, provision, clear_provisions=False, overwrite=False, list_provisions=False): """Install default provisioning data""" log("Installing HFOS default provisions") # from hfos.logger import verbosity, events # verbosity['console'] = verbosity['global'] = events from hfos imp...
Install the plugin modules
def install_modules(wip): """Install the plugin modules""" def install_module(hfos_module): """Install a single module via setuptools""" try: setup = Popen( [ sys.executable, 'setup.py', 'develop' ...
Install systemd service configuration
def service(ctx): """Install systemd service configuration""" install_service(ctx.obj['instance'], ctx.obj['dbhost'], ctx.obj['dbname'], ctx.obj['port'])
Install systemd service configuration
def install_service(instance, dbhost, dbname, port): """Install systemd service configuration""" _check_root() log("Installing systemd service") launcher = os.path.realpath(__file__).replace('manage', 'launcher') executable = sys.executable + " " + launcher executable += " --instance " + inst...
Install nginx configuration
def nginx(ctx, hostname): """Install nginx configuration""" install_nginx(ctx.obj['dbhost'], ctx.obj['dbname'], ctx.obj['port'], hostname)
Install nginx configuration
def install_nginx(instance, dbhost, dbname, port, hostname=None): """Install nginx configuration""" _check_root() log("Installing nginx configuration") if hostname is None: try: configuration = _get_system_configuration(dbhost, dbname) hostname = configuration.hostname...
Install a local SSL certificate
def install_cert(selfsigned): """Install a local SSL certificate""" _check_root() if selfsigned: log('Generating self signed (insecure) certificate/key ' 'combination') try: os.mkdir('/etc/ssl/certs/hfos') except FileExistsError: pass ex...
Build and install frontend
def frontend(ctx, dev, rebuild, no_install, build_type): """Build and install frontend""" install_frontend(instance=ctx.obj['instance'], forcerebuild=rebuild, development=dev, install=not no_install, build_type=build_type)
Default - Install everything installable
def install_all(ctx, clear_all): """Default-Install everything installable \b This includes * System user (hfos.hfos) * Self signed certificate * Variable data locations (/var/lib/hfos and /var/cache/hfos) * All the official modules in this repository * Default module provisioning data ...
Uninstall data and resource locations
def uninstall(): """Uninstall data and resource locations""" _check_root() response = _ask("This will delete all data of your HFOS installations! Type" "YES to continue:", default="N", show_hint=False) if response == 'YES': shutil.rmtree('/var/lib/hfos') shutil.rmtr...
Update a HFOS node
def update(ctx, no_restart, no_rebuild): """Update a HFOS node""" # 0. (NOT YET! MAKE A BACKUP OF EVERYTHING) # 1. update repository # 2. update frontend repository # 3. (Not yet: update venv) # 4. rebuild frontend # 5. restart service instance = ctx.obj['instance'] log('Pulling g...
Handles incoming raw sensor data: param event: Raw sentences incoming data
def raw_data(self, event): """Handles incoming raw sensor data :param event: Raw sentences incoming data """ self.log('Received raw data from bus', lvl=events) if not parse: return nmea_time = event.data[0] try: parsed_data = parse(event....
DANGER! * This command is a maintenance tool and clears the complete database. *
def clear_all(): """DANGER! *This command is a maintenance tool and clears the complete database.* """ sure = input("Are you sure to drop the complete database content? (Type " "in upppercase YES)") if not (sure == 'YES'): db_log('Not deleting the database.') sys.ex...
Generate factories to construct objects from schemata
def _build_model_factories(store): """Generate factories to construct objects from schemata""" result = {} for schemaname in store: schema = None try: schema = store[schemaname]['schema'] except KeyError: schemata_log("No schema found for ", schemaname, lv...
Generate database collections with indices from the schemastore
def _build_collections(store): """Generate database collections with indices from the schemastore""" result = {} client = pymongo.MongoClient(host=dbhost, port=dbport) db = client[dbname] for schemaname in store: schema = None indices = None try: schema = sto...
Initializes the database connectivity schemata and finally object models
def initialize(address='127.0.0.1:27017', database_name='hfos', instance_name="default", reload=False): """Initializes the database connectivity, schemata and finally object models""" global schemastore global l10n_schemastore global objectmodels global collections global dbhost global dbpo...
Profiles object model handling with a very simple benchmarking test
def profile(schemaname='sensordata', profiletype='pjs'): """Profiles object model handling with a very simple benchmarking test""" db_log("Profiling ", schemaname) schema = schemastore[schemaname]['schema'] db_log("Schema: ", schema, lvl=debug) testclass = None if profiletype == 'warmongo':...
Exports all collections to ( JSON - ) files.
def backup(schema, uuid, export_filter, export_format, filename, pretty, export_all, omit): """Exports all collections to (JSON-) files.""" export_format = export_format.upper() if pretty: indent = 4 else: indent = 0 f = None if filename: try: f = open(fil...
Checks node local collection storage sizes
def _check_collections(self): """Checks node local collection storage sizes""" self.collection_sizes = {} self.collection_total = 0 for col in self.db.collection_names(include_system_collections=False): self.collection_sizes[col] = self.db.command('collstats', col).get( ...
Checks used filesystem storage sizes
def _check_free_space(self): """Checks used filesystem storage sizes""" def get_folder_size(path): """Aggregates used size of a specified path, recursively""" total_size = 0 for item in walk(path): for file in item[2]: try: ...
Worker task to send out an email which blocks the process unless it is threaded
def send_mail_worker(config, mail, event): """Worker task to send out an email, which blocks the process unless it is threaded""" log = "" try: if config.mail_ssl: server = SMTP_SSL(config.mail_server, port=config.mail_server_port, timeout=30) else: server = SMTP(con...
Reload the current configuration and set up everything depending on it
def reload_configuration(self, event): """Reload the current configuration and set up everything depending on it""" super(EnrolManager, self).reload_configuration(event) self.log('Reloaded configuration.') self._setup()
An admin user requests a change to an enrolment
def change(self, event): """An admin user requests a change to an enrolment""" uuid = event.data['uuid'] status = event.data['status'] if status not in ['Open', 'Pending', 'Accepted', 'Denied', 'Resend']: self.log('Erroneous status for enrollment requested!', lvl=warn) ...
An enrolled user wants to change their password
def changepassword(self, event): """An enrolled user wants to change their password""" old = event.data['old'] new = event.data['new'] uuid = event.user.uuid # TODO: Write email to notify user of password change user = objectmodels['user'].find_one({'uuid': uuid}) ...
A new user has been invited to enrol by an admin user
def invite(self, event): """A new user has been invited to enrol by an admin user""" self.log('Inviting new user to enrol') name = event.data['name'] email = event.data['email'] method = event.data['method'] self._invite(name, method, email, event.client.uuid, event)
A user tries to self - enrol with the enrolment form
def enrol(self, event): """A user tries to self-enrol with the enrolment form""" if self.config.allow_registration is False: self.log('Someone tried to register although enrolment is closed.') return self.log('Client trying to register a new account:', event, pretty=Tru...
A challenge/ response for an enrolment has been accepted
def accept(self, event): """A challenge/response for an enrolment has been accepted""" self.log('Invitation accepted:', event.__dict__, lvl=debug) try: uuid = event.data enrollment = objectmodels['enrollment'].find_one({ 'uuid': uuid }) ...
An anonymous client wants to know if we re open for enrollment
def status(self, event): """An anonymous client wants to know if we're open for enrollment""" self.log('Registration status requested') response = { 'component': 'hfos.enrol.enrolmanager', 'action': 'status', 'data': self.config.allow_registration } ...
An anonymous client requests a password reset
def request_reset(self, event): """An anonymous client requests a password reset""" self.log('Password reset request received:', event.__dict__, lvl=hilight) user_object = objectmodels['user'] email = event.data.get('email', None) email_user = None if email is not Non...
Delayed transmission of a requested captcha
def captcha_transmit(self, captcha, uuid): """Delayed transmission of a requested captcha""" self.log('Transmitting captcha') response = { 'component': 'hfos.enrol.enrolmanager', 'action': 'captcha', 'data': b64encode(captcha['image'].getvalue()).decode('utf...
Actually invite a given user
def _invite(self, name, method, email, uuid, event, password=""): """Actually invite a given user""" props = { 'uuid': std_uuid(), 'status': 'Open', 'name': name, 'method': method, 'email': email, 'password': password, ...
Create a new user and all initial data
def _create_user(self, username, password, mail, method, uuid): """Create a new user and all initial data""" try: if method == 'Invited': config_role = self.config.group_accept_invited else: config_role = self.config.group_accept_enrolled ...
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 ' + password + ' - please change it after your first l...
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, 'node_url': self.node_url, ...
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 = self._get_recipient(event) content = self._get_content(event) if self.config....
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.getpeername()[0] self.failing_clients[ip]...
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_account.name, ( user_acc...
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.getpeername()[0] in self.failing_clients: self.log('Client failed a login and has to wait', lvl=debug) ...
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: client_config = objectmodels['client'].find_one({...
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. # They're also required in the E...
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: ", user_profile, ...
Called when a sensor sends a new raw data to this serial connector.
def _parse(self, bus, data): """ 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. """ sen_time = time.time() try: # Split up multi...
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 else: # self.log("Incoming data: ", '%.50s ...' % event...
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', 'apex', 'qd', 'mlt'], ...
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:', e, type(e), lvl=verbose, pretty=True) log...
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 password != password_trial: print("\nPa...
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: salt = system_config.salt.encode('ascii') except ...
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'): data = input("%s? [%s]...
Makes sure the latitude is inside [ - 90 90 ] clipping close values ( tolerance 1e - 4 ).
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 o...
Computes sinIm from modified apex latitude.
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(al...
Computes cosIm from modified apex latitude.
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...
Converts: class: datetime. date or: class: datetime. datetime to decimal year.
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 take...
Converts geocentric latitude to geodetic latitude using WGS84.
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 eccentr...
Finds subsolar geocentric latitude and longitude.
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 o...