INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Make the authentication headers needed to use the Appveyor API. | 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.c... |
Get the details of the latest Appveyor build. | 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() |
Download a file from url to filename. | 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):
... |
Display a list of registered schemata | 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:
... |
Display a schemata s form definition | def cli_form(self, *args):
"""Display a schemata's form definition"""
if args[0] == '*':
for schema in schemastore:
self.log(schema, ':', schemastore[schema]['form'], pretty=True)
else:
self.log(schemastore[args[0]]['form'], pretty=True) |
Display a single schema definition | def cli_schema(self, *args):
"""Display a single schema definition"""
key = None
if len(args) > 1:
key = args[1]
args = list(args)
if '-config' in args or '-c' in args:
store = configschemastore
try:
args.remove('-c')
... |
List all available form definitions | 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)
... |
Show default permissions for all schemata | 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... |
Sets up the application after startup. | def ready(self):
"""Sets up the application after startup."""
self.log('Got', len(schemastore), 'data and',
len(configschemastore), 'component schemata.', lvl=debug) |
Return all known schemata to the requesting client | 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_schemas... |
Return a single schema | def get(self, event):
"""Return a single schema"""
self.log("Schemarequest for", event.data, "from",
event.user, lvl=debug)
if event.data in schemastore:
response = {
'component': 'hfos.events.schemamanager',
'action': 'get',
... |
Return all configurable components schemata | 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',
... |
Generates a regular expression controlled UUID field | 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}$',
... |
Generates a basic object with RBAC properties | 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):
... |
Lists serial port names | def serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
Courtesy: Thomas ( http://stackoverflow.com/questions/12090503
/listing-available-com-p... |
Generates a new reference frame from incoming sensordata | 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
# b... |
Pushes the current: referenceframe: out to clients. | def navdatapush(self):
"""
Pushes the current :referenceframe: out to clients.
:return:
"""
try:
self.fireEvent(referenceframe({
'data': self.referenceframe, 'ages': self.referenceages
}), "navdata")
self.intervalcount += 1
... |
Export stored objects | 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, uu... |
Import objects from file | 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_form... |
Checks if the newly created object is a wikipage.. If so rerenders the automatic index. | 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()
... |
Attempt to drop privileges and change user to hfos user/ group | def drop_privileges(uid_name='hfos', gid_name='hfos'):
"""Attempt to drop privileges and change user to 'hfos' user/group"""
if os.getuid() != 0:
hfoslog("Not root, cannot drop privileges", lvl=warn, emitter='CORE')
return
try:
# Get the uid/gid from the name
running_uid = ... |
Preliminary HFOS application Launcher | def construct_graph(args):
"""Preliminary HFOS application Launcher"""
app = Core(args)
setup_root(app)
if args['debug']:
from circuits import Debugger
hfoslog("Starting circuits debugger", lvl=warn, emitter='GRAPH')
dbg = Debugger().register(app)
# TODO: Make these co... |
Bootstrap basics assemble graph and hand over control to the Core component | 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['do... |
All components have initialized set up the component configuration schema - store run the local server and drop privileges | 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()
i... |
Event hook to trigger a new frontend build | 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,
developmen... |
Experimental call to reload the component tree | 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()) |
Provides information about the running instance | 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,
'Front... |
Run the node local server | def _start_server(self, *args):
"""Run the node local server"""
self.log("Starting server", args)
secure = self.certificate is not None
if secure:
self.log("Running SSL server with cert:", self.certificate)
else:
self.log("Running insecure server without ... |
Check all known entry points for components. If necessary manage configuration updates | 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.
... |
Check if it is enabled and start the frontend http & websocket | 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 ser... |
Inspect all loadable components and run them | 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.runningcompon... |
Sets up the application after startup. | def started(self, component):
"""Sets up the application after startup."""
self.log("Running.")
self.log("Started event origin: ", component, lvl=verbose)
populate_user_events()
from hfos.events.system import AuthorizedEvents
self.log(len(AuthorizedEvents), "authorized ... |
[ GROUP ] User management operations | def user(ctx, username, password):
"""[GROUP] User management operations"""
ctx.obj['username'] = username
ctx.obj['password'] = password |
Internal method to create a normal user | 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': usern... |
Creates a new local user | def create_user(ctx):
"""Creates a new local user"""
try:
new_user = _create_user(ctx)
new_user.save()
log("Done")
except KeyError:
log('User already exists', lvl=warn) |
Creates a new local user and assigns admin role | 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) |
Delete a local user | def delete_user(ctx, yes):
"""Delete a local user"""
if ctx.obj['username'] is None:
username = _ask("Please enter username:")
else:
username = ctx.obj['username']
del_user = ctx.obj['db'].objectmodels['user'].find_one({'name': username})
if yes or _ask('Confirm deletion', default=... |
Change password of an existing user | 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({... |
List all locally known users | 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 act... |
Disable an existing user | 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
c... |
Enable an existing user | 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
chan... |
Grant a role to an existing user | 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({
... |
>>> class mock_framework:... def assertIn ( self item list msg = Failed asserting item is in list ):... if item not in list: raise Exception ( msg )... def assertTrue ( self value msg = Failed asserting true ):... if not value: raise Exception ( msg )... def assertFalse ( self value msg ): self. assertTrue ( not value ... | def check_expression(testing_framework, expression_dict):
"""
>>> class mock_framework:
... def assertIn(self, item, list, msg="Failed asserting item is in list"):
... if item not in list: raise Exception(msg)
... def assertTrue(self, value, msg="Failed asserting true"):
... if not v... |
Assemble a list of future alerts | 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') |
Periodical check to issue due alerts | def check_alerts(self):
"""Periodical check to issue due alerts"""
alerted = []
for alert_time, task in self.alerts.items():
task_time = dateutil.parser.parse(alert_time)
if task_time < get_time():
self.log('Alerting about task now:', task)
... |
Handles incoming raw sensor data and broadcasts it to specified udp servers and connected tcp clients: param data: NMEA raw sentences incoming data | def read(self, data):
"""Handles incoming raw sensor data and broadcasts it to specified
udp servers and connected tcp clients
:param data: NMEA raw sentences incoming data
"""
self.log('Received NMEA data:', data, lvl=debug)
# self.log(data, pretty=True)
if sel... |
Generates a command map | def cmdmap(xdot):
"""Generates a command map"""
# TODO: Integrate the output into documentation
from copy import copy
def print_commands(command, map_output, groups=None, depth=0):
if groups is None:
groups = []
if 'commands' in command.__dict__:
if len(groups) ... |
Render a given pystache template with given content | 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... |
Render a given pystache template file with given content | 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) |
Write a new file from a given pystache template file and content | def write_template_file(source, target, content):
"""Write a new file from a given pystache template file and content"""
# print(formatTemplateFile(source, content))
print(target)
data = format_template_file(source, content)
with open(target, 'w') as f:
for line in data:
if type... |
Insert a new nginx service definition | def insert_nginx_service(definition): # pragma: no cover
"""Insert a new nginx service definition"""
config_file = '/etc/nginx/sites-available/hfos.conf'
splitter = "### SERVICE DEFINITIONS ###"
with open(config_file, 'r') as f:
old_config = "".join(f.readlines())
pprint(old_config)
... |
[ GROUP ] Role based access control | def rbac(ctx, schema, object_filter, action, role, all_schemata):
"""[GROUP] Role based access control"""
database = ctx.obj['db']
if schema is None:
if all_schemata is False:
log('No schema given. Read the RBAC group help', lvl=warn)
sys.exit()
else:
sc... |
Adds a role to an action on objects | 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)
r... |
Deletes a role from an action on objects | 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)
... |
Changes the ownership of objects | 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)
... |
Notify a user | def notify(self, event):
"""Notify a user"""
self.log('Got a notification event!')
self.log(event, pretty=True)
self.log(event.__dict__) |
Handler to deal with a possibly disconnected remote controlling client: param event: ClientDisconnect Event | def clientdisconnect(self, event):
"""Handler to deal with a possibly disconnected remote controlling
client
:param event: ClientDisconnect Event
"""
try:
if event.clientuuid == self.remote_controller:
self.log("Remote controller disconnected!", lvl=c... |
Processes configuration list requests | def getlist(self, event):
"""Processes configuration list requests
:param event:
"""
try:
componentlist = model_factory(Schema).find({})
data = []
for comp in componentlist:
try:
data.append({
... |
Store a given configuration | def put(self, event):
"""Store a given configuration"""
self.log("Configuration put request ",
event.user)
try:
component = model_factory(Schema).find_one({
'uuid': event.data['uuid']
})
component.update(event.data)
... |
Get a stored configuration | def get(self, event):
"""Get a stored configuration"""
try:
comp = event.data['uuid']
except KeyError:
comp = None
if not comp:
self.log('Invalid get request without schema or component',
lvl=error)
return
se... |
Records a single snapshot | def rec(self):
"""Records a single snapshot"""
try:
self._snapshot()
except Exception as e:
self.log("Timer error: ", e, type(e), lvl=error) |
Toggles the camera system recording state | 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
s... |
A client has disconnected update possible subscriptions accordingly. | 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) |
Get a specified object | def get(self, event):
"""Get a specified object"""
try:
data, schema, user, client = self._get_args(event)
except AttributeError:
return
object_filter = self._get_filter(event)
if 'subscribe' in data:
do_subscribe = data['subscribe'] is True... |
Search for an object | def search(self, event):
"""Search for an object"""
try:
data, schema, user, client = self._get_args(event)
except AttributeError:
return
# object_filter['$text'] = {'$search': str(data['search'])}
if data.get('fulltext', False) is True:
obje... |
Get a list of objects | def objectlist(self, event):
"""Get a list of objects"""
self.log('LEGACY LIST FUNCTION CALLED!', lvl=warn)
try:
data, schema, user, client = self._get_args(event)
except AttributeError:
return
object_filter = self._get_filter(event)
self.log('Ob... |
Change an existing object | def change(self, event):
"""Change an existing object"""
try:
data, schema, user, client = self._get_args(event)
except AttributeError:
return
try:
uuid = data['uuid']
change = data['change']
field = change['field']
... |
Put an object | def put(self, event):
"""Put an object"""
try:
data, schema, user, client = self._get_args(event)
except AttributeError:
return
try:
clientobject = data['obj']
uuid = clientobject['uuid']
except KeyError as e:
self.log... |
Delete an existing object | def delete(self, event):
"""Delete an existing object"""
try:
data, schema, user, client = self._get_args(event)
except AttributeError:
return
try:
uuids = data['uuid']
if not isinstance(uuids, list):
uuids = [uuids]
... |
Subscribe to an object s future changes | def subscribe(self, event):
"""Subscribe to an object's future changes"""
uuids = event.data
if not isinstance(uuids, list):
uuids = [uuids]
subscribed = []
for uuid in uuids:
try:
self._add_subscription(uuid, event)
subsc... |
Unsubscribe from an object s future changes | def unsubscribe(self, event):
"""Unsubscribe from an object's future changes"""
# TODO: Automatic Unsubscription
uuids = event.data
if not isinstance(uuids, list):
uuids = [uuids]
result = []
for uuid in uuids:
if uuid in self.subscriptions:
... |
OM event handler for to be stored and client shared objectmodels: param event: OMRequest with uuid schema and object data | def update_subscriptions(self, event):
"""OM event handler for to be stored and client shared objectmodels
:param event: OMRequest with uuid, schema and object data
"""
# self.log("Event: '%s'" % event.__dict__)
try:
self._update_subscribers(event.schema, event.data)... |
Project Importer for Github Repository Issues | def GithubImporter(ctx, repository, all, owner, project, ignore_labels, no_tags, username, password):
"""Project Importer for Github Repository Issues
Argument REPOSITORY must be given as 'username/repository'
Owner and project have to be UUIDs
"""
db = ctx.obj['db']
if project is not None:
... |
Compile a list of all available language translations | def all_languages():
"""Compile a list of all available language translations"""
rv = []
for lang in os.listdir(localedir):
base = lang.split('_')[0].split('.')[0].split('@')[0]
if 2 <= len(base) <= 3 and all(c.islower() for c in base):
if base != 'all':
rv.appe... |
Get a descriptive title for all languages | def language_token_to_name(languages):
"""Get a descriptive title for all languages"""
result = {}
with open(os.path.join(localedir, 'languages.json'), 'r') as f:
language_lookup = json.load(f)
for language in languages:
language = language.lower()
try:
result[lang... |
Debugging function to print all message language variants | def print_messages(domain, msg):
"""Debugging function to print all message language variants"""
domain = Domain(domain)
for lang in all_languages():
print(lang, ':', domain.get(lang, msg)) |
Gettext function wrapper to return a message in a specified language by domain | def i18n(msg, event=None, lang='en', domain='backend'):
"""Gettext function wrapper to return a message in a specified language by domain
To use internationalization (i18n) on your messages, import it as '_' and use as usual.
Do not forget to supply the client's language setting."""
if event is not No... |
Generates a cryptographically strong ( sha512 ) hash with this nodes salt added. | def std_hash(word, salt):
"""Generates a cryptographically strong (sha512) hash with this nodes
salt added."""
try:
password = word.encode('utf-8')
except UnicodeDecodeError:
password = word
word_hash = sha512(password)
word_hash.update(salt)
hex_hash = word_hash.hexdigest(... |
Return a random generated human - friendly phrase as low - probability unique id | def std_human_uid(kind=None):
"""Return a random generated human-friendly phrase as low-probability unique id"""
kind_list = alphabet
if kind == 'animal':
kind_list = animals
elif kind == 'place':
kind_list = places
name = "{color} {adjective} {kind} of {attribute}".format(
... |
Return a formatted table of given rows | def std_table(rows):
"""Return a formatted table of given rows"""
result = ""
if len(rows) > 1:
headers = rows[0]._fields
lens = []
for i in range(len(rows[0])):
lens.append(len(max([x[i] for x in rows] + [headers[i]],
key=lambda x: len(st... |
Generates a cryptographically sane salt of length ( default: 16 ) alphanumeric characters | def std_salt(length=16, lowercase=True):
"""Generates a cryptographically sane salt of 'length' (default: 16) alphanumeric
characters
"""
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if lowercase is True:
alphabet += "abcdefghijklmnopqrstuvwxyz"
chars = []
for i in range(lengt... |
Add a new translation language to the live gettext translator | def _get_translation(self, lang):
"""Add a new translation language to the live gettext translator"""
try:
return self._translations[lang]
except KeyError:
# The fact that `fallback=True` is not the default is a serious design flaw.
rv = self._translations[la... |
Creates an Event Handler | def handler(*names, **kwargs):
"""Creates an Event Handler
This decorator can be applied to methods of classes derived from
:class:`circuits.core.components.BaseComponent`. It marks the method as a
handler for the events passed as arguments to the ``@handler`` decorator.
The events are specified by... |
Log a statement from this component | def log(self, *args, **kwargs):
"""Log a statement from this component"""
func = inspect.currentframe().f_back.f_code
# Dump the message + the name of this function to the log.
if 'exc' in kwargs and kwargs['exc'] is True:
exc_type, exc_obj, exc_tb = exc_info()
... |
Register a configurable component in the configuration schema store | def register(self, *args):
"""Register a configurable component in the configuration schema
store"""
super(ConfigurableMeta, self).register(*args)
from hfos.database import configschemastore
# self.log('ADDING SCHEMA:')
# pprint(self.configschema)
configschemasto... |
Removes the unique name from the systems unique name list | def unregister(self):
"""Removes the unique name from the systems unique name list"""
self.names.remove(self.uniquename)
super(ConfigurableMeta, self).unregister() |
Read this component s configuration from the database | def _read_config(self):
"""Read this component's configuration from the database"""
try:
self.config = self.componentmodel.find_one(
{'name': self.uniquename})
except ServerSelectionTimeoutError: # pragma: no cover
self.log("No database access! Check if ... |
Write this component s configuration back to the database | def _write_config(self):
"""Write this component's configuration back to the database"""
if not self.config:
self.log("Unable to write non existing configuration", lvl=error)
return
self.config.save()
self.log("Configuration stored.") |
Set this component s initial configuration | def _set_config(self, config=None):
"""Set this component's initial configuration"""
if not config:
config = {}
try:
# pprint(self.configschema)
self.config = self.componentmodel(config)
# self.log("Config schema:", lvl=critical)
# ppr... |
Event triggered configuration reload | def reload_configuration(self, event):
"""Event triggered configuration reload"""
if event.target == self.uniquename:
self.log('Reloading configuration')
self._read_config() |
Fill out the template information | def _augment_info(info):
"""Fill out the template information"""
info['description_header'] = "=" * len(info['description'])
info['component_name'] = info['plugin_name'].capitalize()
info['year'] = time.localtime().tm_year
info['license_longtext'] = ''
info['keyword_list'] = u""
for keywor... |
Build a module from templates and user supplied information | def _construct_module(info, target):
"""Build a module from templates and user supplied information"""
for path in paths:
real_path = os.path.abspath(os.path.join(target, path.format(**info)))
log("Making directory '%s'" % real_path)
os.makedirs(real_path)
# pprint(info)
for it... |
Asks questions to fill out a HFOS plugin template | def _ask_questionnaire():
"""Asks questions to fill out a HFOS plugin template"""
answers = {}
print(info_header)
pprint(questions.items())
for question, default in questions.items():
response = _ask(question, default, str(type(default)), show_hint=True)
if type(default) == unicode... |
Creates a new template HFOS plugin module | def create_module(clear_target, target):
"""Creates a new template HFOS plugin module"""
if os.path.exists(target):
if clear_target:
shutil.rmtree(target)
else:
log("Target exists! Use --clear to delete it first.",
emitter='MANAGE')
sys.exit(2... |
Generates a lookup field for form definitions | def lookup_field(key, lookup_type=None, placeholder=None, html_class="div",
select_type="strapselect", mapping="uuid"):
"""Generates a lookup field for form definitions"""
if lookup_type is None:
lookup_type = key
if placeholder is None:
placeholder = "Select a " + lookup_... |
A field set with a title and sub items | def fieldset(title, items, options=None):
"""A field set with a title and sub items"""
result = {
'title': title,
'type': 'fieldset',
'items': items
}
if options is not None:
result.update(options)
return result |
A section consisting of rows and columns | def section(rows, columns, items, label=None):
"""A section consisting of rows and columns"""
# TODO: Integrate label
sections = []
column_class = "section-column col-sm-%i" % (12 / columns)
for vertical in range(columns):
column_items = []
for horizontal in range(rows):
... |
An array that starts empty | def emptyArray(key, add_label=None):
"""An array that starts empty"""
result = {
'key': key,
'startEmpty': True
}
if add_label is not None:
result['add'] = add_label
result['style'] = {'add': 'btn-success'}
return result |
A tabbed container widget | def tabset(titles, contents):
"""A tabbed container widget"""
tabs = []
for no, title in enumerate(titles):
tab = {
'title': title,
}
content = contents[no]
if isinstance(content, list):
tab['items'] = content
else:
tab['items'] = ... |
Provides a select box for country selection | def country_field(key='country'):
"""Provides a select box for country selection"""
country_list = list(countries)
title_map = []
for item in country_list:
title_map.append({'value': item.alpha_3, 'name': item.name})
widget = {
'key': key,
'type': 'uiselect',
'title... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.