text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Shell sequence to be run after the command output. <END_TASK> <USER_TASK:> Description: def after_output(command_status): """ Shell sequence to be run after the command output. The ``command_status`` should be in the range 0-255. """
if command_status not in range(256): raise ValueError("command_status must be an integer in the range 0-255") sys.stdout.write(AFTER_OUTPUT.format(command_status=command_status)) # Flushing is important as the command timing feature maybe based on # AFTER_OUTPUT in the future. sys.stdout.flush()
<SYSTEM_TASK:> Given a Variable constructed from GEOS-Chem output, enforce <END_TASK> <USER_TASK:> Description: def enforce_cf_variable(var, mask_and_scale=True): """ Given a Variable constructed from GEOS-Chem output, enforce CF-compliant metadata and formatting. Until a bug with lazily-loaded data and masking/scaling is resolved in xarray, you have the option to manually mask and scale the data here. Parameters ---------- var : xarray.Variable A variable holding information decoded from GEOS-Chem output. mask_and_scale : bool Flag to scale and mask the data given the unit conversions provided Returns ------- out : xarray.Variable The original variable processed to conform to CF standards .. note:: This method borrows heavily from the ideas in ``xarray.decode_cf_variable`` """
var = as_variable(var) data = var._data # avoid loading by accessing _data instead of data dims = var.dims attrs = var.attrs.copy() encoding = var.encoding.copy() orig_dtype = data.dtype # Process masking/scaling coordinates. We only expect a "scale" value # for the units with this output. if 'scale' in attrs: scale = attrs.pop('scale') attrs['scale_factor'] = scale encoding['scale_factor'] = scale # TODO: Once the xr.decode_cf bug is fixed, we won't need to manually # handle masking/scaling if mask_and_scale: data = scale*data # Process units # TODO: How do we want to handle parts-per-* units? These are not part of # the udunits standard, and the CF conventions suggest using units # like 1e-6 for parts-per-million. But we potentially mix mass and # volume/molar mixing ratios in GEOS-Chem output, so we need a way # to handle that edge case. if 'unit' in attrs: unit = attrs.pop('unit') unit = get_cfcompliant_units(unit) attrs['units'] = unit # TODO: Once the xr.decode_cf bug is fixed, we won't need to manually # handle masking/scaling return Variable(dims, data, attrs, encoding=encoding)
<SYSTEM_TASK:> Returns all entries, which publication date has been hit or which have <END_TASK> <USER_TASK:> Description: def published(self, check_language=True, language=None, kwargs=None, exclude_kwargs=None): """ Returns all entries, which publication date has been hit or which have no date and which language matches the current language. """
if check_language: qs = NewsEntry.objects.language(language or get_language()).filter( is_published=True) else: qs = self.get_queryset() qs = qs.filter( models.Q(pub_date__lte=now()) | models.Q(pub_date__isnull=True) ) if kwargs is not None: qs = qs.filter(**kwargs) if exclude_kwargs is not None: qs = qs.exclude(**exclude_kwargs) return qs.distinct().order_by('-pub_date')
<SYSTEM_TASK:> Returns recently published new entries. <END_TASK> <USER_TASK:> Description: def recent(self, check_language=True, language=None, limit=3, exclude=None, kwargs=None, category=None): """ Returns recently published new entries. """
if category: if not kwargs: kwargs = {} kwargs['categories__in'] = [category] qs = self.published(check_language=check_language, language=language, kwargs=kwargs) if exclude: qs = qs.exclude(pk=exclude.pk) return qs[:limit]
<SYSTEM_TASK:> Returns the meta description for the given entry. <END_TASK> <USER_TASK:> Description: def get_newsentry_meta_description(newsentry): """Returns the meta description for the given entry."""
if newsentry.meta_description: return newsentry.meta_description # If there is no seo addon found, take the info from the placeholders text = newsentry.get_description() if len(text) > 160: return u'{}...'.format(text[:160]) return text
<SYSTEM_TASK:> Check if the requirement is satisfied by the marker. <END_TASK> <USER_TASK:> Description: def _requirement_filter_by_marker(req): # type: (pkg_resources.Requirement) -> bool """Check if the requirement is satisfied by the marker. This function checks for a given Requirement whether its environment marker is satisfied on the current platform. Currently only the python version and system platform are checked. """
if hasattr(req, 'marker') and req.marker: marker_env = { 'python_version': '.'.join(map(str, sys.version_info[:2])), 'sys_platform': sys.platform } if not req.marker.evaluate(environment=marker_env): return False return True
<SYSTEM_TASK:> Find lowest required version. <END_TASK> <USER_TASK:> Description: def _requirement_find_lowest_possible(req): # type: (pkg_resources.Requirement) -> List[str] """Find lowest required version. Given a single Requirement, this function calculates the lowest required version to satisfy it. If the requirement excludes a specific version, then this version will not be used as the minimal supported version. Examples -------- >>> req = pkg_resources.Requirement.parse("foobar>=1.0,>2") >>> _requirement_find_lowest_possible(req) ['foobar', '>=', '1.0'] >>> req = pkg_resources.Requirement.parse("baz>=1.3,>3,!=1.5") >>> _requirement_find_lowest_possible(req) ['baz', '>=', '1.3'] """
version_dep = None # type: Optional[str] version_comp = None # type: Optional[str] for dep in req.specs: version = pkg_resources.parse_version(dep[1]) # we don't want to have a not supported version as minimal version if dep[0] == '!=': continue # try to use the lowest version available # i.e. for ">=0.8.4,>=0.9.7", select "0.8.4" if (not version_dep or version < pkg_resources.parse_version(version_dep)): version_dep = dep[1] version_comp = dep[0] assert (version_dep is None and version_comp is None) or \ (version_dep is not None and version_comp is not None) return [ x for x in (req.unsafe_name, version_comp, version_dep) if x is not None]
<SYSTEM_TASK:> Return a coroutine function. <END_TASK> <USER_TASK:> Description: def _ensure_coroutine_function(func): """Return a coroutine function. func: either a coroutine function or a regular function Note a coroutine function is not a coroutine! """
if asyncio.iscoroutinefunction(func): return func else: @asyncio.coroutine def coroutine_function(evt): func(evt) yield return coroutine_function
<SYSTEM_TASK:> Return a string uniquely identifying the event. <END_TASK> <USER_TASK:> Description: def location(self): """Return a string uniquely identifying the event. This string can be used to find the event in the event store UI (cf. id attribute, which is the UUID that at time of writing doesn't let you easily find the event). """
if self._location is None: self._location = "{}/{}-{}".format( self.stream, self.type, self.sequence, ) return self._location
<SYSTEM_TASK:> Return first event matching predicate, or None if none exists. <END_TASK> <USER_TASK:> Description: async def find_backwards(self, stream_name, predicate, predicate_label='predicate'): """Return first event matching predicate, or None if none exists. Note: 'backwards', both here and in Event Store, means 'towards the event emitted furthest in the past'. """
logger = self._logger.getChild(predicate_label) logger.info('Fetching first matching event') uri = self._head_uri try: page = await self._fetcher.fetch(uri) except HttpNotFoundError as e: raise StreamNotFoundError() from e while True: evt = next(page.iter_events_matching(predicate), None) if evt is not None: return evt uri = page.get_link("next") if uri is None: logger.warning("No matching event found") return None page = await self._fetcher.fetch(uri)
<SYSTEM_TASK:> Command line interface for the ``qpass`` program. <END_TASK> <USER_TASK:> Description: def main(): """Command line interface for the ``qpass`` program."""
# Initialize logging to the terminal. coloredlogs.install() # Prepare for command line argument parsing. action = show_matching_entry program_opts = dict(exclude_list=[]) show_opts = dict(filters=[], use_clipboard=is_clipboard_supported()) verbosity = 0 # Parse the command line arguments. try: options, arguments = getopt.gnu_getopt( sys.argv[1:], "elnp:f:x:vqh", ["edit", "list", "no-clipboard", "password-store=", "filter=", "exclude=", "verbose", "quiet", "help"], ) for option, value in options: if option in ("-e", "--edit"): action = edit_matching_entry elif option in ("-l", "--list"): action = list_matching_entries elif option in ("-n", "--no-clipboard"): show_opts["use_clipboard"] = False elif option in ("-p", "--password-store"): stores = program_opts.setdefault("stores", []) stores.append(PasswordStore(directory=value)) elif option in ("-f", "--filter"): show_opts["filters"].append(value) elif option in ("-x", "--exclude"): program_opts["exclude_list"].append(value) elif option in ("-v", "--verbose"): coloredlogs.increase_verbosity() verbosity += 1 elif option in ("-q", "--quiet"): coloredlogs.decrease_verbosity() verbosity -= 1 elif option in ("-h", "--help"): usage(__doc__) return else: raise Exception("Unhandled option! (programming error)") if not (arguments or action == list_matching_entries): usage(__doc__) return except Exception as e: warning("Error: %s", e) sys.exit(1) # Execute the requested action. try: show_opts["quiet"] = verbosity < 0 kw = show_opts if action == show_matching_entry else {} action(QuickPass(**program_opts), arguments, **kw) except PasswordStoreError as e: # Known issues don't get a traceback. logger.error("%s", e) sys.exit(1) except KeyboardInterrupt: # If the user interrupted an interactive prompt they most likely did so # intentionally, so there's no point in generating more output here. sys.exit(1)
<SYSTEM_TASK:> Edit the matching entry. <END_TASK> <USER_TASK:> Description: def edit_matching_entry(program, arguments): """Edit the matching entry."""
entry = program.select_entry(*arguments) entry.context.execute("pass", "edit", entry.name)
<SYSTEM_TASK:> Return altitude for given pressure. <END_TASK> <USER_TASK:> Description: 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 pressure values [hPa]. p_coef : array-like coefficients of the polynomial (default values are for the US Standard Atmosphere). Returns ------- altitude : array-like altitude values [km] (same shape than the pressure input array). See Also -------- prof_pressure : Returns pressure for given altitude. prof_temperature : Returns air temperature for given altitude. Notes ----- Default coefficient values represent a 5th degree polynomial which had been fitted to USSA data from 0-100 km. Accuracy is on the order of 1% for 0-100 km and 0.5% below 30 km. This function, with default values, may thus produce bad results with pressure less than about 3e-4 hPa. Examples -------- >>> prof_altitude([1000, 800, 600]) array([ 0.1065092 , 1.95627858, 4.2060627 ]) """
pressure = np.asarray(pressure) altitude = np.polyval(p_coef, np.log10(pressure.flatten())) return altitude.reshape(pressure.shape)
<SYSTEM_TASK:> Return pressure for given altitude. <END_TASK> <USER_TASK:> Description: 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 altitude values [km]. z_coef : array-like coefficients of the polynomial (default values are for the US Standard Atmosphere). Returns ------- pressure : array-like pressure values [hPa] (same shape than the altitude input array). See Also -------- prof_altitude : Returns altitude for given pressure. prof_temperature : Returns air temperature for given altitude. Notes ----- Default coefficient values represent a 5th degree polynomial which had been fitted to USA data from 0-100 km. Accuracy is on the order of 1% for 0-100 km and 0.5% below 30 km. This function, with default values, may thus produce bad results with altitude > 100 km. Examples -------- >>> prof_pressure([0, 10, 20]) array([ 998.96437334, 264.658697 , 55.28114631]) """
altitude = np.asarray(altitude) pressure = np.power(10, np.polyval(z_coef, altitude.flatten())) return pressure.reshape(altitude.shape)
<SYSTEM_TASK:> Get the grid specifications for a given model. <END_TASK> <USER_TASK:> Description: 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 specifications as a dictionary. Raises ------ ValueError If the model is not supported (see `models`) or if the given `model_name` corresponds to several entries in the list of supported models. """
# trying to get as much as possible a valid model name from the given # `model_name`, using regular expressions. split_name = re.split(r'[\-_\s]', model_name.strip().upper()) sep_chars = ('', ' ', '-', '_') gen_seps = itertools.combinations_with_replacement( sep_chars, len(split_name) - 1 ) test_names = ("".join((n for n in itertools.chain(*list(zip(split_name, s + ('',)))))) for s in gen_seps) match_names = list([name for name in test_names if name in _get_supported_models()]) if not len(match_names): raise ValueError("Model '{0}' is not supported".format(model_name)) elif len(match_names) > 1: raise ValueError("Multiple matched models for given model name '{0}'" .format(model_name)) valid_model_name = match_names[0] parent_models = _find_references(valid_model_name) model_spec = dict() for m in parent_models: model_spec.update(MODELS[m]) model_spec.pop('reference') model_spec['model_family'] = parent_models[0] model_spec['model_name'] = valid_model_name return model_spec
<SYSTEM_TASK:> Extract the list of files from a tar or zip archive. <END_TASK> <USER_TASK:> Description: 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 tar archive FileNotFoundError: when the provided file does not exist (for Python 3) IOError: when the provided file does not exist (for Python 2) """
names = [] # type: List[str] if tarfile.is_tarfile(filename): with tarfile.open(filename) as tar_file: names = sorted(tar_file.getnames()) elif zipfile.is_zipfile(filename): with zipfile.ZipFile(filename) as zip_file: names = sorted(zip_file.namelist()) else: raise ValueError("Can not get filenames from '{!s}'. " "Not a tar or zip file".format(filename)) if "./" in names: names.remove("./") return names
<SYSTEM_TASK:> Checks if the newly created object is a book and only has an ISBN. <END_TASK> <USER_TASK:> Description: 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 isbnmeta: self.log( "No isbntools found! Install it to get full " "functionality!", lvl=warn) return new_book = objectmodels['book'].find_one({'uuid': uuid}) try: if len(new_book.isbn) != 0: self.log('Got a lookup candidate: ', new_book._fields) try: meta = isbnmeta( new_book.isbn, service=self.config.isbnservice ) mapping = libraryfieldmapping[ self.config.isbnservice ] new_meta = {} for key in meta.keys(): if key in mapping: if isinstance(mapping[key], tuple): name, conv = mapping[key] try: new_meta[name] = conv(meta[key]) except ValueError: self.log( 'Bad value from lookup:', name, conv, key ) else: new_meta[mapping[key]] = meta[key] new_book.update(new_meta) new_book.save() self._notify_result(event, new_book) self.log("Book successfully augmented from ", self.config.isbnservice) except Exception as e: self.log("Error during meta lookup: ", e, type(e), new_book.isbn, lvl=error, exc=True) error_response = { 'component': 'hfos.alert.manager', 'action': 'notify', 'data': { 'type': 'error', 'message': 'Could not look up metadata, sorry:' + str(e) } } self.log(event, event.client, pretty=True) self.fireEvent(send(event.client.uuid, error_response)) except Exception as e: self.log("Error during book update.", e, type(e), exc=True, lvl=error) except Exception as e: self.log("Book creation notification error: ", uuid, e, type(e), lvl=error, exc=True)
<SYSTEM_TASK:> Initiates communication with the remote controlled device. <END_TASK> <USER_TASK:> Description: 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 neutralizing rudder") self._send_command(b'v') self._handle_servo(self._machine_channel, 0) self._handle_servo(self._rudder_channel, 127) self._set_digital_pin(self._pump_channel, 0) # self._send_command(b'h') self._send_command(b'l,0') self._send_command(b'm,HFOS Control')
<SYSTEM_TASK:> Activates or deactivates a connected pump. <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Provisions a list of items according to their schema <END_TASK> <USER_TASK:> Description: 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 :param clear: Clears the collection first (Danger!) :param skip_user_check: Skips checking if a system user is existing already (for user provisioning) :return: """
log('Provisioning', items, database_name, lvl=debug) system_user = None def get_system_user(): """Retrieves the node local system user""" user = objectmodels['user'].find_one({'name': 'System'}) try: log('System user uuid: ', user.uuid, lvl=verbose) return user.uuid except AttributeError as e: log('No system user found:', e, lvl=warn) log('Please install the user provision to setup a system user or check your database configuration', lvl=error) return False # TODO: Do not check this on specific objects but on the model (i.e. once) def needs_owner(obj): """Determines whether a basic object has an ownership field""" for privilege in obj._fields.get('perms', None): if 'owner' in obj._fields['perms'][privilege]: return True return False import pymongo from hfos.database import objectmodels, dbhost, dbport, dbname database_object = objectmodels[database_name] log(dbhost, dbname) # TODO: Fix this to make use of the dbhost client = pymongo.MongoClient(dbhost, dbport) db = client[dbname] if not skip_user_check: system_user = get_system_user() if not system_user: return else: # TODO: Evaluate what to do instead of using a hardcoded UUID # This is usually only here for provisioning the system user # One way to avoid this, is to create (instead of provision) # this one upon system installation. system_user = '0ba87daa-d315-462e-9f2e-6091d768fd36' col_name = database_object.collection_name() if clear is True: log("Clearing collection for", col_name, lvl=warn) db.drop_collection(col_name) counter = 0 for no, item in enumerate(items): new_object = None item_uuid = item['uuid'] log("Validating object (%i/%i):" % (no + 1, len(items)), item_uuid, lvl=debug) if database_object.count({'uuid': item_uuid}) > 0: log('Object already present', lvl=warn) if overwrite is False: log("Not updating item", item, lvl=warn) else: log("Overwriting item: ", item_uuid, lvl=warn) new_object = database_object.find_one({'uuid': item_uuid}) new_object._fields.update(item) else: new_object = database_object(item) if new_object is not None: try: if needs_owner(new_object): if not hasattr(new_object, 'owner'): log('Adding system owner to object.', lvl=verbose) new_object.owner = system_user except Exception as e: log('Error during ownership test:', e, type(e), exc=True, lvl=error) try: new_object.validate() new_object.save() counter += 1 except ValidationError as e: raise ValidationError( "Could not provision object: " + str(item_uuid), e) log("Provisioned %i out of %i items successfully." % (counter, len(items)))
<SYSTEM_TASK:> Copies a whole directory tree <END_TASK> <USER_TASK:> Description: 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: src_file = os.path.join(src_dir, file_) dst_file = os.path.join(dst_dir, file_) try: if os.path.exists(dst_file): if hardlink: hfoslog('Removing frontend link:', dst_file, emitter='BUILDER', lvl=verbose) os.remove(dst_file) else: hfoslog('Overwriting frontend file:', dst_file, emitter='BUILDER', lvl=verbose) hfoslog('Hardlinking ', src_file, dst_dir, emitter='BUILDER', lvl=verbose) if hardlink: os.link(src_file, dst_file) else: copy(src_file, dst_dir) except PermissionError as e: hfoslog( " No permission to remove/create target %s for " "frontend:" % ('link' if hardlink else 'copy'), dst_dir, e, emitter='BUILDER', lvl=error) except Exception as e: hfoslog("Error during", 'link' if hardlink else 'copy', "creation:", type(e), e, emitter='BUILDER', lvl=error) hfoslog('Done linking', root_dst_dir, emitter='BUILDER', lvl=verbose)
<SYSTEM_TASK:> Delete an existing component configuration. This will trigger <END_TASK> <USER_TASK:> Description: 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 ' 'one of the uuids as argument. Get a list with "config ' 'list"') return log('Deleting component configuration', componentname, emitter='MANAGE') configuration = col.find_one({'name': componentname}) if configuration is None: configuration = col.find_one({'uuid': componentname}) if configuration is None: log('Component configuration not found:', componentname, emitter='MANAGE') return configuration.delete() log('Done')
<SYSTEM_TASK:> Show the stored, active configuration of a component. <END_TASK> <USER_TASK:> Description: 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"') return if component is None: configurations = col.find() for configuration in configurations: log("%-15s : %s" % (configuration.name, configuration.uuid), emitter='MANAGE') else: configuration = col.find_one({'name': component}) if configuration is None: configuration = col.find_one({'uuid': component}) if configuration is None: log('No component with that name or uuid found.') return print(json.dumps(configuration.serializablefields(), indent=4))
<SYSTEM_TASK:> Registers a new command line interface event hook as command <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Generate a list of all registered authorized and anonymous events <END_TASK> <USER_TASK:> Description: 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 = [klass] while work: parent = work.pop() for child in parent.__subclasses__(): if child not in subclasses_set: # pprint(child.__dict__) name = child.__module__ + "." + child.__name__ if name.startswith('hfos'): subclasses_set.add(child) event = { 'event': child, 'name': name, 'doc': child.__doc__, 'args': [] } if child.__module__ in subclasses: subclasses[child.__module__][ child.__name__] = event else: subclasses[child.__module__] = { child.__name__: event } work.append(child) return subclasses # TODO: Change event system again, to catch authorized (i.e. "user") as # well as normal events, so they can be processed by Automat # NormalEvents = inheritors(Event) AuthorizedEvents = inheritors(authorizedevent) AnonymousEvents = inheritors(anonymousevent)
<SYSTEM_TASK:> Clears an entire database collection irrevocably. Use with caution! <END_TASK> <USER_TASK:> Description: 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 = pymongo.MongoClient(host=host, port=int(port)) database = client[ctx.obj['dbname']] log("Clearing collection for", schema, lvl=warn, emitter='MANAGE') result = database.drop_collection(schema) if not result['ok']: log("Could not drop collection:", lvl=error) log(result, pretty=True, lvl=error) else: log("Done")
<SYSTEM_TASK:> Provision a basic system configuration <END_TASK> <USER_TASK:> Description: 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({ 'name': 'Default System Configuration'}) if default_system_config_count == 0 or (clear or overwrite): provisionList([SystemConfiguration], 'systemconfig', overwrite, clear, skip_user_check) hfoslog('Provisioning: System: Done.', emitter='PROVISIONS') else: hfoslog('Default system configuration already present.', lvl=warn, emitter='PROVISIONS')
<SYSTEM_TASK:> Provides the newly authenticated user with a backlog and general <END_TASK> <USER_TASK:> Description: 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: self.log('Setting up lastlog for a new user.', lvl=debug) lastlog = objectmodels['chatlastlog']({ 'owner': user_uuid, 'uuid': std_uuid(), 'channels': {} }) lastlog.save() self.lastlogs[user_uuid] = lastlog self.users[user_uuid] = user self.user_attention[user_uuid] = None self._send_status(user_uuid, event.clientuuid) except Exception as e: self.log('Error during chat setup of user:', e, type(e), exc=True)
<SYSTEM_TASK:> Builds and installs the complete HFOS documentation. <END_TASK> <USER_TASK:> Description: 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( [ 'make', 'html' ], cwd='docs/' ) build.wait() except Exception as e: log("Problem during documentation building: ", e, type(e), exc=True, lvl=error) return False return True make_docs() # If these need changes, make sure they are watertight and don't remove # wanted stuff! target = os.path.join('/var/lib/hfos', instance, 'frontend/docs') source = 'docs/build/html' log("Updating documentation directory:", target) if not os.path.exists(os.path.join(os.path.curdir, source)): log( "Documentation not existing yet. Run python setup.py " "build_sphinx first.", lvl=error) return if os.path.exists(target): log("Path already exists: " + target) if clear_target: log("Cleaning up " + target, lvl=warn) shutil.rmtree(target) log("Copying docs to " + target) copy_tree(source, target) log("Done: Install Docs")
<SYSTEM_TASK:> Build and install frontend <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Default-Install everything installable <END_TASK> <USER_TASK:> Description: 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 * Documentation * systemd service descriptor It does NOT build and install the HTML5 frontend."""
_check_root() instance = ctx.obj['instance'] dbhost = ctx.obj['dbhost'] dbname = ctx.obj['dbname'] port = ctx.obj['port'] install_system_user() install_cert(selfsigned=True) install_var(instance, clear_target=clear_all, clear_all=clear_all) install_modules(wip=False) install_provisions(provision=None, clear_provisions=clear_all) install_docs(instance, clear_target=clear_all) install_service(instance, dbhost, dbname, port) install_nginx(instance, dbhost, dbname, port) log('Done')
<SYSTEM_TASK:> Generate factories to construct objects from schemata <END_TASK> <USER_TASK:> Description: 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, lvl=critical, exc=True) try: result[schemaname] = warmongo.model_factory(schema) except Exception as e: schemata_log("Could not create factory for schema ", schemaname, schema, lvl=critical, exc=True) return result
<SYSTEM_TASK:> Generate database collections with indices from the schemastore <END_TASK> <USER_TASK:> Description: 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 = store[schemaname]['schema'] indices = store[schemaname].get('indices', None) except KeyError: db_log("No schema found for ", schemaname, lvl=critical) try: result[schemaname] = db[schemaname] except Exception: db_log("Could not get collection for schema ", schemaname, schema, lvl=critical, exc=True) if indices is not None: col = db[schemaname] db_log('Adding indices to', schemaname, lvl=debug) i = 0 keys = list(indices.keys()) while i < len(indices): index_name = keys[i] index = indices[index_name] index_type = index.get('type', None) index_unique = index.get('unique', False) index_sparse = index.get('sparse', True) index_reindex = index.get('reindex', False) if index_type in (None, 'text'): index_type = pymongo.TEXT elif index_type == '2dsphere': index_type = pymongo.GEOSPHERE def do_index(): col.ensure_index([(index_name, index_type)], unique=index_unique, sparse=index_sparse) db_log('Enabling index of type', index_type, 'on', index_name, lvl=debug) try: do_index() i += 1 except pymongo.errors.OperationFailure: db_log(col.list_indexes().__dict__, pretty=True, lvl=verbose) if not index_reindex: db_log('Index was not created!', lvl=warn) i += 1 else: try: col.drop_index(index_name) do_index() i += 1 except pymongo.errors.OperationFailure as e: db_log('Index recreation problem:', exc=True, lvl=error) col.drop_indexes() i = 0 # for index in col.list_indexes(): # db_log("Index: ", index) return result
<SYSTEM_TASK:> Initializes the database connectivity, schemata and finally object models <END_TASK> <USER_TASK:> Description: 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 dbport global dbname global instance global initialized if initialized and not reload: hfoslog('Already initialized and not reloading.', lvl=warn, emitter="DB", frame_ref=2) return dbhost = address.split(':')[0] dbport = int(address.split(":")[1]) if ":" in address else 27017 dbname = database_name db_log("Using database:", dbname, '@', dbhost, ':', dbport) try: client = pymongo.MongoClient(host=dbhost, port=dbport) db = client[dbname] db_log("Database: ", db.command('buildinfo'), lvl=debug) except Exception as e: db_log("No database available! Check if you have mongodb > 3.0 " "installed and running as well as listening on port 27017 " "of localhost. (Error: %s) -> EXIT" % e, lvl=critical) sys.exit(5) warmongo.connect(database_name) schemastore = _build_schemastore_new() l10n_schemastore = _build_l10n_schemastore(schemastore) objectmodels = _build_model_factories(schemastore) collections = _build_collections(schemastore) instance = instance_name initialized = True
<SYSTEM_TASK:> Checks used filesystem storage sizes <END_TASK> <USER_TASK:> Description: 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: total_size = total_size + getsize(join(item[0], file)) except (OSError, PermissionError) as e: self.log("error with file: " + join(item[0], file), e) return total_size for name, checkpoint in self.config.locations.items(): try: stats = statvfs(checkpoint['location']) except (OSError, PermissionError) as e: self.log('Location unavailable:', name, e, type(e), lvl=error, exc=True) continue free_space = stats.f_frsize * stats.f_bavail used_space = get_folder_size( checkpoint['location'] ) / 1024.0 / 1024 self.log('Location %s uses %.2f MB' % (name, used_space)) if free_space < checkpoint['minimum']: self.log('Short of free space on %s: %.2f MB left' % ( name, free_space / 1024.0 / 1024 / 1024), lvl=warn)
<SYSTEM_TASK:> Worker task to send out an email, which blocks the process unless it is threaded <END_TASK> <USER_TASK:> Description: 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(config.mail_server, port=config.mail_server_port, timeout=30) if config.mail_tls: log += 'Starting TLS\n' server.starttls() if config.mail_username != '': log += 'Logging in with ' + str(config.mail_username) + "\n" server.login(config.mail_username, config.mail_password) else: log += 'No username, trying anonymous access\n' log += 'Sending Mail\n' response_send = server.send_message(mail) server.quit() except timeout as e: log += 'Could not send email to enrollee, mailserver timeout: ' + str(e) + "\n" return False, log, event log += 'Server response:' + str(response_send) return True, log, event
<SYSTEM_TASK:> Reload the current configuration and set up everything depending on it <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> An admin user requests a change to an enrolment <END_TASK> <USER_TASK:> Description: 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) return self.log('Changing status of an enrollment', uuid, 'to', status) enrollment = objectmodels['enrollment'].find_one({'uuid': uuid}) if enrollment is not None: self.log('Enrollment found', lvl=debug) else: return if status == 'Resend': enrollment.timestamp = std_now() enrollment.save() self._send_invitation(enrollment, event) reply = {True: 'Resent'} else: enrollment.status = status enrollment.save() reply = {True: enrollment.serializablefields()} if status == 'Accepted' and enrollment.method == 'Enrolled': self._create_user(enrollment.name, enrollment.password, enrollment.email, 'Invited', event.client.uuid) self._send_acceptance(enrollment, None, event) packet = { 'component': 'hfos.enrol.enrolmanager', 'action': 'change', 'data': reply } self.log('packet:', packet, lvl=verbose) self.fireEvent(send(event.client.uuid, packet)) self.log('Enrollment changed', lvl=debug)
<SYSTEM_TASK:> An enrolled user wants to change their password <END_TASK> <USER_TASK:> Description: 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}) if std_hash(old, self.salt) == user.passhash: user.passhash = std_hash(new, self.salt) user.save() packet = { 'component': 'hfos.enrol.enrolmanager', 'action': 'changepassword', 'data': True } self.fireEvent(send(event.client.uuid, packet)) self.log('Successfully changed password for user', uuid) else: packet = { 'component': 'hfos.enrol.enrolmanager', 'action': 'changepassword', 'data': False } self.fireEvent(send(event.client.uuid, packet)) self.log('User tried to change password without supplying old one', lvl=warn)
<SYSTEM_TASK:> A new user has been invited to enrol by an admin user <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> A user tries to self-enrol with the enrolment form <END_TASK> <USER_TASK:> Description: 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=True) # self.log(event.data, pretty=True) uuid = event.client.uuid if uuid in self.captchas and event.data.get('captcha', None) == self.captchas[uuid]['text']: self.log('Captcha solved!') else: self.log('Captcha failed!') self._fail(event, _('You did not solve the captcha correctly.', event)) self._generate_captcha(event) return mail = event.data.get('mail', None) if mail is None: self._fail(event, _('You have to supply all required fields.', event)) return elif not validate_email(mail): self._fail(event, _('The supplied email address seems invalid', event)) return if objectmodels['user'].count({'mail': mail}) > 0: self._fail(event, _('Your mail address cannot be used.', event)) return password = event.data.get('password', None) if password is None or len(password) < 5: self._fail(event, _('Your password is not long enough.', event)) return username = event.data.get('username', None) if username is None or len(username) < 1: self._fail(event, _('Your username is not long enough.', event)) return elif (objectmodels['user'].count({'name': username}) > 0) or \ (objectmodels['enrollment'].count({'name': username}) > 0): self._fail(event, _('The username you supplied is not available.', event)) return self.log('Provided data is good to enrol.') if self.config.no_verify: self._create_user(username, password, mail, 'Enrolled', uuid) else: self._invite(username, 'Enrolled', mail, uuid, event, password)
<SYSTEM_TASK:> An anonymous client wants to know if we're open for enrollment <END_TASK> <USER_TASK:> Description: 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 } self.fire(send(event.client.uuid, response))
<SYSTEM_TASK:> An anonymous client requests a password reset <END_TASK> <USER_TASK:> Description: 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 None and user_object.count({'mail': email}) > 0: email_user = user_object.find_one({'mail': email}) if email_user is None: self._fail(event, msg="Mail address unknown") return
<SYSTEM_TASK:> Delayed transmission of a requested captcha <END_TASK> <USER_TASK:> Description: 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-8') } self.fire(send(uuid, response))
<SYSTEM_TASK:> Actually invite a given user <END_TASK> <USER_TASK:> Description: 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, 'timestamp': std_now() } enrollment = objectmodels['enrollment'](props) enrollment.save() self.log('Enrollment stored', lvl=debug) self._send_invitation(enrollment, event) packet = { 'component': 'hfos.enrol.enrolmanager', 'action': 'invite', 'data': [True, email] } self.fireEvent(send(uuid, packet))
<SYSTEM_TASK:> Create a new user and all initial data <END_TASK> <USER_TASK:> Description: 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 roles = [] if ',' in config_role: for item in config_role.split(','): roles.append(item.lstrip().rstrip()) else: roles = [config_role] newuser = objectmodels['user']({ 'name': username, 'passhash': std_hash(password, self.salt), 'mail': mail, 'uuid': std_uuid(), 'roles': roles, 'created': std_now() }) if method == 'Invited': newuser.needs_password_change = True newuser.save() except Exception as e: self.log("Problem creating new user: ", type(e), e, lvl=error) return try: newprofile = objectmodels['profile']({ 'uuid': std_uuid(), 'owner': newuser.uuid }) self.log("New profile uuid: ", newprofile.uuid, lvl=verbose) newprofile.save() packet = { 'component': 'hfos.enrol.enrolmanager', 'action': 'enrol', 'data': [True, mail] } self.fireEvent(send(uuid, packet)) # TODO: Notify crew-admins except Exception as e: self.log("Problem creating new profile: ", type(e), e, lvl=error)
<SYSTEM_TASK:> Send an invitation mail to an open enrolment <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Send an acceptance mail to an open enrolment <END_TASK> <USER_TASK:> Description: 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 login!' acceptance_text = self.config.acceptance_mail + password_hint else: acceptance_text = self.config.acceptance_mail self._send_mail(self.config.acceptance_subject, acceptance_text, enrollment, event)
<SYSTEM_TASK:> Register event hook on reception of add_auth_hook-event <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Sends a failure message to the requesting client <END_TASK> <USER_TASK:> Description: 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] = event Timer(3, Event.create('notify_fail', event.clientuuid, notification, ip)).register(self)
<SYSTEM_TASK:> Automatic logins for client configurations that allow it <END_TASK> <USER_TASK:> Description: 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({ 'uuid': event.requestedclientuuid }) except Exception: client_config = None if client_config is None or client_config.autologin is False: self.log("Autologin failed:", event.requestedclientuuid, lvl=error) self._fail(event) return try: user_account = objectmodels['user'].find_one({ 'uuid': client_config.owner }) if user_account is None: raise AuthenticationError self.log("Autologin for", user_account.name, lvl=debug) except Exception as e: self.log("No user object due to error: ", e, type(e), lvl=error) self._fail(event) return if user_account.active is False: self.log("Account deactivated.") self._fail(event, 'Account deactivated.') return user_profile = self._get_profile(user_account) self._login(event, user_account, user_profile, client_config) self.log("Autologin successful!", lvl=warn)
<SYSTEM_TASK:> Called when a sensor sends a new raw data to this serial connector. <END_TASK> <USER_TASK:> Description: 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 multiple sentences 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 el else: # TODO: Make sure, this is not identical but new data self.log("Duplicate sentence received: ", el, lvl=debug) sentences = list(unique(sentences)) return sentences except Exception as e: self.log("Error during data unpacking: ", e, type(e), lvl=error, exc=True)
<SYSTEM_TASK:> Executes an external process via subprocess.Popen <END_TASK> <USER_TASK:> Description: 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) return e.output
<SYSTEM_TASK:> Securely and interactively ask for a password <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Obtain user credentials by arguments or asking the user <END_TASK> <USER_TASK:> Description: 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 systemconfig or it is without a salt! ' 'Reinstall the system provisioning with' 'hfos_manage.py install provisions -p system') sys.exit(3) if username is None: username = _ask("Please enter username: ") else: username = username if 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()
<SYSTEM_TASK:> Interactively ask the user for data <END_TASK> <USER_TASK:> Description: 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 == '': return default return data in ('Y', 'J', '1') elif data_type in ('str', 'unicode'): if show_hint: 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(data) return data
<SYSTEM_TASK:> Computes sinIm from modified apex latitude. <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Computes cosIm from modified apex latitude. <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Converts geocentric latitude to geodetic latitude using WGS84. <END_TASK> <USER_TASK:> Description: 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.deg2rad(gclat))/(WGS84_e2 - 1)))
<SYSTEM_TASK:> Finds subsolar geocentric latitude and longitude. <END_TASK> <USER_TASK:> Description: 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. (U.S. Government Printing Office, 1994). Usable for years 1601-2100, inclusive. According to the Almanac, results are good to at least 0.01 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 by A. D. Richmond, NCAR. Translated from IDL by K. Laundal. """
# 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)) nleap -= 99 if year <= 1900: ncent = int(np.floor((year - 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 + 365 * yr + nleap)) # 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 longitude: sslon = 180.0 - (ut / 240.0 + etdeg) # Earth rotates one degree every 240 s. nrot = round(sslon / 360.0) sslon = sslon - 360.0 * nrot return sslat, sslon
<SYSTEM_TASK:> Make the authentication headers needed to use the Appveyor API. <END_TASK> <USER_TASK:> Description: 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.token") as f: token = f.read().strip() headers = { 'Authorization': 'Bearer {}'.format(token), } return headers
<SYSTEM_TASK:> Get the details of the latest Appveyor build. <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Download a file from `url` to `filename`. <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Display a list of registered schemata <END_TASK> <USER_TASK:> Description: 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:', ",".join(sorted(configschemastore.keys())), pretty=True)
<SYSTEM_TASK:> List all available form definitions <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Show default permissions for all schemata <END_TASK> <USER_TASK:> Description: 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 perms == {}: self.log('Schema:', item, pretty=True) self.log( 'Schema:', key, 'read', perms['read']['default'], 'write', perms['write']['default'], 'list', perms['list']['default'], 'create', item['schema']['roles_create'] ) except KeyError as e: self.log('Fishy schema found:', key, e, lvl=error) self.log(item, pretty=True)
<SYSTEM_TASK:> Return all known schemata to the requesting client <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Return all configurable components' schemata <END_TASK> <USER_TASK:> Description: 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(event.client.uuid, response)) except Exception as e: self.log("ERROR:", e)
<SYSTEM_TASK:> Generates a regular expression controlled UUID field <END_TASK> <USER_TASK:> Description: 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': description, } if not display: uuid['x-schema-form'] = { 'condition': "false" } if default is not None: uuid['default'] = default return uuid
<SYSTEM_TASK:> Generates a basic object with RBAC properties <END_TASK> <USER_TASK:> Description: 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_perms: if all_roles: roles_create = ['admin', all_roles] roles_write = ['admin', all_roles] roles_read = ['admin', all_roles] roles_list = ['admin', all_roles] else: if roles_write is None: roles_write = ['admin'] if roles_read is 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 isinstance(roles_list, str): roles_list = [roles_list] if has_owner: roles_write.append('owner') roles_read.append('owner') roles_list.append('owner') base_schema['roles_create'] = roles_create base_schema['properties'].update({ 'perms': { 'id': '#perms', 'type': 'object', 'name': 'perms', 'properties': { 'write': { 'type': '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': 'string', 'description': 'Name of ' + name } }) if has_owner: # TODO: Schema should allow specification of non-local 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: Using this causes all sorts of (obvious) problems with the object # manager if has_uuid: base_schema['properties'].update({ 'uuid': uuid_object(title='Unique ' + name + ' ID', display=False) }) base_schema['required'] = ["uuid"] return base_schema
<SYSTEM_TASK:> Generates a new reference frame from incoming sensordata <END_TASK> <USER_TASK:> Description: 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 exactly # should they be handled? 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 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:", self.subscriptions, ref.name) if ref.name in self.subscriptions: packet = { 'component': 'hfos.navdata.sensors', 'action': 'update', 'data': item } self.log("Serving update: ", packet, lvl=verbose) for uuid in self.subscriptions[ref.name]: self.log("Serving to ", 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.timestamp = timestamp else: self.log("Unknown sensor data received!", data, lvl=warn)
<SYSTEM_TASK:> Export stored objects <END_TASK> <USER_TASK:> Description: 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, export_format, filename, pretty, all_schemata, omit)
<SYSTEM_TASK:> Import objects from file <END_TASK> <USER_TASK:> Description: 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 open(filename, 'r') as f: json_data = f.read() data = json.loads(json_data) # , parse_float=True, parse_int=True) if schema is None: if all_schemata is False: log('No 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: for item in objects: if item['uuid'] == uuid: items = [model(item)] else: items = [] for item in objects: thing = model(item) items.append(thing) schema_total = 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', schema_name) for item in item_list: item._fields['_id'] = bson.objectid.ObjectId(item._fields['_id']) item.save()
<SYSTEM_TASK:> Checks if the newly created object is a wikipage.. <END_TASK> <USER_TASK:> Description: 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(e), lvl=error)
<SYSTEM_TASK:> Bootstrap basics, assemble graph and hand over control to the Core <END_TASK> <USER_TASK:> Description: 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_logfile(args['logfilepath'], args['instance']) if args['livelog'] is True: from hfos import logger logger.live = True hfoslog("Running with Python", sys.version.replace("\n", ""), sys.platform, lvl=debug, emitter='CORE') hfoslog("Interpreter executable:", sys.executable, emitter='CORE') if args['cert'] is not None: 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
<SYSTEM_TASK:> All components have initialized, set up the component <END_TASK> <USER_TASK:> Description: 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.fireEvent(cli_register_event('components', cli_components)) self.fireEvent(cli_register_event('drop_privileges', cli_drop_privileges)) self.fireEvent(cli_register_event('reload_db', cli_reload_db)) self.fireEvent(cli_register_event('reload', cli_reload)) self.fireEvent(cli_register_event('quit', cli_quit)) self.fireEvent(cli_register_event('info', cli_info))
<SYSTEM_TASK:> Event hook to trigger a new frontend build <END_TASK> <USER_TASK:> Description: 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 )
<SYSTEM_TASK:> Experimental call to reload the component tree <END_TASK> <USER_TASK:> Description: 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())
<SYSTEM_TASK:> Provides information about the running instance <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Check all known entry points for components. If necessary, <END_TASK> <USER_TASK:> Description: 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 the # component frontend bits. self.log("Updating components") components = {} if True: # try: from pkg_resources import iter_entry_points entry_point_tuple = ( 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.log("Entry point: ", entry_point, name, entry_point.resolve(), lvl=verbose) self.log("Loaded: ", loaded, lvl=verbose) comp = { 'package': entry_point.dist.project_name, 'location': location, 'version': str(entry_point.dist.parsed_version), 'description': loaded.__doc__ } components[name] = comp self.loadable_components[name] = loaded self.log("Loaded component:", comp, lvl=verbose) except Exception as e: self.log("Could not 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'][ # 'settings'][ # 'oneOf'].append(configobject) # except (KeyError, AttributeError) as e: # self.log('Problematic configuration # properties in ' # 'component ', name, exc=True) # # schemastore['component'] = ComponentBaseConfigSchema # except 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 component configuration differs:", diff, lvl=debug) self.log(self.config.components, components, lvl=verbose) self.config.components = components else: self.log("No component configuration change. Proceeding.") if forcereload: self.log("Restarting all components.", lvl=warn) self._instantiate_components(clear=True)
<SYSTEM_TASK:> Check if it is enabled and start the frontend http & websocket <END_TASK> <USER_TASK:> Description: 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.static = Static("/", docroot=self.frontendtarget).register( self) self.websocket = WebSocketsDispatcher("/websocket").register(self) self.frontendrunning = True
<SYSTEM_TASK:> Inspect all loadable components and run them <END_TASK> <USER_TASK:> Description: 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=True) kill(comp) # removables = deepcopy(list(self.runningcomponents.keys())) # # for key in removables: # comp = self.runningcomponents[key] # self.log(comp) # comp.unregister() # comp.stop() # self.runningcomponents.pop(key) # # objgraph.show_backrefs([comp], # max_depth=5, # 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(self.loadable_components.keys()).difference( self.component_blacklist) self.log('Starting components: ', sorted(running)) for name, componentdata in self.loadable_components.items(): if name in self.component_blacklist: continue self.log("Running component: ", name, lvl=verbose) try: if name in self.runningcomponents: self.log("Component already 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)
<SYSTEM_TASK:> Internal method to create a normal user <END_TASK> <USER_TASK:> Description: 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()), 'created': std_now() }) new_user.name = username new_user.passhash = passhash return new_user
<SYSTEM_TASK:> Creates a new local user and assigns admin role <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Change password of an existing user <END_TASK> <USER_TASK:> Description: 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.passhash = passhash change_user.save() log("Done")
<SYSTEM_TASK:> List all locally known users <END_TASK> <USER_TASK:> Description: 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_user.uuid, end=' ' if active else '\n') if active: print(found_user.active) log("Done")
<SYSTEM_TASK:> Disable an existing user <END_TASK> <USER_TASK:> Description: 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')
<SYSTEM_TASK:> Enable an existing user <END_TASK> <USER_TASK:> Description: 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')
<SYSTEM_TASK:> Grant a role to an existing user <END_TASK> <USER_TASK:> Description: 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_user.roles: change_user.roles.append(role) change_user.save() log('Done') else: log('User already has that role!', lvl=warn)
<SYSTEM_TASK:> Assemble a list of future alerts <END_TASK> <USER_TASK:> Description: 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')
<SYSTEM_TASK:> Render a given pystache template <END_TASK> <USER_TASK:> Description: 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) return result
<SYSTEM_TASK:> Render a given pystache template file with given content <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Write a new file from a given pystache template file and content <END_TASK> <USER_TASK:> Description: 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') f.write(line)
<SYSTEM_TASK:> Adds a role to an action on objects <END_TASK> <USER_TASK:> Description: 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 in item.perms[action]: item.perms[action].append(role) item.save() log("Done")
<SYSTEM_TASK:> Deletes a role from an action on objects <END_TASK> <USER_TASK:> Description: def del_action_role(ctx): """Deletes a role from an action on objects"""
objects = ctx.obj['objects'] action = ctx.obj['action'] role = ctx.obj['role'] if action is None or role is None: log('You need to specify an action or role to the RBAC command group for this to work.', lvl=warn) return for item in objects: if role in item.perms[action]: item.perms[action].remove(role) item.save() log("Done")
<SYSTEM_TASK:> Changes the ownership of objects <END_TASK> <USER_TASK:> Description: def change_owner(ctx, owner, uuid): """Changes the ownership of objects"""
objects = ctx.obj['objects'] database = ctx.obj['db'] if uuid is True: owner_filter = {'uuid': owner} else: owner_filter = {'name': owner} owner = database.objectmodels['user'].find_one(owner_filter) if owner is None: log('User unknown.', lvl=error) return for item in objects: item.owner = owner.uuid item.save() log('Done')
<SYSTEM_TASK:> Processes configuration list requests <END_TASK> <USER_TASK:> Description: def getlist(self, event): """Processes configuration list requests :param 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 without component class encountered:', lvl=warn) self.log(comp.serializablefields(), pretty=True, lvl=warn) data = sorted(data, key=lambda x: x['name']) response = { 'component': 'hfos.ui.configurator', 'action': 'getlist', 'data': data } self.fireEvent(send(event.client.uuid, response)) return except Exception as e: self.log("List error: ", e, type(e), lvl=error, exc=True)
<SYSTEM_TASK:> Records a single snapshot <END_TASK> <USER_TASK:> Description: def rec(self): """Records a single snapshot"""
try: self._snapshot() except Exception as e: self.log("Timer error: ", e, type(e), lvl=error)
<SYSTEM_TASK:> Toggles the camera system recording state <END_TASK> <USER_TASK:> Description: def _toggle_filming(self): """Toggles the camera system recording state"""
if self._filming: self.log("Stopping operation") self._filming = False self.timer.stop() else: self.log("Starting operation") self._filming = True self.timer.start()
<SYSTEM_TASK:> A client has disconnected, update possible subscriptions accordingly. <END_TASK> <USER_TASK:> Description: def client_disconnect(self, event): """ A client has disconnected, update possible subscriptions accordingly. :param event: """
self.log("Removing disconnected client from subscriptions", lvl=debug) client_uuid = event.clientuuid self._unsubscribe(client_uuid)