code
stringlengths
1
18.2k
# get item coords coords = canvas.coords(item) # get item options; # options is a dict: opt. name -> opt. actual value tmp = canvas.itemconfigure(item) options = dict((v0, v4) for v0, v1, v2, v3, v4 in tmp.values()) # get state of item state = options['state'] if 'current' in options['tags']: options['state'] = ACTIVE ...
assert options['state'] in ['normal', DISABLED, 'hidden'] # skip hidden items if options['state'] == 'hidden': continue def get(name, default=""): if state == ACTIVE and options.get(state + name): return options.get(state + name) if state == DISABLED and options.get(state + name): return options.get(state + name) if op...
== 'arc' and options['style'] == ARC: options['fill'] = '' options['activefill'] = '' options['disabledfill'] = '' style = {} style["stroke"] = HTMLcolor(canvas, get("outline")) if get("fill"): style["fill"] = HTMLcolor(canvas, get("fill")) else: style["fill"] = "none" width = float(options['width']) if state == ACTIVE...
the exception in course of processing of such item. # Default value is 0. Hence, it shall not affect width. pass else: if float(disabledwidth) > 0: width = disabledwidth if width != 1.0: style['stroke-width'] = width if width: dash = canvas.itemcget(item, 'dash') if state == DISABLED and canvas.itemcget(item, 'disabled...
if dash != '': try: dash = tuple(map(int, dash.split())) except ValueError: # int can't parse literal, dash defined with -.,_ linewidth = float(get('width')) dash = parse_dash(dash, linewidth) style['stroke-dasharray'] = ",".join(map(str, dash)) style['stroke-dashoffset'] = options['dashoffset'] if itemtype == 'line': ...
smoothline(document, coords) elif options['smooth'] == 'raw': element = cubic_bezier(document, coords) elif options['smooth'] == '0': if len(coords) == 4: # segment element = segment(document, coords) else: # polyline element = polyline(document, coords) style['fill'] = "none" style['stroke-linejoin'] = join_style[opti...
coords[3], coords[0], coords[1], options['arrowshape']) arrow.setAttribute('fill', style['stroke']) elements.append(arrow) if options['arrow'] in [LAST, BOTH]: arrow = arrow_head(document, coords[-4], coords[-3], coords[-2], coords[-1], options['arrowshape']) arrow.setAttribute('fill', style['stroke']) elements.append(...
style['stroke-linejoin'] = join_style[options['joinstyle']] elif itemtype == 'oval': element = oval(document, coords) elements.append(element) elif itemtype == 'rectangle': element = rectangle(document, coords) elements.append(element) elif itemtype == 'arc': element = arc(document, coords, options['start'], options['e...
y at 'dominant-baseline' y = ymin + font_metrics(tk, options['font'], 'ascent') element = setattribs( document.createElement('text'), x = x, y = y ) elements.append(element) element.appendChild(document.createTextNode( tounicode(canvas.itemcget(item, 'text')) )) # 2. Setup style actual = font_actual(tk, options['font']...
size in pixels style['font-size'] = "%s" % (-size) style['font-style'] = font_style[actual['slant']] style['font-weight'] = font_weight[actual['weight']] # overstrike/underline if actual['overstrike'] and actual['underline']: style['text-decoration'] = 'underline line-through' elif actual['overstrike']: style['text-dec...
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= implementation.createDocument(None, "svg", doctype...
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], )
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), )
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, y1 = points[-2] pn = (2*x0-x1, 2*y0-y1) p =...
p[i] c = p[i+1] yield lerp(a, b, 0.5), b, lerp(b, c, 0.5) for i, (A, B, C) in enumerate(pt(points)): if i == 0: path.append("M%s,%s Q%s,%s %s,%s" % (A[0], A[1], B[0], B[1], C[0], C[1])) else: path.append("T%s,%s" % (C[0], C[1])) element.setAttribute('d', ' '.join(path)) return element
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,%s %s,%s" % (A[0], A[1], B[0], B[1], ...
def smoothpolygon(document, coords): "smoothed filled polygon" element = document.createElement('path') path = [] points = [(coords[i], coords[i+1]) for i in range(0, len(coords), 2)] def pt(points): p = points n = len(points) for i in range(0, len(points)): a = p[(i-1) % n] b = p[i] c = p[(i+1) % n] yield lerp(a, b, 0...
i == 0: path.append("M%s,%s Q%s,%s %s,%s" % (A[0], A[1], B[0], B[1], C[0], C[1])) else: path.append("T%s,%s" % (C[0], C[1])) path.append("z") element.setAttribute('d', ' '.join(path)) return element
def oval(document, coords): "circle/ellipse" x1, y1, x2, y2 = coords # circle if x2-x1 == y2-y1: return setattribs(document.createElement('circle'), cx = (x1+x2)/2, cy = (y1+y2)/2, r = abs(x2-x1)/2, ) # ellipse else: return setattribs(document.createElement('ellipse'), cx = (x1+x2)/2, cy = (y1+y2)/2, rx = abs(x2-x1)/2,...
def arc(document, bounding_rect, start, extent, style): "arc, pieslice (filled), arc with chord (filled)" (x1, y1, x2, y2) = bounding_rect import math cx = (x1 + x2)/2.0 cy = (y1 + y2)/2.0 rx = (x2 - x1)/2.0 ry = (y2 - y1)/2.0 start = math.radians(float(start)) extent = math.radians(float(extent)) # from SVG spec: # ht...
math.sin(start) + cy # XXX: ry is negated here x2 = rx * math.cos(start + extent) + cx y2 = -ry * math.sin(start + extent) + cy # XXX: ry is negated here if abs(extent) > math.pi: fa = 1 else: fa = 0 if extent > 0.0: fs = 0 else: fs = 1 path = [] # common: arc path.append('M%s,%s' % (x1,
y1)) path.append('A%s,%s 0 %d %d %s,%s' % (rx, ry, fa, fs, x2, y2)) if style == ARC: pass elif style == CHORD: path.append('z') else: # default: pieslice path.append('L%s,%s' % (cx, cy)) path.append('z') return setattribs(document.createElement('path'), d = ''.join(path))
def HTMLcolor(canvas, color): "returns Tk color in form '#rrggbb' or '#rgb'" if color: # r, g, b \in [0..2**16] r, g, b = ["%02x" % (c // 256) for c in canvas.winfo_rgb(color)] if (r[0] == r[1]) and (g[0] == g[1]) and (b[0] == b[1]): # shorter form #rgb return "#" + r[0] + g[0] + b[0] else: return "#" + r + g +
b else: return color
def arrow_head(document, x0, y0, x1, y1, arrowshape): "make arrow head at (x1,y1), arrowshape is tuple (d1, d2, d3)" import math dx = x1 - x0 dy = y1 - y0 poly = document.createElement('polygon') d = math.sqrt(dx*dx + dy*dy) if d == 0.0: # XXX: equal, no "close enough" return poly try: d1, d2, d3 = list(map(float, arro...
arrowshape.split()) P0 = (x0, y0) P1 = (x1, y1) xa, ya = lerp(P1, P0, d1/d) xb, yb = lerp(P1, P0, d2/d) t = d3/d xc, yc = dx*t, dy*t points = [ x1, y1, xb - yc, yb + xc, xa, ya, xb + yc, yb - xc, ] poly.setAttribute('points', ' '.join(map(str, points))) return poly
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) )
def parse_dash(string, width): "parse dash pattern specified with string" # DashConvert from {tk-sources}/generic/tkCanvUtil.c w = max(1, int(width + 0.5)) n = len(string) result = [] for i, c in enumerate(string): if c == " " and len(result): result[-1] += w + 1 elif c == "_": result.append(8*w) result.append(4*w) eli...
result.append(2*w) result.append(4*w) return result
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 polynomia...
: 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 v...
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)
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 polyno...
: 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 va...
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)
def _find_references(model_name, references=None): """ Iterate over model references for `model_name` and return a list of parent model specifications (including those of `model_name`, ordered from parent to child). """ references = references or [] references.append(model_name) ref = MODELS[model_name].get('reference'...
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 mod...
""" # 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...
_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...
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 provid...
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 f...
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 " "func...
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 = map...
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...
notification error: ", uuid, e, type(e), lvl=error, exc=True)
def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system Courtesy: Thomas ( http://stackoverflow.com/questions/12090503 /listing-available-com-ports-with-python ) """ if sys.platform.startswith('win'): port...
else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result
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_ser...
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)
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)
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)
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: Cl...
= 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 ...
(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 = object...
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 = datab...
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...
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...
def DefaultExtension(schema_obj, form_obj, schemata=None): """Create a default field""" if schemata is None: schemata = ['systemconfig', 'profile', 'client'] DefaultExtends = { 'schema': { "properties/modules": [ schema_obj ] }, 'form': { 'modules': { 'items/': form_obj } } } output = {} for schema in schemata: output[...
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_fi...
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,...
def install_frontend(instance='default', forcereload=False, forcerebuild=False, forcecopy=True, install=True, development=False, build_type='dist'): """Builds and installs the frontend""" hfoslog("Updating frontend components", emitter='BUILDER') components = {} loadable_components = {} # TODO: Fix this up, it is proba...
hfoslog("Running", cmdline, lvl=verbose, emitter='BUILDER') npminstall = Popen(cmdline, cwd=frontendroot) out, err = npminstall.communicate() npminstall.wait() hfoslog("Frontend dependency installing done: ", out, err, lvl=debug, emitter='BUILDER') if True: # try: from pkg_resources import iter_entry_points entry_point...
lvl=debug, emitter='BUILDER') component_name = entry_point.resolve().__module__.split('.')[1] hfoslog("Loaded: ", loaded, lvl=verbose, emitter='BUILDER') comp = { 'location': location, 'version': str(entry_point.dist.parsed_version), 'description': loaded.__doc__ } frontend = os.path.join(location, 'frontend') hfoslog(...
as e: hfoslog("Could not inspect entrypoint: ", e, type(e), entry_point, iterator, lvl=error, exc=True, emitter='BUILDER') # except Exception as e: # hfoslog("Error: ", e, type(e), lvl=error, exc=True, emitter='BUILDER') # return hfoslog('Components after lookup:', sorted(list(components.keys())), emitter='BUILDER') de...
os.path.join(frontendroot, 'src', 'components', name) target = os.path.normpath(target) if install: reqfile = os.path.join(origin, 'requirements.txt') if os.path.exists(reqfile): # TODO: Speed this up by collecting deps first then doing one single install call hfoslog("Installing package dependencies", lvl=debug, emitt...
installing done: ", out, err, lvl=debug, emitter='BUILDER') # if target in ('/', '/boot', '/usr', '/home', '/root', # '/var'): # hfoslog("Unsafe frontend deletion target path, " # "NOT proceeding! ", target, lvl=critical, # emitter='BUILDER') hfoslog("Copying:", origin, target, lvl=debug, emitter='BUILDER') copytree(or...
modules: importlines += line modules.append(modulename) else: hfoslog("Module without frontend:", name, component, lvl=debug, emitter='BUILDER') with open(os.path.join(frontendroot, 'src', 'main.tpl.js'), "r") as f: main = "".join(f.readlines()) parts = main.split("/* COMPONENT SECTION */") if len(parts) != 3: hfoslog(...
f.write(parts[2]) except Exception as e: hfoslog("Error during frontend package info writing. Check " "permissions! ", e, lvl=error, emitter='BUILDER') def _rebuild_frontend(): hfoslog("Starting frontend build.", lvl=warn, emitter='BUILDER') npmbuild = Popen(["npm", "run", build_type], cwd=frontendroot) out, err = npmb...
'assets'), os.path.join(frontendtarget, 'assets'), hardlink=False) hfoslog("Frontend deployed", emitter='BUILDER') hfoslog("Checking component frontend bits in ", frontendroot, lvl=verbose, emitter='BUILDER') _update_frontends(install=install) if forcerebuild: _rebuild_frontend() hfoslog("Done: Install Frontend", emitt...
def config(ctx): """[GROUP] Configuration management operations""" from hfos import database database.initialize(ctx.obj['dbhost'], ctx.obj['dbname']) from hfos.schemata.component import ComponentConfigSchemaTemplate ctx.obj['col'] = model_factory(ComponentConfigSchemaTemplate)
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. G...
None: configuration = col.find_one({'uuid': componentname}) if configuration is None: log('Component configuration not found:', componentname, emitter='MANAGE') return configuration.delete() log('Done')
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_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))
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]
def overlapping(start1, end1, start2, end2): """ >>> overlapping(0, 5, 6, 7) False >>> overlapping(1, 2, 0, 4) True >>> overlapping(5,6,0,5) False """ return not ((start1 <= start2 and start1 <= end2 and end1 <= end2 and end1 <= start2) or (start1 >= start2 and start1 >= end2 and end1 >= end2 and end1 >= start2))
def remove_lower_overlapping(current, higher): """ >>> remove_lower_overlapping([], [('a', 0, 5)]) [('a', 0, 5)] >>> remove_lower_overlapping([('z', 0, 4)], [('a', 0, 5)]) [('a', 0, 5)] >>> remove_lower_overlapping([('z', 5, 6)], [('a', 0, 5)]) [('z', 5, 6), ('a', 0, 5)] """ for (match, h_start, h_end) in higher: overl...
h_start, h_end)) else: current.append((match, h_start, h_end)) return current
def debugrequest(self, event): """Handler for client-side debug requests""" try: self.log("Event: ", event.__dict__, lvl=critical) if event.data == "storejson": self.log("Storing received object to /tmp", lvl=critical) fp = open('/tmp/hfosdebugger_' + str( event.user.useruuid) + "_" + str(uuid4()), "w") json.dump(event...
== "exception": class TestException(BaseException): """Generic exception to test exception monitoring""" pass raise TestException if event.data == "heap": self.log("Heap log:", self.heapy.heap(), lvl=critical) if event.data == "buildfrontend": self.log("Sending frontend build command") self.fireEvent(frontendbuildreque...
def stdin_read(self, data): """read Event (on channel ``stdin``) This is the event handler for ``read`` events specifically from the ``stdin`` channel. This is triggered each time stdin has data that it has read. """ data = data.strip().decode("utf-8") self.log("Incoming:", data, lvl=verbose) if len(data) == 0: self.lo...
[] if ' ' in cmd: cmd, args = cmd.split(' ', maxsplit=1) args = args.split(' ') if cmd in self.hooks: self.log('Firing hooked event:', cmd, args, lvl=debug) self.fireEvent(self.hooks[cmd](*args)) # TODO: Move these out, so we get a simple logic here elif cmd == 'frontend': self.log("Sending %s frontend rebuild event" %...
elif cmd == 'backend': self.log("Sending backend reload event") self.fireEvent(componentupdaterequest(force=False), "setup") else: self.log('Unknown Command:', cmd, '. Use /help to get a list of enabled ' 'cli hooks')
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
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 p...
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 # w...
def db(ctx): """[GROUP] Database management operations""" from hfos import database database.initialize(ctx.obj['dbhost'], ctx.obj['dbname']) ctx.obj['db'] = database
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=...
else: log("Done")
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 S...
def ICALImporter(ctx, filename, all, owner, calendar, create_calendar, clear_calendar, dry, execfilter): """Calendar Importer for iCal (ics) files """ log('iCal importer running') objectmodels = ctx.obj['db'].objectmodels if objectmodels['user'].count({'name': owner}) > 0: owner_object = objectmodels['user'].find_one({...
owner}) > 0: calendar = objectmodels['calendar'].find_one({'uuid': calendar}) elif create_calendar: calendar = objectmodels['calendar']({ 'uuid': std_uuid(), 'name': calendar }) else: log('Calendar unknown and no --create-calendar specified. Specify either uuid or name of an existing calendar.', lvl=warn) return log('F...
'dt', 'description': 'str', 'dtstart': 'dt', 'dtend': 'dt', 'timestamp': 'dt', 'modified': 'dt', 'location': 'str', 'status': 'str', 'summary': 'str', 'uid': 'str' } mapping = { 'description': 'summary', 'summary': 'name' } imports = [] def ical_import_filter(original, logfacilty): log('Passthrough filter') return orig...
event in caldata.walk(): if event.name == 'VEVENT': log(event, lvl=verbose, pretty=True) initializer = { 'uuid': std_uuid(), 'calendar': calendar.uuid, } for item in keys: thing = event.get(item, None) if thing is None: thing = 'NO-' + item else: if keys[item] == 'str': thing = str(thing) else: thing = parser.parse(str...
new_event = objectmodels['event'](initializer) new_event = ical_import_filter(new_event, log) imports.append(new_event) log(new_event, lvl=debug) for ev in imports: log(ev.summary) if not dry: log('Bulk creating events') objectmodels['event'].bulk_create(imports) calendar.save() else: log('Dry run - nothing stored.', l...
def make_migrations(schema=None): """Create migration data for a specified schema""" entrypoints = {} old = {} def apply_migrations(migrations, new_model): """Apply migration data to compile an up to date model""" def get_path(raw_path): """Get local path of schema definition""" print("RAW PATH:", raw_path, type(raw_pa...
ValueError: pass path.append(item) path.remove('root') print("PATH:", path) return path def apply_entry(changetype, change, result): """Upgrade with a single migration""" def apply_removes(removes, result): """Delete removed fields""" for remove in removes: path = get_path(remove) amount = dpath.util.delete(result, pat...
return result if changetype == 'type_changes': hfoslog('Creating new object') result = change['root']['new_value'] return result if changetype == 'dictionary_item_added': hfoslog('Adding items') result = apply_additions(change, result) elif changetype == 'dictionary_item_removed': hfoslog('Removing items') result = app...
path, change[item][ 'new_value']) assert amount == 1 return result def get_renames(migrations): """Check migrations for renamed fields""" hfoslog('Checking for rename operations:') pprint(migrations) for entry in migrations: added = entry.get('dictionary_item_added', None) removed = entry.get('dictionary_item_removed',...
renames.append((removed_path, path)) return renames result = {} for no, migration in enumerate(migrations): hfoslog('Migrating', no) hfoslog('Migration:', migration, lvl=debug) renamed = get_renames(migrations) for entry in migration: result = apply_entry(entry, migration[entry], result) pprint(result) return result de...