text
stringlengths
81
112k
Get equivalent units that are compatible with the udunits2 library (thus CF-compliant). Parameters ---------- units : string A string representation of the units. prefix : string Will be added at the beginning of the returned string (must be a valid udunits2 expression). ...
Replace characters (e.g., ':', '$', '=', '-') of a variable name, which may cause problems when using with (CF-)netCDF based packages. Parameters ---------- varname : string variable name. Notes ----- Characters replacement is based on the table stored in :attr:`VARNAME_MAP_CHA...
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 v...
Returns all entries, which publication date has been hit or which have no date and which language matches the current language. def published(self, check_language=True, language=None, kwargs=None, exclude_kwargs=None): """ Returns all entries, which publication date has been h...
Returns recently published new entries. 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 = {} ...
Returns the meta description for the given entry. 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 =...
DEPRECATED: Template tag to render a placeholder from an NewsEntry object We don't need this any more because we don't have a placeholders M2M field on the model any more. Just use the default ``render_placeholder`` tag. def render_news_placeholder(context, obj, name=False, truncate=False): # pragma: nocover...
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. def _requirement_filter_by_marker(req): # type: (pkg_resources.Requi...
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.Requirem...
Cleanup a list of requirement strings (e.g. from requirements.txt) to only contain entries valid for this platform and with the lowest required version only. Example ------- >>> from sys import version_info >>> _requirements_sanitize([ ... 'foo>=3.0', ... "monotonic>=1.0,>0.1;p...
Return a coroutine function. func: either a coroutine function or a regular function Note a coroutine function is not a coroutine! 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 cor...
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). def location(self): """Return a string uniquely identifying the event. ...
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'. async def find_backwards(self, stream_name, predicate, predicate_label='predicate'): """Return first event matching predicate,...
Command line interface for the ``qpass`` program. 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=[]) sh...
Edit the matching entry. def edit_matching_entry(program, arguments): """Edit the matching entry.""" entry = program.select_entry(*arguments) entry.context.execute("pass", "edit", entry.name)
List the entries matching the given keywords/patterns. def list_matching_entries(program, arguments): """List the entries matching the given keywords/patterns.""" output("\n".join(entry.name for entry in program.smart_search(*arguments)))
Show the matching entry on the terminal (and copy the password to the clipboard). def show_matching_entry(program, arguments, use_clipboard=True, quiet=False, filters=()): """Show the matching entry on the terminal (and copy the password to the clipboard).""" entry = program.select_entry(*arguments) if not...
Parses a set of Payflow Pro response parameter name and value pairs into a list of PayflowProObjects, and returns a tuple containing the object list and a dictionary containing any unconsumed data. The first item in the object list will always be the Response object, and the RecurringPayments obj...
Convert 'items' stored in 'canvas' to SVG 'document'. If 'items' is None, then all items are convered. tounicode is a function that get text and returns it's unicode representation. It should be used when national characters are used on canvas. Return list of XML elements def convert(document, canvas, items=Non...
Create default SVG document def SVGdocument(): "Create default SVG document" import xml.dom.minidom implementation = xml.dom.minidom.getDOMImplementation() doctype = implementation.createDocumentType( "svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" ) document= implementa...
polyline with 2 vertices using <line> tag def segment_to_line(document, coords): "polyline with 2 vertices using <line> tag" return setattribs( document.createElement('line'), x1 = coords[0], y1 = coords[1], x2 = coords[2], y2 = coords[3], )
polyline with more then 2 vertices def polyline(document, coords): "polyline with more then 2 vertices" points = [] for i in range(0, len(coords), 2): points.append("%s,%s" % (coords[i], coords[i+1])) return setattribs( document.createElement('polyline'), points = ' '.join(points), )
smoothed polyline def smoothline(document, coords): "smoothed polyline" element = document.createElement('path') path = [] points = [(coords[i], coords[i+1]) for i in range(0, len(coords), 2)] def pt(points): x0, y0 = points[0] x1, y1 = points[1] p0 = (2*x0-x1, 2*y0-y1) x0, y0 = points[-1] x1...
cubic bezier polyline def cubic_bezier(document, coords): "cubic bezier polyline" element = document.createElement('path') points = [(coords[i], coords[i+1]) for i in range(0, len(coords), 2)] path = ["M%s %s" %points[0]] for n in xrange(1, len(points), 3): A, B, C = points[n:n+3] path.append("C%s,%s %s,...
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...
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 = (...
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(sta...
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 retur...
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: ...
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 ...
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). ...
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). Retur...
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 sp...
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 ------...
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 exi...
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 def _augment_book(self, uuid, event): """ Checks if the newly created object is a book ...
Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system Courtesy: Thomas ( http://stackoverflow.com/questions/12090503 /listing-available-com-ports-with-python ) def seri...
Initiates communication with the remote controlled device. :param args: 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'...
Sets a new machine speed. :param event: 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. :param event: 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. :param event: 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.con...
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 i...
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 ] ...
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...
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') compo...
[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(Compo...
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'...
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 a...
>>> 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 ((s...
>>> 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_ov...
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) ...
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 ``...
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....
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""" ...
[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 Tru...
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...
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({'na...
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): ...
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 = objec...
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 = e...
Chat event handler for incoming events :param event: say-event with incoming chat message def say(self, event): """Chat event handler for incoming events :param event: say-event with incoming chat message """ try: userid = event.user.uuid recipient = sel...
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") ...
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 ...
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['g...
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', ...
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 ...
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) host...
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 FileExistsE...
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, ...
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 servic...
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.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']...
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 ...
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)") ...
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: ...
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 = N...
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 g...
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...
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 file...
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] =...
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 it...
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, por...
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._set...
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 ...
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 = o...
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._i...
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 t...
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...
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...
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) ...
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': b64en...
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, 'pas...
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 = se...